From d979b211ce6a160ce4787ebf2ac073a0ee95852a Mon Sep 17 00:00:00 2001 From: huazhongming Date: Tue, 7 Nov 2023 15:41:45 +0800 Subject: [PATCH] [3.3]Use spotless to format the code (#13322) * Use spotless to format the code Signed-off-by: crazyhzm * Use spotless to format the code Signed-off-by: crazyhzm * Use spotless to format the code Signed-off-by: crazyhzm * degrade dubbo version Signed-off-by: crazyhzm * degrade dubbo version Signed-off-by: crazyhzm * revert degrade dubbo version Signed-off-by: crazyhzm * Fix ut Signed-off-by: crazyhzm --------- Signed-off-by: crazyhzm --- dubbo-cluster/pom.xml | 202 +- .../dubbo/registry/AddressListener.java | 5 +- .../org/apache/dubbo/rpc/cluster/Cluster.java | 4 +- .../cluster/ClusterScopeModelInitializer.java | 3 +- .../dubbo/rpc/cluster/Configurator.java | 8 +- .../rpc/cluster/ConfiguratorFactory.java | 1 - .../apache/dubbo/rpc/cluster/Constants.java | 1 - .../apache/dubbo/rpc/cluster/LoadBalance.java | 1 - .../org/apache/dubbo/rpc/cluster/Merger.java | 1 - .../cluster/ProviderURLMergeProcessor.java | 4 +- .../org/apache/dubbo/rpc/cluster/Router.java | 10 +- .../apache/dubbo/rpc/cluster/RouterChain.java | 71 +- .../dubbo/rpc/cluster/RuleConverter.java | 2 - .../dubbo/rpc/cluster/SingleRouterChain.java | 70 +- .../configurator/AbstractConfigurator.java | 45 +- .../absent/AbsentConfigurator.java | 1 - .../absent/AbsentConfiguratorFactory.java | 1 - .../override/OverrideConfigurator.java | 1 - .../override/OverrideConfiguratorFactory.java | 1 - .../configurator/parser/ConfigParser.java | 19 +- .../parser/model/ConditionMatch.java | 13 +- .../configurator/parser/model/ConfigItem.java | 28 +- .../parser/model/ConfiguratorConfig.java | 4 +- .../configurator/parser/model/ParamMatch.java | 5 +- .../cluster/directory/AbstractDirectory.java | 241 +- .../cluster/directory/StaticDirectory.java | 23 +- .../filter/DefaultFilterChainBuilder.java | 20 +- .../cluster/filter/FilterChainBuilder.java | 53 +- .../cluster/filter/ProtocolFilterWrapper.java | 4 +- .../filter/support/MetricsConsumerFilter.java | 7 +- .../DefaultGovernanceRuleRepositoryImpl.java | 1 - .../governance/GovernanceRuleRepository.java | 1 - .../loadbalance/AbstractLoadBalance.java | 5 +- .../ConsistentHashLoadBalance.java | 10 +- .../loadbalance/LeastActiveLoadBalance.java | 7 +- .../loadbalance/RandomLoadBalance.java | 5 +- .../loadbalance/RoundRobinLoadBalance.java | 9 +- .../ShortestResponseLoadBalance.java | 25 +- .../rpc/cluster/router/AbstractRouter.java | 10 +- .../cluster/router/RouterSnapshotFilter.java | 2 +- .../cluster/router/RouterSnapshotNode.java | 76 +- .../router/RouterSnapshotSwitcher.java | 2 +- .../virtualservice/match/AddressMatch.java | 9 +- .../rule/virtualservice/match/BoolMatch.java | 6 +- .../virtualservice/match/DoubleMatch.java | 3 - .../match/DoubleRangeMatch.java | 3 - .../virtualservice/match/DubboMethodArg.java | 15 +- .../match/DubboMethodMatch.java | 22 +- .../virtualservice/match/ListBoolMatch.java | 3 - .../virtualservice/match/ListDoubleMatch.java | 2 - .../virtualservice/match/ListStringMatch.java | 3 - .../virtualservice/match/StringMatch.java | 16 +- .../router/state/AbstractStateRouter.java | 37 +- .../rpc/cluster/router/state/BitList.java | 12 +- .../state/CacheableStateRouterFactory.java | 3 +- .../router/state/RouterGroupingState.java | 43 +- .../rpc/cluster/router/state/StateRouter.java | 11 +- .../cluster/router/state/TailStateRouter.java | 20 +- .../support/AbstractClusterInvoker.java | 128 +- .../support/AvailableClusterInvoker.java | 4 +- .../rpc/cluster/support/BroadcastCluster.java | 1 - .../support/BroadcastClusterInvoker.java | 57 +- .../rpc/cluster/support/ClusterUtils.java | 19 +- .../rpc/cluster/support/FailbackCluster.java | 3 +- .../support/FailbackClusterInvoker.java | 76 +- .../rpc/cluster/support/FailfastCluster.java | 3 +- .../support/FailfastClusterInvoker.java | 20 +- .../rpc/cluster/support/FailoverCluster.java | 3 +- .../support/FailoverClusterInvoker.java | 55 +- .../rpc/cluster/support/FailsafeCluster.java | 3 +- .../support/FailsafeClusterInvoker.java | 13 +- .../rpc/cluster/support/ForkingCluster.java | 3 +- .../support/ForkingClusterInvoker.java | 64 +- .../DefaultProviderURLMergeProcessor.java | 14 +- .../support/registry/ZoneAwareCluster.java | 3 +- .../registry/ZoneAwareClusterInvoker.java | 34 +- .../support/wrapper/AbstractCluster.java | 54 +- .../support/wrapper/ScopeClusterInvoker.java | 71 +- .../support/wrapper/ScopeClusterWrapper.java | 4 +- .../dubbo/rpc/cluster/ConfiguratorTest.java | 15 +- .../dubbo/rpc/cluster/RouterChainTest.java | 253 - .../apache/dubbo/rpc/cluster/StickyTest.java | 24 +- .../absent/AbsentConfiguratorTest.java | 23 +- .../configurator/consts/UrlConstant.java | 19 +- .../override/OverrideConfiguratorTest.java | 32 +- .../configurator/parser/ConfigParserTest.java | 29 +- .../filter/DefaultFilterChainBuilderTest.java | 82 +- .../dubbo/rpc/cluster/filter/DemoService.java | 1 - .../rpc/cluster/filter/DemoServiceImpl.java | 3 +- .../rpc/cluster/filter/DemoServiceLocal.java | 12 +- .../rpc/cluster/filter/DemoServiceStub.java | 4 +- .../dubbo/rpc/cluster/filter/LogFilter.java | 9 +- .../loadbalance/AbstractLoadBalanceTest.java | 12 +- .../ConsistentHashLoadBalanceTest.java | 35 +- .../loadbalance/LeastActiveBalanceTest.java | 12 +- .../loadbalance/LoadBalanceBaseTest.java | 32 +- .../loadbalance/RandomLoadBalanceTest.java | 11 +- .../RoundRobinLoadBalanceTest.java | 39 +- .../ShortestResponseLoadBalanceTest.java | 30 +- .../dubbo/rpc/cluster/router/MockInvoker.java | 6 +- .../router/RouterSnapshotFilterTest.java | 3 +- .../virtualservice/match/BoolMatchTest.java | 6 +- .../virtualservice/match/DoubleMatchTest.java | 6 - .../match/DubboMethodMatchTest.java | 53 +- .../match/ListBoolMatchTest.java | 6 +- .../match/ListDoubleMatchTest.java | 7 +- .../match/ListStringMatchTest.java | 8 +- .../virtualservice/match/StringMatchTest.java | 5 - .../rpc/cluster/router/state/BitListTest.java | 15 +- .../support/AbstractClusterInvokerTest.java | 101 +- .../support/AvailableClusterInvokerTest.java | 7 +- .../support/BroadCastClusterInvokerTest.java | 13 +- .../rpc/cluster/support/ClusterUtilsTest.java | 103 +- .../support/ConnectivityValidationTest.java | 52 +- .../support/FailSafeClusterInvokerTest.java | 14 +- .../support/FailbackClusterInvokerTest.java | 83 +- .../support/FailfastClusterInvokerTest.java | 8 +- .../support/FailoverClusterInvokerTest.java | 26 +- .../support/ForkingClusterInvokerTest.java | 14 +- .../support/TagProviderURLMergeProcessor.java | 1 - .../DefaultProviderURLMergeProcessorTest.java | 73 +- .../registry/ZoneAwareClusterInvokerTest.java | 118 +- .../support/wrapper/AbstractClusterTest.java | 29 +- .../support/wrapper/DemoClusterFilter.java | 5 +- .../wrapper/ScopeClusterInvokerTest.java | 117 +- dubbo-common/pom.xml | 191 +- .../dubbo/common/BatchExecutorQueue.java | 10 +- .../org/apache/dubbo/common/Experimental.java | 13 +- .../org/apache/dubbo/common/Extension.java | 2 - .../java/org/apache/dubbo/common/Node.java | 1 - .../org/apache/dubbo/common/Parameters.java | 4 +- .../dubbo/common/ProtocolServiceKey.java | 2 +- .../org/apache/dubbo/common/Resetable.java | 1 - .../org/apache/dubbo/common/ServiceKey.java | 9 +- .../java/org/apache/dubbo/common/URL.java | 100 +- .../org/apache/dubbo/common/URLBuilder.java | 42 +- .../org/apache/dubbo/common/URLStrParser.java | 29 +- .../java/org/apache/dubbo/common/Version.java | 58 +- .../dubbo/common/aot/NativeDetector.java | 2 - .../beans/ScopeBeanExtensionInjector.java | 2 +- .../beans/factory/ScopeBeanFactory.java | 36 +- .../beans/support/InstantiationStrategy.java | 7 +- .../common/beanutil/JavaBeanAccessor.java | 1 - .../common/beanutil/JavaBeanDescriptor.java | 2 +- .../beanutil/JavaBeanSerializeUtil.java | 58 +- .../dubbo/common/bytecode/ClassGenerator.java | 65 +- .../common/bytecode/DubboLoaderClassPath.java | 9 +- .../apache/dubbo/common/bytecode/Mixin.java | 33 +- .../bytecode/NoSuchMethodException.java | 1 - .../bytecode/NoSuchPropertyException.java | 1 - .../apache/dubbo/common/bytecode/Proxy.java | 25 +- .../apache/dubbo/common/bytecode/Wrapper.java | 152 +- .../dubbo/common/cache/FileCacheStore.java | 41 +- .../common/cache/FileCacheStoreFactory.java | 59 +- .../common/compact/Dubbo2CompactUtils.java | 1 + .../compact/Dubbo2GenericExceptionUtils.java | 36 +- .../dubbo/common/compiler/Compiler.java | 1 - .../compiler/support/AbstractCompiler.java | 7 +- .../compiler/support/AdaptiveCompiler.java | 1 - .../common/compiler/support/ClassUtils.java | 31 +- .../compiler/support/CtClassBuilder.java | 14 +- .../compiler/support/JavassistCompiler.java | 8 +- .../common/compiler/support/JdkCompiler.java | 45 +- .../dubbo/common/concurrent/AbortPolicy.java | 2 - .../concurrent/CallableSafeInitializer.java | 5 +- .../common/concurrent/DiscardPolicy.java | 5 +- .../common/concurrent/RejectException.java | 3 +- .../common/config/CompositeConfiguration.java | 20 +- .../dubbo/common/config/Configuration.java | 13 +- .../common/config/ConfigurationUtils.java | 79 +- .../dubbo/common/config/Environment.java | 19 +- .../common/config/InmemoryConfiguration.java | 4 +- .../common/config/ModuleEnvironment.java | 6 +- .../OrderedPropertiesConfiguration.java | 9 +- .../config/OrderedPropertiesProvider.java | 5 +- .../common/config/PrefixedConfiguration.java | 1 - .../common/config/SystemConfiguration.java | 1 - .../AbstractDynamicConfiguration.java | 49 +- .../configcenter/ConfigChangedEvent.java | 20 +- .../config/configcenter/ConfigItem.java | 5 +- .../configcenter/DynamicConfiguration.java | 5 +- .../DynamicConfigurationFactory.java | 1 - .../TreePathDynamicConfiguration.java | 13 +- .../CompositeDynamicConfiguration.java | 12 +- .../dubbo/common/constants/ClusterRules.java | 3 - .../common/constants/CommonConstants.java | 10 +- .../common/constants/FilterConstants.java | 1 - .../common/constants/LoadbalanceRules.java | 1 - .../common/constants/LoggerCodeConstants.java | 1 - .../dubbo/common/constants/QosConstants.java | 1 - .../common/constants/RegistryConstants.java | 2 - .../common/constants/RemotingConstants.java | 1 - .../dubbo/common/context/ApplicationExt.java | 4 +- .../common/context/LifecycleAdapter.java | 12 +- .../dubbo/common/context/ModuleExt.java | 4 +- .../dubbo/common/convert/ConverterUtil.java | 17 +- .../dubbo/common/convert/StringConverter.java | 3 +- .../convert/StringToCharArrayConverter.java | 2 - .../convert/StringToDoubleConverter.java | 1 - .../convert/StringToDurationConverter.java | 7 +- .../common/convert/StringToLongConverter.java | 1 - .../convert/StringToOptionalConverter.java | 1 - .../convert/StringToShortConverter.java | 1 - .../multiple/StringToArrayConverter.java | 1 - .../multiple/StringToIterableConverter.java | 34 +- .../multiple/StringToMultiValueConverter.java | 2 +- .../dubbo/common/deploy/AbstractDeployer.java | 35 +- .../deploy/ApplicationDeployListener.java | 4 +- .../dubbo/common/deploy/DeployListener.java | 1 - .../common/deploy/DeployListenerAdapter.java | 21 +- .../common/deploy/ModuleDeployListener.java | 4 +- .../dubbo/common/extension/Activate.java | 2 +- .../dubbo/common/extension/Adaptive.java | 1 - .../extension/AdaptiveClassCodeGenerator.java | 60 +- .../dubbo/common/extension/DisableInject.java | 3 +- .../common/extension/ExtensionAccessor.java | 1 - .../extension/ExtensionAccessorAware.java | 1 - .../common/extension/ExtensionDirector.java | 7 +- .../common/extension/ExtensionInjector.java | 3 +- .../common/extension/ExtensionLoader.java | 375 +- .../extension/ExtensionPostProcessor.java | 1 - .../common/extension/LoadingStrategy.java | 2 +- .../apache/dubbo/common/extension/SPI.java | 1 - .../inject/AdaptiveExtensionInjector.java | 21 +- .../inject/SpiExtensionInjector.java | 2 +- .../extension/support/ActivateComparator.java | 8 +- .../extension/support/WrapperComparator.java | 8 +- .../dubbo/common/function/Predicates.java | 1 - .../apache/dubbo/common/function/Streams.java | 2 - .../dubbo/common/infra/InfraAdapter.java | 2 - .../org/apache/dubbo/common/io/Bytes.java | 70 +- .../apache/dubbo/common/io/StreamUtils.java | 3 +- .../common/io/UnsafeByteArrayInputStream.java | 3 +- .../io/UnsafeByteArrayOutputStream.java | 3 +- .../dubbo/common/io/UnsafeStringReader.java | 3 +- .../dubbo/common/io/UnsafeStringWriter.java | 9 +- .../apache/dubbo/common/json/GsonUtils.java | 12 +- .../json/impl/AbstractJsonUtilImpl.java | 28 +- .../dubbo/common/json/impl/FastJson2Impl.java | 5 +- .../dubbo/common/json/impl/FastJsonImpl.java | 5 +- .../dubbo/common/json/impl/GsonImpl.java | 9 +- .../dubbo/common/json/impl/JacksonImpl.java | 18 +- .../apache/dubbo/common/lang/Nullable.java | 5 +- .../apache/dubbo/common/lang/Prioritized.java | 6 +- .../common/lang/ShutdownHookCallbacks.java | 3 +- .../common/logger/ErrorTypeAwareLogger.java | 1 - .../org/apache/dubbo/common/logger/Level.java | 1 - .../dubbo/common/logger/ListenableLogger.java | 4 +- .../dubbo/common/logger/LogListener.java | 2 - .../apache/dubbo/common/logger/Logger.java | 1 - .../dubbo/common/logger/LoggerFactory.java | 55 +- .../dubbo/common/logger/jcl/JclLogger.java | 1 - .../common/logger/jcl/JclLoggerAdapter.java | 5 +- .../dubbo/common/logger/jdk/JdkLogger.java | 6 +- .../common/logger/jdk/JdkLoggerAdapter.java | 9 +- .../logger/log4j/Log4jLoggerAdapter.java | 6 +- .../logger/log4j2/Log4j2LoggerAdapter.java | 4 +- .../common/logger/slf4j/Slf4jLogger.java | 10 +- .../logger/slf4j/Slf4jLoggerAdapter.java | 8 +- .../support/FailsafeErrorTypeAwareLogger.java | 34 +- .../common/logger/support/FailsafeLogger.java | 4 +- .../dubbo/common/profiler/Profiler.java | 25 +- .../dubbo/common/profiler/ProfilerSwitch.java | 6 +- .../reference/ReferenceCountedResource.java | 9 +- .../dubbo/common/resource/Disposable.java | 1 - .../resource/GlobalResourceInitializer.java | 1 - .../resource/GlobalResourcesRepository.java | 19 +- .../apache/dubbo/common/ssl/CertManager.java | 3 +- .../apache/dubbo/common/ssl/ProviderCert.java | 3 +- .../ssl/impl/SSLConfigCertProvider.java | 89 +- .../apache/dubbo/common/status/Status.java | 1 - .../dubbo/common/status/StatusChecker.java | 1 - .../FrameworkStatusReportService.java | 7 +- .../reporter/FrameworkStatusReporter.java | 2 - .../status/support/LoadStatusChecker.java | 1 - .../status/support/MemoryStatusChecker.java | 8 +- .../common/status/support/StatusUtils.java | 1 - .../apache/dubbo/common/store/DataStore.java | 2 - .../common/store/support/SimpleDataStore.java | 8 +- .../dubbo/common/stream/StreamObserver.java | 2 - .../system/OperatingSystemBeanManager.java | 18 +- .../common/threadlocal/InternalRunnable.java | 16 +- .../common/threadlocal/InternalThread.java | 4 +- .../NamedInternalThreadFactory.java | 1 - .../threadpool/MemoryLimitCalculator.java | 7 +- .../MemoryLimitedLinkedBlockingQueue.java | 1 - .../common/threadpool/MemoryLimiter.java | 1 - .../MemorySafeLinkedBlockingQueue.java | 8 +- .../dubbo/common/threadpool/ThreadPool.java | 3 +- .../common/threadpool/ThreadlessExecutor.java | 1 - .../ScheduledCompletableFuture.java | 32 +- .../manager/DefaultExecutorRepository.java | 70 +- .../manager/ExecutorRepository.java | 13 +- .../manager/FrameworkExecutorRepository.java | 82 +- .../support/AbortPolicyWithReport.java | 59 +- .../support/cached/CachedThreadPool.java | 13 +- .../support/eager/EagerThreadPool.java | 7 +- .../eager/EagerThreadPoolExecutor.java | 15 +- .../threadpool/support/eager/TaskQueue.java | 1 - .../support/fixed/FixedThreadPool.java | 14 +- .../support/limited/LimitedThreadPool.java | 15 +- .../url/component/DubboServiceAddressURL.java | 9 +- .../common/url/component/PathURLAddress.java | 34 +- .../url/component/ServiceAddressURL.java | 10 +- .../url/component/ServiceConfigURL.java | 68 +- .../common/url/component/URLAddress.java | 12 +- .../dubbo/common/url/component/URLParam.java | 103 +- .../common/url/component/URLPlainParam.java | 11 +- .../component/param/DynamicParamTable.java | 7 +- .../url/component/param/FixedParamValue.java | 4 +- .../url/component/param/IgnoredParam.java | 1 - .../url/component/param/ParamValue.java | 1 - .../dubbo/common/utils/AnnotationUtils.java | 62 +- .../apache/dubbo/common/utils/ArrayUtils.java | 4 +- .../org/apache/dubbo/common/utils/Assert.java | 5 +- .../common/utils/AtomicPositiveInteger.java | 3 +- .../dubbo/common/utils/CacheableSupplier.java | 1 - .../common/utils/CharSequenceComparator.java | 5 +- .../dubbo/common/utils/ClassHelper.java | 10 +- .../utils/ClassLoaderResourceLoader.java | 18 +- .../apache/dubbo/common/utils/ClassUtils.java | 114 +- .../dubbo/common/utils/CollectionUtils.java | 10 +- .../common/utils/CompatibleTypeUtils.java | 26 +- .../common/utils/ConcurrentHashMapUtils.java | 7 +- .../dubbo/common/utils/ConcurrentHashSet.java | 1 - .../dubbo/common/utils/ConfigUtils.java | 79 +- .../utils/DefaultSerializeClassChecker.java | 48 +- .../dubbo/common/utils/DubboAppender.java | 7 +- .../dubbo/common/utils/ExecutorUtil.java | 11 +- .../apache/dubbo/common/utils/FieldUtils.java | 1 - .../org/apache/dubbo/common/utils/Holder.java | 1 - .../apache/dubbo/common/utils/IOUtils.java | 14 +- .../org/apache/dubbo/common/utils/JRE.java | 9 +- .../apache/dubbo/common/utils/JVMUtil.java | 17 +- .../common/utils/JsonCompatibilityUtil.java | 23 +- .../apache/dubbo/common/utils/JsonUtils.java | 23 +- .../apache/dubbo/common/utils/LFUCache.java | 15 +- .../apache/dubbo/common/utils/LRU2Cache.java | 1 - .../apache/dubbo/common/utils/LRUCache.java | 1 - .../org/apache/dubbo/common/utils/Log.java | 5 +- .../apache/dubbo/common/utils/LogHelper.java | 4 +- .../apache/dubbo/common/utils/LogUtil.java | 6 +- .../apache/dubbo/common/utils/MD5Utils.java | 2 - .../dubbo/common/utils/MemberUtils.java | 1 - .../dubbo/common/utils/MethodComparator.java | 5 +- .../dubbo/common/utils/MethodUtils.java | 26 +- .../apache/dubbo/common/utils/NetUtils.java | 86 +- .../apache/dubbo/common/utils/PathUtils.java | 5 +- .../apache/dubbo/common/utils/PojoUtils.java | 151 +- .../dubbo/common/utils/ReflectUtils.java | 72 +- .../dubbo/common/utils/ReflectionUtils.java | 8 +- .../dubbo/common/utils/RegexProperties.java | 8 +- .../utils/SerializeSecurityConfigurator.java | 62 +- .../utils/SerializeSecurityManager.java | 3 +- .../utils/ServiceAnnotationResolver.java | 7 +- .../org/apache/dubbo/common/utils/Stack.java | 4 +- .../StringConstantFieldValuePredicate.java | 10 +- .../dubbo/common/utils/StringUtils.java | 30 +- .../apache/dubbo/common/utils/TimeUtils.java | 4 +- .../dubbo/common/utils/ToStringUtils.java | 3 +- .../apache/dubbo/common/utils/TypeUtils.java | 21 +- .../apache/dubbo/common/utils/UrlUtils.java | 70 +- .../apache/dubbo/config/AbstractConfig.java | 135 +- .../dubbo/config/AbstractInterfaceConfig.java | 80 +- .../dubbo/config/AbstractMethodConfig.java | 7 +- .../dubbo/config/AbstractReferenceConfig.java | 9 +- .../dubbo/config/AbstractServiceConfig.java | 3 +- .../dubbo/config/ApplicationConfig.java | 18 +- .../apache/dubbo/config/ArgumentConfig.java | 4 +- .../config/CommonConfigPostProcessor.java | 9 +- .../dubbo/config/ConfigCenterConfig.java | 4 +- .../org/apache/dubbo/config/ConfigKeys.java | 1 - .../org/apache/dubbo/config/Constants.java | 22 +- .../apache/dubbo/config/ConsumerConfig.java | 7 +- .../dubbo/config/MetadataReportConfig.java | 15 +- .../org/apache/dubbo/config/MethodConfig.java | 40 +- .../apache/dubbo/config/MetricsConfig.java | 3 +- .../org/apache/dubbo/config/ModuleConfig.java | 3 +- .../apache/dubbo/config/MonitorConfig.java | 4 +- .../apache/dubbo/config/ProtocolConfig.java | 25 +- .../apache/dubbo/config/ProviderConfig.java | 4 +- .../dubbo/config/ReferenceConfigBase.java | 36 +- .../apache/dubbo/config/RegistryConfig.java | 3 +- .../dubbo/config/ServiceConfigBase.java | 24 +- .../org/apache/dubbo/config/SslConfig.java | 15 +- .../apache/dubbo/config/TracingConfig.java | 4 +- .../org/apache/dubbo/config/TripleConfig.java | 1 - .../dubbo/config/annotation/Argument.java | 6 +- .../dubbo/config/annotation/Method.java | 1 - .../config/context/AbstractConfigManager.java | 116 +- .../dubbo/config/context/ConfigManager.java | 31 +- .../dubbo/config/context/ConfigValidator.java | 1 - .../config/context/ModuleConfigManager.java | 26 +- .../dubbo/config/nested/BaggageConfig.java | 7 +- .../dubbo/config/nested/ExporterConfig.java | 7 +- .../dubbo/config/nested/HistogramConfig.java | 1 - .../config/nested/PropagationConfig.java | 4 +- .../dubbo/config/nested/SamplingConfig.java | 3 +- .../apache/dubbo/config/support/Nested.java | 3 +- .../dubbo/config/support/Parameter.java | 1 - .../definition/MethodDefinitionBuilder.java | 1 - .../definition/ServiceDefinitionBuilder.java | 5 +- .../definition/TypeDefinitionBuilder.java | 4 +- .../definition/builder/ArrayTypeBuilder.java | 1 - .../builder/CollectionTypeBuilder.java | 4 +- .../builder/DefaultTypeBuilder.java | 3 +- .../definition/builder/EnumTypeBuilder.java | 4 +- .../definition/builder/TypeBuilder.java | 1 - .../model/FullServiceDefinition.java | 5 +- .../definition/model/MethodDefinition.java | 6 +- .../definition/model/ServiceDefinition.java | 8 +- .../definition/model/TypeDefinition.java | 13 +- .../metadata/definition/util/ClassUtils.java | 10 +- .../util/JaketConfigurationUtils.java | 1 - .../AbstractIsolationExecutorSupport.java | 3 +- .../rpc/executor/DefaultExecutorSupport.java | 1 - .../IsolationExecutorSupportFactory.java | 4 +- .../dubbo/rpc/model/ApplicationModel.java | 29 +- .../rpc/model/BuiltinServiceDetector.java | 1 - .../dubbo/rpc/model/ConsumerMethodModel.java | 15 +- .../apache/dubbo/rpc/model/ConsumerModel.java | 56 +- .../org/apache/dubbo/rpc/model/DubboStub.java | 4 +- .../dubbo/rpc/model/FrameworkModel.java | 36 +- .../rpc/model/FrameworkServiceRepository.java | 11 +- .../dubbo/rpc/model/MethodDescriptor.java | 6 +- .../apache/dubbo/rpc/model/ModuleModel.java | 21 +- .../rpc/model/ModuleServiceRepository.java | 61 +- .../java/org/apache/dubbo/rpc/model/Pack.java | 2 - .../dubbo/rpc/model/PackableMethod.java | 3 - .../rpc/model/PackableMethodFactory.java | 2 - .../apache/dubbo/rpc/model/ProviderModel.java | 38 +- .../rpc/model/ReflectionMethodDescriptor.java | 43 +- .../model/ReflectionServiceDescriptor.java | 30 +- .../apache/dubbo/rpc/model/ScopeModel.java | 3 +- .../dubbo/rpc/model/ScopeModelAccessor.java | 1 - .../dubbo/rpc/model/ScopeModelAware.java | 13 +- .../dubbo/rpc/model/ServiceDescriptor.java | 1 - .../dubbo/rpc/model/ServiceMetadata.java | 3 +- .../apache/dubbo/rpc/model/ServiceModel.java | 35 +- .../dubbo/rpc/model/ServiceRepository.java | 8 +- .../dubbo/rpc/model/StubMethodDescriptor.java | 28 +- .../rpc/model/StubServiceDescriptor.java | 20 +- .../org/apache/dubbo/rpc/model/UnPack.java | 2 - .../apache/dubbo/rpc/model/WrapperUnPack.java | 2 - .../apache/dubbo/rpc/service/Destroyable.java | 1 - .../apache/dubbo/rpc/service/EchoService.java | 1 - .../rpc/service/EchoServiceDetector.java | 1 - .../dubbo/rpc/service/GenericException.java | 4 +- .../dubbo/rpc/service/GenericService.java | 4 +- .../rpc/service/GenericServiceDetector.java | 1 - .../ServiceDescriptorInternalCache.java | 3 +- .../rpc/support/GroupServiceKeyCache.java | 2 +- .../dubbo/rpc/support/ProtocolUtils.java | 33 +- .../src/test/java/com/pojo/Demo2.java | 3 +- .../src/test/java/com/pojo/Demo3.java | 3 +- .../src/test/java/com/pojo/Demo4.java | 3 +- .../src/test/java/com/pojo/Demo5.java | 3 +- .../src/test/java/com/pojo/Demo6.java | 3 +- .../src/test/java/com/pojo/Demo7.java | 3 +- .../src/test/java/com/pojo/Demo8.java | 3 +- .../test/java/com/pojo/DemoException1.java | 3 +- .../test/java/com/pojo/DemoException2.java | 3 +- .../test/java/com/pojo/DemoException3.java | 3 +- .../src/test/java/com/pojo/Simple.java | 3 +- .../test/java/com/service/DemoService1.java | 14 +- .../test/java/com/service/DemoService2.java | 3 +- .../test/java/com/service/DemoService4.java | 4 +- .../test/java/com/service/DemoService5.java | 3 +- .../src/test/java/com/service/Params.java | 1 - .../src/test/java/com/service/Service.java | 27 +- .../src/test/java/com/service/User.java | 1 - .../test/java/com/service/UserService.java | 31 +- .../deep1/deep2/deep3/DemoService3.java | 3 +- .../dubbo/common/BaseServiceMetadataTest.java | 39 +- .../dubbo/common/InterfaceAddressURLTest.java | 41 +- .../PojoUtilsForNonPublicStaticTest.java | 2 +- .../common/ProtocolServiceKeyMatcherTest.java | 87 +- .../dubbo/common/ProtocolServiceKeyTest.java | 42 +- .../dubbo/common/ServiceKeyMatcherTest.java | 217 +- .../apache/dubbo/common/ServiceKeyTest.java | 2 +- .../apache/dubbo/common/URLBuilderTest.java | 55 +- .../apache/dubbo/common/URLStrParserTest.java | 19 +- .../java/org/apache/dubbo/common/URLTest.java | 182 +- .../beans/InstantiationStrategyTest.java | 16 +- .../common/beans/ScopeBeanFactoryTest.java | 19 +- .../apache/dubbo/common/beanutil/Bean.java | 8 +- .../common/beanutil/JavaBeanAccessorTest.java | 6 +- .../beanutil/JavaBeanSerializeUtilTest.java | 87 +- .../common/bytecode/ClassGeneratorTest.java | 98 +- .../dubbo/common/bytecode/MixinTest.java | 4 +- .../dubbo/common/bytecode/ProxyTest.java | 2 +- .../dubbo/common/bytecode/WrapperTest.java | 75 +- .../cache/FileCacheStoreFactoryTest.java | 12 +- .../common/cache/FileCacheStoreTest.java | 7 +- .../support/AdaptiveCompilerTest.java | 4 +- .../compiler/support/ClassUtilsTest.java | 50 +- .../common/compiler/support/HelloService.java | 1 - .../common/compiler/support/JavaCodeTest.java | 16 +- .../support/JavassistCompilerTest.java | 24 +- .../compiler/support/JdkCompilerTest.java | 16 +- .../internal/HelloServiceInternalImpl.java | 3 +- .../concurrent/CompletableFutureTaskTest.java | 60 +- .../config/CompositeConfigurationTest.java | 4 +- .../common/config/ConfigurationCacheTest.java | 2 +- .../common/config/ConfigurationUtilsTest.java | 14 +- .../config/EnvironmentConfigurationTest.java | 6 +- .../dubbo/common/config/EnvironmentTest.java | 7 +- .../config/InmemoryConfigurationTest.java | 16 +- .../OrderedPropertiesConfigurationTest.java | 7 +- .../config/PrefixedConfigurationTest.java | 14 +- .../config/PropertiesConfigurationTest.java | 6 +- .../config/SystemConfigurationTest.java | 4 +- ...stractDynamicConfigurationFactoryTest.java | 2 +- .../AbstractDynamicConfigurationTest.java | 27 +- .../configcenter/ConfigChangeTypeTest.java | 4 +- .../configcenter/ConfigChangedEventTest.java | 14 +- .../DynamicConfigurationFactoryTest.java | 9 +- .../common/constants/CommonConstantsTest.java | 2 +- .../dubbo/common/convert/ConverterTest.java | 8 +- .../convert/StringToBooleanConverterTest.java | 5 +- .../StringToCharArrayConverterTest.java | 7 +- .../StringToCharacterConverterTest.java | 5 +- .../convert/StringToDoubleConverterTest.java | 5 +- .../StringToDurationConverterTest.java | 9 +- .../convert/StringToFloatConverterTest.java | 2 +- .../convert/StringToIntegerConverterTest.java | 5 +- .../StringToOptionalConverterTest.java | 9 +- .../convert/StringToShortConverterTest.java | 2 +- .../convert/StringToStringConverterTest.java | 5 +- .../multiple/MultiValueConverterTest.java | 6 +- .../multiple/StringToArrayConverterTest.java | 6 +- .../StringToBlockingDequeConverterTest.java | 13 +- .../StringToBlockingQueueConverterTest.java | 12 +- .../StringToCollectionConverterTest.java | 9 +- .../multiple/StringToDequeConverterTest.java | 9 +- .../multiple/StringToListConverterTest.java | 9 +- .../StringToNavigableSetConverterTest.java | 9 +- .../multiple/StringToQueueConverterTest.java | 8 +- .../multiple/StringToSetConverterTest.java | 8 +- .../StringToSortedSetConverterTest.java | 9 +- .../StringToTransferQueueConverterTest.java | 8 +- .../AdaptiveClassCodeGeneratorTest.java | 8 +- .../extension/ExtensionDirectorTest.java | 137 +- .../common/extension/ExtensionLoaderTest.java | 191 +- .../ExtensionLoader_Activate_Test.java | 5 +- .../ExtensionLoader_Adaptive_Test.java | 45 +- ...onLoader_Adaptive_UseJdkCompiler_Test.java | 2 +- .../ExtensionLoader_Compatible_Test.java | 8 +- .../dubbo/common/extension/SPI1Impl.java | 2 +- .../dubbo/common/extension/SPI2Impl.java | 2 +- .../dubbo/common/extension/SPI3Impl.java | 2 +- .../dubbo/common/extension/SPI4Impl.java | 2 +- .../extension/activate/ActivateExt1.java | 1 - .../activate/ActivateWrapperExt1.java | 1 - .../activate/impl/ActivateExt1Impl1.java | 5 +- .../impl/ActivateOnClassExt1Impl.java | 6 +- .../impl/ActivateWrapperExt1Impl1.java | 5 +- .../impl/ActivateWrapperExt1Impl2.java | 5 +- .../impl/ActivateWrapperExt1Wrapper.java | 2 - .../activate/impl/GroupActivateExtImpl.java | 1 - .../activate/impl/OrderActivateExtImpl1.java | 5 +- .../activate/impl/OrderActivateExtImpl2.java | 5 +- .../activate/impl/ValueActivateExtImpl.java | 5 +- .../extension/adaptive/HasAdaptiveExt.java | 1 - .../impl/HasAdaptiveExt_ManualAdaptive.java | 3 +- .../compatible/impl/CompatibleExtImpl2.java | 1 - .../convert/String2BooleanConverter.java | 3 +- .../convert/String2DoubleConverter.java | 3 +- .../convert/String2IntegerConverter.java | 3 +- .../extension/director/FooAppProvider.java | 1 - .../director/FooFrameworkProvider.java | 1 - .../extension/director/FooModuleProvider.java | 1 - .../extension/director/FooModuleService.java | 1 - .../director/impl/TestAppProvider.java | 4 +- .../director/impl/TestAppService.java | 4 +- .../director/impl/TestFrameworkProvider.java | 4 +- .../director/impl/TestFrameworkService.java | 4 +- .../director/impl/TestModuleProvider.java | 5 +- .../director/impl/TestModuleService.java | 4 +- .../extension/ext1/impl/SimpleExtImpl2.java | 1 - .../extension/ext1/impl/SimpleExtImpl3.java | 1 - .../ext10_multi_names/Ext10MultiNames.java | 3 +- .../impl/Ext10MultiNamesImpl.java | 3 +- .../common/extension/ext2/impl/Ext2Impl2.java | 1 - .../common/extension/ext2/impl/Ext2Impl3.java | 1 - .../common/extension/ext4/impl/Ext4Impl2.java | 1 - .../common/extension/ext6_inject/Dao.java | 1 - .../extension/ext6_inject/impl/DaoImpl.java | 5 +- .../extension/ext6_inject/impl/Ext6Impl1.java | 2 - .../extension/ext6_inject/impl/Ext6Impl2.java | 1 - .../ext6_wrap/impl/Ext6Wrapper3.java | 4 +- .../ext6_wrap/impl/Ext6Wrapper4.java | 4 +- .../common/extension/ext7/impl/Ext7Impl.java | 1 - .../ext7/impl/Ext7InitErrorImpl.java | 1 - .../ext9_empty/impl/Ext9EmptyImpl.java | 4 +- .../inject/AdaptiveExtensionInjectorTest.java | 10 +- .../support/ActivateComparatorTest.java | 13 +- .../common/extension/support/Filter0.java | 3 +- .../common/extension/support/Filter1.java | 3 +- .../common/extension/support/Filter2.java | 3 +- .../common/extension/support/Filter3.java | 3 +- .../common/extension/support/Filter4.java | 3 +- .../extension/support/Order0Filter0.java | 4 +- .../extension/support/Order0Filter1.java | 4 +- .../extension/support/Order0Filter2.java | 4 +- .../common/extension/wrapper/WrapperTest.java | 2 +- .../extension/wrapper/impl/DemoImpl.java | 6 +- .../extension/wrapper/impl/DemoWrapper.java | 4 +- .../extension/wrapper/impl/DemoWrapper2.java | 4 +- .../dubbo/common/function/PredicatesTest.java | 2 +- .../dubbo/common/function/StreamsTest.java | 6 +- .../common/function/ThrowableActionTest.java | 11 +- .../function/ThrowableConsumerTest.java | 11 +- .../function/ThrowableFunctionTest.java | 11 +- .../org/apache/dubbo/common/io/BytesTest.java | 21 +- .../dubbo/common/io/StreamUtilsTest.java | 8 +- .../io/UnsafeByteArrayInputStreamTest.java | 6 +- .../io/UnsafeByteArrayOutputStreamTest.java | 10 +- .../common/io/UnsafeStringReaderTest.java | 6 +- .../common/io/UnsafeStringWriterTest.java | 6 +- .../dubbo/common/json/GsonUtilsTest.java | 12 +- .../common/json/impl/FastJson2ImplTest.java | 20 +- .../common/json/impl/FastJsonImplTest.java | 11 +- .../dubbo/common/json/impl/GsonImplTest.java | 39 +- .../dubbo/common/lang/PrioritizedTest.java | 10 +- .../lang/ShutdownHookCallbacksTest.java | 5 +- .../common/logger/LoggerAdapterTest.java | 22 +- .../common/logger/LoggerFactoryTest.java | 12 +- .../dubbo/common/logger/LoggerTest.java | 15 +- .../common/logger/slf4j/Slf4jLoggerTest.java | 17 +- .../FailsafeErrorTypeAwareLoggerTest.java | 30 +- .../logger/support/FailsafeLoggerTest.java | 2 +- .../org/apache/dubbo/common/model/Person.java | 21 +- .../common/model/SerializablePerson.java | 24 +- .../org/apache/dubbo/common/model/User.java | 1 - .../dubbo/common/model/media/Image.java | 9 +- .../dubbo/common/model/media/Media.java | 26 +- .../dubbo/common/model/person/BigPerson.java | 47 +- .../dubbo/common/model/person/Dgeneric.java | 2 +- .../common/model/person/FullAddress.java | 68 +- .../dubbo/common/model/person/PersonInfo.java | 64 +- .../dubbo/common/model/person/PersonMap.java | 1 - .../dubbo/common/model/person/Phone.java | 37 +- .../dubbo/common/profiler/ProfilerTest.java | 2 +- .../GlobalResourcesRepositoryTest.java | 10 +- .../dubbo/common/ssl/CertManagerTest.java | 1 + .../dubbo/common/ssl/FirstCertProvider.java | 1 + .../common/ssl/SSLConfigCertProviderTest.java | 52 +- .../dubbo/common/ssl/SecondCertProvider.java | 1 + .../dubbo/common/status/StatusTest.java | 5 +- .../FrameworkStatusReportServiceTest.java | 39 +- .../status/support/LoadStatusCheckerTest.java | 3 +- .../support/MemoryStatusCheckerTest.java | 3 +- .../status/support/StatusUtilsTest.java | 9 +- .../store/support/SimpleDataStoreTest.java | 6 +- .../threadlocal/InternalThreadLocalTest.java | 30 +- .../NamedInternalThreadFactoryTest.java | 3 +- .../MemoryLimitedLinkedBlockingQueueTest.java | 9 +- .../MemorySafeLinkedBlockingQueueTest.java | 32 +- .../threadpool/ThreadlessExecutorTest.java | 12 +- .../ThreadPoolExhaustedEventListenerTest.java | 6 +- .../event/ThreadPoolExhaustedEventTest.java | 5 +- .../manager/ExecutorRepositoryTest.java | 22 +- .../FrameworkExecutorRepositoryTest.java | 22 +- .../serial/SerializingExecutorTest.java | 9 +- .../support/AbortPolicyWithReportTest.java | 31 +- .../support/cached/CachedThreadPoolTest.java | 24 +- .../eager/EagerThreadPoolExecutorTest.java | 88 +- .../support/eager/EagerThreadPoolTest.java | 25 +- .../support/eager/TaskQueueTest.java | 13 +- .../support/fixed/FixedThreadPoolTest.java | 24 +- .../limited/LimitedThreadPoolTest.java | 22 +- .../common/timer/HashedWheelTimerTest.java | 71 +- .../apache/dubbo/common/url/URLParamTest.java | 50 +- .../common/utils/AnnotationUtilsTest.java | 73 +- .../dubbo/common/utils/ArrayUtilsTest.java | 6 +- .../apache/dubbo/common/utils/AssertTest.java | 11 +- .../utils/AtomicPositiveIntegerTest.java | 7 +- .../dubbo/common/utils/CIDRUtilsTest.java | 8 +- .../utils/ClassLoaderResourceLoaderTest.java | 11 +- .../dubbo/common/utils/ClassUtilsTest.java | 13 +- .../common/utils/CollectionUtilsTest.java | 20 +- .../common/utils/CompatibleTypeUtilsTest.java | 21 +- .../utils/ConcurrentHashMapUtilsTest.java | 20 +- .../dubbo/common/utils/ConfigUtilsTest.java | 69 +- .../dubbo/common/utils/DefaultPageTest.java | 6 +- .../DefaultSerializeClassCheckerTest.java | 105 +- .../dubbo/common/utils/DubboAppenderTest.java | 3 +- .../dubbo/common/utils/ExecutorUtilTest.java | 9 +- .../dubbo/common/utils/FieldUtilsTest.java | 4 +- .../apache/dubbo/common/utils/HolderTest.java | 5 +- .../dubbo/common/utils/IOUtilsTest.java | 22 +- .../apache/dubbo/common/utils/JRETest.java | 13 +- .../dubbo/common/utils/JVMUtilTest.java | 6 +- .../utils/JsonCompatibilityUtilTest.java | 9 +- .../dubbo/common/utils/JsonUtilsTest.java | 43 +- .../dubbo/common/utils/LFUCacheTest.java | 4 +- .../dubbo/common/utils/LRU2CacheTest.java | 3 +- .../dubbo/common/utils/LogHelperTest.java | 3 +- .../apache/dubbo/common/utils/LogTest.java | 4 +- .../dubbo/common/utils/LogUtilTest.java | 4 +- .../dubbo/common/utils/MD5UtilsTest.java | 21 +- .../dubbo/common/utils/MemberUtilsTest.java | 16 +- .../dubbo/common/utils/MethodUtilsTest.java | 25 +- .../org/apache/dubbo/common/utils/MyEnum.java | 5 +- .../common/utils/NamedThreadFactoryTest.java | 7 +- ...rfaceDisplayNameHasMetaCharactersTest.java | 35 +- .../dubbo/common/utils/NetUtilsTest.java | 33 +- .../dubbo/common/utils/PojoUtilsTest.java | 228 +- .../dubbo/common/utils/ReflectUtilsTest.java | 75 +- .../common/utils/RegexPropertiesTest.java | 16 +- .../SerializeSecurityConfiguratorTest.java | 75 +- .../apache/dubbo/common/utils/StackTest.java | 9 +- ...StringConstantFieldValuePredicateTest.java | 6 +- .../dubbo/common/utils/StringUtilsTest.java | 19 +- .../utils/TestAllowClassNotifyListener.java | 10 +- .../dubbo/common/utils/TimeUtilsTest.java | 1 - .../dubbo/common/utils/UrlUtilsTest.java | 22 +- .../apache/dubbo/common/utils/json/Color.java | 8 +- .../apache/dubbo/common/utils/json/Range.java | 7 +- .../dubbo/common/utils/json/Service.java | 1 - .../dubbo/common/utils/json/Student.java | 5 +- .../dubbo/common/utils/json/Teacher.java | 5 +- .../dubbo/common/utils/json/TestEnum.java | 4 +- .../dubbo/common/utils/json/TestObjectA.java | 3 +- .../dubbo/common/utils/json/TestObjectB.java | 1 - .../dubbo/common/version/VersionTest.java | 27 +- .../org/apache/dubbo/common/vo/UserVo.java | 9 +- .../config/AbstractInterfaceConfigTest.java | 18 +- .../org/apache/dubbo/config/Greeting.java | 2 +- .../apache/dubbo/config/GreetingLocal1.java | 6 +- .../apache/dubbo/config/GreetingLocal2.java | 2 +- .../apache/dubbo/config/GreetingLocal3.java | 2 +- .../ConfigConfigurationAdapterTest.java | 2 +- .../config/context/ConfigManagerTest.java | 40 +- .../metadata/definition/MetadataTest.java | 12 +- .../ServiceDefinitionBuilderTest.java | 96 +- .../metadata/definition/Test3TypeBuilder.java | 4 +- .../metadata/definition/TestTypeBuilder.java | 2 +- .../definition/common/ClassExtendsMap.java | 3 +- .../metadata/definition/common/ColorEnum.java | 5 +- .../common/ResultWithRawCollections.java | 3 +- .../definition/service/ComplexObject.java | 71 +- .../definition/service/DemoService.java | 3 +- .../IsolationExecutorSupportFactoryTest.java | 24 +- .../dubbo/rpc/model/ApplicationModelTest.java | 8 +- .../dubbo/rpc/model/FrameworkModelTest.java | 1 - .../model/FrameworkServiceRepositoryTest.java | 35 +- .../dubbo/rpc/model/ModuleModelTest.java | 1 - .../model/ModuleServiceRepositoryTest.java | 41 +- .../org/apache/dubbo/rpc/model/Person.java | 21 +- .../model/ReflectionMethodDescriptorTest.java | 26 +- .../ReflectionServiceDescriptorTest.java | 26 +- ...ScopeModelAwareExtensionProcessorTest.java | 3 +- .../dubbo/rpc/model/ScopeModelTest.java | 16 +- .../dubbo/rpc/model/ScopeModelUtilTest.java | 58 +- .../dubbo/rpc/model/SerializablePerson.java | 21 +- .../rpc/model/ServiceRepositoryTest.java | 42 +- .../java/org/apache/dubbo/rpc/model/User.java | 1 - .../apache/dubbo/rpc/model/media/Image.java | 9 +- .../apache/dubbo/rpc/model/media/Media.java | 26 +- .../dubbo/rpc/model/person/BigPerson.java | 47 +- .../dubbo/rpc/model/person/FullAddress.java | 68 +- .../dubbo/rpc/model/person/PersonInfo.java | 64 +- .../apache/dubbo/rpc/model/person/Phone.java | 37 +- .../rpc/service/GenericExceptionTest.java | 5 +- .../ServiceDescriptorInternalCacheTest.java | 12 +- .../dubbo/rpc/support/DemoService1Impl.java | 2 +- .../dubbo/rpc/support/ProtocolUtilsTest.java | 6 +- dubbo-compatible/pom.xml | 226 +- .../java/com/alibaba/dubbo/cache/Cache.java | 4 +- .../com/alibaba/dubbo/cache/CacheFactory.java | 4 +- .../cache/support/AbstractCacheFactory.java | 10 +- .../com/alibaba/dubbo/common/Constants.java | 48 +- .../com/alibaba/dubbo/common/DelegateURL.java | 3 +- .../java/com/alibaba/dubbo/common/URL.java | 91 +- .../dubbo/common/compiler/Compiler.java | 4 +- .../dubbo/common/extension/Activate.java | 1 - .../common/extension/ExtensionFactory.java | 3 +- .../dubbo/common/logger/LoggerAdapter.java | 4 +- .../dubbo/common/serialize/ObjectInput.java | 4 +- .../dubbo/common/serialize/ObjectOutput.java | 4 +- .../dubbo/common/serialize/Serialization.java | 13 +- .../alibaba/dubbo/common/status/Status.java | 1 - .../dubbo/common/status/StatusChecker.java | 1 - .../alibaba/dubbo/common/store/DataStore.java | 4 +- .../dubbo/common/threadpool/ThreadPool.java | 1 - .../alibaba/dubbo/common/utils/UrlUtils.java | 22 +- .../dubbo/config/ApplicationConfig.java | 1 - .../alibaba/dubbo/config/ArgumentConfig.java | 4 +- .../alibaba/dubbo/config/ConsumerConfig.java | 1 - .../alibaba/dubbo/config/MethodConfig.java | 1 - .../alibaba/dubbo/config/ModuleConfig.java | 4 +- .../alibaba/dubbo/config/MonitorConfig.java | 4 +- .../alibaba/dubbo/config/ProtocolConfig.java | 6 +- .../alibaba/dubbo/config/ProviderConfig.java | 1 - .../alibaba/dubbo/config/ReferenceConfig.java | 4 +- .../alibaba/dubbo/config/RegistryConfig.java | 4 +- .../alibaba/dubbo/config/ServiceConfig.java | 8 +- .../dubbo/config/annotation/Reference.java | 3 - .../dubbo/config/annotation/Service.java | 2 - .../context/annotation/EnableDubbo.java | 7 +- .../alibaba/dubbo/container/Container.java | 4 +- .../alibaba/dubbo/container/page/Menu.java | 1 - .../dubbo/container/page/MenuComparator.java | 9 +- .../alibaba/dubbo/container/page/Page.java | 16 +- .../dubbo/container/page/PageHandler.java | 2 - .../dubbo/container/page/PageServlet.java | 38 +- .../dubbo/container/page/ResourceFilter.java | 13 +- .../container/page/pages/HomePageHandler.java | 9 +- .../container/page/pages/LogPageHandler.java | 35 +- .../page/pages/StatusPageHandler.java | 25 +- .../page/pages/SystemPageHandler.java | 20 +- .../com/alibaba/dubbo/monitor/Monitor.java | 5 +- .../alibaba/dubbo/monitor/MonitorFactory.java | 1 - .../dubbo/qos/command/BaseCommand.java | 1 - .../dubbo/qos/command/CommandContext.java | 1 - .../dubbo/registry/NotifyListener.java | 7 +- .../com/alibaba/dubbo/registry/Registry.java | 12 +- .../dubbo/registry/RegistryFactory.java | 1 - .../registry/support/AbstractRegistry.java | 66 +- .../support/AbstractRegistryFactory.java | 5 +- .../registry/support/FailbackRegistry.java | 61 +- .../com/alibaba/dubbo/remoting/Channel.java | 1 - .../dubbo/remoting/ChannelHandler.java | 30 +- .../com/alibaba/dubbo/remoting/Codec.java | 4 +- .../com/alibaba/dubbo/remoting/Codec2.java | 4 +- .../alibaba/dubbo/remoting/Dispatcher.java | 5 +- .../dubbo/remoting/RemotingException.java | 6 +- .../com/alibaba/dubbo/remoting/Server.java | 3 +- .../alibaba/dubbo/remoting/Transporter.java | 1 - .../dubbo/remoting/exchange/Exchanger.java | 4 +- .../remoting/exchange/ResponseCallback.java | 2 - .../remoting/exchange/ResponseFuture.java | 2 - .../dubbo/remoting/http/HttpBinder.java | 4 +- .../dubbo/remoting/telnet/TelnetHandler.java | 4 +- .../zookeeper/ZookeeperTransporter.java | 4 +- .../java/com/alibaba/dubbo/rpc/Exporter.java | 1 - .../java/com/alibaba/dubbo/rpc/Filter.java | 11 +- .../com/alibaba/dubbo/rpc/Invocation.java | 13 +- .../java/com/alibaba/dubbo/rpc/Invoker.java | 11 +- .../alibaba/dubbo/rpc/InvokerListener.java | 1 - .../java/com/alibaba/dubbo/rpc/Protocol.java | 10 +- .../com/alibaba/dubbo/rpc/ProxyFactory.java | 4 +- .../java/com/alibaba/dubbo/rpc/Result.java | 24 +- .../com/alibaba/dubbo/rpc/RpcContext.java | 24 +- .../com/alibaba/dubbo/rpc/RpcException.java | 1 - .../com/alibaba/dubbo/rpc/RpcInvocation.java | 36 +- .../java/com/alibaba/dubbo/rpc/RpcResult.java | 4 +- .../alibaba/dubbo/rpc/cluster/Cluster.java | 4 +- .../alibaba/dubbo/rpc/cluster/Directory.java | 11 +- .../dubbo/rpc/cluster/LoadBalance.java | 23 +- .../com/alibaba/dubbo/rpc/cluster/Merger.java | 4 +- .../com/alibaba/dubbo/rpc/cluster/Router.java | 29 +- .../dubbo/rpc/cluster/RouterFactory.java | 1 - .../dubbo/rpc/cluster/RuleConverter.java | 6 +- .../loadbalance/AbstractLoadBalance.java | 16 +- .../rpc/protocol/dubbo/FutureAdapter.java | 17 +- .../protocol/rest/support/ContentType.java | 4 +- .../dubbo/rpc/service/EchoService.java | 4 +- .../dubbo/rpc/service/GenericException.java | 5 +- .../dubbo/rpc/service/GenericService.java | 4 +- .../alibaba/dubbo/rpc/support/RpcUtils.java | 7 +- .../alibaba/dubbo/validation/Validation.java | 4 +- .../alibaba/dubbo/validation/Validator.java | 4 +- .../org/apache/dubbo/cache/CacheTest.java | 16 +- .../java/org/apache/dubbo/cache/MyCache.java | 10 +- .../apache/dubbo/cache/MyCacheFactory.java | 1 - .../dubbo/common/extension/ExtensionTest.java | 21 +- .../common/extension/MockDispatcher.java | 3 +- .../common/extension/MyExtensionFactory.java | 2 +- .../extension/activate/ActivateExt1.java | 1 - .../activate/impl/ActivateExt1Impl1.java | 5 +- .../support/ActivateComparatorTest.java | 13 +- .../common/extension/support/Filter0.java | 3 +- .../common/extension/support/Filter1.java | 3 +- .../common/extension/support/Filter2.java | 3 +- .../common/extension/support/Filter3.java | 3 +- .../common/extension/support/Filter4.java | 3 +- .../common/extension/support/OldFilter0.java | 3 +- .../common/extension/support/OldFilter5.java | 4 +- .../extension/support/Order0Filter0.java | 4 +- .../extension/support/Order0Filter1.java | 4 +- .../extension/support/Order0Filter2.java | 4 +- .../common/utils/AnnotationUtilsTest.java | 78 +- .../dubbo/config/ApplicationConfigTest.java | 9 +- .../dubbo/config/ArgumentConfigTest.java | 7 +- .../org/apache/dubbo/config/ConfigTest.java | 7 +- .../dubbo/config/ConsumerConfigTest.java | 1 - .../apache/dubbo/config/MethodConfigTest.java | 15 +- .../apache/dubbo/config/ModuleConfigTest.java | 9 +- .../dubbo/config/ProtocolConfigTest.java | 7 +- .../dubbo/config/ProviderConfigTest.java | 8 +- .../dubbo/config/ReferenceConfigTest.java | 1 - .../dubbo/config/RegistryConfigTest.java | 7 +- .../apache/dubbo/config/SignatureTest.java | 45 +- .../apache/dubbo/config/spring/api/Box.java | 1 - .../dubbo/config/spring/api/DemoService.java | 1 - .../dubbo/config/spring/api/HelloService.java | 1 - .../ServiceAnnotationTestConfiguration.java | 12 +- .../DubboComponentScanRegistrarTest.java | 8 +- .../DubboConfigConfigurationTest.java | 8 +- .../annotation/EnableDubboConfigTest.java | 25 +- .../context/annotation/EnableDubboTest.java | 12 +- .../consumer/ConsumerConfiguration.java | 12 +- .../test/TestConsumerConfiguration.java | 17 +- .../provider/DefaultHelloService.java | 1 - .../annotation/provider/DemoServiceImpl.java | 4 +- .../provider/ProviderConfiguration.java | 6 +- .../dubbo/config/spring/filter/MockDao.java | 4 +- .../config/spring/filter/MockDaoImpl.java | 4 +- .../config/spring/filter/MockFilter.java | 1 - .../apache/dubbo/echo/EchoServiceTest.java | 7 +- .../org/apache/dubbo/filter/FilterTest.java | 7 +- .../apache/dubbo/filter/LegacyInvocation.java | 8 +- .../apache/dubbo/filter/LegacyInvoker.java | 5 +- .../org/apache/dubbo/filter/MyFilter.java | 2 - .../dubbo/generic/GenericServiceTest.java | 132 +- .../AbstractAnnotationProcessingTest.java | 9 +- .../AnnotationProcessingTestProcessor.java | 17 +- .../CompilerInvocationInterceptor.java | 19 +- .../ArrayTypeDefinitionBuilderTest.java | 43 +- .../CollectionTypeDefinitionBuilderTest.java | 52 +- .../EnumTypeDefinitionBuilderTest.java | 8 +- .../GeneralTypeDefinitionBuilderTest.java | 14 +- .../builder/MapTypeDefinitionBuilderTest.java | 44 +- .../PrimitiveTypeDefinitionBuilderTest.java | 28 +- .../builder/ServiceDefinitionBuilderTest.java | 11 +- .../SimpleTypeDefinitionBuilderTest.java | 6 +- .../processing/model/ArrayTypeModel.java | 9 +- .../processing/model/CollectionTypeModel.java | 7 +- .../annotation/processing/model/Color.java | 5 +- .../processing/model/MapTypeModel.java | 6 +- .../processing/util/AnnotationUtilsTest.java | 80 +- .../processing/util/FieldUtilsTest.java | 9 +- .../processing/util/MemberUtilsTest.java | 8 +- .../processing/util/MethodUtilsTest.java | 13 +- .../util/ServiceAnnotationUtilsTest.java | 41 +- .../processing/util/TypeUtilsTest.java | 102 +- .../dubbo/metadata/rest/RestService.java | 1 - .../metadata/rest/SpringRestService.java | 23 +- .../metadata/rest/StandardRestService.java | 18 +- .../apache/dubbo/metadata/tools/Compiler.java | 11 +- .../dubbo/metadata/tools/CompilerTest.java | 10 +- .../tools/DefaultRestServiceTest.java | 7 +- .../metadata/tools/DefaultTestService.java | 7 +- .../metadata/tools/GenericTestService.java | 8 +- .../dubbo/metadata/tools/RestServiceTest.java | 8 +- .../metadata/tools/SpringRestServiceTest.java | 4 +- .../tools/StandardRestServiceTest.java | 4 +- .../dubbo/metadata/tools/TestProcessor.java | 3 +- .../dubbo/metadata/tools/TestService.java | 1 + .../dubbo/metadata/tools/TestServiceImpl.java | 10 +- .../org/apache/dubbo/rpc/RpcContextTest.java | 7 +- .../dubbo/rpc/cluster/CompatibleRouter.java | 4 +- .../dubbo/rpc/cluster/CompatibleRouter2.java | 4 +- .../apache/dubbo/rpc/cluster/RouterTest.java | 12 +- .../rpc/filter/GenericImplFilterTest.java | 23 +- .../apache/dubbo/rpc/support/DemoService.java | 5 +- .../org/apache/dubbo/rpc/support/Type.java | 4 +- .../dubbo/serialization/MyObjectInput.java | 5 +- .../dubbo/serialization/MyObjectOutput.java | 45 +- .../dubbo/serialization/MySerialization.java | 9 +- .../serialization/SerializationTest.java | 11 +- .../apache/dubbo/service/ComplexObject.java | 74 +- .../apache/dubbo/service/CustomArgument.java | 4 +- .../org/apache/dubbo/service/DemoService.java | 6 +- .../apache/dubbo/service/DemoServiceImpl.java | 16 +- .../apache/dubbo/service/MockInvocation.java | 22 +- .../java/org/apache/dubbo/service/Type.java | 4 +- dubbo-config/dubbo-config-api/pom.xml | 446 +- .../dubbo/config/ConfigInitializer.java | 10 +- .../dubbo/config/ConfigPostProcessor.java | 8 +- .../config/ConfigScopeModelInitializer.java | 1 - .../dubbo/config/DubboShutdownHook.java | 34 +- .../apache/dubbo/config/ReferenceConfig.java | 181 +- .../apache/dubbo/config/ServiceConfig.java | 292 +- .../bootstrap/BootstrapTakeoverMode.java | 5 +- .../config/bootstrap/DubboBootstrap.java | 18 +- .../DubboBootstrapStartStopListener.java | 1 - .../bootstrap/builders/AbstractBuilder.java | 3 +- .../builders/AbstractInterfaceBuilder.java | 4 +- .../builders/AbstractMethodBuilder.java | 2 +- .../builders/AbstractReferenceBuilder.java | 3 +- .../builders/AbstractServiceBuilder.java | 3 +- .../InternalServiceConfigBuilder.java | 137 +- .../bootstrap/builders/MethodBuilder.java | 1 + .../bootstrap/builders/ProtocolBuilder.java | 2 +- .../bootstrap/builders/ServiceBuilder.java | 16 +- .../deploy/DefaultApplicationDeployer.java | 343 +- .../deploy/DefaultMetricsServiceExporter.java | 57 +- .../config/deploy/DefaultModuleDeployer.java | 152 +- .../config/deploy/FrameworkModelCleaner.java | 4 +- .../ConfigurableMetadataServiceExporter.java | 30 +- .../metadata/ExporterDeployListener.java | 37 +- ...ataServiceURLParamsMetadataCustomizer.java | 6 +- .../config/utils/CompositeReferenceCache.java | 14 +- .../config/utils/ConfigValidationUtils.java | 143 +- .../config/utils/DefaultConfigValidator.java | 1 - .../config/utils/SimpleReferenceCache.java | 22 +- .../demo/MultiClassLoaderServiceImpl.java | 4 +- .../demo/MultiClassLoaderServiceRequest.java | 3 +- .../demo/MultiClassLoaderServiceResult.java | 3 +- .../dubbo/config/AbstractConfigTest.java | 109 +- .../config/AbstractMethodConfigTest.java | 10 +- .../config/AbstractReferenceConfigTest.java | 34 +- .../config/AbstractServiceConfigTest.java | 13 +- .../dubbo/config/ApplicationConfigTest.java | 35 +- .../dubbo/config/ArgumentConfigTest.java | 7 +- .../dubbo/config/ConfigCenterConfigTest.java | 91 +- .../ConfigScopeModelInitializerTest.java | 2 +- .../dubbo/config/ConsumerConfigTest.java | 63 +- .../dubbo/config/DubboShutdownHookTest.java | 12 +- .../config/MetadataReportConfigTest.java | 7 +- .../apache/dubbo/config/MethodConfigTest.java | 143 +- .../dubbo/config/MetricsConfigTest.java | 5 +- .../apache/dubbo/config/ModuleConfigTest.java | 15 +- .../dubbo/config/MonitorConfigTest.java | 13 +- .../dubbo/config/ProtocolConfigTest.java | 33 +- .../dubbo/config/ProviderConfigTest.java | 13 +- .../dubbo/config/ReferenceConfigTest.java | 479 +- .../dubbo/config/RegistryConfigTest.java | 29 +- .../dubbo/config/ServiceConfigTest.java | 178 +- .../org/apache/dubbo/config/SysProps.java | 1 - .../java/org/apache/dubbo/config/api/Box.java | 1 - .../dubbo/config/api/DemoException.java | 1 - .../apache/dubbo/config/api/DemoService.java | 4 +- .../org/apache/dubbo/config/api/Greeting.java | 2 +- .../org/apache/dubbo/config/api/User.java | 4 +- .../ConsulDubboServiceConsumerBootstrap.java | 9 +- .../ConsulDubboServiceProviderBootstrap.java | 8 +- .../config/bootstrap/DubboBootstrapTest.java | 119 +- .../DubboServiceConsumerBootstrap.java | 21 +- .../DubboServiceProviderBootstrap.java | 28 +- .../DubboServiceProviderMinimumBootstrap.java | 11 +- .../EtcdDubboServiceConsumerBootstrap.java | 15 +- .../EtcdDubboServiceProviderBootstrap.java | 30 +- .../config/bootstrap/MultiInstanceTest.java | 288 +- .../NacosDubboServiceConsumerBootstrap.java | 8 +- .../NacosDubboServiceProviderBootstrap.java | 12 +- ...ookeeperDubboServiceConsumerBootstrap.java | 7 +- ...ookeeperDubboServiceProviderBootstrap.java | 11 +- .../builders/AbstractBuilderTest.java | 11 +- .../AbstractInterfaceBuilderTest.java | 34 +- .../builders/AbstractMethodBuilderTest.java | 25 +- .../AbstractReferenceBuilderTest.java | 17 +- .../builders/AbstractServiceBuilderTest.java | 32 +- .../builders/ApplicationBuilderTest.java | 37 +- .../builders/ArgumentBuilderTest.java | 2 +- .../builders/ConfigCenterBuilderTest.java | 26 +- .../builders/ConsumerBuilderTest.java | 12 +- .../builders/MetadataReportBuilderTest.java | 22 +- .../bootstrap/builders/MethodBuilderTest.java | 27 +- .../bootstrap/builders/ModuleBuilderTest.java | 15 +- .../builders/MonitorBuilderTest.java | 21 +- .../builders/ProtocolBuilderTest.java | 49 +- .../builders/ProviderBuilderTest.java | 32 +- .../builders/ReferenceBuilderTest.java | 9 +- .../builders/RegistryBuilderTest.java | 37 +- .../builders/ServiceBuilderTest.java | 43 +- .../DubboInterfaceConsumerBootstrap.java | 10 +- .../dubbo/config/bootstrap/rest/User.java | 39 +- .../config/bootstrap/rest/UserService.java | 35 +- .../bootstrap/rest/UserServiceImpl.java | 27 +- .../dubbo/config/cache/CacheService.java | 1 - .../dubbo/config/cache/CacheServiceImpl.java | 1 - .../apache/dubbo/config/cache/CacheTest.java | 27 +- .../DefaultApplicationDeployerTest.java | 1 - ...bstractRegistryCenterExporterListener.java | 12 +- ...AbstractRegistryCenterServiceListener.java | 4 +- .../config/integration/IntegrationTest.java | 2 +- .../integration/multiple/AbstractStorage.java | 1 - .../config/integration/multiple/Storage.java | 2 +- ...ryCenterExportMetadataIntegrationTest.java | 30 +- ...pleRegistryCenterExportProviderFilter.java | 2 +- ...ryCenterExportProviderIntegrationTest.java | 56 +- ...xportProviderRegistryProtocolListener.java | 13 +- .../MultipleRegistryCenterInjvmFilter.java | 2 +- ...pleRegistryCenterInjvmIntegrationTest.java | 31 +- ...rviceDiscoveryRegistryIntegrationTest.java | 54 +- ...coveryRegistryRegistryServiceListener.java | 15 +- ...erServiceDiscoveryRegistryServiceImpl.java | 3 +- .../ServiceDiscoveryRegistryStorage.java | 4 +- ...tryCenterDubboProtocolIntegrationTest.java | 101 +- ...ryCenterExportMetadataIntegrationTest.java | 25 +- ...gleRegistryCenterExportProviderFilter.java | 2 +- ...ryCenterExportProviderIntegrationTest.java | 55 +- ...xportProviderRegistryProtocolListener.java | 13 +- .../SingleRegistryCenterInjvmFilter.java | 2 +- ...gleRegistryCenterInjvmIntegrationTest.java | 24 +- .../DelegateProviderMetaDataInvokerTest.java | 4 +- ...erviceURLParamsMetadataCustomizerTest.java | 24 +- .../dubbo/config/mock/GreetingLocal1.java | 6 +- .../dubbo/config/mock/GreetingLocal2.java | 2 +- .../dubbo/config/mock/GreetingLocal3.java | 2 +- .../apache/dubbo/config/mock/MockCluster.java | 2 +- .../apache/dubbo/config/mock/MockCodec.java | 7 +- .../dubbo/config/mock/MockDispatcher.java | 3 +- .../dubbo/config/mock/MockExchanger.java | 3 +- .../config/mock/MockExporterListener.java | 11 +- .../apache/dubbo/config/mock/MockFilter.java | 2 +- .../config/mock/MockInvokerListener.java | 10 +- .../dubbo/config/mock/MockLoadBalance.java | 2 +- .../dubbo/config/mock/MockProtocol.java | 9 +- .../dubbo/config/mock/MockProtocol2.java | 3 +- .../dubbo/config/mock/MockProxyFactory.java | 2 +- .../dubbo/config/mock/MockRegistry.java | 21 +- .../config/mock/MockRegistryFactory.java | 1 - .../config/mock/MockRegistryFactory2.java | 3 +- .../config/mock/MockServiceDiscovery.java | 19 +- .../config/mock/MockServiceListener.java | 3 +- .../dubbo/config/mock/MockStatusChecker.java | 3 +- .../dubbo/config/mock/MockTelnetHandler.java | 3 +- .../dubbo/config/mock/MockThreadPool.java | 3 +- .../dubbo/config/mock/MockTransporter.java | 3 +- .../dubbo/config/mock/TestProxyFactory.java | 3 +- .../config/nested/AggregationConfigTest.java | 2 +- .../config/provider/impl/DemoServiceImpl.java | 1 - .../config/url/ExporterSideConfigUrlTest.java | 25 +- .../config/url/InvokerSideConfigUrlTest.java | 138 +- .../config/url/RpcConfigGetSetProxy.java | 8 +- .../apache/dubbo/config/url/UrlTestBase.java | 44 +- .../utils/ConfigValidationUtilsTest.java | 44 +- .../config/utils/ReferenceCacheTest.java | 36 +- .../config/utils/service/FooService.java | 3 +- .../config/utils/service/FooServiceImpl.java | 3 +- .../config/utils/service/XxxService.java | 3 +- .../config/utils/service/XxxServiceImpl.java | 3 +- .../metadata/MetadataServiceExporterTest.java | 256 - dubbo-config/dubbo-config-spring/pom.xml | 551 +- .../dubbo/config/spring/ConfigCenterBean.java | 26 +- .../apache/dubbo/config/spring/Constants.java | 1 - .../dubbo/config/spring/ReferenceBean.java | 110 +- .../dubbo/config/spring/ServiceBean.java | 11 +- .../spring/SpringScopeModelInitializer.java | 12 +- .../spring/aot/AotWithSpringDetector.java | 2 +- .../AbstractAnnotationBeanPostProcessor.java | 126 +- .../AnnotationPropertyValuesAdapter.java | 26 +- .../DubboConfigAliasPostProcessor.java | 8 +- .../ReferenceAnnotationBeanPostProcessor.java | 181 +- .../ServiceAnnotationPostProcessor.java | 206 +- .../annotation/ServiceBeanNameBuilder.java | 10 +- .../annotation/ServicePackagesHolder.java | 2 - ...DefaultPropertyValueBeanPostProcessor.java | 17 +- .../DubboBootstrapApplicationListener.java | 26 +- .../DubboConfigApplicationListener.java | 21 +- .../context/DubboConfigBeanInitializer.java | 13 +- .../context/DubboContextPostProcessor.java | 11 +- .../DubboDeployApplicationListener.java | 35 +- .../DubboInfraBeanRegisterPostProcessor.java | 12 +- .../context/DubboSpringInitContext.java | 6 +- .../context/DubboSpringInitCustomizer.java | 1 - .../DubboSpringInitCustomizerHolder.java | 4 +- .../context/DubboSpringInitializer.java | 54 +- .../DubboClassPathBeanDefinitionScanner.java | 25 +- .../annotation/DubboComponentScan.java | 5 +- .../DubboComponentScanRegistrar.java | 31 +- .../annotation/DubboConfigConfiguration.java | 60 +- .../context/annotation/EnableDubbo.java | 6 +- .../context/annotation/EnableDubboConfig.java | 7 +- ...DefaultValueDubboConfigBeanCustomizer.java | 7 +- .../context/event/DubboConfigInitEvent.java | 1 - .../properties/AbstractDubboConfigBinder.java | 1 - .../properties/DefaultDubboConfigBinder.java | 21 +- .../extension/SpringExtensionInjector.java | 21 +- .../spring/reference/ReferenceAttributes.java | 10 +- .../reference/ReferenceBeanBuilder.java | 84 +- .../reference/ReferenceBeanManager.java | 49 +- .../reference/ReferenceBeanSupport.java | 84 +- .../spring/reference/ReferenceCreator.java | 50 +- .../AnnotationBeanDefinitionParser.java | 5 +- .../schema/DubboBeanDefinitionParser.java | 205 +- .../status/DataSourceStatusChecker.java | 12 +- .../spring/status/SpringStatusChecker.java | 9 +- .../config/spring/util/AnnotationUtils.java | 228 +- .../spring/util/DubboAnnotationUtils.java | 82 +- .../config/spring/util/DubboBeanUtils.java | 81 +- .../config/spring/util/EnvironmentUtils.java | 29 +- .../util/GenericBeanPostProcessorAdapter.java | 15 +- .../util/LazyTargetInvocationHandler.java | 4 +- .../dubbo/config/spring/util/LockUtils.java | 7 +- .../spring/util/PropertySourcesUtils.java | 19 +- .../config/spring/util/SpringCompatUtils.java | 27 +- .../spring/AbstractRegistryService.java | 21 +- .../dubbo/config/spring/ConfigTest.java | 218 +- .../spring/ControllerServiceConfigTest.java | 5 +- .../config/spring/DubboStateListener.java | 4 +- .../config/spring/JavaConfigBeanTest.java | 19 +- .../dubbo/config/spring/ServiceBeanTest.java | 4 +- .../config/spring/SimpleRegistryExporter.java | 13 +- .../config/spring/SimpleRegistryService.java | 46 +- .../apache/dubbo/config/spring/SysProps.java | 1 - .../spring/action/DemoActionByAnnotation.java | 1 - .../spring/action/DemoActionBySetter.java | 1 - .../config/spring/action/DemoInterceptor.java | 1 - .../annotation/consumer/AnnotationAction.java | 5 +- .../annotation/merged/MergedReference.java | 5 +- .../annotation/merged/MergedService.java | 5 +- .../provider/AnnotationServiceImpl.java | 1 - .../apache/dubbo/config/spring/api/Box.java | 1 - .../dubbo/config/spring/api/DemoService.java | 1 - .../dubbo/config/spring/api/HelloService.java | 1 - .../DubboConfigAliasPostProcessorTest.java | 1 - .../annotation/MergedAnnotationTest.java | 13 +- .../annotation/MethodConfigCallbackTest.java | 63 +- .../annotation/ParameterConvertTest.java | 25 +- ...erenceAnnotationBeanPostProcessorTest.java | 93 +- .../annotation/ReferenceCreatorTest.java | 107 +- .../ServiceAnnotationPostProcessorTest.java | 29 +- .../ServiceAnnotationTestConfiguration.java | 12 +- .../ServiceBeanNameBuilderTest.java | 31 +- ...ultPropertyValueBeanPostProcessorTest.java | 5 +- ...MultipleServicesWithMethodConfigsTest.java | 5 +- .../config/YamlPropertySourceFactory.java | 87 +- .../config/YamlPropertySourceFactoryTest.java | 7 +- .../XmlReferenceBeanConditionalTest.java | 31 +- ...nnotationReferenceBeanConditionalTest.java | 32 +- ...ConfigRawReferenceBeanConditionalTest.java | 32 +- ...vaConfigReferenceBeanConditionalTest4.java | 32 +- .../SpringBootConfigPropsTest.java | 62 +- .../SpringBootMultipleConfigPropsTest.java | 76 +- .../SpringBootImportDubboXmlTest.java | 17 +- .../boot/importxml2/HelloServiceImpl.java | 1 - .../SpringBootImportAndScanTest.java | 28 +- .../KeepRunningOnSpringClosedTest.java | 15 +- .../DubboComponentScanRegistrarTest.java | 10 +- .../DubboConfigConfigurationTest.java | 8 +- .../annotation/EnableDubboConfigTest.java | 25 +- .../context/annotation/EnableDubboTest.java | 26 +- .../consumer/ConsumerConfiguration.java | 12 +- .../test/TestConsumerConfiguration.java | 8 +- .../provider/DefaultHelloService.java | 1 - .../annotation/provider/DemoServiceImpl.java | 4 +- .../annotation/provider/HelloServiceImpl.java | 1 - .../provider/ProviderConfiguration.java | 6 +- .../DubboSpringInitCustomizerTest.java | 11 +- .../DefaultDubboConfigBinderTest.java | 4 +- .../SpringExtensionInjectorTest.java | 18 +- .../dubbo/config/spring/filter/MockDao.java | 4 +- .../config/spring/filter/MockDaoImpl.java | 4 +- .../config/spring/filter/MockFilter.java | 1 - .../config/spring/impl/DemoServiceImpl.java | 1 - .../spring/impl/DemoServiceSonImpl.java | 1 - .../spring/impl/MethodCallbackImpl.java | 8 +- .../UnserializableBoxDemoServiceImpl.java | 1 - .../isolation/api/ApiIsolationTest.java | 49 +- .../spring/isolation/spring/BaseTest.java | 8 +- .../annotation/AnnotationIsolationTest.java | 23 +- .../consumer/dubbo/DemoServiceV1.java | 1 + .../consumer/dubbo/HelloServiceV2.java | 1 + .../consumer/dubbo/HelloServiceV3.java | 1 + .../consumer/tri/DemoServiceV1.java | 3 +- .../consumer/tri/HelloServiceV2.java | 1 + .../consumer/tri/HelloServiceV3.java | 1 + .../provider/HelloServiceImplV2.java | 1 + .../provider/HelloServiceImplV3.java | 2 +- .../spring/support/DemoServiceExecutor.java | 3 +- .../spring/support/HelloServiceExecutor.java | 10 +- .../spring/xml/XmlIsolationTest.java | 12 +- .../issues/issue6000/Issue6000Test.java | 3 +- .../issues/issue6252/Issue6252Test.java | 1 - .../issues/issue7003/Issue7003Test.java | 14 +- .../MultipleConsumerAndProviderTest.java | 16 +- .../issue9207/ConfigCenterBeanTest.java | 41 +- .../metrics/SpringBootConfigMetricsTest.java | 50 +- .../consumer/PropertyConfigurerTest.java | 20 +- .../PropertySourcesConfigurerTest.java | 19 +- .../PropertySourcesInJavaConfigTest.java | 32 +- .../provider/HelloServiceImpl.java | 7 +- .../DubboConfigBeanInitializerTest.java | 35 +- .../spring/reference/ReferenceKeyTest.java | 274 +- .../JavaConfigReferenceBeanTest.java | 110 +- .../reference/localcall/LocalCallTest.java | 19 +- .../reference/localcall/LocalCallTest2.java | 11 +- .../localcall/LocalHelloServiceImpl.java | 5 +- .../LocalCallReferenceAnnotationTest.java | 16 +- ...lCallMultipleReferenceAnnotationsTest.java | 36 +- .../LocalCallReferenceMixTest.java | 15 +- .../consumer/DubboXmlConsumerTest.java | 13 +- .../provider/DubboXmlProviderTest.java | 17 +- .../config/spring/registry/MockRegistry.java | 4 +- .../spring/registry/MockServiceDiscovery.java | 26 +- .../DemoServiceConsumerBootstrap.java | 7 +- .../DemoServiceConsumerXmlBootstrap.java | 4 +- .../DemoServiceProviderBootstrap.java | 4 +- .../DemoServiceProviderXmlBootstrap.java | 4 +- .../nacos/demo/service/DefaultService.java | 4 +- .../nacos/demo/service/DemoService.java | 1 - .../nacos/nacos/NacosServiceNameTest.java | 3 +- .../schema/DubboNamespaceHandlerTest.java | 92 +- .../spring/schema/GenericServiceTest.java | 10 +- .../GenericServiceWithoutInterfaceTest.java | 11 +- .../status/DataSourceStatusCheckerTest.java | 22 +- .../status/SpringStatusCheckerTest.java | 13 +- .../spring/util/EnvironmentUtilsTest.java | 12 +- dubbo-config/dubbo-config-spring6/pom.xml | 143 +- ...nceAnnotationWithAotBeanPostProcessor.java | 123 +- ...ServiceAnnotationWithAotPostProcessor.java | 16 +- .../factory/aot/AutowiredElementResolver.java | 22 +- .../aot/ReferencedFieldValueResolver.java | 36 +- .../ReferencedMethodArgumentsResolver.java | 67 +- .../DubboInfraBeanRegisterPostProcessor.java | 8 +- .../dubbo/config/spring6/utils/AotUtils.java | 32 +- .../config/spring6/utils/AotUtilsTest.java | 4 +- .../config/spring6/utils/DemoService.java | 2 - .../config/spring6/utils/HelloRequest.java | 1 - .../spring6/utils/HelloRequestSuper.java | 3 +- .../config/spring6/utils/HelloResponse.java | 1 - dubbo-config/pom.xml | 122 +- .../dubbo-configcenter-apollo/pom.xml | 103 +- .../apollo/ApolloDynamicConfiguration.java | 85 +- .../ApolloDynamicConfigurationFactory.java | 4 +- .../ApolloDynamicConfigurationTest.java | 58 +- .../support/apollo/EmbeddedApolloJunit5.java | 25 +- .../dubbo-configcenter-file/pom.xml | 81 +- .../file/FileSystemDynamicConfiguration.java | 175 +- ...SystemDynamicConfigurationFactoryTest.java | 7 +- .../FileSystemDynamicConfigurationTest.java | 54 +- .../dubbo-configcenter-nacos/pom.xml | 87 +- .../nacos/NacosDynamicConfiguration.java | 58 +- .../NacosDynamicConfigurationFactory.java | 5 +- .../support/nacos/MockConfigService.java | 18 +- .../nacos/NacosDynamicConfigurationTest.java | 65 +- .../configcenter/support/nacos/RetryTest.java | 51 +- .../dubbo-configcenter-zookeeper/pom.xml | 157 +- .../support/zookeeper/CacheListener.java | 17 +- .../zookeeper/ZookeeperDataListener.java | 10 +- .../ZookeeperDynamicConfiguration.java | 35 +- .../ZookeeperDynamicConfigurationTest.java | 84 +- dubbo-configcenter/pom.xml | 57 +- dubbo-container/dubbo-container-api/pom.xml | 75 +- .../org/apache/dubbo/container/Container.java | 1 - .../java/org/apache/dubbo/container/Main.java | 13 +- .../dubbo-container-spring/pom.xml | 61 +- .../container/spring/SpringContainer.java | 1 - .../container/spring/SpringContainerTest.java | 9 +- dubbo-container/pom.xml | 37 +- .../dubbo-demo-annotation-consumer/pom.xml | 165 +- .../dubbo/demo/consumer/Application.java | 7 +- .../consumer/comp/DemoServiceComponent.java | 4 +- .../dubbo-demo-annotation-provider/pom.xml | 165 +- .../dubbo/demo/provider/Application.java | 3 +- .../dubbo/demo/provider/DemoServiceImpl.java | 11 +- dubbo-demo/dubbo-demo-annotation/pom.xml | 65 +- .../dubbo-demo-api-consumer/pom.xml | 167 +- .../dubbo/demo/consumer/Application.java | 25 +- .../dubbo-demo-api-provider/pom.xml | 160 +- .../dubbo/demo/provider/Application.java | 14 +- .../dubbo/demo/provider/DemoServiceImpl.java | 11 +- dubbo-demo/dubbo-demo-api/pom.xml | 70 +- dubbo-demo/dubbo-demo-generic-call/pom.xml | 155 +- .../demo/consumer/GenericApplication.java | 17 +- dubbo-demo/dubbo-demo-interface/pom.xml | 63 +- .../org/apache/dubbo/demo/DemoService.java | 1 - .../apache/dubbo/demo/RestDemoService.java | 14 +- .../dubbo/demo/rest/api/CurlService.java | 8 +- .../api/DubboServiceAnnotationService.java | 4 - .../demo/rest/api/ExceptionMapperService.java | 3 - .../demo/rest/api/HttpMethodService.java | 7 +- ...tpRequestAndResponseRPCContextService.java | 5 +- .../demo/rest/api/JaxRsRestDemoService.java | 15 +- .../demo/rest/api/SpringRestDemoService.java | 26 +- .../src/main/java/po/TestPO.java | 9 +- .../src/main/java/po/User.java | 10 +- .../dubbo-demo-native-consumer/pom.xml | 361 +- .../demo/graalvm/consumer/Application.java | 18 +- .../dubbo-demo-native-interface/pom.xml | 27 +- .../dubbo/graalvm/demo/DemoService.java | 1 - .../dubbo-demo-native-provider/pom.xml | 363 +- .../demo/graalvm/provider/Application.java | 22 +- .../graalvm/provider/DemoServiceImpl.java | 11 +- dubbo-demo/dubbo-demo-native/pom.xml | 39 +- .../dubbo-demo-spring-boot-consumer/pom.xml | 183 +- .../demo/consumer/ConsumerApplication.java | 2 +- .../dubbo-demo-spring-boot-interface/pom.xml | 27 +- .../dubbo/springboot/demo/DemoService.java | 1 - .../dubbo-demo-spring-boot-provider/pom.xml | 173 +- .../demo/provider/DemoServiceImpl.java | 9 +- .../demo/provider/ProviderApplication.java | 7 +- dubbo-demo/dubbo-demo-spring-boot/pom.xml | 117 +- dubbo-demo/dubbo-demo-triple/pom.xml | 298 +- .../org/apache/dubbo/demo/GreeterService.java | 2 - .../apache/dubbo/demo/GreeterServiceImpl.java | 4 +- .../dubbo/demo/consumer/ApiConsumer.java | 18 +- .../demo/consumer/ApiWrapperConsumer.java | 11 +- .../dubbo/demo/provider/ApiProvider.java | 13 +- .../demo/provider/ApiWrapperProvider.java | 13 +- .../dubbo-demo-jaxrs-rest-consumer/pom.xml | 252 +- .../dubbo/demo/rest/api/RestConsumer.java | 25 +- ...DubboServiceAnnotationServiceConsumer.java | 1 + .../demo/rest/api/config/DubboConfig.java | 3 +- .../dubbo-demo-jaxrs-rest-provider/pom.xml | 252 +- .../dubbo/demo/rest/api/RestProvider.java | 19 +- .../demo/rest/api/config/DubboConfig.java | 3 +- .../api/extension/ExceptionMapperForTest.java | 2 - .../demo/rest/api/impl/CurlServiceImpl.java | 4 +- .../api/impl/ExceptionMapperServiceImpl.java | 3 +- .../rest/api/impl/HttpMethodServiceImpl.java | 2 +- ...questAndResponseRPCContextServiceImpl.java | 6 +- .../api/impl/JaxRsRestDemoServiceImpl.java | 16 +- .../pom.xml | 253 +- .../demo/rest/api/SpringMvcRestConsumer.java | 12 +- .../demo/rest/api/config/DubboConfig.java | 5 +- .../SpringRestDemoServiceConsumer.java | 5 +- .../pom.xml | 252 +- .../demo/rest/api/SpringMvcRestProvider.java | 7 +- .../demo/rest/api/config/DubboConfig.java | 3 +- .../api/impl/SpringRestDemoServiceImpl.java | 14 +- .../dubbo-demo-xml-consumer/pom.xml | 191 +- .../dubbo/demo/consumer/Application.java | 85 +- .../dubbo-demo-xml-provider/pom.xml | 214 +- .../dubbo/demo/provider/DemoServiceImpl.java | 20 +- .../demo/provider/RestDemoServiceImpl.java | 8 +- .../demo/provider/TripleServiceImpl.java | 1 - dubbo-demo/dubbo-demo-xml/pom.xml | 75 +- dubbo-demo/pom.xml | 61 +- dubbo-dependencies-bom/pom.xml | 2240 ++--- .../pom.xml | 382 +- .../dubbo-dependencies-zookeeper/pom.xml | 370 +- dubbo-dependencies/pom.xml | 205 +- dubbo-distribution/dubbo-all/pom.xml | 2767 +++--- dubbo-distribution/dubbo-bom/pom.xml | 1528 ++-- dubbo-distribution/pom.xml | 151 +- dubbo-kubernetes/pom.xml | 116 +- .../kubernetes/KubernetesMeshEnvListener.java | 27 +- .../kubernetes/KubernetesRegistry.java | 16 +- .../KubernetesServiceDiscovery.java | 227 +- .../registry/kubernetes/MeshConstant.java | 26 +- .../NopKubernetesMeshEnvListener.java | 8 +- .../util/KubernetesClientConst.java | 54 +- .../util/KubernetesConfigUtils.java | 24 +- .../KubernetesServiceDiscoveryTest.java | 137 +- dubbo-maven-plugin/pom.xml | 160 +- .../maven/plugin/aot/DubboProcessAotMojo.java | 22 +- .../plugin/protoc/DubboProtocPlugin.java | 24 +- .../protoc/DubboProtocPluginWrapper.java | 4 +- .../DubboProtocPluginWrapperFactory.java | 8 +- .../protoc/LinuxDubboProtocPluginWrapper.java | 13 +- .../maven/plugin/protoc/ProtocMetaData.java | 15 +- .../protoc/WinDubboProtocPluginWrapper.java | 37 +- .../protoc/enums/DubboGenerateTypeEnum.java | 15 +- dubbo-metadata/dubbo-metadata-api/pom.xml | 99 +- .../dubbo/metadata/AbstractCacheManager.java | 34 +- .../metadata/AbstractServiceNameMapping.java | 59 +- .../metadata/DefaultMetadataParamsFilter.java | 20 +- .../dubbo/metadata/MappingCacheManager.java | 2 +- .../dubbo/metadata/MappingChangedEvent.java | 3 +- .../dubbo/metadata/MetadataConstants.java | 1 - .../apache/dubbo/metadata/MetadataInfo.java | 165 +- .../dubbo/metadata/MetadataParamsFilter.java | 16 +- .../metadata/MetadataServiceDetector.java | 1 - .../metadata/ParameterTypesComparator.java | 4 - .../dubbo/metadata/RevisionResolver.java | 2 - .../dubbo/metadata/ServiceNameMapping.java | 6 +- ...adataReflectionTypeDescriberRegistrar.java | 7 +- .../dubbo/metadata/report/MetadataReport.java | 15 +- .../report/MetadataReportFactory.java | 3 +- .../report/MetadataReportInstance.java | 27 +- .../report/MetadataScopeModelInitializer.java | 8 +- .../BaseApplicationMetadataIdentifier.java | 3 +- .../identifier/BaseMetadataIdentifier.java | 1 - .../report/identifier/KeyTypeEnum.java | 2 - .../report/identifier/MetadataIdentifier.java | 17 +- .../identifier/ServiceMetadataIdentifier.java | 23 +- .../SubscriberMetadataIdentifier.java | 6 +- .../support/AbstractMetadataReport.java | 188 +- .../AbstractMetadataReportFactory.java | 6 +- .../metadata/report/support/Constants.java | 1 - .../report/support/NopMetadataReport.java | 29 +- .../AbstractServiceNameMappingTest.java | 46 +- .../apache/dubbo/metadata/DemoService.java | 37 - .../dubbo/metadata/MetadataInfoTest.java | 54 +- .../metadata/ServiceNameMappingTest.java | 125 - .../filter/CustomizedParamsFilter.java | 2 +- .../metadata/filter/ExcludedParamsFilter.java | 2 +- .../filter/ExcludedParamsFilter2.java | 2 +- .../report/MetadataReportInstanceTest.java | 15 +- ...BaseApplicationMetadataIdentifierTest.java | 2 +- .../BaseServiceMetadataIdentifierTest.java | 2 +- .../identifier/MetadataIdentifierTest.java | 26 +- .../AbstractMetadataReportFactoryTest.java | 56 +- .../support/AbstractMetadataReportTest.java | 183 +- .../test/JTestMetadataReport4Test.java | 11 +- .../test/JTestMetadataReportFactory4Test.java | 1 - .../pom.xml | 47 +- .../protobuf/ProtobufTypeBuilder.java | 28 +- .../protobuf/ProtobufTypeBuilderTest.java | 22 +- .../definition/protobuf/model/GooglePB.java | 7477 +++++++++-------- .../dubbo-metadata-processor/pom.xml | 196 +- .../AbstractServiceAnnotationProcessor.java | 5 +- .../processing/ClassPathMetadataStorage.java | 22 +- ...DefinitionMetadataAnnotationProcessor.java | 4 +- .../builder/ArrayTypeDefinitionBuilder.java | 7 +- .../CollectionTypeDefinitionBuilder.java | 12 +- .../builder/EnumTypeDefinitionBuilder.java | 7 +- .../builder/GeneralTypeDefinitionBuilder.java | 7 +- .../builder/MapTypeDefinitionBuilder.java | 12 +- .../builder/MethodDefinitionBuilder.java | 7 +- .../PrimitiveTypeDefinitionBuilder.java | 4 +- .../builder/ServiceDefinitionBuilder.java | 4 +- .../builder/SimpleTypeDefinitionBuilder.java | 5 +- .../processing/builder/TypeBuilder.java | 1 + .../builder/TypeDefinitionBuilder.java | 31 +- ...ractAnnotatedMethodParameterProcessor.java | 17 +- .../AbstractServiceRestMetadataResolver.java | 124 +- .../AnnotatedMethodParameterProcessor.java | 9 +- .../DefaultServiceRestMetadataResolver.java | 55 +- ...erviceRestMetadataAnnotationProcessor.java | 16 +- .../rest/ServiceRestMetadataResolver.java | 8 +- .../rest/ServiceRestMetadataStorage.java | 27 +- .../jaxrs/DefaultValueParameterProcessor.java | 12 +- .../jaxrs/HeaderParamParameterProcessor.java | 11 +- .../JAXRSServiceRestMetadataResolver.java | 33 +- .../ParamAnnotationParameterProcessor.java | 10 +- ...ctRequestAnnotationParameterProcessor.java | 13 +- .../RequestHeaderParameterProcessor.java | 10 +- .../RequestParamParameterProcessor.java | 11 +- .../SpringMvcServiceRestMetadataResolver.java | 56 +- .../processing/util/AnnotationUtils.java | 89 +- .../util/ExecutableElementComparator.java | 9 +- .../processing/util/FieldUtils.java | 12 +- .../processing/util/LoggerUtils.java | 1 - .../processing/util/MemberUtils.java | 4 +- .../processing/util/MethodUtils.java | 41 +- .../util/ServiceAnnotationUtils.java | 7 +- .../annotation/processing/util/TypeUtils.java | 57 +- .../AbstractAnnotationProcessingTest.java | 10 +- .../AnnotationProcessingTestProcessor.java | 17 +- .../CompilerInvocationInterceptor.java | 19 +- .../ArrayTypeDefinitionBuilderTest.java | 43 +- .../CollectionTypeDefinitionBuilderTest.java | 52 +- .../EnumTypeDefinitionBuilderTest.java | 8 +- .../GeneralTypeDefinitionBuilderTest.java | 14 +- .../builder/MapTypeDefinitionBuilderTest.java | 44 +- .../PrimitiveTypeDefinitionBuilderTest.java | 28 +- .../builder/ServiceDefinitionBuilderTest.java | 11 +- .../SimpleTypeDefinitionBuilderTest.java | 6 +- .../processing/model/ArrayTypeModel.java | 9 +- .../processing/model/CollectionTypeModel.java | 7 +- .../annotation/processing/model/Color.java | 5 +- .../processing/model/MapTypeModel.java | 6 +- .../processing/util/AnnotationUtilsTest.java | 86 +- .../processing/util/FieldUtilsTest.java | 9 +- .../processing/util/MemberUtilsTest.java | 8 +- .../processing/util/MethodUtilsTest.java | 13 +- .../util/ServiceAnnotationUtilsTest.java | 42 +- .../processing/util/TypeUtilsTest.java | 102 +- .../dubbo/metadata/rest/RestService.java | 1 - .../metadata/rest/SpringRestService.java | 23 +- .../metadata/rest/StandardRestService.java | 18 +- .../apache/dubbo/metadata/tools/Compiler.java | 11 +- .../dubbo/metadata/tools/CompilerTest.java | 10 +- .../tools/DefaultRestServiceTest.java | 7 +- .../metadata/tools/DefaultTestService.java | 7 +- .../metadata/tools/GenericTestService.java | 6 +- .../dubbo/metadata/tools/RestServiceTest.java | 8 +- .../metadata/tools/SpringRestServiceTest.java | 4 +- .../tools/StandardRestServiceTest.java | 4 +- .../dubbo/metadata/tools/TestProcessor.java | 3 +- .../dubbo/metadata/tools/TestService.java | 1 + .../dubbo/metadata/tools/TestServiceImpl.java | 7 +- .../dubbo-metadata-report-nacos/pom.xml | 44 +- .../nacos/NacosConfigServiceWrapper.java | 1 - .../store/nacos/NacosMetadataReport.java | 93 +- .../nacos/NacosMetadataReportFactory.java | 1 - .../store/nacos/MockConfigService.java | 12 +- .../dubbo/metadata/store/nacos/RetryTest.java | 42 +- .../dubbo-metadata-report-redis/pom.xml | 65 +- .../store/redis/RedisMetadataReport.java | 28 +- .../redis/RedisMetadataReportFactory.java | 2 - .../store/redis/RedisMetadata4TstService.java | 1 - .../store/redis/RedisMetadataReportTest.java | 82 +- .../dubbo-metadata-report-zookeeper/pom.xml | 114 +- .../zookeeper/ZookeeperMetadataReport.java | 8 +- .../ZookeeperMetadataReportFactory.java | 1 - .../ZookeeperMetadataReportTest.java | 152 +- dubbo-metadata/dubbo-metadata-rest/pom.xml | 87 +- ...ractAnnotatedMethodParameterProcessor.java | 39 +- ...AbstractNoAnnotatedParameterProcessor.java | 12 +- .../AbstractServiceRestMetadataResolver.java | 131 +- .../AnnotatedMethodParameterProcessor.java | 13 +- .../apache/dubbo/metadata/rest/ArgInfo.java | 24 +- .../DefaultServiceRestMetadataResolver.java | 11 +- .../metadata/rest/JAXRSClassConstants.java | 5 - .../apache/dubbo/metadata/rest/ParamType.java | 39 +- .../dubbo/metadata/rest/PathMatcher.java | 65 +- .../apache/dubbo/metadata/rest/PathUtil.java | 14 +- .../dubbo/metadata/rest/RequestMetadata.java | 49 +- .../metadata/rest/RestMetadataConstants.java | 10 +- .../metadata/rest/RestMethodMetadata.java | 54 +- .../metadata/rest/ServiceRestMetadata.java | 52 +- .../rest/ServiceRestMetadataReader.java | 1 - .../rest/ServiceRestMetadataResolver.java | 2 +- .../rest/SpringMvcClassConstants.java | 6 +- .../rest/jaxrs/BodyParameterProcessor.java | 16 +- .../jaxrs/DefaultValueParameterProcessor.java | 11 +- .../jaxrs/FormBodyParameterProcessor.java | 14 +- .../jaxrs/HeaderParamParameterProcessor.java | 10 +- .../JAXRSServiceRestMetadataResolver.java | 12 +- .../ParamAnnotationParameterProcessor.java | 10 +- .../jaxrs/PathParamParameterProcessor.java | 2 - .../dubbo/metadata/rest/media/MediaType.java | 7 +- ...AnnotationServiceRestMetadataResolver.java | 15 +- .../PathVariableParameterProcessor.java | 2 - .../RequestHeaderParameterProcessor.java | 11 +- .../RequestParamParameterProcessor.java | 10 +- .../SpringMvcServiceRestMetadataResolver.java | 18 +- .../dubbo/metadata/rest/tag/BodyTag.java | 3 +- .../metadata/rest/tag/NoAnnotationTag.java | 3 +- .../dubbo/metadata/rest/tag/ParamTag.java | 3 +- .../dubbo/metadata/PathMatcherTest.java | 12 +- .../apache/dubbo/metadata/TestMediaType.java | 1 + .../metadata/rest/DefaultRestService.java | 12 +- .../dubbo/metadata/rest/RestService.java | 5 +- .../metadata/rest/SpringRestService.java | 47 +- .../metadata/rest/StandardRestService.java | 30 +- ...oubleCheckContainsPathVariableService.java | 1 - .../rest/api/JaxrsRestDoubleCheckService.java | 1 + .../metadata/rest/api/JaxrsRestService.java | 2 - .../rest/api/JaxrsRestServiceImpl.java | 1 - .../metadata/rest/api/JaxrsUsingService.java | 1 - .../rest/api/SpringControllerService.java | 49 +- .../metadata/rest/api/SpringRestService.java | 60 +- .../rest/api/SpringRestServiceImpl.java | 4 +- .../rest/feign/FeignClientController.java | 1 - .../rest/feign/FeignClientControllerImpl.java | 4 +- .../JAXRSServiceRestMetadataResolverTest.java | 40 +- .../rest/jaxrs/JaxrsRestDoubleCheckTest.java | 21 +- ...tationServiceRestMetadataResolverTest.java | 41 +- .../springmvc/FeignClientAnnotationTest.java | 14 +- ...ingMvcServiceRestMetadataResolverTest.java | 44 +- dubbo-metadata/pom.xml | 57 +- dubbo-metrics/dubbo-metrics-api/pom.xml | 82 +- .../apache/dubbo/metrics/aggregate/Pane.java | 1 - .../aggregate/SampleAggregatedEntry.java | 2 - .../metrics/aggregate/SlidingWindow.java | 4 +- .../aggregate/TimeWindowAggregator.java | 4 +- .../metrics/aggregate/TimeWindowCounter.java | 7 +- .../metrics/aggregate/TimeWindowQuantile.java | 8 +- .../ApplicationMetricsCollector.java | 3 - .../collector/CombMetricsCollector.java | 12 +- .../collector/MethodMetricsCollector.java | 2 - .../metrics/collector/MetricsCollector.java | 5 +- .../collector/ServiceMetricsCollector.java | 2 - .../collector/stat/MetricsStatHandler.java | 2 - .../data/ApplicationStatComposite.java | 8 +- .../dubbo/metrics/data/BaseStatComposite.java | 13 +- .../metrics/data/MethodStatComposite.java | 20 +- .../dubbo/metrics/data/RtStatComposite.java | 48 +- .../metrics/data/ServiceStatComposite.java | 14 +- .../metrics/event/MetricsDispatcher.java | 5 +- .../dubbo/metrics/event/MetricsInitEvent.java | 12 +- .../event/SimpleMetricsEventMulticaster.java | 1 - .../listener/AbstractMetricsKeyListener.java | 10 +- .../listener/AbstractMetricsListener.java | 5 +- .../listener/MetricsApplicationListener.java | 34 +- .../metrics/listener/MetricsLifeListener.java | 7 +- .../listener/MetricsServiceListener.java | 26 +- .../metrics/model/ApplicationMetric.java | 6 +- .../metrics/model/ConfigCenterMetric.java | 11 +- .../dubbo/metrics/model/ErrorCodeMetric.java | 1 - .../dubbo/metrics/model/MethodMetric.java | 27 +- .../apache/dubbo/metrics/model/Metric.java | 1 - .../dubbo/metrics/model/MetricsCategory.java | 1 - .../dubbo/metrics/model/MetricsSupport.java | 102 +- .../dubbo/metrics/model/ServiceKeyMetric.java | 9 +- .../dubbo/metrics/model/ThreadPoolMetric.java | 21 +- .../metrics/model/ThreadPoolRejectMetric.java | 20 +- .../model/container/AtomicLongContainer.java | 3 - .../container/LongAccumulatorContainer.java | 7 +- .../model/container/LongContainer.java | 6 +- .../metrics/model/key/CategoryOverall.java | 8 +- .../dubbo/metrics/model/key/MetricsCat.java | 9 +- .../metrics/model/key/MetricsKeyWrapper.java | 4 +- .../metrics/model/key/MetricsPlaceValue.java | 1 - .../model/sample/CounterMetricSample.java | 7 +- .../model/sample/GaugeMetricSample.java | 32 +- .../metrics/model/sample/MetricSample.java | 37 +- .../metrics/report/AbstractMetricsExport.java | 1 - .../AbstractMetricsReporterFactory.java | 1 - .../dubbo/metrics/report/MetricsExport.java | 1 - .../dubbo/metrics/report/MetricsReporter.java | 1 - .../report/MetricsReporterFactory.java | 1 - .../dubbo/metrics/service/MetricsEntity.java | 11 +- .../dubbo/metrics/service/MetricsService.java | 9 +- .../service/MetricsServiceExporter.java | 1 - .../metrics/utils/MetricsSupportUtil.java | 1 - .../dubbo/metrics/MetricsSupportTest.java | 18 +- .../dubbo/metrics/aggregate/PaneTest.java | 5 +- .../metrics/aggregate/SlidingWindowTest.java | 12 +- .../aggregate/TimeWindowAggregatorTest.java | 18 +- .../aggregate/TimeWindowCounterTest.java | 1 - .../aggregate/TimeWindowQuantileTest.java | 21 +- .../SimpleMetricsEventMulticasterTest.java | 21 +- .../metrics/model/ApplicationMetricTest.java | 35 +- .../dubbo-metrics-config-center/pom.xml | 36 +- .../config/ConfigCenterMetricsConstants.java | 1 - .../ConfigCenterMetricsCollector.java | 9 +- .../config/event/ConfigCenterEvent.java | 18 +- .../event/ConfigCenterSubDispatcher.java | 15 +- .../ConfigCenterMetricsCollectorTest.java | 16 +- dubbo-metrics/dubbo-metrics-default/pom.xml | 66 +- .../dubbo/metrics/DefaultConstants.java | 114 +- .../dubbo/metrics/MetricsGlobalRegistry.java | 13 +- .../metrics/MetricsScopeModelInitializer.java | 9 +- ...tricsReflectionTypeDescriberRegistrar.java | 3 +- .../collector/AggregateMetricsCollector.java | 177 +- .../collector/DefaultMetricsCollector.java | 73 +- .../collector/HistogramMetricsCollector.java | 38 +- .../ErrorCodeMetricsListenRegister.java | 3 +- .../collector/sample/ErrorCodeSampler.java | 16 +- .../MetricThreadPoolExhaustedListener.java | 15 +- .../sample/MetricsCountSampleConfigurer.java | 11 +- .../collector/sample/MetricsCountSampler.java | 2 - .../sample/MetricsNameCountSampler.java | 13 +- .../collector/sample/MetricsSampler.java | 1 - .../sample/SimpleMetricsCountSampler.java | 11 +- .../sample/ThreadPoolMetricsSampler.java | 102 +- .../ThreadRejectMetricsCountSampler.java | 24 +- .../metrics/event/DefaultSubDispatcher.java | 80 +- .../dubbo/metrics/event/RequestEvent.java | 47 +- .../dubbo/metrics/filter/MetricsFilter.java | 17 +- .../metrics/filter/MetricsProviderFilter.java | 7 +- .../register/HistogramMetricRegister.java | 16 +- .../metrics/register/MetricRegister.java | 5 +- .../report/AbstractMetricsReporter.java | 42 +- .../report/DefaultMetricsReporter.java | 70 +- .../report/DefaultMetricsReporterFactory.java | 1 - .../report/nop/NopMetricsReporter.java | 13 +- .../report/nop/NopMetricsReporterFactory.java | 1 - .../metrics/sample/HistogramMetricSample.java | 9 +- .../service/DefaultMetricsService.java | 7 +- .../filter/support/MetricsClusterFilter.java | 12 +- .../metrics/DefaultMetricsServiceTest.java | 21 +- .../dubbo/metrics/TestMetricsInvoker.java | 6 +- .../AggregateMetricsCollectorTest.java | 83 +- .../collector/DefaultCollectorTest.java | 130 +- .../collector/InitServiceMetricsTest.java | 50 +- .../sample/ThreadPoolMetricsSamplerTest.java | 13 +- .../metrics/filter/MetricsFilterTest.java | 39 +- .../metrics/model/MethodMetricTest.java | 19 +- .../model/sample/ErrorCodeSampleTest.java | 15 +- .../model/sample/GaugeMetricSampleTest.java | 12 +- .../model/sample/MetricSampleTest.java | 8 +- .../metrics/service/MetricsEntityTest.java | 8 +- .../filter/MetricsClusterFilterTest.java | 49 +- .../rpc/cluster/filter/MockInvocation.java | 5 +- dubbo-metrics/dubbo-metrics-event/pom.xml | 46 +- .../dubbo/metrics/MetricsConstants.java | 4 +- .../dubbo/metrics/event/MetricsEvent.java | 16 +- .../dubbo/metrics/event/MetricsEventBus.java | 2 - .../event/MetricsEventMulticaster.java | 1 - .../dubbo/metrics/event/TimeCounterEvent.java | 8 +- .../MetricsNeverHappenException.java | 1 - .../metrics/listener/MetricsListener.java | 4 - .../apache/dubbo/metrics/model/TimePair.java | 1 - .../dubbo/metrics/model/key/MetricsKey.java | 45 +- .../dubbo/metrics/model/key/MetricsLevel.java | 7 +- .../dubbo/metrics/model/key/TypeWrapper.java | 2 - dubbo-metrics/dubbo-metrics-metadata/pom.xml | 46 +- .../metadata/MetadataMetricsConstants.java | 20 +- .../collector/MetadataMetricsCollector.java | 2 - .../metrics/metadata/event/MetadataEvent.java | 26 +- .../metadata/event/MetadataSubDispatcher.java | 51 +- .../MetadataMetricsCollectorTest.java | 259 +- .../metadata/MetadataStatCompositeTest.java | 49 +- dubbo-metrics/dubbo-metrics-netty/pom.xml | 46 +- .../registry/NettyMetricsConstants.java | 17 +- .../collector/NettyMetricsCollector.java | 3 - .../metrics/registry/event/NettyEvent.java | 8 +- .../registry/event/NettySubDispatcher.java | 11 +- .../dubbo-metrics-prometheus/pom.xml | 94 +- .../NopPrometheusMetricsReporter.java | 9 +- .../prometheus/PrometheusMetricsReporter.java | 24 +- .../PrometheusMetricsReporterCmd.java | 11 +- .../PrometheusMetricsReporterFactory.java | 25 +- .../PrometheusMetricsReporterFactoryTest.java | 1 - .../PrometheusMetricsReporterTest.java | 39 +- .../PrometheusMetricsThreadPoolTest.java | 42 +- dubbo-metrics/dubbo-metrics-registry/pom.xml | 46 +- .../registry/RegistryMetricsConstants.java | 34 +- .../collector/RegistryMetricsCollector.java | 55 +- .../collector/RegistryStatComposite.java | 8 +- .../metrics/registry/event/RegistryEvent.java | 50 +- .../registry/event/RegistrySpecListener.java | 122 +- .../registry/event/RegistrySubDispatcher.java | 95 +- .../RegistryMetricsCollectorTest.java | 248 +- .../collector/RegistryMetricsSampleTest.java | 31 +- .../collector/RegistryMetricsTest.java | 29 +- .../collector/RegistryStatCompositeTest.java | 84 +- dubbo-metrics/dubbo-tracing/pom.xml | 181 +- ...ractDefaultDubboObservationConvention.java | 19 +- ...faultDubboClientObservationConvention.java | 11 +- ...faultDubboServerObservationConvention.java | 3 +- .../DubboObservationDocumentation.java | 3 - .../tracing/DubboObservationRegistry.java | 34 +- .../tracing/context/DubboClientContext.java | 5 +- .../tracing/context/DubboServerContext.java | 3 +- .../exporter/otlp/OTlpSpanExporter.java | 13 +- .../exporter/zipkin/ZipkinSpanExporter.java | 3 +- .../exporter/zipkin/ZipkinSpanHandler.java | 3 +- .../filter/ObservationReceiverFilter.java | 8 +- .../filter/ObservationSenderFilter.java | 8 +- .../dubbo/tracing/tracer/TracerProvider.java | 1 - .../tracer/brave/BravePropagatorProvider.java | 1 - .../tracing/tracer/brave/BraveProvider.java | 66 +- .../tracer/otel/OpenTelemetryProvider.java | 89 +- .../tracing/utils/ObservationConstants.java | 1 - .../dubbo/tracing/utils/PropagationType.java | 2 - ...tDubboClientObservationConventionTest.java | 9 +- ...tDubboServerObservationConventionTest.java | 6 +- .../apache/dubbo/tracing/MockInvocation.java | 9 +- .../exporter/otlp/OTlpSpanExporterTest.java | 6 +- .../zipkin/ZipkinSpanExporterTest.java | 7 +- .../zipkin/ZipkinSpanHandlerTest.java | 6 +- .../filter/AbstractObservationFilterTest.java | 4 +- .../filter/ObservationReceiverFilterTest.java | 51 +- .../filter/ObservationSenderFilterTest.java | 31 +- .../tracer/PropagatorProviderFactoryTest.java | 2 +- .../brave/BravePropagatorProviderTest.java | 2 +- .../tracer/brave/BraveProviderTest.java | 21 +- .../otel/OTelPropagatorProviderTest.java | 3 +- .../otel/OpenTelemetryProviderTest.java | 20 +- .../utils/ObservationConventionUtils.java | 15 +- .../utils/ObservationSupportUtilTest.java | 1 - .../tracing/utils/PropagationTypeTest.java | 2 +- dubbo-metrics/pom.xml | 70 +- dubbo-monitor/dubbo-monitor-api/pom.xml | 43 +- .../apache/dubbo/monitor/MetricsService.java | 1 - .../org/apache/dubbo/monitor/Monitor.java | 4 +- .../apache/dubbo/monitor/MonitorFactory.java | 1 - .../apache/dubbo/monitor/MonitorService.java | 2 - dubbo-monitor/dubbo-monitor-common/pom.xml | 53 +- .../support/AbstractMonitorFactory.java | 20 +- .../support/MetricsServiceDetector.java | 1 - .../monitor/support/MonitorClusterFilter.java | 3 +- .../dubbo/monitor/support/MonitorFilter.java | 67 +- .../support/MonitorServiceDetector.java | 1 - .../support/AbstractMonitorFactoryTest.java | 14 +- .../monitor/support/MonitorFilterTest.java | 54 +- dubbo-monitor/dubbo-monitor-default/pom.xml | 138 +- .../dubbo/monitor/dubbo/DubboMonitor.java | 126 +- .../monitor/dubbo/DubboMonitorFactory.java | 4 +- .../dubbo/monitor/dubbo/MetricsFilter.java | 102 +- .../dubbo/monitor/dubbo/Statistics.java | 1 - .../dubbo/monitor/dubbo/StatisticsItem.java | 16 +- .../dubbo/DubboMonitorFactoryTest.java | 3 +- .../dubbo/monitor/dubbo/DubboMonitorTest.java | 116 +- .../monitor/dubbo/MetricsFilterTest.java | 240 +- .../monitor/dubbo/MockMonitorService.java | 1 - .../dubbo/monitor/dubbo/StatisticsTest.java | 2 +- .../monitor/dubbo/service/DemoService.java | 2 - dubbo-monitor/pom.xml | 55 +- dubbo-plugin/dubbo-auth/pom.xml | 49 +- .../dubbo/auth/AccessKeyAuthenticator.java | 17 +- .../java/org/apache/dubbo/auth/Constants.java | 1 - .../dubbo/auth/DefaultAccessKeyStorage.java | 1 - .../exception/AccessKeyNotFoundException.java | 6 +- .../exception/RpcAuthenticationException.java | 4 +- .../dubbo/auth/filter/ConsumerSignFilter.java | 3 +- .../dubbo/auth/filter/ProviderAuthFilter.java | 5 +- .../dubbo/auth/model/AccessKeyPair.java | 15 +- .../dubbo/auth/spi/AccessKeyStorage.java | 1 - .../apache/dubbo/auth/spi/Authenticator.java | 2 - .../dubbo/auth/utils/SignatureUtils.java | 10 +- .../auth/AccessKeyAuthenticatorTest.java | 16 +- .../auth/DefaultAccessKeyStorageTest.java | 3 +- .../auth/filter/ConsumerSignFilterTest.java | 3 +- .../auth/filter/ProviderAuthFilterTest.java | 27 +- .../dubbo/auth/utils/SignatureUtilsTest.java | 8 +- dubbo-plugin/dubbo-compiler/pom.xml | 157 +- .../apache/dubbo/gen/AbstractGenerator.java | 175 +- .../dubbo/gen/DubboGeneratorPlugin.java | 23 +- .../dubbo/gen/dubbo/Dubbo3Generator.java | 5 +- .../dubbo/gen/dubbo/DubboGenerator.java | 1 - .../dubbo/gen/grpc/DubboGrpcGenerator.java | 1 - .../reactive/ReactorDubboGrpcGenerator.java | 2 - .../dubbo/gen/tri/Dubbo3TripleGenerator.java | 1 - .../ReactorDubbo3TripleGenerator.java | 1 - dubbo-plugin/dubbo-filter-cache/pom.xml | 63 +- .../java/org/apache/dubbo/cache/Cache.java | 1 - .../org/apache/dubbo/cache/CacheFactory.java | 1 - .../dubbo/cache/filter/CacheFilter.java | 17 +- .../cache/support/AbstractCacheFactory.java | 1 - .../cache/support/expiring/ExpiringCache.java | 2 - .../expiring/ExpiringCacheFactory.java | 2 - .../cache/support/expiring/ExpiringMap.java | 27 +- .../dubbo/cache/support/jcache/JCache.java | 22 +- .../cache/support/jcache/JCacheFactory.java | 1 - .../dubbo/cache/support/lfu/LfuCache.java | 3 +- .../cache/support/lfu/LfuCacheFactory.java | 1 - .../dubbo/cache/support/lru/LruCache.java | 1 - .../cache/support/lru/LruCacheFactory.java | 1 - .../support/threadlocal/ThreadLocalCache.java | 1 - .../threadlocal/ThreadLocalCacheFactory.java | 1 - .../dubbo/cache/filter/CacheFilterTest.java | 28 +- .../support/AbstractCacheFactoryTest.java | 2 +- .../expiring/ExpiringCacheFactoryTest.java | 6 +- .../support/lru/LruCacheFactoryTest.java | 4 +- .../ThreadLocalCacheFactoryTest.java | 2 +- dubbo-plugin/dubbo-filter-validation/pom.xml | 123 +- .../apache/dubbo/validation/Validation.java | 1 - .../apache/dubbo/validation/Validator.java | 1 - .../validation/filter/ValidationFilter.java | 13 +- .../support/AbstractValidation.java | 1 - .../support/jvalidation/JValidation.java | 1 - .../support/jvalidation/JValidationNew.java | 1 - .../support/jvalidation/JValidator.java | 73 +- .../support/jvalidation/JValidatorNew.java | 71 +- .../filter/ValidationFilterTest.java | 25 +- .../support/jvalidation/JValidationTest.java | 11 +- .../support/jvalidation/JValidatorTest.java | 89 +- .../mock/JValidatorTestTarget.java | 16 +- .../jvalidation/mock/ValidationParameter.java | 3 +- dubbo-plugin/dubbo-native/pom.xml | 37 +- .../dubbo/aot/api/ConditionalDescriber.java | 1 - .../apache/dubbo/aot/api/ExecutableMode.java | 49 +- .../dubbo/aot/api/JdkProxyDescriber.java | 4 +- .../apache/dubbo/aot/api/MemberCategory.java | 178 +- .../aot/api/ResourceBundleDescriber.java | 1 - .../aot/api/ResourcePatternDescriber.java | 9 +- .../apache/dubbo/aot/api/TypeDescriber.java | 11 +- .../dubbo/aot/generate/AotProcessor.java | 59 +- .../aot/generate/ClassSourceScanner.java | 56 +- .../aot/generate/ExecutableDescriber.java | 10 +- .../apache/dubbo/aot/generate/JarScanner.java | 7 +- .../aot/generate/NativeClassSourceWriter.java | 39 +- .../generate/NativeConfigurationWriter.java | 17 +- .../ProxyConfigMetadataRepository.java | 5 +- .../dubbo/aot/generate/ProxyConfigWriter.java | 3 +- .../ReflectConfigMetadataRepository.java | 24 +- .../aot/generate/ReflectionConfigWriter.java | 106 +- .../ResourceConfigMetadataRepository.java | 3 +- .../aot/generate/ResourceConfigWriter.java | 21 +- .../dubbo/aot/generate/ResourceScanner.java | 17 +- .../ResourcePatternDescriberTest.java | 8 +- dubbo-plugin/dubbo-plugin-access-log/pom.xml | 46 +- .../dubbo/rpc/filter/AccessLogFilter.java | 61 +- .../dubbo/rpc/support/AccessLogData.java | 37 +- .../dubbo/rpc/filter/AccessLogFilterTest.java | 14 +- .../dubbo/rpc/support/MockInvocation.java | 9 +- .../apache/dubbo/rpc/support/MyInvoker.java | 1 - .../dubbo-plugin-classloader-filter/pom.xml | 46 +- .../support/ConsumerClassLoaderFilter.java | 4 +- .../rpc/filter/ClassLoaderFilterTest.java | 7 +- .../apache/dubbo/rpc/support/MyInvoker.java | 1 - .../dubbo-plugin-cluster-mergeable/pom.xml | 36 +- ...MergeableClusterScopeModelInitializer.java | 6 +- .../cluster/merger/BooleanArrayMerger.java | 2 - .../rpc/cluster/merger/ByteArrayMerger.java | 2 - .../rpc/cluster/merger/CharArrayMerger.java | 1 - .../rpc/cluster/merger/DoubleArrayMerger.java | 4 +- .../rpc/cluster/merger/FloatArrayMerger.java | 1 - .../rpc/cluster/merger/IntArrayMerger.java | 5 +- .../dubbo/rpc/cluster/merger/ListMerger.java | 6 +- .../rpc/cluster/merger/LongArrayMerger.java | 4 +- .../dubbo/rpc/cluster/merger/MapMerger.java | 1 - .../rpc/cluster/merger/MergerFactory.java | 13 +- .../rpc/cluster/merger/ShortArrayMerger.java | 1 - .../rpc/cluster/support/MergeableCluster.java | 1 - .../support/MergeableClusterInvoker.java | 35 +- .../rpc/cluster/merger/DoubleSumMerger.java | 6 +- .../rpc/cluster/merger/FloatSumMerger.java | 3 +- .../rpc/cluster/merger/IntSumMerger.java | 6 +- .../rpc/cluster/merger/LongSumMerger.java | 6 +- .../rpc/cluster/merger/ResultMergerTest.java | 136 +- .../dubbo/rpc/cluster/support/Menu.java | 4 +- .../rpc/cluster/support/MenuService.java | 1 - .../support/MergeableClusterInvokerTest.java | 199 +- dubbo-plugin/dubbo-plugin-context/pom.xml | 46 +- .../filter/support/ConsumerContextFilter.java | 34 +- .../dubbo/rpc/filter/ContextFilter.java | 29 +- .../dubbo/rpc/filter/ContextFilterTest.java | 4 +- .../dubbo/rpc/support/MockInvocation.java | 9 +- .../apache/dubbo/rpc/support/MyInvoker.java | 1 - .../dubbo-plugin-generic-invoke/pom.xml | 46 +- .../dubbo/rpc/filter/GenericFilter.java | 203 +- .../dubbo/rpc/filter/GenericImplFilter.java | 73 +- .../dubbo/rpc/filter/GenericFilterTest.java | 53 +- .../rpc/filter/GenericImplFilterTest.java | 72 +- .../apache/dubbo/rpc/support/DemoService.java | 1 - .../dubbo-plugin-loadbalance-adaptive/pom.xml | 46 +- .../org/apache/dubbo/rpc/AdaptiveMetrics.java | 30 +- .../rpc/AdaptiveScopeModelInitializer.java | 6 +- .../loadbalance/AdaptiveLoadBalance.java | 48 +- .../rpc/filter/AdaptiveLoadBalanceFilter.java | 37 +- .../loadbalance/AdaptiveLoadBalanceTest.java | 52 +- .../loadbalance/LoadBalanceBaseTest.java | 31 +- dubbo-plugin/dubbo-plugin-loom/pom.xml | 68 +- .../support/loom/VirtualThreadPool.java | 7 +- .../support/loom/VirtualThreadPoolTest.java | 15 +- dubbo-plugin/dubbo-plugin-mock/pom.xml | 46 +- .../router/mock/MockInvokersSelector.java | 15 +- .../router/mock/MockStateRouterFactory.java | 1 - .../support/wrapper/MockClusterInvoker.java | 56 +- .../support/wrapper/MockClusterWrapper.java | 3 +- .../rpc/support/MockConfigPostProcessor.java | 15 +- .../apache/dubbo/rpc/support/MockInvoker.java | 51 +- .../dubbo/rpc/support/MockProtocol.java | 2 +- .../router/mock/MockInvokersSelectorTest.java | 27 +- .../wrapper/MockClusterInvokerTest.java | 301 +- .../wrapper/MockProviderRpcExceptionTest.java | 38 +- .../support/wrapper/MyMockException.java | 2 - .../dubbo/rpc/support/DemoServiceAMock.java | 3 +- .../apache/dubbo/rpc/support/Greeting.java | 2 +- .../dubbo/rpc/support/GreetingMock1.java | 5 +- .../dubbo/rpc/support/GreetingMock2.java | 5 +- .../MockAbstractClusterInvokerTest.java | 43 +- .../support/MockConfigPostProcessorTest.java | 6 +- .../dubbo/rpc/support/MockInvokerTest.java | 78 +- .../dubbo-plugin-proxy-bytebuddy/pom.xml | 44 +- .../proxy/bytebuddy/ByteBuddyInterceptor.java | 10 +- .../rpc/proxy/bytebuddy/ByteBuddyProxy.java | 34 +- .../bytebuddy/ByteBuddyProxyInvoker.java | 8 +- .../dubbo/rpc/proxy/AbstractProxyTest.java | 30 +- .../bytebuddy/ByteBuddyInterceptorTest.java | 12 +- .../bytebuddy/ByteBuddyProxyFactoryTest.java | 1 - .../bytebuddy/ByteBuddyProxyInvokerTest.java | 11 +- .../proxy/bytebuddy/ByteBuddyProxyTest.java | 7 +- .../dubbo/rpc/support/DemoServiceImpl.java | 1 - .../apache/dubbo/rpc/support/MyInvoker.java | 1 - dubbo-plugin/dubbo-plugin-qos-trace/pom.xml | 56 +- .../dubbo/qos/legacy/ChangeTelnetHandler.java | 5 +- .../dubbo/qos/legacy/TraceTelnetHandler.java | 9 +- .../protocol/dubbo/filter/TraceFilter.java | 18 +- .../qos/legacy/ChangeTelnetHandlerTest.java | 26 +- .../dubbo/qos/legacy/ProtocolUtils.java | 6 +- .../qos/legacy/TraceTelnetHandlerTest.java | 14 +- .../dubbo/qos/legacy/channel/MockChannel.java | 4 +- .../dubbo/qos/legacy/service/DemoService.java | 1 - .../protocol/dubbo/filter/MockChannel.java | 15 +- .../dubbo/filter/TraceFilterTest.java | 16 +- .../dubbo-plugin-router-condition/pom.xml | 36 +- .../condition/ConditionStateRouter.java | 102 +- .../config/ListenableStateRouter.java | 36 +- .../config/ProviderAppStateRouter.java | 9 +- .../config/ServiceStateRouterFactory.java | 1 - .../config/model/ConditionRouterRule.java | 7 +- .../config/model/ConditionRuleParser.java | 5 +- .../matcher/AbstractConditionMatcher.java | 27 +- .../argument/ArgumentConditionMatcher.java | 14 +- .../AttachmentConditionMatcher.java | 18 +- .../param/UrlParamConditionMatcher.java | 1 - .../pattern/range/RangeValuePattern.java | 13 +- .../cluster/directory/MockDirInvocation.java | 25 +- .../directory/StaticDirectoryTest.java | 26 +- .../router/ConfigConditionRouterTest.java | 82 +- .../dubbo/rpc/cluster/router/MockInvoker.java | 6 +- .../condition/ConditionStateRouterTest.java | 602 +- .../ProviderAppConditionStateRouterTest.java | 43 +- dubbo-plugin/dubbo-plugin-router-mesh/pom.xml | 36 +- .../mesh/MeshScopeModelInitializer.java | 7 +- .../mesh/route/MeshAppRuleListener.java | 42 +- .../router/mesh/route/MeshEnvListener.java | 1 - .../router/mesh/route/MeshRuleCache.java | 37 +- .../router/mesh/route/MeshRuleManager.java | 18 +- .../router/mesh/route/MeshRuleRouter.java | 62 +- .../route/StandardMeshRuleRouterFactory.java | 2 - .../cluster/router/mesh/rule/BaseRule.java | 11 +- .../router/mesh/rule/VsDestinationGroup.java | 2 - .../destination/ConnectionPoolSettings.java | 5 +- .../rule/destination/DestinationRule.java | 7 +- .../rule/destination/DestinationRuleSpec.java | 11 +- .../router/mesh/rule/destination/Subset.java | 7 +- .../mesh/rule/destination/TCPSettings.java | 2 - .../mesh/rule/destination/TcpKeepalive.java | 3 - .../mesh/rule/destination/TrafficPolicy.java | 6 +- .../loadbalance/ConsistentHashLB.java | 5 +- .../loadbalance/LoadBalancerSettings.java | 7 +- .../destination/loadbalance/SimpleLB.java | 2 - .../virtualservice/DubboMatchRequest.java | 18 +- .../mesh/rule/virtualservice/DubboRoute.java | 8 +- .../rule/virtualservice/DubboRouteDetail.java | 8 +- .../virtualservice/VirtualServiceRule.java | 7 +- .../virtualservice/VirtualServiceSpec.java | 7 +- .../destination/DubboDestination.java | 3 - .../destination/DubboRouteDestination.java | 2 - .../match/DubboAttachmentMatch.java | 4 +- .../router/mesh/util/MeshRuleDispatcher.java | 11 +- .../router/mesh/util/MeshRuleListener.java | 2 - .../mesh/route/MeshAppRuleListenerTest.java | 226 +- .../router/mesh/route/MeshRuleCacheTest.java | 17 +- .../mesh/route/MeshRuleManagerTest.java | 121 +- .../router/mesh/route/MeshRuleRouterTest.java | 365 +- .../StandardMeshRuleRouterFactoryTest.java | 6 +- .../router/mesh/rule/DestinationRuleTest.java | 77 +- .../mesh/rule/VirtualServiceRuleTest.java | 41 +- .../virtualservice/DubboMatchRequestTest.java | 24 +- .../match/DubboAttachmentMatchTest.java | 29 +- .../mesh/util/MeshRuleDispatcherTest.java | 61 +- .../dubbo-plugin-router-script/pom.xml | 36 +- .../router/file/FileStateRouterFactory.java | 5 +- .../router/script/ScriptStateRouter.java | 55 +- .../script/ScriptStateRouterFactory.java | 1 - .../script/config/AppScriptStateRouter.java | 53 +- .../script/config/model/ScriptRule.java | 4 +- .../dubbo/rpc/cluster/router/MockInvoker.java | 6 +- .../router/file/FileRouterEngineTest.java | 40 +- .../router/script/ScriptStateRouterTest.java | 83 +- .../config/AppScriptStateRouterTest.java | 53 +- dubbo-plugin/dubbo-plugin-router-tag/pom.xml | 36 +- .../cluster/router/tag/TagStateRouter.java | 80 +- .../rpc/cluster/router/tag/model/Tag.java | 34 +- .../router/tag/model/TagRouterRule.java | 67 +- .../router/tag/model/TagRuleParser.java | 4 +- .../dubbo/rpc/cluster/router/MockInvoker.java | 6 +- .../router/tag/TagStateRouterTest.java | 178 +- dubbo-plugin/dubbo-plugin-token/pom.xml | 46 +- .../apache/dubbo/rpc/filter/TokenFilter.java | 12 +- .../dubbo/rpc/filter/TokenHeaderFilter.java | 10 +- .../dubbo/rpc/filter/TokenFilterTest.java | 7 +- dubbo-plugin/dubbo-plugin-tps/pom.xml | 46 +- .../dubbo/rpc/filter/ActiveLimitFilter.java | 13 +- .../dubbo/rpc/filter/ExecuteLimitFilter.java | 19 +- .../dubbo/rpc/filter/TpsLimitFilter.java | 10 +- .../rpc/filter/tps/DefaultTPSLimiter.java | 6 +- .../apache/dubbo/rpc/filter/tps/StatItem.java | 8 +- .../dubbo/rpc/filter/tps/TPSLimiter.java | 1 - .../rpc/filter/ActiveLimitFilterTest.java | 22 +- .../rpc/filter/ExecuteLimitFilterTest.java | 15 +- .../rpc/filter/tps/DefaultTPSLimiterTest.java | 17 +- .../dubbo/rpc/filter/tps/StatItemTest.java | 13 +- .../rpc/filter/tps/TpsLimitFilterTest.java | 3 +- .../dubbo/rpc/support/MockInvocation.java | 9 +- .../apache/dubbo/rpc/support/MyInvoker.java | 1 - .../rpc/support/RuntimeExceptionInvoker.java | 1 - dubbo-plugin/dubbo-qos-api/pom.xml | 51 +- .../java/org/apache/dubbo/qos/api/Cmd.java | 1 - .../apache/dubbo/qos/api/CommandContext.java | 29 +- .../apache/dubbo/qos/api/PermissionLevel.java | 14 +- .../dubbo/qos/api/QosConfiguration.java | 35 +- dubbo-plugin/dubbo-qos/pom.xml | 133 +- .../dubbo/qos/QosScopeModelInitializer.java | 8 +- .../QosReflectionTypeDescriberRegistrar.java | 4 +- .../qos/command/DefaultCommandExecutor.java | 53 +- .../command/decoder/HttpCommandDecoder.java | 25 +- .../command/decoder/TelnetCommandDecoder.java | 4 +- .../dubbo/qos/command/impl/BaseOffline.java | 21 +- .../dubbo/qos/command/impl/BaseOnline.java | 10 +- .../dubbo/qos/command/impl/ChangeTelnet.java | 17 +- .../dubbo/qos/command/impl/CountTelnet.java | 79 +- .../impl/DefaultMetricsReporterCmd.java | 5 +- .../command/impl/DisableDetailProfiler.java | 5 +- .../command/impl/DisableRouterSnapshot.java | 12 +- .../command/impl/DisableSimpleProfiler.java | 5 +- .../command/impl/EnableDetailProfiler.java | 5 +- .../command/impl/EnableRouterSnapshot.java | 12 +- .../command/impl/EnableSimpleProfiler.java | 5 +- .../dubbo/qos/command/impl/GetAddress.java | 203 +- .../dubbo/qos/command/impl/GetConfig.java | 89 +- .../impl/GetEnabledRouterSnapshot.java | 7 +- .../command/impl/GetRecentRouterSnapshot.java | 10 +- .../qos/command/impl/GetRouterSnapshot.java | 36 +- .../qos/command/impl/GracefulShutdown.java | 11 +- .../apache/dubbo/qos/command/impl/Help.java | 23 +- .../dubbo/qos/command/impl/InvokeTelnet.java | 61 +- .../apache/dubbo/qos/command/impl/Live.java | 26 +- .../dubbo/qos/command/impl/LoggerInfo.java | 15 +- .../org/apache/dubbo/qos/command/impl/Ls.java | 39 +- .../dubbo/qos/command/impl/Offline.java | 8 +- .../dubbo/qos/command/impl/OfflineApp.java | 8 +- .../qos/command/impl/OfflineInterface.java | 8 +- .../apache/dubbo/qos/command/impl/Online.java | 8 +- .../dubbo/qos/command/impl/OnlineApp.java | 9 +- .../qos/command/impl/OnlineInterface.java | 8 +- .../dubbo/qos/command/impl/PortTelnet.java | 13 +- .../qos/command/impl/PublishMetadata.java | 36 +- .../dubbo/qos/command/impl/PwdTelnet.java | 12 +- .../apache/dubbo/qos/command/impl/Quit.java | 2 +- .../apache/dubbo/qos/command/impl/Ready.java | 25 +- .../dubbo/qos/command/impl/SelectTelnet.java | 24 +- .../command/impl/SerializeCheckStatus.java | 33 +- .../command/impl/SerializeWarnedClasses.java | 22 +- .../command/impl/SetProfilerWarnPercent.java | 13 +- .../qos/command/impl/ShutdownTelnet.java | 13 +- .../dubbo/qos/command/impl/Startup.java | 24 +- .../qos/command/impl/SwitchLogLevel.java | 9 +- .../dubbo/qos/command/impl/SwitchLogger.java | 9 +- .../dubbo/qos/command/impl/Version.java | 10 +- .../dubbo/qos/command/util/CommandHelper.java | 13 +- .../qos/command/util/SerializeCheckUtils.java | 6 +- .../qos/command/util/ServiceCheckUtils.java | 31 +- .../apache/dubbo/qos/common/QosConstants.java | 1 - .../dubbo/qos/legacy/LogTelnetHandler.java | 18 +- ...faultAnonymousAccessPermissionChecker.java | 30 +- .../probe/impl/DeployerReadinessProbe.java | 1 - .../probe/impl/ProviderReadinessProbe.java | 6 +- .../qos/protocol/QosProtocolWrapper.java | 9 +- .../apache/dubbo/qos/server/DubboLogo.java | 8 +- .../org/apache/dubbo/qos/server/Server.java | 23 +- .../handler/ForeignHostPermitHandler.java | 14 +- .../server/handler/HttpProcessHandler.java | 28 +- .../qos/server/handler/QosProcessHandler.java | 24 +- .../handler/TelnetIdleEventHandler.java | 1 - .../server/handler/TelnetProcessHandler.java | 17 +- .../apache/dubbo/qos/textui/TComponent.java | 1 - .../java/org/apache/dubbo/qos/textui/TKv.java | 18 +- .../org/apache/dubbo/qos/textui/TLadder.java | 10 +- .../org/apache/dubbo/qos/textui/TTable.java | 55 +- .../org/apache/dubbo/qos/textui/TTree.java | 24 +- .../command/CommandContextFactoryTest.java | 6 +- .../dubbo/qos/command/CommandContextTest.java | 10 +- .../command/DefaultCommandExecutorTest.java | 18 +- .../dubbo/qos/command/GreetingCommand.java | 13 +- .../decoder/HttpCommandDecoderTest.java | 4 +- .../qos/command/impl/ChangeTelnetTest.java | 33 +- .../qos/command/impl/CountTelnetTest.java | 23 +- .../dubbo/qos/command/impl/GetConfigTest.java | 24 +- .../dubbo/qos/command/impl/HelpTest.java | 2 +- .../qos/command/impl/InvokeTelnetTest.java | 92 +- .../apache/dubbo/qos/command/impl/LsTest.java | 49 +- .../dubbo/qos/command/impl/OfflineTest.java | 27 +- .../dubbo/qos/command/impl/OnlineTest.java | 27 +- .../qos/command/impl/PortTelnetTest.java | 13 +- .../qos/command/impl/PublishMetadataTest.java | 17 +- .../dubbo/qos/command/impl/PwdTelnetTest.java | 9 +- .../dubbo/qos/command/impl/ReadyTest.java | 19 +- .../qos/command/impl/SelectTelnetTest.java | 42 +- .../impl/SerializeCheckStatusTest.java | 48 +- .../impl/SerializeWarnedClassesTest.java | 25 +- .../qos/command/impl/ShutdownTelnetTest.java | 2 +- .../dubbo/qos/command/impl/StartupTest.java | 15 +- .../impl/channel/MockNettyChannel.java | 23 +- .../qos/command/util/CommandHelperTest.java | 4 +- .../command/util/ServiceCheckUtilsTest.java | 44 +- .../qos/legacy/LogTelnetHandlerTest.java | 3 +- .../qos/legacy/service/CustomArgument.java | 4 +- .../dubbo/qos/legacy/service/DemoService.java | 2 - .../qos/legacy/service/DemoServiceImpl.java | 15 +- .../apache/dubbo/qos/legacy/service/Man.java | 1 - .../qos/legacy/service/NonSerialized.java | 4 +- .../apache/dubbo/qos/legacy/service/Type.java | 4 +- .../legacy/service/generic/DemoException.java | 1 - .../legacy/service/generic/DemoService.java | 2 - .../service/generic/DemoServiceImpl.java | 2 - .../service/generic/GenericServiceTest.java | 66 +- .../qos/legacy/service/generic/User.java | 4 +- ...tAnonymousAccessPermissionCheckerTest.java | 8 +- .../qos/protocol/QosProtocolWrapperTest.java | 4 +- .../handler/ForeignHostPermitHandlerTest.java | 54 +- .../handler/HttpProcessHandlerTest.java | 23 +- .../server/handler/QosProcessHandlerTest.java | 34 +- .../handler/TelnetProcessHandlerTest.java | 26 +- .../org/apache/dubbo/qos/textui/TKvTest.java | 10 +- .../apache/dubbo/qos/textui/TLadderTest.java | 12 +- .../apache/dubbo/qos/textui/TTableTest.java | 28 +- .../apache/dubbo/qos/textui/TTreeTest.java | 17 +- dubbo-plugin/dubbo-reactive/pom.xml | 59 +- .../AbstractTripleReactorPublisher.java | 14 +- .../AbstractTripleReactorSubscriber.java | 6 +- .../ClientTripleReactorPublisher.java | 4 +- .../ClientTripleReactorSubscriber.java | 1 - .../ServerTripleReactorPublisher.java | 1 - .../ServerTripleReactorSubscriber.java | 1 - .../reactive/calls/ReactorClientCalls.java | 91 +- .../reactive/calls/ReactorServerCalls.java | 80 +- .../handler/ManyToManyMethodHandler.java | 4 +- .../handler/ManyToOneMethodHandler.java | 6 +- .../handler/OneToManyMethodHandler.java | 6 +- .../handler/OneToOneMethodHandler.java | 4 +- .../dubbo/reactive/CreateObserverAdapter.java | 15 +- .../reactive/ManyToManyMethodHandlerTest.java | 13 +- .../reactive/ManyToOneMethodHandlerTest.java | 15 +- .../reactive/OneToManyMethodHandlerTest.java | 35 +- .../reactive/OneToOneMethodHandlerTest.java | 11 +- dubbo-plugin/dubbo-security/pom.xml | 218 +- .../dubbo/security/cert/CertConfig.java | 8 +- .../security/cert/CertDeployerListener.java | 21 +- .../apache/dubbo/security/cert/CertPair.java | 5 +- .../cert/CertScopeModelInitializer.java | 8 +- .../dubbo/security/cert/DubboCertManager.java | 154 +- .../security/cert/DubboCertProvider.java | 16 +- .../cert/CertDeployerListenerTest.java | 77 +- .../security/cert/DubboCertManagerTest.java | 81 +- .../security/cert/DubboCertProviderTest.java | 34 +- dubbo-plugin/dubbo-spring-security/pom.xml | 118 +- ...thenticationExceptionTranslatorFilter.java | 22 +- ...textHolderAuthenticationPrepareFilter.java | 13 +- ...extHolderAuthenticationResolverFilter.java | 14 +- ...olderParametersSelectedTransferFilter.java | 7 +- .../security/jackson/ObjectMapperCodec.java | 39 +- .../jackson/ObjectMapperCodecCustomer.java | 3 +- .../model/SecurityScopeModelInitializer.java | 28 +- .../spring/security/utils/SecurityNames.java | 10 +- .../jackson/ObjectMapperCodecTest.java | 47 +- dubbo-plugin/pom.xml | 143 +- dubbo-registry/dubbo-registry-api/pom.xml | 206 +- .../org/apache/dubbo/registry/Constants.java | 5 +- .../registry/ListenerRegistryWrapper.java | 7 +- .../apache/dubbo/registry/NotifyListener.java | 4 +- .../dubbo/registry/RegistryFactory.java | 1 - .../registry/RegistryFactoryWrapper.java | 7 +- .../dubbo/registry/RegistryNotifier.java | 14 +- .../RegistryScopeModelInitializer.java | 4 +- .../dubbo/registry/RegistryService.java | 1 - .../registry/RegistryServiceListener.java | 18 +- ...istryReflectionTypeDescriberRegistrar.java | 4 +- .../client/AbstractServiceDiscovery.java | 126 +- .../AbstractServiceDiscoveryFactory.java | 1 - .../client/DefaultServiceInstance.java | 36 +- .../client/FileSystemServiceDiscovery.java | 214 - .../registry/client/InstanceAddressURL.java | 36 +- .../registry/client/NopServiceDiscovery.java | 12 +- .../client/OverrideInstanceAddressURL.java | 22 +- .../ReflectionBasedServiceDiscovery.java | 131 +- .../client/RegistryClusterIdentifier.java | 4 +- .../registry/client/ServiceDiscovery.java | 13 +- .../client/ServiceDiscoveryFactory.java | 3 +- .../client/ServiceDiscoveryRegistry.java | 81 +- .../ServiceDiscoveryRegistryDirectory.java | 308 +- .../ServiceDiscoveryRegistryFactory.java | 1 - .../registry/client/ServiceInstance.java | 1 - .../RetryServiceInstancesChangedEvent.java | 2 +- .../event/ServiceInstancesChangedEvent.java | 2 - .../ServiceInstancesChangedListener.java | 167 +- .../metadata/MetadataServiceDelegation.java | 40 +- .../metadata/MetadataServiceNameMapping.java | 52 +- .../client/metadata/MetadataUtils.java | 77 +- .../ProtocolPortsMetadataCustomizer.java | 15 +- .../ServiceInstanceHostPortCustomizer.java | 19 +- .../ServiceInstanceMetadataCustomizer.java | 3 +- .../ServiceInstanceMetadataUtils.java | 35 +- ...ServiceInstanceNotificationCustomizer.java | 41 +- .../StandardMetadataServiceURLBuilder.java | 54 +- .../DefaultMigrationAddressComparator.java | 14 +- .../client/migration/MigrationInvoker.java | 110 +- .../migration/MigrationRuleHandler.java | 31 +- .../migration/MigrationRuleListener.java | 90 +- .../ServiceDiscoveryMigrationInvoker.java | 14 +- .../client/migration/model/MigrationRule.java | 56 +- .../migration/model/SubMigrationRule.java | 2 +- .../AbstractConfiguratorListener.java | 25 +- .../integration/DynamicDirectory.java | 68 +- .../registry/integration/ExporterFactory.java | 15 +- .../InterfaceCompatibleRegistryProtocol.java | 14 +- .../integration/ReferenceCountExporter.java | 8 +- .../integration/RegistryDirectory.java | 249 +- .../integration/RegistryProtocol.java | 392 +- .../registry/retry/AbstractRetryTask.java | 16 +- .../registry/retry/FailedRegisteredTask.java | 1 - .../registry/retry/FailedSubscribedTask.java | 1 - .../retry/FailedUnregisteredTask.java | 1 - .../retry/FailedUnsubscribedTask.java | 1 - .../status/RegistryStatusChecker.java | 1 - .../registry/support/AbstractRegistry.java | 141 +- .../support/AbstractRegistryFactory.java | 25 +- .../support/CacheableFailbackRegistry.java | 97 +- .../support/DefaultProviderFirstParams.java | 9 +- .../registry/support/FailbackRegistry.java | 94 +- .../registry/support/RegistryManager.java | 42 +- .../CacheableFailbackRegistryTest.java | 19 +- .../registry/ListenerRegistryWrapperTest.java | 21 +- .../registry/MockCacheableRegistryImpl.java | 8 +- .../org/apache/dubbo/registry/MockLogger.java | 76 +- .../registry/PerformanceRegistryTest.java | 25 +- .../dubbo/registry/PerformanceUtils.java | 12 +- .../registry/RegistryFactoryWrapperTest.java | 8 +- .../registry/RegistryServiceListener1.java | 1 - .../registry/RegistryServiceListener2.java | 1 - .../dubbo/registry/SimpleRegistryFactory.java | 2 +- .../org/apache/dubbo/registry/ZKTools.java | 231 +- .../AbstractServiceDiscoveryFactoryTest.java | 8 +- .../client/DefaultServiceInstanceTest.java | 12 +- .../FileSystemServiceDiscoveryTest.java | 57 - .../client/InstanceAddressURLTest.java | 80 +- .../client/ServiceDiscoveryCacheTest.java | 35 +- .../client/ServiceDiscoveryRegistryTest.java | 78 +- .../registry/client/ServiceDiscoveryTest.java | 247 - .../ServiceInstancesChangedListenerTest.java | 97 +- ...hangedListenerWithoutEmptyProtectTest.java | 94 +- ...efaultServiceInstanceDeserializerTest.java | 58 - .../MetadataServiceNameMappingTest.java | 38 +- .../MetadataServiceURLBuilderTest.java | 16 +- .../ProtocolPortsMetadataCustomizerTest.java | 19 +- ...ServiceInstanceHostPortCustomizerTest.java | 11 +- ...ServiceInstanceMetadataCustomizerTest.java | 23 +- .../ServiceInstanceMetadataUtilsTest.java | 194 - ...ingCloudMetadataServiceURLBuilderTest.java | 8 +- ...StandardMetadataServiceURLBuilderTest.java | 14 +- .../store/CustomizedParamsFilter.java | 4 +- .../metadata/store/ExcludedParamsFilter.java | 2 +- .../metadata/store/ExcludedParamsFilter2.java | 2 +- .../store/InMemoryMetadataServiceTest.java | 216 - .../metadata/store/MetaCacheManagerTest.java | 34 +- ...DefaultMigrationAddressComparatorTest.java | 8 +- .../migration/MigrationInvokerTest.java | 26 +- .../migration/MigrationRuleHandlerTest.java | 9 +- .../migration/MigrationRuleListenerTest.java | 135 +- .../migration/model/MigrationRuleTest.java | 57 +- .../client/support/MockServiceDiscovery.java | 20 +- .../CountRegistryProtocolListener.java | 10 +- .../registry/integration/DemoService.java | 4 +- .../integration/DynamicDirectoryTest.java | 80 +- .../integration/RegistryProtocolTest.java | 207 +- .../support/AbstractRegistryFactoryTest.java | 56 +- .../support/AbstractRegistryTest.java | 47 +- .../support/FailbackRegistryTest.java | 51 +- .../dubbo-registry-multicast/pom.xml | 45 +- .../registry/multicast/MulticastRegistry.java | 94 +- .../multicast/MulticastRegistryFactory.java | 1 - .../multicast/MulticastServiceDiscovery.java | 20 +- .../multicast/MulticastRegistryTest.java | 13 +- .../dubbo-registry-multiple/pom.xml | 107 +- .../registry/multiple/MultipleRegistry.java | 55 +- .../multiple/MultipleRegistryFactory.java | 1 - .../multiple/MultipleServiceDiscovery.java | 32 +- .../multiple/MultipleRegistry2S2RTest.java | 74 +- .../multiple/MultipleRegistryTestUtil.java | 10 +- .../MultipleServiceDiscoveryTest.java | 42 +- dubbo-registry/dubbo-registry-nacos/pom.xml | 121 +- .../nacos/NacosAggregateListener.java | 30 +- .../nacos/NacosConnectionManager.java | 45 +- .../nacos/NacosNamingServiceWrapper.java | 161 +- .../dubbo/registry/nacos/NacosRegistry.java | 240 +- .../registry/nacos/NacosServiceDiscovery.java | 55 +- .../nacos/NacosServiceDiscoveryFactory.java | 1 - .../registry/nacos/NacosServiceName.java | 16 +- ...NacosReflectionTypeDescriberRegistrar.java | 107 +- .../nacos/util/NacosNamingServiceUtils.java | 12 +- .../registry/nacos/MockNamingService.java | 112 +- .../nacos/NacosConnectionsManagerTest.java | 43 +- .../nacos/NacosNamingServiceWrapperTest.java | 440 +- .../nacos/NacosRegistryFactoryTest.java | 8 +- .../registry/nacos/NacosRegistryTest.java | 88 +- .../NacosServiceDiscoveryFactoryTest.java | 5 +- .../nacos/NacosServiceDiscoveryTest.java | 60 +- .../util/NacosNamingServiceUtilsTest.java | 56 +- .../dubbo-registry-zookeeper/pom.xml | 61 +- .../registry/zookeeper/ZookeeperInstance.java | 8 +- .../registry/zookeeper/ZookeeperRegistry.java | 98 +- .../zookeeper/ZookeeperRegistryFactory.java | 1 - .../zookeeper/ZookeeperServiceDiscovery.java | 54 +- ...ookeeperServiceDiscoveryChangeWatcher.java | 39 +- ...eeperReflectionTypeDescriberRegistrar.java | 4 +- .../util/CuratorFrameworkParams.java | 6 +- .../zookeeper/util/CuratorFrameworkUtils.java | 53 +- .../zookeeper/ZookeeperRegistryTest.java | 23 +- .../ZookeeperServiceDiscoveryTest.java | 23 +- .../util/CuratorFrameworkUtilsTest.java | 30 +- dubbo-registry/pom.xml | 59 +- dubbo-remoting/dubbo-remoting-api/pom.xml | 87 +- .../apache/dubbo/remoting/ChannelHandler.java | 2 - .../org/apache/dubbo/remoting/Client.java | 1 - .../java/org/apache/dubbo/remoting/Codec.java | 1 - .../org/apache/dubbo/remoting/Codec2.java | 6 +- .../org/apache/dubbo/remoting/Constants.java | 4 +- .../org/apache/dubbo/remoting/Decodeable.java | 2 - .../org/apache/dubbo/remoting/Dispatcher.java | 1 - .../org/apache/dubbo/remoting/Endpoint.java | 1 - .../dubbo/remoting/ExecutionException.java | 16 +- .../dubbo/remoting/RemotingException.java | 19 +- .../apache/dubbo/remoting/RemotingServer.java | 1 - .../dubbo/remoting/TimeoutException.java | 5 +- .../apache/dubbo/remoting/Transporter.java | 1 - .../apache/dubbo/remoting/Transporters.java | 8 +- .../api/AbstractHttpProtocolDetector.java | 12 +- .../remoting/api/AbstractWireProtocol.java | 7 +- .../dubbo/remoting/api/ProtocolDetector.java | 14 +- .../connection/AbstractConnectionClient.java | 8 +- .../api/connection/ConnectionHandler.java | 1 - .../api/connection/ConnectionManager.java | 1 - .../MultiplexProtocolConnectionManager.java | 7 +- .../SingleProtocolConnectionManager.java | 4 +- .../api/pu/ChannelHandlerPretender.java | 1 - .../dubbo/remoting/api/pu/DefaultCodec.java | 4 +- .../remoting/api/pu/DefaultPuHandler.java | 20 +- .../api/pu/PortUnificationTransporter.java | 1 - .../buffer/AbstractChannelBuffer.java | 13 +- .../buffer/ByteBufferBackedChannelBuffer.java | 22 +- .../dubbo/remoting/buffer/ChannelBuffer.java | 5 +- .../remoting/buffer/ChannelBufferFactory.java | 1 - .../buffer/ChannelBufferInputStream.java | 2 - .../buffer/ChannelBufferOutputStream.java | 1 - .../dubbo/remoting/buffer/ChannelBuffers.java | 11 +- .../buffer/DirectChannelBufferFactory.java | 2 - .../remoting/buffer/DynamicChannelBuffer.java | 19 - .../remoting/buffer/HeapChannelBuffer.java | 7 +- .../buffer/HeapChannelBufferFactory.java | 2 - .../remoting/exchange/ExchangeClient.java | 4 +- .../remoting/exchange/ExchangeHandler.java | 1 - .../remoting/exchange/ExchangeServer.java | 1 - .../dubbo/remoting/exchange/Exchanger.java | 1 - .../dubbo/remoting/exchange/Exchangers.java | 11 +- .../remoting/exchange/HeartBeatResponse.java | 2 +- .../exchange/PortUnificationExchanger.java | 9 +- .../dubbo/remoting/exchange/Request.java | 3 +- .../dubbo/remoting/exchange/Response.java | 3 +- .../exchange/codec/ExchangeCodec.java | 78 +- .../exchange/support/DefaultFuture.java | 71 +- .../support/ExchangeHandlerAdapter.java | 1 - .../support/ExchangeHandlerDispatcher.java | 1 - .../support/ExchangeServerDelegate.java | 4 +- .../exchange/support/MultiMessage.java | 5 +- .../remoting/exchange/support/Replier.java | 1 - .../exchange/support/ReplierDispatcher.java | 1 - .../support/header/AbstractTimerTask.java | 1 - .../support/header/CloseTimerTask.java | 19 +- .../support/header/HeaderExchangeChannel.java | 30 +- .../support/header/HeaderExchangeClient.java | 24 +- .../support/header/HeaderExchangeHandler.java | 28 +- .../support/header/HeaderExchangeServer.java | 23 +- .../support/header/HeaderExchanger.java | 14 +- .../support/header/HeartbeatHandler.java | 8 +- .../support/header/HeartbeatTimerTask.java | 17 +- .../support/header/ReconnectTimerTask.java | 22 +- .../dubbo/remoting/telnet/TelnetHandler.java | 1 - .../remoting/telnet/codec/TelnetCodec.java | 28 +- .../dubbo/remoting/telnet/support/Help.java | 1 - .../telnet/support/TelnetHandlerAdapter.java | 4 +- .../remoting/telnet/support/TelnetUtils.java | 18 +- .../support/command/ClearTelnetHandler.java | 3 +- .../support/command/ExitTelnetHandler.java | 1 - .../support/command/HelpTelnetHandler.java | 11 +- .../support/command/LogTelnetHandler.java | 12 +- .../support/command/StatusTelnetHandler.java | 5 +- .../remoting/transport/AbstractChannel.java | 9 +- .../remoting/transport/AbstractClient.java | 102 +- .../remoting/transport/AbstractCodec.java | 14 +- .../remoting/transport/AbstractEndpoint.java | 12 +- .../remoting/transport/AbstractServer.java | 45 +- .../remoting/transport/ChannelDelegate.java | 4 +- .../transport/ChannelHandlerAdapter.java | 16 +- .../transport/ChannelHandlerDispatcher.java | 10 +- .../remoting/transport/ClientDelegate.java | 4 +- .../remoting/transport/CodecSupport.java | 40 +- .../remoting/transport/DecodeHandler.java | 1 - .../transport/MultiMessageHandler.java | 17 +- .../remoting/transport/ServerDelegate.java | 3 +- .../transport/codec/CodecAdapter.java | 4 +- .../dispatcher/ChannelEventRunnable.java | 54 +- .../transport/dispatcher/ChannelHandlers.java | 9 +- .../dispatcher/WrappedChannelHandler.java | 20 +- .../dispatcher/all/AllChannelHandler.java | 8 +- .../dispatcher/all/AllDispatcher.java | 1 - .../ConnectionOrderedChannelHandler.java | 28 +- .../ConnectionOrderedDispatcher.java | 1 - .../direct/DirectChannelHandler.java | 1 - .../dispatcher/direct/DirectDispatcher.java | 1 - .../execution/ExecutionDispatcher.java | 1 - .../message/MessageOnlyChannelHandler.java | 3 +- .../message/MessageOnlyDispatcher.java | 1 - .../apache/dubbo/remoting/utils/UrlUtils.java | 5 +- .../dubbo/remoting/ChanelHandlerTest.java | 20 +- .../remoting/PerformanceClientCloseTest.java | 75 +- .../remoting/PerformanceClientFixedTest.java | 35 +- .../dubbo/remoting/PerformanceClientMain.java | 2 - .../dubbo/remoting/PerformanceClientTest.java | 132 +- .../dubbo/remoting/PerformanceServerMain.java | 1 - .../dubbo/remoting/PerformanceServerTest.java | 135 +- .../dubbo/remoting/PerformanceUtils.java | 12 +- .../apache/dubbo/remoting/TelnetServer.java | 1 - .../dubbo/remoting/api/EmptyProtocol.java | 13 +- .../buffer/AbstractChannelBufferTest.java | 16 +- .../ByteBufferBackedChannelBufferTest.java | 2 +- .../buffer/ChannelBufferFactoryTest.java | 7 +- .../buffer/ChannelBufferStreamTest.java | 40 +- .../remoting/buffer/ChannelBuffersTest.java | 16 +- .../buffer/DirectChannelBufferTest.java | 2 +- .../buffer/DynamicChannelBufferTest.java | 8 +- .../buffer/HeapChannelBufferTest.java | 2 +- .../remoting/codec/AbstractMockChannel.java | 4 +- .../remoting/codec/CodecAdapterTest.java | 1 - .../codec/DeprecatedExchangeCodec.java | 31 +- .../remoting/codec/DeprecatedTelnetCodec.java | 43 +- .../remoting/codec/ExchangeCodecTest.java | 137 +- .../dubbo/remoting/codec/TelnetCodecTest.java | 138 +- .../remoting/exchange/ExchangersTest.java | 15 +- .../remoting/exchange/MockExchanger.java | 2 +- .../dubbo/remoting/exchange/RequestTest.java | 1 - .../dubbo/remoting/exchange/ResponseTest.java | 1 - .../exchange/support/DefaultFutureTest.java | 70 +- .../ExchangeHandlerDispatcherTest.java | 4 +- .../exchange/support/MultiMessageTest.java | 12 +- .../support/header/CloseTimerTaskTest.java | 7 +- .../header/HeaderExchangeChannelTest.java | 15 +- .../header/HeaderExchangeServerTest.java | 15 +- .../support/header/HeartBeatTaskTest.java | 14 +- .../exchange/support/header/MockChannel.java | 9 +- .../header/ReconnectTimerTaskTest.java | 10 +- .../handler/HeaderExchangeHandlerTest.java | 11 +- .../dubbo/remoting/handler/MockedChannel.java | 4 +- .../handler/MockedChannelHandler.java | 3 +- .../remoting/telnet/TelnetUtilsTest.java | 20 +- .../support/ClearTelnetHandlerTest.java | 3 +- .../telnet/support/HelpTelnetHandlerTest.java | 14 +- .../support/StatusTelnetHandlerTest.java | 10 +- .../support/TelnetHandlerAdapterTest.java | 12 +- .../remoting/transport/AbstractCodecTest.java | 36 +- .../ChannelHandlerDispatcherTest.java | 27 +- .../remoting/transport/CodecSupportTest.java | 5 +- .../transport/MultiMessageHandlerTest.java | 10 +- .../dispatcher/ChannelEventRunnableTest.java | 25 +- dubbo-remoting/dubbo-remoting-http/pom.xml | 128 +- .../dubbo/remoting/http/BaseRestClient.java | 2 - .../dubbo/remoting/http/HttpBinder.java | 1 - .../dubbo/remoting/http/HttpHandler.java | 1 - .../dubbo/remoting/http/HttpServer.java | 1 - .../dubbo/remoting/http/RequestTemplate.java | 18 +- .../dubbo/remoting/http/RestClient.java | 2 - .../http/config/HttpClientConfig.java | 4 +- .../factory/AbstractHttpClientFactory.java | 28 +- .../http/factory/RestClientFactory.java | 3 - .../factory/impl/ApacheHttpClientFactory.java | 2 - .../factory/impl/OkHttpClientFactory.java | 1 - .../impl/URLConnectionClientFactory.java | 1 - .../remoting/http/jetty/JettyHttpBinder.java | 1 - .../remoting/http/jetty/JettyHttpServer.java | 11 +- .../http/restclient/HttpClientRestClient.java | 36 +- .../http/restclient/OKHttpRestClient.java | 28 +- .../restclient/URLConnectionRestClient.java | 23 +- .../http/servlet/BootstrapListener.java | 3 +- .../http/servlet/DispatcherServlet.java | 4 +- .../http/servlet/ServletHttpBinder.java | 1 - .../http/servlet/ServletHttpServer.java | 1 - .../remoting/http/servlet/ServletManager.java | 1 + .../http/support/AbstractHttpServer.java | 20 +- .../http/tomcat/TomcatHttpBinder.java | 1 - .../http/tomcat/TomcatHttpServer.java | 4 +- .../http/jetty/JettyHttpBinderTest.java | 16 +- .../http/jetty/JettyLoggerAdapterTest.java | 37 +- .../remoting/http/rest/RestClientTest.java | 48 +- .../http/tomcat/TomcatHttpBinderTest.java | 27 +- dubbo-remoting/dubbo-remoting-http12/pom.xml | 91 +- .../AbstractServerHttpChannelObserver.java | 15 +- .../CustomizableHttpChannelObserver.java | 1 - .../remoting/http12/ErrorCodeHolder.java | 1 - .../http12/ErrorResponseCustomizer.java | 3 +- .../http12/FlowControlStreamObserver.java | 1 - .../remoting/http12/HeadersCustomizer.java | 3 +- .../dubbo/remoting/http12/HttpChannel.java | 1 - .../remoting/http12/HttpChannelObserver.java | 1 - .../remoting/http12/HttpHeaderNames.java | 1 - .../dubbo/remoting/http12/HttpHeaders.java | 16 - .../remoting/http12/HttpInputMessage.java | 1 - .../dubbo/remoting/http12/HttpMetadata.java | 1 - .../remoting/http12/HttpOutputMessage.java | 1 - .../dubbo/remoting/http12/HttpStatus.java | 1 - .../http12/HttpTransportListener.java | 1 - .../remoting/http12/RequestMetadata.java | 1 - .../remoting/http12/TrailersCustomizer.java | 3 +- .../http12/command/DataQueueCommand.java | 15 +- .../http12/command/HeaderQueueCommand.java | 3 +- .../command/HttpChannelQueueCommand.java | 4 +- .../remoting/http12/command/QueueCommand.java | 4 +- .../http12/exception/HttpRequestTimeout.java | 5 +- .../exception/IllegalPathException.java | 5 +- .../http12/h1/Http1OutputMessage.java | 1 - .../remoting/http12/h1/Http1Request.java | 4 +- .../http12/h1/Http1ServerChannelObserver.java | 3 +- .../h1/Http1ServerStreamChannelObserver.java | 4 +- .../h1/Http1ServerTransportListener.java | 4 +- .../Http1ServerTransportListenerFactory.java | 1 - .../h2/CancelableTransportListener.java | 4 +- .../remoting/http12/h2/Http2Headers.java | 3 +- .../remoting/http12/h2/Http2InputMessage.java | 4 +- .../http12/h2/Http2ServerChannelObserver.java | 5 +- .../Http2ServerTransportListenerFactory.java | 1 - .../http12/h2/Http2TransportListener.java | 4 +- .../http12/h2/command/ResetQueueCommand.java | 16 +- .../http12/message/HttpMessageCodec.java | 9 +- .../message/HttpMessageCodecFactory.java | 1 - .../remoting/http12/message/JsonCodec.java | 3 +- .../remoting/http12/message/JsonPbCodec.java | 18 +- .../http12/message/JsonPbCodecFactory.java | 9 +- .../message/LengthFieldStreamingDecoder.java | 2 +- .../http12/message/ListeningDecoder.java | 4 +- .../remoting/http12/message/MediaType.java | 1 - .../http12/message/MethodMetadata.java | 19 +- .../http12/message/StreamingDecoder.java | 6 +- .../http12/netty4/HttpWriteQueueHandler.java | 3 +- .../NettyHttpChannelFutureListener.java | 4 +- .../http12/netty4/h1/NettyHttp1Channel.java | 9 +- .../http12/netty4/h1/NettyHttp1Codec.java | 39 +- .../h1/NettyHttp1ConnectionHandler.java | 45 +- .../netty4/h2/NettyH2StreamChannel.java | 11 +- .../netty4/h2/NettyHttp2FrameCodec.java | 30 +- .../netty4/h2/NettyHttp2FrameHandler.java | 14 +- .../h2/NettyHttp2ProtocolSelectorHandler.java | 26 +- dubbo-remoting/dubbo-remoting-netty/pom.xml | 85 +- .../netty/NettyBackedChannelBuffer.java | 61 - .../NettyBackedChannelBufferFactory.java | 7 +- .../transport/netty/NettyChannel.java | 20 +- .../remoting/transport/netty/NettyClient.java | 49 +- .../transport/netty/NettyCodecAdapter.java | 7 +- .../transport/netty/NettyHandler.java | 23 +- .../remoting/transport/netty/NettyHelper.java | 1 - .../netty/NettyPortUnificationServer.java | 36 +- .../remoting/transport/netty/NettyServer.java | 21 +- .../transport/netty/NettyTransporter.java | 1 - .../support/header/HeartbeatHandlerTest.java | 33 +- .../dispatcher/FakeChannelHandlers.java | 4 +- .../transport/netty/ClientReconnectTest.java | 15 +- .../transport/netty/ClientToServerTest.java | 46 +- .../remoting/transport/netty/ClientsTest.java | 10 +- .../dubbo/remoting/transport/netty/Hello.java | 4 +- .../netty/NettyBackedChannelBufferTest.java | 1 - .../transport/netty/NettyClientTest.java | 22 +- .../netty/NettyClientToServerTest.java | 1 - .../transport/netty/NettyStringTest.java | 13 +- .../transport/netty/TelnetServerHandler.java | 3 +- .../transport/netty/ThreadNameTest.java | 24 +- .../dubbo/remoting/transport/netty/World.java | 4 +- .../transport/netty/WorldHandler.java | 1 - dubbo-remoting/dubbo-remoting-netty4/pom.xml | 141 +- .../netty4/Netty4BatchWriteQueue.java | 14 +- .../netty4/NettyBackedChannelBuffer.java | 69 +- .../transport/netty4/NettyChannel.java | 39 +- .../transport/netty4/NettyChannelHandler.java | 19 +- .../transport/netty4/NettyClient.java | 96 +- .../transport/netty4/NettyClientHandler.java | 10 +- .../transport/netty4/NettyCodecAdapter.java | 12 +- .../transport/netty4/NettyConfigOperator.java | 37 +- .../netty4/NettyConnectionClient.java | 98 +- .../netty4/NettyConnectionHandler.java | 35 +- .../netty4/NettyEventLoopFactory.java | 17 +- .../netty4/NettyPortUnificationServer.java | 77 +- .../NettyPortUnificationServerHandler.java | 80 +- .../NettyPortUnificationTransporter.java | 4 +- .../transport/netty4/NettyServer.java | 88 +- .../transport/netty4/NettyServerHandler.java | 25 +- .../netty4/NettySslContextOperator.java | 3 +- .../transport/netty4/NettyTransporter.java | 1 - ...etty4ReflectionTypeDescriberRegistrar.java | 4 +- .../netty4/logging/FormattingTuple.java | 1 - .../netty4/logging/MessageFormatter.java | 34 +- .../netty4/ssl/SslClientTlsHandler.java | 17 +- .../transport/netty4/ssl/SslContexts.java | 29 +- .../netty4/ssl/SslServerTlsHandler.java | 34 +- .../transport/netty4/ClientReconnectTest.java | 14 +- .../transport/netty4/ClientToServerTest.java | 10 +- .../transport/netty4/ClientsTest.java | 10 +- .../transport/netty4/ConnectionTest.java | 19 +- .../transport/netty4/DefaultCodec.java | 4 +- .../transport/netty4/DemoService.java | 1 - .../transport/netty4/DemoServiceImpl.java | 1 - .../remoting/transport/netty4/Hello.java | 4 +- .../remoting/transport/netty4/MockResult.java | 1 - .../netty4/NettyBackedChannelBufferTest.java | 2 - .../transport/netty4/NettyChannelTest.java | 34 +- .../netty4/NettyClientHandlerTest.java | 11 +- .../netty4/NettyClientToServerTest.java | 6 +- .../netty4/NettyEventLoopFactoryTest.java | 7 +- .../netty4/NettyTransporterTest.java | 12 +- .../netty4/PortUnificationExchangerTest.java | 2 +- .../netty4/PortUnificationServerTest.java | 1 - .../netty4/ReplierDispatcherTest.java | 40 +- .../remoting/transport/netty4/RpcMessage.java | 2 - .../transport/netty4/RpcMessageHandler.java | 5 +- .../remoting/transport/netty4/World.java | 4 +- .../transport/netty4/WorldHandler.java | 1 - .../netty4/api/EmptyWireProtocol.java | 13 +- ...ultiplexProtocolConnectionManagerTest.java | 15 +- .../SingleProtocolConnectionManagerTest.java | 25 +- .../dubbo-remoting-zookeeper-api/pom.xml | 59 +- .../RemotingScopeModelInitializer.java | 22 +- .../zookeeper/AbstractZookeeperClient.java | 24 +- .../AbstractZookeeperTransporter.java | 16 +- .../remoting/zookeeper/ChildListener.java | 1 - .../dubbo/remoting/zookeeper/EventType.java | 3 +- .../remoting/zookeeper/StateListener.java | 1 - .../remoting/zookeeper/ZookeeperClient.java | 1 - .../zookeeper/ZookeeperTransporter.java | 3 +- .../dubbo-remoting-zookeeper-curator5/pom.xml | 100 +- .../curator5/Curator5ZookeeperClient.java | 122 +- .../Curator5ZookeeperTransporter.java | 1 - ...eeperReflectionTypeDescriberRegistrar.java | 9 +- .../curator5/Curator5ZookeeperClientTest.java | 182 +- .../Curator5ZookeeperTransporterTest.java | 3 +- .../AbstractZookeeperTransporterTest.java | 154 +- .../dubbo-remoting-zookeeper/pom.xml | 119 +- .../curator/CuratorZookeeperClient.java | 144 +- .../curator/CuratorZookeeperTransporter.java | 2 - ...eeperReflectionTypeDescriberRegistrar.java | 12 +- .../curator/CuratorZookeeperClientTest.java | 185 +- .../CuratorZookeeperTransporterTest.java | 4 +- .../AbstractZookeeperTransporterTest.java | 155 +- dubbo-remoting/pom.xml | 64 +- dubbo-rpc/dubbo-rpc-api/pom.xml | 83 +- .../org/apache/dubbo/rpc/AppResponse.java | 25 +- .../apache/dubbo/rpc/AsyncContextImpl.java | 3 +- .../org/apache/dubbo/rpc/AsyncRpcResult.java | 28 +- .../apache/dubbo/rpc/CancellationContext.java | 15 +- .../dubbo/rpc/CancellationListener.java | 2 - .../java/org/apache/dubbo/rpc/Constants.java | 1 - .../apache/dubbo/rpc/ExecutableListener.java | 3 - .../java/org/apache/dubbo/rpc/Exporter.java | 1 - .../apache/dubbo/rpc/ExporterListener.java | 1 - .../java/org/apache/dubbo/rpc/Filter.java | 4 +- .../org/apache/dubbo/rpc/FutureContext.java | 4 +- .../java/org/apache/dubbo/rpc/Invocation.java | 8 +- .../java/org/apache/dubbo/rpc/InvokeMode.java | 6 +- .../java/org/apache/dubbo/rpc/Invoker.java | 1 - .../org/apache/dubbo/rpc/InvokerListener.java | 1 - .../org/apache/dubbo/rpc/PathResolver.java | 1 - .../rpc/PenetrateAttachmentSelector.java | 8 +- .../java/org/apache/dubbo/rpc/Protocol.java | 1 - .../org/apache/dubbo/rpc/ProtocolServer.java | 6 +- .../org/apache/dubbo/rpc/ProxyFactory.java | 1 - .../java/org/apache/dubbo/rpc/Result.java | 1 - .../org/apache/dubbo/rpc/RpcConstants.java | 8 +- .../java/org/apache/dubbo/rpc/RpcContext.java | 92 +- .../dubbo/rpc/RpcContextAttachment.java | 5 +- .../org/apache/dubbo/rpc/RpcException.java | 2 +- .../org/apache/dubbo/rpc/RpcInvocation.java | 309 +- .../dubbo/rpc/RpcScopeModelInitializer.java | 8 +- .../dubbo/rpc/RpcServerContextAttachment.java | 28 +- .../apache/dubbo/rpc/RpcServiceContext.java | 20 +- .../java/org/apache/dubbo/rpc/RpcStatus.java | 14 +- .../org/apache/dubbo/rpc/ServerService.java | 2 - .../apache/dubbo/rpc/TimeoutCountDown.java | 6 +- .../org/apache/dubbo/rpc/ZoneDetector.java | 1 - .../rpc/cluster/filter/ClusterFilter.java | 3 +- .../dubbo/rpc/filter/CompatibleFilter.java | 13 +- .../dubbo/rpc/filter/DeprecatedFilter.java | 8 +- .../apache/dubbo/rpc/filter/EchoFilter.java | 1 - .../dubbo/rpc/filter/ExceptionFilter.java | 51 +- .../rpc/filter/ProfilerServerFilter.java | 50 +- .../dubbo/rpc/filter/RpcExceptionFilter.java | 6 +- .../dubbo/rpc/filter/TimeoutFilter.java | 12 +- .../listener/DeprecatedInvokerListener.java | 11 +- .../rpc/listener/ExporterListenerAdapter.java | 7 +- .../rpc/listener/InjvmExporterListener.java | 4 - .../rpc/listener/InvokerListenerAdapter.java | 7 +- .../rpc/listener/ListenerExporterWrapper.java | 3 +- .../rpc/listener/ListenerInvokerWrapper.java | 11 +- .../dubbo/rpc/protocol/AbstractExporter.java | 14 +- .../dubbo/rpc/protocol/AbstractInvoker.java | 60 +- .../dubbo/rpc/protocol/AbstractProtocol.java | 13 +- .../rpc/protocol/AbstractProxyProtocol.java | 43 +- .../dubbo/rpc/protocol/InvokerWrapper.java | 1 - .../PermittedSerializationKeeper.java | 3 +- .../rpc/protocol/ProtocolListenerWrapper.java | 23 +- .../rpc/protocol/ProtocolSecurityWrapper.java | 36 +- .../ProtocolSerializationWrapper.java | 5 +- .../ReferenceCountInvokerWrapper.java | 31 +- .../rpc/protocol/dubbo/FutureAdapter.java | 9 +- .../protocol/dubbo/filter/FutureFilter.java | 37 +- .../AbstractFallbackJdkProxyFactory.java | 58 +- .../dubbo/rpc/proxy/AbstractProxyFactory.java | 21 +- .../dubbo/rpc/proxy/AbstractProxyInvoker.java | 30 +- .../dubbo/rpc/proxy/InvocationUtil.java | 50 +- .../rpc/proxy/InvokerInvocationHandler.java | 8 +- .../apache/dubbo/rpc/proxy/MethodInvoker.java | 15 +- .../javassist/JavassistProxyFactory.java | 66 +- .../dubbo/rpc/proxy/jdk/JdkProxyFactory.java | 9 +- .../wrapper/StubProxyFactoryWrapper.java | 32 +- .../dubbo/rpc/stub/BiStreamMethodHandler.java | 1 - .../rpc/stub/FutureToObserverAdaptor.java | 1 - .../rpc/stub/ServerStreamMethodHandler.java | 1 - .../apache/dubbo/rpc/stub/StubInvoker.java | 8 +- .../dubbo/rpc/stub/StubMethodHandler.java | 2 - .../dubbo/rpc/stub/StubProxyFactory.java | 1 - .../apache/dubbo/rpc/stub/StubSuppliers.java | 12 +- .../rpc/stub/UnaryStubMethodHandler.java | 1 - .../rpc/support/Dubbo2RpcExceptionUtils.java | 3 +- .../apache/dubbo/rpc/support/RpcUtils.java | 50 +- .../org/apache/dubbo/rpc/AppResponseTest.java | 9 +- .../dubbo/rpc/CancellationContextTest.java | 6 +- .../org/apache/dubbo/rpc/CustomArgument.java | 4 +- .../org/apache/dubbo/rpc/DemoRequest.java | 1 - .../apache/dubbo/rpc/FutureContextTest.java | 8 +- .../rpc/PenetrateAttachmentSelectorTest.java | 18 +- .../org/apache/dubbo/rpc/RpcContextTest.java | 52 +- .../apache/dubbo/rpc/RpcInvocationTest.java | 3 +- .../org/apache/dubbo/rpc/RpcStatusTest.java | 8 +- .../dubbo/rpc/TimeoutCountDownTest.java | 5 +- .../filter/CompatibleFilterFilterTest.java | 28 +- .../rpc/filter/DeprecatedFilterTest.java | 7 +- .../dubbo/rpc/filter/EchoFilterTest.java | 7 +- .../dubbo/rpc/filter/ExceptionFilterTest.java | 27 +- .../dubbo/rpc/filter/TimeoutFilterTest.java | 5 +- .../rpc/protocol/CountInvokerListener.java | 7 +- .../protocol/ProtocolListenerWrapperTest.java | 87 +- .../rpc/protocol/dubbo/FutureFilterTest.java | 6 +- .../dubbo/rpc/proxy/AbstractProxyTest.java | 31 +- .../apache/dubbo/rpc/proxy/DemoRequest.java | 1 - .../dubbo/rpc/proxy/DemoServiceImpl.java | 13 +- .../proxy/InvokerInvocationHandlerTest.java | 7 +- .../dubbo/rpc/proxy/MethodInvokerTest.java | 19 +- .../dubbo/rpc/proxy/RemoteServiceImpl.java | 3 +- .../java/org/apache/dubbo/rpc/proxy/Type.java | 4 +- .../javassist/JavassistProxyFactoryTest.java | 1 - .../rpc/proxy/jdk/JdkProxyFactoryTest.java | 1 - .../wrapper/StubProxyFactoryWrapperTest.java | 1 - .../rpc/stub/BiStreamMethodHandlerTest.java | 15 +- .../rpc/stub/FutureToObserverAdaptorTest.java | 7 +- .../stub/ServerStreamMethodHandlerTest.java | 24 +- .../dubbo/rpc/stub/StubInvokerTest.java | 17 +- .../dubbo/rpc/stub/StubProxyFactoryTest.java | 15 +- .../dubbo/rpc/stub/StubSuppliersTest.java | 1 - .../apache/dubbo/rpc/support/DemoService.java | 3 +- .../dubbo/rpc/support/DemoServiceImpl.java | 17 +- .../dubbo/rpc/support/DemoServiceStub.java | 2 +- .../dubbo/rpc/support/LocalException.java | 2 - .../dubbo/rpc/support/MockInvocation.java | 9 +- .../apache/dubbo/rpc/support/MyInvoker.java | 1 - .../PenetrateAttachmentSelectorMock.java | 11 +- .../dubbo/rpc/support/RpcUtilsTest.java | 265 +- .../rpc/support/RuntimeExceptionInvoker.java | 1 - .../org/apache/dubbo/rpc/support/Type.java | 4 +- dubbo-rpc/dubbo-rpc-dubbo/pom.xml | 183 +- .../rpc/protocol/dubbo/ByteAccessor.java | 1 - .../protocol/dubbo/CallbackServiceCodec.java | 124 +- .../protocol/dubbo/ChannelWrappedInvoker.java | 24 +- .../dubbo/rpc/protocol/dubbo/Constants.java | 3 - .../dubbo/DecodeableRpcInvocation.java | 47 +- .../protocol/dubbo/DecodeableRpcResult.java | 18 +- .../dubbo/rpc/protocol/dubbo/DubboCodec.java | 72 +- .../rpc/protocol/dubbo/DubboCodecSupport.java | 8 +- .../rpc/protocol/dubbo/DubboCountCodec.java | 2 - .../rpc/protocol/dubbo/DubboExporter.java | 1 - .../protocol/dubbo/DubboGracefulShutdown.java | 7 +- .../rpc/protocol/dubbo/DubboInvoker.java | 28 +- .../dubbo/DubboIsolationExecutorSupport.java | 3 +- .../rpc/protocol/dubbo/DubboProtocol.java | 176 +- .../dubbo/ExclusiveClientsProvider.java | 3 +- .../dubbo/LazyConnectExchangeClient.java | 17 +- .../dubbo/ReferenceCountExchangeClient.java | 15 +- .../protocol/dubbo/SharedClientsProvider.java | 16 +- .../rpc/protocol/dubbo/pu/DubboDetector.java | 7 +- .../protocol/dubbo/pu/DubboWireProtocol.java | 1 - .../dubbo/status/ServerStatusChecker.java | 1 - .../dubbo/status/ThreadPoolStatusChecker.java | 21 +- .../protocol/dubbo/ArgumentCallbackTest.java | 171 +- .../dubbo/DecodeableRpcInvocationTest.java | 33 +- .../dubbo/DecodeableRpcResultTest.java | 33 +- .../protocol/dubbo/DubboCountCodecTest.java | 10 +- .../dubbo/DubboInvokerAvailableTest.java | 31 +- .../protocol/dubbo/DubboLazyConnectTest.java | 16 +- .../rpc/protocol/dubbo/DubboProtocolTest.java | 251 +- .../protocol/dubbo/ImplicitCallBackTest.java | 406 - .../rpc/protocol/dubbo/MultiThreadTest.java | 35 +- .../ReferenceCountExchangeClientTest.java | 31 +- .../rpc/protocol/dubbo/RpcFilterTest.java | 15 +- .../dubbo/decode/DubboTelnetDecodeTest.java | 217 +- .../dubbo/decode/LocalEmbeddedChannel.java | 4 +- .../protocol/dubbo/decode/MockChannel.java | 28 +- .../dubbo/decode/MockChannelHandler.java | 3 +- .../protocol/dubbo/decode/MockHandler.java | 4 +- .../dubbo/managemode/ChannelHandlersTest.java | 1 + .../managemode/ConnectChannelHandlerTest.java | 35 +- .../dubbo/managemode/MockedChannel.java | 4 +- .../managemode/MockedChannelHandler.java | 3 +- .../managemode/WrappedChannelHandlerTest.java | 15 +- .../dubbo/status/ServerStatusCheckerTest.java | 12 +- .../status/ThreadPoolStatusCheckerTest.java | 16 +- .../dubbo/support/CustomArgument.java | 5 +- .../protocol/dubbo/support/DemoRequest.java | 1 - .../protocol/dubbo/support/DemoService.java | 2 - .../dubbo/support/DemoServiceImpl.java | 15 +- .../rpc/protocol/dubbo/support/EnumBak.java | 86 +- .../dubbo/rpc/protocol/dubbo/support/Man.java | 1 - .../protocol/dubbo/support/NonSerialized.java | 4 +- .../protocol/dubbo/support/ProtocolUtils.java | 10 +- .../dubbo/support/RemoteServiceImpl.java | 3 +- .../rpc/protocol/dubbo/support/Type.java | 4 +- dubbo-rpc/dubbo-rpc-injvm/pom.xml | 67 +- .../injvm/DefaultParamDeepCopyUtil.java | 11 +- .../rpc/protocol/injvm/InjvmExporter.java | 1 - .../rpc/protocol/injvm/InjvmInvoker.java | 111 +- .../rpc/protocol/injvm/InjvmProtocol.java | 1 - .../src/test/java/demo/Empty.java | 3 +- .../demo/MultiClassLoaderServiceImpl.java | 4 +- .../demo/MultiClassLoaderServiceRequest.java | 3 +- .../demo/MultiClassLoaderServiceResult.java | 3 +- .../dubbo/rpc/protocol/injvm/DemoRequest.java | 1 - .../dubbo/rpc/protocol/injvm/DemoService.java | 1 - .../rpc/protocol/injvm/DemoServiceImpl.java | 13 +- .../protocol/injvm/InjvmClassLoaderTest.java | 93 +- .../rpc/protocol/injvm/InjvmDeepCopyTest.java | 40 +- .../rpc/protocol/injvm/InjvmProtocolTest.java | 90 +- .../rpc/protocol/injvm/ProtocolTest.java | 17 +- .../apache/dubbo/rpc/protocol/injvm/Type.java | 4 +- dubbo-rpc/dubbo-rpc-rest/pom.xml | 269 +- .../dubbo/rpc/protocol/rest/Constants.java | 2 - .../protocol/rest/PathAndInvokerMapper.java | 67 +- .../protocol/rest/ReferenceCountedClient.java | 12 +- .../rest/RestConstraintViolation.java | 4 +- .../rpc/protocol/rest/RestHeaderEnum.java | 2 - .../dubbo/rpc/protocol/rest/RestInvoker.java | 45 +- .../dubbo/rpc/protocol/rest/RestProtocol.java | 70 +- .../protocol/rest/RestRPCInvocationUtil.java | 45 +- .../rpc/protocol/rest/RpcExceptionMapper.java | 5 +- .../rpc/protocol/rest/ViolationReport.java | 3 +- .../rest/annotation/BaseParseContext.java | 3 - .../protocol/rest/annotation/ParamParser.java | 1 - .../rest/annotation/ParamParserManager.java | 14 +- .../consumer/HttpConnectionCreateContext.java | 5 +- .../inercept/AddMustAttachmentIntercept.java | 12 +- .../inercept/AttachmentIntercept.java | 4 +- .../inercept/ParamParseIntercept.java | 5 +- .../inercept/PathVariableIntercept.java | 12 +- .../inercept/RequestHeaderIntercept.java | 12 +- .../inercept/SerializeBodyIntercept.java | 22 +- .../annotation/metadata/MetadataResolver.java | 30 +- .../consumer/BaseConsumerParamParser.java | 1 - .../consumer/BodyConsumerParamParser.java | 5 +- .../parse/consumer/ConsumerParseContext.java | 2 - .../consumer/FormConsumerParamParser.java | 12 +- .../consumer/HeaderConsumerParamParser.java | 3 - .../ParameterConsumerParamParser.java | 4 - .../provider/BaseProviderParamParser.java | 3 - .../provider/BodyProviderParamParser.java | 4 +- .../provider/HeaderProviderParamParser.java | 9 +- .../NoAnnotationParamProviderParamParser.java | 3 - .../provider/ParamProviderParamParser.java | 8 +- .../provider/PathProviderParamParser.java | 5 +- .../parse/provider/ProviderParamParser.java | 4 - .../parse/provider/ProviderParseContext.java | 6 - ...gnClientAnnotationConfigPostProcessor.java | 11 +- .../protocol/rest/constans/RestConstant.java | 3 - .../protocol/rest/deploy/ServiceDeployer.java | 23 +- .../rest/deploy/ServiceDeployerManager.java | 17 +- .../CodeStyleNotSupportException.java | 2 +- .../MediaTypeUnSupportException.java | 2 +- .../rest/exception/PathNoFoundException.java | 2 +- .../RemoteServerInternalException.java | 2 +- .../UnSupportContentTypeException.java | 3 +- .../exception/mapper/ExceptionHandler.java | 4 - .../mapper/ExceptionHandlerResult.java | 9 +- .../exception/mapper/ExceptionMapper.java | 31 +- .../mapper/RestEasyExceptionMapper.java | 4 +- .../extension/resteasy/ResteasyContext.java | 86 +- .../resteasy/filter/DubboBuiltResponse.java | 1 - .../DubboContainerResponseContextImpl.java | 97 +- .../DubboPreMatchContainerRequestContext.java | 43 +- .../filter/ResteasyNettyHttpResponse.java | 15 +- ...ResteasyRequestContainerFilterAdapter.java | 25 +- ...esteasyResponseContainerFilterAdapter.java | 33 +- .../DubboServerWriterInterceptorContext.java | 39 +- .../ResteasyWriterInterceptorAdapter.java | 68 +- .../rpc/protocol/rest/filter/RestFilter.java | 1 - .../rest/filter/RestRequestFilter.java | 4 +- .../rest/filter/RestResponseFilter.java | 4 +- .../rest/filter/RestResponseInterceptor.java | 1 - .../rest/filter/ServiceInvokeRestFilter.java | 103 +- .../ServiceInvokeRestResponseInterceptor.java | 7 +- .../rest/filter/context/FilterContext.java | 3 +- .../filter/context/RestFilterContext.java | 3 +- .../filter/context/RestInterceptContext.java | 9 +- .../rest/handler/NettyHttpHandler.java | 65 +- .../DubboSwaggerApiListingResource.java | 14 +- .../swagger/DubboSwaggerService.java | 8 +- .../rest/message/HttpMessageCodec.java | 6 +- .../rest/message/HttpMessageCodecManager.java | 29 +- .../rest/message/HttpMessageDecode.java | 5 +- .../rest/message/HttpMessageEncode.java | 4 - .../rest/message/MediaTypeMatcher.java | 7 - .../rest/message/codec/ByteArrayCodec.java | 2 - .../rest/message/codec/JsonCodec.java | 2 - .../rest/message/codec/MultiValueCodec.java | 13 +- .../message/codec/ResteasyResponseCodec.java | 1 - .../rest/message/codec/StringCodec.java | 5 +- .../rest/message/codec/TextCodec.java | 1 - .../protocol/rest/message/codec/XMLCodec.java | 17 +- .../rest/netty/ChunkOutputStream.java | 14 +- .../rpc/protocol/rest/netty/HttpResponse.java | 6 - .../rest/netty/NettyHttpResponse.java | 55 +- .../rest/netty/RestHttpRequestDecoder.java | 45 +- .../rest/netty/UnSharedHandlerCreator.java | 3 +- .../protocol/rest/netty/ssl/SslContexts.java | 28 +- .../rest/netty/ssl/SslServerTlsHandler.java | 43 +- .../InvokerAndRestMethodMetadataPair.java | 11 +- .../rest/pair/MessageCodecResultPair.java | 2 - .../protocol/rest/pu/RestHttp1Detector.java | 1 - .../rest/pu/RestHttp1WireProtocol.java | 28 +- .../rest/request/NettyRequestFacade.java | 30 +- .../protocol/rest/request/RequestFacade.java | 11 +- .../protocol/rest/support/ContentType.java | 3 +- .../ConstraintViolationExceptionConvert.java | 8 +- .../protocol/rest/util/DataParseUtils.java | 17 +- .../protocol/rest/util/HttpHeaderUtil.java | 19 +- .../rpc/protocol/rest/util/MediaTypeUtil.java | 2 - .../protocol/rest/util/MultiValueCreator.java | 26 +- .../rest/util/NoAnnotationBodyParseUtil.java | 7 +- .../rpc/protocol/rest/util/NumberUtils.java | 8 +- .../rpc/protocol/rest/util/ReflectUtils.java | 15 +- .../rpc/protocol/rest/DataParseUtilsTest.java | 14 +- .../dubbo/rpc/protocol/rest/DemoService.java | 9 +- .../rpc/protocol/rest/DemoServiceImpl.java | 16 +- .../protocol/rest/ExceptionMapperTest.java | 16 +- .../rest/FeignClientRestProtocolTest.java | 32 +- .../rest/HttpMessageCodecManagerTest.java | 20 +- .../protocol/rest/JaxrsRestProtocolTest.java | 171 +- .../rest/JsonCompatibilityCheckTest.java | 23 +- .../rpc/protocol/rest/MediaTypeUtilTest.java | 13 +- .../protocol/rest/NettyRequestFacadeTest.java | 32 +- .../rest/NoAnnotationRestProtocolTest.java | 46 +- .../rpc/protocol/rest/NumberUtilsTest.java | 27 +- .../protocol/rest/ResteasyResponseTest.java | 28 +- .../protocol/rest/RpcExceptionMapperTest.java | 20 +- .../rpc/protocol/rest/ServiceConfigTest.java | 26 +- .../rest/SpringMvcRestProtocolTest.java | 70 +- .../protocol/rest/compatibility/Apple.java | 1 - .../protocol/rest/compatibility/Fruit.java | 1 - .../rest/compatibility/RestDemoService.java | 1 - .../filter/TestContainerRequestFilter.java | 2 +- .../rpc/protocol/rest/filter/TraceFilter.java | 37 +- .../filter/TraceRequestAndResponseFilter.java | 36 +- .../DubboSwaggerApiListingResourceTest.java | 24 +- .../integration/swagger/SwaggerService.java | 7 +- .../intercept/DynamicTraceInterceptor.java | 11 +- .../rest/mvc/SpringDemoServiceImpl.java | 11 +- .../rest/mvc/SpringRestDemoService.java | 17 +- .../rest/mvc/feign/FeignClientController.java | 1 - .../mvc/feign/FeignClientControllerImpl.java | 4 +- .../noannotation/NoAnnotationDemoService.java | 3 - .../NoAnnotationDemoServiceImpl.java | 5 +- .../rest/rest/AnotherUserRestService.java | 3 +- .../rest/rest/AnotherUserRestServiceImpl.java | 4 - .../protocol/rest/rest/HttpMethodService.java | 1 - .../rest/rest/HttpMethodServiceImpl.java | 3 +- .../rest/rest/RegistrationResult.java | 4 +- .../rest/rest/RestDemoForTestException.java | 2 +- .../protocol/rest/rest/RestDemoService.java | 5 +- .../rest/rest/RestDemoServiceImpl.java | 13 +- .../rest/rest/TestGetInvokerService.java | 2 - .../rest/rest/TestGetInvokerServiceImpl.java | 13 +- dubbo-rpc/dubbo-rpc-triple/pom.xml | 287 +- .../apache/dubbo/rpc/StatusRpcException.java | 4 +- .../org/apache/dubbo/rpc/TriRpcStatus.java | 15 +- .../tri/CancelableStreamObserver.java | 1 - .../dubbo/rpc/protocol/tri/ClassLoadUtil.java | 1 - .../protocol/tri/ClientStreamObserver.java | 3 - .../rpc/protocol/tri/DeadlineFuture.java | 26 +- .../tri/DefaultPackableMethodFactory.java | 2 - .../rpc/protocol/tri/ExceptionUtils.java | 1 - .../rpc/protocol/tri/GrpcHttp2Protocol.java | 4 +- .../dubbo/rpc/protocol/tri/GrpcProtocol.java | 1 - .../protocol/tri/Http2ProtocolDetector.java | 2 +- .../dubbo/rpc/protocol/tri/PbArrayPacker.java | 5 +- .../dubbo/rpc/protocol/tri/PbUnpack.java | 1 - .../tri/ReflectionPackableMethod.java | 146 +- .../rpc/protocol/tri/RequestMetadata.java | 29 +- .../protocol/tri/ServerStreamObserver.java | 2 - .../rpc/protocol/tri/SingleProtobufUtils.java | 24 +- .../rpc/protocol/tri/TripleConstant.java | 3 - .../tri/TripleCustomerProtocolWapper.java | 61 +- .../rpc/protocol/tri/TripleHeaderEnum.java | 8 +- .../tri/TripleHttp2FrameCodecBuilder.java | 8 +- .../rpc/protocol/tri/TripleHttp2Protocol.java | 89 +- .../dubbo/rpc/protocol/tri/TripleInvoker.java | 126 +- .../rpc/protocol/tri/TriplePathResolver.java | 2 - .../protocol/tri/TriplePingPongHandler.java | 14 +- .../rpc/protocol/tri/TripleProtocol.java | 79 +- ...ripleReflectionTypeDescriberRegistrar.java | 5 +- .../protocol/tri/call/AbstractServerCall.java | 149 +- .../tri/call/AbstractServerCallListener.java | 30 +- .../tri/call/BiStreamServerCallListener.java | 8 +- .../rpc/protocol/tri/call/ClientCall.java | 6 +- .../ObserverToClientCallListenerAdapter.java | 3 +- .../call/ReflectionAbstractServerCall.java | 85 +- .../rpc/protocol/tri/call/ServerCall.java | 2 - .../call/ServerStreamServerCallListener.java | 12 +- .../tri/call/StubAbstractServerCall.java | 36 +- .../protocol/tri/call/TripleClientCall.java | 127 +- .../tri/call/UnaryClientCallListener.java | 6 +- .../tri/call/UnaryServerCallListener.java | 12 +- .../tri/command/CancelQueueCommand.java | 5 +- .../tri/command/CreateStreamQueueCommand.java | 15 +- .../tri/command/DataQueueCommand.java | 13 +- .../tri/command/EndStreamQueueCommand.java | 4 +- .../tri/command/HeaderQueueCommand.java | 10 +- .../protocol/tri/command/QueuedCommand.java | 2 - .../tri/command/StreamQueueCommand.java | 4 +- .../tri/command/TextDataQueueCommand.java | 7 +- .../rpc/protocol/tri/compressor/Bzip2.java | 7 +- .../protocol/tri/compressor/Compressor.java | 2 - .../protocol/tri/compressor/DeCompressor.java | 2 - .../rpc/protocol/tri/compressor/Gzip.java | 2 - .../rpc/protocol/tri/compressor/Identity.java | 1 - .../tri/compressor/MessageEncoding.java | 1 - .../rpc/protocol/tri/compressor/Snappy.java | 1 - .../rpc/protocol/tri/frame/Deframer.java | 1 - .../rpc/protocol/tri/frame/TriDecoder.java | 9 +- .../tri/h12/AbstractServerCallListener.java | 31 +- .../h12/AbstractServerTransportListener.java | 114 +- .../tri/h12/BiStreamServerCallListener.java | 8 +- .../tri/h12/DefaultHttpMessageListener.java | 4 +- .../tri/h12/ServerCallToObserverAdapter.java | 1 - .../h12/ServerStreamServerCallListener.java | 10 +- .../tri/h12/TripleProtocolDetector.java | 9 +- .../tri/h12/UnaryServerCallListener.java | 10 +- .../tri/h12/grpc/GrpcCompositeCodec.java | 18 +- .../tri/h12/grpc/GrpcHeaderNames.java | 1 - .../GrpcHttp2ServerTransportListener.java | 45 +- .../rpc/protocol/tri/h12/grpc/GrpcUtils.java | 5 +- .../grpc/StreamingHttpMessageListener.java | 3 +- .../tri/h12/grpc/WrapperHttpMessageCodec.java | 27 +- .../DefaultHttp11ServerTransportListener.java | 24 +- ...tHttp11ServerTransportListenerFactory.java | 3 +- .../GenericHttp2ServerTransportListener.java | 35 +- ...icHttp2ServerTransportListenerFactory.java | 4 +- .../Http2ServerCallToObserverAdapter.java | 3 +- .../h12/http2/Http2ServerStreamObserver.java | 3 +- .../tri/observer/CallStreamObserver.java | 3 - .../observer/ClientCallToObserverAdapter.java | 7 +- .../observer/ServerCallToObserverAdapter.java | 11 +- .../tri/service/HealthStatusManager.java | 1 - .../tri/service/ReflectionV1AlphaService.java | 89 +- .../tri/service/SchemaDescriptorRegistry.java | 12 +- .../tri/service/TriBuiltinService.java | 21 +- .../protocol/tri/service/TriHealthImpl.java | 40 +- .../protocol/tri/stream/AbstractStream.java | 2 - .../rpc/protocol/tri/stream/ClientStream.java | 17 +- .../rpc/protocol/tri/stream/ServerStream.java | 9 +- .../dubbo/rpc/protocol/tri/stream/Stream.java | 8 +- .../rpc/protocol/tri/stream/StreamUtils.java | 51 +- .../tri/stream/TripleClientStream.java | 148 +- .../tri/stream/TripleServerStream.java | 225 +- .../tri/stream/TripleStreamChannelFuture.java | 6 +- .../AbstractH2TransportListener.java | 21 +- .../tri/transport/GracefulShutdown.java | 21 +- .../tri/transport/H2TransportListener.java | 3 - .../TripleCommandOutBoundHandler.java | 1 - .../tri/transport/TripleGoAwayHandler.java | 10 +- .../TripleHttp2ClientResponseHandler.java | 29 +- .../TripleHttp2FrameServerHandler.java | 42 +- .../TripleIsolationExecutorSupport.java | 16 +- .../TripleServerConnectionHandler.java | 29 +- .../tri/transport/TripleTailHandler.java | 1 - .../tri/transport/TripleWriteQueue.java | 11 +- .../protocol/tri/transport/WriteQueue.java | 10 +- .../dubbo/rpc/stub/StubInvocationUtil.java | 42 +- .../dubbo/rpc/StatusRpcExceptionTest.java | 5 +- .../apache/dubbo/rpc/TriRpcStatusTest.java | 94 +- .../tri/CancelableStreamObserverTest.java | 16 +- .../rpc/protocol/tri/ClassLoadUtilTest.java | 1 - .../rpc/protocol/tri/DeadlineFutureTest.java | 16 +- .../rpc/protocol/tri/DescriptorService.java | 5 - .../rpc/protocol/tri/ExceptionUtilsTest.java | 61 +- .../dubbo/rpc/protocol/tri/HelloReply.java | 2 - .../tri/Http2ProtocolDetectorTest.java | 10 +- .../dubbo/rpc/protocol/tri/PbUnpackTest.java | 10 +- .../tri/ReflectionPackableMethodTest.java | 52 +- .../protocol/tri/SingleProtobufUtilsTest.java | 14 +- .../tri/TripleCustomerProtocolWapperTest.java | 191 +- .../rpc/protocol/tri/TripleInvokerTest.java | 20 +- .../protocol/tri/TriplePathResolverTest.java | 10 +- .../rpc/protocol/tri/TripleProtocolTest.java | 40 +- .../rpc/protocol/tri/call/ClientCallTest.java | 6 +- .../tri/call/ReflectionServerCallTest.java | 50 +- .../protocol/tri/call/StubServerCallTest.java | 35 +- .../protocol/tri/compressor/Bzip2Test.java | 19 +- .../rpc/protocol/tri/compressor/GzipTest.java | 19 +- .../protocol/tri/compressor/IdentityTest.java | 5 +- .../protocol/tri/compressor/SnappyTest.java | 18 +- .../protocol/tri/frame/RecordListener.java | 1 - .../protocol/tri/frame/TriDecoderTest.java | 2 - .../tri/service/HealthStatusManagerTest.java | 30 +- .../tri/service/TriBuiltinServiceTest.java | 10 +- .../tri/service/TriHealthImplTest.java | 55 +- .../tri/stream/MockClientStreamListener.java | 8 +- .../protocol/tri/stream/StreamUtilsTest.java | 24 +- .../tri/stream/TripleClientStreamTest.java | 50 +- .../rpc/protocol/tri/support/IGreeter.java | 26 +- .../protocol/tri/support/IGreeter2Impl.java | 4 +- .../tri/support/IGreeterException.java | 2 +- .../protocol/tri/support/IGreeterImpl.java | 27 +- .../tri/support/MockStreamObserver.java | 24 +- .../AbstractH2TransportListenerTest.java | 24 +- .../TripleHttp2ClientResponseHandlerTest.java | 6 +- .../tri/transport/WriteQueueTest.java | 42 +- .../rpc/stub/StubInvocationUtilTest.java | 37 +- dubbo-rpc/pom.xml | 59 +- .../dubbo-serialization-api/pom.xml | 46 +- .../dubbo/common/serialize/Constants.java | 1 - .../DefaultMultipleSerialization.java | 12 +- .../DefaultSerializationExceptionWrapper.java | 6 - .../serialize/MultipleSerialization.java | 5 +- .../dubbo/common/serialize/ObjectInput.java | 1 - .../dubbo/common/serialize/ObjectOutput.java | 1 - .../dubbo/common/serialize/Serialization.java | 3 +- .../serialize/SerializationException.java | 1 - .../support/DefaultSerializationSelector.java | 7 +- .../support/SerializableClassRegistry.java | 1 - .../dubbo-serialization-fastjson2/pom.xml | 55 +- .../fastjson2/FastJson2ObjectInput.java | 86 +- .../fastjson2/FastJson2ObjectOutput.java | 46 +- .../fastjson2/FastJson2Serialization.java | 29 +- .../fastjson2/Fastjson2CreatorManager.java | 15 +- .../Fastjson2ScopeModelInitializer.java | 8 +- .../fastjson2/Fastjson2SecurityManager.java | 75 +- .../fastjson2/FastJson2SerializationTest.java | 105 +- .../serialize/fastjson2/TypeMatchTest.java | 38 +- .../dubbo-serialization-hessian2/pom.xml | 54 +- .../hessian2/Hessian2ClassLoaderListener.java | 3 +- .../hessian2/Hessian2FactoryManager.java | 19 +- .../hessian2/Hessian2ObjectInput.java | 39 +- .../hessian2/Hessian2ObjectOutput.java | 15 +- .../Hessian2ScopeModelInitializer.java | 8 +- .../hessian2/Hessian2Serialization.java | 15 +- .../hessian2/Hessian2SerializerFactory.java | 16 +- .../hessian2/Hessian2SerializationTest.java | 109 +- .../serialize/hessian2/TypeMatchTest.java | 45 +- .../dubbo-serialization-jdk/pom.xml | 54 +- .../java/CompactedJavaSerialization.java | 1 - .../java/CompactedObjectInputStream.java | 1 - .../serialize/java/JavaObjectInput.java | 4 +- .../serialize/java/JavaSerialization.java | 21 +- .../nativejava/NativeJavaObjectInput.java | 3 +- .../nativejava/NativeJavaObjectOutput.java | 1 - .../nativejava/NativeJavaSerialization.java | 21 +- dubbo-serialization/pom.xml | 57 +- .../dubbo-spring-boot-actuator/pom.xml | 198 +- ...boEndpointAnnotationAutoConfiguration.java | 1 - .../DubboMetricsAutoConfiguration.java | 9 +- .../DubboConfigsMetadataEndpoint.java | 4 +- .../endpoint/DubboMetadataEndpoint.java | 5 +- .../DubboPropertiesMetadataEndpoint.java | 4 +- .../DubboReferencesMetadataEndpoint.java | 4 +- .../DubboServicesMetadataEndpoint.java | 4 +- .../endpoint/DubboShutdownEndpoint.java | 5 +- ...ompatibleConditionalOnEnabledEndpoint.java | 8 +- .../CompatibleOnEnabledEndpointCondition.java | 14 +- .../actuate/mertics/DubboMetricsBinder.java | 13 +- ...dpointAnnotationAutoConfigurationTest.java | 83 +- .../actuate/endpoint/DubboEndpointTest.java | 19 +- .../dubbo-spring-boot-autoconfigure/pom.xml | 110 +- .../BinderDubboConfigBinder.java | 20 +- ...DubboRelaxedBinding2AutoConfiguration.java | 10 +- .../BinderDubboConfigBinderTest.java | 6 +- ...oRelaxedBinding2AutoConfigurationTest.java | 20 +- ...ropertiesEnvironmentPostProcessorTest.java | 6 +- .../actuator/pom.xml | 148 +- .../DubboEndpointAutoConfiguration.java | 12 +- ...ubboEndpointMetadataAutoConfiguration.java | 18 +- ...DubboHealthIndicatorAutoConfiguration.java | 5 +- ...ndpointManagementContextConfiguration.java | 5 +- .../boot/actuate/endpoint/DubboEndpoint.java | 5 +- .../metadata/AbstractDubboMetadata.java | 21 +- .../metadata/DubboConfigsMetadata.java | 15 +- .../endpoint/metadata/DubboMetadata.java | 4 +- .../metadata/DubboPropertiesMetadata.java | 4 +- .../metadata/DubboReferencesMetadata.java | 11 +- .../metadata/DubboServicesMetadata.java | 9 +- .../metadata/DubboShutdownMetadata.java | 11 +- .../endpoint/mvc/DubboMvcEndpoint.java | 34 +- .../actuate/health/DubboHealthIndicator.java | 32 +- .../DubboHealthIndicatorProperties.java | 7 +- .../DubboEndpointAutoConfigurationTest.java | 81 +- .../health/DubboHealthIndicatorTest.java | 38 +- .../autoconfigure/pom.xml | 144 +- .../autoconfigure/DubboAutoConfiguration.java | 16 +- .../DubboConfigurationProperties.java | 5 +- .../DubboRelaxedBindingAutoConfiguration.java | 5 +- .../RelaxedDubboConfigBinder.java | 12 +- .../ServiceBeanIdConflictProcessor.java | 16 +- .../DubboApplicationContextInitializer.java | 1 - .../AwaitingNonWebApplicationListener.java | 21 +- ...DefinitionConflictApplicationListener.java | 37 +- .../event/WelcomeLogoApplicationListener.java | 19 +- ...ultPropertiesEnvironmentPostProcessor.java | 18 +- .../dubbo/spring/boot/util/DubboUtils.java | 17 +- .../apache/dubbo/spring/boot/TestSuite.java | 23 +- .../CompatibleDubboAutoConfigurationTest.java | 12 +- ...utoConfigurationTestWithoutProperties.java | 10 +- ...AutoConfigurationOnMultipleConfigTest.java | 50 +- ...boAutoConfigurationOnSingleConfigTest.java | 30 +- .../RelaxedDubboConfigBinderTest.java | 24 +- ...AwaitingNonWebApplicationListenerTest.java | 58 +- ...nitionConflictApplicationListenerTest.java | 24 +- .../WelcomeLogoApplicationListenerTest.java | 6 +- ...ropertiesEnvironmentPostProcessorTest.java | 4 +- .../spring/boot/util/DubboUtilsTest.java | 3 - .../metadata/pom.xml | 326 +- ...ubboMetadataGenerateAutoConfiguration.java | 3 +- .../dubbo-spring-boot-compatible/pom.xml | 111 +- .../dubbo-spring-boot-interceptor/pom.xml | 63 +- .../DubboTagCookieInterceptor.java | 16 +- .../DubboTagHeaderOrParameterInterceptor.java | 10 +- .../dubbo-spring-boot-starter/pom.xml | 50 +- .../dubbo-nacos-spring-boot-starter/pom.xml | 43 +- .../dubbo-seata-spring-boot-starter/pom.xml | 65 +- .../pom.xml | 51 +- .../pom.xml | 76 +- .../pom.xml | 54 +- .../observability/autoconfigure/pom.xml | 262 +- ...bboMicrometerTracingAutoConfiguration.java | 21 +- .../DubboObservationAutoConfiguration.java | 75 +- .../autoconfigure/ObservabilityUtils.java | 15 +- .../ObservationHandlerGrouping.java | 13 +- .../ObservationRegistryPostProcessor.java | 15 +- .../ConditionalOnDubboTracingEnable.java | 7 +- .../brave/BraveAutoConfiguration.java | 135 +- .../exporter/otlp/OtlpAutoConfiguration.java | 8 +- .../exporter/zipkin/HttpSender.java | 16 +- .../zipkin/ZipkinAutoConfiguration.java | 16 +- .../exporter/zipkin/ZipkinConfigurations.java | 62 +- .../zipkin/ZipkinRestTemplateSender.java | 2 - .../zipkin/ZipkinWebClientSender.java | 5 +- .../ZipkinRestTemplateBuilderCustomizer.java | 1 - .../ZipkinWebClientBuilderCustomizer.java | 3 - .../otel/OpenTelemetryAutoConfiguration.java | 158 +- ...crometerTracingAutoConfigurationTests.java | 35 +- .../pom.xml | 48 +- .../pom.xml | 56 +- .../pom.xml | 56 +- .../pom.xml | 56 +- .../observability/pom.xml | 128 +- .../dubbo-spring-boot-starters/pom.xml | 42 +- dubbo-spring-boot/pom.xml | 334 +- dubbo-test/dubbo-dependencies-all/pom.xml | 1135 ++- dubbo-test/dubbo-test-check/pom.xml | 154 +- ...ctRegistryCenterTestExecutionListener.java | 18 +- .../dubbo/test/check/DubboTestChecker.java | 60 +- .../test/check/RegistryCenterFinished.java | 5 +- .../check/exception/DubboTestException.java | 1 - .../test/check/registrycenter/Config.java | 2 +- .../test/check/registrycenter/Context.java | 3 +- .../ZookeeperRegistryCenter.java | 13 +- .../config/ZookeeperConfig.java | 14 +- .../context/ZookeeperWindowsContext.java | 17 +- .../ConfigZookeeperInitializer.java | 31 +- .../DownloadZookeeperInitializer.java | 115 +- .../UnpackZookeeperInitializer.java | 36 +- .../processor/FindPidWindowsProcessor.java | 23 +- .../KillProcessWindowsProcessor.java | 7 +- .../processor/ResetZookeeperProcessor.java | 10 +- .../StartZookeeperUnixProcessor.java | 20 +- .../StartZookeeperWindowsProcessor.java | 20 +- .../processor/StopZookeeperUnixProcessor.java | 20 +- .../processor/ZookeeperUnixProcessor.java | 12 +- .../processor/ZookeeperWindowsProcessor.java | 1 + dubbo-test/dubbo-test-common/pom.xml | 79 +- .../dubbo/test/common/ErrorHandler.java | 1 - .../apache/dubbo/test/common/SysProps.java | 1 - .../dubbo/test/common/api/DemoService.java | 1 - .../test/common/api/RestDemoService.java | 1 - .../test/common/impl/DemoServiceImpl.java | 10 +- .../test/common/impl/GreetingServiceImpl.java | 1 - .../test/common/impl/RestDemoServiceImpl.java | 2 - dubbo-test/dubbo-test-modules/pom.xml | 56 +- .../org/apache/dubbo/dependency/FileTest.java | 471 +- dubbo-test/dubbo-test-spring/pom.xml | 327 +- .../test/spring/SpringAnnotationBeanTest.java | 5 +- .../test/spring/SpringJavaConfigBeanTest.java | 19 +- .../test/spring/SpringXmlConfigTest.java | 3 +- .../context/MockSpringInitCustomizer.java | 21 +- dubbo-test/dubbo-test-spring3.2/pom.xml | 182 +- dubbo-test/dubbo-test-spring4.1/pom.xml | 182 +- dubbo-test/dubbo-test-spring4.2/pom.xml | 182 +- dubbo-test/pom.xml | 49 +- dubbo-xds/pom.xml | 200 +- .../xds/XdsInitializationException.java | 12 +- .../dubbo/registry/xds/XdsRegistry.java | 16 +- .../registry/xds/XdsServiceDiscovery.java | 35 +- .../xds/XdsServiceDiscoveryFactory.java | 10 +- .../istio/IstioCitadelCertificateSigner.java | 108 +- .../registry/xds/istio/IstioConstant.java | 61 +- .../dubbo/registry/xds/istio/IstioEnv.java | 63 +- .../dubbo/registry/xds/util/AdsObserver.java | 38 +- .../dubbo/registry/xds/util/NodeBuilder.java | 12 +- .../registry/xds/util/PilotExchanger.java | 127 +- .../dubbo/registry/xds/util/XdsChannel.java | 92 +- .../xds/util/bootstrap/BootstrapInfoImpl.java | 40 +- .../xds/util/bootstrap/Bootstrapper.java | 10 +- .../xds/util/bootstrap/BootstrapperImpl.java | 39 +- .../CertificateProviderInfoImpl.java | 6 +- .../xds/util/bootstrap/ServerInfoImpl.java | 17 +- .../xds/util/protocol/AbstractProtocol.java | 56 +- .../util/protocol/delta/DeltaEndpoint.java | 5 +- .../util/protocol/delta/DeltaListener.java | 4 +- .../xds/util/protocol/impl/EdsProtocol.java | 31 +- .../xds/util/protocol/impl/LdsProtocol.java | 37 +- .../xds/util/protocol/impl/RdsProtocol.java | 40 +- .../xds/util/protocol/message/Endpoint.java | 19 +- .../util/protocol/message/EndpointResult.java | 4 +- .../util/protocol/message/ListenerResult.java | 4 +- .../util/protocol/message/RouteResult.java | 12 +- .../router/xds/EdsEndpointListener.java | 2 - .../router/xds/EdsEndpointManager.java | 47 +- .../router/xds/RdsRouteRuleManager.java | 28 +- .../router/xds/RdsVirtualHostListener.java | 52 +- .../router/xds/XdsRouteRuleListener.java | 2 - .../rpc/cluster/router/xds/XdsRouter.java | 52 +- .../router/xds/XdsScopeModelInitializer.java | 7 +- .../router/xds/rule/ClusterWeight.java | 1 - .../router/xds/rule/DestinationSubset.java | 1 - .../router/xds/rule/HTTPRouteDestination.java | 1 - .../router/xds/rule/HeaderMatcher.java | 2 - .../router/xds/rule/HttpRequestMatch.java | 2 - .../router/xds/rule/LongRangeMatch.java | 2 - .../cluster/router/xds/rule/PathMatcher.java | 9 +- .../cluster/router/xds/rule/XdsRouteRule.java | 4 - .../xds/util/bootstrap/BootstrapperTest.java | 193 +- .../util/protocol/impl/DsProtocolTest.java | 542 -- .../util/protocol/impl/EdsProtocolMock.java | 13 +- .../util/protocol/impl/LdsProtocolMock.java | 20 +- .../util/protocol/impl/RdsProtocolMock.java | 13 +- .../router/xds/EdsEndpointManagerTest.java | 18 +- .../router/xds/RdsRouteRuleManagerTest.java | 29 +- .../xds/RdsVirtualHostListenerTest.java | 191 +- .../rpc/cluster/router/xds/XdsRouteTest.java | 193 +- .../router/xds/rule/HeaderMatcherTest.java | 3 - .../router/xds/rule/PathMatcherTest.java | 3 - pom.xml | 1683 ++-- 3497 files changed, 57977 insertions(+), 54188 deletions(-) delete mode 100644 dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/RouterChainTest.java delete mode 100644 dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/metadata/MetadataServiceExporterTest.java delete mode 100644 dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/DemoService.java delete mode 100644 dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/ServiceNameMappingTest.java delete mode 100644 dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/FileSystemServiceDiscovery.java delete mode 100644 dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/FileSystemServiceDiscoveryTest.java delete mode 100644 dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryTest.java delete mode 100644 dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/fastjson/DefaultServiceInstanceDeserializerTest.java delete mode 100644 dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtilsTest.java delete mode 100644 dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/InMemoryMetadataServiceTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ImplicitCallBackTest.java delete mode 100644 dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/protocol/impl/DsProtocolTest.java diff --git a/dubbo-cluster/pom.xml b/dubbo-cluster/pom.xml index c21fab1581..0939998741 100644 --- a/dubbo-cluster/pom.xml +++ b/dubbo-cluster/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - org.apache.dubbo - dubbo-parent - ${revision} - ../pom.xml - - dubbo-cluster - jar - ${project.artifactId} - The cluster module of dubbo project - - false - 15.4 - - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - - - org.yaml - snakeyaml - - - org.apache.dubbo - dubbo-rpc-injvm - ${project.parent.version} - test - - - org.apache.curator - curator-framework - test - - - org.apache.zookeeper - zookeeper - test - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-test-check - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-metrics-registry - ${project.parent.version} - compile - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - true - - - io.micrometer - micrometer-tracing-integration-test - test - - - org.slf4j - slf4j-log4j12 - test - - + + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + + dubbo-cluster + jar + ${project.artifactId} + The cluster module of dubbo project + + false + 15.4 + + + + org.apache.dubbo + dubbo-rpc-api + ${project.parent.version} + + + org.yaml + snakeyaml + + + org.apache.dubbo + dubbo-rpc-injvm + ${project.parent.version} + test + + + org.apache.curator + curator-framework + test + + + org.apache.zookeeper + zookeeper + test + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-test-check + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-metrics-registry + ${project.parent.version} + compile + + + org.apache.dubbo + dubbo-metrics-default + ${project.parent.version} + true + + + io.micrometer + micrometer-tracing-integration-test + test + + + org.slf4j + slf4j-log4j12 + test + + - - - - nashorn-jdk11 - - [11,) - - - - org.openjdk.nashorn - nashorn-core - ${nashorn-core.version} - test - - - - + + nashorn-jdk11 + + [11,) + + + + org.openjdk.nashorn + nashorn-core + ${nashorn-core.version} + test + + + + diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/registry/AddressListener.java b/dubbo-cluster/src/main/java/org/apache/dubbo/registry/AddressListener.java index e45c6e8cd4..c72655478f 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/registry/AddressListener.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/registry/AddressListener.java @@ -35,8 +35,5 @@ public interface AddressListener { */ List notify(List addresses, URL consumerUrl, Directory registryDirectory); - default void destroy(URL consumerUrl, Directory registryDirectory) { - - } - + default void destroy(URL consumerUrl, Directory registryDirectory) {} } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Cluster.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Cluster.java index 909693cb90..0ddc3628af 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Cluster.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Cluster.java @@ -55,6 +55,8 @@ public interface Cluster { if (StringUtils.isEmpty(name)) { name = Cluster.DEFAULT; } - return ScopeModelUtil.getApplicationModel(scopeModel).getExtensionLoader(Cluster.class).getExtension(name, wrap); + return ScopeModelUtil.getApplicationModel(scopeModel) + .getExtensionLoader(Cluster.class) + .getExtension(name, wrap); } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ClusterScopeModelInitializer.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ClusterScopeModelInitializer.java index ede8f85f03..fb9d23b0c3 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ClusterScopeModelInitializer.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ClusterScopeModelInitializer.java @@ -38,6 +38,5 @@ public class ClusterScopeModelInitializer implements ScopeModelInitializer { } @Override - public void initializeModuleModel(ModuleModel moduleModel) { - } + public void initializeModuleModel(ModuleModel moduleModel) {} } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.java index 1f1df9c200..f99b05ac87 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Configurator.java @@ -51,7 +51,6 @@ public interface Configurator extends Comparable { */ URL configure(URL url); - /** * Convert override urls to map for use when re-refer. Send all rules every time, the urls will be reassembled and * calculated @@ -73,7 +72,9 @@ public interface Configurator extends Comparable { return Optional.empty(); } - ConfiguratorFactory configuratorFactory = urls.get(0).getOrDefaultApplicationModel().getExtensionLoader(ConfiguratorFactory.class) + ConfiguratorFactory configuratorFactory = urls.get(0) + .getOrDefaultApplicationModel() + .getExtensionLoader(ConfiguratorFactory.class) .getAdaptiveExtension(); List configurators = new ArrayList<>(urls.size()); @@ -83,7 +84,8 @@ public interface Configurator extends Comparable { break; } Map override = new HashMap<>(url.getParameters()); - //The anyhost parameter of override may be added automatically, it can't change the judgement of changing url + // The anyhost parameter of override may be added automatically, it can't change the judgement of changing + // url override.remove(ANYHOST_KEY); if (CollectionUtils.isEmptyMap(override)) { continue; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ConfiguratorFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ConfiguratorFactory.java index 031f597dc0..920d936cb6 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ConfiguratorFactory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ConfiguratorFactory.java @@ -36,5 +36,4 @@ public interface ConfiguratorFactory { */ @Adaptive(CommonConstants.PROTOCOL_KEY) Configurator getConfigurator(URL url); - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Constants.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Constants.java index ab8c50b568..0e59f2cacf 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Constants.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Constants.java @@ -100,7 +100,6 @@ public interface Constants { String OVERRIDE_PROVIDERS_KEY = "providerAddresses"; - /** * key for router type, for e.g., "script"/"file", corresponding to ScriptRouterFactory.NAME, FileRouterFactory.NAME */ diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/LoadBalance.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/LoadBalance.java index 94b28a8bc3..42a556d2c6 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/LoadBalance.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/LoadBalance.java @@ -46,5 +46,4 @@ public interface LoadBalance { */ @Adaptive("loadbalance") Invoker select(List> invokers, URL url, Invocation invocation) throws RpcException; - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Merger.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Merger.java index 64bccf8cbd..b505772ccc 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Merger.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Merger.java @@ -22,5 +22,4 @@ import org.apache.dubbo.common.extension.SPI; public interface Merger { T merge(T... items); - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ProviderURLMergeProcessor.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ProviderURLMergeProcessor.java index f38424e4df..4421755bbc 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ProviderURLMergeProcessor.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/ProviderURLMergeProcessor.java @@ -33,7 +33,9 @@ public interface ProviderURLMergeProcessor { */ URL mergeUrl(URL remoteUrl, Map localParametersMap); - default Map mergeLocalParams(Map localMap) { return localMap; } + default Map mergeLocalParams(Map localMap) { + return localMap; + } default boolean accept(URL providerUrl, Map localParametersMap) { return true; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Router.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Router.java index 23c4fefca7..678888b4ec 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Router.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/Router.java @@ -68,8 +68,8 @@ public interface Router extends Comparable { * @return state with route result * @throws RpcException */ - default RouterResult> route(List> invokers, URL url, Invocation invocation, - boolean needToPrintMessage) throws RpcException { + default RouterResult> route( + List> invokers, URL url, Invocation invocation, boolean needToPrintMessage) throws RpcException { return new RouterResult<>(route(invokers, url, invocation)); } @@ -80,9 +80,7 @@ public interface Router extends Comparable { * @param invokers invoker list * @param invoker's type */ - default void notify(List> invokers) { - - } + default void notify(List> invokers) {} /** * To decide whether this router need to execute every time an RPC comes or should only execute when addresses or @@ -109,7 +107,7 @@ public interface Router extends Comparable { int getPriority(); default void stop() { - //do nothing by default + // do nothing by default } @Override diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterChain.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterChain.java index e0d15af1fe..895aa582ba 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterChain.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RouterChain.java @@ -16,12 +16,6 @@ */ package org.apache.dubbo.rpc.cluster; -import java.util.List; -import java.util.concurrent.atomic.AtomicReference; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.stream.Collectors; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.constants.LoggerCodeConstants; @@ -36,6 +30,12 @@ import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ScopeModelUtil; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.stream.Collectors; + import static org.apache.dubbo.rpc.cluster.Constants.ROUTER_KEY; /** @@ -52,31 +52,30 @@ public class RouterChain { public static RouterChain buildChain(Class interfaceClass, URL url) { SingleRouterChain chain1 = buildSingleChain(interfaceClass, url); SingleRouterChain chain2 = buildSingleChain(interfaceClass, url); - return new RouterChain<>(new SingleRouterChain[]{chain1, chain2}); + return new RouterChain<>(new SingleRouterChain[] {chain1, chain2}); } public static SingleRouterChain buildSingleChain(Class interfaceClass, URL url) { ModuleModel moduleModel = url.getOrDefaultModuleModel(); - List extensionFactories = moduleModel.getExtensionLoader(RouterFactory.class) - .getActivateExtension(url, ROUTER_KEY); + List extensionFactories = + moduleModel.getExtensionLoader(RouterFactory.class).getActivateExtension(url, ROUTER_KEY); List routers = extensionFactories.stream() - .map(factory -> factory.getRouter(url)) - .sorted(Router::compareTo) - .collect(Collectors.toList()); + .map(factory -> factory.getRouter(url)) + .sorted(Router::compareTo) + .collect(Collectors.toList()); - List> stateRouters = moduleModel - .getExtensionLoader(StateRouterFactory.class) - .getActivateExtension(url, ROUTER_KEY) - .stream() - .map(factory -> factory.getRouter(interfaceClass, url)) - .collect(Collectors.toList()); + List> stateRouters = + moduleModel.getExtensionLoader(StateRouterFactory.class).getActivateExtension(url, ROUTER_KEY).stream() + .map(factory -> factory.getRouter(interfaceClass, url)) + .collect(Collectors.toList()); + boolean shouldFailFast = Boolean.parseBoolean( + ConfigurationUtils.getProperty(moduleModel, Constants.SHOULD_FAIL_FAST_KEY, "true")); - boolean shouldFailFast = Boolean.parseBoolean(ConfigurationUtils.getProperty(moduleModel, Constants.SHOULD_FAIL_FAST_KEY, "true")); - - RouterSnapshotSwitcher routerSnapshotSwitcher = ScopeModelUtil.getFrameworkModel(moduleModel).getBeanFactory().getBean(RouterSnapshotSwitcher.class); + RouterSnapshotSwitcher routerSnapshotSwitcher = + ScopeModelUtil.getFrameworkModel(moduleModel).getBeanFactory().getBean(RouterSnapshotSwitcher.class); return new SingleRouterChain<>(routers, stateRouters, shouldFailFast, routerSnapshotSwitcher); } @@ -106,9 +105,9 @@ public class RouterChain { // If `availableInvokers` is created from origin invokers => use backup chain // If `availableInvokers` is created from newly invokers => use main chain BitList> notifying = notifyingInvokers.get(); - if (notifying != null && - currentChain == backupChain && - availableInvokers.getOriginList() == notifying.getOriginList()) { + if (notifying != null + && currentChain == backupChain + && availableInvokers.getOriginList() == notifying.getOriginList()) { return mainChain; } return currentChain; @@ -140,7 +139,8 @@ public class RouterChain { } // Refresh main chain. - // No one can request to use main chain. `currentChain` is backup chain. `route` method cannot access main chain. + // No one can request to use main chain. `currentChain` is backup chain. `route` method cannot access main + // chain. try { // Lock main chain to wait all invocation end // To wait until no one is using main chain. @@ -157,26 +157,32 @@ public class RouterChain { } // Set the reference of newly invokers to temp variable. - // Reason: The next step will switch the invokers reference in directory, so we should check the `availableInvokers` - // argument when `route`. If the current invocation use newly invokers, we should use main chain to route, and + // Reason: The next step will switch the invokers reference in directory, so we should check the + // `availableInvokers` + // argument when `route`. If the current invocation use newly invokers, we should use main chain to + // route, and // this can prevent use newly invokers to route backup chain, which can only route origin invokers now. notifyingInvokers.set(invokers); // Switch the invokers reference in directory. - // Cannot switch before update main chain or after backup chain update success. Or that will cause state inconsistent. + // Cannot switch before update main chain or after backup chain update success. Or that will cause state + // inconsistent. switchAction.run(); try { // Lock to prevent directory continue list - // The invokers reference in directory now should be the newly one and should always use the newly one once lock released. + // The invokers reference in directory now should be the newly one and should always use the newly one once + // lock released. lock.writeLock().lock(); // Switch to main chain. Will update backup chain later. currentChain = mainChain; // Clean up temp variable. - // `availableInvokers` check is useless now, because `route` method will no longer receive any `availableInvokers` related - // with the origin invokers. The getter of invokers reference in directory is locked now, and will return newly invokers + // `availableInvokers` check is useless now, because `route` method will no longer receive any + // `availableInvokers` related + // with the origin invokers. The getter of invokers reference in directory is locked now, and will return + // newly invokers // once lock released. notifyingInvokers.set(null); } finally { @@ -186,7 +192,8 @@ public class RouterChain { } // Refresh main chain. - // No one can request to use main chain. `currentChain` is main chain. `route` method cannot access backup chain. + // No one can request to use main chain. `currentChain` is main chain. `route` method cannot access backup + // chain. try { // Lock main chain to wait all invocation end backupChain.getLock().writeLock().lock(); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RuleConverter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RuleConverter.java index f2cecdc4d7..211e03a56a 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RuleConverter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/RuleConverter.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster; import org.apache.dubbo.common.URL; @@ -26,5 +25,4 @@ import java.util.List; public interface RuleConverter { List convert(URL subscribeUrl, Object source); - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/SingleRouterChain.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/SingleRouterChain.java index 278722eded..c217bdb0d6 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/SingleRouterChain.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/SingleRouterChain.java @@ -16,13 +16,6 @@ */ package org.apache.dubbo.rpc.cluster; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -40,6 +33,13 @@ import org.apache.dubbo.rpc.cluster.router.state.BitList; import org.apache.dubbo.rpc.cluster.router.state.StateRouter; import org.apache.dubbo.rpc.cluster.router.state.TailStateRouter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_STOP; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_NO_VALID_PROVIDER; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; @@ -79,7 +79,11 @@ public class SingleRouterChain { private final ReadWriteLock lock = new ReentrantReadWriteLock(); - public SingleRouterChain(List routers, List> stateRouters, boolean shouldFailFast, RouterSnapshotSwitcher routerSnapshotSwitcher) { + public SingleRouterChain( + List routers, + List> stateRouters, + boolean shouldFailFast, + RouterSnapshotSwitcher routerSnapshotSwitcher) { initWithRouters(routers); initWithStateRouters(stateRouters); @@ -134,9 +138,12 @@ public class SingleRouterChain { public List> route(URL url, BitList> availableInvokers, Invocation invocation) { if (invokers.getOriginList() != availableInvokers.getOriginList()) { - logger.error(INTERNAL_ERROR, "", "Router's invoker size: " + invokers.getOriginList().size() + - " Invocation's invoker size: " + availableInvokers.getOriginList().size(), - "Reject to route, because the invokers has changed."); + logger.error( + INTERNAL_ERROR, + "", + "Router's invoker size: " + invokers.getOriginList().size() + " Invocation's invoker size: " + + availableInvokers.getOriginList().size(), + "Reject to route, because the invokers has changed."); throw new IllegalStateException("reject to route, because the invokers has changed."); } if (RpcContext.getServiceContext().isNeedPrintRouterSnapshot()) { @@ -202,7 +209,8 @@ public class SingleRouterChain { /** * Build each router's result */ - public RouterSnapshotNode buildRouterSnapshot(URL url, BitList> availableInvokers, Invocation invocation) { + public RouterSnapshotNode buildRouterSnapshot( + URL url, BitList> availableInvokers, Invocation invocation) { BitList> resultInvokers = availableInvokers.clone(); RouterSnapshotNode parentNode = new RouterSnapshotNode("Parent", resultInvokers.clone()); parentNode.setNodeOutputInvokers(resultInvokers.clone()); @@ -228,7 +236,8 @@ public class SingleRouterChain { // Copy resultInvokers to a arrayList. BitList not support List> inputInvokers = new ArrayList<>(commonRouterResult); - RouterSnapshotNode currentNode = new RouterSnapshotNode(router.getClass().getSimpleName(), inputInvokers); + RouterSnapshotNode currentNode = + new RouterSnapshotNode(router.getClass().getSimpleName(), inputInvokers); // append to router node chain commonRouterNode.appendNode(currentNode); @@ -268,24 +277,27 @@ public class SingleRouterChain { } private void logRouterSnapshot(URL url, Invocation invocation, RouterSnapshotNode snapshotNode) { - if (snapshotNode.getChainOutputInvokers() == null || - snapshotNode.getChainOutputInvokers().isEmpty()) { + if (snapshotNode.getChainOutputInvokers() == null + || snapshotNode.getChainOutputInvokers().isEmpty()) { if (logger.isWarnEnabled()) { String message = "No provider available after route for the service " + url.getServiceKey() - + " from registry " + url.getAddress() - + " on the consumer " + NetUtils.getLocalHost() - + " using the dubbo version " + Version.getVersion() + ". Router snapshot is below: \n" + snapshotNode.toString(); + + " from registry " + url.getAddress() + + " on the consumer " + NetUtils.getLocalHost() + + " using the dubbo version " + Version.getVersion() + ". Router snapshot is below: \n" + + snapshotNode.toString(); if (routerSnapshotSwitcher.isEnable()) { routerSnapshotSwitcher.setSnapshot(message); } - logger.warn(CLUSTER_NO_VALID_PROVIDER, "No provider available after route for the service", "", message); + logger.warn( + CLUSTER_NO_VALID_PROVIDER, "No provider available after route for the service", "", message); } } else { if (logger.isInfoEnabled()) { String message = "Router snapshot service " + url.getServiceKey() - + " from registry " + url.getAddress() - + " on the consumer " + NetUtils.getLocalHost() - + " using the dubbo version " + Version.getVersion() + " is below: \n" + snapshotNode.toString(); + + " from registry " + url.getAddress() + + " on the consumer " + NetUtils.getLocalHost() + + " using the dubbo version " + Version.getVersion() + " is below: \n" + + snapshotNode.toString(); if (routerSnapshotSwitcher.isEnable()) { routerSnapshotSwitcher.setSnapshot(message); } @@ -330,7 +342,12 @@ public class SingleRouterChain { try { router.stop(); } catch (Exception e) { - logger.error(CLUSTER_FAILED_STOP, "route stop failed", "", "Error trying to stop router " + router.getClass(), e); + logger.error( + CLUSTER_FAILED_STOP, + "route stop failed", + "", + "Error trying to stop router " + router.getClass(), + e); } } routers = Collections.emptyList(); @@ -340,7 +357,12 @@ public class SingleRouterChain { try { router.stop(); } catch (Exception e) { - logger.error(CLUSTER_FAILED_STOP, "StateRouter stop failed", "", "Error trying to stop StateRouter " + router.getClass(), e); + logger.error( + CLUSTER_FAILED_STOP, + "StateRouter stop failed", + "", + "Error trying to stop StateRouter " + router.getClass(), + e); } } stateRouters = Collections.emptyList(); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java index 1a6b1381b9..a72956054a 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/AbstractConfigurator.java @@ -72,7 +72,10 @@ public abstract class AbstractConfigurator implements Configurator { @Override public URL configure(URL url) { // If override url is not enabled or is invalid, just return. - if (!configuratorUrl.getParameter(ENABLED_KEY, true) || configuratorUrl.getHost() == null || url == null || url.getHost() == null) { + if (!configuratorUrl.getParameter(ENABLED_KEY, true) + || configuratorUrl.getHost() == null + || url == null + || url.getHost() == null) { logger.info("Cannot apply configurator rule, the rule is disabled or is invalid: \n" + configuratorUrl); return url; } @@ -98,7 +101,9 @@ public abstract class AbstractConfigurator implements Configurator { @Deprecated private URL configureDeprecated(URL url) { - // If override url has port, means it is a provider address. We want to control a specific provider with this override url, it may take effect on the specific provider instance or on consumers holding this provider instance. + // If override url has port, means it is a provider address. We want to control a specific provider with this + // override url, it may take effect on the specific provider instance or on consumers holding this provider + // instance. if (configuratorUrl.getPort() != 0) { if (url.getPort() == configuratorUrl.getPort()) { return configureIfMatch(url.getHost(), url); @@ -131,7 +136,8 @@ public abstract class AbstractConfigurator implements Configurator { if (matcher.isMatch(host, url)) { return doConfigure(url, configuratorUrl.removeParameters(conditionKeys)); } else { - logger.debug("Cannot apply configurator rule, param mismatch, current params are " + url + ", params in rule is " + matcher); + logger.debug("Cannot apply configurator rule, param mismatch, current params are " + url + + ", params in rule is " + matcher); } } else { return doConfigure(url, configuratorUrl.removeParameters(conditionKeys)); @@ -141,7 +147,8 @@ public abstract class AbstractConfigurator implements Configurator { } } } else { - logger.debug("Cannot apply configurator rule, host mismatch, current host is " + host + ", host in rule is " + configuratorUrl.getHost()); + logger.debug("Cannot apply configurator rule, host mismatch, current host is " + host + ", host in rule is " + + configuratorUrl.getHost()); } return url; } @@ -159,15 +166,16 @@ public abstract class AbstractConfigurator implements Configurator { String[] providerAddresses = providers.split(CommonConstants.COMMA_SEPARATOR); for (String address : providerAddresses) { if (address.equals(url.getAddress()) - || address.equals(ANYHOST_VALUE) - || address.equals(ANYHOST_VALUE + CommonConstants.GROUP_CHAR_SEPARATOR + ANY_VALUE) - || address.equals(ANYHOST_VALUE + CommonConstants.GROUP_CHAR_SEPARATOR + url.getPort()) - || address.equals(url.getHost())) { + || address.equals(ANYHOST_VALUE) + || address.equals(ANYHOST_VALUE + CommonConstants.GROUP_CHAR_SEPARATOR + ANY_VALUE) + || address.equals(ANYHOST_VALUE + CommonConstants.GROUP_CHAR_SEPARATOR + url.getPort()) + || address.equals(url.getHost())) { match = true; } } if (!match) { - logger.debug("Cannot apply configurator rule, provider address mismatch, current address " + url.getAddress() + ", address in rule is " + providers); + logger.debug("Cannot apply configurator rule, provider address mismatch, current address " + + url.getAddress() + ", address in rule is " + providers); return false; } } @@ -175,17 +183,18 @@ public abstract class AbstractConfigurator implements Configurator { String configApplication = configuratorUrl.getApplication(configuratorUrl.getUsername()); String currentApplication = url.getApplication(url.getUsername()); if (configApplication != null - && !ANY_VALUE.equals(configApplication) - && !configApplication.equals(currentApplication)) { - logger.debug("Cannot apply configurator rule, application name mismatch, current application is " + currentApplication + ", application in rule is " + configApplication); + && !ANY_VALUE.equals(configApplication) + && !configApplication.equals(currentApplication)) { + logger.debug("Cannot apply configurator rule, application name mismatch, current application is " + + currentApplication + ", application in rule is " + configApplication); return false; } String configServiceKey = configuratorUrl.getServiceKey(); String currentServiceKey = url.getServiceKey(); - if (!ANY_VALUE.equals(configServiceKey) - && !configServiceKey.equals(currentServiceKey)) { - logger.debug("Cannot apply configurator rule, service mismatch, current service is " + currentServiceKey + ", service in rule is " + configServiceKey); + if (!ANY_VALUE.equals(configServiceKey) && !configServiceKey.equals(currentServiceKey)) { + logger.debug("Cannot apply configurator rule, service mismatch, current service is " + currentServiceKey + + ", service in rule is " + configServiceKey); return false; } @@ -202,8 +211,9 @@ public abstract class AbstractConfigurator implements Configurator { if (startWithTilde) { conditionKeys.add(key); } - if (value != null && !ANY_VALUE.equals(value) - && !value.equals(url.getParameter(startWithTilde ? key.substring(1) : key))) { + if (value != null + && !ANY_VALUE.equals(value) + && !value.equals(url.getParameter(startWithTilde ? key.substring(1) : key))) { result = false; break; } @@ -233,5 +243,4 @@ public abstract class AbstractConfigurator implements Configurator { } protected abstract URL doConfigure(URL currentUrl, URL configUrl); - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/absent/AbsentConfigurator.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/absent/AbsentConfigurator.java index bd8a325463..182f9107cb 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/absent/AbsentConfigurator.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/absent/AbsentConfigurator.java @@ -32,5 +32,4 @@ public class AbsentConfigurator extends AbstractConfigurator { public URL doConfigure(URL currentUrl, URL configUrl) { return currentUrl.addParametersIfAbsent(configUrl.getParameters()); } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/absent/AbsentConfiguratorFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/absent/AbsentConfiguratorFactory.java index 479eb5082a..737d67ca12 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/absent/AbsentConfiguratorFactory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/absent/AbsentConfiguratorFactory.java @@ -30,5 +30,4 @@ public class AbsentConfiguratorFactory implements ConfiguratorFactory { public Configurator getConfigurator(URL url) { return new AbsentConfigurator(url); } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/override/OverrideConfigurator.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/override/OverrideConfigurator.java index a61190d7cd..72895aeb8a 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/override/OverrideConfigurator.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/override/OverrideConfigurator.java @@ -36,5 +36,4 @@ public class OverrideConfigurator extends AbstractConfigurator { logger.info("Start overriding url " + currentUrl + " with override url " + configUrl); return currentUrl.addParameters(configUrl.getParameters()); } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/override/OverrideConfiguratorFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/override/OverrideConfiguratorFactory.java index 504ae3b5d7..972eac4cea 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/override/OverrideConfiguratorFactory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/override/OverrideConfiguratorFactory.java @@ -30,5 +30,4 @@ public class OverrideConfiguratorFactory implements ConfiguratorFactory { public Configurator getConfigurator(URL url) { return new OverrideConfigurator(url); } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java index 7a12e0f379..203033c734 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParser.java @@ -23,14 +23,14 @@ import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.cluster.configurator.parser.model.ConfigItem; import org.apache.dubbo.rpc.cluster.configurator.parser.model.ConfiguratorConfig; -import org.yaml.snakeyaml.LoaderOptions; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.SafeConstructor; - import java.util.ArrayList; import java.util.List; import java.util.Map; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.SafeConstructor; + import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.RegistryConstants.APP_DYNAMIC_CONFIGURATORS_CATEGORY; @@ -104,7 +104,12 @@ public class ConfigParser { if (CollectionUtils.isNotEmpty(apps)) { apps.forEach(app -> { StringBuilder tmpUrlBuilder = new StringBuilder(urlBuilder); - urls.add(appendMatchCondition(URL.valueOf(tmpUrlBuilder.append("&application=").append(app).toString()), item)); + urls.add(appendMatchCondition( + URL.valueOf(tmpUrlBuilder + .append("&application=") + .append(app) + .toString()), + item)); }); } else { urls.add(appendMatchCondition(URL.valueOf(urlBuilder.toString()), item)); @@ -155,8 +160,8 @@ public class ConfigParser { } Map parameters = item.getParameters(); if (CollectionUtils.isEmptyMap(parameters)) { - throw new IllegalStateException("Invalid configurator rule, please specify at least one parameter " + - "you want to change in the rule."); + throw new IllegalStateException("Invalid configurator rule, please specify at least one parameter " + + "you want to change in the rule."); } parameters.forEach((k, v) -> { diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ConditionMatch.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ConditionMatch.java index 4a828d4484..853a6ae8df 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ConditionMatch.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ConditionMatch.java @@ -101,12 +101,11 @@ public class ConditionMatch { @Override public String toString() { - return "ConditionMatch{" + - "address='" + address + '\'' + - "providerAddress='" + providerAddress + '\'' + - ", service='" + service + '\'' + - ", app='" + app + '\'' + - ", param='" + param + '\'' + - '}'; + return "ConditionMatch{" + "address='" + + address + '\'' + "providerAddress='" + + providerAddress + '\'' + ", service='" + + service + '\'' + ", app='" + + app + '\'' + ", param='" + + param + '\'' + '}'; } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ConfigItem.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ConfigItem.java index 249baeb556..78547fd7d8 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ConfigItem.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ConfigItem.java @@ -68,32 +68,33 @@ public class ConfigItem { Object addresses = map.get(ADDRESSES_KEY); if (addresses != null && List.class.isAssignableFrom(addresses.getClass())) { - configItem.setAddresses(((List) addresses).stream() - .map(String::valueOf).collect(Collectors.toList())); + configItem.setAddresses( + ((List) addresses).stream().map(String::valueOf).collect(Collectors.toList())); } Object providerAddresses = map.get(PROVIDER_ADDRESSES_KEY); if (providerAddresses != null && List.class.isAssignableFrom(providerAddresses.getClass())) { - configItem.setProviderAddresses(((List) providerAddresses).stream() - .map(String::valueOf).collect(Collectors.toList())); + configItem.setProviderAddresses(((List) providerAddresses) + .stream().map(String::valueOf).collect(Collectors.toList())); } Object services = map.get(SERVICES_KEY); if (services != null && List.class.isAssignableFrom(services.getClass())) { - configItem.setServices(((List) services).stream() - .map(String::valueOf).collect(Collectors.toList())); + configItem.setServices( + ((List) services).stream().map(String::valueOf).collect(Collectors.toList())); } Object applications = map.get(APPLICATIONS_KEY); if (applications != null && List.class.isAssignableFrom(applications.getClass())) { - configItem.setApplications(((List) applications).stream() - .map(String::valueOf).collect(Collectors.toList())); + configItem.setApplications( + ((List) applications).stream().map(String::valueOf).collect(Collectors.toList())); } Object parameters = map.get(PARAMETERS_KEY); if (parameters != null && Map.class.isAssignableFrom(parameters.getClass())) { - configItem.setParameters(((Map) parameters).entrySet() - .stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().toString()))); + configItem.setParameters(((Map) parameters) + .entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue() + .toString()))); } try { @@ -102,7 +103,12 @@ public class ConfigItem { configItem.setMatch(PojoUtils.mapToPojo((Map) match, ConditionMatch.class)); } } catch (Throwable t) { - logger.error(CLUSTER_FAILED_RECEIVE_RULE, " Failed to parse dynamic configuration rule", String.valueOf(map.get(MATCH_KEY)), "Error occurred when parsing rule component.", t); + logger.error( + CLUSTER_FAILED_RECEIVE_RULE, + " Failed to parse dynamic configuration rule", + String.valueOf(map.get(MATCH_KEY)), + "Error occurred when parsing rule component.", + t); } configItem.setSide((String) map.get(SIDE_KEY)); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ConfiguratorConfig.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ConfiguratorConfig.java index 4a9c8e13a1..2b51957c04 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ConfiguratorConfig.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ConfiguratorConfig.java @@ -52,8 +52,8 @@ public class ConfiguratorConfig { Object configs = map.get(CONFIGS_KEY); if (configs != null && List.class.isAssignableFrom(configs.getClass())) { - configuratorConfig.setConfigs(((List>) configs).stream() - .map(ConfigItem::parseFromMap).collect(Collectors.toList())); + configuratorConfig.setConfigs(((List>) configs) + .stream().map(ConfigItem::parseFromMap).collect(Collectors.toList())); } return configuratorConfig; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ParamMatch.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ParamMatch.java index 42303e6a49..ad6dae436f 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ParamMatch.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/configurator/parser/model/ParamMatch.java @@ -50,9 +50,6 @@ public class ParamMatch { @Override public String toString() { - return "ParamMatch{" + - "key='" + key + '\'' + - ", value='" + value + '\'' + - '}'; + return "ParamMatch{" + "key='" + key + '\'' + ", value='" + value + '\'' + '}'; } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java index dab89c0848..087eacbade 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/AbstractDirectory.java @@ -160,18 +160,20 @@ public abstract class AbstractDirectory implements Directory { // remove some local only parameters applicationModel = url.getOrDefaultApplicationModel(); - this.queryMap = applicationModel.getBeanFactory().getBean(ClusterUtils.class).mergeLocalParams(queryMap); + this.queryMap = + applicationModel.getBeanFactory().getBean(ClusterUtils.class).mergeLocalParams(queryMap); if (consumerUrl == null) { - String host = isNotEmpty(queryMap.get(REGISTER_IP_KEY)) ? queryMap.get(REGISTER_IP_KEY) : this.url.getHost(); + String host = + isNotEmpty(queryMap.get(REGISTER_IP_KEY)) ? queryMap.get(REGISTER_IP_KEY) : this.url.getHost(); String path = isNotEmpty(queryMap.get(PATH_KEY)) ? queryMap.get(PATH_KEY) : queryMap.get(INTERFACE_KEY); String consumedProtocol = isNotEmpty(queryMap.get(PROTOCOL_KEY)) ? queryMap.get(PROTOCOL_KEY) : CONSUMER; URL consumerUrlFrom = this.url - .setHost(host) - .setPort(0) - .setProtocol(consumedProtocol) - .setPath(path); + .setHost(host) + .setPort(0) + .setProtocol(consumedProtocol) + .setPath(path); if (isUrlFromRegistry) { // reserve parameters if url is already a consumer url consumerUrlFrom = consumerUrlFrom.clearParameters(); @@ -179,19 +181,23 @@ public abstract class AbstractDirectory implements Directory { this.consumerUrl = consumerUrlFrom.addParameters(queryMap); } - this.connectivityExecutor = applicationModel.getFrameworkModel().getBeanFactory() - .getBean(FrameworkExecutorRepository.class).getConnectivityScheduledExecutor(); + this.connectivityExecutor = applicationModel + .getFrameworkModel() + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class) + .getConnectivityScheduledExecutor(); Configuration configuration = ConfigurationUtils.getGlobalConfiguration(url.getOrDefaultModuleModel()); this.reconnectTaskTryCount = configuration.getInt(RECONNECT_TASK_TRY_COUNT, DEFAULT_RECONNECT_TASK_TRY_COUNT); this.reconnectTaskPeriod = configuration.getInt(RECONNECT_TASK_PERIOD, DEFAULT_RECONNECT_TASK_PERIOD); setRouterChain(routerChain); - } @Override public List> list(Invocation invocation) throws RpcException { if (destroyed) { - throw new RpcException("Directory of type " + this.getClass().getSimpleName() + " already destroyed for service " + getConsumerUrl().getServiceKey() + " from registry " + getUrl()); + throw new RpcException( + "Directory of type " + this.getClass().getSimpleName() + " already destroyed for service " + + getConsumerUrl().getServiceKey() + " from registry " + getUrl()); } BitList> availableInvokers; @@ -222,12 +228,16 @@ public abstract class AbstractDirectory implements Directory { if (routedResult.isEmpty()) { // 2-2 - No provider available. - logger.warn(CLUSTER_NO_VALID_PROVIDER, "provider server or registry center crashed", "", - "No provider available after connectivity filter for the service " + getConsumerUrl().getServiceKey() - + " All routed invokers' size: " + routedResult.size() - + " from registry " + this - + " on the consumer " + NetUtils.getLocalHost() - + " using the dubbo version " + Version.getVersion() + "."); + logger.warn( + CLUSTER_NO_VALID_PROVIDER, + "provider server or registry center crashed", + "", + "No provider available after connectivity filter for the service " + + getConsumerUrl().getServiceKey() + + " All routed invokers' size: " + routedResult.size() + + " from registry " + this + + " on the consumer " + NetUtils.getLocalHost() + + " using the dubbo version " + Version.getVersion() + "."); } return Collections.unmodifiableList(routedResult); } finally { @@ -290,68 +300,78 @@ public abstract class AbstractDirectory implements Directory { // 3. try start check connectivity task checkConnectivity(); - logger.info("The invoker " + invoker.getUrl() + " has been added to invalidate list due to connectivity problem. " + - "Will trying to reconnect to it in the background."); + logger.info("The invoker " + invoker.getUrl() + + " has been added to invalidate list due to connectivity problem. " + + "Will trying to reconnect to it in the background."); } } public void checkConnectivity() { // try to submit task, to ensure there is only one task at most for each directory if (checkConnectivityPermit.tryAcquire()) { - this.connectivityCheckFuture = connectivityExecutor.schedule(() -> { - try { - if (isDestroyed()) { - return; - } - RpcContext.getServiceContext().setConsumerUrl(getConsumerUrl()); - List> needDeleteList = new ArrayList<>(); - List> invokersToTry = new ArrayList<>(); - - // 1. pick invokers from invokersToReconnect - // limit max reconnectTaskTryCount, prevent this task hang up all the connectivityExecutor for long time - if (invokersToReconnect.size() < reconnectTaskTryCount) { - invokersToTry.addAll(invokersToReconnect); - } else { - for (int i = 0; i < reconnectTaskTryCount; i++) { - Invoker tInvoker = invokersToReconnect.get(ThreadLocalRandom.current().nextInt(invokersToReconnect.size())); - if (!invokersToTry.contains(tInvoker)) { - // ignore if is selected, invokersToTry's size is always smaller than reconnectTaskTryCount + 1 - invokersToTry.add(tInvoker); + this.connectivityCheckFuture = connectivityExecutor.schedule( + () -> { + try { + if (isDestroyed()) { + return; } - } - } + RpcContext.getServiceContext().setConsumerUrl(getConsumerUrl()); + List> needDeleteList = new ArrayList<>(); + List> invokersToTry = new ArrayList<>(); - // 2. try to check the invoker's status - for (Invoker invoker : invokersToTry) { - if (invokers.contains(invoker)) { - if (invoker.isAvailable()) { - needDeleteList.add(invoker); + // 1. pick invokers from invokersToReconnect + // limit max reconnectTaskTryCount, prevent this task hang up all the connectivityExecutor + // for long time + if (invokersToReconnect.size() < reconnectTaskTryCount) { + invokersToTry.addAll(invokersToReconnect); + } else { + for (int i = 0; i < reconnectTaskTryCount; i++) { + Invoker tInvoker = invokersToReconnect.get( + ThreadLocalRandom.current().nextInt(invokersToReconnect.size())); + if (!invokersToTry.contains(tInvoker)) { + // ignore if is selected, invokersToTry's size is always smaller than + // reconnectTaskTryCount + 1 + invokersToTry.add(tInvoker); + } + } } - } else { - needDeleteList.add(invoker); - } - } - // 3. recover valid invoker - for (Invoker tInvoker : needDeleteList) { - if (invokers.contains(tInvoker)) { - addValidInvoker(tInvoker); - logger.info("Recover service address: " + tInvoker.getUrl() + " from invalid list."); - } - invokersToReconnect.remove(tInvoker); - } - } finally { - checkConnectivityPermit.release(); - } + // 2. try to check the invoker's status + for (Invoker invoker : invokersToTry) { + if (invokers.contains(invoker)) { + if (invoker.isAvailable()) { + needDeleteList.add(invoker); + } + } else { + needDeleteList.add(invoker); + } + } - // 4. submit new task if it has more to recover - if (!invokersToReconnect.isEmpty()) { - checkConnectivity(); - } - MetricsEventBus.publish(RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); - }, reconnectTaskPeriod, TimeUnit.MILLISECONDS); + // 3. recover valid invoker + for (Invoker tInvoker : needDeleteList) { + if (invokers.contains(tInvoker)) { + addValidInvoker(tInvoker); + logger.info( + "Recover service address: " + tInvoker.getUrl() + " from invalid list."); + } + invokersToReconnect.remove(tInvoker); + } + } finally { + checkConnectivityPermit.release(); + } + + // 4. submit new task if it has more to recover + if (!invokersToReconnect.isEmpty()) { + checkConnectivity(); + } + MetricsEventBus.publish(RegistryEvent.refreshDirectoryEvent( + applicationModel, getSummary(), getDirectoryMeta())); + }, + reconnectTaskPeriod, + TimeUnit.MILLISECONDS); } - MetricsEventBus.publish(RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); + MetricsEventBus.publish( + RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); } /** @@ -365,7 +385,8 @@ public abstract class AbstractDirectory implements Directory { if (invokersInitialized) { refreshInvokerInternal(); } - MetricsEventBus.publish(RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); + MetricsEventBus.publish( + RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); } protected Map getDirectoryMeta() { @@ -398,7 +419,8 @@ public abstract class AbstractDirectory implements Directory { removeValidInvoker(invoker); logger.info("Disable service address: " + invoker.getUrl() + "."); } - MetricsEventBus.publish(RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); + MetricsEventBus.publish( + RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); } @Override @@ -411,19 +433,24 @@ public abstract class AbstractDirectory implements Directory { } } - MetricsEventBus.publish(RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); + MetricsEventBus.publish( + RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); } protected final void refreshRouter(BitList> newlyInvokers, Runnable switchAction) { try { routerChain.setInvokers(newlyInvokers.clone(), switchAction); } catch (Throwable t) { - logger.error(LoggerCodeConstants.INTERNAL_ERROR, "", "", "Error occurred when refreshing router chain. " + - "The addresses from notification: " + - newlyInvokers.stream() - .map(Invoker::getUrl) - .map(URL::getAddress) - .collect(Collectors.joining(", ")), t); + logger.error( + LoggerCodeConstants.INTERNAL_ERROR, + "", + "", + "Error occurred when refreshing router chain. " + "The addresses from notification: " + + newlyInvokers.stream() + .map(Invoker::getUrl) + .map(URL::getAddress) + .collect(Collectors.joining(", ")), + t); throw t; } @@ -468,7 +495,8 @@ public abstract class AbstractDirectory implements Directory { refreshInvokerInternal(); this.invokersInitialized = true; - MetricsEventBus.publish(RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); + MetricsEventBus.publish( + RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); } protected void destroyInvokers() { @@ -483,7 +511,8 @@ public abstract class AbstractDirectory implements Directory { synchronized (this.validInvokers) { result = this.validInvokers.add(invoker); } - MetricsEventBus.publish(RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); + MetricsEventBus.publish( + RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); return result; } @@ -492,12 +521,14 @@ public abstract class AbstractDirectory implements Directory { synchronized (this.validInvokers) { result = this.validInvokers.remove(invoker); } - MetricsEventBus.publish(RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); + MetricsEventBus.publish( + RegistryEvent.refreshDirectoryEvent(applicationModel, getSummary(), getDirectoryMeta())); return result; } - protected abstract List> doList(SingleRouterChain singleRouterChain, - BitList> invokers, Invocation invocation) throws RpcException; + protected abstract List> doList( + SingleRouterChain singleRouterChain, BitList> invokers, Invocation invocation) + throws RpcException; protected String joinValidInvokerAddresses() { BitList> validInvokers = getValidInvokers().clone(); @@ -505,10 +536,10 @@ public abstract class AbstractDirectory implements Directory { return "empty"; } return validInvokers.stream() - .limit(5) - .map(Invoker::getUrl) - .map(URL::getAddress) - .collect(Collectors.joining(",")); + .limit(5) + .map(Invoker::getUrl) + .map(URL::getAddress) + .collect(Collectors.joining(",")); } private Map> getSummary() { @@ -527,25 +558,27 @@ public abstract class AbstractDirectory implements Directory { @Override public String toString() { - return "Directory(" + - "invokers: " + invokers.size() + "[" + - invokers.stream() - .map(Invoker::getUrl) - .map(URL::getAddress) - .limit(3) - .collect(Collectors.joining(", ")) + "]" + - ", validInvokers: " + validInvokers.size() + "[" + - validInvokers.stream() - .map(Invoker::getUrl) - .map(URL::getAddress) - .limit(3) - .collect(Collectors.joining(", ")) + "]" + - ", invokersToReconnect: " + invokersToReconnect.size() + "[" + - invokersToReconnect.stream() - .map(Invoker::getUrl) - .map(URL::getAddress) - .limit(3) - .collect(Collectors.joining(", ")) + "]" + - ')'; + return "Directory(" + "invokers: " + + invokers.size() + "[" + + invokers.stream() + .map(Invoker::getUrl) + .map(URL::getAddress) + .limit(3) + .collect(Collectors.joining(", ")) + + "]" + ", validInvokers: " + + validInvokers.size() + "[" + + validInvokers.stream() + .map(Invoker::getUrl) + .map(URL::getAddress) + .limit(3) + .collect(Collectors.joining(", ")) + + "]" + ", invokersToReconnect: " + + invokersToReconnect.size() + "[" + + invokersToReconnect.stream() + .map(Invoker::getUrl) + .map(URL::getAddress) + .limit(3) + .collect(Collectors.joining(", ")) + + "]" + ')'; } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectory.java index 6fae2eeb8f..14a4a5747f 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectory.java @@ -55,7 +55,12 @@ public class StaticDirectory extends AbstractDirectory { } public StaticDirectory(URL url, List> invokers, RouterChain routerChain) { - super(url == null && CollectionUtils.isNotEmpty(invokers) ? invokers.get(0).getUrl() : url, routerChain, false); + super( + url == null && CollectionUtils.isNotEmpty(invokers) + ? invokers.get(0).getUrl() + : url, + routerChain, + false); if (CollectionUtils.isEmpty(invokers)) { throw new IllegalArgumentException("invokers == null"); } @@ -101,28 +106,34 @@ public class StaticDirectory extends AbstractDirectory { public void buildRouterChain() { RouterChain routerChain = RouterChain.buildChain(getInterface(), getUrl()); - routerChain.setInvokers(getInvokers(), () -> { - }); + routerChain.setInvokers(getInvokers(), () -> {}); this.setRouterChain(routerChain); } public void notify(List> invokers) { BitList> bitList = new BitList<>(invokers); if (routerChain != null) { - refreshRouter(bitList.clone(), () -> this.setInvokers(bitList)); + refreshRouter(bitList.clone(), () -> this.setInvokers(bitList)); } else { this.setInvokers(bitList); } } @Override - protected List> doList(SingleRouterChain singleRouterChain, BitList> invokers, Invocation invocation) throws RpcException { + protected List> doList( + SingleRouterChain singleRouterChain, BitList> invokers, Invocation invocation) + throws RpcException { if (singleRouterChain != null) { try { List> finalInvokers = singleRouterChain.route(getConsumerUrl(), invokers, invocation); return finalInvokers == null ? BitList.emptyList() : finalInvokers; } catch (Throwable t) { - logger.error(CLUSTER_FAILED_SITE_SELECTION, "Failed to execute router", "", "Failed to execute router: " + getUrl() + ", cause: " + t.getMessage(), t); + logger.error( + CLUSTER_FAILED_SITE_SELECTION, + "Failed to execute router", + "", + "Failed to execute router: " + getUrl() + ", cause: " + t.getMessage(), + t); return BitList.emptyList(); } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/DefaultFilterChainBuilder.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/DefaultFilterChainBuilder.java index 22a22cd982..4be2ba9ba1 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/DefaultFilterChainBuilder.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/DefaultFilterChainBuilder.java @@ -47,12 +47,14 @@ public class DefaultFilterChainBuilder implements FilterChainBuilder { List moduleModels = getModuleModelsFromUrl(url); List filters; if (moduleModels != null && moduleModels.size() == 1) { - filters = ScopeModelUtil.getExtensionLoader(Filter.class, moduleModels.get(0)).getActivateExtension(url, key, group); + filters = ScopeModelUtil.getExtensionLoader(Filter.class, moduleModels.get(0)) + .getActivateExtension(url, key, group); } else if (moduleModels != null && moduleModels.size() > 1) { filters = new ArrayList<>(); List directors = new ArrayList<>(); for (ModuleModel moduleModel : moduleModels) { - List tempFilters = ScopeModelUtil.getExtensionLoader(Filter.class, moduleModel).getActivateExtension(url, key, group); + List tempFilters = ScopeModelUtil.getExtensionLoader(Filter.class, moduleModel) + .getActivateExtension(url, key, group); filters.addAll(tempFilters); directors.add(moduleModel.getExtensionDirector()); } @@ -62,7 +64,6 @@ public class DefaultFilterChainBuilder implements FilterChainBuilder { filters = ScopeModelUtil.getExtensionLoader(Filter.class, null).getActivateExtension(url, key, group); } - if (!CollectionUtils.isEmpty(filters)) { for (int i = filters.size() - 1; i >= 0; i--) { final Filter filter = filters.get(i); @@ -79,25 +80,29 @@ public class DefaultFilterChainBuilder implements FilterChainBuilder { * build consumer cluster filter chain */ @Override - public ClusterInvoker buildClusterInvokerChain(final ClusterInvoker originalInvoker, String key, String group) { + public ClusterInvoker buildClusterInvokerChain( + final ClusterInvoker originalInvoker, String key, String group) { ClusterInvoker last = originalInvoker; URL url = originalInvoker.getUrl(); List moduleModels = getModuleModelsFromUrl(url); List filters; if (moduleModels != null && moduleModels.size() == 1) { - filters = ScopeModelUtil.getExtensionLoader(ClusterFilter.class, moduleModels.get(0)).getActivateExtension(url, key, group); + filters = ScopeModelUtil.getExtensionLoader(ClusterFilter.class, moduleModels.get(0)) + .getActivateExtension(url, key, group); } else if (moduleModels != null && moduleModels.size() > 1) { filters = new ArrayList<>(); List directors = new ArrayList<>(); for (ModuleModel moduleModel : moduleModels) { - List tempFilters = ScopeModelUtil.getExtensionLoader(ClusterFilter.class, moduleModel).getActivateExtension(url, key, group); + List tempFilters = ScopeModelUtil.getExtensionLoader(ClusterFilter.class, moduleModel) + .getActivateExtension(url, key, group); filters.addAll(tempFilters); directors.add(moduleModel.getExtensionDirector()); } filters = sortingAndDeduplication(filters, directors); } else { - filters = ScopeModelUtil.getExtensionLoader(ClusterFilter.class, null).getActivateExtension(url, key, group); + filters = + ScopeModelUtil.getExtensionLoader(ClusterFilter.class, null).getActivateExtension(url, key, group); } if (!CollectionUtils.isEmpty(filters)) { @@ -141,5 +146,4 @@ public class DefaultFilterChainBuilder implements FilterChainBuilder { } return moduleModels; } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/FilterChainBuilder.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/FilterChainBuilder.java index 815f8821dd..92ab4a5848 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/FilterChainBuilder.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/FilterChainBuilder.java @@ -92,7 +92,8 @@ public interface FilterChainBuilder { public Result invoke(Invocation invocation) throws RpcException { Result asyncResult; try { - InvocationProfilerUtils.enterDetailProfiler(invocation, () -> "Filter " + filter.getClass().getName() + " invoke."); + InvocationProfilerUtils.enterDetailProfiler( + invocation, () -> "Filter " + filter.getClass().getName() + " invoke."); asyncResult = filter.invoke(nextNode, invocation); } catch (Exception e) { InvocationProfilerUtils.releaseDetailProfiler(invocation); @@ -159,12 +160,11 @@ public interface FilterChainBuilder { * @param */ class ClusterFilterChainNode, FILTER extends BaseFilter> - extends FilterChainNode implements ClusterInvoker { + extends FilterChainNode implements ClusterInvoker { public ClusterFilterChainNode(TYPE originalInvoker, Invoker nextNode, FILTER filter) { super(originalInvoker, nextNode, filter); } - @Override public URL getRegistryUrl() { return getOriginalInvoker().getRegistryUrl(); @@ -182,7 +182,8 @@ public interface FilterChainBuilder { } class CallbackRegistrationInvoker implements Invoker { - private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(CallbackRegistrationInvoker.class); + private static final ErrorTypeAwareLogger LOGGER = + LoggerFactory.getErrorTypeAwareLogger(CallbackRegistrationInvoker.class); final Invoker filterInvoker; final List filters; @@ -223,9 +224,20 @@ public interface FilterChainBuilder { } } } catch (RuntimeException runtimeException) { - LOGGER.error(CLUSTER_EXECUTE_FILTER_EXCEPTION, "the custom filter is abnormal", "", String.format("Exception occurred while executing the %s filter named %s.", i, filter.getClass().getSimpleName())); + LOGGER.error( + CLUSTER_EXECUTE_FILTER_EXCEPTION, + "the custom filter is abnormal", + "", + String.format( + "Exception occurred while executing the %s filter named %s.", + i, filter.getClass().getSimpleName())); if (LOGGER.isDebugEnabled()) { - LOGGER.debug(String.format("Whole filter list is: %s", filters.stream().map(tmpFilter -> tmpFilter.getClass().getSimpleName()).collect(Collectors.toList()))); + LOGGER.debug(String.format( + "Whole filter list is: %s", + filters.stream() + .map(tmpFilter -> + tmpFilter.getClass().getSimpleName()) + .collect(Collectors.toList()))); } filterRuntimeException = runtimeException; t = runtimeException; @@ -264,11 +276,12 @@ public interface FilterChainBuilder { } } - class ClusterCallbackRegistrationInvoker extends CallbackRegistrationInvoker - implements ClusterInvoker { + class ClusterCallbackRegistrationInvoker + extends CallbackRegistrationInvoker implements ClusterInvoker { private ClusterInvoker originalInvoker; - public ClusterCallbackRegistrationInvoker(ClusterInvoker originalInvoker, Invoker filterInvoker, List filters) { + public ClusterCallbackRegistrationInvoker( + ClusterInvoker originalInvoker, Invoker filterInvoker, List filters) { super(filterInvoker, filters); this.originalInvoker = originalInvoker; } @@ -293,10 +306,11 @@ public interface FilterChainBuilder { } } - - @Experimental("Works for the same purpose as FilterChainNode, replace FilterChainNode with this one when proved stable enough") + @Experimental( + "Works for the same purpose as FilterChainNode, replace FilterChainNode with this one when proved stable enough") class CopyOfFilterChainNode, FILTER extends BaseFilter> implements Invoker { - private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(CopyOfFilterChainNode.class); + private static final ErrorTypeAwareLogger LOGGER = + LoggerFactory.getErrorTypeAwareLogger(CopyOfFilterChainNode.class); TYPE originalInvoker; Invoker nextNode; FILTER filter; @@ -330,11 +344,14 @@ public interface FilterChainBuilder { public Result invoke(Invocation invocation) throws RpcException { Result asyncResult; try { - InvocationProfilerUtils.enterDetailProfiler(invocation, () -> "Filter " + filter.getClass().getName() + " invoke."); + InvocationProfilerUtils.enterDetailProfiler( + invocation, () -> "Filter " + filter.getClass().getName() + " invoke."); asyncResult = filter.invoke(nextNode, invocation); if (!(asyncResult instanceof AsyncRpcResult)) { - String msg = "The result of filter invocation must be AsyncRpcResult. (If you want to recreate a result, please use AsyncRpcResult.newDefaultAsyncResult.) " + - "Filter class: " + filter.getClass().getName() + ". Result class: " + asyncResult.getClass().getName() + "."; + String msg = + "The result of filter invocation must be AsyncRpcResult. (If you want to recreate a result, please use AsyncRpcResult.newDefaultAsyncResult.) " + + "Filter class: " + filter.getClass().getName() + ". Result class: " + + asyncResult.getClass().getName() + "."; LOGGER.error(INTERNAL_ERROR, "", "", msg); throw new RpcException(msg); } @@ -372,14 +389,14 @@ public interface FilterChainBuilder { } } - @Experimental("Works for the same purpose as ClusterFilterChainNode, replace ClusterFilterChainNode with this one when proved stable enough") + @Experimental( + "Works for the same purpose as ClusterFilterChainNode, replace ClusterFilterChainNode with this one when proved stable enough") class CopyOfClusterFilterChainNode, FILTER extends BaseFilter> - extends CopyOfFilterChainNode implements ClusterInvoker { + extends CopyOfFilterChainNode implements ClusterInvoker { public CopyOfClusterFilterChainNode(TYPE originalInvoker, Invoker nextNode, FILTER filter) { super(originalInvoker, nextNode, filter); } - @Override public URL getRegistryUrl() { return getOriginalInvoker().getRegistryUrl(); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/ProtocolFilterWrapper.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/ProtocolFilterWrapper.java index efbc4540cc..1a8c144c79 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/ProtocolFilterWrapper.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/ProtocolFilterWrapper.java @@ -62,7 +62,8 @@ public class ProtocolFilterWrapper implements Protocol { } private FilterChainBuilder getFilterChainBuilder(URL url) { - return ScopeModelUtil.getExtensionLoader(FilterChainBuilder.class, url.getScopeModel()).getDefaultExtension(); + return ScopeModelUtil.getExtensionLoader(FilterChainBuilder.class, url.getScopeModel()) + .getDefaultExtension(); } @Override @@ -83,5 +84,4 @@ public class ProtocolFilterWrapper implements Protocol { public List getServers() { return protocol.getServers(); } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsConsumerFilter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsConsumerFilter.java index 10136c17d8..7e3619094b 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsConsumerFilter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsConsumerFilter.java @@ -27,10 +27,11 @@ import org.apache.dubbo.rpc.cluster.filter.ClusterFilter; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; -@Activate(group = {CONSUMER}, order = Integer.MIN_VALUE + 100) +@Activate( + group = {CONSUMER}, + order = Integer.MIN_VALUE + 100) public class MetricsConsumerFilter extends MetricsFilter implements ClusterFilter, BaseFilter.Listener { - public MetricsConsumerFilter() { - } + public MetricsConsumerFilter() {} @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/governance/DefaultGovernanceRuleRepositoryImpl.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/governance/DefaultGovernanceRuleRepositoryImpl.java index 1d8d7183c3..57913b0a52 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/governance/DefaultGovernanceRuleRepositoryImpl.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/governance/DefaultGovernanceRuleRepositoryImpl.java @@ -56,5 +56,4 @@ public class DefaultGovernanceRuleRepositoryImpl implements GovernanceRuleReposi private DynamicConfiguration getDynamicConfiguration() { return moduleModel.modelEnvironment().getDynamicConfiguration().orElse(null); } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/governance/GovernanceRuleRepository.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/governance/GovernanceRuleRepository.java index 7c51a04c24..3bd0dd1c99 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/governance/GovernanceRuleRepository.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/governance/GovernanceRuleRepository.java @@ -36,7 +36,6 @@ public interface GovernanceRuleRepository { addListener(key, DEFAULT_GROUP, listener); } - /** * {@link #removeListener(String, String, ConfigurationListener)} * diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java index 59ecd9a305..c4eec1e005 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java @@ -47,7 +47,7 @@ public abstract class AbstractLoadBalance implements LoadBalance { * @return weight which takes warmup into account */ static int calculateWarmupWeight(int uptime, int warmup, int weight) { - int ww = (int) ( uptime / ((float) warmup / weight)); + int ww = (int) (uptime / ((float) warmup / weight)); return ww < 1 ? 1 : (Math.min(ww, weight)); } @@ -64,7 +64,6 @@ public abstract class AbstractLoadBalance implements LoadBalance { protected abstract Invoker doSelect(List> invokers, URL url, Invocation invocation); - /** * Get the weight of the invoker's invocation which takes warmup time into account * if the uptime is within the warmup time, the weight will be reduce proportionally @@ -94,7 +93,7 @@ public abstract class AbstractLoadBalance implements LoadBalance { } int warmup = invoker.getUrl().getParameter(WARMUP_KEY, DEFAULT_WARMUP); if (uptime > 0 && uptime < warmup) { - weight = calculateWarmupWeight((int)uptime, warmup, weight); + weight = calculateWarmupWeight((int) uptime, warmup, weight); } } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java index 37386ab186..7fdfd8f79b 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java @@ -46,7 +46,8 @@ public class ConsistentHashLoadBalance extends AbstractLoadBalance { */ public static final String HASH_ARGUMENTS = "hash.arguments"; - private final ConcurrentMap> selectors = new ConcurrentHashMap>(); + private final ConcurrentMap> selectors = + new ConcurrentHashMap>(); @SuppressWarnings("unchecked") @Override @@ -124,11 +125,10 @@ public class ConsistentHashLoadBalance extends AbstractLoadBalance { private long hash(byte[] digest, int number) { return (((long) (digest[3 + number * 4] & 0xFF) << 24) - | ((long) (digest[2 + number * 4] & 0xFF) << 16) - | ((long) (digest[1 + number * 4] & 0xFF) << 8) - | (digest[number * 4] & 0xFF)) + | ((long) (digest[2 + number * 4] & 0xFF) << 16) + | ((long) (digest[1 + number * 4] & 0xFF) << 8) + | (digest[number * 4] & 0xFF)) & 0xFFFFFFFFL; } } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/LeastActiveLoadBalance.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/LeastActiveLoadBalance.java index 9eb41f6fe9..76f82ebb7d 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/LeastActiveLoadBalance.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/LeastActiveLoadBalance.java @@ -56,17 +56,18 @@ public class LeastActiveLoadBalance extends AbstractLoadBalance { // Every least active invoker has the same weight value? boolean sameWeight = true; - // Filter out all the least active invokers for (int i = 0; i < length; i++) { Invoker invoker = invokers.get(i); // Get the active number of the invoker - int active = RpcStatus.getStatus(invoker.getUrl(), RpcUtils.getMethodName(invocation)).getActive(); + int active = RpcStatus.getStatus(invoker.getUrl(), RpcUtils.getMethodName(invocation)) + .getActive(); // Get the weight of the invoker's configuration. The default value is 100. int afterWarmup = getWeight(invoker, invocation); // save for later use weights[i] = afterWarmup; - // If it is the first invoker or the active number of the invoker is less than the current least active number + // If it is the first invoker or the active number of the invoker is less than the current least active + // number if (leastActive == -1 || active < leastActive) { // Reset the active number of the current invoker to the least active number leastActive = active; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java index 1b0b9fce7e..c264aa63a8 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java @@ -78,7 +78,8 @@ public class RandomLoadBalance extends AbstractLoadBalance { } } if (totalWeight > 0 && !sameWeight) { - // If (not every invoker has the same weight & at least one invoker's weight>0), select randomly based on totalWeight. + // If (not every invoker has the same weight & at least one invoker's weight>0), select randomly based on + // totalWeight. int offset = ThreadLocalRandom.current().nextInt(totalWeight); // Return an invoker based on the random value. if (length <= 4) { @@ -92,7 +93,7 @@ public class RandomLoadBalance extends AbstractLoadBalance { if (i < 0) { i = -i - 1; } else { - while (weights[i+1] == offset) { + while (weights[i + 1] == offset) { i++; } i++; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RoundRobinLoadBalance.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RoundRobinLoadBalance.java index 0ee6a82c5d..f60c0f61b9 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RoundRobinLoadBalance.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RoundRobinLoadBalance.java @@ -37,7 +37,8 @@ public class RoundRobinLoadBalance extends AbstractLoadBalance { private static final int RECYCLE_PERIOD = 60000; - private final ConcurrentMap> methodWeightMap = new ConcurrentHashMap<>(); + private final ConcurrentMap> methodWeightMap = + new ConcurrentHashMap<>(); protected static class WeightedRoundRobin { private int weight; @@ -91,7 +92,8 @@ public class RoundRobinLoadBalance extends AbstractLoadBalance { @Override protected Invoker doSelect(List> invokers, URL url, Invocation invocation) { String key = invokers.get(0).getUrl().getServiceKey() + "." + RpcUtils.getMethodName(invocation); - ConcurrentMap map = ConcurrentHashMapUtils.computeIfAbsent(methodWeightMap, key, k -> new ConcurrentHashMap<>()); + ConcurrentMap map = + ConcurrentHashMapUtils.computeIfAbsent(methodWeightMap, key, k -> new ConcurrentHashMap<>()); int totalWeight = 0; long maxCurrent = Long.MIN_VALUE; long now = System.currentTimeMillis(); @@ -107,7 +109,7 @@ public class RoundRobinLoadBalance extends AbstractLoadBalance { }); if (weight != weightedRoundRobin.getWeight()) { - //weight changed + // weight changed weightedRoundRobin.setWeight(weight); } long cur = weightedRoundRobin.increaseCurrent(); @@ -129,5 +131,4 @@ public class RoundRobinLoadBalance extends AbstractLoadBalance { // should not happen here return invokers.get(0); } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ShortestResponseLoadBalance.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ShortestResponseLoadBalance.java index 1244e76147..09837a3197 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ShortestResponseLoadBalance.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/ShortestResponseLoadBalance.java @@ -59,9 +59,15 @@ public class ShortestResponseLoadBalance extends AbstractLoadBalance implements @Override public void setApplicationModel(ApplicationModel applicationModel) { - slidePeriod = applicationModel.modelEnvironment().getConfiguration().getInt(Constants.SHORTEST_RESPONSE_SLIDE_PERIOD, 30_000); - executorService = applicationModel.getFrameworkModel().getBeanFactory() - .getBean(FrameworkExecutorRepository.class).getSharedExecutor(); + slidePeriod = applicationModel + .modelEnvironment() + .getConfiguration() + .getInt(Constants.SHORTEST_RESPONSE_SLIDE_PERIOD, 30_000); + executorService = applicationModel + .getFrameworkModel() + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class) + .getSharedExecutor(); } protected static class SlideWindowData { @@ -118,9 +124,11 @@ public class ShortestResponseLoadBalance extends AbstractLoadBalance implements for (int i = 0; i < length; i++) { Invoker invoker = invokers.get(i); RpcStatus rpcStatus = RpcStatus.getStatus(invoker.getUrl(), RpcUtils.getMethodName(invocation)); - SlideWindowData slideWindowData = ConcurrentHashMapUtils.computeIfAbsent(methodMap, rpcStatus, SlideWindowData::new); + SlideWindowData slideWindowData = + ConcurrentHashMapUtils.computeIfAbsent(methodMap, rpcStatus, SlideWindowData::new); - // Calculate the estimated response time from the product of active connections and succeeded average elapsed time. + // Calculate the estimated response time from the product of active connections and succeeded average + // elapsed time. long estimateResponse = slideWindowData.getEstimateResponse(); int afterWarmup = getWeight(invoker, invocation); weights[i] = afterWarmup; @@ -135,16 +143,15 @@ public class ShortestResponseLoadBalance extends AbstractLoadBalance implements } else if (estimateResponse == shortestResponse) { shortestIndexes[shortestCount++] = i; totalWeight += afterWarmup; - if (sameWeight && i > 0 - && afterWarmup != firstWeight) { + if (sameWeight && i > 0 && afterWarmup != firstWeight) { sameWeight = false; } } } if (System.currentTimeMillis() - lastUpdateTime > slidePeriod - && onResetSlideWindow.compareAndSet(false, true)) { - //reset slideWindowData in async way + && onResetSlideWindow.compareAndSet(false, true)) { + // reset slideWindowData in async way executorService.execute(() -> { methodMap.values().forEach(SlideWindowData::reset); lastUpdateTime = System.currentTimeMillis(); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/AbstractRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/AbstractRouter.java index d677843439..b38581264e 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/AbstractRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/AbstractRouter.java @@ -28,12 +28,13 @@ public abstract class AbstractRouter implements Router { private GovernanceRuleRepository ruleRepository; public AbstractRouter(URL url) { - this.ruleRepository = url.getOrDefaultModuleModel().getExtensionLoader(GovernanceRuleRepository.class).getDefaultExtension(); + this.ruleRepository = url.getOrDefaultModuleModel() + .getExtensionLoader(GovernanceRuleRepository.class) + .getDefaultExtension(); this.url = url; } - public AbstractRouter() { - } + public AbstractRouter() {} @Override public URL getUrl() { @@ -67,8 +68,7 @@ public abstract class AbstractRouter implements Router { this.priority = priority; } - public GovernanceRuleRepository getRuleRepository(){ + public GovernanceRuleRepository getRuleRepository() { return this.ruleRepository; } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/RouterSnapshotFilter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/RouterSnapshotFilter.java index 93f47f800d..62b48dee09 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/RouterSnapshotFilter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/RouterSnapshotFilter.java @@ -34,7 +34,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; public class RouterSnapshotFilter implements ClusterFilter, BaseFilter.Listener { private final RouterSnapshotSwitcher switcher; - private final static Logger logger = LoggerFactory.getLogger(RouterSnapshotFilter.class); + private static final Logger logger = LoggerFactory.getLogger(RouterSnapshotFilter.class); public RouterSnapshotFilter(FrameworkModel frameworkModel) { this.switcher = frameworkModel.getBeanFactory().getBean(RouterSnapshotSwitcher.class); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/RouterSnapshotNode.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/RouterSnapshotNode.java index b0a09759b6..faa57f0a40 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/RouterSnapshotNode.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/RouterSnapshotNode.java @@ -114,43 +114,55 @@ public class RouterSnapshotNode { public String toString(int level) { StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("[ ") - .append(name) - .append(' ') - .append("(Input: ").append(beforeSize).append(") ") - .append("(Current Node Output: ").append(nodeOutputSize).append(") ") - .append("(Chain Node Output: ").append(chainOutputSize).append(')') - .append(routerMessage == null ? "" : " Router message: ") - .append(routerMessage == null ? "" : routerMessage) - .append(" ] "); + stringBuilder + .append("[ ") + .append(name) + .append(' ') + .append("(Input: ") + .append(beforeSize) + .append(") ") + .append("(Current Node Output: ") + .append(nodeOutputSize) + .append(") ") + .append("(Chain Node Output: ") + .append(chainOutputSize) + .append(')') + .append(routerMessage == null ? "" : " Router message: ") + .append(routerMessage == null ? "" : routerMessage) + .append(" ] "); if (level == 1) { - stringBuilder.append("Input: ") - .append(CollectionUtils.isEmpty(inputInvokers) ? "Empty" : - inputInvokers.subList(0, Math.min(5, inputInvokers.size())) - .stream() - .map(Invoker::getUrl) - .map(URL::getAddress) - .collect(Collectors.joining(","))) - .append(" -> "); + stringBuilder + .append("Input: ") + .append( + CollectionUtils.isEmpty(inputInvokers) + ? "Empty" + : inputInvokers.subList(0, Math.min(5, inputInvokers.size())).stream() + .map(Invoker::getUrl) + .map(URL::getAddress) + .collect(Collectors.joining(","))) + .append(" -> "); - stringBuilder.append("Chain Node Output: ") - .append(CollectionUtils.isEmpty(chainOutputInvokers) ? "Empty" : - chainOutputInvokers.subList(0, Math.min(5, chainOutputInvokers.size())) - .stream() - .map(Invoker::getUrl) - .map(URL::getAddress) - .collect(Collectors.joining(","))); + stringBuilder + .append("Chain Node Output: ") + .append( + CollectionUtils.isEmpty(chainOutputInvokers) + ? "Empty" + : chainOutputInvokers.subList(0, Math.min(5, chainOutputInvokers.size())).stream() + .map(Invoker::getUrl) + .map(URL::getAddress) + .collect(Collectors.joining(","))); } else { - stringBuilder.append("Current Node Output: ") - .append(CollectionUtils.isEmpty(nodeOutputInvokers) ? "Empty" : - nodeOutputInvokers.subList(0, Math.min(5, nodeOutputInvokers.size())) - .stream() - .map(Invoker::getUrl) - .map(URL::getAddress) - .collect(Collectors.joining(","))); + stringBuilder + .append("Current Node Output: ") + .append( + CollectionUtils.isEmpty(nodeOutputInvokers) + ? "Empty" + : nodeOutputInvokers.subList(0, Math.min(5, nodeOutputInvokers.size())).stream() + .map(Invoker::getUrl) + .map(URL::getAddress) + .collect(Collectors.joining(","))); } - if (nodeOutputInvokers != null && nodeOutputInvokers.size() > 5) { stringBuilder.append("..."); } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/RouterSnapshotSwitcher.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/RouterSnapshotSwitcher.java index 139a0bcee2..39bda00c27 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/RouterSnapshotSwitcher.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/RouterSnapshotSwitcher.java @@ -26,7 +26,7 @@ public class RouterSnapshotSwitcher { private volatile boolean enable; private final Set enabledService = new ConcurrentHashSet<>(); - private final static int MAX_LENGTH = 1 << 5; // 2 ^ 5 = 31 + private static final int MAX_LENGTH = 1 << 5; // 2 ^ 5 = 31 private final AtomicInteger offset = new AtomicInteger(0); private volatile String[] recentSnapshot = new String[MAX_LENGTH]; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/AddressMatch.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/AddressMatch.java index b8fdc3b578..834a519496 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/AddressMatch.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/AddressMatch.java @@ -62,7 +62,14 @@ public class AddressMatch { try { return input.equals(getCird()) || matchIpExpression(getCird(), input); } catch (UnknownHostException e) { - logger.error(CLUSTER_FAILED_EXEC_CONDITION_ROUTER, "Executing routing rule match expression error.", "", String.format("Error trying to match cird formatted address %s with input %s in AddressMatch.", getCird(), input), e); + logger.error( + CLUSTER_FAILED_EXEC_CONDITION_ROUTER, + "Executing routing rule match expression error.", + "", + String.format( + "Error trying to match cird formatted address %s with input %s in AddressMatch.", + getCird(), input), + e); } } if (getWildcard() != null && input != null) { diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/BoolMatch.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/BoolMatch.java index c9a6fab9e5..b185cf488e 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/BoolMatch.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/BoolMatch.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match; - public class BoolMatch { private Boolean exact; @@ -29,8 +27,8 @@ public class BoolMatch { this.exact = exact; } - public boolean isMatch(boolean input){ - if (exact != null){ + public boolean isMatch(boolean input) { + if (exact != null) { return input == exact; } return false; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DoubleMatch.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DoubleMatch.java index 55db3e232c..b3fd223b89 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DoubleMatch.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DoubleMatch.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match; - public class DoubleMatch { private Double exact; private DoubleRangeMatch range; @@ -47,7 +45,6 @@ public class DoubleMatch { this.mod = mod; } - public boolean isMatch(Double input) { if (exact != null && mod == null) { return input.equals(exact); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DoubleRangeMatch.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DoubleRangeMatch.java index ad4ea5633c..6deccf479a 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DoubleRangeMatch.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DoubleRangeMatch.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match; - public class DoubleRangeMatch { private Double start; private Double end; @@ -38,7 +36,6 @@ public class DoubleRangeMatch { this.end = end; } - public boolean isMatch(Double input) { if (start != null && end != null) { return input.compareTo(start) >= 0 && input.compareTo(end) < 0; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboMethodArg.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboMethodArg.java index d02cd0793b..3095e509df 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboMethodArg.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboMethodArg.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match; - public class DubboMethodArg { private int index; private String type; @@ -79,12 +77,11 @@ public class DubboMethodArg { @Override public String toString() { - return "DubboMethodArg{" + - "index=" + index + - ", type='" + type + '\'' + - ", str_value=" + str_value + - ", num_value=" + num_value + - ", bool_value=" + bool_value + - '}'; + return "DubboMethodArg{" + "index=" + + index + ", type='" + + type + '\'' + ", str_value=" + + str_value + ", num_value=" + + num_value + ", bool_value=" + + bool_value + '}'; } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboMethodMatch.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboMethodMatch.java index f252410478..e724e9f10c 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboMethodMatch.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboMethodMatch.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match; import org.apache.dubbo.rpc.Invocation; @@ -23,7 +22,6 @@ import org.apache.dubbo.rpc.support.RpcUtils; import java.util.List; import java.util.Map; - public class DubboMethodMatch { private StringMatch name_match; private Integer argc; @@ -73,13 +71,12 @@ public class DubboMethodMatch { @Override public String toString() { - return "DubboMethodMatch{" + - "name_match=" + name_match + - ", argc=" + argc + - ", args=" + args + - ", argp=" + argp + - ", headers=" + headers + - '}'; + return "DubboMethodMatch{" + "name_match=" + + name_match + ", argc=" + + argc + ", args=" + + args + ", argp=" + + argp + ", headers=" + + headers + '}'; } public boolean isMatch(Invocation invocation) { @@ -90,8 +87,8 @@ public class DubboMethodMatch { Integer argc = getArgc(); Object[] arguments = invocation.getArguments(); - if (argc != null && - ((argc != 0 && (arguments == null || arguments.length == 0)) || (argc != arguments.length))) { + if (argc != null + && ((argc != 0 && (arguments == null || arguments.length == 0)) || (argc != arguments.length))) { return false; } @@ -107,7 +104,7 @@ public class DubboMethodMatch { for (int index = 0; index < argp.size(); index++) { boolean match = argp.get(index).isMatch(parameterTypes[index].getName()) - || argp.get(index).isMatch(parameterTypes[index].getSimpleName()); + || argp.get(index).isMatch(parameterTypes[index].getSimpleName()); if (!match) { return false; } @@ -134,4 +131,3 @@ public class DubboMethodMatch { return true; } } - diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListBoolMatch.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListBoolMatch.java index 570a5e8551..940d9a8b1f 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListBoolMatch.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListBoolMatch.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match; - import java.util.List; public class ListBoolMatch { @@ -41,4 +39,3 @@ public class ListBoolMatch { return false; } } - diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListDoubleMatch.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListDoubleMatch.java index 0a19334ecc..d1599521d9 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListDoubleMatch.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListDoubleMatch.java @@ -14,12 +14,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match; import java.util.List; - public class ListDoubleMatch { private List oneof; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListStringMatch.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListStringMatch.java index 0fce727503..4c555780e6 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListStringMatch.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListStringMatch.java @@ -14,12 +14,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match; import java.util.List; - public class ListStringMatch { private List oneof; @@ -31,7 +29,6 @@ public class ListStringMatch { this.oneof = oneof; } - public boolean isMatch(String input) { for (StringMatch stringMatch : oneof) { diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/StringMatch.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/StringMatch.java index dda2de7df3..3a2a85b5fd 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/StringMatch.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/StringMatch.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match; - import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; public class StringMatch { @@ -28,7 +26,6 @@ public class StringMatch { private String empty; private String wildcard; - public String getExact() { return exact; } @@ -98,12 +95,11 @@ public class StringMatch { @Override public String toString() { - return "StringMatch{" + - "exact='" + exact + '\'' + - ", prefix='" + prefix + '\'' + - ", regex='" + regex + '\'' + - ", noempty='" + noempty + '\'' + - ", empty='" + empty + '\'' + - '}'; + return "StringMatch{" + "exact='" + + exact + '\'' + ", prefix='" + + prefix + '\'' + ", regex='" + + regex + '\'' + ", noempty='" + + noempty + '\'' + ", empty='" + + empty + '\'' + '}'; } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/AbstractStateRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/AbstractStateRouter.java index 2b25ed5564..f3f1bd208a 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/AbstractStateRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/AbstractStateRouter.java @@ -47,9 +47,11 @@ public abstract class AbstractStateRouter implements StateRouter { public AbstractStateRouter(URL url) { moduleModel = url.getOrDefaultModuleModel(); - this.ruleRepository = moduleModel.getExtensionLoader(GovernanceRuleRepository.class).getDefaultExtension(); + this.ruleRepository = + moduleModel.getExtensionLoader(GovernanceRuleRepository.class).getDefaultExtension(); this.url = url; - this.shouldFailFast = Boolean.parseBoolean(ConfigurationUtils.getProperty(moduleModel, Constants.SHOULD_FAIL_FAST_KEY, "true")); + this.shouldFailFast = Boolean.parseBoolean( + ConfigurationUtils.getProperty(moduleModel, Constants.SHOULD_FAIL_FAST_KEY, "true")); } @Override @@ -89,7 +91,13 @@ public abstract class AbstractStateRouter implements StateRouter { } @Override - public final BitList> route(BitList> invokers, URL url, Invocation invocation, boolean needToPrintMessage, Holder> nodeHolder) throws RpcException { + public final BitList> route( + BitList> invokers, + URL url, + Invocation invocation, + boolean needToPrintMessage, + Holder> nodeHolder) + throws RpcException { if (needToPrintMessage && (nodeHolder == null || nodeHolder.get() == null)) { needToPrintMessage = false; } @@ -151,17 +159,26 @@ public abstract class AbstractStateRouter implements StateRouter { * @param messageHolder message holder when router should current router print message * @return routed result */ - protected abstract BitList> doRoute(BitList> invokers, URL url, Invocation invocation, - boolean needToPrintMessage, Holder> nodeHolder, - Holder messageHolder) throws RpcException; + protected abstract BitList> doRoute( + BitList> invokers, + URL url, + Invocation invocation, + boolean needToPrintMessage, + Holder> nodeHolder, + Holder messageHolder) + throws RpcException; /** * Call next router to get result * * @param invokers current router filtered invokers */ - protected final BitList> continueRoute(BitList> invokers, URL url, Invocation invocation, - boolean needToPrintMessage, Holder> nodeHolder) { + protected final BitList> continueRoute( + BitList> invokers, + URL url, + Invocation invocation, + boolean needToPrintMessage, + Holder> nodeHolder) { if (nextRouter != null) { return nextRouter.route(invokers, url, invocation, needToPrintMessage, nodeHolder); } else { @@ -192,9 +209,7 @@ public abstract class AbstractStateRouter implements StateRouter { @Override public final String buildSnapshot() { - return doBuildSnapshot() + - " v \n" + - nextRouter.buildSnapshot(); + return doBuildSnapshot() + " v \n" + nextRouter.buildSnapshot(); } protected String doBuildSnapshot() { diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/BitList.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/BitList.java index b3fda63948..2c04539b07 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/BitList.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/BitList.java @@ -55,7 +55,7 @@ import java.util.concurrent.ThreadLocalRandom; public class BitList extends AbstractList implements Cloneable { private final BitSet rootSet; private volatile List originList; - private final static BitList emptyList = new BitList(Collections.emptyList()); + private static final BitList emptyList = new BitList(Collections.emptyList()); private volatile List tailList = null; public BitList(List originList) { @@ -367,7 +367,8 @@ public class BitList extends AbstractList implements Cloneable { copiedTailList = null; resultSet.set(toIndex, resultSet.length(), false); } else { - copiedTailList = copiedTailList == null ? null : copiedTailList.subList(0, toIndex - rootSet.cardinality()); + copiedTailList = + copiedTailList == null ? null : copiedTailList.subList(0, toIndex - rootSet.cardinality()); } } if (fromIndex > 0) { @@ -375,7 +376,9 @@ public class BitList extends AbstractList implements Cloneable { resultSet.set(0, fromIndex, false); } else { resultSet.clear(); - copiedTailList = copiedTailList == null ? null : copiedTailList.subList(fromIndex - rootSet.cardinality(), copiedTailList.size()); + copiedTailList = copiedTailList == null + ? null + : copiedTailList.subList(fromIndex - rootSet.cardinality(), copiedTailList.size()); } } return new BitList<>(originList, resultSet, copiedTailList); @@ -551,6 +554,7 @@ public class BitList extends AbstractList implements Cloneable { @Override public BitList clone() { - return new BitList<>(originList, (BitSet) rootSet.clone(), tailList == null ? null : new LinkedList<>(tailList)); + return new BitList<>( + originList, (BitSet) rootSet.clone(), tailList == null ? null : new LinkedList<>(tailList)); } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/CacheableStateRouterFactory.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/CacheableStateRouterFactory.java index 91d28bbbbc..3447fc79f7 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/CacheableStateRouterFactory.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/CacheableStateRouterFactory.java @@ -32,7 +32,8 @@ public abstract class CacheableStateRouterFactory implements StateRouterFactory @Override public StateRouter getRouter(Class interfaceClass, URL url) { - return ConcurrentHashMapUtils.computeIfAbsent(routerMap, url.getServiceKey(), k -> createRouter(interfaceClass, url)); + return ConcurrentHashMapUtils.computeIfAbsent( + routerMap, url.getServiceKey(), k -> createRouter(interfaceClass, url)); } protected abstract StateRouter createRouter(Class interfaceClass, URL url); diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/RouterGroupingState.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/RouterGroupingState.java index fed028b7e2..8eabe70160 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/RouterGroupingState.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/RouterGroupingState.java @@ -48,29 +48,32 @@ public class RouterGroupingState { @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append(routerName) - .append(' ') - .append(" Total: ") - .append(total) - .append("\n"); + stringBuilder + .append(routerName) + .append(' ') + .append(" Total: ") + .append(total) + .append("\n"); for (Map.Entry>> entry : grouping.entrySet()) { BitList> invokers = entry.getValue(); - stringBuilder.append("[ ") - .append(entry.getKey()) - .append(" -> ") - .append(invokers.isEmpty() ? - "Empty" : - invokers.stream() - .limit(5) - .map(Invoker::getUrl) - .map(URL::getAddress) - .collect(Collectors.joining(","))) - .append(invokers.size() > 5 ? "..." : "") - .append(" (Total: ") - .append(invokers.size()) - .append(") ]") - .append("\n"); + stringBuilder + .append("[ ") + .append(entry.getKey()) + .append(" -> ") + .append( + invokers.isEmpty() + ? "Empty" + : invokers.stream() + .limit(5) + .map(Invoker::getUrl) + .map(URL::getAddress) + .collect(Collectors.joining(","))) + .append(invokers.size() > 5 ? "..." : "") + .append(" (Total: ") + .append(invokers.size()) + .append(") ]") + .append("\n"); } return stringBuilder.toString(); } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/StateRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/StateRouter.java index 94d82fd405..ccfa60c5de 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/StateRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/StateRouter.java @@ -55,8 +55,13 @@ public interface StateRouter { * @return state with route result * @since 3.0 */ - BitList> route(BitList> invokers, URL url, Invocation invocation, - boolean needToPrintMessage, Holder> nodeHolder) throws RpcException; + BitList> route( + BitList> invokers, + URL url, + Invocation invocation, + boolean needToPrintMessage, + Holder> nodeHolder) + throws RpcException; /** * To decide whether this router need to execute every time an RPC comes or should only execute when addresses or @@ -92,7 +97,7 @@ public interface StateRouter { String buildSnapshot(); default void stop() { - //do nothing by default + // do nothing by default } /** diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/TailStateRouter.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/TailStateRouter.java index 8a0780c763..e5b4a999ee 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/TailStateRouter.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/TailStateRouter.java @@ -31,14 +31,10 @@ public class TailStateRouter implements StateRouter { return INSTANCE; } - private TailStateRouter() { - - } + private TailStateRouter() {} @Override - public void setNextRouter(StateRouter nextRouter) { - - } + public void setNextRouter(StateRouter nextRouter) {} @Override public URL getUrl() { @@ -46,7 +42,13 @@ public class TailStateRouter implements StateRouter { } @Override - public BitList> route(BitList> invokers, URL url, Invocation invocation, boolean needToPrintMessage, Holder> nodeHolder) throws RpcException { + public BitList> route( + BitList> invokers, + URL url, + Invocation invocation, + boolean needToPrintMessage, + Holder> nodeHolder) + throws RpcException { return invokers; } @@ -61,9 +63,7 @@ public class TailStateRouter implements StateRouter { } @Override - public void notify(BitList> invokers) { - - } + public void notify(BitList> invokers) {} @Override public String buildSnapshot() { diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvoker.java index 745e602f1f..4411eae7a9 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvoker.java @@ -61,7 +61,8 @@ import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_CLUSTER_STICKY; */ public abstract class AbstractClusterInvoker implements ClusterInvoker { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractClusterInvoker.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(AbstractClusterInvoker.class); protected Directory directory; @@ -75,8 +76,7 @@ public abstract class AbstractClusterInvoker implements ClusterInvoker { private volatile Invoker stickyInvoker = null; - public AbstractClusterInvoker() { - } + public AbstractClusterInvoker() {} public AbstractClusterInvoker(Directory directory) { this(directory, directory.getUrl()); @@ -88,7 +88,7 @@ public abstract class AbstractClusterInvoker implements ClusterInvoker { } this.directory = directory; - //sticky: invoker.isAvailable() should always be checked before using when availablecheck is true. + // sticky: invoker.isAvailable() should always be checked before using when availablecheck is true. this.availableCheck = url.getParameter(CLUSTER_AVAILABLE_CHECK_KEY, DEFAULT_CLUSTER_AVAILABLE_CHECK); Configuration configuration = ConfigurationUtils.getGlobalConfiguration(url.getOrDefaultModuleModel()); this.reselectCount = configuration.getInt(RESELECT_COUNT, DEFAULT_RESELECT_COUNT); @@ -152,22 +152,23 @@ public abstract class AbstractClusterInvoker implements ClusterInvoker { * @return the invoker which will final to do invoke. * @throws RpcException exception */ - protected Invoker select(LoadBalance loadbalance, Invocation invocation, - List> invokers, List> selected) throws RpcException { + protected Invoker select( + LoadBalance loadbalance, Invocation invocation, List> invokers, List> selected) + throws RpcException { if (CollectionUtils.isEmpty(invokers)) { return null; } String methodName = invocation == null ? StringUtils.EMPTY_STRING : RpcUtils.getMethodName(invocation); - boolean sticky = invokers.get(0).getUrl() - .getMethodParameter(methodName, CLUSTER_STICKY_KEY, DEFAULT_CLUSTER_STICKY); + boolean sticky = + invokers.get(0).getUrl().getMethodParameter(methodName, CLUSTER_STICKY_KEY, DEFAULT_CLUSTER_STICKY); - //ignore overloaded method + // ignore overloaded method if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { stickyInvoker = null; } - //ignore concurrency problem + // ignore concurrency problem if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { if (availableCheck && stickyInvoker.isAvailable()) { return stickyInvoker; @@ -183,8 +184,9 @@ public abstract class AbstractClusterInvoker implements ClusterInvoker { return invoker; } - private Invoker doSelect(LoadBalance loadbalance, Invocation invocation, - List> invokers, List> selected) throws RpcException { + private Invoker doSelect( + LoadBalance loadbalance, Invocation invocation, List> invokers, List> selected) + throws RpcException { if (CollectionUtils.isEmpty(invokers)) { return null; @@ -196,7 +198,7 @@ public abstract class AbstractClusterInvoker implements ClusterInvoker { } Invoker invoker = loadbalance.select(invokers, getUrl(), invocation); - //If the `invoker` is in the `selected` or invoker is unavailable && availablecheck is true, reselect. + // If the `invoker` is in the `selected` or invoker is unavailable && availablecheck is true, reselect. boolean isSelected = selected != null && selected.contains(invoker); boolean isUnavailable = availableCheck && !invoker.isAvailable() && getUrl() != null; @@ -209,17 +211,28 @@ public abstract class AbstractClusterInvoker implements ClusterInvoker { if (rInvoker != null) { invoker = rInvoker; } else { - //Check the index of current selected invoker, if it's not the last one, choose the one at index+1. + // Check the index of current selected invoker, if it's not the last one, choose the one at index+1. int index = invokers.indexOf(invoker); try { - //Avoid collision + // Avoid collision invoker = invokers.get((index + 1) % invokers.size()); } catch (Exception e) { - logger.warn(CLUSTER_FAILED_RESELECT_INVOKERS,"select invokers exception","",e.getMessage() + " may because invokers list dynamic change, ignore.",e); + logger.warn( + CLUSTER_FAILED_RESELECT_INVOKERS, + "select invokers exception", + "", + e.getMessage() + " may because invokers list dynamic change, ignore.", + e); } } } catch (Throwable t) { - logger.error(CLUSTER_FAILED_RESELECT_INVOKERS,"failed to reselect invokers","","cluster reselect fail reason is :" + t.getMessage() + " if can not solve, you can set cluster.availablecheck=false in url",t); + logger.error( + CLUSTER_FAILED_RESELECT_INVOKERS, + "failed to reselect invokers", + "", + "cluster reselect fail reason is :" + t.getMessage() + + " if can not solve, you can set cluster.availablecheck=false in url", + t); } } @@ -238,8 +251,13 @@ public abstract class AbstractClusterInvoker implements ClusterInvoker { * @return the reselect result to do invoke * @throws RpcException exception */ - private Invoker reselect(LoadBalance loadbalance, Invocation invocation, - List> invokers, List> selected, boolean availableCheck) throws RpcException { + private Invoker reselect( + LoadBalance loadbalance, + Invocation invocation, + List> invokers, + List> selected, + boolean availableCheck) + throws RpcException { // Allocating one in advance, this list is certain to be used. List> reselectInvokers = new ArrayList<>(Math.min(invokers.size(), reselectCount)); @@ -247,9 +265,12 @@ public abstract class AbstractClusterInvoker implements ClusterInvoker { // 1. Try picking some invokers not in `selected`. // 1.1. If all selectable invokers' size is smaller than reselectCount, just add all // 1.2. If all selectable invokers' size is greater than reselectCount, randomly select reselectCount. - // The result size of invokers might smaller than reselectCount due to disAvailable or de-duplication (might be zero). - // This means there is probable that reselectInvokers is empty however all invoker list may contain available invokers. - // Use reselectCount can reduce retry times if invokers' size is huge, which may lead to long time hang up. + // The result size of invokers might smaller than reselectCount due to disAvailable or de-duplication + // (might be zero). + // This means there is probable that reselectInvokers is empty however all invoker list may contain + // available invokers. + // Use reselectCount can reduce retry times if invokers' size is huge, which may lead to long time + // hang up. if (reselectCount >= invokers.size()) { for (Invoker invoker : invokers) { // check if available @@ -290,7 +311,7 @@ public abstract class AbstractClusterInvoker implements ClusterInvoker { if (selected != null) { for (Invoker invoker : selected) { if ((invoker.isAvailable()) // available first - && !reselectInvokers.contains(invoker)) { + && !reselectInvokers.contains(invoker)) { reselectInvokers.add(invoker); } } @@ -325,10 +346,10 @@ public abstract class AbstractClusterInvoker implements ClusterInvoker { checkWhetherDestroyed(); // binding attachments into invocation. -// Map contextAttachments = RpcContext.getClientAttachment().getObjectAttachments(); -// if (contextAttachments != null && contextAttachments.size() != 0) { -// ((RpcInvocation) invocation).addObjectAttachmentsIfAbsent(contextAttachments); -// } + // Map contextAttachments = RpcContext.getClientAttachment().getObjectAttachments(); + // if (contextAttachments != null && contextAttachments.size() != 0) { + // ((RpcInvocation) invocation).addObjectAttachmentsIfAbsent(contextAttachments); + // } InvocationProfilerUtils.enterDetailProfiler(invocation, () -> "Router route."); List> invokers = list(invocation); @@ -339,7 +360,8 @@ public abstract class AbstractClusterInvoker implements ClusterInvoker { LoadBalance loadbalance = initLoadBalance(invokers, invocation); RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation); - InvocationProfilerUtils.enterDetailProfiler(invocation, () -> "Cluster " + this.getClass().getName() + " invoke."); + InvocationProfilerUtils.enterDetailProfiler( + invocation, () -> "Cluster " + this.getClass().getName() + " invoke."); try { return doInvoke(invocation, invokers, loadbalance); } finally { @@ -349,9 +371,10 @@ public abstract class AbstractClusterInvoker implements ClusterInvoker { protected void checkWhetherDestroyed() { if (destroyed.get()) { - throw new RpcException("Rpc cluster invoker for " + getInterface() + " on consumer " + NetUtils.getLocalHost() - + " use dubbo version " + Version.getVersion() - + " is now destroyed! Can not invoke any more."); + throw new RpcException( + "Rpc cluster invoker for " + getInterface() + " on consumer " + NetUtils.getLocalHost() + + " use dubbo version " + Version.getVersion() + + " is now destroyed! Can not invoke any more."); } } @@ -362,13 +385,17 @@ public abstract class AbstractClusterInvoker implements ClusterInvoker { protected void checkInvokers(List> invokers, Invocation invocation) { if (CollectionUtils.isEmpty(invokers)) { - throw new RpcException(RpcException.NO_INVOKER_AVAILABLE_AFTER_FILTER, "Failed to invoke the method " - + RpcUtils.getMethodName(invocation) + " in the service " + getInterface().getName() - + ". No provider available for the service " + getDirectory().getConsumerUrl().getServiceKey() - + " from registry " + getDirectory() - + " on the consumer " + NetUtils.getLocalHost() - + " using the dubbo version " + Version.getVersion() - + ". Please check if the providers have been started and registered."); + throw new RpcException( + RpcException.NO_INVOKER_AVAILABLE_AFTER_FILTER, + "Failed to invoke the method " + + RpcUtils.getMethodName(invocation) + " in the service " + + getInterface().getName() + + ". No provider available for the service " + + getDirectory().getConsumerUrl().getServiceKey() + + " from registry " + getDirectory() + + " on the consumer " + NetUtils.getLocalHost() + + " using the dubbo version " + Version.getVersion() + + ". Please check if the providers have been started and registered."); } } @@ -377,7 +404,9 @@ public abstract class AbstractClusterInvoker implements ClusterInvoker { Result result; try { if (ProfilerSwitch.isEnableSimpleProfiler()) { - InvocationProfilerUtils.enterProfiler(invocation, "Invoker invoke. Target Address: " + invoker.getUrl().getAddress()); + InvocationProfilerUtils.enterProfiler( + invocation, + "Invoker invoke. Target Address: " + invoker.getUrl().getAddress()); } setRemote(invoker, invocation); result = invoker.invoke(invocation); @@ -416,8 +445,8 @@ public abstract class AbstractClusterInvoker implements ClusterInvoker { return result; } - protected abstract Result doInvoke(Invocation invocation, List> invokers, - LoadBalance loadbalance) throws RpcException; + protected abstract Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) + throws RpcException; protected List> list(Invocation invocation) throws RpcException { return getDirectory().list(invocation); @@ -437,17 +466,17 @@ public abstract class AbstractClusterInvoker implements ClusterInvoker { protected LoadBalance initLoadBalance(List> invokers, Invocation invocation) { ApplicationModel applicationModel = ScopeModelUtil.getApplicationModel(invocation.getModuleModel()); if (CollectionUtils.isNotEmpty(invokers)) { - return applicationModel.getExtensionLoader(LoadBalance.class).getExtension( - invokers.get(0).getUrl().getMethodParameter( - RpcUtils.getMethodName(invocation), LOADBALANCE_KEY, DEFAULT_LOADBALANCE - ) - ); + return applicationModel + .getExtensionLoader(LoadBalance.class) + .getExtension(invokers.get(0) + .getUrl() + .getMethodParameter( + RpcUtils.getMethodName(invocation), LOADBALANCE_KEY, DEFAULT_LOADBALANCE)); } else { return applicationModel.getExtensionLoader(LoadBalance.class).getExtension(DEFAULT_LOADBALANCE); } } - private Invoker setContext(Invoker invoker) { return setContext(invoker, null); } @@ -456,7 +485,10 @@ public abstract class AbstractClusterInvoker implements ClusterInvoker { RpcServiceContext context = RpcContext.getServiceContext(); Invoker originInvoker = context.getInvoker(); context.setInvoker(invoker) - .setConsumerUrl(null != consumerUrl ? consumerUrl : RpcContext.getServiceContext().getConsumerUrl()); + .setConsumerUrl( + null != consumerUrl + ? consumerUrl + : RpcContext.getServiceContext().getConsumerUrl()); return (Invoker) originInvoker; } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AvailableClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AvailableClusterInvoker.java index cf71aa2370..184332680d 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AvailableClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/AvailableClusterInvoker.java @@ -36,7 +36,8 @@ public class AvailableClusterInvoker extends AbstractClusterInvoker { } @Override - public Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) throws RpcException { + public Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) + throws RpcException { for (Invoker invoker : invokers) { if (invoker.isAvailable()) { return invokeWithContext(invoker, invocation); @@ -44,5 +45,4 @@ public class AvailableClusterInvoker extends AbstractClusterInvoker { } throw new RpcException("No provider available in " + invokers); } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/BroadcastCluster.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/BroadcastCluster.java index c9798de61a..9c4137dadb 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/BroadcastCluster.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/BroadcastCluster.java @@ -30,5 +30,4 @@ public class BroadcastCluster extends AbstractCluster { public AbstractClusterInvoker doJoin(Directory directory) throws RpcException { return new BroadcastClusterInvoker<>(directory); } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/BroadcastClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/BroadcastClusterInvoker.java index bdf8f6f02e..83141fefb9 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/BroadcastClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/BroadcastClusterInvoker.java @@ -39,7 +39,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_ERRO */ public class BroadcastClusterInvoker extends AbstractClusterInvoker { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(BroadcastClusterInvoker.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(BroadcastClusterInvoker.class); private static final String BROADCAST_FAIL_PERCENT_KEY = "broadcast.fail.percent"; private static final int MAX_BROADCAST_FAIL_PERCENT = 100; private static final int MIN_BROADCAST_FAIL_PERCENT = 0; @@ -50,19 +51,23 @@ public class BroadcastClusterInvoker extends AbstractClusterInvoker { @Override @SuppressWarnings({"unchecked", "rawtypes"}) - public Result doInvoke(final Invocation invocation, List> invokers, LoadBalance loadbalance) throws RpcException { + public Result doInvoke(final Invocation invocation, List> invokers, LoadBalance loadbalance) + throws RpcException { RpcContext.getServiceContext().setInvokers((List) invokers); RpcException exception = null; Result result = null; URL url = getUrl(); // The value range of broadcast.fail.threshold must be 0~100. - // 100 means that an exception will be thrown last, and 0 means that as long as an exception occurs, it will be thrown. + // 100 means that an exception will be thrown last, and 0 means that as long as an exception occurs, it will be + // thrown. // see https://github.com/apache/dubbo/pull/7174 int broadcastFailPercent = url.getParameter(BROADCAST_FAIL_PERCENT_KEY, MAX_BROADCAST_FAIL_PERCENT); if (broadcastFailPercent < MIN_BROADCAST_FAIL_PERCENT || broadcastFailPercent > MAX_BROADCAST_FAIL_PERCENT) { - logger.info(String.format("The value corresponding to the broadcast.fail.percent parameter must be between 0 and 100. " + - "The current setting is %s, which is reset to 100.", broadcastFailPercent)); + logger.info(String.format( + "The value corresponding to the broadcast.fail.percent parameter must be between 0 and 100. " + + "The current setting is %s, which is reset to 100.", + broadcastFailPercent)); broadcastFailPercent = MAX_BROADCAST_FAIL_PERCENT; } @@ -72,17 +77,29 @@ public class BroadcastClusterInvoker extends AbstractClusterInvoker { Invoker invoker = invokers.get(i); RpcContext.RestoreContext restoreContext = new RpcContext.RestoreContext(); try { - RpcInvocation subInvocation = new RpcInvocation(invocation.getTargetServiceUniqueName(), - invocation.getServiceModel(), invocation.getMethodName(), invocation.getServiceName(), invocation.getProtocolServiceKey(), - invocation.getParameterTypes(), invocation.getArguments(), invocation.copyObjectAttachments(), - invocation.getInvoker(), Collections.synchronizedMap(new HashMap<>(invocation.getAttributes())), - invocation instanceof RpcInvocation ? ((RpcInvocation) invocation).getInvokeMode() : null); + RpcInvocation subInvocation = new RpcInvocation( + invocation.getTargetServiceUniqueName(), + invocation.getServiceModel(), + invocation.getMethodName(), + invocation.getServiceName(), + invocation.getProtocolServiceKey(), + invocation.getParameterTypes(), + invocation.getArguments(), + invocation.copyObjectAttachments(), + invocation.getInvoker(), + Collections.synchronizedMap(new HashMap<>(invocation.getAttributes())), + invocation instanceof RpcInvocation ? ((RpcInvocation) invocation).getInvokeMode() : null); result = invokeWithContext(invoker, subInvocation); if (null != result && result.hasException()) { Throwable resultException = result.getException(); if (null != resultException) { exception = getRpcException(result.getException()); - logger.warn(CLUSTER_ERROR_RESPONSE,"provider return error response","",exception.getMessage(),exception); + logger.warn( + CLUSTER_ERROR_RESPONSE, + "provider return error response", + "", + exception.getMessage(), + exception); failIndex++; if (failIndex == failThresholdIndex) { break; @@ -91,7 +108,12 @@ public class BroadcastClusterInvoker extends AbstractClusterInvoker { } } catch (Throwable e) { exception = getRpcException(e); - logger.warn(CLUSTER_ERROR_RESPONSE,"provider return error response","",exception.getMessage(),exception); + logger.warn( + CLUSTER_ERROR_RESPONSE, + "provider return error response", + "", + exception.getMessage(), + exception); failIndex++; if (failIndex == failThresholdIndex) { break; @@ -106,14 +128,15 @@ public class BroadcastClusterInvoker extends AbstractClusterInvoker { if (exception != null) { if (failIndex == failThresholdIndex) { if (logger.isDebugEnabled()) { - logger.debug( - String.format("The number of BroadcastCluster call failures has reached the threshold %s", failThresholdIndex)); - + logger.debug(String.format( + "The number of BroadcastCluster call failures has reached the threshold %s", + failThresholdIndex)); } } else { if (logger.isDebugEnabled()) { - logger.debug(String.format("The number of BroadcastCluster call failures has not reached the threshold %s, fail size is %s", - failThresholdIndex, failIndex)); + logger.debug(String.format( + "The number of BroadcastCluster call failures has not reached the threshold %s, fail size is %s", + failThresholdIndex, failIndex)); } } throw exception; diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java index eca3993964..591f16a377 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ClusterUtils.java @@ -26,7 +26,6 @@ import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.URL_MERGE_PROCESSOR_KEY; - /** * ClusterUtils */ @@ -45,9 +44,13 @@ public class ClusterUtils implements ScopeModelAware { ProviderURLMergeProcessor providerUrlMergeProcessor; if (StringUtils.isNotEmpty(ump)) { - providerUrlMergeProcessor = applicationModel.getExtensionLoader(ProviderURLMergeProcessor.class).getExtension(ump); + providerUrlMergeProcessor = applicationModel + .getExtensionLoader(ProviderURLMergeProcessor.class) + .getExtension(ump); } else { - providerUrlMergeProcessor = applicationModel.getExtensionLoader(ProviderURLMergeProcessor.class).getExtension("default"); + providerUrlMergeProcessor = applicationModel + .getExtensionLoader(ProviderURLMergeProcessor.class) + .getExtension("default"); } return providerUrlMergeProcessor.mergeUrl(remoteUrl, localMap); @@ -58,13 +61,15 @@ public class ClusterUtils implements ScopeModelAware { ProviderURLMergeProcessor providerUrlMergeProcessor; if (StringUtils.isNotEmpty(ump)) { - providerUrlMergeProcessor = applicationModel.getExtensionLoader(ProviderURLMergeProcessor.class).getExtension(ump); + providerUrlMergeProcessor = applicationModel + .getExtensionLoader(ProviderURLMergeProcessor.class) + .getExtension(ump); } else { - providerUrlMergeProcessor = applicationModel.getExtensionLoader(ProviderURLMergeProcessor.class).getExtension("default"); + providerUrlMergeProcessor = applicationModel + .getExtensionLoader(ProviderURLMergeProcessor.class) + .getExtension("default"); } return providerUrlMergeProcessor.mergeLocalParams(localMap); - } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailbackCluster.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailbackCluster.java index 0916f724bc..7bfaadef9d 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailbackCluster.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailbackCluster.java @@ -26,11 +26,10 @@ import org.apache.dubbo.rpc.cluster.support.wrapper.AbstractCluster; */ public class FailbackCluster extends AbstractCluster { - public final static String NAME = "failback"; + public static final String NAME = "failback"; @Override public AbstractClusterInvoker doJoin(Directory directory) throws RpcException { return new FailbackClusterInvoker<>(directory); } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvoker.java index 1a20839768..5dbc97d105 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvoker.java @@ -53,7 +53,8 @@ import static org.apache.dubbo.rpc.cluster.Constants.FAIL_BACK_TASKS_KEY; */ public class FailbackClusterInvoker extends AbstractClusterInvoker { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FailbackClusterInvoker.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(FailbackClusterInvoker.class); private static final long RETRY_FAILED_PERIOD = 5; @@ -81,27 +82,41 @@ public class FailbackClusterInvoker extends AbstractClusterInvoker { failbackTasks = failbackTasksConfig; } - private void addFailed(LoadBalance loadbalance, Invocation invocation, List> invokers, Invoker lastInvoker, URL consumerUrl) { + private void addFailed( + LoadBalance loadbalance, + Invocation invocation, + List> invokers, + Invoker lastInvoker, + URL consumerUrl) { if (failTimer == null) { synchronized (this) { if (failTimer == null) { failTimer = new HashedWheelTimer( - new NamedThreadFactory("failback-cluster-timer", true), - 1, - TimeUnit.SECONDS, 32, failbackTasks); + new NamedThreadFactory("failback-cluster-timer", true), + 1, + TimeUnit.SECONDS, + 32, + failbackTasks); } } } - RetryTimerTask retryTimerTask = new RetryTimerTask(loadbalance, invocation, invokers, lastInvoker, retries, RETRY_FAILED_PERIOD, consumerUrl); + RetryTimerTask retryTimerTask = new RetryTimerTask( + loadbalance, invocation, invokers, lastInvoker, retries, RETRY_FAILED_PERIOD, consumerUrl); try { failTimer.newTimeout(retryTimerTask, RETRY_FAILED_PERIOD, TimeUnit.SECONDS); } catch (Throwable e) { - logger.error(CLUSTER_TIMER_RETRY_FAILED,"add newTimeout exception","","Failback background works error, invocation->" + invocation + ", exception: " + e.getMessage(),e); + logger.error( + CLUSTER_TIMER_RETRY_FAILED, + "add newTimeout exception", + "", + "Failback background works error, invocation->" + invocation + ", exception: " + e.getMessage(), + e); } } @Override - protected Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) throws RpcException { + protected Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) + throws RpcException { Invoker invoker = null; URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl(); try { @@ -110,10 +125,14 @@ public class FailbackClusterInvoker extends AbstractClusterInvoker { // Then the serviceContext will be cleared after the call is completed. return invokeWithContextAsync(invoker, invocation, consumerUrl); } catch (Throwable e) { - logger.error(CLUSTER_FAILED_INVOKE_SERVICE,"Failback to invoke method and start to retries", - "","Failback to invoke method " + RpcUtils.getMethodName(invocation) + - ", wait for retry in background. Ignored exception: " - + e.getMessage() + ", ",e); + logger.error( + CLUSTER_FAILED_INVOKE_SERVICE, + "Failback to invoke method and start to retries", + "", + "Failback to invoke method " + RpcUtils.getMethodName(invocation) + + ", wait for retry in background. Ignored exception: " + + e.getMessage() + ", ", + e); if (retries > 0) { addFailed(loadbalance, invocation, invokers, invoker, consumerUrl); } @@ -150,8 +169,14 @@ public class FailbackClusterInvoker extends AbstractClusterInvoker { */ private int retriedTimes = 0; - RetryTimerTask(LoadBalance loadbalance, Invocation invocation, List> invokers, Invoker lastInvoker, - int retries, long tick, URL consumerUrl) { + RetryTimerTask( + LoadBalance loadbalance, + Invocation invocation, + List> invokers, + Invoker lastInvoker, + int retries, + long tick, + URL consumerUrl) { this.loadbalance = loadbalance; this.invocation = invocation; this.invokers = invokers; @@ -164,15 +189,28 @@ public class FailbackClusterInvoker extends AbstractClusterInvoker { @Override public void run(Timeout timeout) { try { - logger.info("Attempt to retry to invoke method " + RpcUtils.getMethodName(invocation) + - ". The total will retry " + retries + " times, the current is the " + retriedTimes + " retry"); - Invoker retryInvoker = select(loadbalance, invocation, invokers, Collections.singletonList(lastInvoker)); + logger.info("Attempt to retry to invoke method " + RpcUtils.getMethodName(invocation) + + ". The total will retry " + retries + " times, the current is the " + retriedTimes + + " retry"); + Invoker retryInvoker = + select(loadbalance, invocation, invokers, Collections.singletonList(lastInvoker)); lastInvoker = retryInvoker; invokeWithContextAsync(retryInvoker, invocation, consumerUrl); } catch (Throwable e) { - logger.error(CLUSTER_FAILED_INVOKE_SERVICE,"Failed retry to invoke method","","Failed retry to invoke method " + RpcUtils.getMethodName(invocation) + ", waiting again.",e); + logger.error( + CLUSTER_FAILED_INVOKE_SERVICE, + "Failed retry to invoke method", + "", + "Failed retry to invoke method " + RpcUtils.getMethodName(invocation) + ", waiting again.", + e); if ((++retriedTimes) >= retries) { - logger.error(CLUSTER_FAILED_INVOKE_SERVICE,"Failed retry to invoke method and retry times exceed threshold","","Failed retry times exceed threshold (" + retries + "), We have to abandon, invocation->" + invocation,e); + logger.error( + CLUSTER_FAILED_INVOKE_SERVICE, + "Failed retry to invoke method and retry times exceed threshold", + "", + "Failed retry times exceed threshold (" + retries + "), We have to abandon, invocation->" + + invocation, + e); } else { rePut(timeout); } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailfastCluster.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailfastCluster.java index 2a04a1535b..0c9fe5a1d2 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailfastCluster.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailfastCluster.java @@ -26,11 +26,10 @@ import org.apache.dubbo.rpc.cluster.support.wrapper.AbstractCluster; */ public class FailfastCluster extends AbstractCluster { - public final static String NAME = "failfast"; + public static final String NAME = "failfast"; @Override public AbstractClusterInvoker doJoin(Directory directory) throws RpcException { return new FailfastClusterInvoker<>(directory); } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailfastClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailfastClusterInvoker.java index 87b3b45c5a..f8f7e04dbc 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailfastClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailfastClusterInvoker.java @@ -41,7 +41,8 @@ public class FailfastClusterInvoker extends AbstractClusterInvoker { } @Override - public Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) throws RpcException { + public Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) + throws RpcException { Invoker invoker = select(loadbalance, invocation, invokers, null); try { return invokeWithContext(invoker, invocation); @@ -49,13 +50,16 @@ public class FailfastClusterInvoker extends AbstractClusterInvoker { if (e instanceof RpcException && ((RpcException) e).isBiz()) { // biz exception. throw (RpcException) e; } - throw new RpcException(e instanceof RpcException ? ((RpcException) e).getCode() : 0, - "Failfast invoke providers " + invoker.getUrl() + " " + loadbalance.getClass().getSimpleName() - + " for service " + getInterface().getName() - + " method " + RpcUtils.getMethodName(invocation) + " on consumer " + NetUtils.getLocalHost() - + " use dubbo version " + Version.getVersion() - + ", but no luck to perform the invocation. Last error is: " + e.getMessage(), - e.getCause() != null ? e.getCause() : e); + throw new RpcException( + e instanceof RpcException ? ((RpcException) e).getCode() : 0, + "Failfast invoke providers " + invoker.getUrl() + " " + + loadbalance.getClass().getSimpleName() + + " for service " + getInterface().getName() + + " method " + RpcUtils.getMethodName(invocation) + " on consumer " + + NetUtils.getLocalHost() + + " use dubbo version " + Version.getVersion() + + ", but no luck to perform the invocation. Last error is: " + e.getMessage(), + e.getCause() != null ? e.getCause() : e); } } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailoverCluster.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailoverCluster.java index e9e6101b05..7bf6b3300f 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailoverCluster.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailoverCluster.java @@ -26,11 +26,10 @@ import org.apache.dubbo.rpc.cluster.support.wrapper.AbstractCluster; */ public class FailoverCluster extends AbstractCluster { - public final static String NAME = "failover"; + public static final String NAME = "failover"; @Override public AbstractClusterInvoker doJoin(Directory directory) throws RpcException { return new FailoverClusterInvoker<>(directory); } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvoker.java index b0cdb8ff53..a840773c51 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvoker.java @@ -47,7 +47,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAIL */ public class FailoverClusterInvoker extends AbstractClusterInvoker { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FailoverClusterInvoker.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(FailoverClusterInvoker.class); public FailoverClusterInvoker(Directory directory) { super(directory); @@ -55,7 +56,8 @@ public class FailoverClusterInvoker extends AbstractClusterInvoker { @Override @SuppressWarnings({"unchecked", "rawtypes"}) - public Result doInvoke(Invocation invocation, final List> invokers, LoadBalance loadbalance) throws RpcException { + public Result doInvoke(Invocation invocation, final List> invokers, LoadBalance loadbalance) + throws RpcException { List> copyInvokers = invokers; String methodName = RpcUtils.getMethodName(invocation); int len = calculateInvokeTimes(methodName); @@ -64,8 +66,8 @@ public class FailoverClusterInvoker extends AbstractClusterInvoker { List> invoked = new ArrayList>(copyInvokers.size()); // invoked invokers. Set providers = new HashSet(len); for (int i = 0; i < len; i++) { - //Reselect before retry to avoid a change of candidate `invokers`. - //NOTE: if `invokers` changed, then `invoked` also lose accuracy. + // Reselect before retry to avoid a change of candidate `invokers`. + // NOTE: if `invokers` changed, then `invoked` also lose accuracy. if (i > 0) { checkWhetherDestroyed(); copyInvokers = list(invocation); @@ -79,15 +81,22 @@ public class FailoverClusterInvoker extends AbstractClusterInvoker { try { Result result = invokeWithContext(invoker, invocation); if (le != null && logger.isWarnEnabled()) { - logger.warn(CLUSTER_FAILED_MULTIPLE_RETRIES,"failed to retry do invoke","","Although retry the method " + methodName - + " in the service " + getInterface().getName() - + " was successful by the provider " + invoker.getUrl().getAddress() - + ", but there have been failed providers " + providers - + " (" + providers.size() + "/" + copyInvokers.size() - + ") from the registry " + directory.getUrl().getAddress() - + " on the consumer " + NetUtils.getLocalHost() - + " using the dubbo version " + Version.getVersion() + ". Last error is: " - + le.getMessage(),le); + logger.warn( + CLUSTER_FAILED_MULTIPLE_RETRIES, + "failed to retry do invoke", + "", + "Although retry the method " + methodName + + " in the service " + getInterface().getName() + + " was successful by the provider " + + invoker.getUrl().getAddress() + + ", but there have been failed providers " + providers + + " (" + providers.size() + "/" + copyInvokers.size() + + ") from the registry " + + directory.getUrl().getAddress() + + " on the consumer " + NetUtils.getLocalHost() + + " using the dubbo version " + Version.getVersion() + ". Last error is: " + + le.getMessage(), + le); } success = true; return result; @@ -104,14 +113,17 @@ public class FailoverClusterInvoker extends AbstractClusterInvoker { } } } - throw new RpcException(le.getCode(), "Failed to invoke the method " - + methodName + " in the service " + getInterface().getName() - + ". Tried " + len + " times of the providers " + providers - + " (" + providers.size() + "/" + copyInvokers.size() - + ") from the registry " + directory.getUrl().getAddress() - + " on the consumer " + NetUtils.getLocalHost() + " using the dubbo version " - + Version.getVersion() + ". Last error is: " - + le.getMessage(), le.getCause() != null ? le.getCause() : le); + throw new RpcException( + le.getCode(), + "Failed to invoke the method " + + methodName + " in the service " + getInterface().getName() + + ". Tried " + len + " times of the providers " + providers + + " (" + providers.size() + "/" + copyInvokers.size() + + ") from the registry " + directory.getUrl().getAddress() + + " on the consumer " + NetUtils.getLocalHost() + " using the dubbo version " + + Version.getVersion() + ". Last error is: " + + le.getMessage(), + le.getCause() != null ? le.getCause() : le); } private int calculateInvokeTimes(String methodName) { @@ -128,5 +140,4 @@ public class FailoverClusterInvoker extends AbstractClusterInvoker { return len; } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailsafeCluster.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailsafeCluster.java index 7064950489..baaa1191f3 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailsafeCluster.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailsafeCluster.java @@ -26,11 +26,10 @@ import org.apache.dubbo.rpc.cluster.support.wrapper.AbstractCluster; */ public class FailsafeCluster extends AbstractCluster { - public final static String NAME = "failsafe"; + public static final String NAME = "failsafe"; @Override public AbstractClusterInvoker doJoin(Directory directory) throws RpcException { return new FailsafeClusterInvoker<>(directory); } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailsafeClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailsafeClusterInvoker.java index 78c3540895..ba255405c7 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailsafeClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailsafeClusterInvoker.java @@ -38,19 +38,26 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_ERRO * */ public class FailsafeClusterInvoker extends AbstractClusterInvoker { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FailsafeClusterInvoker.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(FailsafeClusterInvoker.class); public FailsafeClusterInvoker(Directory directory) { super(directory); } @Override - public Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) throws RpcException { + public Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) + throws RpcException { try { Invoker invoker = select(loadbalance, invocation, invokers, null); return invokeWithContext(invoker, invocation); } catch (Throwable e) { - logger.error(CLUSTER_ERROR_RESPONSE,"Failsafe for provider exception","","Failsafe ignore exception: " + e.getMessage(),e); + logger.error( + CLUSTER_ERROR_RESPONSE, + "Failsafe for provider exception", + "", + "Failsafe ignore exception: " + e.getMessage(), + e); return AsyncRpcResult.newDefaultAsyncResult(null, null, invocation); // ignore } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingCluster.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingCluster.java index 83ecbb8c3b..82f1784e76 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingCluster.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingCluster.java @@ -26,11 +26,10 @@ import org.apache.dubbo.rpc.cluster.support.wrapper.AbstractCluster; */ public class ForkingCluster extends AbstractCluster { - public final static String NAME = "forking"; + public static final String NAME = "forking"; @Override public AbstractClusterInvoker doJoin(Directory directory) throws RpcException { return new ForkingClusterInvoker<>(directory); } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvoker.java index b2f0d2e095..b9d67834f3 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvoker.java @@ -59,13 +59,18 @@ public class ForkingClusterInvoker extends AbstractClusterInvoker { public ForkingClusterInvoker(Directory directory) { super(directory); - executor = directory.getUrl().getOrDefaultFrameworkModel().getBeanFactory() - .getBean(FrameworkExecutorRepository.class).getSharedExecutor(); + executor = directory + .getUrl() + .getOrDefaultFrameworkModel() + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class) + .getSharedExecutor(); } @Override @SuppressWarnings({"unchecked", "rawtypes"}) - public Result doInvoke(final Invocation invocation, List> invokers, LoadBalance loadbalance) throws RpcException { + public Result doInvoke(final Invocation invocation, List> invokers, LoadBalance loadbalance) + throws RpcException { try { final List> selected; final int forks = getUrl().getParameter(FORKS_KEY, DEFAULT_FORKS); @@ -77,7 +82,7 @@ public class ForkingClusterInvoker extends AbstractClusterInvoker { while (selected.size() < forks) { Invoker invoker = select(loadbalance, invocation, invokers, selected); if (!selected.contains(invoker)) { - //Avoid add the same invoker several times. + // Avoid add the same invoker several times. selected.add(invoker); } } @@ -87,34 +92,43 @@ public class ForkingClusterInvoker extends AbstractClusterInvoker { final BlockingQueue ref = new LinkedBlockingQueue<>(1); selected.forEach(invoker -> { URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl(); - CompletableFuture.supplyAsync(() -> { - if (ref.size() > 0) { - return null; - } - return invokeWithContextAsync(invoker, invocation, consumerUrl); - }, executor).whenComplete((v, t) -> { - if (t == null) { - ref.offer(v); - } else { - int value = count.incrementAndGet(); - if (value >= selected.size()) { - ref.offer(t); - } - } - }); + CompletableFuture.supplyAsync( + () -> { + if (ref.size() > 0) { + return null; + } + return invokeWithContextAsync(invoker, invocation, consumerUrl); + }, + executor) + .whenComplete((v, t) -> { + if (t == null) { + ref.offer(v); + } else { + int value = count.incrementAndGet(); + if (value >= selected.size()) { + ref.offer(t); + } + } + }); }); try { Object ret = ref.poll(timeout, TimeUnit.MILLISECONDS); if (ret instanceof Throwable) { - Throwable e = ret instanceof CompletionException ? ((CompletionException) ret).getCause() : (Throwable) ret; - throw new RpcException(e instanceof RpcException ? ((RpcException) e).getCode() : RpcException.UNKNOWN_EXCEPTION, - "Failed to forking invoke provider " + selected + ", but no luck to perform the invocation. " + - "Last error is: " + e.getMessage(), e.getCause() != null ? e.getCause() : e); + Throwable e = ret instanceof CompletionException + ? ((CompletionException) ret).getCause() + : (Throwable) ret; + throw new RpcException( + e instanceof RpcException ? ((RpcException) e).getCode() : RpcException.UNKNOWN_EXCEPTION, + "Failed to forking invoke provider " + selected + + ", but no luck to perform the invocation. " + "Last error is: " + e.getMessage(), + e.getCause() != null ? e.getCause() : e); } return (Result) ret; } catch (InterruptedException e) { - throw new RpcException("Failed to forking invoke provider " + selected + ", " + - "but no luck to perform the invocation. Last error is: " + e.getMessage(), e); + throw new RpcException( + "Failed to forking invoke provider " + selected + ", " + + "but no luck to perform the invocation. Last error is: " + e.getMessage(), + e); } } finally { // clear attachments which is binding to current thread. diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/merger/DefaultProviderURLMergeProcessor.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/merger/DefaultProviderURLMergeProcessor.java index 8610bc893f..8a97a0f21f 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/merger/DefaultProviderURLMergeProcessor.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/merger/DefaultProviderURLMergeProcessor.java @@ -43,7 +43,6 @@ import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; - public class DefaultProviderURLMergeProcessor implements ProviderURLMergeProcessor { @Override @@ -104,14 +103,18 @@ public class DefaultProviderURLMergeProcessor implements ProviderURLMergeProcess // Combine filters and listeners on Provider and Consumer String remoteFilter = remoteMap.get(REFERENCE_FILTER_KEY); String localFilter = copyOfLocalMap.get(REFERENCE_FILTER_KEY); - if (remoteFilter != null && remoteFilter.length() > 0 - && localFilter != null && localFilter.length() > 0) { + if (remoteFilter != null + && remoteFilter.length() > 0 + && localFilter != null + && localFilter.length() > 0) { map.put(REFERENCE_FILTER_KEY, remoteFilter + "," + localFilter); } String remoteListener = remoteMap.get(INVOKER_LISTENER_KEY); String localListener = copyOfLocalMap.get(INVOKER_LISTENER_KEY); - if (remoteListener != null && remoteListener.length() > 0 - && localListener != null && localListener.length() > 0) { + if (remoteListener != null + && remoteListener.length() > 0 + && localListener != null + && localListener.length() > 0) { map.put(INVOKER_LISTENER_KEY, remoteListener + "," + localListener); } } @@ -119,5 +122,4 @@ public class DefaultProviderURLMergeProcessor implements ProviderURLMergeProcess return remoteUrl.clearParameters().addParameters(map); } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/registry/ZoneAwareCluster.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/registry/ZoneAwareCluster.java index cfd36e1254..a1cbf14e60 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/registry/ZoneAwareCluster.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/registry/ZoneAwareCluster.java @@ -23,11 +23,10 @@ import org.apache.dubbo.rpc.cluster.support.wrapper.AbstractCluster; public class ZoneAwareCluster extends AbstractCluster { - public final static String NAME = "zone-aware"; + public static final String NAME = "zone-aware"; @Override protected AbstractClusterInvoker doJoin(Directory directory) throws RpcException { return new ZoneAwareClusterInvoker(directory); } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/registry/ZoneAwareClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/registry/ZoneAwareClusterInvoker.java index f6550cb8af..c537f03381 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/registry/ZoneAwareClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/registry/ZoneAwareClusterInvoker.java @@ -55,7 +55,8 @@ public class ZoneAwareClusterInvoker extends AbstractClusterInvoker { public ZoneAwareClusterInvoker(Directory directory) { super(directory); - ExtensionLoader loader = directory.getConsumerUrl().getOrDefaultApplicationModel().getExtensionLoader(ZoneDetector.class); + ExtensionLoader loader = + directory.getConsumerUrl().getOrDefaultApplicationModel().getExtensionLoader(ZoneDetector.class); if (loader.hasExtension("default")) { zoneDetector = loader.getExtension("default"); } @@ -63,12 +64,13 @@ public class ZoneAwareClusterInvoker extends AbstractClusterInvoker { @Override @SuppressWarnings({"unchecked", "rawtypes"}) - public Result doInvoke(Invocation invocation, final List> invokers, LoadBalance loadbalance) throws RpcException { - // First, pick the invoker (XXXClusterInvoker) that comes from the local registry, distinguish by a 'preferred' key. + public Result doInvoke(Invocation invocation, final List> invokers, LoadBalance loadbalance) + throws RpcException { + // First, pick the invoker (XXXClusterInvoker) that comes from the local registry, distinguish by a 'preferred' + // key. for (Invoker invoker : invokers) { ClusterInvoker clusterInvoker = (ClusterInvoker) invoker; - if (clusterInvoker.isAvailable() && clusterInvoker.getRegistryUrl() - .getParameter(PREFERRED_KEY, false)) { + if (clusterInvoker.isAvailable() && clusterInvoker.getRegistryUrl().getParameter(PREFERRED_KEY, false)) { return clusterInvoker.invoke(invocation); } } @@ -85,25 +87,32 @@ public class ZoneAwareClusterInvoker extends AbstractClusterInvoker { if (StringUtils.isNotEmpty(zone)) { for (Invoker invoker : invokers) { ClusterInvoker clusterInvoker = (ClusterInvoker) invoker; - if (clusterInvoker.isAvailable() && zone.equals(clusterInvoker.getRegistryUrl().getParameter(ZONE_KEY))) { + if (clusterInvoker.isAvailable() + && zone.equals(clusterInvoker.getRegistryUrl().getParameter(ZONE_KEY))) { return clusterInvoker.invoke(invocation); } } if (StringUtils.isNotEmpty(force) && "true".equalsIgnoreCase(force)) { - throw new IllegalStateException("No registry instance in zone or no available providers in the registry, zone: " - + zone - + ", registries: " + invokers.stream().map(invoker -> ((ClusterInvoker) invoker).getRegistryUrl().toString()).collect(Collectors.joining(","))); + throw new IllegalStateException( + "No registry instance in zone or no available providers in the registry, zone: " + + zone + + ", registries: " + + invokers.stream() + .map(invoker -> ((ClusterInvoker) invoker) + .getRegistryUrl() + .toString()) + .collect(Collectors.joining(","))); } } - // load balance among all registries, with registry weight count in. Invoker balancedInvoker = select(loadbalance, invocation, invokers, null); - if (balancedInvoker!=null && balancedInvoker.isAvailable()) { + if (balancedInvoker != null && balancedInvoker.isAvailable()) { return balancedInvoker.invoke(invocation); } - // If none of the invokers has a preferred signal or is picked by the loadbalancer, pick the first one available. + // If none of the invokers has a preferred signal or is picked by the loadbalancer, pick the first one + // available. for (Invoker invoker : invokers) { ClusterInvoker clusterInvoker = (ClusterInvoker) invoker; if (clusterInvoker.isAvailable()) { @@ -113,5 +122,4 @@ public class ZoneAwareClusterInvoker extends AbstractClusterInvoker { throw new RpcException("No provider available in " + invokers); } - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/AbstractCluster.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/AbstractCluster.java index 2a19a54e68..98082f971c 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/AbstractCluster.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/AbstractCluster.java @@ -45,7 +45,10 @@ public abstract class AbstractCluster implements Cluster { private Invoker buildClusterInterceptors(AbstractClusterInvoker clusterInvoker) { AbstractClusterInvoker last = buildInterceptorInvoker(new ClusterFilterInvoker<>(clusterInvoker)); - if (Boolean.parseBoolean(ConfigurationUtils.getProperty(clusterInvoker.getDirectory().getConsumerUrl().getScopeModel(), CLUSTER_INTERCEPTOR_COMPATIBLE_KEY, "false"))) { + if (Boolean.parseBoolean(ConfigurationUtils.getProperty( + clusterInvoker.getDirectory().getConsumerUrl().getScopeModel(), + CLUSTER_INTERCEPTOR_COMPATIBLE_KEY, + "false"))) { return build27xCompatibleClusterInterceptors(clusterInvoker, last); } return last; @@ -61,7 +64,10 @@ public abstract class AbstractCluster implements Cluster { } private AbstractClusterInvoker buildInterceptorInvoker(AbstractClusterInvoker invoker) { - List builders = ScopeModelUtil.getApplicationModel(invoker.getUrl().getScopeModel()).getExtensionLoader(InvocationInterceptorBuilder.class).getActivateExtensions(); + List builders = ScopeModelUtil.getApplicationModel( + invoker.getUrl().getScopeModel()) + .getExtensionLoader(InvocationInterceptorBuilder.class) + .getActivateExtensions(); if (CollectionUtils.isEmpty(builders)) { return invoker; } @@ -74,13 +80,17 @@ public abstract class AbstractCluster implements Cluster { private final ClusterInvoker filterInvoker; public ClusterFilterInvoker(AbstractClusterInvoker invoker) { - List builders = ScopeModelUtil.getApplicationModel(invoker.getUrl().getScopeModel()).getExtensionLoader(FilterChainBuilder.class).getActivateExtensions(); + List builders = ScopeModelUtil.getApplicationModel( + invoker.getUrl().getScopeModel()) + .getExtensionLoader(FilterChainBuilder.class) + .getActivateExtensions(); if (CollectionUtils.isEmpty(builders)) { filterInvoker = invoker; } else { ClusterInvoker tmpInvoker = invoker; for (FilterChainBuilder builder : builders) { - tmpInvoker = builder.buildClusterInvokerChain(tmpInvoker, REFERENCE_FILTER_KEY, CommonConstants.CONSUMER); + tmpInvoker = builder.buildClusterInvokerChain( + tmpInvoker, REFERENCE_FILTER_KEY, CommonConstants.CONSUMER); } filterInvoker = tmpInvoker; } @@ -96,8 +106,6 @@ public abstract class AbstractCluster implements Cluster { return filterInvoker.getDirectory(); } - - @Override public URL getRegistryUrl() { return filterInvoker.getRegistryUrl(); @@ -118,8 +126,9 @@ public abstract class AbstractCluster implements Cluster { * Use ClusterInvoker to replace AbstractClusterInvoker in the future. */ @Override - protected Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) throws RpcException { - return null; + protected Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) + throws RpcException { + return null; } public ClusterInvoker getFilterInvoker() { @@ -130,10 +139,12 @@ public abstract class AbstractCluster implements Cluster { static class InvocationInterceptorInvoker extends AbstractClusterInvoker { private ClusterInvoker interceptorInvoker; - public InvocationInterceptorInvoker(AbstractClusterInvoker invoker, List builders) { + public InvocationInterceptorInvoker( + AbstractClusterInvoker invoker, List builders) { ClusterInvoker tmpInvoker = invoker; for (InvocationInterceptorBuilder builder : builders) { - tmpInvoker = builder.buildClusterInterceptorChain(tmpInvoker, INVOCATION_INTERCEPTOR_KEY, CommonConstants.CONSUMER); + tmpInvoker = builder.buildClusterInterceptorChain( + tmpInvoker, INVOCATION_INTERCEPTOR_KEY, CommonConstants.CONSUMER); } interceptorInvoker = tmpInvoker; } @@ -168,14 +179,19 @@ public abstract class AbstractCluster implements Cluster { * Use ClusterInvoker to replace AbstractClusterInvoker in the future. */ @Override - protected Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) throws RpcException { + protected Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) + throws RpcException { return null; } } @Deprecated - private ClusterInvoker build27xCompatibleClusterInterceptors(AbstractClusterInvoker clusterInvoker, AbstractClusterInvoker last) { - List interceptors = ScopeModelUtil.getApplicationModel(clusterInvoker.getUrl().getScopeModel()).getExtensionLoader(ClusterInterceptor.class).getActivateExtensions(); + private ClusterInvoker build27xCompatibleClusterInterceptors( + AbstractClusterInvoker clusterInvoker, AbstractClusterInvoker last) { + List interceptors = ScopeModelUtil.getApplicationModel( + clusterInvoker.getUrl().getScopeModel()) + .getExtensionLoader(ClusterInterceptor.class) + .getActivateExtensions(); if (!interceptors.isEmpty()) { for (int i = interceptors.size() - 1; i >= 0; i--) { @@ -194,9 +210,10 @@ public abstract class AbstractCluster implements Cluster { private final ClusterInterceptor interceptor; private final AbstractClusterInvoker next; - public InterceptorInvokerNode(AbstractClusterInvoker clusterInvoker, - ClusterInterceptor interceptor, - AbstractClusterInvoker next) { + public InterceptorInvokerNode( + AbstractClusterInvoker clusterInvoker, + ClusterInterceptor interceptor, + AbstractClusterInvoker next) { this.clusterInvoker = clusterInvoker; this.interceptor = interceptor; this.next = next; @@ -257,11 +274,10 @@ public abstract class AbstractCluster implements Cluster { } @Override - protected Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) throws RpcException { + protected Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) + throws RpcException { // The only purpose is to build an interceptor chain, so the cluster related logic doesn't matter. return null; } } - - } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterInvoker.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterInvoker.java index d1d47645f7..50e172b149 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterInvoker.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterInvoker.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.support.wrapper; import org.apache.dubbo.common.URL; @@ -62,7 +61,6 @@ public class ScopeClusterInvoker implements ClusterInvoker, ExporterChange private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ScopeClusterInvoker.class); - private final Object createLock = new Object(); private Protocol protocolSPI; private final Directory directory; @@ -144,26 +142,30 @@ public class ScopeClusterInvoker implements ClusterInvoker, ExporterChange // When broadcasting, it should be called remotely. if (isBroadcast()) { if (logger.isDebugEnabled()) { - logger.debug("Performing broadcast call for method: " + RpcUtils.getMethodName(invocation) + " of service: " + getUrl().getServiceKey()); + logger.debug("Performing broadcast call for method: " + RpcUtils.getMethodName(invocation) + + " of service: " + getUrl().getServiceKey()); } return invoker.invoke(invocation); } if (peerFlag) { if (logger.isDebugEnabled()) { - logger.debug("Performing point-to-point call for method: " + RpcUtils.getMethodName(invocation) + " of service: " + getUrl().getServiceKey()); + logger.debug("Performing point-to-point call for method: " + RpcUtils.getMethodName(invocation) + + " of service: " + getUrl().getServiceKey()); } // If it's a point-to-point direct connection, invoke the original Invoker return invoker.invoke(invocation); } if (isInjvmExported()) { if (logger.isDebugEnabled()) { - logger.debug("Performing local JVM call for method: " + RpcUtils.getMethodName(invocation) + " of service: " + getUrl().getServiceKey()); + logger.debug("Performing local JVM call for method: " + RpcUtils.getMethodName(invocation) + + " of service: " + getUrl().getServiceKey()); } // If it's exported to the local JVM, invoke the corresponding Invoker return injvmInvoker.invoke(invocation); } if (logger.isDebugEnabled()) { - logger.debug("Performing remote call for method: " + RpcUtils.getMethodName(invocation) + " of service: " + getUrl().getServiceKey()); + logger.debug("Performing remote call for method: " + RpcUtils.getMethodName(invocation) + " of service: " + + getUrl().getServiceKey()); } // Otherwise, delegate the invocation to the original Invoker return invoker.invoke(invocation); @@ -179,7 +181,7 @@ public class ScopeClusterInvoker implements ClusterInvoker, ExporterChange return; } if (getUrl().getServiceKey().equals(exporter.getInvoker().getUrl().getServiceKey()) - && exporter.getInvoker().getUrl().getProtocol().equalsIgnoreCase(LOCAL_PROTOCOL)) { + && exporter.getInvoker().getUrl().getProtocol().equalsIgnoreCase(LOCAL_PROTOCOL)) { createInjvmInvoker(exporter); isExported.compareAndSet(false, true); } @@ -188,7 +190,7 @@ public class ScopeClusterInvoker implements ClusterInvoker, ExporterChange @Override public void onExporterChangeUnExport(Exporter exporter) { if (getUrl().getServiceKey().equals(exporter.getInvoker().getUrl().getServiceKey()) - && exporter.getInvoker().getUrl().getProtocol().equalsIgnoreCase(LOCAL_PROTOCOL)) { + && exporter.getInvoker().getUrl().getProtocol().equalsIgnoreCase(LOCAL_PROTOCOL)) { destroyInjvmInvoker(); isExported.compareAndSet(true, false); } @@ -211,21 +213,26 @@ public class ScopeClusterInvoker implements ClusterInvoker, ExporterChange return; } // Check if the service has been exported through Injvm protocol - if (injvmInvoker == null && LOCAL_PROTOCOL.equalsIgnoreCase(getRegistryUrl().getProtocol())) { + if (injvmInvoker == null + && LOCAL_PROTOCOL.equalsIgnoreCase(getRegistryUrl().getProtocol())) { injvmInvoker = invoker; isExported.compareAndSet(false, true); injvmFlag = true; return; } // Check if the service has been exported through Injvm protocol or the SCOPE_LOCAL parameter is set - if (Boolean.TRUE.toString().equalsIgnoreCase(isInjvm) || SCOPE_LOCAL.equalsIgnoreCase(getUrl().getParameter(SCOPE_KEY))) { + if (Boolean.TRUE.toString().equalsIgnoreCase(isInjvm) + || SCOPE_LOCAL.equalsIgnoreCase(getUrl().getParameter(SCOPE_KEY))) { injvmFlag = true; } else if (isInjvm == null) { injvmFlag = isNotRemoteOrGeneric(); } - protocolSPI = getUrl().getApplicationModel().getExtensionLoader(Protocol.class).getAdaptiveExtension(); - injvmExporterListener = getUrl().getOrDefaultFrameworkModel().getBeanFactory().getBean(InjvmExporterListener.class); + protocolSPI = getUrl().getApplicationModel() + .getExtensionLoader(Protocol.class) + .getAdaptiveExtension(); + injvmExporterListener = + getUrl().getOrDefaultFrameworkModel().getBeanFactory().getBean(InjvmExporterListener.class); injvmExporterListener.addExporterChangeListener(this, getUrl().getServiceKey()); } @@ -235,8 +242,8 @@ public class ScopeClusterInvoker implements ClusterInvoker, ExporterChange * @return boolean */ private boolean isNotRemoteOrGeneric() { - return !SCOPE_REMOTE.equalsIgnoreCase(getUrl().getParameter(SCOPE_KEY)) && - !getUrl().getParameter(GENERIC_KEY, false); + return !SCOPE_REMOTE.equalsIgnoreCase(getUrl().getParameter(SCOPE_KEY)) + && !getUrl().getParameter(GENERIC_KEY, false); } /** @@ -262,15 +269,16 @@ public class ScopeClusterInvoker implements ClusterInvoker, ExporterChange // When calling locally, determine whether it does not meet the requirements if (!isExportedValue && (isForceLocal() || localOnce)) { // If it's supposed to be exported to the local JVM ,but it's not, throw an exception - throw new RpcException("Local service for " + getUrl().getServiceInterface() + " has not been exposed yet!"); + throw new RpcException( + "Local service for " + getUrl().getServiceInterface() + " has not been exposed yet!"); } return isExportedValue && injvmFlag; } private boolean isForceLocal() { - return SCOPE_LOCAL.equalsIgnoreCase(getUrl().getParameter(SCOPE_KEY)) || - Boolean.TRUE.toString().equalsIgnoreCase(getUrl().getParameter(LOCAL_PROTOCOL)); + return SCOPE_LOCAL.equalsIgnoreCase(getUrl().getParameter(SCOPE_KEY)) + || Boolean.TRUE.toString().equalsIgnoreCase(getUrl().getParameter(LOCAL_PROTOCOL)); } /** @@ -280,18 +288,26 @@ public class ScopeClusterInvoker implements ClusterInvoker, ExporterChange if (injvmInvoker == null) { synchronized (createLock) { if (injvmInvoker == null) { - URL url = new ServiceConfigURL(LOCAL_PROTOCOL, NetUtils.getLocalHost(), getUrl().getPort(), - getInterface().getName(), getUrl().getParameters()); + URL url = new ServiceConfigURL( + LOCAL_PROTOCOL, + NetUtils.getLocalHost(), + getUrl().getPort(), + getInterface().getName(), + getUrl().getParameters()); url = url.setScopeModel(getUrl().getScopeModel()); url = url.setServiceModel(getUrl().getServiceModel()); - DubboServiceAddressURL consumerUrl = new DubboServiceAddressURL(url.getUrlAddress(), url.getUrlParam(), - exporter.getInvoker().getUrl(), null); + DubboServiceAddressURL consumerUrl = new DubboServiceAddressURL( + url.getUrlAddress(), + url.getUrlParam(), + exporter.getInvoker().getUrl(), + null); Invoker invoker = protocolSPI.refer(getInterface(), consumerUrl); List> invokers = new ArrayList<>(); invokers.add(invoker); - injvmInvoker = Cluster.getCluster(url.getScopeModel(), Cluster.DEFAULT, false).join(new StaticDirectory(url, invokers), true); + injvmInvoker = Cluster.getCluster(url.getScopeModel(), Cluster.DEFAULT, false) + .join(new StaticDirectory(url, invokers), true); } } } @@ -309,11 +325,10 @@ public class ScopeClusterInvoker implements ClusterInvoker, ExporterChange @Override public String toString() { - return "ScopeClusterInvoker{" + - "directory=" + directory + - ", isExported=" + isExported + - ", peerFlag=" + peerFlag + - ", injvmFlag=" + injvmFlag + - '}'; + return "ScopeClusterInvoker{" + "directory=" + + directory + ", isExported=" + + isExported + ", peerFlag=" + + peerFlag + ", injvmFlag=" + + injvmFlag + '}'; } } diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterWrapper.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterWrapper.java index f76b8710c6..0513f35843 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterWrapper.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterWrapper.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.support.wrapper; import org.apache.dubbo.common.extension.Wrapper; @@ -36,8 +35,7 @@ public class ScopeClusterWrapper implements Cluster { @Override public Invoker join(Directory directory, boolean buildFilterChain) throws RpcException { - return new ScopeClusterInvoker<>(directory, - this.cluster.join(directory, buildFilterChain)); + return new ScopeClusterInvoker<>(directory, this.cluster.join(directory, buildFilterChain)); } public Cluster getCluster() { diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/ConfiguratorTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/ConfiguratorTest.java index bdf95198df..7227362ccd 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/ConfiguratorTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/ConfiguratorTest.java @@ -21,13 +21,13 @@ import org.apache.dubbo.rpc.cluster.configurator.absent.AbsentConfigurator; import org.apache.dubbo.rpc.cluster.configurator.override.OverrideConfigurator; import org.apache.dubbo.rpc.cluster.configurator.parser.ConfigParser; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.Collections; import java.util.List; import java.util.Optional; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + /** * {@link Configurator} */ @@ -39,16 +39,17 @@ class ConfiguratorTest { Optional> emptyOptional = Configurator.toConfigurators(Collections.emptyList()); Assertions.assertEquals(Optional.empty(), emptyOptional); - String configData = "[\"override://0.0.0.0/com.xx.Service?category=configurators&timeout=6666&disabled=true&dynamic=false&enabled=true&group=dubbo&priority=2&version=1.0\"" + - ", \"absent://0.0.0.0/com.xx.Service?category=configurators&timeout=6666&disabled=true&dynamic=false&enabled=true&group=dubbo&priority=1&version=1.0\" ]"; + String configData = + "[\"override://0.0.0.0/com.xx.Service?category=configurators&timeout=6666&disabled=true&dynamic=false&enabled=true&group=dubbo&priority=2&version=1.0\"" + + ", \"absent://0.0.0.0/com.xx.Service?category=configurators&timeout=6666&disabled=true&dynamic=false&enabled=true&group=dubbo&priority=1&version=1.0\" ]"; List urls = ConfigParser.parseConfigurators(configData); Optional> optionalList = Configurator.toConfigurators(urls); Assertions.assertTrue(optionalList.isPresent()); List configurators = optionalList.get(); Assertions.assertEquals(configurators.size(), 2); - // The hosts of AbsentConfigurator and OverrideConfigurator are equal, but the priority of OverrideConfigurator is higher + // The hosts of AbsentConfigurator and OverrideConfigurator are equal, but the priority of OverrideConfigurator + // is higher Assertions.assertTrue(configurators.get(0) instanceof AbsentConfigurator); Assertions.assertTrue(configurators.get(1) instanceof OverrideConfigurator); } - } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/RouterChainTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/RouterChainTest.java deleted file mode 100644 index 01911e6ce2..0000000000 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/RouterChainTest.java +++ /dev/null @@ -1,253 +0,0 @@ -///* -// * Licensed to the Apache Software Foundation (ASF) under one or more -// * contributor license agreements. See the NOTICE file distributed with -// * this work for additional information regarding copyright ownership. -// * The ASF licenses this file to You 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 org.apache.dubbo.rpc.cluster; -// -// -//import java.util.Arrays; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -//import java.util.concurrent.ConcurrentHashMap; -// -//import org.apache.dubbo.common.URL; -//import org.apache.dubbo.common.config.configcenter.ConfigChangeType; -//import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; -//import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; -//import org.apache.dubbo.common.url.component.ServiceConfigURL; -//import org.apache.dubbo.common.utils.CollectionUtils; -//import org.apache.dubbo.rpc.Invoker; -//import org.apache.dubbo.rpc.RpcContext; -//import org.apache.dubbo.rpc.RpcInvocation; -//import org.apache.dubbo.rpc.cluster.filter.DemoService; -//import org.apache.dubbo.rpc.cluster.router.RouterSnapshotSwitcher; -//import org.apache.dubbo.rpc.cluster.router.condition.config.AppStateRouter; -//import org.apache.dubbo.rpc.cluster.router.condition.config.ListenableStateRouter; -//import org.apache.dubbo.rpc.cluster.router.condition.config.ServiceStateRouter; -//import org.apache.dubbo.rpc.cluster.router.mesh.route.MeshAppRuleListener; -//import org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleManager; -//import org.apache.dubbo.rpc.cluster.router.state.BitList; -//import org.apache.dubbo.rpc.model.FrameworkModel; -//import org.junit.jupiter.api.Assertions; -//import org.junit.jupiter.api.Test; -//import org.mockito.Mockito; -// -//import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; -//import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY; -//import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.MESH_RULE_DATA_ID_SUFFIX; -//import static org.mockito.Mockito.when; -// -//class RouterChainTest { -// -// /** -// * verify the router and state router loaded by default -// */ -// @Test -// void testBuildRouterChain() { -// RouterChain routerChain = createRouterChanin(); -// Assertions.assertEquals(0, routerChain.getRouters().size()); -// Assertions.assertEquals(7, routerChain.getStateRouters().size()); -// } -// -// private RouterChain createRouterChanin() { -// Map parameters = new HashMap<>(); -// parameters.put(INTERFACE_KEY, DemoService.class.getName()); -// parameters.put("registry", "zookeeper"); -// URL url = new ServiceConfigURL("dubbo", -// "127.0.0.1", -// 20881, -// DemoService.class.getName(), -// parameters); -// -// RouterChain routerChain = RouterChain.buildChain(DemoService.class, url); -// return routerChain; -// } -// -// @Test -// void testRoute() { -// RouterChain routerChain = createRouterChanin(); -// -// // mockInvoker will be filtered out by MockInvokersSelector -// Invoker mockInvoker = createMockInvoker(); -// -// // invoker1 will be filtered out by MeshStateRouter -// Map map1 = new HashMap<>(); -// map1.put("env-sign", "yyyyyyy"); -// Invoker invoker1 = createNormalInvoker(map1); -// -// // invoker2 will be filtered out by TagStateRouter -// Map map2 = new HashMap<>(); -// map2.put("env-sign", "xxx"); -// map2.put("tag1", "hello"); -// Invoker invoker2 = createNormalInvoker(map2); -// -// // invoker3 will be filtered out by AppStateRouter -// Map map3 = new HashMap<>(); -// map3.put("env-sign", "xxx"); -// map3.put("tag1", "hello"); -// map3.put(TAG_KEY, "TAG_"); -// Invoker invoker3 = createNormalInvoker(map3); -// -// // invoker4 will be filtered out by ServiceStateRouter -// Map map4 = new HashMap<>(); -// map4.put("env-sign", "xxx"); -// map4.put("tag1", "hello"); -// map4.put(TAG_KEY, "TAG_"); -// map4.put("timeout", "5000"); -// Invoker invoker4 = createNormalInvoker(map4); -// -// // invoker5 is the only one returned at the end that is not filtered out -// Map map5 = new HashMap<>(); -// map5.put("env-sign", "xxx"); -// map5.put("tag1", "hello"); -// map5.put(TAG_KEY, "TAG_"); -// map5.put("timeout", "5000"); -// map5.put("serialization", "hessian2"); -// Invoker invoker5 = createNormalInvoker(map5); -// -// BitList> invokers = new BitList<>(Arrays.asList(mockInvoker, invoker1, invoker2, invoker3, invoker4, invoker5)); -// routerChain.setInvokers(invokers, () -> {}); -// -// // mesh rule for MeshStateRouter -// MeshRuleManager meshRuleManager = mockInvoker.getUrl().getOrDefaultModuleModel().getBeanFactory().getBean(MeshRuleManager.class); -// ConcurrentHashMap appRuleListeners = meshRuleManager.getAppRuleListeners(); -// MeshAppRuleListener meshAppRuleListener = appRuleListeners.get(invoker1.getUrl().getRemoteApplication()); -// ConfigChangedEvent configChangedEvent = new ConfigChangedEvent("demo-route" + MESH_RULE_DATA_ID_SUFFIX, DynamicConfiguration.DEFAULT_GROUP, -// MESH_RULE1 + "---\n" + MESH_RULE2, ConfigChangeType.ADDED); -// meshAppRuleListener.process(configChangedEvent); -// -// -// // condition rule for AppStateRouter&ServiceStateRouter -// ListenableStateRouter serviceRouter = routerChain.getStateRouters().stream().filter(s -> s instanceof ServiceStateRouter).map(s -> (ListenableStateRouter) s).findAny().orElse(null); -// ConfigChangedEvent serviceConditionEvent = new ConfigChangedEvent(DynamicConfiguration.getRuleKey(mockInvoker.getUrl()) + ".condition-router", DynamicConfiguration.DEFAULT_GROUP, -// SERVICE_CONDITION_RULE, ConfigChangeType.ADDED); -// serviceRouter.process(serviceConditionEvent); -// -// ListenableStateRouter appRouter = routerChain.getStateRouters().stream().filter(s -> s instanceof AppStateRouter).map(s -> (ListenableStateRouter) s).findAny().orElse(null); -// ConfigChangedEvent appConditionEvent = new ConfigChangedEvent("app.condition-router", DynamicConfiguration.DEFAULT_GROUP, -// APP_CONDITION_RULE, ConfigChangeType.ADDED); -// appRouter.process(appConditionEvent); -// -// // prepare consumerUrl and RpcInvocation -// URL consumerUrl = URL.valueOf("consumer://localhost/DemoInterface?remote.application=app1"); -// RpcInvocation rpcInvocation = new RpcInvocation(); -// rpcInvocation.setServiceName("DemoService"); -// rpcInvocation.setObjectAttachment("trafficLabel", "xxx"); -// rpcInvocation.setObjectAttachment(TAG_KEY, "TAG_"); -// -// RpcContext.getServiceContext().setNeedPrintRouterSnapshot(true); -// RouterSnapshotSwitcher routerSnapshotSwitcher = FrameworkModel.defaultModel().getBeanFactory().getBean(RouterSnapshotSwitcher.class); -// routerSnapshotSwitcher.addEnabledService("org.apache.dubbo.demo.DemoService"); -// // route -// List> result = routerChain.getSingleChain(consumerUrl, invokers, rpcInvocation) -// .route(consumerUrl, invokers, rpcInvocation); -// Assertions.assertEquals(result.size(), 1); -// Assertions.assertTrue(result.contains(invoker5)); -// -// String snapshotLog = -// "[ Parent (Input: 6) (Current Node Output: 6) (Chain Node Output: 1) ] Input: localhost:9103,localhost:9103,localhost:9103,localhost:9103,localhost:9103 -> Chain Node Output: localhost:9103...\n" + -// " [ MockInvokersSelector (Input: 6) (Current Node Output: 5) (Chain Node Output: 1) Router message: invocation.need.mock not set. Return normal Invokers. ] Current Node Output: localhost:9103,localhost:9103,localhost:9103,localhost:9103,localhost:9103\n" + -// " [ StandardMeshRuleRouter (Input: 5) (Current Node Output: 4) (Chain Node Output: 1) Router message: Match App: app Subset: isolation ] Current Node Output: localhost:9103,localhost:9103,localhost:9103,localhost:9103\n" + -// " [ TagStateRouter (Input: 4) (Current Node Output: 3) (Chain Node Output: 1) Router message: Disable Tag Router. Reason: tagRouterRule is invalid or disabled ] Current Node Output: localhost:9103,localhost:9103,localhost:9103\n" + -// " [ ServiceStateRouter (Input: 3) (Current Node Output: 3) (Chain Node Output: 1) Router message: null ] Current Node Output: localhost:9103,localhost:9103,localhost:9103\n" + -// " [ ConditionStateRouter (Input: 3) (Current Node Output: 2) (Chain Node Output: 2) Router message: Match return. ] Current Node Output: localhost:9103,localhost:9103\n" + -// " [ ProviderAppStateRouter (Input: 2) (Current Node Output: 2) (Chain Node Output: 1) Router message: Directly return. Reason: Invokers from previous router is empty or conditionRouters is empty. ] Current Node Output: localhost:9103,localhost:9103\n" + -// " [ AppStateRouter (Input: 2) (Current Node Output: 2) (Chain Node Output: 1) Router message: null ] Current Node Output: localhost:9103,localhost:9103\n" + -// " [ ConditionStateRouter (Input: 2) (Current Node Output: 1) (Chain Node Output: 1) Router message: Match return. ] Current Node Output: localhost:9103\n" + -// " [ AppScriptStateRouter (Input: 1) (Current Node Output: 1) (Chain Node Output: 1) Router message: Directly return from script router. Reason: Invokers from previous router is empty or script is not enabled. Script rule is: null ] Current Node Output: localhost:9103"; -// String[] snapshot = routerSnapshotSwitcher.cloneSnapshot(); -// Assertions.assertTrue(snapshot[0].contains(snapshotLog)); -// -// RpcContext.getServiceContext().setNeedPrintRouterSnapshot(false); -// result = routerChain.getSingleChain(consumerUrl, invokers, rpcInvocation) -// .route(consumerUrl, invokers, rpcInvocation); -// Assertions.assertEquals(result.size(), 1); -// Assertions.assertTrue(result.contains(invoker5)); -// -// routerChain.destroy(); -// Assertions.assertEquals(routerChain.getRouters().size(), 0); -// Assertions.assertEquals(routerChain.getStateRouters().size(), 0); -// -// } -// -// private Invoker createMockInvoker() { -// URL url = URL.valueOf("mock://localhost:9103/DemoInterface?remote.application=app"); -// Invoker invoker = Mockito.mock(Invoker.class); -// when(invoker.getUrl()).thenReturn(url); -// return invoker; -// } -// -// private Invoker createNormalInvoker(Map parameters) { -// URL url = URL.valueOf("dubbo://localhost:9103/DemoInterface?remote.application=app"); -// if (CollectionUtils.isNotEmptyMap(parameters)) { -// url = url.addParameters(parameters); -// } -// Invoker invoker = Mockito.mock(Invoker.class); -// when(invoker.getUrl()).thenReturn(url); -// return invoker; -// } -// -// -// private final static String MESH_RULE1 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + -// "kind: DestinationRule\n" + -// "metadata: { name: demo-route }\n" + -// "spec:\n" + -// " host: demo\n" + -// " subsets:\n" + -// " - labels: { env-sign: xxx, tag1: hello }\n" + -// " name: isolation\n" + -// " - labels: { env-sign: yyy }\n" + -// " name: testing-trunk\n" + -// " - labels: { env-sign: zzz }\n" + -// " name: testing\n" + -// " trafficPolicy:\n" + -// " loadBalancer: { simple: ROUND_ROBIN }\n" + -// "\n"; -// -// private final static String MESH_RULE2 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + -// "kind: VirtualService\n" + -// "metadata: { name: demo-route }\n" + -// "spec:\n" + -// " dubbo:\n" + -// " - routedetail:\n" + -// " - match:\n" + -// " - attachments: \n" + -// " dubboContext: {trafficLabel: {regex: xxx}}\n" + -// " name: xxx-project\n" + -// " route:\n" + -// " - destination: {host: demo, subset: isolation}\n" + -// " services:\n" + -// " - {regex: DemoService}\n" + -// " hosts: [demo]\n"; -// -// private static final String APP_CONDITION_RULE = "scope: application\n" + -// "force: true\n" + -// "runtime: false\n" + -// "enabled: true\n" + -// "priority: 1\n" + -// "key: demo-consumer\n" + -// "conditions:\n" + -// "- => serialization=hessian2"; -// -// private static final String SERVICE_CONDITION_RULE = "scope: service\n" + -// "force: true\n" + -// "runtime: false\n" + -// "enabled: true\n" + -// "priority: 1\n" + -// "key: org.apache.dubbo.demo.DemoService\n" + -// "conditions:\n" + -// "- => timeout=5000"; -//} diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/StickyTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/StickyTest.java index d19cf3f720..e728d4b0be 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/StickyTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/StickyTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster; - import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invocation; @@ -26,13 +25,13 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker; +import java.util.ArrayList; +import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.ArrayList; -import java.util.List; - import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_STICKY_KEY; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -42,17 +41,14 @@ class StickyTest { private List> invokers = new ArrayList>(); - private Invoker invoker1 = mock(Invoker.class); - private Invoker invoker2 = mock(Invoker.class); + private Invoker invoker2 = mock(Invoker.class); private RpcInvocation invocation; private Directory dic; private Result result = new AppResponse(); private StickyClusterInvoker clusterinvoker = null; - private URL url = URL.valueOf("test://test:11/test?" - + "&loadbalance=roundrobin" - + "&" + CLUSTER_STICKY_KEY + "=true" - ); + private URL url = + URL.valueOf("test://test:11/test?" + "&loadbalance=roundrobin" + "&" + CLUSTER_STICKY_KEY + "=true"); private int runs = 1; @BeforeEach @@ -70,7 +66,6 @@ class StickyTest { invokers.add(invoker2); clusterinvoker = new StickyClusterInvoker(dic); - } @Test @@ -101,7 +96,7 @@ class StickyTest { @Test void testMethodsSticky() { - for (int i = 0; i < 100; i++) {//Two different methods should always use the same invoker every time. + for (int i = 0; i < 100; i++) { // Two different methods should always use the same invoker every time. int count1 = testSticky("method1", true); int count2 = testSticky("method2", true); Assertions.assertEquals(count1, count2); @@ -137,7 +132,6 @@ class StickyTest { return count; } - static class StickyClusterInvoker extends AbstractClusterInvoker { private Invoker selectedInvoker; @@ -150,8 +144,8 @@ class StickyTest { } @Override - protected Result doInvoke(Invocation invocation, List> invokers, - LoadBalance loadbalance) throws RpcException { + protected Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) + throws RpcException { Invoker invoker = select(loadbalance, invocation, invokers, null); selectedInvoker = invoker; return null; diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/absent/AbsentConfiguratorTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/absent/AbsentConfiguratorTest.java index ec862a9358..869c97e4d4 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/absent/AbsentConfiguratorTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/absent/AbsentConfiguratorTest.java @@ -20,21 +20,21 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.cluster.configurator.consts.UrlConstant; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + /** * OverrideConfiguratorTest */ class AbsentConfiguratorTest { - @Test void testOverrideApplication() { - AbsentConfigurator configurator = new AbsentConfigurator(URL.valueOf("override://foo@0.0.0.0/com.foo.BarService?timeout=200")); + AbsentConfigurator configurator = + new AbsentConfigurator(URL.valueOf("override://foo@0.0.0.0/com.foo.BarService?timeout=200")); URL url = configurator.configure(URL.valueOf(UrlConstant.URL_CONSUMER)); Assertions.assertEquals("200", url.getParameter("timeout")); @@ -51,7 +51,8 @@ class AbsentConfiguratorTest { @Test void testOverrideHost() { - AbsentConfigurator configurator = new AbsentConfigurator(URL.valueOf("override://" + NetUtils.getLocalHost() + "/com.foo.BarService?timeout=200")); + AbsentConfigurator configurator = new AbsentConfigurator( + URL.valueOf("override://" + NetUtils.getLocalHost() + "/com.foo.BarService?timeout=200")); URL url = configurator.configure(URL.valueOf(UrlConstant.URL_CONSUMER)); Assertions.assertEquals("200", url.getParameter("timeout")); @@ -72,7 +73,8 @@ class AbsentConfiguratorTest { @Test void testAbsentForVersion27() { { - String consumerUrlV27 = "dubbo://172.24.160.179/com.foo.BarService?application=foo&side=consumer&timeout=100"; + String consumerUrlV27 = + "dubbo://172.24.160.179/com.foo.BarService?application=foo&side=consumer&timeout=100"; URL consumerConfiguratorUrl = URL.valueOf("absent://0.0.0.0/com.foo.BarService"); Map params = new HashMap<>(); @@ -95,7 +97,8 @@ class AbsentConfiguratorTest { } { - String providerUrlV27 = "dubbo://172.24.160.179:21880/com.foo.BarService?application=foo&side=provider&weight=100"; + String providerUrlV27 = + "dubbo://172.24.160.179:21880/com.foo.BarService?application=foo&side=provider&weight=100"; URL providerConfiguratorUrl = URL.valueOf("absent://172.24.160.179:21880/com.foo.BarService"); Map params = new HashMap<>(); @@ -108,7 +111,8 @@ class AbsentConfiguratorTest { // Meet the configured conditions: // same side // same port - // The host of configuratorUrl is 0.0.0.0 or the host of providerConfiguratorUrl is the same as consumerUrlV27 + // The host of configuratorUrl is 0.0.0.0 or the host of providerConfiguratorUrl is the same as + // consumerUrlV27 // same appName AbsentConfigurator configurator = new AbsentConfigurator(providerConfiguratorUrl); URL url = configurator.configure(URL.valueOf(providerUrlV27)); @@ -116,5 +120,4 @@ class AbsentConfiguratorTest { Assertions.assertEquals("100", url.getParameter("weight")); } } - } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/consts/UrlConstant.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/consts/UrlConstant.java index 193f7ac364..0893b618be 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/consts/UrlConstant.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/consts/UrlConstant.java @@ -20,12 +20,17 @@ package org.apache.dubbo.rpc.cluster.configurator.consts; * test case url constant */ public class UrlConstant { - public static final String URL_CONSUMER = "dubbo://10.20.153.10:20880/com.foo.BarService?application=foo&side=consumer"; - public static final String URL_ONE = "dubbo://10.20.153.10:20880/com.foo.BarService?application=foo&timeout=1000&side=consumer"; - public static final String APPLICATION_BAR_SIDE_CONSUMER_11 = "dubbo://10.20.153.11:20880/com.foo.BarService?application=bar&side=consumer"; - public static final String TIMEOUT_1000_SIDE_CONSUMER_11 = "dubbo://10.20.153.11:20880/com.foo.BarService?application=bar&timeout=1000&side=consumer"; + public static final String URL_CONSUMER = + "dubbo://10.20.153.10:20880/com.foo.BarService?application=foo&side=consumer"; + public static final String URL_ONE = + "dubbo://10.20.153.10:20880/com.foo.BarService?application=foo&timeout=1000&side=consumer"; + public static final String APPLICATION_BAR_SIDE_CONSUMER_11 = + "dubbo://10.20.153.11:20880/com.foo.BarService?application=bar&side=consumer"; + public static final String TIMEOUT_1000_SIDE_CONSUMER_11 = + "dubbo://10.20.153.11:20880/com.foo.BarService?application=bar&timeout=1000&side=consumer"; public static final String SERVICE_TIMEOUT_200 = "override://10.20.153.10/com.foo.BarService?timeout=200"; - public static final String APPLICATION_BAR_SIDE_CONSUMER_10 = "dubbo://10.20.153.10:20880/com.foo.BarService?application=bar&side=consumer"; - public static final String TIMEOUT_1000_SIDE_CONSUMER_10 = "dubbo://10.20.153.10:20880/com.foo.BarService?application=bar&timeout=1000&side=consumer"; - + public static final String APPLICATION_BAR_SIDE_CONSUMER_10 = + "dubbo://10.20.153.10:20880/com.foo.BarService?application=bar&side=consumer"; + public static final String TIMEOUT_1000_SIDE_CONSUMER_10 = + "dubbo://10.20.153.10:20880/com.foo.BarService?application=bar&timeout=1000&side=consumer"; } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/override/OverrideConfiguratorTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/override/OverrideConfiguratorTest.java index ea139d0e04..f85155852d 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/override/OverrideConfiguratorTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/override/OverrideConfiguratorTest.java @@ -24,13 +24,13 @@ import org.apache.dubbo.rpc.cluster.configurator.parser.model.ConditionMatch; import org.apache.dubbo.rpc.cluster.configurator.parser.model.ParamMatch; import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.StringMatch; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.Arrays; import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.rpc.cluster.configurator.parser.model.ConfiguratorConfig.MATCH_CONDITION; /** @@ -40,7 +40,8 @@ class OverrideConfiguratorTest { @Test void testOverride_Application() { - OverrideConfigurator configurator = new OverrideConfigurator(URL.valueOf("override://foo@0.0.0.0/com.foo.BarService?timeout=200")); + OverrideConfigurator configurator = + new OverrideConfigurator(URL.valueOf("override://foo@0.0.0.0/com.foo.BarService?timeout=200")); URL url = configurator.configure(URL.valueOf(UrlConstant.URL_CONSUMER)); Assertions.assertEquals("200", url.getParameter("timeout")); @@ -57,7 +58,8 @@ class OverrideConfiguratorTest { @Test void testOverride_Host() { - OverrideConfigurator configurator = new OverrideConfigurator(URL.valueOf("override://" + NetUtils.getLocalHost() + "/com.foo.BarService?timeout=200")); + OverrideConfigurator configurator = new OverrideConfigurator( + URL.valueOf("override://" + NetUtils.getLocalHost() + "/com.foo.BarService?timeout=200")); URL url = configurator.configure(URL.valueOf(UrlConstant.URL_CONSUMER)); Assertions.assertEquals("200", url.getParameter("timeout")); @@ -65,7 +67,8 @@ class OverrideConfiguratorTest { url = configurator.configure(URL.valueOf(UrlConstant.URL_ONE)); Assertions.assertEquals("200", url.getParameter("timeout")); - AbsentConfigurator configurator1 = new AbsentConfigurator(URL.valueOf("override://10.20.153.10/com.foo.BarService?timeout=200")); + AbsentConfigurator configurator1 = + new AbsentConfigurator(URL.valueOf("override://10.20.153.10/com.foo.BarService?timeout=200")); url = configurator1.configure(URL.valueOf(UrlConstant.APPLICATION_BAR_SIDE_CONSUMER_10)); Assertions.assertNull(url.getParameter("timeout")); @@ -78,7 +81,8 @@ class OverrideConfiguratorTest { @Test void testOverrideForVersion27() { { - String consumerUrlV27 = "dubbo://172.24.160.179/com.foo.BarService?application=foo&side=consumer&timeout=100"; + String consumerUrlV27 = + "dubbo://172.24.160.179/com.foo.BarService?application=foo&side=consumer&timeout=100"; URL consumerConfiguratorUrl = URL.valueOf("override://0.0.0.0/com.foo.BarService"); Map params = new HashMap<>(); @@ -100,7 +104,8 @@ class OverrideConfiguratorTest { } { - String providerUrlV27 = "dubbo://172.24.160.179:21880/com.foo.BarService?application=foo&side=provider&weight=100"; + String providerUrlV27 = + "dubbo://172.24.160.179:21880/com.foo.BarService?application=foo&side=provider&weight=100"; URL providerConfiguratorUrl = URL.valueOf("override://172.24.160.179:21880/com.foo.BarService"); Map params = new HashMap<>(); @@ -112,13 +117,13 @@ class OverrideConfiguratorTest { // Meet the configured conditions: // same side // same port - // The host of configuratorUrl is 0.0.0.0 or the host of providerConfiguratorUrl is the same as consumerUrlV27 + // The host of configuratorUrl is 0.0.0.0 or the host of providerConfiguratorUrl is the same as + // consumerUrlV27 // same appName OverrideConfigurator configurator = new OverrideConfigurator(providerConfiguratorUrl); URL url = configurator.configure(URL.valueOf(providerUrlV27)); Assertions.assertEquals(url.getParameter("weight"), "200"); } - } // Test the version after 2.7 @@ -126,7 +131,8 @@ class OverrideConfiguratorTest { void testOverrideForVersion3() { // match { - String consumerUrlV3 = "dubbo://172.24.160.179/com.foo.BarService?match_key=value&application=foo&side=consumer&timeout=100"; + String consumerUrlV3 = + "dubbo://172.24.160.179/com.foo.BarService?match_key=value&application=foo&side=consumer&timeout=100"; URL consumerConfiguratorUrl = URL.valueOf("override://0.0.0.0/com.foo.BarService"); Map params = new HashMap<>(); @@ -160,7 +166,8 @@ class OverrideConfiguratorTest { // mismatch { - String consumerUrlV3 = "dubbo://172.24.160.179/com.foo.BarService?match_key=value&application=foo&side=consumer&timeout=100"; + String consumerUrlV3 = + "dubbo://172.24.160.179/com.foo.BarService?match_key=value&application=foo&side=consumer&timeout=100"; URL consumerConfiguratorUrl = URL.valueOf("override://0.0.0.0/com.foo.BarService"); Map params = new HashMap<>(); @@ -192,5 +199,4 @@ class OverrideConfiguratorTest { Assertions.assertEquals("100", url.getParameter("timeout")); } } - } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.java index f5596d56b4..f68a68efe1 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.java @@ -20,17 +20,17 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.cluster.configurator.parser.model.ConditionMatch; import org.apache.dubbo.rpc.cluster.configurator.parser.model.ConfiguratorConfig; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.Map; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.SafeConstructor; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; -import java.util.Map; - import static org.apache.dubbo.common.constants.CommonConstants.LOADBALANCE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.rpc.cluster.Constants.OVERRIDE_PROVIDERS_KEY; @@ -121,7 +121,6 @@ class ConfigParserTest { } } - @Test void parseConfiguratorsAppAnyServicesTest() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream("/AppAnyServices.yml")) { @@ -182,9 +181,11 @@ class ConfigParserTest { URL matchURL1 = URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value1"); URL matchURL2 = URL.valueOf("dubbo://10.0.0.1:20880/DemoService2?match_key1=value1"); - URL notMatchURL1 = URL.valueOf("dubbo://10.0.0.2:20880/DemoService?match_key1=value1");// address not match - URL notMatchURL2 = URL.valueOf("dubbo://10.0.0.1:20880/DemoServiceNotMatch?match_key1=value1");// service not match - URL notMatchURL3 = URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value_not_match");// key not match + URL notMatchURL1 = URL.valueOf("dubbo://10.0.0.2:20880/DemoService?match_key1=value1"); // address not match + URL notMatchURL2 = + URL.valueOf("dubbo://10.0.0.1:20880/DemoServiceNotMatch?match_key1=value1"); // service not match + URL notMatchURL3 = + URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value_not_match"); // key not match ConditionMatch matcher = (ConditionMatch) url.getAttribute(MATCH_CONDITION); Assertions.assertTrue(matcher.isMatch(matchURL1.getAddress(), matchURL1)); @@ -208,7 +209,8 @@ class ConfigParserTest { Assertions.assertEquals("demo-provider", url.getApplication()); URL matchURL = URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value1"); - URL notMatchURL = URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value_not_match");// key not match + URL notMatchURL = + URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value_not_match"); // key not match ConditionMatch matcher = (ConditionMatch) url.getAttribute(MATCH_CONDITION); Assertions.assertTrue(matcher.isMatch(matchURL.getAddress(), matchURL)); @@ -229,7 +231,8 @@ class ConfigParserTest { Assertions.assertEquals("demo-provider", url.getApplication()); URL matchURL = URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value1"); - URL notMatchURL = URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value_not_match");// key not match + URL notMatchURL = + URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value_not_match"); // key not match ConditionMatch matcher = (ConditionMatch) url.getAttribute(MATCH_CONDITION); Assertions.assertTrue(matcher.isMatch(matchURL.getAddress(), matchURL)); @@ -240,7 +243,8 @@ class ConfigParserTest { @Test void parseURLJsonArrayCompatible() { - String configData = "[\"override://0.0.0.0/com.xx.Service?category=configurators&timeout=6666&disabled=true&dynamic=false&enabled=true&group=dubbo&priority=1&version=1.0\" ]"; + String configData = + "[\"override://0.0.0.0/com.xx.Service?category=configurators&timeout=6666&disabled=true&dynamic=false&enabled=true&group=dubbo&priority=1&version=1.0\" ]"; List urls = ConfigParser.parseConfigurators(configData); @@ -252,5 +256,4 @@ class ConfigParserTest { Assertions.assertEquals("com.xx.Service", url.getServiceInterface()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); } - } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DefaultFilterChainBuilderTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DefaultFilterChainBuilderTest.java index 3a173c2ceb..3acd371699 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DefaultFilterChainBuilderTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DefaultFilterChainBuilderTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.filter; - import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -38,30 +37,34 @@ class DefaultFilterChainBuilderTest { DefaultFilterChainBuilder defaultFilterChainBuilder = new DefaultFilterChainBuilder(); // verify that no filter is built by default - URL urlWithoutFilter = URL.valueOf("injvm://127.0.0.1/DemoService") - .addParameter(INTERFACE_KEY, DemoService.class.getName()); + URL urlWithoutFilter = + URL.valueOf("injvm://127.0.0.1/DemoService").addParameter(INTERFACE_KEY, DemoService.class.getName()); urlWithoutFilter = urlWithoutFilter.setScopeModel(ApplicationModel.defaultModel()); - AbstractInvoker invokerWithoutFilter = new AbstractInvoker(DemoService.class, urlWithoutFilter) { - @Override - protected Result doInvoke(Invocation invocation) { - return null; - } - }; + AbstractInvoker invokerWithoutFilter = + new AbstractInvoker(DemoService.class, urlWithoutFilter) { + @Override + protected Result doInvoke(Invocation invocation) { + return null; + } + }; - Invoker invokerAfterBuild = defaultFilterChainBuilder.buildInvokerChain(invokerWithoutFilter, REFERENCE_FILTER_KEY, CONSUMER); + Invoker invokerAfterBuild = + defaultFilterChainBuilder.buildInvokerChain(invokerWithoutFilter, REFERENCE_FILTER_KEY, CONSUMER); // verify that if LogFilter is configured, LogFilter should exist in the filter chain URL urlWithFilter = URL.valueOf("injvm://127.0.0.1/DemoService") - .addParameter(INTERFACE_KEY, DemoService.class.getName()) - .addParameter(REFERENCE_FILTER_KEY, "log"); + .addParameter(INTERFACE_KEY, DemoService.class.getName()) + .addParameter(REFERENCE_FILTER_KEY, "log"); urlWithFilter = urlWithFilter.setScopeModel(ApplicationModel.defaultModel()); - AbstractInvoker invokerWithFilter = new AbstractInvoker(DemoService.class, urlWithFilter) { - @Override - protected Result doInvoke(Invocation invocation) { - return null; - } - }; - invokerAfterBuild = defaultFilterChainBuilder.buildInvokerChain(invokerWithFilter, REFERENCE_FILTER_KEY, CONSUMER); + AbstractInvoker invokerWithFilter = + new AbstractInvoker(DemoService.class, urlWithFilter) { + @Override + protected Result doInvoke(Invocation invocation) { + return null; + } + }; + invokerAfterBuild = + defaultFilterChainBuilder.buildInvokerChain(invokerWithFilter, REFERENCE_FILTER_KEY, CONSUMER); Assertions.assertTrue(invokerAfterBuild instanceof FilterChainBuilder.CallbackRegistrationInvoker); } @@ -71,31 +74,34 @@ class DefaultFilterChainBuilderTest { // verify that no filter is built by default URL urlWithoutFilter = URL.valueOf("dubbo://127.0.0.1:20880/DemoService") - .addParameter(INTERFACE_KEY, DemoService.class.getName()); + .addParameter(INTERFACE_KEY, DemoService.class.getName()); urlWithoutFilter = urlWithoutFilter.setScopeModel(ApplicationModel.defaultModel()); - AbstractInvoker invokerWithoutFilter = new AbstractInvoker(DemoService.class, urlWithoutFilter) { - @Override - protected Result doInvoke(Invocation invocation) { - return null; - } - }; + AbstractInvoker invokerWithoutFilter = + new AbstractInvoker(DemoService.class, urlWithoutFilter) { + @Override + protected Result doInvoke(Invocation invocation) { + return null; + } + }; - Invoker invokerAfterBuild = defaultFilterChainBuilder.buildInvokerChain(invokerWithoutFilter, REFERENCE_FILTER_KEY, CONSUMER); -// Assertions.assertTrue(invokerAfterBuild instanceof AbstractInvoker); + Invoker invokerAfterBuild = + defaultFilterChainBuilder.buildInvokerChain(invokerWithoutFilter, REFERENCE_FILTER_KEY, CONSUMER); + // Assertions.assertTrue(invokerAfterBuild instanceof AbstractInvoker); // verify that if LogFilter is configured, LogFilter should exist in the filter chain URL urlWithFilter = URL.valueOf("dubbo://127.0.0.1:20880/DemoService") - .addParameter(INTERFACE_KEY, DemoService.class.getName()) - .addParameter(REFERENCE_FILTER_KEY, "log"); + .addParameter(INTERFACE_KEY, DemoService.class.getName()) + .addParameter(REFERENCE_FILTER_KEY, "log"); urlWithFilter = urlWithFilter.setScopeModel(ApplicationModel.defaultModel()); - AbstractInvoker invokerWithFilter = new AbstractInvoker(DemoService.class, urlWithFilter) { - @Override - protected Result doInvoke(Invocation invocation) { - return null; - } - }; - invokerAfterBuild = defaultFilterChainBuilder.buildInvokerChain(invokerWithFilter, REFERENCE_FILTER_KEY, CONSUMER); + AbstractInvoker invokerWithFilter = + new AbstractInvoker(DemoService.class, urlWithFilter) { + @Override + protected Result doInvoke(Invocation invocation) { + return null; + } + }; + invokerAfterBuild = + defaultFilterChainBuilder.buildInvokerChain(invokerWithFilter, REFERENCE_FILTER_KEY, CONSUMER); Assertions.assertTrue(invokerAfterBuild instanceof FilterChainBuilder.CallbackRegistrationInvoker); - } } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoService.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoService.java index 6c8f7fff83..3501992d6b 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoService.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoService.java @@ -19,7 +19,6 @@ package org.apache.dubbo.rpc.cluster.filter; /** * TestService */ - public interface DemoService { String sayHello(String name); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceImpl.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceImpl.java index 58f176aab8..8ad99c2476 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceImpl.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceImpl.java @@ -16,8 +16,7 @@ */ package org.apache.dubbo.rpc.cluster.filter; - -class DemoServiceImpl implements DemoService{ +class DemoServiceImpl implements DemoService { @Override public String sayHello(String name) { diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceLocal.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceLocal.java index f7650da9c4..7d8b14a85c 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceLocal.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceLocal.java @@ -19,11 +19,9 @@ package org.apache.dubbo.rpc.cluster.filter; /** * TestService */ - class DemoServiceLocal implements DemoService { - public DemoServiceLocal(DemoService demoService) { - } + public DemoServiceLocal(DemoService demoService) {} public String sayHello(String name) { return name; @@ -33,11 +31,7 @@ class DemoServiceLocal implements DemoService { return a + b; } - public void ondisconnect() { + public void ondisconnect() {} - } - - public void onconnect() { - - } + public void onconnect() {} } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceStub.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceStub.java index d230eaf5b8..206818a14d 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceStub.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/DemoServiceStub.java @@ -19,11 +19,9 @@ package org.apache.dubbo.rpc.cluster.filter; /** * TestService */ - class DemoServiceStub implements DemoService { - public DemoServiceStub(DemoService demoService) { - } + public DemoServiceStub(DemoService demoService) {} public String sayHello(String name) { return name; diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/LogFilter.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/LogFilter.java index 0007d65ad3..dc2b8725fc 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/LogFilter.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/filter/LogFilter.java @@ -25,7 +25,6 @@ import org.apache.dubbo.rpc.RpcException; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; - @Activate(group = CONSUMER, value = "log") public class LogFilter implements Filter, Filter.Listener { @@ -35,12 +34,8 @@ public class LogFilter implements Filter, Filter.Listener { } @Override - public void onResponse(Result appResponse, Invoker invoker, Invocation invocation) { - - } + public void onResponse(Result appResponse, Invoker invoker, Invocation invocation) {} @Override - public void onError(Throwable t, Invoker invoker, Invocation invocation) { - - } + public void onError(Throwable t, Invoker invoker, Invocation invocation) {} } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/AbstractLoadBalanceTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/AbstractLoadBalanceTest.java index d5419a0a95..f261381899 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/AbstractLoadBalanceTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/AbstractLoadBalanceTest.java @@ -23,13 +23,13 @@ import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.ClusterInvoker; +import java.util.HashMap; +import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.HashMap; -import java.util.List; - import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; import static org.apache.dubbo.rpc.cluster.Constants.WEIGHT_KEY; import static org.mockito.BDDMockito.given; @@ -71,10 +71,12 @@ class AbstractLoadBalanceTest { URL url1 = new ServiceConfigURL("", "", 0, "DemoService", new HashMap<>()); given(invoker1.getUrl()).willReturn(url1); - ClusterInvoker invoker2 = mock(ClusterInvoker.class, Mockito.withSettings().stubOnly()); + ClusterInvoker invoker2 = + mock(ClusterInvoker.class, Mockito.withSettings().stubOnly()); URL url2 = new ServiceConfigURL("", "", 0, "org.apache.dubbo.registry.RegistryService", new HashMap<>()); url2 = url2.addParameter(WEIGHT_KEY, 20); - URL registryUrl2 = new ServiceConfigURL("", "", 0, "org.apache.dubbo.registry.RegistryService", new HashMap<>()); + URL registryUrl2 = + new ServiceConfigURL("", "", 0, "org.apache.dubbo.registry.RegistryService", new HashMap<>()); registryUrl2 = registryUrl2.addParameter(WEIGHT_KEY, 30); given(invoker2.getUrl()).willReturn(url2); given(invoker2.getRegistryUrl()).willReturn(registryUrl2); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalanceTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalanceTest.java index 4e4b1e7b63..64641a5798 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalanceTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalanceTest.java @@ -16,16 +16,17 @@ */ package org.apache.dubbo.rpc.cluster.loadbalance; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicLong; - import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.cluster.LoadBalance; import org.apache.dubbo.rpc.cluster.RouterChain; import org.apache.dubbo.rpc.cluster.router.state.BitList; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -41,21 +42,20 @@ class ConsistentHashLoadBalanceTest extends LoadBalanceBaseTest { Invoker genericHitted = findHitted(genericInvokeCounter); Invoker hitted = findHitted(invokeCounter); - Assertions.assertEquals(hitted, - genericHitted, "hitted should equals to genericHitted"); + Assertions.assertEquals(hitted, genericHitted, "hitted should equals to genericHitted"); } - private Invoker findHitted(Map invokerCounter) { + private Invoker findHitted(Map invokerCounter) { Invoker invoker = null; - for (Map.Entry entry : invokerCounter.entrySet()) { + for (Map.Entry entry : invokerCounter.entrySet()) { if (entry.getValue().longValue() > 0) { invoker = entry.getKey(); break; } } - Assertions.assertNotNull(invoker,"invoker should be found"); + Assertions.assertNotNull(invoker, "invoker should be found"); return null; } @@ -76,11 +76,13 @@ class ConsistentHashLoadBalanceTest extends LoadBalanceBaseTest { } } - Assertions.assertEquals(counter.size() - 1, - unHitedInvokerCount, "the number of unHitedInvoker should be counter.size() - 1"); + Assertions.assertEquals( + counter.size() - 1, unHitedInvokerCount, "the number of unHitedInvoker should be counter.size() - 1"); Assertions.assertEquals(1, hitedInvokers.size(), "the number of hitedInvoker should be 1"); - Assertions.assertEquals(runs, - hitedInvokers.values().iterator().next().intValue(), "the number of hited count should be the number of runs"); + Assertions.assertEquals( + runs, + hitedInvokers.values().iterator().next().intValue(), + "the number of hited count should be the number of runs"); } // https://github.com/apache/dubbo/issues/5429 @@ -93,8 +95,9 @@ class ConsistentHashLoadBalanceTest extends LoadBalanceBaseTest { for (int i = 0; i < 100; i++) { routerChain.setInvokers(new BitList<>(invokers), () -> {}); - List> routeInvokers = routerChain.getSingleChain(url, new BitList<>(invokers), invocation) - .route(url, new BitList<>(invokers), invocation); + List> routeInvokers = routerChain + .getSingleChain(url, new BitList<>(invokers), invocation) + .route(url, new BitList<>(invokers), invocation); Invoker finalInvoker = lb.select(routeInvokers, url, invocation); Assertions.assertEquals(result, finalInvoker); } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LeastActiveBalanceTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LeastActiveBalanceTest.java index 64ee44b863..4326ef079b 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LeastActiveBalanceTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LeastActiveBalanceTest.java @@ -18,13 +18,13 @@ package org.apache.dubbo.rpc.cluster.loadbalance; import org.apache.dubbo.rpc.Invoker; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import java.util.Map; -import java.util.concurrent.atomic.AtomicLong; - class LeastActiveBalanceTest extends LoadBalanceBaseTest { @Disabled @Test @@ -35,7 +35,8 @@ class LeastActiveBalanceTest extends LoadBalanceBaseTest { Long count = entry.getValue().get(); // System.out.println(count); Assertions.assertTrue( - Math.abs(count - runs / (0f + invokers.size())) < runs / (0f + invokers.size()), "abs diff should < avg"); + Math.abs(count - runs / (0f + invokers.size())) < runs / (0f + invokers.size()), + "abs diff should < avg"); } } @@ -57,7 +58,8 @@ class LeastActiveBalanceTest extends LoadBalanceBaseTest { sumInvoker2++; } // never select invoker3 because it's active is more than invoker1 and invoker2 - Assertions.assertTrue(!selected.getUrl().getProtocol().equals("test3"), "select is not the least active one"); + Assertions.assertTrue( + !selected.getUrl().getProtocol().equals("test3"), "select is not the least active one"); } // the sumInvoker1 : sumInvoker2 approximately equal to 1: 9 diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LoadBalanceBaseTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LoadBalanceBaseTest.java index 564680472d..9aa57ef690 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LoadBalanceBaseTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LoadBalanceBaseTest.java @@ -25,18 +25,18 @@ import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.RpcStatus; import org.apache.dubbo.rpc.cluster.LoadBalance; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_WARMUP; import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_WEIGHT; import static org.mockito.BDDMockito.given; @@ -67,8 +67,7 @@ class LoadBalanceBaseTest { * @throws java.lang.Exception */ @BeforeAll - public static void setUpBeforeClass() throws Exception { - } + public static void setUpBeforeClass() throws Exception {} /** * @throws java.lang.Exception @@ -78,14 +77,14 @@ class LoadBalanceBaseTest { invocation = mock(Invocation.class); given(invocation.getMethodName()).willReturn("method1"); - given(invocation.getArguments()).willReturn(new Object[] {"arg1","arg2","arg3"}); + given(invocation.getArguments()).willReturn(new Object[] {"arg1", "arg2", "arg3"}); genericInvocation = mock(Invocation.class); String methodName = "method1"; given(genericInvocation.getMethodName()).willReturn("$invoke"); - String[] paraTypes = new String[] {String.class.getName(),String.class.getName(),String.class.getName()}; - Object[] argsObject = new Object[] {"arg1","arg2","arg3"}; - Object[] args = new Object[] {methodName,paraTypes,argsObject}; + String[] paraTypes = new String[] {String.class.getName(), String.class.getName(), String.class.getName()}; + Object[] argsObject = new Object[] {"arg1", "arg2", "arg3"}; + Object[] args = new Object[] {methodName, paraTypes, argsObject}; given(genericInvocation.getArguments()).willReturn(args); invoker1 = mock(Invoker.class); @@ -156,7 +155,8 @@ class LoadBalanceBaseTest { } protected AbstractLoadBalance getLoadBalance(String loadbalanceName) { - return (AbstractLoadBalance) ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(loadbalanceName); + return (AbstractLoadBalance) + ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(loadbalanceName); } @Test @@ -229,7 +229,7 @@ class LoadBalanceBaseTest { } protected List> weightInvokers = new ArrayList>(); - protected List> weightInvokersSR= new ArrayList>(); + protected List> weightInvokersSR = new ArrayList>(); protected Invoker weightInvoker1; protected Invoker weightInvoker2; @@ -287,7 +287,6 @@ class LoadBalanceBaseTest { weightTestRpcStatus3 = RpcStatus.getStatus(weightInvoker3.getUrl(), weightTestInvocation.getMethodName()); weightTestRpcStatus5 = RpcStatus.getStatus(weightInvoker5.getUrl(), weightTestInvocation.getMethodName()); - // weightTestRpcStatus3 active is 1 RpcStatus.beginCount(weightInvoker3.getUrl(), weightTestInvocation.getMethodName()); @@ -302,7 +301,7 @@ class LoadBalanceBaseTest { Map counter = new ConcurrentHashMap(); AbstractLoadBalance lb = getLoadBalance(loadbalanceName); int totalWeight = 0; - for (int i = 0; i < weightInvokers.size(); i ++) { + for (int i = 0; i < weightInvokers.size(); i++) { InvokeResult invokeResult = new InvokeResult(lb.getWeight(weightInvokers.get(i), weightTestInvocation)); counter.put(weightInvokers.get(i), invokeResult); totalWeight += invokeResult.getWeight(); @@ -317,5 +316,4 @@ class LoadBalanceBaseTest { } return counter; } - } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalanceTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalanceTest.java index f01ac1d526..7fb7864340 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalanceTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalanceTest.java @@ -19,12 +19,12 @@ package org.apache.dubbo.rpc.cluster.loadbalance; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcStatus; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.Map; import java.util.concurrent.atomic.AtomicLong; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + /** * RandomLoadBalance Test */ @@ -35,7 +35,9 @@ class RandomLoadBalanceTest extends LoadBalanceBaseTest { Map counter = getInvokeCounter(runs, RandomLoadBalance.NAME); for (Map.Entry entry : counter.entrySet()) { Long count = entry.getValue().get(); - Assertions.assertTrue(Math.abs(count - runs / (0f + invokers.size())) < runs / (0f + invokers.size()), "abs diff should < avg"); + Assertions.assertTrue( + Math.abs(count - runs / (0f + invokers.size())) < runs / (0f + invokers.size()), + "abs diff should < avg"); } for (int i = 0; i < 5; i++) { @@ -84,5 +86,4 @@ class RandomLoadBalanceTest extends LoadBalanceBaseTest { System.out.println(sumInvoker3); Assertions.assertEquals(sumInvoker1 + sumInvoker2 + sumInvoker3, loop, "select failed!"); } - } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/RoundRobinLoadBalanceTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/RoundRobinLoadBalanceTest.java index 0a407847be..f201bbf7db 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/RoundRobinLoadBalanceTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/RoundRobinLoadBalanceTest.java @@ -18,10 +18,6 @@ package org.apache.dubbo.rpc.cluster.loadbalance; import org.apache.dubbo.rpc.Invoker; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; @@ -31,6 +27,10 @@ import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + @Disabled class RoundRobinLoadBalanceTest extends LoadBalanceBaseTest { @@ -77,7 +77,9 @@ class RoundRobinLoadBalanceTest extends LoadBalanceBaseTest { if (!totalMap.containsKey(entry.getKey())) { totalMap.put(entry.getKey(), entry.getValue()); } else { - totalMap.get(entry.getKey()).getCount().addAndGet(entry.getValue().getCount().get()); + totalMap.get(entry.getKey()) + .getCount() + .addAndGet(entry.getValue().getCount().get()); } } } @@ -100,7 +102,7 @@ class RoundRobinLoadBalanceTest extends LoadBalanceBaseTest { @Test void testNodeCacheShouldNotRecycle() { int loop = 10000; - //tmperately add a new invoker + // tmperately add a new invoker weightInvokers.add(weightInvokerTmp); try { Map resultMap = getWeightedInvokeResult(loop, RoundRobinLoadBalance.NAME); @@ -108,16 +110,20 @@ class RoundRobinLoadBalanceTest extends LoadBalanceBaseTest { // inner nodes cache judgement RoundRobinLoadBalance lb = (RoundRobinLoadBalance) getLoadBalance(RoundRobinLoadBalance.NAME); - Assertions.assertEquals(weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size()); + Assertions.assertEquals( + weightInvokers.size(), + lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size()); weightInvokers.remove(weightInvokerTmp); resultMap = getWeightedInvokeResult(loop, RoundRobinLoadBalance.NAME); assertStrictWRRResult(loop, resultMap); - Assertions.assertNotEquals(weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size()); + Assertions.assertNotEquals( + weightInvokers.size(), + lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size()); } finally { - //prevent other UT's failure + // prevent other UT's failure weightInvokers.remove(weightInvokerTmp); } } @@ -127,7 +133,7 @@ class RoundRobinLoadBalanceTest extends LoadBalanceBaseTest { { Field recycleTimeField = null; try { - //change recycle time to 1 ms + // change recycle time to 1 ms recycleTimeField = RoundRobinLoadBalance.class.getDeclaredField("RECYCLE_PERIOD"); recycleTimeField.setAccessible(true); recycleTimeField.setInt(RoundRobinLoadBalance.class, 10); @@ -137,7 +143,7 @@ class RoundRobinLoadBalanceTest extends LoadBalanceBaseTest { } int loop = 10000; - //tmperately add a new invoker + // tmperately add a new invoker weightInvokers.add(weightInvokerTmp); try { Map resultMap = getWeightedInvokeResult(loop, RoundRobinLoadBalance.NAME); @@ -145,18 +151,21 @@ class RoundRobinLoadBalanceTest extends LoadBalanceBaseTest { // inner nodes cache judgement RoundRobinLoadBalance lb = (RoundRobinLoadBalance) getLoadBalance(RoundRobinLoadBalance.NAME); - Assertions.assertEquals(weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size()); + Assertions.assertEquals( + weightInvokers.size(), + lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size()); weightInvokers.remove(weightInvokerTmp); resultMap = getWeightedInvokeResult(loop, RoundRobinLoadBalance.NAME); assertStrictWRRResult(loop, resultMap); - Assertions.assertEquals(weightInvokers.size(), lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size()); + Assertions.assertEquals( + weightInvokers.size(), + lb.getInvokerAddrList(weightInvokers, weightTestInvocation).size()); } finally { - //prevent other UT's failure + // prevent other UT's failure weightInvokers.remove(weightInvokerTmp); } } - } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/ShortestResponseLoadBalanceTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/ShortestResponseLoadBalanceTest.java index bf617a6923..6275ab65d7 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/ShortestResponseLoadBalanceTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/ShortestResponseLoadBalanceTest.java @@ -21,18 +21,18 @@ import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcStatus; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Order; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; - import java.lang.reflect.Field; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.stream.Collectors; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class ShortestResponseLoadBalanceTest extends LoadBalanceBaseTest { @@ -74,13 +74,14 @@ class ShortestResponseLoadBalanceTest extends LoadBalanceBaseTest { int sumInvoker5 = 0; int loop = 10000; - //active -> 0 + // active -> 0 RpcStatus.endCount(weightInvoker5.getUrl(), weightTestInvocation.getMethodName(), 5000L, true); ShortestResponseLoadBalance lb = new ShortestResponseLoadBalance(); lb.setApplicationModel(ApplicationModel.defaultModel()); - //reset slideWindow - Field lastUpdateTimeField = ReflectUtils.forName(ShortestResponseLoadBalance.class.getName()).getDeclaredField("lastUpdateTime"); + // reset slideWindow + Field lastUpdateTimeField = ReflectUtils.forName(ShortestResponseLoadBalance.class.getName()) + .getDeclaredField("lastUpdateTime"); lastUpdateTimeField.setAccessible(true); lastUpdateTimeField.setLong(lb, System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(31)); lb.select(weightInvokersSR, null, weightTestInvocation); @@ -101,14 +102,19 @@ class ShortestResponseLoadBalanceTest extends LoadBalanceBaseTest { } } Map, Integer> weightMap = weightInvokersSR.stream() - .collect(Collectors.toMap(Function.identity(), e -> Integer.valueOf(e.getUrl().getParameter("weight")))); + .collect(Collectors.toMap( + Function.identity(), e -> Integer.valueOf(e.getUrl().getParameter("weight")))); Integer totalWeight = weightMap.values().stream().reduce(0, Integer::sum); // max deviation = expectWeightValue * 2 int expectWeightValue = loop / totalWeight; int maxDeviation = expectWeightValue * 2; Assertions.assertEquals(sumInvoker1 + sumInvoker2 + sumInvoker5, loop, "select failed!"); - Assertions.assertTrue(Math.abs(sumInvoker2 / weightMap.get(weightInvoker2) - expectWeightValue) < maxDeviation, "select failed!"); - Assertions.assertTrue(Math.abs(sumInvoker5 / weightMap.get(weightInvoker5) - expectWeightValue) < maxDeviation, "select failed!"); + Assertions.assertTrue( + Math.abs(sumInvoker2 / weightMap.get(weightInvoker2) - expectWeightValue) < maxDeviation, + "select failed!"); + Assertions.assertTrue( + Math.abs(sumInvoker5 / weightMap.get(weightInvoker5) - expectWeightValue) < maxDeviation, + "select failed!"); } } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/MockInvoker.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/MockInvoker.java index 11a87dcf09..7de1783028 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/MockInvoker.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/MockInvoker.java @@ -26,8 +26,7 @@ public class MockInvoker implements Invoker { private boolean available = false; private URL url; - public MockInvoker() { - } + public MockInvoker() {} public MockInvoker(URL url) { super(); @@ -64,6 +63,5 @@ public class MockInvoker implements Invoker { } @Override - public void destroy() { - } + public void destroy() {} } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/RouterSnapshotFilterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/RouterSnapshotFilterTest.java index 4dd245f1f3..2c6d1c0b9f 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/RouterSnapshotFilterTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/RouterSnapshotFilterTest.java @@ -37,7 +37,8 @@ class RouterSnapshotFilterTest { @Test void test() { FrameworkModel frameworkModel = new FrameworkModel(); - RouterSnapshotSwitcher routerSnapshotSwitcher = frameworkModel.getBeanFactory().getBean(RouterSnapshotSwitcher.class); + RouterSnapshotSwitcher routerSnapshotSwitcher = + frameworkModel.getBeanFactory().getBean(RouterSnapshotSwitcher.class); RouterSnapshotFilter routerSnapshotFilter = new RouterSnapshotFilter(frameworkModel); Invoker invoker = Mockito.mock(Invoker.class); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/BoolMatchTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/BoolMatchTest.java index 5b9ad498ae..fcef780c74 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/BoolMatchTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/BoolMatchTest.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match; - import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -27,16 +25,14 @@ class BoolMatchTest { @Test void isMatch() { - BoolMatch boolMatch = new BoolMatch(); + BoolMatch boolMatch = new BoolMatch(); boolMatch.setExact(true); - assertTrue(boolMatch.isMatch(true)); assertFalse(boolMatch.isMatch(false)); boolMatch.setExact(false); assertFalse(boolMatch.isMatch(true)); assertTrue(boolMatch.isMatch(false)); - } } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DoubleMatchTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DoubleMatchTest.java index 2412e175e4..630bb37f85 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DoubleMatchTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DoubleMatchTest.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match; - import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -47,7 +45,6 @@ class DoubleMatchTest { assertFalse(doubleMatch.isMatch(9.0)); } - @Test void rangeEndMatch() { DoubleMatch doubleMatch = new DoubleMatch(); @@ -61,7 +58,6 @@ class DoubleMatchTest { assertTrue(doubleMatch.isMatch(9.0)); } - @Test void rangeStartEndMatch() { DoubleMatch doubleMatch = new DoubleMatch(); @@ -79,7 +75,6 @@ class DoubleMatchTest { assertFalse(doubleMatch.isMatch(10.1)); assertTrue(doubleMatch.isMatch(6.0)); - } @Test @@ -97,5 +92,4 @@ class DoubleMatchTest { assertFalse(doubleMatch.isMatch(2.0)); assertTrue(doubleMatch.isMatch(3.0)); } - } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboMethodMatchTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboMethodMatchTest.java index 267a30f662..ca478c5868 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboMethodMatchTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboMethodMatchTest.java @@ -14,17 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match; - import org.apache.dubbo.rpc.RpcInvocation; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.List; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -39,17 +37,19 @@ class DubboMethodMatchTest { dubboMethodMatch.setName_match(nameStringMatch); - assertTrue(dubboMethodMatch.isMatch(new RpcInvocation(null, "sayHello", "", "", new Class[]{}, new Object[]{}))); + assertTrue( + dubboMethodMatch.isMatch(new RpcInvocation(null, "sayHello", "", "", new Class[] {}, new Object[] {}))); } - @Test void argcMatch() { DubboMethodMatch dubboMethodMatch = new DubboMethodMatch(); dubboMethodMatch.setArgc(1); - assertFalse(dubboMethodMatch.isMatch(new RpcInvocation(null, "sayHello", "", "", new Class[]{}, new Object[]{}))); - assertTrue(dubboMethodMatch.isMatch(new RpcInvocation(null, "sayHello", "", "", new Class[]{}, new Object[]{"1"}))); + assertFalse( + dubboMethodMatch.isMatch(new RpcInvocation(null, "sayHello", "", "", new Class[] {}, new Object[] {}))); + assertTrue(dubboMethodMatch.isMatch( + new RpcInvocation(null, "sayHello", "", "", new Class[] {}, new Object[] {"1"}))); } @Test @@ -69,10 +69,12 @@ class DubboMethodMatchTest { dubboMethodMatch.setArgp(argpMatch); - - assertTrue(dubboMethodMatch.isMatch(new RpcInvocation(null, "sayHello", "", "", new Class[]{Long.class, String.class}, new Object[]{}))); - assertFalse(dubboMethodMatch.isMatch(new RpcInvocation(null, "sayHello", "", "", new Class[]{Long.class, String.class, String.class}, new Object[]{}))); - assertFalse(dubboMethodMatch.isMatch(new RpcInvocation(null, "sayHello", "", "", new Class[]{}, new Object[]{}))); + assertTrue(dubboMethodMatch.isMatch( + new RpcInvocation(null, "sayHello", "", "", new Class[] {Long.class, String.class}, new Object[] {}))); + assertFalse(dubboMethodMatch.isMatch(new RpcInvocation( + null, "sayHello", "", "", new Class[] {Long.class, String.class, String.class}, new Object[] {}))); + assertFalse( + dubboMethodMatch.isMatch(new RpcInvocation(null, "sayHello", "", "", new Class[] {}, new Object[] {}))); } @Test @@ -82,7 +84,7 @@ class DubboMethodMatchTest { List parametersMatch = new ArrayList<>(); - //----- index 0 + // ----- index 0 { DubboMethodArg dubboMethodArg0 = new DubboMethodArg(); dubboMethodArg0.setIndex(0); @@ -102,10 +104,9 @@ class DubboMethodMatchTest { parametersMatch.add(dubboMethodArg0); } - //-----index 1 + // -----index 1 { - DubboMethodArg dubboMethodArg1 = new DubboMethodArg(); dubboMethodArg1.setIndex(1); @@ -127,28 +128,32 @@ class DubboMethodMatchTest { dubboMethodMatch.setArgs(parametersMatch); - assertTrue(dubboMethodMatch.isMatch(new RpcInvocation(null, "test", "", "", new Class[]{int.class, String.class}, new Object[]{10, "sayHello"}))); - assertFalse(dubboMethodMatch.isMatch(new RpcInvocation(null, "test", "", "", new Class[]{int.class, String.class}, new Object[]{10, "sayHi"}))); + assertTrue(dubboMethodMatch.isMatch(new RpcInvocation( + null, "test", "", "", new Class[] {int.class, String.class}, new Object[] {10, "sayHello"}))); + assertFalse(dubboMethodMatch.isMatch(new RpcInvocation( + null, "test", "", "", new Class[] {int.class, String.class}, new Object[] {10, "sayHi"}))); - - //-----index 2 + // -----index 2 { - DubboMethodArg dubboMethodArg2 = new DubboMethodArg(); dubboMethodArg2.setIndex(2); BoolMatch boolMatch = new BoolMatch(); boolMatch.setExact(true); - dubboMethodArg2.setBool_value(boolMatch); parametersMatch.add(dubboMethodArg2); } - - assertTrue(dubboMethodMatch.isMatch(new RpcInvocation(null, "test", "", "", new Class[]{int.class, String.class, boolean.class}, new Object[]{10, "sayHello", true}))); - assertFalse(dubboMethodMatch.isMatch(new RpcInvocation(null, "test", "", "", new Class[]{int.class, String.class, boolean.class}, new Object[]{10, "sayHello", false}))); + assertTrue(dubboMethodMatch.isMatch(new RpcInvocation( + null, "test", "", "", new Class[] {int.class, String.class, boolean.class}, new Object[] { + 10, "sayHello", true + }))); + assertFalse(dubboMethodMatch.isMatch(new RpcInvocation( + null, "test", "", "", new Class[] {int.class, String.class, boolean.class}, new Object[] { + 10, "sayHello", false + }))); } } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListBoolMatchTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListBoolMatchTest.java index 7984a028ae..e5edd0f134 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListBoolMatchTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListBoolMatchTest.java @@ -14,18 +14,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.List; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; - class ListBoolMatchTest { @Test diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListDoubleMatchTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListDoubleMatchTest.java index 1730b76bd7..74176a1e72 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListDoubleMatchTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListDoubleMatchTest.java @@ -14,19 +14,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match; - -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.List; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; - class ListDoubleMatchTest { @Test diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListStringMatchTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListStringMatchTest.java index 7a7e68cf0b..7c41cb702f 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListStringMatchTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListStringMatchTest.java @@ -14,15 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match; - -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.List; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -43,12 +41,10 @@ class ListStringMatchTest { oneof.add(stringMatch1); oneof.add(stringMatch2); - listStringMatch.setOneof(oneof); assertTrue(listStringMatch.isMatch("1")); assertTrue(listStringMatch.isMatch("2")); assertFalse(listStringMatch.isMatch("3")); - } } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/StringMatchTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/StringMatchTest.java index 5a3b13c57a..fdae04519e 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/StringMatchTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/StringMatchTest.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match; - import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -35,7 +33,6 @@ class StringMatchTest { assertFalse(stringMatch.isMatch(null)); } - @Test void prefixMatch() { StringMatch stringMatch = new StringMatch(); @@ -46,7 +43,6 @@ class StringMatchTest { assertFalse(stringMatch.isMatch(null)); } - @Test void regxMatch() { StringMatch stringMatch = new StringMatch(); @@ -58,7 +54,6 @@ class StringMatchTest { assertFalse(stringMatch.isMatch("com.taobao")); } - @Test void emptyMatch() { StringMatch stringMatch = new StringMatch(); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/state/BitListTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/state/BitListTest.java index 54bc765fb2..9996de577f 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/state/BitListTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/state/BitListTest.java @@ -16,10 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.router.state; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.provider.ValueSource; - import java.util.Arrays; import java.util.Collections; import java.util.HashSet; @@ -27,6 +23,10 @@ import java.util.LinkedList; import java.util.List; import java.util.ListIterator; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.provider.ValueSource; + class BitListTest { @Test void test() { @@ -152,7 +152,6 @@ class BitListTest { Assertions.assertEquals(3, bitList1.size()); Assertions.assertFalse(bitList1.hasMoreElementInTailList()); - bitList1.addAll(bitList2); Assertions.assertEquals(3, bitList1.size()); @@ -353,7 +352,10 @@ class BitListTest { } @Test - @ValueSource(ints = {2, }) + @ValueSource( + ints = { + 2, + }) void testListIterator2() { List list = Arrays.asList("A", "B", "C", "D", "E"); BitList bitList = new BitList<>(list); @@ -435,7 +437,6 @@ class BitListTest { Assertions.assertEquals(expectedResult, bitList); - while (listIterator.hasPrevious()) { Assertions.assertEquals(expectedIterator.previousIndex(), listIterator.previousIndex()); Assertions.assertEquals(expectedIterator.previous(), listIterator.previous()); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java index 496e4369b2..6cbed8481f 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AbstractClusterInvokerTest.java @@ -36,6 +36,14 @@ import org.apache.dubbo.rpc.cluster.loadbalance.RandomLoadBalance; import org.apache.dubbo.rpc.cluster.loadbalance.RoundRobinLoadBalance; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicLong; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; @@ -45,14 +53,6 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicLong; - import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; import static org.apache.dubbo.common.constants.CommonConstants.ENABLE_CONNECTIVITY_VALIDATION; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; @@ -78,8 +78,11 @@ class AbstractClusterInvokerTest { AbstractClusterInvoker cluster_nocheck; StaticDirectory dic; RpcInvocation invocation = new RpcInvocation(); - URL url = URL.valueOf("registry://localhost:9090/org.apache.dubbo.rpc.cluster.support.AbstractClusterInvokerTest.IHelloService?refer=" + URL.encode("application=abstractClusterInvokerTest")); - URL consumerUrl = URL.valueOf("dubbo://localhost?application=abstractClusterInvokerTest&refer=application%3DabstractClusterInvokerTest"); + URL url = URL.valueOf( + "registry://localhost:9090/org.apache.dubbo.rpc.cluster.support.AbstractClusterInvokerTest.IHelloService?refer=" + + URL.encode("application=abstractClusterInvokerTest")); + URL consumerUrl = URL.valueOf( + "dubbo://localhost?application=abstractClusterInvokerTest&refer=application%3DabstractClusterInvokerTest"); Invoker invoker1; Invoker invoker2; @@ -156,17 +159,19 @@ class AbstractClusterInvokerTest { } }; - cluster_nocheck = new AbstractClusterInvoker(dic, url.addParameterIfAbsent(CLUSTER_AVAILABLE_CHECK_KEY, Boolean.FALSE.toString())) { - @Override - protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance) - throws RpcException { - return null; - } - }; - + cluster_nocheck = + new AbstractClusterInvoker( + dic, url.addParameterIfAbsent(CLUSTER_AVAILABLE_CHECK_KEY, Boolean.FALSE.toString())) { + @Override + protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance) + throws RpcException { + return null; + } + }; } - @Disabled("RpcContext attachments will be set to Invocation twice, first in ConsumerContextFilter, second AbstractInvoker") + @Disabled( + "RpcContext attachments will be set to Invocation twice, first in ConsumerContextFilter, second AbstractInvoker") @Test void testBindingAttachment() { final String attachKey = "attach"; @@ -175,7 +180,7 @@ class AbstractClusterInvokerTest { // setup attachment RpcContext.getClientAttachment().setAttachment(attachKey, attachValue); Map attachments = RpcContext.getClientAttachment().getObjectAttachments(); - Assertions.assertTrue( attachments != null && attachments.size() == 1,"set attachment failed!"); + Assertions.assertTrue(attachments != null && attachments.size() == 1, "set attachment failed!"); cluster = new AbstractClusterInvoker(dic) { @Override @@ -196,7 +201,7 @@ class AbstractClusterInvokerTest { @Test void testSelect_Invokersize0() { LoadBalance l = cluster.initLoadBalance(invokers, invocation); - Assertions.assertNotNull(l,"cluster.initLoadBalance returns null!"); + Assertions.assertNotNull(l, "cluster.initLoadBalance returns null!"); { Invoker invoker = cluster.select(l, null, null, null); Assertions.assertNull(invoker); @@ -214,7 +219,7 @@ class AbstractClusterInvokerTest { cluster = new AbstractClusterInvoker(dic) { @Override protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance) - throws RpcException { + throws RpcException { checkInvokers(invokers, invocation); Invoker invoker = select(loadbalance, invocation, invokers, null); return invokeWithContext(invoker, invocation); @@ -232,7 +237,7 @@ class AbstractClusterInvokerTest { invokers.clear(); invokers.add(invoker1); LoadBalance l = cluster.initLoadBalance(invokers, invocation); - Assertions.assertNotNull(l,"cluster.initLoadBalance returns null!"); + Assertions.assertNotNull(l, "cluster.initLoadBalance returns null!"); Invoker invoker = cluster.select(l, null, invokers, null); Assertions.assertEquals(invoker1, invoker); } @@ -243,7 +248,7 @@ class AbstractClusterInvokerTest { invokers.add(invoker2); invokers.add(invoker4); LoadBalance l = cluster.initLoadBalance(invokers, invocation); - Assertions.assertNotNull(l,"cluster.initLoadBalance returns null!"); + Assertions.assertNotNull(l, "cluster.initLoadBalance returns null!"); { selectedInvokers.clear(); selectedInvokers.add(invoker4); @@ -268,7 +273,7 @@ class AbstractClusterInvokerTest { @Test void testCloseAvailablecheck() { LoadBalance lb = mock(LoadBalance.class); - Map queryMap = (Map )url.getAttribute(REFER_KEY); + Map queryMap = (Map) url.getAttribute(REFER_KEY); URL tmpUrl = turnRegistryUrlToConsumerUrl(url, queryMap); when(lb.select(same(invokers), eq(tmpUrl), same(invocation))).thenReturn(invoker1); @@ -277,11 +282,11 @@ class AbstractClusterInvokerTest { Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers); Assertions.assertFalse(sinvoker.isAvailable()); Assertions.assertEquals(invoker1, sinvoker); - } private URL turnRegistryUrlToConsumerUrl(URL url, Map queryMap) { - String host = StringUtils.isNotEmpty(queryMap.get("register.ip")) ? queryMap.get("register.ip") : this.url.getHost(); + String host = + StringUtils.isNotEmpty(queryMap.get("register.ip")) ? queryMap.get("register.ip") : this.url.getHost(); String path = queryMap.get(PATH_KEY); String consumedProtocol = queryMap.get(PROTOCOL_KEY) == null ? CONSUMER : queryMap.get(PROTOCOL_KEY); @@ -299,7 +304,7 @@ class AbstractClusterInvokerTest { LoadBalance lb = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(RoundRobinLoadBalance.NAME); initlistsize5(); { - //Boundary condition test . + // Boundary condition test . selectedInvokers.clear(); selectedInvokers.add(invoker2); selectedInvokers.add(invoker3); @@ -309,7 +314,7 @@ class AbstractClusterInvokerTest { Assertions.assertSame(invoker1, sinvoker); } { - //Boundary condition test . + // Boundary condition test . selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker3); @@ -319,7 +324,7 @@ class AbstractClusterInvokerTest { Assertions.assertSame(invoker2, sinvoker); } { - //Boundary condition test . + // Boundary condition test . selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker2); @@ -329,7 +334,7 @@ class AbstractClusterInvokerTest { Assertions.assertSame(invoker3, sinvoker); } { - //Boundary condition test . + // Boundary condition test . selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker2); @@ -339,7 +344,7 @@ class AbstractClusterInvokerTest { Assertions.assertSame(invoker5, sinvoker); } { - //Boundary condition test . + // Boundary condition test . selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker2); @@ -349,7 +354,6 @@ class AbstractClusterInvokerTest { Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers); Assertions.assertTrue(invokers.contains(sinvoker)); } - } @Test @@ -358,7 +362,7 @@ class AbstractClusterInvokerTest { LoadBalance lb = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(RoundRobinLoadBalance.NAME); initlistsize5(); { - //Boundary condition test . + // Boundary condition test . selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker2); @@ -368,7 +372,7 @@ class AbstractClusterInvokerTest { Assertions.assertSame(sinvoker, invoker4); } { - //Boundary condition test . + // Boundary condition test . selectedInvokers.clear(); selectedInvokers.add(invoker2); selectedInvokers.add(invoker3); @@ -378,7 +382,7 @@ class AbstractClusterInvokerTest { Assertions.assertTrue(sinvoker == invoker2 || sinvoker == invoker4); } { - //Boundary condition test . + // Boundary condition test . for (int i = 0; i < 100; i++) { selectedInvokers.clear(); Invoker sinvoker = cluster.select(lb, invocation, invokers, selectedInvokers); @@ -386,7 +390,7 @@ class AbstractClusterInvokerTest { } } { - //Boundary condition test . + // Boundary condition test . for (int i = 0; i < 100; i++) { selectedInvokers.clear(); selectedInvokers.add(invoker1); @@ -397,7 +401,7 @@ class AbstractClusterInvokerTest { } } { - //Boundary condition test . + // Boundary condition test . for (int i = 0; i < 100; i++) { selectedInvokers.clear(); selectedInvokers.add(invoker1); @@ -411,7 +415,6 @@ class AbstractClusterInvokerTest { } } - public void testSelect_multiInvokers(String lbname) { int min = 100, max = 500; @@ -496,18 +499,19 @@ class AbstractClusterInvokerTest { for (Map.Entry entry : counter.entrySet()) { Long count = entry.getValue().get(); -// System.out.println(count); + // System.out.println(count); if (entry.getKey().isAvailable()) - Assertions.assertTrue(count > runs / invokers.size(),"count should > avg"); + Assertions.assertTrue(count > runs / invokers.size(), "count should > avg"); } - Assertions.assertEquals(runs, counter.get(invoker2).get() + counter.get(invoker4).get()); - + Assertions.assertEquals( + runs, counter.get(invoker2).get() + counter.get(invoker4).get()); } private void initlistsize5() { invokers.clear(); - selectedInvokers.clear();//Clear first, previous test case will make sure that the right invoker2 will be used. + selectedInvokers + .clear(); // Clear first, previous test case will make sure that the right invoker2 will be used. invokers.add(invoker1); invokers.add(invoker2); invokers.add(invoker3); @@ -545,12 +549,12 @@ class AbstractClusterInvokerTest { } @Override - public void destroy() { - } + public void destroy() {} }); Directory directory = new StaticDirectory(invokers); FailoverClusterInvoker failoverClusterInvoker = new FailoverClusterInvoker(directory); - RpcInvocation invocation = new RpcInvocation("sayHello", DemoService.class.getName(), "", new Class[0], new Object[0]); + RpcInvocation invocation = + new RpcInvocation("sayHello", DemoService.class.getName(), "", new Class[0], new Object[0]); try { failoverClusterInvoker.invoke(invocation); Assertions.fail(); @@ -575,6 +579,5 @@ class AbstractClusterInvokerTest { } } - public static interface IHelloService { - } + public static interface IHelloService {} } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AvailableClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AvailableClusterInvokerTest.java index b3357e9ba4..d4d03530a2 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AvailableClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/AvailableClusterInvokerTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.support; - import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invoker; @@ -25,13 +24,13 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.Directory; +import java.util.ArrayList; +import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.ArrayList; -import java.util.List; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.BDDMockito.given; diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/BroadCastClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/BroadCastClusterInvokerTest.java index 9cba72c075..5e63e97153 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/BroadCastClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/BroadCastClusterInvokerTest.java @@ -25,11 +25,11 @@ import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.cluster.filter.DemoService; +import java.util.Arrays; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Arrays; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -50,7 +50,6 @@ class BroadCastClusterInvokerTest { private MockInvoker invoker3; private MockInvoker invoker4; - @BeforeEach public void setUp() throws Exception { @@ -72,7 +71,6 @@ class BroadCastClusterInvokerTest { clusterInvoker = new BroadcastClusterInvoker(dic); } - @Test void testNormal() { given(dic.list(invocation)).willReturn(Arrays.asList(invoker1, invoker2, invoker3, invoker4)); @@ -91,7 +89,8 @@ class BroadCastClusterInvokerTest { assertThrows(RpcException.class, () -> { clusterInvoker.invoke(invocation); }); - // The default failure percentage is 100, even if a certain invoker#invoke throws an exception, other invokers will still be called + // The default failure percentage is 100, even if a certain invoker#invoke throws an exception, other invokers + // will still be called assertTrue(invoker1.isInvoked()); assertTrue(invoker2.isInvoked()); assertTrue(invoker3.isInvoked()); @@ -136,9 +135,7 @@ class MockInvoker implements Invoker { } @Override - public void destroy() { - - } + public void destroy() {} @Override public Class getInterface() { diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ClusterUtilsTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ClusterUtilsTest.java index 2f3bbe0e41..da26d2be04 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ClusterUtilsTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ClusterUtilsTest.java @@ -20,12 +20,12 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.Map; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Map; - import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY; @@ -43,7 +43,6 @@ import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.URL_MERGE_PROCESSOR_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; - class ClusterUtilsTest { private ClusterUtils clusterUtils; @@ -57,39 +56,37 @@ class ClusterUtilsTest { @Test void testMergeUrl() { URL providerURL = URL.valueOf("dubbo://localhost:55555"); - providerURL = providerURL.setPath("path") - .setUsername("username") - .setPassword("password"); + providerURL = providerURL.setPath("path").setUsername("username").setPassword("password"); providerURL = URLBuilder.from(providerURL) - .addParameter(GROUP_KEY, "dubbo") - .addParameter(VERSION_KEY, "1.2.3") - .addParameter(DUBBO_VERSION_KEY, "2.3.7") - .addParameter(THREADPOOL_KEY, "fixed") - .addParameter(THREADS_KEY, Integer.MAX_VALUE) - .addParameter(THREAD_NAME_KEY, "test") - .addParameter(CORE_THREADS_KEY, Integer.MAX_VALUE) - .addParameter(QUEUES_KEY, Integer.MAX_VALUE) - .addParameter(ALIVE_KEY, Integer.MAX_VALUE) - .addParameter(DEFAULT_KEY_PREFIX + THREADS_KEY, Integer.MAX_VALUE) - .addParameter(DEFAULT_KEY_PREFIX + THREADPOOL_KEY, "fixed") - .addParameter(DEFAULT_KEY_PREFIX + CORE_THREADS_KEY, Integer.MAX_VALUE) - .addParameter(DEFAULT_KEY_PREFIX + QUEUES_KEY, Integer.MAX_VALUE) - .addParameter(DEFAULT_KEY_PREFIX + ALIVE_KEY, Integer.MAX_VALUE) - .addParameter(DEFAULT_KEY_PREFIX + THREAD_NAME_KEY, "test") - .addParameter(APPLICATION_KEY, "provider") - .addParameter(REFERENCE_FILTER_KEY, "filter1,filter2") - .addParameter(TAG_KEY, "TTT") - .build(); + .addParameter(GROUP_KEY, "dubbo") + .addParameter(VERSION_KEY, "1.2.3") + .addParameter(DUBBO_VERSION_KEY, "2.3.7") + .addParameter(THREADPOOL_KEY, "fixed") + .addParameter(THREADS_KEY, Integer.MAX_VALUE) + .addParameter(THREAD_NAME_KEY, "test") + .addParameter(CORE_THREADS_KEY, Integer.MAX_VALUE) + .addParameter(QUEUES_KEY, Integer.MAX_VALUE) + .addParameter(ALIVE_KEY, Integer.MAX_VALUE) + .addParameter(DEFAULT_KEY_PREFIX + THREADS_KEY, Integer.MAX_VALUE) + .addParameter(DEFAULT_KEY_PREFIX + THREADPOOL_KEY, "fixed") + .addParameter(DEFAULT_KEY_PREFIX + CORE_THREADS_KEY, Integer.MAX_VALUE) + .addParameter(DEFAULT_KEY_PREFIX + QUEUES_KEY, Integer.MAX_VALUE) + .addParameter(DEFAULT_KEY_PREFIX + ALIVE_KEY, Integer.MAX_VALUE) + .addParameter(DEFAULT_KEY_PREFIX + THREAD_NAME_KEY, "test") + .addParameter(APPLICATION_KEY, "provider") + .addParameter(REFERENCE_FILTER_KEY, "filter1,filter2") + .addParameter(TAG_KEY, "TTT") + .build(); // Verify default ProviderURLMergeProcessor URL consumerURL = new URLBuilder(DUBBO_PROTOCOL, "localhost", 55555) - .addParameter(PID_KEY, "1234") - .addParameter(THREADPOOL_KEY, "foo") - .addParameter(APPLICATION_KEY, "consumer") - .addParameter(REFERENCE_FILTER_KEY, "filter3") - .addParameter(TAG_KEY, "UUU") - .build(); + .addParameter(PID_KEY, "1234") + .addParameter(THREADPOOL_KEY, "foo") + .addParameter(APPLICATION_KEY, "consumer") + .addParameter(REFERENCE_FILTER_KEY, "filter3") + .addParameter(TAG_KEY, "UUU") + .build(); URL url = clusterUtils.mergeUrl(providerURL, consumerURL.getParameters()); @@ -123,13 +120,13 @@ class ClusterUtilsTest { // Verify custom ProviderURLMergeProcessor URL consumerUrlForTag = new URLBuilder(DUBBO_PROTOCOL, "localhost", 55555) - .addParameter(PID_KEY, "1234") - .addParameter(THREADPOOL_KEY, "foo") - .addParameter(APPLICATION_KEY, "consumer") - .addParameter(REFERENCE_FILTER_KEY, "filter3") - .addParameter(TAG_KEY, "UUU") - .addParameter(URL_MERGE_PROCESSOR_KEY, "tag") - .build(); + .addParameter(PID_KEY, "1234") + .addParameter(THREADPOOL_KEY, "foo") + .addParameter(APPLICATION_KEY, "consumer") + .addParameter(REFERENCE_FILTER_KEY, "filter3") + .addParameter(TAG_KEY, "UUU") + .addParameter(URL_MERGE_PROCESSOR_KEY, "tag") + .build(); URL urlForTag = clusterUtils.mergeUrl(providerURL, consumerUrlForTag.getParameters()); Assertions.assertEquals("UUU", urlForTag.getParameter(TAG_KEY)); @@ -140,14 +137,14 @@ class ClusterUtilsTest { // Verify default ProviderURLMergeProcessor URL consumerURL = new URLBuilder(DUBBO_PROTOCOL, "localhost", 55555) - .addParameter(PID_KEY, "1234") - .addParameter(THREADPOOL_KEY, "foo") - .addParameter(APPLICATION_KEY, "consumer") - .addParameter(REFERENCE_FILTER_KEY, "filter3") - .addParameter(TAG_KEY, "UUU") - .build(); + .addParameter(PID_KEY, "1234") + .addParameter(THREADPOOL_KEY, "foo") + .addParameter(APPLICATION_KEY, "consumer") + .addParameter(REFERENCE_FILTER_KEY, "filter3") + .addParameter(TAG_KEY, "UUU") + .build(); - Map params = clusterUtils.mergeLocalParams(consumerURL.getParameters()); + Map params = clusterUtils.mergeLocalParams(consumerURL.getParameters()); Assertions.assertEquals("1234", params.get(PID_KEY)); Assertions.assertEquals("foo", params.get(THREADPOOL_KEY)); @@ -157,15 +154,15 @@ class ClusterUtilsTest { // Verify custom ProviderURLMergeProcessor URL consumerUrlForTag = new URLBuilder(DUBBO_PROTOCOL, "localhost", 55555) - .addParameter(PID_KEY, "1234") - .addParameter(THREADPOOL_KEY, "foo") - .addParameter(APPLICATION_KEY, "consumer") - .addParameter(REFERENCE_FILTER_KEY, "filter3") - .addParameter(TAG_KEY, "UUU") - .addParameter(URL_MERGE_PROCESSOR_KEY, "tag") - .build(); + .addParameter(PID_KEY, "1234") + .addParameter(THREADPOOL_KEY, "foo") + .addParameter(APPLICATION_KEY, "consumer") + .addParameter(REFERENCE_FILTER_KEY, "filter3") + .addParameter(TAG_KEY, "UUU") + .addParameter(URL_MERGE_PROCESSOR_KEY, "tag") + .build(); - Map paramsForTag = clusterUtils.mergeLocalParams(consumerUrlForTag.getParameters()); + Map paramsForTag = clusterUtils.mergeLocalParams(consumerUrlForTag.getParameters()); Assertions.assertEquals("1234", paramsForTag.get(PID_KEY)); Assertions.assertEquals("foo", paramsForTag.get(THREADPOOL_KEY)); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ConnectivityValidationTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ConnectivityValidationTest.java index 23cb42831f..a2f6b1499f 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ConnectivityValidationTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ConnectivityValidationTest.java @@ -28,15 +28,7 @@ import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.cluster.LoadBalance; import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; - import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; import java.util.Collections; import java.util.HashSet; @@ -45,6 +37,14 @@ import java.util.List; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + import static org.mockito.Mockito.when; @SuppressWarnings("all") @@ -143,7 +143,8 @@ class ConnectivityValidationTest { Assertions.assertEquals(5, directory.list(invocation).size()); - Assertions.assertNotNull(clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList())); + Assertions.assertNotNull( + clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList())); when(invoker1.isAvailable()).thenReturn(false); when(invoker2.isAvailable()).thenReturn(false); @@ -159,20 +160,23 @@ class ConnectivityValidationTest { invokerSet.add(invoker1); waitRefresh(invokerSet); Assertions.assertEquals(1, directory.list(invocation).size()); - Assertions.assertNotNull(clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList())); + Assertions.assertNotNull( + clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList())); when(invoker2.isAvailable()).thenReturn(true); invokerSet.add(invoker2); waitRefresh(invokerSet); Assertions.assertEquals(2, directory.list(invocation).size()); - Assertions.assertNotNull(clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList())); + Assertions.assertNotNull( + clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList())); invokerList.remove(invoker5); directory.notify(invokerList); when(invoker2.isAvailable()).thenReturn(true); waitRefresh(invokerSet); Assertions.assertEquals(2, directory.list(invocation).size()); - Assertions.assertNotNull(clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList())); + Assertions.assertNotNull( + clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList())); when(invoker3.isAvailable()).thenReturn(true); when(invoker4.isAvailable()).thenReturn(true); @@ -180,7 +184,8 @@ class ConnectivityValidationTest { invokerSet.add(invoker4); waitRefresh(invokerSet); Assertions.assertEquals(4, directory.list(invocation).size()); - Assertions.assertNotNull(clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList())); + Assertions.assertNotNull( + clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList())); } @Test @@ -196,7 +201,10 @@ class ConnectivityValidationTest { Assertions.assertEquals(2, directory.list(invocation).size()); when(invoker1.isAvailable()).thenReturn(false); - Assertions.assertEquals(invoker2, clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.singletonList(invoker2))); + Assertions.assertEquals( + invoker2, + clusterInvoker.select( + loadBalance, invocation, directory.list(invocation), Collections.singletonList(invoker2))); Assertions.assertEquals(1, directory.list(invocation).size()); when(invoker1.isAvailable()).thenReturn(true); @@ -244,7 +252,10 @@ class ConnectivityValidationTest { clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList()); } for (int i = 0; i < 5; i++) { - Assertions.assertEquals(invoker1, clusterInvoker.select(loadBalance, invocation, directory.list(invocation), Collections.emptyList())); + Assertions.assertEquals( + invoker1, + clusterInvoker.select( + loadBalance, invocation, directory.list(invocation), Collections.emptyList())); } when(invoker1.isAvailable()).thenReturn(false); @@ -293,12 +304,15 @@ class ConnectivityValidationTest { } @Override - public Invoker select(LoadBalance loadbalance, Invocation invocation, List> invokers, List> selected) throws RpcException { + public Invoker select( + LoadBalance loadbalance, Invocation invocation, List> invokers, List> selected) + throws RpcException { return super.select(loadbalance, invocation, invokers, selected); } @Override - protected Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) throws RpcException { + protected Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) + throws RpcException { return null; } } @@ -318,7 +332,9 @@ class ConnectivityValidationTest { private static class RandomLoadBalance implements LoadBalance { @Override public Invoker select(List> invokers, URL url, Invocation invocation) throws RpcException { - return CollectionUtils.isNotEmpty(invokers) ? invokers.get(ThreadLocalRandom.current().nextInt(invokers.size())) : null; + return CollectionUtils.isNotEmpty(invokers) + ? invokers.get(ThreadLocalRandom.current().nextInt(invokers.size())) + : null; } } } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailSafeClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailSafeClusterInvokerTest.java index 91c1c9ddd9..b1fe930960 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailSafeClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailSafeClusterInvokerTest.java @@ -26,13 +26,13 @@ import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.cluster.filter.DemoService; +import java.util.ArrayList; +import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.ArrayList; -import java.util.List; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -53,7 +53,6 @@ class FailSafeClusterInvokerTest { /** * @throws java.lang.Exception */ - @BeforeEach public void setUp() throws Exception { RpcContext.removeServiceContext(); @@ -81,7 +80,7 @@ class FailSafeClusterInvokerTest { given(invoker.getInterface()).willReturn(DemoService.class); } - //TODO assert error log + // TODO assert error log @Test void testInvokeExceptoin() { resetInvokerToException(); @@ -115,12 +114,11 @@ class FailSafeClusterInvokerTest { FailsafeClusterInvoker invoker = new FailsafeClusterInvoker(dic); - try{ + try { invoker.invoke(invocation); - } catch (RpcException e){ + } catch (RpcException e) { Assertions.assertTrue(e.getMessage().contains("No provider available")); assertFalse(e.getCause() instanceof RpcException); } } - } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvokerTest.java index bbc17745fc..413cc9615d 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailbackClusterInvokerTest.java @@ -1,4 +1,3 @@ - /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -29,6 +28,12 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.Directory; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + import org.apache.log4j.Level; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; @@ -39,12 +44,6 @@ import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - import static org.apache.dubbo.common.constants.CommonConstants.RETRIES_KEY; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.mockito.BDDMockito.given; @@ -68,7 +67,6 @@ class FailbackClusterInvokerTest { /** * @throws java.lang.Exception */ - @BeforeEach public void setUp() throws Exception { RpcContext.removeServiceContext(); @@ -92,7 +90,6 @@ class FailbackClusterInvokerTest { invokers.clear(); } - private void resetInvokerToException() { given(invoker.invoke(invocation)).willThrow(new RuntimeException()); given(invoker.getUrl()).willReturn(url); @@ -172,9 +169,9 @@ class FailbackClusterInvokerTest { invokers.add(invoker); FailbackClusterInvoker invoker = new FailbackClusterInvoker<>(dic); - try{ + try { invoker.invoke(invocation); - } catch (RpcException e){ + } catch (RpcException e) { Assertions.assertTrue(e.getMessage().contains("No provider available")); assertFalse(e.getCause() instanceof RpcException); } @@ -184,7 +181,7 @@ class FailbackClusterInvokerTest { @Test @Order(4) public void testARetryFailed() throws Exception { - //Test retries and + // Test retries and resetInvokerToException(); @@ -195,19 +192,23 @@ class FailbackClusterInvokerTest { invoker.invoke(invocation); invoker.invoke(invocation); Assertions.assertNull(RpcContext.getServiceContext().getInvoker()); -// invoker.retryFailed();// when retry the invoker which get from failed map already is not the mocked invoker,so - //Ensure that the main thread is online + // invoker.retryFailed();// when retry the invoker which get from failed map already is not the mocked + // invoker,so + // Ensure that the main thread is online CountDownLatch countDown = new CountDownLatch(1); countDown.await(15000L, TimeUnit.MILLISECONDS); LogUtil.stop(); - Assertions.assertEquals(4, LogUtil.findMessage(Level.ERROR, "Failed retry to invoke method"), "must have four error message "); - Assertions.assertEquals(2, LogUtil.findMessage(Level.ERROR, "Failed retry times exceed threshold"), "must have two error message "); - Assertions.assertEquals(1, LogUtil.findMessage(Level.ERROR, "Failback background works error"), "must have one error message "); + Assertions.assertEquals( + 4, LogUtil.findMessage(Level.ERROR, "Failed retry to invoke method"), "must have four error message "); + Assertions.assertEquals( + 2, + LogUtil.findMessage(Level.ERROR, "Failed retry times exceed threshold"), + "must have two error message "); + Assertions.assertEquals( + 1, LogUtil.findMessage(Level.ERROR, "Failback background works error"), "must have one error message "); // it can be invoke successfully } - - private long getRetryFailedPeriod() throws NoSuchFieldException, IllegalAccessException { Field retryFailedPeriod = FailbackClusterInvoker.class.getDeclaredField("RETRY_FAILED_PERIOD"); retryFailedPeriod.setAccessible(true); @@ -216,8 +217,8 @@ class FailbackClusterInvokerTest { @Test @Order(5) - public void testInvokeRetryTimesWithZeroValue() throws InterruptedException, NoSuchFieldException, - IllegalAccessException { + public void testInvokeRetryTimesWithZeroValue() + throws InterruptedException, NoSuchFieldException, IllegalAccessException { int retries = 0; resetInvokerToException(); given(dic.getConsumerUrl()).willReturn(url.addParameter(RETRIES_KEY, retries)); @@ -232,14 +233,17 @@ class FailbackClusterInvokerTest { CountDownLatch countDown = new CountDownLatch(1); countDown.await(getRetryFailedPeriod() * (retries + 1), TimeUnit.SECONDS); LogUtil.stop(); - Assertions.assertEquals(0, LogUtil.findMessage(Level.INFO, "Attempt to retry to invoke method " + - "testInvokeRetryTimesWithZeroValue"), "No retry messages allowed"); + Assertions.assertEquals( + 0, + LogUtil.findMessage( + Level.INFO, "Attempt to retry to invoke method " + "testInvokeRetryTimesWithZeroValue"), + "No retry messages allowed"); } @Test @Order(6) - public void testInvokeRetryTimesWithTwoValue() throws InterruptedException, NoSuchFieldException, - IllegalAccessException { + public void testInvokeRetryTimesWithTwoValue() + throws InterruptedException, NoSuchFieldException, IllegalAccessException { int retries = 2; resetInvokerToException(); given(dic.getConsumerUrl()).willReturn(url.addParameter(RETRIES_KEY, retries)); @@ -254,14 +258,17 @@ class FailbackClusterInvokerTest { CountDownLatch countDown = new CountDownLatch(1); countDown.await(getRetryFailedPeriod() * (retries + 1), TimeUnit.SECONDS); LogUtil.stop(); - Assertions.assertEquals(2, LogUtil.findMessage(Level.INFO, "Attempt to retry to invoke method " + - "testInvokeRetryTimesWithTwoValue"), "Must have two error message "); + Assertions.assertEquals( + 2, + LogUtil.findMessage( + Level.INFO, "Attempt to retry to invoke method " + "testInvokeRetryTimesWithTwoValue"), + "Must have two error message "); } @Test @Order(7) - public void testInvokeRetryTimesWithDefaultValue() throws InterruptedException, NoSuchFieldException, - IllegalAccessException { + public void testInvokeRetryTimesWithDefaultValue() + throws InterruptedException, NoSuchFieldException, IllegalAccessException { resetInvokerToException(); given(dic.getConsumerUrl()).willReturn(URL.valueOf("test://test:11/test")); @@ -275,14 +282,17 @@ class FailbackClusterInvokerTest { CountDownLatch countDown = new CountDownLatch(1); countDown.await(getRetryFailedPeriod() * (CommonConstants.DEFAULT_FAILBACK_TIMES + 1), TimeUnit.SECONDS); LogUtil.stop(); - Assertions.assertEquals(3, LogUtil.findMessage(Level.INFO, "Attempt to retry to invoke method " + - "testInvokeRetryTimesWithDefaultValue"), "Must have three error message "); + Assertions.assertEquals( + 3, + LogUtil.findMessage( + Level.INFO, "Attempt to retry to invoke method " + "testInvokeRetryTimesWithDefaultValue"), + "Must have three error message "); } @Test @Order(8) - public void testInvokeRetryTimesWithIllegalValue() throws InterruptedException, NoSuchFieldException, - IllegalAccessException { + public void testInvokeRetryTimesWithIllegalValue() + throws InterruptedException, NoSuchFieldException, IllegalAccessException { resetInvokerToException(); given(dic.getConsumerUrl()).willReturn(url.addParameter(RETRIES_KEY, -100)); @@ -296,7 +306,10 @@ class FailbackClusterInvokerTest { CountDownLatch countDown = new CountDownLatch(1); countDown.await(getRetryFailedPeriod() * (CommonConstants.DEFAULT_FAILBACK_TIMES + 1), TimeUnit.SECONDS); LogUtil.stop(); - Assertions.assertEquals(3, LogUtil.findMessage(Level.INFO, "Attempt to retry to invoke method " + - "testInvokeRetryTimesWithIllegalValue"), "Must have three error message "); + Assertions.assertEquals( + 3, + LogUtil.findMessage( + Level.INFO, "Attempt to retry to invoke method " + "testInvokeRetryTimesWithIllegalValue"), + "Must have three error message "); } } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailfastClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailfastClusterInvokerTest.java index f1f3412138..972d3d7683 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailfastClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailfastClusterInvokerTest.java @@ -25,13 +25,13 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.Directory; +import java.util.ArrayList; +import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.ArrayList; -import java.util.List; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertSame; @@ -54,7 +54,6 @@ class FailfastClusterInvokerTest { /** * @throws java.lang.Exception */ - @BeforeEach public void setUp() throws Exception { @@ -141,5 +140,4 @@ class FailfastClusterInvokerTest { assertFalse(expected.getCause() instanceof RpcException); } } - } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvokerTest.java index 4c99c50b35..bc48b8629c 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/FailoverClusterInvokerTest.java @@ -32,13 +32,14 @@ import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; import org.apache.dubbo.rpc.cluster.router.state.BitList; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.protocol.AbstractInvoker; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertSame; @@ -64,7 +65,6 @@ class FailoverClusterInvokerTest { /** * @throws java.lang.Exception */ - @BeforeEach public void setUp() throws Exception { ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); @@ -80,7 +80,6 @@ class FailoverClusterInvokerTest { invokers.add(invoker2); } - @Test void testInvokeWithRuntimeException() { given(invoker1.invoke(invocation)).willThrow(new RuntimeException()); @@ -197,7 +196,8 @@ class FailoverClusterInvokerTest { @Test void testInvoke_without_retry() { int withoutRetry = 0; - final URL url = URL.valueOf("test://localhost/" + Demo.class.getName() + "?loadbalance=roundrobin&retries=" + withoutRetry); + final URL url = URL.valueOf( + "test://localhost/" + Demo.class.getName() + "?loadbalance=roundrobin&retries=" + withoutRetry); RpcException exception = new RpcException(RpcException.TIMEOUT_EXCEPTION); MockInvoker invoker1 = new MockInvoker<>(Demo.class, url); invoker1.setException(exception); @@ -224,7 +224,8 @@ class FailoverClusterInvokerTest { @Test void testInvoke_when_retry_illegal() { int illegalRetry = -1; - final URL url = URL.valueOf("test://localhost/" + Demo.class.getName() + "?loadbalance=roundrobin&retries=" + illegalRetry); + final URL url = URL.valueOf( + "test://localhost/" + Demo.class.getName() + "?loadbalance=roundrobin&retries=" + illegalRetry); RpcException exception = new RpcException(RpcException.TIMEOUT_EXCEPTION); MockInvoker invoker1 = new MockInvoker<>(Demo.class, url); invoker1.setException(exception); @@ -260,7 +261,6 @@ class FailoverClusterInvokerTest { invokers.add(invoker1); - FailoverClusterInvoker invoker = new FailoverClusterInvoker<>(dic); try { invoker.invoke(invocation); @@ -276,7 +276,8 @@ class FailoverClusterInvokerTest { */ @Test void testInvokerDestroyAndReList() { - final URL url = URL.valueOf("test://localhost/" + Demo.class.getName() + "?loadbalance=roundrobin&retries=" + retries); + final URL url = + URL.valueOf("test://localhost/" + Demo.class.getName() + "?loadbalance=roundrobin&retries=" + retries); RpcException exception = new RpcException(RpcException.TIMEOUT_EXCEPTION); MockInvoker invoker1 = new MockInvoker<>(Demo.class, url); invoker1.setException(exception); @@ -291,7 +292,7 @@ class FailoverClusterInvokerTest { MockDirectory dic = new MockDirectory<>(url, invokers); Callable callable = () -> { - //Simulation: all invokers are destroyed + // Simulation: all invokers are destroyed for (Invoker invoker : invokers) { invoker.destroy(); } @@ -312,8 +313,7 @@ class FailoverClusterInvokerTest { clusterInvoker.invoke(inv); } - public interface Demo { - } + public interface Demo {} public static class MockInvoker extends AbstractInvoker { URL url; @@ -362,7 +362,9 @@ class FailoverClusterInvokerTest { } @Override - protected List> doList(SingleRouterChain singleRouterChain, BitList> invokers, Invocation invocation) throws RpcException { + protected List> doList( + SingleRouterChain singleRouterChain, BitList> invokers, Invocation invocation) + throws RpcException { return super.doList(singleRouterChain, invokers, invocation); } } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvokerTest.java index 4fe7400a33..1076babf80 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/ForkingClusterInvokerTest.java @@ -25,14 +25,14 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.Directory; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertFalse; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -67,7 +67,6 @@ class ForkingClusterInvokerTest { invokers.add(invoker1); invokers.add(invoker2); invokers.add(invoker3); - } private void resetInvokerToException() { @@ -134,7 +133,9 @@ class ForkingClusterInvokerTest { invoker.invoke(invocation); Assertions.fail(); } catch (RpcException expected) { - Assertions.assertTrue(expected.getMessage().contains("Failed to forking invoke provider"), "Succeeded to forking invoke provider !"); + Assertions.assertTrue( + expected.getMessage().contains("Failed to forking invoke provider"), + "Succeeded to forking invoke provider !"); assertFalse(expected.getCause() instanceof RpcException); } Map afterInvoke = RpcContext.getClientAttachment().getObjectAttachments(); @@ -165,5 +166,4 @@ class ForkingClusterInvokerTest { Result ret = invoker.invoke(invocation); Assertions.assertSame(result, ret); } - } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/TagProviderURLMergeProcessor.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/TagProviderURLMergeProcessor.java index 02d8ed6789..347146f0a7 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/TagProviderURLMergeProcessor.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/TagProviderURLMergeProcessor.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.support; - import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.cluster.ProviderURLMergeProcessor; diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/merger/DefaultProviderURLMergeProcessorTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/merger/DefaultProviderURLMergeProcessorTest.java index 9d3ce74e36..b26407b7ca 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/merger/DefaultProviderURLMergeProcessorTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/merger/DefaultProviderURLMergeProcessorTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.support.merger; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.rpc.cluster.ProviderURLMergeProcessor; @@ -59,38 +58,36 @@ class DefaultProviderURLMergeProcessorTest { @Test void testMergeUrl() { URL providerURL = URL.valueOf("dubbo://localhost:55555"); - providerURL = providerURL.setPath("path") - .setUsername("username") - .setPassword("password"); + providerURL = providerURL.setPath("path").setUsername("username").setPassword("password"); providerURL = URLBuilder.from(providerURL) - .addParameter(GROUP_KEY, "dubbo") - .addParameter(VERSION_KEY, "1.2.3") - .addParameter(DUBBO_VERSION_KEY, "2.3.7") - .addParameter(THREADPOOL_KEY, "fixed") - .addParameter(THREADS_KEY, Integer.MAX_VALUE) - .addParameter(THREAD_NAME_KEY, "test") - .addParameter(CORE_THREADS_KEY, Integer.MAX_VALUE) - .addParameter(QUEUES_KEY, Integer.MAX_VALUE) - .addParameter(ALIVE_KEY, Integer.MAX_VALUE) - .addParameter(DEFAULT_KEY_PREFIX + THREADS_KEY, Integer.MAX_VALUE) - .addParameter(DEFAULT_KEY_PREFIX + THREADPOOL_KEY, "fixed") - .addParameter(DEFAULT_KEY_PREFIX + CORE_THREADS_KEY, Integer.MAX_VALUE) - .addParameter(DEFAULT_KEY_PREFIX + QUEUES_KEY, Integer.MAX_VALUE) - .addParameter(DEFAULT_KEY_PREFIX + ALIVE_KEY, Integer.MAX_VALUE) - .addParameter(DEFAULT_KEY_PREFIX + THREAD_NAME_KEY, "test") - .addParameter(APPLICATION_KEY, "provider") - .addParameter(REFERENCE_FILTER_KEY, "filter1,filter2") - .addParameter(TAG_KEY, "TTT") - .build(); + .addParameter(GROUP_KEY, "dubbo") + .addParameter(VERSION_KEY, "1.2.3") + .addParameter(DUBBO_VERSION_KEY, "2.3.7") + .addParameter(THREADPOOL_KEY, "fixed") + .addParameter(THREADS_KEY, Integer.MAX_VALUE) + .addParameter(THREAD_NAME_KEY, "test") + .addParameter(CORE_THREADS_KEY, Integer.MAX_VALUE) + .addParameter(QUEUES_KEY, Integer.MAX_VALUE) + .addParameter(ALIVE_KEY, Integer.MAX_VALUE) + .addParameter(DEFAULT_KEY_PREFIX + THREADS_KEY, Integer.MAX_VALUE) + .addParameter(DEFAULT_KEY_PREFIX + THREADPOOL_KEY, "fixed") + .addParameter(DEFAULT_KEY_PREFIX + CORE_THREADS_KEY, Integer.MAX_VALUE) + .addParameter(DEFAULT_KEY_PREFIX + QUEUES_KEY, Integer.MAX_VALUE) + .addParameter(DEFAULT_KEY_PREFIX + ALIVE_KEY, Integer.MAX_VALUE) + .addParameter(DEFAULT_KEY_PREFIX + THREAD_NAME_KEY, "test") + .addParameter(APPLICATION_KEY, "provider") + .addParameter(REFERENCE_FILTER_KEY, "filter1,filter2") + .addParameter(TAG_KEY, "TTT") + .build(); URL consumerURL = new URLBuilder(DUBBO_PROTOCOL, "localhost", 55555) - .addParameter(PID_KEY, "1234") - .addParameter(THREADPOOL_KEY, "foo") - .addParameter(APPLICATION_KEY, "consumer") - .addParameter(REFERENCE_FILTER_KEY, "filter3") - .addParameter(TAG_KEY, "UUU") - .build(); + .addParameter(PID_KEY, "1234") + .addParameter(THREADPOOL_KEY, "foo") + .addParameter(APPLICATION_KEY, "consumer") + .addParameter(REFERENCE_FILTER_KEY, "filter3") + .addParameter(TAG_KEY, "UUU") + .build(); URL url = providerURLMergeProcessor.mergeUrl(providerURL, consumerURL.getParameters()); @@ -126,10 +123,12 @@ class DefaultProviderURLMergeProcessorTest { @Test void testUseProviderParams() { // present in both local and remote, but uses remote value. - URL localURL = URL.valueOf("dubbo://localhost:20880/DemoService?version=local&group=local&dubbo=local&release=local" + - "&methods=local&tag=local×tamp=local"); - URL remoteURL = URL.valueOf("dubbo://localhost:20880/DemoService?version=remote&group=remote&dubbo=remote&release=remote" + - "&methods=remote&tag=remote×tamp=remote"); + URL localURL = + URL.valueOf("dubbo://localhost:20880/DemoService?version=local&group=local&dubbo=local&release=local" + + "&methods=local&tag=local×tamp=local"); + URL remoteURL = URL.valueOf( + "dubbo://localhost:20880/DemoService?version=remote&group=remote&dubbo=remote&release=remote" + + "&methods=remote&tag=remote×tamp=remote"); URL mergedUrl = providerURLMergeProcessor.mergeUrl(remoteURL, localURL.getParameters()); Assertions.assertEquals(remoteURL.getVersion(), mergedUrl.getVersion()); @@ -141,8 +140,8 @@ class DefaultProviderURLMergeProcessorTest { Assertions.assertEquals(remoteURL.getParameter(TAG_KEY), mergedUrl.getParameter(TAG_KEY)); // present in local url but not in remote url, parameters of remote url is empty - localURL = URL.valueOf("dubbo://localhost:20880/DemoService?version=local&group=local&dubbo=local&release=local" + - "&methods=local&tag=local×tamp=local"); + localURL = URL.valueOf("dubbo://localhost:20880/DemoService?version=local&group=local&dubbo=local&release=local" + + "&methods=local&tag=local×tamp=local"); remoteURL = URL.valueOf("dubbo://localhost:20880/DemoService"); mergedUrl = providerURLMergeProcessor.mergeUrl(remoteURL, localURL.getParameters()); @@ -155,8 +154,8 @@ class DefaultProviderURLMergeProcessorTest { Assertions.assertNull(mergedUrl.getParameter(TAG_KEY)); // present in local url but not in remote url - localURL = URL.valueOf("dubbo://localhost:20880/DemoService?version=local&group=local&dubbo=local&release=local" + - "&methods=local&tag=local×tamp=local"); + localURL = URL.valueOf("dubbo://localhost:20880/DemoService?version=local&group=local&dubbo=local&release=local" + + "&methods=local&tag=local×tamp=local"); remoteURL = URL.valueOf("dubbo://localhost:20880/DemoService?key=value"); mergedUrl = providerURLMergeProcessor.mergeUrl(remoteURL, localURL.getParameters()); diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/registry/ZoneAwareClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/registry/ZoneAwareClusterInvokerTest.java index 9a20078935..6ced222f62 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/registry/ZoneAwareClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/registry/ZoneAwareClusterInvokerTest.java @@ -24,14 +24,13 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.cluster.ClusterInvoker; import org.apache.dubbo.rpc.cluster.Directory; -import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.HashMap; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.PREFERRED_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_ZONE; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_ZONE_FORCE; @@ -57,28 +56,29 @@ class ZoneAwareClusterInvokerTest { @Test void testPreferredStrategy() { - given(invocation.getParameterTypes()).willReturn(new Class[]{}); - given(invocation.getArguments()).willReturn(new Object[]{}); + given(invocation.getParameterTypes()).willReturn(new Class[] {}); + given(invocation.getArguments()).willReturn(new Object[] {}); given(invocation.getObjectAttachments()).willReturn(new HashMap<>()); firstInvoker = newUnexpectedInvoker(); thirdInvoker = newUnexpectedInvoker(); - secondInvoker = (ClusterInvoker) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{ClusterInvoker.class}, (proxy, method, args) -> { - if ("getUrl".equals(method.getName())) { - return url; - } - if ("getRegistryUrl".equals(method.getName())) { - return registryUrl.addParameter(PREFERRED_KEY, true); - } - if ("isAvailable".equals(method.getName())) { - return true; - } - if ("invoke".equals(method.getName())) { - return new AppResponse(expectedValue); - } - return null; - }); + secondInvoker = (ClusterInvoker) Proxy.newProxyInstance( + getClass().getClassLoader(), new Class[] {ClusterInvoker.class}, (proxy, method, args) -> { + if ("getUrl".equals(method.getName())) { + return url; + } + if ("getRegistryUrl".equals(method.getName())) { + return registryUrl.addParameter(PREFERRED_KEY, true); + } + if ("isAvailable".equals(method.getName())) { + return true; + } + if ("invoke".equals(method.getName())) { + return new AppResponse(expectedValue); + } + return null; + }); given(directory.list(invocation)).willReturn(new ArrayList() { { @@ -100,29 +100,30 @@ class ZoneAwareClusterInvokerTest { void testRegistryZoneStrategy() { String zoneKey = "zone"; - given(invocation.getParameterTypes()).willReturn(new Class[]{}); - given(invocation.getArguments()).willReturn(new Object[]{}); + given(invocation.getParameterTypes()).willReturn(new Class[] {}); + given(invocation.getArguments()).willReturn(new Object[] {}); given(invocation.getObjectAttachments()).willReturn(new HashMap<>()); RpcContext.getClientAttachment().setAttachment(REGISTRY_ZONE, zoneKey); firstInvoker = newUnexpectedInvoker(); thirdInvoker = newUnexpectedInvoker(); - secondInvoker = (ClusterInvoker) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{ClusterInvoker.class}, (proxy, method, args) -> { - if ("getUrl".equals(method.getName())) { - return url; - } - if ("getRegistryUrl".equals(method.getName())) { - return registryUrl.addParameter(ZONE_KEY, zoneKey); - } - if ("isAvailable".equals(method.getName())) { - return true; - } - if ("invoke".equals(method.getName())) { - return new AppResponse(expectedValue); - } - return null; - }); + secondInvoker = (ClusterInvoker) Proxy.newProxyInstance( + getClass().getClassLoader(), new Class[] {ClusterInvoker.class}, (proxy, method, args) -> { + if ("getUrl".equals(method.getName())) { + return url; + } + if ("getRegistryUrl".equals(method.getName())) { + return registryUrl.addParameter(ZONE_KEY, zoneKey); + } + if ("isAvailable".equals(method.getName())) { + return true; + } + if ("invoke".equals(method.getName())) { + return new AppResponse(expectedValue); + } + return null; + }); given(directory.list(invocation)).willReturn(new ArrayList() { { @@ -144,8 +145,8 @@ class ZoneAwareClusterInvokerTest { void testRegistryZoneForceStrategy() { String zoneKey = "zone"; - given(invocation.getParameterTypes()).willReturn(new Class[]{}); - given(invocation.getArguments()).willReturn(new Object[]{}); + given(invocation.getParameterTypes()).willReturn(new Class[] {}); + given(invocation.getArguments()).willReturn(new Object[] {}); given(invocation.getObjectAttachments()).willReturn(new HashMap<>()); RpcContext.getClientAttachment().setAttachment(REGISTRY_ZONE, zoneKey); RpcContext.getClientAttachment().setAttachment(REGISTRY_ZONE_FORCE, "true"); @@ -166,8 +167,7 @@ class ZoneAwareClusterInvokerTest { given(directory.getConsumerUrl()).willReturn(url); zoneAwareClusterInvoker = new ZoneAwareClusterInvoker<>(directory); - Assertions.assertThrows(IllegalStateException.class, - () -> zoneAwareClusterInvoker.invoke(invocation)); + Assertions.assertThrows(IllegalStateException.class, () -> zoneAwareClusterInvoker.invoke(invocation)); } @Test @@ -179,25 +179,25 @@ class ZoneAwareClusterInvokerTest { zoneAwareClusterInvoker = new ZoneAwareClusterInvoker<>(directory); - Assertions.assertThrows(RpcException.class, - () -> zoneAwareClusterInvoker.invoke(invocation)); + Assertions.assertThrows(RpcException.class, () -> zoneAwareClusterInvoker.invoke(invocation)); } private ClusterInvoker newUnexpectedInvoker() { - return (ClusterInvoker) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{ClusterInvoker.class}, (proxy, method, args) -> { - if ("getUrl".equals(method.getName())) { - return url; - } - if ("getRegistryUrl".equals(method.getName())) { - return registryUrl; - } - if ("isAvailable".equals(method.getName())) { - return true; - } - if ("invoke".equals(method.getName())) { - return new AppResponse(unexpectedValue); - } - return null; - }); + return (ClusterInvoker) Proxy.newProxyInstance( + getClass().getClassLoader(), new Class[] {ClusterInvoker.class}, (proxy, method, args) -> { + if ("getUrl".equals(method.getName())) { + return url; + } + if ("getRegistryUrl".equals(method.getName())) { + return registryUrl; + } + if ("isAvailable".equals(method.getName())) { + return true; + } + if ("invoke".equals(method.getName())) { + return new AppResponse(unexpectedValue); + } + return null; + }); } } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/AbstractClusterTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/AbstractClusterTest.java index 395620923a..beb4536325 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/AbstractClusterTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/AbstractClusterTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.support.wrapper; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.rpc.Invocation; @@ -30,13 +29,13 @@ import org.apache.dubbo.rpc.cluster.filter.FilterChainBuilder; import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REFERENCE_FILTER_KEY; import static org.mockito.Mockito.mock; @@ -51,16 +50,9 @@ class AbstractClusterTest { parameters.put(INTERFACE_KEY, DemoService.class.getName()); parameters.put("registry", "zookeeper"); parameters.put(REFERENCE_FILTER_KEY, "demo"); - ServiceConfigURL url = new ServiceConfigURL("registry", - "127.0.0.1", - 2181, - "org.apache.dubbo.registry.RegistryService", - parameters); - URL consumerUrl = new ServiceConfigURL("dubbo", - "127.0.0.1", - 20881, - DemoService.class.getName(), - parameters); + ServiceConfigURL url = new ServiceConfigURL( + "registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters); + URL consumerUrl = new ServiceConfigURL("dubbo", "127.0.0.1", 20881, DemoService.class.getName(), parameters); consumerUrl = consumerUrl.setScopeModel(ApplicationModel.defaultModel().getInternalModule()); Directory directory = mock(Directory.class); when(directory.getUrl()).thenReturn(url); @@ -68,10 +60,9 @@ class AbstractClusterTest { DemoCluster demoCluster = new DemoCluster(); Invoker invoker = demoCluster.join(directory, true); Assertions.assertTrue(invoker instanceof AbstractCluster.ClusterFilterInvoker); - Assertions.assertTrue(((AbstractCluster.ClusterFilterInvoker) invoker).getFilterInvoker() - instanceof FilterChainBuilder.ClusterCallbackRegistrationInvoker); - - + Assertions.assertTrue( + ((AbstractCluster.ClusterFilterInvoker) invoker).getFilterInvoker() + instanceof FilterChainBuilder.ClusterCallbackRegistrationInvoker); } static class DemoCluster extends AbstractCluster { @@ -102,6 +93,4 @@ class AbstractClusterTest { return null; } } - - } diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/DemoClusterFilter.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/DemoClusterFilter.java index 2cea0f4408..e17176b98b 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/DemoClusterFilter.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/DemoClusterFilter.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.support.wrapper; - import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -26,7 +25,9 @@ import org.apache.dubbo.rpc.cluster.filter.ClusterFilter; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; -@Activate(value = "demo",group = {CONSUMER}) +@Activate( + value = "demo", + group = {CONSUMER}) public class DemoClusterFilter implements ClusterFilter { @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { diff --git a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterInvokerTest.java b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterInvokerTest.java index 389aab4d4d..f04617e668 100644 --- a/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterInvokerTest.java +++ b/dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/ScopeClusterInvokerTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.support.wrapper; import org.apache.dubbo.common.URL; @@ -34,11 +33,6 @@ import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; @@ -46,6 +40,11 @@ import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.EXPORTER_LISTENER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE; @@ -60,8 +59,10 @@ class ScopeClusterInvokerTest { private final List> invokers = new ArrayList<>(); - private final Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - private final ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + private final Protocol protocol = + ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); + private final ProxyFactory proxy = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); private final List> exporters = new ArrayList<>(); @@ -88,14 +89,13 @@ class ScopeClusterInvokerTest { @Test void testScopeNull_RemoteInvoke() { URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName()); - url = url.addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + DemoService.class.getName())); + url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName())); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Invoker cluster = getClusterInvoker(url); invokers.add(cluster); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("doSomething1"); Result ret = cluster.invoke(invocation); @@ -105,23 +105,22 @@ class ScopeClusterInvokerTest { @Test void testScopeNull_LocalInvoke() { URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName()); - url = url.addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + DemoService.class.getName())); + url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName())); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); URL injvmUrl = URL.valueOf("injvm://127.0.0.1/TestService") - .addParameter(INTERFACE_KEY, DemoService.class.getName()).setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); + .addParameter(INTERFACE_KEY, DemoService.class.getName()) + .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Exporter exporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, injvmUrl)); exporters.add(exporter); - Invoker cluster = getClusterInvoker(url); invokers.add(cluster); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("doSomething2"); - invocation.setParameterTypes(new Class[]{}); + invocation.setParameterTypes(new Class[] {}); Result ret = cluster.invoke(invocation); Assertions.assertEquals("doSomething2", ret.getValue()); } @@ -129,23 +128,23 @@ class ScopeClusterInvokerTest { @Test void testScopeRemoteInvoke() { URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName()); - url = url.addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + DemoService.class.getName())); + url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName())); url = url.addParameter(SCOPE_KEY, "remote"); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); URL injvmUrl = URL.valueOf("injvm://127.0.0.1/TestService") - .addParameter(INTERFACE_KEY, DemoService.class.getName()).setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); + .addParameter(INTERFACE_KEY, DemoService.class.getName()) + .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Exporter exporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, injvmUrl)); exporters.add(exporter); Invoker cluster = getClusterInvoker(url); invokers.add(cluster); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("doSomething3"); - invocation.setParameterTypes(new Class[]{}); + invocation.setParameterTypes(new Class[] {}); Result ret = cluster.invoke(invocation); Assertions.assertEquals("doSomething3", ret.getValue()); } @@ -153,8 +152,7 @@ class ScopeClusterInvokerTest { @Test void testScopeLocalInvoke() { URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName()); - url = url.addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + DemoService.class.getName())); + url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName())); url = url.addParameter(SCOPE_KEY, SCOPE_LOCAL); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); @@ -163,21 +161,21 @@ class ScopeClusterInvokerTest { RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("doSomething4"); - invocation.setParameterTypes(new Class[]{}); + invocation.setParameterTypes(new Class[] {}); Assertions.assertFalse(cluster.isAvailable(), ""); RpcInvocation finalInvocation = invocation; Assertions.assertThrows(RpcException.class, () -> cluster.invoke(finalInvocation)); - URL injvmUrl = URL.valueOf("injvm://127.0.0.1/TestService") - .addParameter(INTERFACE_KEY, DemoService.class.getName()); - injvmUrl = injvmUrl.addParameter(EXPORTER_LISTENER_KEY, LOCAL_PROTOCOL).setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); + URL injvmUrl = + URL.valueOf("injvm://127.0.0.1/TestService").addParameter(INTERFACE_KEY, DemoService.class.getName()); + injvmUrl = injvmUrl.addParameter(EXPORTER_LISTENER_KEY, LOCAL_PROTOCOL) + .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Exporter exporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, injvmUrl)); exporters.add(exporter); - invocation = new RpcInvocation(); invocation.setMethodName("doSomething4"); - invocation.setParameterTypes(new Class[]{}); + invocation.setParameterTypes(new Class[] {}); Assertions.assertTrue(cluster.isAvailable(), ""); Result ret2 = cluster.invoke(invocation); Assertions.assertEquals("doSomething4", ret2.getValue()); @@ -186,12 +184,12 @@ class ScopeClusterInvokerTest { @Test void testInjvmRefer() { URL url = new URL(LOCAL_PROTOCOL, LOCALHOST_VALUE, 0, DemoService.class.getName()); - url = url.addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + DemoService.class.getName())); + url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName())); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); URL injvmUrl = URL.valueOf("injvm://127.0.0.1/TestService") - .addParameter(INTERFACE_KEY, DemoService.class.getName()).setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); + .addParameter(INTERFACE_KEY, DemoService.class.getName()) + .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Exporter exporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, injvmUrl)); exporters.add(exporter); @@ -200,7 +198,7 @@ class ScopeClusterInvokerTest { RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("doSomething5"); - invocation.setParameterTypes(new Class[]{}); + invocation.setParameterTypes(new Class[] {}); Assertions.assertTrue(cluster.isAvailable(), ""); Result ret = cluster.invoke(invocation); Assertions.assertEquals("doSomething5", ret.getValue()); @@ -209,13 +207,13 @@ class ScopeClusterInvokerTest { @Test void testListenUnExport() throws NoSuchFieldException, IllegalAccessException { URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName()); - url = url.addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + DemoService.class.getName())); + url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName())); url = url.addParameter(SCOPE_KEY, "local"); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); URL injvmUrl = URL.valueOf("injvm://127.0.0.1/TestService") - .addParameter(INTERFACE_KEY, DemoService.class.getName()).setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); + .addParameter(INTERFACE_KEY, DemoService.class.getName()) + .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Exporter exporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, injvmUrl)); Invoker cluster = getClusterInvoker(url); @@ -237,8 +235,7 @@ class ScopeClusterInvokerTest { @Test void testPeerInvoke() { URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName()); - url = url.addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + DemoService.class.getName())); + url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName())); Map peer = new HashMap<>(); peer.put(PEER_KEY, true); url = url.addAttributes(peer); @@ -247,39 +244,35 @@ class ScopeClusterInvokerTest { Invoker cluster = getClusterInvoker(url); invokers.add(cluster); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("doSomething6"); - invocation.setParameterTypes(new Class[]{}); + invocation.setParameterTypes(new Class[] {}); Result ret = cluster.invoke(invocation); Assertions.assertEquals("doSomething6", ret.getValue()); - } @Test void testInjvmUrlInvoke() { URL url = URL.valueOf("injvm://1.2.3.4/" + DemoService.class.getName()); - url = url.addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + DemoService.class.getName())); + url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName())); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Invoker cluster = getClusterInvoker(url); invokers.add(cluster); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("doSomething7"); - invocation.setParameterTypes(new Class[]{}); + invocation.setParameterTypes(new Class[] {}); Result ret = cluster.invoke(invocation); Assertions.assertEquals("doSomething7", ret.getValue()); - } @Test void testDynamicInvoke() { URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName()); - url = url.addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + DemoService.class.getName())); + url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName())); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Invoker cluster = getClusterInvoker(url); @@ -287,7 +280,7 @@ class ScopeClusterInvokerTest { RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("doSomething8"); - invocation.setParameterTypes(new Class[]{}); + invocation.setParameterTypes(new Class[] {}); Result ret1 = cluster.invoke(invocation); Assertions.assertEquals("doSomething8", ret1.getValue()); @@ -295,18 +288,19 @@ class ScopeClusterInvokerTest { invocation = new RpcInvocation(); invocation.setMethodName("doSomething8"); - invocation.setParameterTypes(new Class[]{}); + invocation.setParameterTypes(new Class[] {}); RpcInvocation finalInvocation = invocation; Assertions.assertThrows(RpcException.class, () -> cluster.invoke(finalInvocation)); URL injvmUrl = URL.valueOf("injvm://127.0.0.1/TestService") - .addParameter(INTERFACE_KEY, DemoService.class.getName()).setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); + .addParameter(INTERFACE_KEY, DemoService.class.getName()) + .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Exporter exporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, injvmUrl)); exporters.add(exporter); invocation = new RpcInvocation(); invocation.setMethodName("doSomething8"); - invocation.setParameterTypes(new Class[]{}); + invocation.setParameterTypes(new Class[] {}); Result ret2 = cluster.invoke(invocation); Assertions.assertEquals("doSomething8", ret2.getValue()); @@ -314,7 +308,7 @@ class ScopeClusterInvokerTest { invocation = new RpcInvocation(); invocation.setMethodName("doSomething8"); - invocation.setParameterTypes(new Class[]{}); + invocation.setParameterTypes(new Class[] {}); Result ret3 = cluster.invoke(invocation); Assertions.assertEquals("doSomething8", ret3.getValue()); } @@ -322,9 +316,8 @@ class ScopeClusterInvokerTest { @Test void testBroadcast() { URL url = URL.valueOf("remote://1.2.3.4/" + DemoService.class.getName()); - url = url.addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + DemoService.class.getName())); - url = url.addParameter("cluster","broadcast"); + url = url.addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + DemoService.class.getName())); + url = url.addParameter("cluster", "broadcast"); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Invoker cluster = getClusterInvoker(url); @@ -332,7 +325,7 @@ class ScopeClusterInvokerTest { RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("doSomething8"); - invocation.setParameterTypes(new Class[]{}); + invocation.setParameterTypes(new Class[] {}); Result ret = cluster.invoke(invocation); Assertions.assertEquals("doSomething8", ret.getValue()); } @@ -340,7 +333,8 @@ class ScopeClusterInvokerTest { private Invoker getClusterInvoker(URL url) { final URL durl = url.addParameter("proxy", "jdk"); invokers.clear(); - ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getExtension("jdk"); + ProxyFactory proxy = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getExtension("jdk"); Invoker invoker1 = proxy.getInvoker(new DemoServiceImpl(), DemoService.class, durl); invokers.add(invoker1); @@ -349,7 +343,7 @@ class ScopeClusterInvokerTest { AbstractClusterInvoker cluster = new AbstractClusterInvoker(dic) { @Override protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance) - throws RpcException { + throws RpcException { if (durl.getParameter("invoke_return_error", false)) { throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "test rpc exception"); } else { @@ -391,7 +385,6 @@ class ScopeClusterInvokerTest { @Override public String doSomething2() { return "doSomething2"; - } @Override @@ -425,5 +418,3 @@ class ScopeClusterInvokerTest { } } } - - diff --git a/dubbo-common/pom.xml b/dubbo-common/pom.xml index ce9048b28d..8f418e1a4f 100644 --- a/dubbo-common/pom.xml +++ b/dubbo-common/pom.xml @@ -1,3 +1,4 @@ + + + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + + dubbo-common + jar + ${project.artifactId} + The common module of dubbo project + + false + + + + org.slf4j + slf4j-api + provided + + + commons-logging + commons-logging + provided + - - 4.0.0 - - org.apache.dubbo - dubbo-parent - ${revision} - ../pom.xml - - dubbo-common - jar - ${project.artifactId} - The common module of dubbo project - - false - - - - org.slf4j - slf4j-api - provided - - - commons-logging - commons-logging - provided - + + log4j + log4j + provided + + + org.apache.logging.log4j + log4j-api + provided + + + org.apache.logging.log4j + log4j-core + provided + + + org.javassist + javassist + + + com.alibaba + fastjson + true + + + com.google.code.gson + gson + true + + + com.fasterxml.jackson.core + jackson-core + true + + + com.fasterxml.jackson.core + jackson-databind + true + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + true + + + com.alibaba.fastjson2 + fastjson2 + + + commons-io + commons-io + + + + javax.annotation + javax.annotation-api + - - log4j - log4j - provided - - - org.apache.logging.log4j - log4j-api - provided - - - org.apache.logging.log4j - log4j-core - provided - - - org.javassist - javassist - - - com.alibaba - fastjson - true - - - com.google.code.gson - gson - true - - - com.fasterxml.jackson.core - jackson-core - true - - - com.fasterxml.jackson.core - jackson-databind - true - - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - true - - - com.alibaba.fastjson2 - fastjson2 - - - commons-io - commons-io - - - - javax.annotation - javax.annotation-api - - - - cglib - cglib-nodep - test - - - org.slf4j - slf4j-log4j12 - test - - + + cglib + cglib-nodep + test + + + org.slf4j + slf4j-log4j12 + test + + diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/BatchExecutorQueue.java b/dubbo-common/src/main/java/org/apache/dubbo/common/BatchExecutorQueue.java index c958f56508..a8cd6a6fd3 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/BatchExecutorQueue.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/BatchExecutorQueue.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common; import java.util.LinkedList; @@ -85,12 +84,7 @@ public class BatchExecutorQueue { } } - protected void prepare(T item) { - - } - - protected void flush(T item) { - - } + protected void prepare(T item) {} + protected void flush(T item) {} } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Experimental.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Experimental.java index 746bc1b7ad..5429b9cad9 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/Experimental.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Experimental.java @@ -26,12 +26,13 @@ import java.lang.annotation.Target; */ @Retention(RetentionPolicy.CLASS) @Target({ - ElementType.ANNOTATION_TYPE, - ElementType.CONSTRUCTOR, - ElementType.FIELD, - ElementType.METHOD, - ElementType.PACKAGE, - ElementType.TYPE}) + ElementType.ANNOTATION_TYPE, + ElementType.CONSTRUCTOR, + ElementType.FIELD, + ElementType.METHOD, + ElementType.PACKAGE, + ElementType.TYPE +}) public @interface Experimental { String value(); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Extension.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Extension.java index 4e4815bc13..520184014e 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/Extension.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Extension.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common; import java.lang.annotation.Documented; @@ -64,5 +63,4 @@ public @interface Extension { */ @Deprecated String value() default ""; - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Node.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Node.java index 1bd8c74e64..68206dbf4b 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/Node.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Node.java @@ -39,5 +39,4 @@ public interface Node { * destroy. */ void destroy(); - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Parameters.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Parameters.java index 42f7bd5459..4a368b2a89 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/Parameters.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Parameters.java @@ -47,7 +47,8 @@ public class Parameters { } public Parameters(Map parameters) { - this.parameters = Collections.unmodifiableMap(parameters != null ? new HashMap<>(parameters) : new HashMap<>(0)); + this.parameters = + Collections.unmodifiableMap(parameters != null ? new HashMap<>(parameters) : new HashMap<>(0)); } private static Map toMap(String... pairs) { @@ -276,5 +277,4 @@ public class Parameters { public String toString() { return StringUtils.toQueryString(getParameters()); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/ProtocolServiceKey.java b/dubbo-common/src/main/java/org/apache/dubbo/common/ProtocolServiceKey.java index 0cc8b203d4..e4f5862c02 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/ProtocolServiceKey.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/ProtocolServiceKey.java @@ -96,7 +96,7 @@ public class ProtocolServiceKey extends ServiceKey { if (StringUtils.isNotEmpty(rule.getProtocol())) { // 4.3. if rule protocol contains ',', split and match each if (rule.getProtocol().contains(CommonConstants.COMMA_SEPARATOR)) { - String[] protocols = rule.getProtocol().split("\\" +CommonConstants.COMMA_SEPARATOR, -1); + String[] protocols = rule.getProtocol().split("\\" + CommonConstants.COMMA_SEPARATOR, -1); boolean match = false; for (String protocol : protocols) { protocol = protocol.trim(); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Resetable.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Resetable.java index 873c0be17c..2121c783da 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/Resetable.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Resetable.java @@ -27,5 +27,4 @@ public interface Resetable { * @param url */ void reset(URL url); - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/ServiceKey.java b/dubbo-common/src/main/java/org/apache/dubbo/common/ServiceKey.java index c8d8f846cc..6b906d5ede 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/ServiceKey.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/ServiceKey.java @@ -53,7 +53,9 @@ public class ServiceKey { return false; } ServiceKey that = (ServiceKey) o; - return Objects.equals(interfaceName, that.interfaceName) && Objects.equals(group, that.group) && Objects.equals(version, that.version); + return Objects.equals(interfaceName, that.interfaceName) + && Objects.equals(group, that.group) + && Objects.equals(version, that.version); } @Override @@ -66,7 +68,6 @@ public class ServiceKey { return BaseServiceMetadata.buildServiceKey(interfaceName, group, version); } - public static class Matcher { public static boolean isMatch(ServiceKey rule, ServiceKey target) { // 1. match interface (accurate match) @@ -84,7 +85,7 @@ public class ServiceKey { if (!StringUtils.isEmpty(rule.getVersion())) { // 2.3. if rule version contains ',', split and match each if (rule.getVersion().contains(CommonConstants.COMMA_SEPARATOR)) { - String[] versions = rule.getVersion().split("\\" +CommonConstants.COMMA_SEPARATOR, -1); + String[] versions = rule.getVersion().split("\\" + CommonConstants.COMMA_SEPARATOR, -1); boolean match = false; for (String version : versions) { version = version.trim(); @@ -117,7 +118,7 @@ public class ServiceKey { if (!StringUtils.isEmpty(rule.getGroup())) { // 3.3. if rule group contains ',', split and match each if (rule.getGroup().contains(CommonConstants.COMMA_SEPARATOR)) { - String[] groups = rule.getGroup().split("\\" +CommonConstants.COMMA_SEPARATOR, -1); + String[] groups = rule.getGroup().split("\\" + CommonConstants.COMMA_SEPARATOR, -1); boolean match = false; for (String group : groups) { group = group.trim(); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java b/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java index 15e2185494..28c841996c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/URL.java @@ -111,8 +111,7 @@ import static org.apache.dubbo.common.utils.StringUtils.isBlank; * @see java.net.URL * @see java.net.URI */ -public /*final**/ -class URL implements Serializable { +public /*final**/ class URL implements Serializable { private static final long serialVersionUID = -1985165475234910535L; @@ -152,7 +151,11 @@ class URL implements Serializable { this(protocol, null, null, host, port, null, (Map) null); } - public URL(String protocol, String host, int port, String[] pairs) { // varargs ... conflict with the following path argument, use array instead. + public URL( + String protocol, + String host, + int port, + String[] pairs) { // varargs ... conflict with the following path argument, use array instead. this(protocol, null, null, host, port, null, CollectionUtils.toStringMap(pairs)); } @@ -180,15 +183,15 @@ class URL implements Serializable { this(protocol, username, password, host, port, path, CollectionUtils.toStringMap(pairs)); } - public URL(String protocol, - String username, - String password, - String host, - int port, - String path, - Map parameters) { - if (StringUtils.isEmpty(username) - && StringUtils.isNotEmpty(password)) { + public URL( + String protocol, + String username, + String password, + String host, + int port, + String path, + Map parameters) { + if (StringUtils.isEmpty(username) && StringUtils.isNotEmpty(password)) { throw new IllegalArgumentException("Invalid url, password without username!"); } @@ -197,16 +200,16 @@ class URL implements Serializable { this.attributes = null; } - protected URL(String protocol, - String username, - String password, - String host, - int port, - String path, - Map parameters, - boolean modifiable) { - if (StringUtils.isEmpty(username) - && StringUtils.isNotEmpty(password)) { + protected URL( + String protocol, + String username, + String password, + String host, + int port, + String path, + Map parameters, + boolean modifiable) { + if (StringUtils.isEmpty(username) && StringUtils.isNotEmpty(password)) { throw new IllegalArgumentException("Invalid url, password without username!"); } @@ -292,8 +295,25 @@ class URL implements Serializable { } } } - return newMap.isEmpty() ? new ServiceConfigURL(url.getProtocol(), url.getUsername(), url.getPassword(), url.getHost(), url.getPort(), url.getPath(), (Map) null, url.getAttributes()) - : new ServiceConfigURL(url.getProtocol(), url.getUsername(), url.getPassword(), url.getHost(), url.getPort(), url.getPath(), newMap, url.getAttributes()); + return newMap.isEmpty() + ? new ServiceConfigURL( + url.getProtocol(), + url.getUsername(), + url.getPassword(), + url.getHost(), + url.getPort(), + url.getPath(), + (Map) null, + url.getAttributes()) + : new ServiceConfigURL( + url.getProtocol(), + url.getUsername(), + url.getPassword(), + url.getHost(), + url.getPort(), + url.getPath(), + newMap, + url.getAttributes()); } public static String encode(String value) { @@ -357,7 +377,8 @@ class URL implements Serializable { public URL setUsername(String username) { if (urlAddress == null) { - return new ServiceConfigURL(getProtocol(), getHost(), getPort(), getPath(), getParameters()).setUsername(username); + return new ServiceConfigURL(getProtocol(), getHost(), getPort(), getPath(), getParameters()) + .setUsername(username); } else { URLAddress newURLAddress = urlAddress.setUsername(username); return returnURL(newURLAddress); @@ -370,7 +391,8 @@ class URL implements Serializable { public URL setPassword(String password) { if (urlAddress == null) { - return new ServiceConfigURL(getProtocol(), getHost(), getPort(), getPath(), getParameters()).setPassword(password); + return new ServiceConfigURL(getProtocol(), getHost(), getPort(), getPath(), getParameters()) + .setPassword(password); } else { URLAddress newURLAddress = urlAddress.setPassword(password); return returnURL(newURLAddress); @@ -439,7 +461,6 @@ class URL implements Serializable { } } - public int getPort() { return urlAddress == null ? 0 : urlAddress.getPort(); } @@ -625,7 +646,10 @@ class URL implements Serializable { String value = getParameter(key); T result = null; if (!isBlank(value)) { - result = getOrDefaultFrameworkModel().getBeanFactory().getBean(ConverterUtil.class).convertIfPossible(value, valueType); + result = getOrDefaultFrameworkModel() + .getBeanFactory() + .getBean(ConverterUtil.class) + .convertIfPossible(value, valueType); } if (result == null) { result = defaultValue; @@ -665,8 +689,6 @@ class URL implements Serializable { return (ServiceModel) getAttribute(CommonConstants.SERVICE_MODEL); } - - public URL getUrlParameter(String key) { String value = getParameterAndDecoded(key); if (StringUtils.isEmpty(value)) { @@ -1155,7 +1177,8 @@ class URL implements Serializable { } public String toIdentityString(String... parameters) { - return buildString(true, false, parameters); // only return identity message, see the method "equals" and "hashCode" + return buildString( + true, false, parameters); // only return identity message, see the method "equals" and "hashCode" } public String toFullString() { @@ -1181,8 +1204,7 @@ class URL implements Serializable { List includes = (ArrayUtils.isEmpty(parameters) ? null : Arrays.asList(parameters)); boolean first = true; for (Map.Entry entry : new TreeMap<>(getParameters()).entrySet()) { - if (StringUtils.isNotEmpty(entry.getKey()) - && (includes == null || includes.contains(entry.getKey()))) { + if (StringUtils.isNotEmpty(entry.getKey()) && (includes == null || includes.contains(entry.getKey()))) { if (first) { if (concat) { buf.append('?'); @@ -1203,7 +1225,8 @@ class URL implements Serializable { return buildString(appendUser, appendParameter, false, false, parameters); } - private String buildString(boolean appendUser, boolean appendParameter, boolean useIP, boolean useService, String... parameters) { + private String buildString( + boolean appendUser, boolean appendParameter, boolean useIP, boolean useService, String... parameters) { StringBuilder buf = new StringBuilder(); if (StringUtils.isNotEmpty(getProtocol())) { buf.append(getProtocol()); @@ -1310,8 +1333,7 @@ class URL implements Serializable { if (StringUtils.isEmpty(getVersion())) { return getServiceInterface(); } - return getServiceInterface() + - COLON_SEPARATOR + getVersion(); + return getServiceInterface() + COLON_SEPARATOR + getVersion(); } /** @@ -1485,10 +1507,12 @@ class URL implements Serializable { return false; } URL other = (URL) obj; - return Objects.equals(this.getUrlAddress(), other.getUrlAddress()) && Objects.equals(this.getUrlParam(), other.getUrlParam()); + return Objects.equals(this.getUrlAddress(), other.getUrlAddress()) + && Objects.equals(this.getUrlParam(), other.getUrlParam()); } - public static void putMethodParameter(String method, String key, String value, Map> methodParameters) { + public static void putMethodParameter( + String method, String key, String value, Map> methodParameters) { Map subParameter = methodParameters.computeIfAbsent(method, k -> new HashMap<>()); subParameter.put(key, value); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/URLBuilder.java b/dubbo-common/src/main/java/org/apache/dubbo/common/URLBuilder.java index fba84657ab..e5c18bdaaf 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/URLBuilder.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/URLBuilder.java @@ -85,24 +85,26 @@ public final class URLBuilder extends ServiceConfigURL { this(protocol, null, null, host, port, path, parameters); } - public URLBuilder(String protocol, - String username, - String password, - String host, - int port, - String path, - Map parameters) { + public URLBuilder( + String protocol, + String username, + String password, + String host, + int port, + String path, + Map parameters) { this(protocol, username, password, host, port, path, parameters, null); } - public URLBuilder(String protocol, - String username, - String password, - String host, - int port, - String path, - Map parameters, - Map attributes) { + public URLBuilder( + String protocol, + String username, + String password, + String host, + int port, + String path, + Map parameters, + Map attributes) { this.protocol = protocol; this.username = username; this.password = password; @@ -122,15 +124,7 @@ public final class URLBuilder extends ServiceConfigURL { String path = url.getPath(); Map parameters = new HashMap<>(url.getParameters()); Map attributes = new HashMap<>(url.getAttributes()); - return new URLBuilder( - protocol, - username, - password, - host, - port, - path, - parameters, - attributes); + return new URLBuilder(protocol, username, password, host, port, path, parameters, attributes); } public ServiceConfigURL build() { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/URLStrParser.java b/dubbo-common/src/main/java/org/apache/dubbo/common/URLStrParser.java index d4b5143f7c..3b1761e2ff 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/URLStrParser.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/URLStrParser.java @@ -38,10 +38,9 @@ public final class URLStrParser { private static final ThreadLocal DECODE_TEMP_BUF = ThreadLocal.withInitial(() -> new TempBuf(1024)); private URLStrParser() { - //empty + // empty } - /** * @param decodedURLStr : after {@link URL#decode} string * decodedURLStr format: protocol://username:password@host:port/path?k1=v1&k2=v2 @@ -140,7 +139,7 @@ public final class URLStrParser { int pwdEndIdx = lastIndexOf(decodedBody, '@', starIdx, endIdx); if (pwdEndIdx > 0) { int passwordStartIdx = indexOf(decodedBody, ':', starIdx, pwdEndIdx); - if (passwordStartIdx != -1) {//tolerate incomplete user pwd input, like '1234@' + if (passwordStartIdx != -1) { // tolerate incomplete user pwd input, like '1234@' username = decodedBody.substring(starIdx, passwordStartIdx); password = decodedBody.substring(passwordStartIdx + 1, pwdEndIdx); } else { @@ -177,7 +176,7 @@ public final class URLStrParser { public static String[] parseRawURLToArrays(String rawURLStr, int pathEndIdx) { String[] parts = new String[2]; - int paramStartIdx = pathEndIdx + 3;//skip ENCODED_QUESTION_MARK + int paramStartIdx = pathEndIdx + 3; // skip ENCODED_QUESTION_MARK if (pathEndIdx == -1) { pathEndIdx = rawURLStr.indexOf('?'); if (pathEndIdx == -1) { @@ -191,7 +190,7 @@ public final class URLStrParser { parts[0] = rawURLStr.substring(0, pathEndIdx); parts[1] = rawURLStr.substring(paramStartIdx); } else { - parts = new String[]{rawURLStr}; + parts = new String[] {rawURLStr}; } return parts; } @@ -210,14 +209,14 @@ public final class URLStrParser { */ public static URL parseEncodedStr(String encodedURLStr) { Map parameters = null; - int pathEndIdx = encodedURLStr.toUpperCase().indexOf("%3F");// '?' + int pathEndIdx = encodedURLStr.toUpperCase().indexOf("%3F"); // '?' if (pathEndIdx >= 0) { parameters = parseEncodedParams(encodedURLStr, pathEndIdx + 3); } else { pathEndIdx = encodedURLStr.length(); } - //decodedBody format: [protocol://][username:password@][host:port]/[path] + // decodedBody format: [protocol://][username:password@][host:port]/[path] String decodedBody = decodeComponent(encodedURLStr, 0, pathEndIdx, false, DECODE_TEMP_BUF.get()); return parseURLBody(encodedURLStr, decodedBody, parameters); } @@ -264,8 +263,14 @@ public final class URLStrParser { return params; } - private static boolean addParam(String str, boolean isEncoded, int nameStart, int valueStart, int valueEnd, Map params, - TempBuf tempBuf) { + private static boolean addParam( + String str, + boolean isEncoded, + int nameStart, + int valueStart, + int valueEnd, + Map params, + TempBuf tempBuf) { if (nameStart >= valueEnd) { return false; } @@ -282,7 +287,7 @@ public final class URLStrParser { } else { value = decodeComponent(str, valueStart, valueEnd, false, tempBuf); } - URLItemCache.putParams(params,name, value); + URLItemCache.putParams(params, name, value); // compatible with lower versions registering "default." keys if (name.startsWith(DEFAULT_KEY_PREFIX)) { params.putIfAbsent(name.substring(DEFAULT_KEY_PREFIX.length()), value); @@ -332,8 +337,8 @@ public final class URLStrParser { return decodeUtf8Component(s, firstEscaped, toExcluded, isPath, buf, charBuf, charBufIdx); } - private static String decodeUtf8Component(String str, int firstEscaped, int toExcluded, boolean isPath, byte[] buf, - char[] charBuf, int charBufIdx) { + private static String decodeUtf8Component( + String str, int firstEscaped, int toExcluded, boolean isPath, byte[] buf, char[] charBuf, int charBufIdx) { int bufIdx; for (int i = firstEscaped; i < toExcluded; i++) { char c = str.charAt(i); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/Version.java b/dubbo-common/src/main/java/org/apache/dubbo/common/Version.java index ec317703a5..a33be42ddc 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/Version.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/Version.java @@ -58,6 +58,7 @@ public final class Version { * performance than string. */ public static final int LOWEST_VERSION_FOR_RESPONSE_ATTACHMENT = 2000200; // 2.0.2 + public static final int HIGHEST_PROTOCOL_VERSION = 2009900; // 2.0.99 private static final Map VERSION2INT = new HashMap(); @@ -67,7 +68,12 @@ public final class Version { tryLoadVersionFromResource(); checkDuplicate(); } catch (Throwable e) { - logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "continue the old logic, ignore exception " + e.getMessage(), e); + logger.warn( + COMMON_UNEXPECTED_EXCEPTION, + "", + "", + "continue the old logic, ignore exception " + e.getMessage(), + e); } if (StringUtils.isEmpty(VERSION)) { VERSION = getVersion(Version.class, ""); @@ -81,7 +87,8 @@ public final class Version { Enumeration configLoader = Version.class.getClassLoader().getResources("META-INF/versions/dubbo-common"); if (configLoader.hasMoreElements()) { URL url = configLoader.nextElement(); - try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) { + try (BufferedReader reader = + new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { if (line.startsWith("revision=")) { @@ -94,8 +101,7 @@ public final class Version { } } - private Version() { - } + private Version() {} public static String getProtocolVersion() { return DEFAULT_DUBBO_PROTOCOL_VERSION; @@ -169,9 +175,13 @@ public final class Version { v = v * 100; } } catch (Exception e) { - logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "Please make sure your version value has the right format: " + - "\n 1. only contains digital number: 2.0.0; \n 2. with string suffix: 2.6.7-stable. " + - "\nIf you are using Dubbo before v2.6.2, the version value is the same with the jar version."); + logger.warn( + COMMON_UNEXPECTED_EXCEPTION, + "", + "", + "Please make sure your version value has the right format: " + + "\n 1. only contains digital number: 2.0.0; \n 2. with string suffix: 2.6.7-stable. " + + "\nIf you are using Dubbo before v2.6.2, the version value is the same with the jar version."); v = LEGACY_DUBBO_PROTOCOL_VERSION; } VERSION2INT.put(version, v); @@ -223,13 +233,15 @@ public final class Version { // guess version from jar file name if nothing's found from MANIFEST.MF CodeSource codeSource = cls.getProtectionDomain().getCodeSource(); if (codeSource == null) { - logger.info("No codeSource for class " + cls.getName() + " when getVersion, use default version " + defaultVersion); + logger.info("No codeSource for class " + cls.getName() + " when getVersion, use default version " + + defaultVersion); return defaultVersion; } URL location = codeSource.getLocation(); if (location == null) { - logger.info("No location for class " + cls.getName() + " when getVersion, use default version " + defaultVersion); + logger.info("No location for class " + cls.getName() + " when getVersion, use default version " + + defaultVersion); return defaultVersion; } String file = location.getFile(); @@ -241,7 +253,12 @@ public final class Version { return StringUtils.isEmpty(version) ? defaultVersion : version; } catch (Throwable e) { // return default version when any exception is thrown - logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", "return default version, ignore exception " + e.getMessage(), e); + logger.error( + COMMON_UNEXPECTED_EXCEPTION, + "", + "", + "return default version, ignore exception " + e.getMessage(), + e); return defaultVersion; } } @@ -294,10 +311,12 @@ public final class Version { } private static void checkArtifact(String artifactId) throws IOException { - Enumeration artifactEnumeration = Version.class.getClassLoader().getResources("META-INF/versions/" + artifactId); + Enumeration artifactEnumeration = + Version.class.getClassLoader().getResources("META-INF/versions/" + artifactId); while (artifactEnumeration.hasMoreElements()) { URL url = artifactEnumeration.nextElement(); - try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) { + try (BufferedReader reader = + new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { if (line.startsWith("#")) { @@ -316,23 +335,25 @@ public final class Version { private static void checkVersion(String artifactId, URL url, String key, String value) { if ("revision".equals(key) && !value.equals(VERSION)) { - String error = "Inconsistent version " + value + " found in " + artifactId + " from " + url.getPath() + ", " + - "expected dubbo-common version is " + VERSION; + String error = "Inconsistent version " + value + " found in " + artifactId + " from " + url.getPath() + ", " + + "expected dubbo-common version is " + VERSION; logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", error); } if ("git.commit.id".equals(key) && !value.equals(LATEST_COMMIT_ID)) { - String error = "Inconsistent git build commit id " + value + " found in " + artifactId + " from " + url.getPath() + ", " + - "expected dubbo-common version is " + LATEST_COMMIT_ID; + String error = "Inconsistent git build commit id " + value + " found in " + artifactId + " from " + + url.getPath() + ", " + "expected dubbo-common version is " + LATEST_COMMIT_ID; logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", error); } } private static Set loadArtifactIds() throws IOException { - Enumeration artifactsEnumeration = Version.class.getClassLoader().getResources("META-INF/versions/.artifacts"); + Enumeration artifactsEnumeration = + Version.class.getClassLoader().getResources("META-INF/versions/.artifacts"); Set artifactIds = new HashSet<>(); while (artifactsEnumeration.hasMoreElements()) { URL url = artifactsEnumeration.nextElement(); - try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) { + try (BufferedReader reader = + new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { if (line.startsWith("#")) { @@ -347,5 +368,4 @@ public final class Version { } return artifactIds; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/aot/NativeDetector.java b/dubbo-common/src/main/java/org/apache/dubbo/common/aot/NativeDetector.java index df8bec0fab..657cfb6ee1 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/aot/NativeDetector.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/aot/NativeDetector.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.aot; - public abstract class NativeDetector { /** @@ -30,5 +29,4 @@ public abstract class NativeDetector { public static boolean inNativeImage() { return IMAGE_CODE; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/beans/ScopeBeanExtensionInjector.java b/dubbo-common/src/main/java/org/apache/dubbo/common/beans/ScopeBeanExtensionInjector.java index 570e9fdb92..e55b5e46f7 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/beans/ScopeBeanExtensionInjector.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/beans/ScopeBeanExtensionInjector.java @@ -25,7 +25,7 @@ import org.apache.dubbo.rpc.model.ScopeModelAware; * Inject scope bean to SPI extension instance */ public class ScopeBeanExtensionInjector implements ExtensionInjector, ScopeModelAware { - + private ScopeBeanFactory beanFactory; @Override diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/beans/factory/ScopeBeanFactory.java b/dubbo-common/src/main/java/org/apache/dubbo/common/beans/factory/ScopeBeanFactory.java index 8d2647135c..0da12b3893 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/beans/factory/ScopeBeanFactory.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/beans/factory/ScopeBeanFactory.java @@ -86,7 +86,8 @@ public class ScopeBeanFactory { checkDestroyed(); T instance = getBean(name, clazz); if (instance != null) { - throw new ScopeBeanException("already exists bean with same name and type, name=" + name + ", type=" + clazz.getName()); + throw new ScopeBeanException( + "already exists bean with same name and type, name=" + name + ", type=" + clazz.getName()); } try { instance = instantiationStrategy.instantiate(clazz); @@ -140,7 +141,8 @@ public class ScopeBeanFactory { return getOrRegisterBean(null, type, mappingFunction); } - public T getOrRegisterBean(String name, Class type, Function, ? extends T> mappingFunction) { + public T getOrRegisterBean( + String name, Class type, Function, ? extends T> mappingFunction) { T bean = getBean(name, type); if (bean == null) { // lock by type @@ -165,14 +167,16 @@ public class ScopeBeanFactory { processor.postProcessAfterInitialization(bean, name); } } catch (Exception e) { - throw new ScopeBeanException("register bean failed! name=" + name + ", type=" + bean.getClass().getName(), e); + throw new ScopeBeanException( + "register bean failed! name=" + name + ", type=" + + bean.getClass().getName(), + e); } } private boolean containsBean(String name, Object bean) { for (BeanInfo beanInfo : registeredBeanInfos) { - if (beanInfo.instance == bean && - (name == null || StringUtils.isEquals(name, beanInfo.name))) { + if (beanInfo.instance == bean && (name == null || StringUtils.isEquals(name, beanInfo.name))) { return true; } } @@ -180,12 +184,16 @@ public class ScopeBeanFactory { } private int getNextId(Class beanClass) { - return ConcurrentHashMapUtils.computeIfAbsent(beanNameIdCounterMap, beanClass, key -> new AtomicInteger()).incrementAndGet(); + return ConcurrentHashMapUtils.computeIfAbsent(beanNameIdCounterMap, beanClass, key -> new AtomicInteger()) + .incrementAndGet(); } @SuppressWarnings("unchecked") public List getBeansOfType(Class type) { - List currentBeans = (List) registeredBeanInfos.stream().filter(beanInfo -> type.isInstance(beanInfo.instance)).map(beanInfo -> beanInfo.instance).collect(Collectors.toList()); + List currentBeans = (List) registeredBeanInfos.stream() + .filter(beanInfo -> type.isInstance(beanInfo.instance)) + .map(beanInfo -> beanInfo.instance) + .collect(Collectors.toList()); if (parent != null) { currentBeans.addAll(parent.getBeansOfType(type)); } @@ -238,8 +246,10 @@ public class ScopeBeanFactory { if (candidates.size() == 1) { return (T) candidates.get(0).instance; } else if (candidates.size() > 1) { - List candidateBeanNames = candidates.stream().map(beanInfo -> beanInfo.name).collect(Collectors.toList()); - throw new ScopeBeanException("expected single matching bean but found " + candidates.size() + " candidates for type [" + type.getName() + "]: " + candidateBeanNames); + List candidateBeanNames = + candidates.stream().map(beanInfo -> beanInfo.name).collect(Collectors.toList()); + throw new ScopeBeanException("expected single matching bean but found " + candidates.size() + + " candidates for type [" + type.getName() + "]: " + candidateBeanNames); } } else if (firstCandidate != null) { return (T) firstCandidate.instance; @@ -255,7 +265,13 @@ public class ScopeBeanFactory { Disposable beanInstance = (Disposable) beanInfo.instance; beanInstance.destroy(); } catch (Throwable e) { - LOGGER.error(CONFIG_FAILED_DESTROY_INVOKER, "", "", "An error occurred when destroy bean [name=" + beanInfo.name + ", bean=" + beanInfo.instance + "]: " + e, e); + LOGGER.error( + CONFIG_FAILED_DESTROY_INVOKER, + "", + "", + "An error occurred when destroy bean [name=" + beanInfo.name + ", bean=" + + beanInfo.instance + "]: " + e, + e); } } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/beans/support/InstantiationStrategy.java b/dubbo-common/src/main/java/org/apache/dubbo/common/beans/support/InstantiationStrategy.java index 9d73843279..980b3ee209 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/beans/support/InstantiationStrategy.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/beans/support/InstantiationStrategy.java @@ -74,9 +74,9 @@ public class InstantiationStrategy { Constructor targetConstructor; if (matchedConstructors.size() > 1) { - throw new IllegalArgumentException("Expect only one but found " + - matchedConstructors.size() + " matched constructors for type: " + type.getName() + - ", matched constructors: " + matchedConstructors); + throw new IllegalArgumentException("Expect only one but found " + matchedConstructors.size() + + " matched constructors for type: " + type.getName() + ", matched constructors: " + + matchedConstructors); } else if (matchedConstructors.size() == 1) { targetConstructor = matchedConstructors.get(0); } else if (defaultConstructor != null) { @@ -122,5 +122,4 @@ public class InstantiationStrategy { } return null; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/beanutil/JavaBeanAccessor.java b/dubbo-common/src/main/java/org/apache/dubbo/common/beanutil/JavaBeanAccessor.java index 7160de265f..ab5bcfa438 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/beanutil/JavaBeanAccessor.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/beanutil/JavaBeanAccessor.java @@ -38,5 +38,4 @@ public enum JavaBeanAccessor { public static boolean isAccessByField(JavaBeanAccessor accessor) { return FIELD.equals(accessor) || ALL.equals(accessor); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/beanutil/JavaBeanDescriptor.java b/dubbo-common/src/main/java/org/apache/dubbo/common/beanutil/JavaBeanDescriptor.java index d572720fc1..e39150fc3c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/beanutil/JavaBeanDescriptor.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/beanutil/JavaBeanDescriptor.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.beanutil; import java.io.Serializable; @@ -35,6 +34,7 @@ public final class JavaBeanDescriptor implements Serializable, Iterable cache) { + private static JavaBeanDescriptor createDescriptorIfAbsent( + Object obj, JavaBeanAccessor accessor, IdentityHashMap cache) { if (cache.containsKey(obj)) { return cache.get(obj); } @@ -121,8 +120,11 @@ public final class JavaBeanSerializeUtil { return result; } - private static void serializeInternal(JavaBeanDescriptor descriptor, Object obj, JavaBeanAccessor accessor, - IdentityHashMap cache) { + private static void serializeInternal( + JavaBeanDescriptor descriptor, + Object obj, + JavaBeanAccessor accessor, + IdentityHashMap cache) { if (obj == null || descriptor == null) { return; } @@ -161,7 +163,7 @@ public final class JavaBeanSerializeUtil { Object keyDescriptor = key == null ? null : createDescriptorIfAbsent(key, accessor, cache); Object valueDescriptor = value == null ? null : createDescriptorIfAbsent(value, accessor, cache); descriptor.setProperty(keyDescriptor, valueDescriptor); - });// ~ end of loop map + }); // ~ end of loop map } else { if (JavaBeanAccessor.isAccessByMethod(accessor)) { Map methods = ReflectUtils.getBeanPropertyReadMethods(obj.getClass()); @@ -196,15 +198,11 @@ public final class JavaBeanSerializeUtil { } } // ~ end of loop field map } // ~ end of if (JavaBeanAccessor.isAccessByField(accessor)) - } // ~ end of else - } // ~ end of method serializeInternal public static Object deserialize(JavaBeanDescriptor beanDescriptor) { - return deserialize( - beanDescriptor, - Thread.currentThread().getContextClassLoader()); + return deserialize(beanDescriptor, Thread.currentThread().getContextClassLoader()); } public static Object deserialize(JavaBeanDescriptor beanDescriptor, ClassLoader loader) { @@ -217,8 +215,11 @@ public final class JavaBeanSerializeUtil { return result; } - private static void deserializeInternal(Object result, JavaBeanDescriptor beanDescriptor, ClassLoader loader, - IdentityHashMap cache) { + private static void deserializeInternal( + Object result, + JavaBeanDescriptor beanDescriptor, + ClassLoader loader, + IdentityHashMap cache) { if (beanDescriptor.isEnumType() || beanDescriptor.isClassType() || beanDescriptor.isPrimitiveType()) { return; } @@ -299,9 +300,8 @@ public final class JavaBeanSerializeUtil { } } } else { - throw new IllegalArgumentException("Unsupported type " + - beanDescriptor.getClassName() + - ":" + beanDescriptor.getType()); + throw new IllegalArgumentException( + "Unsupported type " + beanDescriptor.getClassName() + ":" + beanDescriptor.getType()); } } @@ -312,8 +312,7 @@ public final class JavaBeanSerializeUtil { method = cls.getMethod(name, valueCls); } catch (NoSuchMethodException e) { for (Method m : cls.getMethods()) { - if (ReflectUtils.isBeanPropertyWriteMethod(m) - && m.getName().equals(name)) { + if (ReflectUtils.isBeanPropertyWriteMethod(m) && m.getName().equals(name)) { method = m; } } @@ -387,8 +386,8 @@ public final class JavaBeanSerializeUtil { return null; } - private static Object instantiateForDeserialize(JavaBeanDescriptor beanDescriptor, ClassLoader loader, - IdentityHashMap cache) { + private static Object instantiateForDeserialize( + JavaBeanDescriptor beanDescriptor, ClassLoader loader, IdentityHashMap cache) { if (cache.containsKey(beanDescriptor)) { return cache.get(beanDescriptor); } @@ -473,13 +472,10 @@ public final class JavaBeanSerializeUtil { } private static boolean isReferenceType(String type) { - return type != null - && type.startsWith(REFERENCE_TYPE_PREFIX) - && type.endsWith(REFERENCE_TYPE_SUFFIX); + return type != null && type.startsWith(REFERENCE_TYPE_PREFIX) && type.endsWith(REFERENCE_TYPE_SUFFIX); } private static Method getEnumValueOfMethod(Class cl) throws NoSuchMethodException { return cl.getMethod("valueOf", Class.class, String.class); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/ClassGenerator.java b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/ClassGenerator.java index f6a12df2ef..95ee995c55 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/ClassGenerator.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/ClassGenerator.java @@ -20,17 +20,6 @@ import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; -import javassist.CannotCompileException; -import javassist.ClassPool; -import javassist.CtClass; -import javassist.CtConstructor; -import javassist.CtField; -import javassist.CtMethod; -import javassist.CtNewConstructor; -import javassist.CtNewMethod; -import javassist.LoaderClassPath; -import javassist.NotFoundException; - import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; @@ -43,6 +32,16 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; +import javassist.CannotCompileException; +import javassist.ClassPool; +import javassist.CtClass; +import javassist.CtConstructor; +import javassist.CtField; +import javassist.CtMethod; +import javassist.CtNewConstructor; +import javassist.CtNewMethod; +import javassist.LoaderClassPath; +import javassist.NotFoundException; /** * ClassGenerator @@ -51,7 +50,7 @@ public final class ClassGenerator { private static final AtomicLong CLASS_NAME_COUNTER = new AtomicLong(0); private static final String SIMPLE_NAME_TAG = ""; - private static final Map POOL_MAP = new ConcurrentHashMap<>(); //ClassLoader - ClassPool + private static final Map POOL_MAP = new ConcurrentHashMap<>(); // ClassLoader - ClassPool private ClassPool mPool; private CtClass mCtc; private String mClassName; @@ -65,8 +64,7 @@ public final class ClassGenerator { private Map> mCopyConstructors; // private boolean mDefaultConstructor = false; - private ClassGenerator() { - } + private ClassGenerator() {} private ClassGenerator(ClassLoader classLoader, ClassPool pool) { mClassLoader = classLoader; @@ -74,7 +72,9 @@ public final class ClassGenerator { } public static ClassGenerator newInstance() { - return new ClassGenerator(Thread.currentThread().getContextClassLoader(), getClassPool(Thread.currentThread().getContextClassLoader())); + return new ClassGenerator( + Thread.currentThread().getContextClassLoader(), + getClassPool(Thread.currentThread().getContextClassLoader())); } public static ClassGenerator newInstance(ClassLoader loader) { @@ -192,10 +192,13 @@ public final class ClassGenerator { return addMethod(name, mod, rt, pts, null, body); } - public ClassGenerator addMethod(String name, int mod, Class rt, Class[] pts, Class[] ets, - String body) { + public ClassGenerator addMethod(String name, int mod, Class rt, Class[] pts, Class[] ets, String body) { StringBuilder sb = new StringBuilder(); - sb.append(modifier(mod)).append(' ').append(ReflectUtils.getName(rt)).append(' ').append(name); + sb.append(modifier(mod)) + .append(' ') + .append(ReflectUtils.getName(rt)) + .append(' ') + .append(name); sb.append('('); if (ArrayUtils.isNotEmpty(pts)) { for (int i = 0; i < pts.length; i++) { @@ -296,9 +299,7 @@ public final class ClassGenerator { * class belongs to. It is used to load the class. */ public Class toClass(Class neighbor) { - return toClass(neighbor, - mClassLoader, - getClass().getProtectionDomain()); + return toClass(neighbor, mClassLoader, getClass().getProtectionDomain()); } public Class toClass(Class neighborClass, ClassLoader loader, ProtectionDomain pd) { @@ -310,7 +311,9 @@ public final class ClassGenerator { CtClass ctcs = mSuperClass == null ? null : mPool.get(mSuperClass); if (mClassName == null) { mClassName = (mSuperClass == null || javassist.Modifier.isPublic(ctcs.getModifiers()) - ? ClassGenerator.class.getName() : mSuperClass + "$sc") + id; + ? ClassGenerator.class.getName() + : mSuperClass + "$sc") + + id; } mCtc = mPool.makeClass(mClassName); if (mSuperClass != null) { @@ -330,8 +333,11 @@ public final class ClassGenerator { if (mMethods != null) { for (String code : mMethods) { if (code.charAt(0) == ':') { - mCtc.addMethod(CtNewMethod.copy(getCtMethod(mCopyMethods.get(code.substring(1))), - code.substring(1, code.indexOf('(')), mCtc, null)); + mCtc.addMethod(CtNewMethod.copy( + getCtMethod(mCopyMethods.get(code.substring(1))), + code.substring(1, code.indexOf('(')), + mCtc, + null)); } else { mCtc.addMethod(CtNewMethod.make(code, mCtc)); } @@ -343,8 +349,8 @@ public final class ClassGenerator { if (mConstructors != null) { for (String code : mConstructors) { if (code.charAt(0) == ':') { - mCtc.addConstructor(CtNewConstructor - .copy(getCtConstructor(mCopyConstructors.get(code.substring(1))), mCtc, null)); + mCtc.addConstructor(CtNewConstructor.copy( + getCtConstructor(mCopyConstructors.get(code.substring(1))), mCtc, null)); } else { String[] sn = mCtc.getSimpleName().split("\\$+"); // inner class name include $. mCtc.addConstructor( @@ -397,15 +403,12 @@ public final class ClassGenerator { } private CtMethod getCtMethod(Method m) throws NotFoundException { - return getCtClass(m.getDeclaringClass()) - .getMethod(m.getName(), ReflectUtils.getDescWithoutMethodName(m)); + return getCtClass(m.getDeclaringClass()).getMethod(m.getName(), ReflectUtils.getDescWithoutMethodName(m)); } private CtConstructor getCtConstructor(Constructor c) throws NotFoundException { return getCtClass(c.getDeclaringClass()).getConstructor(ReflectUtils.getDesc(c)); } - public static interface DC { - - } // dynamic class tag interface. + public static interface DC {} // dynamic class tag interface. } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/DubboLoaderClassPath.java b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/DubboLoaderClassPath.java index f0c5b377f2..1f3252bceb 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/DubboLoaderClassPath.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/DubboLoaderClassPath.java @@ -16,11 +16,10 @@ */ package org.apache.dubbo.common.bytecode; -import javassist.LoaderClassPath; -import javassist.NotFoundException; - import java.io.InputStream; import java.net.URL; +import javassist.LoaderClassPath; +import javassist.NotFoundException; /** * Ensure javassist will load Dubbo's class from Dubbo's classLoader @@ -32,7 +31,9 @@ public class DubboLoaderClassPath extends LoaderClassPath { @Override public InputStream openClassfile(String classname) throws NotFoundException { - if (!classname.startsWith("org.apache.dubbo") && !classname.startsWith("grpc.health") && !classname.startsWith("com.google")) { + if (!classname.startsWith("org.apache.dubbo") + && !classname.startsWith("grpc.health") + && !classname.startsWith("com.google")) { return null; } return super.openClassfile(classname); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Mixin.java b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Mixin.java index 12293d1976..81cadc0d76 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Mixin.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Mixin.java @@ -32,8 +32,7 @@ public abstract class Mixin { private static final String PACKAGE_NAME = Mixin.class.getPackage().getName(); private static final AtomicLong MIXIN_CLASS_COUNTER = new AtomicLong(0); - protected Mixin() { - } + protected Mixin() {} /** * mixin interface and delegates. @@ -44,7 +43,7 @@ public abstract class Mixin { * @return Mixin instance. */ public static Mixin mixin(Class[] ics, Class dc) { - return mixin(ics, new Class[]{dc}); + return mixin(ics, new Class[] {dc}); } /** @@ -57,7 +56,7 @@ public abstract class Mixin { * @return Mixin instance. */ public static Mixin mixin(Class[] ics, Class dc, ClassLoader cl) { - return mixin(ics, new Class[]{dc}, cl); + return mixin(ics, new Class[] {dc}, cl); } /** @@ -106,12 +105,18 @@ public abstract class Mixin { ccp.addField("private " + dcs[i].getName() + " d" + i + ";"); - code.append('d').append(i).append(" = (").append(dcs[i].getName()).append(")$1[").append(i).append("];\n"); + code.append('d') + .append(i) + .append(" = (") + .append(dcs[i].getName()) + .append(")$1[") + .append(i) + .append("];\n"); if (MixinAware.class.isAssignableFrom(dcs[i])) { code.append('d').append(i).append(".setMixinInstance(this);\n"); } } - ccp.addConstructor(Modifier.PUBLIC, new Class[]{Object[].class}, code.toString()); + ccp.addConstructor(Modifier.PUBLIC, new Class[] {Object[].class}, code.toString()); Class neighbor = null; // impl methods. @@ -150,10 +155,20 @@ public abstract class Mixin { Class rt = method.getReturnType(); String mn = method.getName(); if (Void.TYPE.equals(rt)) { - ccp.addMethod(mn, method.getModifiers(), rt, method.getParameterTypes(), method.getExceptionTypes(), + ccp.addMethod( + mn, + method.getModifiers(), + rt, + method.getParameterTypes(), + method.getExceptionTypes(), "d" + ix + "." + mn + "($$);"); } else { - ccp.addMethod(mn, method.getModifiers(), rt, method.getParameterTypes(), method.getExceptionTypes(), + ccp.addMethod( + mn, + method.getModifiers(), + rt, + method.getParameterTypes(), + method.getExceptionTypes(), "return ($r)d" + ix + "." + mn + "($$);"); } } @@ -222,7 +237,7 @@ public abstract class Mixin { * @param ds delegates instance. * @return instance. */ - abstract public Object newInstance(Object[] ds); + public abstract Object newInstance(Object[] ds); public static interface MixinAware { void setMixinInstance(Object instance); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/NoSuchMethodException.java b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/NoSuchMethodException.java index 31679daa70..0cf1743b00 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/NoSuchMethodException.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/NoSuchMethodException.java @@ -19,7 +19,6 @@ package org.apache.dubbo.common.bytecode; /** * NoSuchMethodException. */ - public class NoSuchMethodException extends RuntimeException { private static final long serialVersionUID = -2725364246023268766L; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/NoSuchPropertyException.java b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/NoSuchPropertyException.java index 7b6f8ecef3..015ca47e32 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/NoSuchPropertyException.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/NoSuchPropertyException.java @@ -19,7 +19,6 @@ package org.apache.dubbo.common.bytecode; /** * NoSuchPropertyException. */ - public class NoSuchPropertyException extends RuntimeException { private static final long serialVersionUID = -2725364246023268766L; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Proxy.java b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Proxy.java index 256eb63e95..29b990894d 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Proxy.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Proxy.java @@ -147,17 +147,31 @@ public class Proxy { Class rt = method.getReturnType(); Class[] pts = method.getParameterTypes(); - StringBuilder code = new StringBuilder("Object[] args = new Object[").append(pts.length).append("];"); + StringBuilder code = new StringBuilder("Object[] args = new Object[") + .append(pts.length) + .append("];"); for (int j = 0; j < pts.length; j++) { - code.append(" args[").append(j).append("] = ($w)$").append(j + 1).append(';'); + code.append(" args[") + .append(j) + .append("] = ($w)$") + .append(j + 1) + .append(';'); } - code.append(" Object ret = handler.invoke(this, methods[").append(ix).append("], args);"); + code.append(" Object ret = handler.invoke(this, methods[") + .append(ix) + .append("], args);"); if (!Void.TYPE.equals(rt)) { code.append(" return ").append(asArgument(rt, "ret")).append(';'); } methods.add(method); - ccp.addMethod(method.getName(), method.getModifiers(), rt, pts, method.getExceptionTypes(), code.toString()); + ccp.addMethod( + method.getName(), + method.getModifiers(), + rt, + pts, + method.getExceptionTypes(), + code.toString()); } } @@ -166,7 +180,8 @@ public class Proxy { ccp.setClassName(pcn); ccp.addField("public static java.lang.reflect.Method[] methods;"); ccp.addField("private " + InvocationHandler.class.getName() + " handler;"); - ccp.addConstructor(Modifier.PUBLIC, new Class[]{InvocationHandler.class}, new Class[0], "handler=$1;"); + ccp.addConstructor( + Modifier.PUBLIC, new Class[] {InvocationHandler.class}, new Class[0], "handler=$1;"); ccp.addDefaultConstructor(); Class clazz = ccp.toClass(neighbor, cl, domain); clazz.getField("methods").set(null, methods.toArray(new Method[0])); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Wrapper.java b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Wrapper.java index d5be038cb5..b42d5e286f 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Wrapper.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/bytecode/Wrapper.java @@ -20,8 +20,6 @@ import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.ReflectUtils; -import javassist.ClassPool; -import javassist.CtMethod; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -37,14 +35,17 @@ import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Matcher; import java.util.stream.Collectors; +import javassist.ClassPool; +import javassist.CtMethod; /** * Wrapper. */ public abstract class Wrapper { - private static final ConcurrentMap, Wrapper> WRAPPER_MAP = new ConcurrentHashMap, Wrapper>(); //class wrapper map + private static final ConcurrentMap, Wrapper> WRAPPER_MAP = + new ConcurrentHashMap, Wrapper>(); // class wrapper map private static final String[] EMPTY_STRING_ARRAY = new String[0]; - private static final String[] OBJECT_METHODS = new String[]{"getClass", "hashCode", "toString", "equals"}; + private static final String[] OBJECT_METHODS = new String[] {"getClass", "hashCode", "toString", "equals"}; private static final Wrapper OBJECT_WRAPPER = new Wrapper() { @Override public String[] getMethodNames() { @@ -82,7 +83,8 @@ public abstract class Wrapper { } @Override - public Object invokeMethod(Object instance, String mn, Class[] types, Object[] args) throws NoSuchMethodException { + public Object invokeMethod(Object instance, String mn, Class[] types, Object[] args) + throws NoSuchMethodException { if ("getClass".equals(mn)) { return instance.getClass(); } @@ -132,11 +134,22 @@ public abstract class Wrapper { StringBuilder c1 = new StringBuilder("public void setPropertyValue(Object o, String n, Object v){ "); StringBuilder c2 = new StringBuilder("public Object getPropertyValue(Object o, String n){ "); - StringBuilder c3 = new StringBuilder("public Object invokeMethod(Object o, String n, Class[] p, Object[] v) throws " + InvocationTargetException.class.getName() + "{ "); + StringBuilder c3 = + new StringBuilder("public Object invokeMethod(Object o, String n, Class[] p, Object[] v) throws " + + InvocationTargetException.class.getName() + "{ "); - c1.append(name).append(" w; try{ w = ((").append(name).append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }"); - c2.append(name).append(" w; try{ w = ((").append(name).append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }"); - c3.append(name).append(" w; try{ w = ((").append(name).append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }"); + c1.append(name) + .append(" w; try{ w = ((") + .append(name) + .append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }"); + c2.append(name) + .append(" w; try{ w = ((") + .append(name) + .append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }"); + c3.append(name) + .append(" w; try{ w = ((") + .append(name) + .append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }"); Map> pts = new HashMap<>(); // Map ms = new LinkedHashMap<>(); // @@ -147,12 +160,28 @@ public abstract class Wrapper { for (Field f : c.getFields()) { String fn = f.getName(); Class ft = f.getType(); - if (Modifier.isStatic(f.getModifiers()) || Modifier.isTransient(f.getModifiers()) || Modifier.isFinal(f.getModifiers())) { + if (Modifier.isStatic(f.getModifiers()) + || Modifier.isTransient(f.getModifiers()) + || Modifier.isFinal(f.getModifiers())) { continue; } - c1.append(" if( $2.equals(\"").append(fn).append("\") ){ ((").append(f.getDeclaringClass().getName()).append(")w).").append(fn).append('=').append(arg(ft, "$3")).append("; return; }"); - c2.append(" if( $2.equals(\"").append(fn).append("\") ){ return ($w)((").append(f.getDeclaringClass().getName()).append(")w).").append(fn).append("; }"); + c1.append(" if( $2.equals(\"") + .append(fn) + .append("\") ){ ((") + .append(f.getDeclaringClass().getName()) + .append(")w).") + .append(fn) + .append('=') + .append(arg(ft, "$3")) + .append("; return; }"); + c2.append(" if( $2.equals(\"") + .append(fn) + .append("\") ){ return ($w)((") + .append(f.getDeclaringClass().getName()) + .append(")w).") + .append(fn) + .append("; }"); pts.put(fn, ft); } @@ -169,21 +198,20 @@ public abstract class Wrapper { } Method[] methods = Arrays.stream(c.getMethods()) - .filter(method -> allMethod.contains(ReflectUtils.getDesc(method))) - .collect(Collectors.toList()) - .toArray(new Method[]{}); + .filter(method -> allMethod.contains(ReflectUtils.getDesc(method))) + .collect(Collectors.toList()) + .toArray(new Method[] {}); // get all public method. boolean hasMethod = ClassUtils.hasMethods(methods); if (hasMethod) { Map sameNameMethodCount = new HashMap<>((int) (methods.length / 0.75f) + 1); for (Method m : methods) { - sameNameMethodCount.compute(m.getName(), - (key, oldValue) -> oldValue == null ? 1 : oldValue + 1); + sameNameMethodCount.compute(m.getName(), (key, oldValue) -> oldValue == null ? 1 : oldValue + 1); } c3.append(" try{"); for (Method m : methods) { - //ignore Object's method. + // ignore Object's method. if (m.getDeclaringClass() == Object.class) { continue; } @@ -197,8 +225,12 @@ public abstract class Wrapper { if (overload) { if (len > 0) { for (int l = 0; l < len; l++) { - c3.append(" && ").append(" $3[").append(l).append("].getName().equals(\"") - .append(m.getParameterTypes()[l].getName()).append("\")"); + c3.append(" && ") + .append(" $3[") + .append(l) + .append("].getName().equals(\"") + .append(m.getParameterTypes()[l].getName()) + .append("\")"); } } } @@ -206,9 +238,18 @@ public abstract class Wrapper { c3.append(" ) { "); if (m.getReturnType() == Void.TYPE) { - c3.append(" w.").append(mn).append('(').append(args(m.getParameterTypes(), "$4")).append(");").append(" return null;"); + c3.append(" w.") + .append(mn) + .append('(') + .append(args(m.getParameterTypes(), "$4")) + .append(");") + .append(" return null;"); } else { - c3.append(" return ($w)w.").append(mn).append('(').append(args(m.getParameterTypes(), "$4")).append(");"); + c3.append(" return ($w)w.") + .append(mn) + .append('(') + .append(args(m.getParameterTypes(), "$4")) + .append(");"); } c3.append(" }"); @@ -224,7 +265,11 @@ public abstract class Wrapper { c3.append(" }"); } - c3.append(" throw new ").append(NoSuchMethodException.class.getName()).append("(\"Not found method \\\"\"+$2+\"\\\" in class ").append(c.getName()).append(".\"); }"); + c3.append(" throw new ") + .append(NoSuchMethodException.class.getName()) + .append("(\"Not found method \\\"\"+$2+\"\\\" in class ") + .append(c.getName()) + .append(".\"); }"); // deal with get/set method. Matcher matcher; @@ -233,21 +278,43 @@ public abstract class Wrapper { Method method = entry.getValue(); if ((matcher = ReflectUtils.GETTER_METHOD_DESC_PATTERN.matcher(md)).matches()) { String pn = propertyName(matcher.group(1)); - c2.append(" if( $2.equals(\"").append(pn).append("\") ){ return ($w)w.").append(method.getName()).append("(); }"); + c2.append(" if( $2.equals(\"") + .append(pn) + .append("\") ){ return ($w)w.") + .append(method.getName()) + .append("(); }"); pts.put(pn, method.getReturnType()); } else if ((matcher = ReflectUtils.IS_HAS_CAN_METHOD_DESC_PATTERN.matcher(md)).matches()) { String pn = propertyName(matcher.group(1)); - c2.append(" if( $2.equals(\"").append(pn).append("\") ){ return ($w)w.").append(method.getName()).append("(); }"); + c2.append(" if( $2.equals(\"") + .append(pn) + .append("\") ){ return ($w)w.") + .append(method.getName()) + .append("(); }"); pts.put(pn, method.getReturnType()); } else if ((matcher = ReflectUtils.SETTER_METHOD_DESC_PATTERN.matcher(md)).matches()) { Class pt = method.getParameterTypes()[0]; String pn = propertyName(matcher.group(1)); - c1.append(" if( $2.equals(\"").append(pn).append("\") ){ w.").append(method.getName()).append('(').append(arg(pt, "$3")).append("); return; }"); + c1.append(" if( $2.equals(\"") + .append(pn) + .append("\") ){ w.") + .append(method.getName()) + .append('(') + .append(arg(pt, "$3")) + .append("); return; }"); pts.put(pn, pt); } } - c1.append(" throw new ").append(NoSuchPropertyException.class.getName()).append("(\"Not found property \\\"\"+$2+\"\\\" field or setter method in class ").append(c.getName()).append(".\"); }"); - c2.append(" throw new ").append(NoSuchPropertyException.class.getName()).append("(\"Not found property \\\"\"+$2+\"\\\" field or getter method in class ").append(c.getName()).append(".\"); }"); + c1.append(" throw new ") + .append(NoSuchPropertyException.class.getName()) + .append("(\"Not found property \\\"\"+$2+\"\\\" field or setter method in class ") + .append(c.getName()) + .append(".\"); }"); + c2.append(" throw new ") + .append(NoSuchPropertyException.class.getName()) + .append("(\"Not found property \\\"\"+$2+\"\\\" field or getter method in class ") + .append(c.getName()) + .append(".\"); }"); // make class long id = WRAPPER_CLASS_COUNTER.getAndIncrement(); @@ -345,7 +412,9 @@ public abstract class Wrapper { } private static String propertyName(String pn) { - return pn.length() == 1 || Character.isLowerCase(pn.charAt(1)) ? Character.toLowerCase(pn.charAt(0)) + pn.substring(1) : pn; + return pn.length() == 1 || Character.isLowerCase(pn.charAt(1)) + ? Character.toLowerCase(pn.charAt(0)) + pn.substring(1) + : pn; } /** @@ -353,7 +422,7 @@ public abstract class Wrapper { * * @return property name array. */ - abstract public String[] getPropertyNames(); + public abstract String[] getPropertyNames(); /** * get property type. @@ -361,7 +430,7 @@ public abstract class Wrapper { * @param pn property name. * @return Property type or nul. */ - abstract public Class getPropertyType(String pn); + public abstract Class getPropertyType(String pn); /** * has property. @@ -369,7 +438,7 @@ public abstract class Wrapper { * @param name property name. * @return has or has not. */ - abstract public boolean hasProperty(String name); + public abstract boolean hasProperty(String name); /** * get property value. @@ -378,7 +447,8 @@ public abstract class Wrapper { * @param pn property name. * @return value. */ - abstract public Object getPropertyValue(Object instance, String pn) throws NoSuchPropertyException, IllegalArgumentException; + public abstract Object getPropertyValue(Object instance, String pn) + throws NoSuchPropertyException, IllegalArgumentException; /** * set property value. @@ -387,7 +457,8 @@ public abstract class Wrapper { * @param pn property name. * @param pv property value. */ - abstract public void setPropertyValue(Object instance, String pn, Object pv) throws NoSuchPropertyException, IllegalArgumentException; + public abstract void setPropertyValue(Object instance, String pn, Object pv) + throws NoSuchPropertyException, IllegalArgumentException; /** * get property value. @@ -396,7 +467,8 @@ public abstract class Wrapper { * @param pns property name array. * @return value array. */ - public Object[] getPropertyValues(Object instance, String[] pns) throws NoSuchPropertyException, IllegalArgumentException { + public Object[] getPropertyValues(Object instance, String[] pns) + throws NoSuchPropertyException, IllegalArgumentException { Object[] ret = new Object[pns.length]; for (int i = 0; i < ret.length; i++) { ret[i] = getPropertyValue(instance, pns[i]); @@ -411,7 +483,8 @@ public abstract class Wrapper { * @param pns property name array. * @param pvs property value array. */ - public void setPropertyValues(Object instance, String[] pns, Object[] pvs) throws NoSuchPropertyException, IllegalArgumentException { + public void setPropertyValues(Object instance, String[] pns, Object[] pvs) + throws NoSuchPropertyException, IllegalArgumentException { if (pns.length != pvs.length) { throw new IllegalArgumentException("pns.length != pvs.length"); } @@ -426,14 +499,14 @@ public abstract class Wrapper { * * @return method name array. */ - abstract public String[] getMethodNames(); + public abstract String[] getMethodNames(); /** * get method name array. * * @return method name array. */ - abstract public String[] getDeclaredMethodNames(); + public abstract String[] getDeclaredMethodNames(); /** * has method. @@ -459,5 +532,6 @@ public abstract class Wrapper { * @param args argument array. * @return return value. */ - abstract public Object invokeMethod(Object instance, String mn, Class[] types, Object[] args) throws NoSuchMethodException, InvocationTargetException; + public abstract Object invokeMethod(Object instance, String mn, Class[] types, Object[] args) + throws NoSuchMethodException, InvocationTargetException; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/cache/FileCacheStore.java b/dubbo-common/src/main/java/org/apache/dubbo/common/cache/FileCacheStore.java index 4e250fdf1f..5a31f82b4d 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/cache/FileCacheStore.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/cache/FileCacheStore.java @@ -77,20 +77,20 @@ public class FileCacheStore { } if (count > entrySize) { - logger.warn(COMMON_CACHE_MAX_FILE_SIZE_LIMIT_EXCEED, "mis-configuration of system properties", - "Check Java system property 'dubbo.mapping.cache.entrySize' and 'dubbo.meta.cache.entrySize'.", - "Cache file was truncated for exceeding the maximum entry size: " + entrySize); + logger.warn( + COMMON_CACHE_MAX_FILE_SIZE_LIMIT_EXCEED, + "mis-configuration of system properties", + "Check Java system property 'dubbo.mapping.cache.entrySize' and 'dubbo.meta.cache.entrySize'.", + "Cache file was truncated for exceeding the maximum entry size: " + entrySize); } } catch (IOException e) { - logger.warn(COMMON_CACHE_PATH_INACCESSIBLE, "inaccessible of cache path", "", - "Load cache failed ", e); + logger.warn(COMMON_CACHE_PATH_INACCESSIBLE, "inaccessible of cache path", "", "Load cache failed ", e); throw e; } return properties; } - private void unlock() { if (directoryLock != null && directoryLock.isValid()) { try { @@ -98,8 +98,12 @@ public class FileCacheStore { directoryLock.channel().close(); deleteFile(lockFile); } catch (IOException e) { - logger.error(COMMON_CACHE_PATH_INACCESSIBLE, "inaccessible of cache path", "", - "Failed to release cache path's lock file:" + lockFile, e); + logger.error( + COMMON_CACHE_PATH_INACCESSIBLE, + "inaccessible of cache path", + "", + "Failed to release cache path's lock file:" + lockFile, + e); throw new RuntimeException("Failed to release cache path's lock file:" + lockFile, e); } @@ -111,10 +115,8 @@ public class FileCacheStore { return; } - try (LimitedLengthBufferedWriter bw = - new LimitedLengthBufferedWriter( - new OutputStreamWriter( - new FileOutputStream(cacheFile, false), StandardCharsets.UTF_8), maxFileSize)) { + try (LimitedLengthBufferedWriter bw = new LimitedLengthBufferedWriter( + new OutputStreamWriter(new FileOutputStream(cacheFile, false), StandardCharsets.UTF_8), maxFileSize)) { bw.write("#" + comment); bw.newLine(); @@ -132,13 +134,15 @@ public class FileCacheStore { long remainSize = bw.getRemainSize(); if (remainSize < 0) { - logger.warn(COMMON_CACHE_MAX_ENTRY_COUNT_LIMIT_EXCEED, "mis-configuration of system properties", - "Check Java system property 'dubbo.mapping.cache.maxFileSize' and 'dubbo.meta.cache.maxFileSize'.", - "Cache file was truncated for exceeding the maximum file size " + maxFileSize + " byte. Exceeded by " + (-remainSize) + " byte."); + logger.warn( + COMMON_CACHE_MAX_ENTRY_COUNT_LIMIT_EXCEED, + "mis-configuration of system properties", + "Check Java system property 'dubbo.mapping.cache.maxFileSize' and 'dubbo.meta.cache.maxFileSize'.", + "Cache file was truncated for exceeding the maximum file size " + maxFileSize + + " byte. Exceeded by " + (-remainSize) + " byte."); } } catch (IOException e) { - logger.warn(COMMON_CACHE_PATH_INACCESSIBLE, "inaccessible of cache path", "", - "Update cache error.", e); + logger.warn(COMMON_CACHE_PATH_INACCESSIBLE, "inaccessible of cache path", "", "Update cache error.", e); } } @@ -168,8 +172,7 @@ public class FileCacheStore { private File lockFile; private FileLock directoryLock; - private Builder() { - } + private Builder() {} public Builder cacheFilePath(String cacheFilePath) { this.cacheFilePath = cacheFilePath; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/cache/FileCacheStoreFactory.java b/dubbo-common/src/main/java/org/apache/dubbo/common/cache/FileCacheStoreFactory.java index a339021afa..1f25041116 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/cache/FileCacheStoreFactory.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/cache/FileCacheStoreFactory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.cache; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -50,27 +49,30 @@ public final class FileCacheStoreFactory { throw new UnsupportedOperationException("No instance of 'FileCacheStoreFactory' for you! "); } - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FileCacheStoreFactory.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(FileCacheStoreFactory.class); private static final ConcurrentMap cacheMap = new ConcurrentHashMap<>(); private static final String SUFFIX = ".dubbo.cache"; private static final char ESCAPE_MARK = '%'; - private static final Set LEGAL_CHARACTERS = Collections.unmodifiableSet(new HashSet() {{ - // - $ . _ 0-9 a-z A-Z - add('-'); - add('$'); - add('.'); - add('_'); - for (char c = '0'; c <= '9'; c++) { - add(c); + private static final Set LEGAL_CHARACTERS = Collections.unmodifiableSet(new HashSet() { + { + // - $ . _ 0-9 a-z A-Z + add('-'); + add('$'); + add('.'); + add('_'); + for (char c = '0'; c <= '9'; c++) { + add(c); + } + for (char c = 'a'; c <= 'z'; c++) { + add(c); + } + for (char c = 'A'; c <= 'Z'; c++) { + add(c); + } } - for (char c = 'a'; c <= 'z'; c++) { - add(c); - } - for (char c = 'A'; c <= 'Z'; c++) { - add(c); - } - }}); + }); public static FileCacheStore getInstance(String basePath, String cacheName) { return getInstance(basePath, cacheName, true); @@ -95,8 +97,12 @@ public final class FileCacheStoreFactory { } catch (IOException e) { // 0-3 - cache path inaccessible - logger.error(COMMON_CACHE_PATH_INACCESSIBLE, "inaccessible of cache path", "", - "Cache store path can't be created: ", e); + logger.error( + COMMON_CACHE_PATH_INACCESSIBLE, + "inaccessible of cache path", + "", + "Cache store path can't be created: ", + e); throw new RuntimeException("Cache store path can't be created: " + candidate, e); } @@ -154,14 +160,17 @@ public final class FileCacheStoreFactory { Files.createFile(pathObjectOfFile); } - builder.cacheFilePath(name) - .cacheFile(file); + builder.cacheFilePath(name).cacheFile(file); return builder.build(); } catch (Throwable t) { - logger.warn(COMMON_CACHE_PATH_INACCESSIBLE, "inaccessible of cache path", "", - "Failed to create file store cache. Local file cache will be disabled. Cache file name: " + name, t); + logger.warn( + COMMON_CACHE_PATH_INACCESSIBLE, + "inaccessible of cache path", + "", + "Failed to create file store cache. Local file cache will be disabled. Cache file name: " + name, + t); return FileCacheStore.Empty.getInstance(name); } @@ -185,7 +194,8 @@ public final class FileCacheStoreFactory { } if (dirLock == null) { - throw new PathNotExclusiveException(fileName + " is not exclusive. Maybe multiple Dubbo instances are using the same folder."); + throw new PathNotExclusiveException( + fileName + " is not exclusive. Maybe multiple Dubbo instances are using the same folder."); } lockFile.deleteOnExit(); @@ -201,5 +211,4 @@ public final class FileCacheStoreFactory { super(msg); } } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2CompactUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2CompactUtils.java index c3a3952e0a..f492847a68 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2CompactUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2CompactUtils.java @@ -84,6 +84,7 @@ public class Dubbo2CompactUtils { return null; } } + public static boolean isReferenceClassLoaded() { return REFERENCE_CLASS != null; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2GenericExceptionUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2GenericExceptionUtils.java index 0e4e28d2e0..2bf3b25efa 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2GenericExceptionUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/compact/Dubbo2GenericExceptionUtils.java @@ -22,11 +22,16 @@ import java.lang.reflect.Constructor; public class Dubbo2GenericExceptionUtils { private static final Class GENERIC_EXCEPTION_CLASS; - private static final Constructor GENERIC_EXCEPTION_CONSTRUCTOR; - private static final Constructor GENERIC_EXCEPTION_CONSTRUCTOR_S; - private static final Constructor GENERIC_EXCEPTION_CONSTRUCTOR_S_S; - private static final Constructor GENERIC_EXCEPTION_CONSTRUCTOR_T; - private static final Constructor GENERIC_EXCEPTION_CONSTRUCTOR_S_T_S_S; + private static final Constructor + GENERIC_EXCEPTION_CONSTRUCTOR; + private static final Constructor + GENERIC_EXCEPTION_CONSTRUCTOR_S; + private static final Constructor + GENERIC_EXCEPTION_CONSTRUCTOR_S_S; + private static final Constructor + GENERIC_EXCEPTION_CONSTRUCTOR_T; + private static final Constructor + GENERIC_EXCEPTION_CONSTRUCTOR_S_T_S_S; static { GENERIC_EXCEPTION_CLASS = loadClass(); @@ -34,7 +39,8 @@ public class Dubbo2GenericExceptionUtils { GENERIC_EXCEPTION_CONSTRUCTOR_S = loadConstructor(String.class); GENERIC_EXCEPTION_CONSTRUCTOR_S_S = loadConstructor(String.class, String.class); GENERIC_EXCEPTION_CONSTRUCTOR_T = loadConstructor(Throwable.class); - GENERIC_EXCEPTION_CONSTRUCTOR_S_T_S_S = loadConstructor(String.class, Throwable.class, String.class, String.class); + GENERIC_EXCEPTION_CONSTRUCTOR_S_T_S_S = + loadConstructor(String.class, Throwable.class, String.class, String.class); } @SuppressWarnings("unchecked") @@ -51,7 +57,8 @@ public class Dubbo2GenericExceptionUtils { } } - private static Constructor loadConstructor(Class... parameterTypes) { + private static Constructor loadConstructor( + Class... parameterTypes) { if (GENERIC_EXCEPTION_CLASS == null) { return null; } @@ -63,9 +70,12 @@ public class Dubbo2GenericExceptionUtils { } public static boolean isGenericExceptionClassLoaded() { - return GENERIC_EXCEPTION_CLASS != null && GENERIC_EXCEPTION_CONSTRUCTOR != null - && GENERIC_EXCEPTION_CONSTRUCTOR_S != null && GENERIC_EXCEPTION_CONSTRUCTOR_S_S != null - && GENERIC_EXCEPTION_CONSTRUCTOR_T != null && GENERIC_EXCEPTION_CONSTRUCTOR_S_T_S_S != null; + return GENERIC_EXCEPTION_CLASS != null + && GENERIC_EXCEPTION_CONSTRUCTOR != null + && GENERIC_EXCEPTION_CONSTRUCTOR_S != null + && GENERIC_EXCEPTION_CONSTRUCTOR_S_S != null + && GENERIC_EXCEPTION_CONSTRUCTOR_T != null + && GENERIC_EXCEPTION_CONSTRUCTOR_S_T_S_S != null; } public static Class getGenericExceptionClass() { @@ -94,7 +104,8 @@ public class Dubbo2GenericExceptionUtils { } } - public static org.apache.dubbo.rpc.service.GenericException newGenericException(String exceptionClass, String exceptionMessage) { + public static org.apache.dubbo.rpc.service.GenericException newGenericException( + String exceptionClass, String exceptionMessage) { if (GENERIC_EXCEPTION_CONSTRUCTOR_S_S == null) { return null; } @@ -116,7 +127,8 @@ public class Dubbo2GenericExceptionUtils { } } - public static org.apache.dubbo.rpc.service.GenericException newGenericException(String message, Throwable cause, String exceptionClass, String exceptionMessage) { + public static org.apache.dubbo.rpc.service.GenericException newGenericException( + String message, Throwable cause, String exceptionClass, String exceptionMessage) { if (GENERIC_EXCEPTION_CONSTRUCTOR_S_T_S_S == null) { return null; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/Compiler.java b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/Compiler.java index dca8ec5eb2..b5b1d0a5ee 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/Compiler.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/Compiler.java @@ -50,5 +50,4 @@ public interface Compiler { default Class compile(Class neighbor, String code, ClassLoader classLoader) { return compile(code, classLoader); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/AbstractCompiler.java b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/AbstractCompiler.java index 7d4886814c..dacfe3043a 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/AbstractCompiler.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/AbstractCompiler.java @@ -71,7 +71,8 @@ public abstract class AbstractCompiler implements Compiler { } catch (RuntimeException t) { throw t; } catch (Throwable t) { - throw new IllegalStateException("Failed to compile class, cause: " + t.getMessage() + ", class: " + className + ", code: \n" + code + "\n, stack: " + ClassUtils.toString(t)); + throw new IllegalStateException("Failed to compile class, cause: " + t.getMessage() + ", class: " + + className + ", code: \n" + code + "\n, stack: " + ClassUtils.toString(t)); } } finally { lock.unlock(); @@ -82,8 +83,8 @@ public abstract class AbstractCompiler implements Compiler { return null; } - protected Class doCompile(Class neighbor,ClassLoader classLoader, String name, String source) throws Throwable { + protected Class doCompile(Class neighbor, ClassLoader classLoader, String name, String source) + throws Throwable { return doCompile(classLoader, name, source); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/AdaptiveCompiler.java b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/AdaptiveCompiler.java index 2518c22789..aac8e6d434 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/AdaptiveCompiler.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/AdaptiveCompiler.java @@ -52,5 +52,4 @@ public class AdaptiveCompiler implements Compiler, ScopeModelAware { } return compiler.compile(neighbor, code, classLoader); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/ClassUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/ClassUtils.java index c6d477b070..d2c39053d6 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/ClassUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/ClassUtils.java @@ -40,13 +40,15 @@ public class ClassUtils { public static final String JAVA_EXTENSION = ".java"; private static final int JIT_LIMIT = 5 * 1024; - private ClassUtils() { - } + private ClassUtils() {} public static Object newInstance(String name) { try { return forName(name).getDeclaredConstructor().newInstance(); - } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + } catch (InstantiationException + | IllegalAccessException + | InvocationTargetException + | NoSuchMethodException e) { throw new IllegalStateException(e.getMessage(), e); } } @@ -127,9 +129,10 @@ public class ClassUtils { } private static Class arrayForName(String className) throws ClassNotFoundException { - return Class.forName(className.endsWith("[]") - ? "[L" + className.substring(0, className.length() - 2) + ";" - : className, true, Thread.currentThread().getContextClassLoader()); + return Class.forName( + className.endsWith("[]") ? "[L" + className.substring(0, className.length() - 2) + ";" : className, + true, + Thread.currentThread().getContextClassLoader()); } public static Class getBoxedClass(Class type) { @@ -254,9 +257,12 @@ public class ClassUtils { } public static boolean isBeforeJava5(String javaVersion) { - return (StringUtils.isEmpty(javaVersion) || "1.0".equals(javaVersion) - || "1.1".equals(javaVersion) || "1.2".equals(javaVersion) - || "1.3".equals(javaVersion) || "1.4".equals(javaVersion)); + return (StringUtils.isEmpty(javaVersion) + || "1.0".equals(javaVersion) + || "1.1".equals(javaVersion) + || "1.2".equals(javaVersion) + || "1.3".equals(javaVersion) + || "1.4".equals(javaVersion)); } public static boolean isBeforeJava6(String javaVersion) { @@ -281,7 +287,8 @@ public class ClassUtils { public static void checkBytecode(String name, byte[] bytecode) { if (bytecode.length > JIT_LIMIT) { - System.err.println("The template bytecode too long, may be affect the JIT compiler. template class: " + name); + System.err.println( + "The template bytecode too long, may be affect the JIT compiler. template class: " + name); } } @@ -335,7 +342,8 @@ public class ClassUtils { return method.getName() + "(" + buf + ")"; } - public static Method searchMethod(Class currentClass, String name, Class[] parameterTypes) throws NoSuchMethodException { + public static Method searchMethod(Class currentClass, String name, Class[] parameterTypes) + throws NoSuchMethodException { if (currentClass == null) { throw new NoSuchMethodException("class == null"); } @@ -403,5 +411,4 @@ public class ClassUtils { int i = qualifiedName.lastIndexOf('.'); return i < 0 ? qualifiedName : qualifiedName.substring(i + 1); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/CtClassBuilder.java b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/CtClassBuilder.java index 9029d6d2cd..cf36f931cf 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/CtClassBuilder.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/CtClassBuilder.java @@ -18,6 +18,10 @@ package org.apache.dubbo.common.compiler.support; import org.apache.dubbo.common.bytecode.DubboLoaderClassPath; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; @@ -27,11 +31,6 @@ import javassist.CtNewMethod; import javassist.LoaderClassPath; import javassist.NotFoundException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - /** * CtClassBuilder is builder for CtClass *

@@ -122,7 +121,7 @@ public class CtClassBuilder { /** * get full qualified class name - * + * * @param className super class name, maybe qualified or not */ protected String getQualifiedClassName(String className) { @@ -144,7 +143,7 @@ public class CtClassBuilder { ClassPool pool = new ClassPool(true); pool.insertClassPath(new LoaderClassPath(classLoader)); pool.insertClassPath(new DubboLoaderClassPath()); - + // create class CtClass ctClass = pool.makeClass(className, pool.get(superClassName)); @@ -173,5 +172,4 @@ public class CtClassBuilder { return ctClass; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/JavassistCompiler.java b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/JavassistCompiler.java index 177a766d3a..129d58455c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/JavassistCompiler.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/JavassistCompiler.java @@ -18,15 +18,14 @@ package org.apache.dubbo.common.compiler.support; import org.apache.dubbo.common.bytecode.DubboLoaderClassPath; +import java.util.Arrays; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.LoaderClassPath; -import java.util.Arrays; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - /** * JavassistCompiler. (SPI, Singleton, ThreadSafe) */ @@ -99,5 +98,4 @@ public class JavassistCompiler extends AbstractCompiler { throw t; } } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/JdkCompiler.java b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/JdkCompiler.java index 55daa1b8ba..e7cf1bb9d4 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/JdkCompiler.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/compiler/support/JdkCompiler.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.compiler.support; - import javax.tools.DiagnosticCollector; import javax.tools.FileObject; import javax.tools.ForwardingJavaFileManager; @@ -28,6 +27,7 @@ import javax.tools.SimpleJavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.StandardLocation; import javax.tools.ToolProvider; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -66,9 +66,7 @@ public class JdkCompiler extends AbstractCompiler { private static final String DEFAULT_JAVA_VERSION = "1.8"; private static List buildDefaultOptions(String javaVersion) { - return Arrays.asList( - "-source", javaVersion, "-target", javaVersion - ); + return Arrays.asList("-source", javaVersion, "-target", javaVersion); } private static List buildDefaultOptions() { @@ -115,13 +113,19 @@ public class JdkCompiler extends AbstractCompiler { String packageName = i < 0 ? "" : name.substring(0, i); String className = i < 0 ? name : name.substring(i + 1); JavaFileObjectImpl javaFileObject = new JavaFileObjectImpl(className, sourceCode); - javaFileManager.putFileForInput(StandardLocation.SOURCE_PATH, packageName, - className + ClassUtils.JAVA_EXTENSION, javaFileObject); - Boolean result = compiler.getTask(null, javaFileManager, diagnosticCollector, options, - null, Collections.singletonList(javaFileObject)).call(); + javaFileManager.putFileForInput( + StandardLocation.SOURCE_PATH, packageName, className + ClassUtils.JAVA_EXTENSION, javaFileObject); + Boolean result = compiler.getTask( + null, + javaFileManager, + diagnosticCollector, + options, + null, + Collections.singletonList(javaFileObject)) + .call(); if (result == null || !result) { - throw new IllegalStateException("Compilation failed. class: " + name + ", diagnostics: " - + diagnosticCollector.getDiagnostics()); + throw new IllegalStateException( + "Compilation failed. class: " + name + ", diagnostics: " + diagnosticCollector.getDiagnostics()); } return classLoader.loadClass(name); } @@ -181,7 +185,8 @@ public class JdkCompiler extends AbstractCompiler { } @Override - public FileObject getFileForInput(Location location, String packageName, String relativeName) throws IOException { + public FileObject getFileForInput(Location location, String packageName, String relativeName) + throws IOException { FileObject o = fileObjects.get(uri(location, packageName, relativeName)); if (o != null) { return o; @@ -189,7 +194,8 @@ public class JdkCompiler extends AbstractCompiler { return super.getFileForInput(location, packageName, relativeName); } - public void putFileForInput(StandardLocation location, String packageName, String relativeName, JavaFileObject file) { + public void putFileForInput( + StandardLocation location, String packageName, String relativeName, JavaFileObject file) { fileObjects.put(uri(location, packageName, relativeName), file); } @@ -198,8 +204,8 @@ public class JdkCompiler extends AbstractCompiler { } @Override - public JavaFileObject getJavaFileForOutput(Location location, String qualifiedName, Kind kind, FileObject outputFile) - throws IOException { + public JavaFileObject getJavaFileForOutput( + Location location, String qualifiedName, Kind kind, FileObject outputFile) throws IOException { JavaFileObject file = new JavaFileObjectImpl(qualifiedName, kind); classLoader.add(qualifiedName, file); return file; @@ -271,7 +277,8 @@ public class JdkCompiler extends AbstractCompiler { return defineClass(qualifiedClassName, bytes, 0, bytes.length); } try { - return org.apache.dubbo.common.utils.ClassUtils.forNameWithCallerClassLoader(qualifiedClassName, getClass()); + return org.apache.dubbo.common.utils.ClassUtils.forNameWithCallerClassLoader( + qualifiedClassName, getClass()); } catch (ClassNotFoundException nf) { return super.findClass(qualifiedClassName); } @@ -282,14 +289,16 @@ public class JdkCompiler extends AbstractCompiler { } @Override - protected synchronized Class loadClass(final String name, final boolean resolve) throws ClassNotFoundException { + protected synchronized Class loadClass(final String name, final boolean resolve) + throws ClassNotFoundException { return super.loadClass(name, resolve); } @Override public InputStream getResourceAsStream(final String name) { if (name.endsWith(ClassUtils.CLASS_EXTENSION)) { - String qualifiedClassName = name.substring(0, name.length() - ClassUtils.CLASS_EXTENSION.length()).replace('/', '.'); + String qualifiedClassName = name.substring(0, name.length() - ClassUtils.CLASS_EXTENSION.length()) + .replace('/', '.'); JavaFileObjectImpl file = (JavaFileObjectImpl) classes.get(qualifiedClassName); if (file != null) { return new ByteArrayInputStream(file.getByteCode()); @@ -298,6 +307,4 @@ public class JdkCompiler extends AbstractCompiler { return super.getResourceAsStream(name); } } - - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/AbortPolicy.java b/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/AbortPolicy.java index 602ba6470d..e3af1dad5a 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/AbortPolicy.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/AbortPolicy.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.concurrent; import java.util.Queue; @@ -28,5 +27,4 @@ public class AbortPolicy implements Rejector { public void reject(final E e, final Queue queue) { throw new RejectException("no more memory can be used !"); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/CallableSafeInitializer.java b/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/CallableSafeInitializer.java index 3b41942fca..86fa8985f9 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/CallableSafeInitializer.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/CallableSafeInitializer.java @@ -31,8 +31,7 @@ import java.util.function.Consumer; */ public class CallableSafeInitializer { /** A guard which ensures that initialize() is called only once. */ - private final AtomicReference> factory = - new AtomicReference<>(); + private final AtomicReference> factory = new AtomicReference<>(); /** Holds the reference to the managed object. */ private final AtomicReference reference = new AtomicReference<>(); @@ -50,7 +49,7 @@ public class CallableSafeInitializer { * @return lazily initialized object * exception */ - //@Override + // @Override public final T get() { T result; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/DiscardPolicy.java b/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/DiscardPolicy.java index 4830b2aefd..881d5ba009 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/DiscardPolicy.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/DiscardPolicy.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.concurrent; - import java.util.Queue; /** @@ -25,7 +24,5 @@ import java.util.Queue; public class DiscardPolicy implements Rejector { @Override - public void reject(final E e, final Queue queue) { - - } + public void reject(final E e, final Queue queue) {} } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/RejectException.java b/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/RejectException.java index a7c2177264..26890c646c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/RejectException.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/RejectException.java @@ -29,8 +29,7 @@ public class RejectException extends RuntimeException { * Constructs a {@code RejectException} with no detail message. The cause is not initialized, and may subsequently be initialized by a * call to {@link #initCause(Throwable) initCause}. */ - public RejectException() { - } + public RejectException() {} /** * Constructs a {@code RejectException} with the specified detail message. The cause is not initialized, and may subsequently be diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/CompositeConfiguration.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/CompositeConfiguration.java index 1653e96134..1e07e012ab 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/CompositeConfiguration.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/CompositeConfiguration.java @@ -37,19 +37,20 @@ public class CompositeConfiguration implements Configuration { */ private final List configList = new CopyOnWriteArrayList<>(); - //FIXME, consider change configList to SortedMap to replace this boolean status. + // FIXME, consider change configList to SortedMap to replace this boolean status. private boolean dynamicIncluded; - public CompositeConfiguration() { - } + public CompositeConfiguration() {} public CompositeConfiguration(Configuration... configurations) { if (ArrayUtils.isNotEmpty(configurations)) { - Arrays.stream(configurations).filter(config -> !configList.contains(config)).forEach(configList::add); + Arrays.stream(configurations) + .filter(config -> !configList.contains(config)) + .forEach(configList::add); } } - //FIXME, consider changing configList to SortedMap to replace this boolean status. + // FIXME, consider changing configList to SortedMap to replace this boolean status. public boolean isDynamicIncluded() { return dynamicIncluded; } @@ -82,11 +83,14 @@ public class CompositeConfiguration implements Configuration { return value; } } catch (Exception e) { - logger.error(CONFIG_FAILED_LOAD_ENV_VARIABLE, "", "", "Error when trying to get value for key " + key + " from " + config + ", " + - "will continue to try the next one."); + logger.error( + CONFIG_FAILED_LOAD_ENV_VARIABLE, + "", + "", + "Error when trying to get value for key " + key + " from " + config + ", " + + "will continue to try the next one."); } } return null; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/Configuration.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/Configuration.java index 7734b5fbbe..5fa2143fd7 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/Configuration.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/Configuration.java @@ -74,9 +74,12 @@ public interface Configuration { return convert(Integer.class, key, defaultValue); } catch (NumberFormatException e) { // 0-2 Property type mismatch. - interfaceLevelLogger.error(COMMON_PROPERTY_TYPE_MISMATCH, "typo in property value", - "This property requires an integer value.", - "Actual Class: " + getClass().getName(), e); + interfaceLevelLogger.error( + COMMON_PROPERTY_TYPE_MISMATCH, + "typo in property value", + "This property requires an integer value.", + "Actual Class: " + getClass().getName(), + e); throw new IllegalStateException('\'' + key + "' doesn't map to a Integer object", e); } @@ -99,7 +102,8 @@ public interface Configuration { try { return convert(Boolean.class, key, defaultValue); } catch (Exception e) { - throw new IllegalStateException("Try to get " + '\'' + key + "' failed, maybe because this key doesn't map to a Boolean object", e); + throw new IllegalStateException( + "Try to get " + '\'' + key + "' failed, maybe because this key doesn't map to a Boolean object", e); } } @@ -150,7 +154,6 @@ public interface Configuration { return !isEmptyValue(getProperty(key)); } - default T convert(Class cls, String key, T defaultValue) { // we only process String properties for now String value = (String) getProperty(key); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java index ab91c881bb..6b260fc2fb 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/ConfigurationUtils.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.config; import org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory; @@ -78,7 +77,9 @@ public final class ConfigurationUtils { * @return */ public static Configuration getSystemConfiguration(ScopeModel scopeModel) { - return getScopeModelOrDefaultApplicationModel(scopeModel).modelEnvironment().getSystemConfiguration(); + return getScopeModelOrDefaultApplicationModel(scopeModel) + .modelEnvironment() + .getSystemConfiguration(); } /** @@ -87,7 +88,9 @@ public final class ConfigurationUtils { * @return */ public static Configuration getEnvConfiguration(ScopeModel scopeModel) { - return getScopeModelOrDefaultApplicationModel(scopeModel).modelEnvironment().getEnvironmentConfiguration(); + return getScopeModelOrDefaultApplicationModel(scopeModel) + .modelEnvironment() + .getEnvironmentConfiguration(); } /** @@ -97,9 +100,10 @@ public final class ConfigurationUtils { * * @return */ - public static Configuration getGlobalConfiguration(ScopeModel scopeModel) { - return getScopeModelOrDefaultApplicationModel(scopeModel).modelEnvironment().getConfiguration(); + return getScopeModelOrDefaultApplicationModel(scopeModel) + .modelEnvironment() + .getConfiguration(); } public static Configuration getDynamicGlobalConfiguration(ScopeModel scopeModel) { @@ -168,7 +172,8 @@ public final class ConfigurationUtils { public static String getCachedDynamicProperty(ScopeModel realScopeModel, String key, String defaultValue) { ScopeModel scopeModel = getScopeModelOrDefaultApplicationModel(realScopeModel); ConfigurationCache configurationCache = scopeModel.getBeanFactory().getBean(ConfigurationCache.class); - String value = configurationCache.computeIfAbsent(key, _k -> ConfigurationUtils.getDynamicProperty(scopeModel, _k, "")); + String value = configurationCache.computeIfAbsent( + key, _k -> ConfigurationUtils.getDynamicProperty(scopeModel, _k, "")); return StringUtils.isEmpty(value) ? defaultValue : value; } @@ -206,26 +211,24 @@ public final class ConfigurationUtils { } else { Properties properties = new Properties(); properties.load(new StringReader(content)); - properties.stringPropertyNames().forEach( - k -> { - boolean deny = false; - for (String key : securityKey) { - if (k.contains(key)) { - deny = true; - break; - } + properties.stringPropertyNames().forEach(k -> { + boolean deny = false; + for (String key : securityKey) { + if (k.contains(key)) { + deny = true; + break; } - if (!deny) { - map.put(k, properties.getProperty(k)); - } - }); + } + if (!deny) { + map.put(k, properties.getProperty(k)); + } + }); } return map; } public static boolean isEmptyValue(Object value) { - return value == null || - value instanceof String && StringUtils.isBlank((String) value); + return value == null || value instanceof String && StringUtils.isBlank((String) value); } /** @@ -248,7 +251,8 @@ public final class ConfigurationUtils { * @param * @return */ - public static Map getSubProperties(Collection> configMaps, String prefix) { + public static Map getSubProperties( + Collection> configMaps, String prefix) { Map map = new LinkedHashMap<>(); for (Map configMap : configMaps) { getSubProperties(configMap, prefix, map); @@ -260,7 +264,8 @@ public final class ConfigurationUtils { return getSubProperties(configMap, prefix, null); } - private static Map getSubProperties(Map configMap, String prefix, Map resultMap) { + private static Map getSubProperties( + Map configMap, String prefix, Map resultMap) { if (!prefix.endsWith(".")) { prefix += "."; } @@ -277,9 +282,10 @@ public final class ConfigurationUtils { for (Map.Entry entry : copy.entrySet()) { String key = entry.getKey(); V val = entry.getValue(); - if ((StringUtils.startsWithIgnoreCase(key, prefix) || StringUtils.startsWithIgnoreCase(key, StringUtils.toOSStyleKey(prefix))) - && key.length() > prefix.length() - && !ConfigurationUtils.isEmptyValue(val)) { + if ((StringUtils.startsWithIgnoreCase(key, prefix) + || StringUtils.startsWithIgnoreCase(key, StringUtils.toOSStyleKey(prefix))) + && key.length() > prefix.length() + && !ConfigurationUtils.isEmptyValue(val)) { String k = key.substring(prefix.length()); // convert camelCase/snake_case to kebab-case @@ -317,9 +323,10 @@ public final class ConfigurationUtils { } for (Map.Entry entry : copy.entrySet()) { String key = entry.getKey(); - if ((StringUtils.startsWithIgnoreCase(key, prefix) || StringUtils.startsWithIgnoreCase(key, StringUtils.toOSStyleKey(prefix))) - && key.length() > prefix.length() - && !ConfigurationUtils.isEmptyValue(entry.getValue())) { + if ((StringUtils.startsWithIgnoreCase(key, prefix) + || StringUtils.startsWithIgnoreCase(key, StringUtils.toOSStyleKey(prefix))) + && key.length() > prefix.length() + && !ConfigurationUtils.isEmptyValue(entry.getValue())) { return true; } } @@ -358,8 +365,8 @@ public final class ConfigurationUtils { String key = entry.getKey(); V val = entry.getValue(); if (StringUtils.startsWithIgnoreCase(key, prefix) - && key.length() > prefix.length() - && !ConfigurationUtils.isEmptyValue(val)) { + && key.length() > prefix.length() + && !ConfigurationUtils.isEmptyValue(val)) { String k = key.substring(prefix.length()); int endIndex = k.indexOf("."); @@ -381,8 +388,10 @@ public final class ConfigurationUtils { * @return non-null * @see 2.7.4 */ - public static DynamicConfigurationFactory getDynamicConfigurationFactory(ExtensionAccessor extensionAccessor, String name) { - ExtensionLoader loader = extensionAccessor.getExtensionLoader(DynamicConfigurationFactory.class); + public static DynamicConfigurationFactory getDynamicConfigurationFactory( + ExtensionAccessor extensionAccessor, String name) { + ExtensionLoader loader = + extensionAccessor.getExtensionLoader(DynamicConfigurationFactory.class); return loader.getOrDefaultExtension(name); } @@ -423,7 +432,10 @@ public final class ConfigurationUtils { */ @Deprecated public static Configuration getDynamicGlobalConfiguration() { - return ApplicationModel.defaultModel().getDefaultModule().modelEnvironment().getDynamicGlobalConfiguration(); + return ApplicationModel.defaultModel() + .getDefaultModule() + .modelEnvironment() + .getDynamicGlobalConfiguration(); } /** @@ -485,5 +497,4 @@ public final class ConfigurationUtils { public static int get(String property, int defaultValue) { return get(ApplicationModel.defaultModel(), property, defaultValue); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/Environment.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/Environment.java index e20959e3a1..644ed4a2f9 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/Environment.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/Environment.java @@ -182,7 +182,8 @@ public class Environment extends LifecycleAdapter implements ApplicationExt { */ public Configuration getPrefixedConfiguration(AbstractConfig config, String prefix) { - // The sequence would be: SystemConfiguration -> EnvironmentConfiguration -> AppExternalConfiguration -> ExternalConfiguration -> AppConfiguration -> AbstractConfig -> PropertiesConfiguration + // The sequence would be: SystemConfiguration -> EnvironmentConfiguration -> AppExternalConfiguration -> + // ExternalConfiguration -> AppConfiguration -> AbstractConfig -> PropertiesConfiguration Configuration instanceConfiguration = new ConfigConfigurationAdapter(config, prefix); CompositeConfiguration compositeConfiguration = new CompositeConfiguration(); compositeConfiguration.addConfiguration(systemConfiguration); @@ -224,7 +225,8 @@ public class Environment extends LifecycleAdapter implements ApplicationExt { * @return */ public List> getConfigurationMaps(AbstractConfig config, String prefix) { - // The sequence would be: SystemConfiguration -> EnvironmentConfiguration -> AppExternalConfiguration -> ExternalConfiguration -> AppConfiguration -> AbstractConfig -> PropertiesConfiguration + // The sequence would be: SystemConfiguration -> EnvironmentConfiguration -> AppExternalConfiguration -> + // ExternalConfiguration -> AppConfiguration -> AbstractConfig -> PropertiesConfiguration List> maps = new ArrayList<>(); maps.add(systemConfiguration.getProperties()); @@ -268,7 +270,12 @@ public class Environment extends LifecycleAdapter implements ApplicationExt { try { defaultDynamicConfiguration.close(); } catch (Exception e) { - logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "close dynamic configuration failed: " + e.getMessage(), e); + logger.warn( + COMMON_UNEXPECTED_EXCEPTION, + "", + "", + "close dynamic configuration failed: " + e.getMessage(), + e); } defaultDynamicConfiguration = null; } @@ -327,7 +334,11 @@ public class Environment extends LifecycleAdapter implements ApplicationExt { if (defaultDynamicGlobalConfiguration == null) { if (defaultDynamicConfiguration == null) { if (logger.isWarnEnabled()) { - logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "dynamicConfiguration is null , return globalConfiguration."); + logger.warn( + COMMON_UNEXPECTED_EXCEPTION, + "", + "", + "dynamicConfiguration is null , return globalConfiguration."); } return getConfiguration(); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/InmemoryConfiguration.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/InmemoryConfiguration.java index 92d808de9f..8179dfc6ea 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/InmemoryConfiguration.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/InmemoryConfiguration.java @@ -29,8 +29,7 @@ public class InmemoryConfiguration implements Configuration { // stores the configuration key-value pairs private Map store = new LinkedHashMap<>(); - public InmemoryConfiguration() { - } + public InmemoryConfiguration() {} public InmemoryConfiguration(String name) { this.name = name; @@ -73,5 +72,4 @@ public class InmemoryConfiguration implements Configuration { public Map getProperties() { return store; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/ModuleEnvironment.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/ModuleEnvironment.java index cf51624262..3de18ccbf0 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/ModuleEnvironment.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/ModuleEnvironment.java @@ -99,7 +99,11 @@ public class ModuleEnvironment extends Environment implements ModuleExt { if (dynamicGlobalConfiguration == null) { if (dynamicConfiguration == null) { if (logger.isWarnEnabled()) { - logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "dynamicConfiguration is null , return globalConfiguration."); + logger.warn( + COMMON_UNEXPECTED_EXCEPTION, + "", + "", + "dynamicConfiguration is null , return globalConfiguration."); } return getConfiguration(); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/OrderedPropertiesConfiguration.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/OrderedPropertiesConfiguration.java index b4440a0764..a2838a9d96 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/OrderedPropertiesConfiguration.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/OrderedPropertiesConfiguration.java @@ -37,7 +37,8 @@ public class OrderedPropertiesConfiguration implements Configuration { public void refresh() { properties = new Properties(); - ExtensionLoader propertiesProviderExtensionLoader = moduleModel.getExtensionLoader(OrderedPropertiesProvider.class); + ExtensionLoader propertiesProviderExtensionLoader = + moduleModel.getExtensionLoader(OrderedPropertiesProvider.class); Set propertiesProviderNames = propertiesProviderExtensionLoader.getSupportedExtensions(); if (CollectionUtils.isEmpty(propertiesProviderNames)) { return; @@ -47,15 +48,13 @@ public class OrderedPropertiesConfiguration implements Configuration { orderedPropertiesProviders.add(propertiesProviderExtensionLoader.getExtension(propertiesProviderName)); } - //order the propertiesProvider according the priority descending + // order the propertiesProvider according the priority descending orderedPropertiesProviders.sort((a, b) -> b.priority() - a.priority()); - - //override the properties. + // override the properties. for (OrderedPropertiesProvider orderedPropertiesProvider : orderedPropertiesProviders) { properties.putAll(orderedPropertiesProvider.initProperties()); } - } @Override diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/OrderedPropertiesProvider.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/OrderedPropertiesProvider.java index ccc0539e16..051104ce4d 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/OrderedPropertiesProvider.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/OrderedPropertiesProvider.java @@ -16,16 +16,15 @@ */ package org.apache.dubbo.common.config; - import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import java.util.Properties; /** - * + * * The smaller value, the higher priority - * + * */ @SPI(scope = ExtensionScope.MODULE) public interface OrderedPropertiesProvider { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/PrefixedConfiguration.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/PrefixedConfiguration.java index d8b45881fa..d16c5d005d 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/PrefixedConfiguration.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/PrefixedConfiguration.java @@ -41,5 +41,4 @@ public class PrefixedConfiguration implements Configuration { } return null; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/SystemConfiguration.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/SystemConfiguration.java index 8341fd4e15..eaedbda378 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/SystemConfiguration.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/SystemConfiguration.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.config; - import java.util.Map; /** diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfiguration.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfiguration.java index afd1cac989..c9bd32b9f0 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfiguration.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfiguration.java @@ -50,7 +50,8 @@ public abstract class AbstractDynamicConfiguration implements DynamicConfigurati /** * The keep alive time in milliseconds for threads in {@link ThreadPoolExecutor} */ - public static final String THREAD_POOL_KEEP_ALIVE_TIME_PARAM_NAME = PARAM_NAME_PREFIX + "thread-pool.keep-alive-time"; + public static final String THREAD_POOL_KEEP_ALIVE_TIME_PARAM_NAME = + PARAM_NAME_PREFIX + "thread-pool.keep-alive-time"; /** * The parameter name of group for config-center @@ -88,27 +89,26 @@ public abstract class AbstractDynamicConfiguration implements DynamicConfigurati private final long timeout; protected AbstractDynamicConfiguration(URL url) { - this(getThreadPoolPrefixName(url), getThreadPoolSize(url), getThreadPoolKeepAliveTime(url), getGroup(url), - getTimeout(url)); + this( + getThreadPoolPrefixName(url), + getThreadPoolSize(url), + getThreadPoolKeepAliveTime(url), + getGroup(url), + getTimeout(url)); } - protected AbstractDynamicConfiguration(String threadPoolPrefixName, - int threadPoolSize, - long keepAliveTime, - String group, - long timeout) { + protected AbstractDynamicConfiguration( + String threadPoolPrefixName, int threadPoolSize, long keepAliveTime, String group, long timeout) { this.workersThreadPool = initWorkersThreadPool(threadPoolPrefixName, threadPoolSize, keepAliveTime); this.group = group; this.timeout = timeout; } @Override - public void addListener(String key, String group, ConfigurationListener listener) { - } + public void addListener(String key, String group, ConfigurationListener listener) {} @Override - public void removeListener(String key, String group, ConfigurationListener listener) { - } + public void removeListener(String key, String group, ConfigurationListener listener) {} @Override public final String getConfig(String key, String group, long timeout) throws IllegalStateException { @@ -187,10 +187,12 @@ public abstract class AbstractDynamicConfiguration implements DynamicConfigurati * @param timeout timeout in milliseconds */ protected final void execute(Runnable task, long timeout) { - execute(() -> { - task.run(); - return null; - }, timeout); + execute( + () -> { + task.run(); + return null; + }, + timeout); } /** @@ -233,11 +235,15 @@ public abstract class AbstractDynamicConfiguration implements DynamicConfigurati } } - protected ThreadPoolExecutor initWorkersThreadPool(String threadPoolPrefixName, - int threadPoolSize, - long keepAliveTime) { - return new ThreadPoolExecutor(threadPoolSize, threadPoolSize, keepAliveTime, - TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), new NamedThreadFactory(threadPoolPrefixName, true)); + protected ThreadPoolExecutor initWorkersThreadPool( + String threadPoolPrefixName, int threadPoolSize, long keepAliveTime) { + return new ThreadPoolExecutor( + threadPoolSize, + threadPoolSize, + keepAliveTime, + TimeUnit.MILLISECONDS, + new LinkedBlockingQueue<>(), + new NamedThreadFactory(threadPoolPrefixName, true)); } protected static String getThreadPoolPrefixName(URL url) { @@ -273,7 +279,6 @@ public abstract class AbstractDynamicConfiguration implements DynamicConfigurati return defaultValue; } - protected String getGroup() { return group; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigChangedEvent.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigChangedEvent.java index f7c2ec71ba..405adbb61b 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigChangedEvent.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigChangedEvent.java @@ -64,12 +64,12 @@ public class ConfigChangedEvent extends EventObject { @Override public String toString() { - return "ConfigChangedEvent{" + - "key='" + key + '\'' + - ", group='" + group + '\'' + - ", content='" + content + '\'' + - ", changeType=" + changeType + - "} " + super.toString(); + return "ConfigChangedEvent{" + "key='" + + key + '\'' + ", group='" + + group + '\'' + ", content='" + + content + '\'' + ", changeType=" + + changeType + "} " + + super.toString(); } @Override @@ -81,10 +81,10 @@ public class ConfigChangedEvent extends EventObject { return false; } ConfigChangedEvent that = (ConfigChangedEvent) o; - return Objects.equals(getKey(), that.getKey()) && - Objects.equals(getGroup(), that.getGroup()) && - Objects.equals(getContent(), that.getContent()) && - getChangeType() == that.getChangeType(); + return Objects.equals(getKey(), that.getKey()) + && Objects.equals(getGroup(), that.getGroup()) + && Objects.equals(getContent(), that.getContent()) + && getChangeType() == that.getChangeType(); } @Override diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigItem.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigItem.java index ad5aa1bdc2..6acdc7cd51 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigItem.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/ConfigItem.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.config.configcenter; /** @@ -52,7 +51,5 @@ public class ConfigItem { this.ticket = ticket; } - public ConfigItem() { - - } + public ConfigItem() {} } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/DynamicConfiguration.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/DynamicConfiguration.java index fc505d51a6..70d4428026 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/DynamicConfiguration.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/DynamicConfiguration.java @@ -19,7 +19,6 @@ package org.apache.dubbo.common.config.configcenter; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.Configuration; - /** * Dynamic Configuration *
@@ -48,7 +47,6 @@ public interface DynamicConfiguration extends Configuration, AutoCloseable { addListener(key, getDefaultGroup(), listener); } - /** * {@link #removeListener(String, String, ConfigurationListener)} * @@ -170,7 +168,8 @@ public interface DynamicConfiguration extends Configuration, AutoCloseable { * @return * @throws UnsupportedOperationException */ - default boolean publishConfigCas(String key, String group, String content, Object ticket) throws UnsupportedOperationException { + default boolean publishConfigCas(String key, String group, String content, Object ticket) + throws UnsupportedOperationException { return false; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/DynamicConfigurationFactory.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/DynamicConfigurationFactory.java index a6b6dbc076..1fb89e4bd1 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/DynamicConfigurationFactory.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/DynamicConfigurationFactory.java @@ -27,5 +27,4 @@ import org.apache.dubbo.common.extension.SPI; public interface DynamicConfigurationFactory { DynamicConfiguration getDynamicConfiguration(URL url); - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/TreePathDynamicConfiguration.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/TreePathDynamicConfiguration.java index fcf6cc16b8..868cb6753e 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/TreePathDynamicConfiguration.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/TreePathDynamicConfiguration.java @@ -62,12 +62,13 @@ public abstract class TreePathDynamicConfiguration extends AbstractDynamicConfig this.rootPath = getRootPath(url); } - public TreePathDynamicConfiguration(String rootPath, - String threadPoolPrefixName, - int threadPoolSize, - long keepAliveTime, - String group, - long timeout) { + public TreePathDynamicConfiguration( + String rootPath, + String threadPoolPrefixName, + int threadPoolSize, + long keepAliveTime, + String group, + long timeout) { super(threadPoolPrefixName, threadPoolSize, keepAliveTime, group, timeout); this.rootPath = rootPath; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/wrapper/CompositeDynamicConfiguration.java b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/wrapper/CompositeDynamicConfiguration.java index b4afd0d46e..5ff967de41 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/wrapper/CompositeDynamicConfiguration.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/config/configcenter/wrapper/CompositeDynamicConfiguration.java @@ -35,7 +35,8 @@ public class CompositeDynamicConfiguration implements DynamicConfiguration { public static final String NAME = "COMPOSITE"; - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CompositeDynamicConfiguration.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(CompositeDynamicConfiguration.class); private final Set configurations = new HashSet<>(); @@ -49,7 +50,6 @@ public class CompositeDynamicConfiguration implements DynamicConfiguration { return configurations; } - @Override public void addListener(String key, String group, ConfigurationListener listener) { iterateListenerOperation(configuration -> configuration.addListener(key, group, listener)); @@ -92,7 +92,13 @@ public class CompositeDynamicConfiguration implements DynamicConfiguration { try { configuration.close(); } catch (Exception e) { - logger.warn(INTERNAL_ERROR, "unknown error in configuration-center related code in common module", "", "close dynamic configuration " + configuration.getClass().getName() + "failed: " + e.getMessage(), e); + logger.warn( + INTERNAL_ERROR, + "unknown error in configuration-center related code in common module", + "", + "close dynamic configuration " + + configuration.getClass().getName() + "failed: " + e.getMessage(), + e); } } configurations.clear(); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ClusterRules.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ClusterRules.java index f5f87299c4..29b6037b14 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ClusterRules.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/ClusterRules.java @@ -52,12 +52,9 @@ public interface ClusterRules { **/ String BROADCAST = "broadcast"; - String AVAILABLE = "available"; String MERGEABLE = "mergeable"; String EMPTY = ""; - - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java index a0faee25a9..c4ee8a9255 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.constants; import org.apache.dubbo.common.URL; @@ -268,6 +267,7 @@ public interface CommonConstants { * generic call */ String $INVOKE = "$invoke"; + String $INVOKE_ASYNC = "$invokeAsync"; String GENERIC_PARAMETER_DESC = "Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/Object;"; @@ -309,6 +309,7 @@ public interface CommonConstants { @Deprecated String SHUTDOWN_WAIT_SECONDS_KEY = "dubbo.service.shutdown.wait.seconds"; + String SHUTDOWN_WAIT_KEY = "dubbo.service.shutdown.wait"; String DUBBO_PROTOCOL = "dubbo"; @@ -610,17 +611,16 @@ public interface CommonConstants { * used for thread isolation between services */ String SERVICE_EXECUTOR = "service-executor"; + String EXECUTOR_MANAGEMENT_MODE = "executor-management-mode"; String EXECUTOR_MANAGEMENT_MODE_DEFAULT = "default"; String EXECUTOR_MANAGEMENT_MODE_ISOLATION = "isolation"; - /** * used in JVMUtil.java ,Control stack print lines, default is 32 lines */ String DUBBO_JSTACK_MAXLINE = "dubbo.jstack-dump.max-line"; - String ENCODE_IN_IO_THREAD_KEY = "encode.in.io"; boolean DEFAULT_ENCODE_IN_IO_THREAD = false; @@ -645,13 +645,10 @@ public interface CommonConstants { String SERVICE_DEPLOYER_ATTRIBUTE_KEY = "serviceDeployer"; - - String DUBBO_MANUAL_REGISTER_KEY = "dubbo.application.manual-register"; String DUBBO2_COMPACT_ENABLE = "dubbo.compact.enable"; - String POD_NAMESPACE = "POD_NAMESPACE"; String CLUSTER_DOMAIN = "CLUSTER_DOMAIN"; @@ -659,5 +656,4 @@ public interface CommonConstants { String EXT_PROTOCOL = "ext.protocol"; String IS_EXTRA = "isExtra"; - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/FilterConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/FilterConstants.java index f4199ffe41..028535bfc6 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/FilterConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/FilterConstants.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.constants; public interface FilterConstants { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/LoadbalanceRules.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/LoadbalanceRules.java index b129d9d4e4..25a399ab78 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/LoadbalanceRules.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/LoadbalanceRules.java @@ -52,5 +52,4 @@ public interface LoadbalanceRules { String ADAPTIVE = "adaptive"; String EMPTY = ""; - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/LoggerCodeConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/LoggerCodeConstants.java index 7a598ddddf..dbad366d6f 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/LoggerCodeConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/LoggerCodeConstants.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.constants; /** diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/QosConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/QosConstants.java index 01286e6e4f..3a0460977c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/QosConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/QosConstants.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.constants; /** diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java index c26f67a02c..0302f318ea 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RegistryConstants.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.constants; public interface RegistryConstants { @@ -143,5 +142,4 @@ public interface RegistryConstants { boolean DEFAULT_ENABLE_EMPTY_PROTECTION = false; String REGISTER_CONSUMER_URL_KEY = "register-consumer-url"; String REGISTRY_PROTOCOL_TYPE = "registry-protocol-type"; - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RemotingConstants.java b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RemotingConstants.java index cbdb0bffe1..f02264decb 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RemotingConstants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/constants/RemotingConstants.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.constants; /** diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/context/ApplicationExt.java b/dubbo-common/src/main/java/org/apache/dubbo/common/context/ApplicationExt.java index 2e6471dd9d..1f0ceb2c00 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/context/ApplicationExt.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/context/ApplicationExt.java @@ -20,6 +20,4 @@ import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; @SPI(scope = ExtensionScope.APPLICATION) -public interface ApplicationExt extends Lifecycle { - -} +public interface ApplicationExt extends Lifecycle {} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/context/LifecycleAdapter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/context/LifecycleAdapter.java index 3f67fa1200..a69f9e3266 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/context/LifecycleAdapter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/context/LifecycleAdapter.java @@ -19,17 +19,11 @@ package org.apache.dubbo.common.context; public abstract class LifecycleAdapter implements Lifecycle { @Override - public void initialize() throws IllegalStateException { - - } + public void initialize() throws IllegalStateException {} @Override - public void start() throws IllegalStateException { - - } + public void start() throws IllegalStateException {} @Override - public void destroy() throws IllegalStateException { - - } + public void destroy() throws IllegalStateException {} } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/context/ModuleExt.java b/dubbo-common/src/main/java/org/apache/dubbo/common/context/ModuleExt.java index bb85139961..300e4c5013 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/context/ModuleExt.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/context/ModuleExt.java @@ -20,6 +20,4 @@ import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; @SPI(scope = ExtensionScope.MODULE) -public interface ModuleExt extends Lifecycle { - -} +public interface ModuleExt extends Lifecycle {} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/convert/ConverterUtil.java b/dubbo-common/src/main/java/org/apache/dubbo/common/convert/ConverterUtil.java index 7e5c8b65fc..a6c3c25840 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/convert/ConverterUtil.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/convert/ConverterUtil.java @@ -27,7 +27,8 @@ import java.util.stream.Collectors; public class ConverterUtil { private final FrameworkModel frameworkModel; - private final ConcurrentMap, ConcurrentMap, List>> converterCache = new ConcurrentHashMap<>(); + private final ConcurrentMap, ConcurrentMap, List>> converterCache = + new ConcurrentHashMap<>(); public ConverterUtil(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; @@ -42,12 +43,14 @@ public class ConverterUtil { * @see ExtensionLoader#getSupportedExtensionInstances() */ public Converter getConverter(Class sourceType, Class targetType) { - ConcurrentMap, List> toTargetMap = ConcurrentHashMapUtils.computeIfAbsent(converterCache, sourceType, (k) -> new ConcurrentHashMap<>()); - List converters = ConcurrentHashMapUtils.computeIfAbsent(toTargetMap, targetType, (k) -> frameworkModel.getExtensionLoader(Converter.class) - .getSupportedExtensionInstances() - .stream() - .filter(converter -> converter.accept(sourceType, targetType)) - .collect(Collectors.toList())); + ConcurrentMap, List> toTargetMap = + ConcurrentHashMapUtils.computeIfAbsent(converterCache, sourceType, (k) -> new ConcurrentHashMap<>()); + List converters = ConcurrentHashMapUtils.computeIfAbsent( + toTargetMap, + targetType, + (k) -> frameworkModel.getExtensionLoader(Converter.class).getSupportedExtensionInstances().stream() + .filter(converter -> converter.accept(sourceType, targetType)) + .collect(Collectors.toList())); return converters.size() > 0 ? converters.get(0) : null; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringConverter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringConverter.java index 9232fedc5f..6f12b70827 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringConverter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringConverter.java @@ -23,5 +23,4 @@ package org.apache.dubbo.common.convert; * @since 2.7.6 */ @FunctionalInterface -public interface StringConverter extends Converter { -} +public interface StringConverter extends Converter {} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToCharArrayConverter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToCharArrayConverter.java index 3e40bf1ed8..4c58cd1349 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToCharArrayConverter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToCharArrayConverter.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.convert; - import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty; /** @@ -31,7 +30,6 @@ public class StringToCharArrayConverter implements StringConverter { return isNotEmpty(source) ? source.toCharArray() : null; } - @Override public int getPriority() { return NORMAL_PRIORITY + 7; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToDoubleConverter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToDoubleConverter.java index 148b2f8b5c..85aa2201fc 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToDoubleConverter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToDoubleConverter.java @@ -31,7 +31,6 @@ public class StringToDoubleConverter implements StringConverter { return isNotEmpty(source) ? valueOf(source) : null; } - @Override public int getPriority() { return NORMAL_PRIORITY + 3; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToDurationConverter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToDurationConverter.java index edd1cf297f..067f5d836c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToDurationConverter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToDurationConverter.java @@ -56,13 +56,14 @@ public class StringToDurationConverter implements StringConverter { Matcher matcher = matcher(value); Assert.assertTrue(matcher.matches(), "Does not match simple duration pattern"); String suffix = matcher.group(2); - return (StringUtils.isNotBlank(suffix) ? TimeUnit.fromSuffix(suffix) : TimeUnit.fromChronoUnit(unit)) + return (StringUtils.isNotBlank(suffix) + ? TimeUnit.fromSuffix(suffix) + : TimeUnit.fromChronoUnit(unit)) .parse(matcher.group(1)); } catch (Exception ex) { throw new IllegalArgumentException("'" + value + "' is not a valid simple duration", ex); } } - }, /** @@ -77,7 +78,6 @@ public class StringToDurationConverter implements StringConverter { throw new IllegalArgumentException("'" + value + "' is not a valid ISO-8601 duration", ex); } } - }; private final Pattern pattern; @@ -237,7 +237,6 @@ public class StringToDurationConverter implements StringConverter { } throw new IllegalArgumentException("Unknown unit '" + suffix + "'"); } - } } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToLongConverter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToLongConverter.java index f9ebdcd687..680298c646 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToLongConverter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToLongConverter.java @@ -31,7 +31,6 @@ public class StringToLongConverter implements StringConverter { return isNotEmpty(source) ? valueOf(source) : null; } - @Override public int getPriority() { return NORMAL_PRIORITY + 1; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToOptionalConverter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToOptionalConverter.java index a26fa04b02..3fbea3c415 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToOptionalConverter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToOptionalConverter.java @@ -32,7 +32,6 @@ public class StringToOptionalConverter implements StringConverter { return ofNullable(source); } - @Override public int getPriority() { return MIN_PRIORITY; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToShortConverter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToShortConverter.java index 6427b17de4..cd2cef3050 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToShortConverter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/convert/StringToShortConverter.java @@ -31,7 +31,6 @@ public class StringToShortConverter implements StringConverter { return isNotEmpty(source) ? valueOf(source) : null; } - @Override public int getPriority() { return NORMAL_PRIORITY + 2; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToArrayConverter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToArrayConverter.java index aab20facf3..41b710be95 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToArrayConverter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToArrayConverter.java @@ -59,7 +59,6 @@ public class StringToArrayConverter implements StringToMultiValueConverter { return array; } - @Override public int getPriority() { return MIN_PRIORITY; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToIterableConverter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToIterableConverter.java index ad9fec9eb1..067f1f6118 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToIterableConverter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToIterableConverter.java @@ -39,7 +39,6 @@ public abstract class StringToIterableConverter implements S converterUtil = frameworkModel.getBeanFactory().getBean(ConverterUtil.class); } - public boolean accept(Class type, Class multiValueType) { return isAssignableFrom(getSupportedType(), multiValueType); } @@ -49,22 +48,23 @@ public abstract class StringToIterableConverter implements S Optional stringConverter = getStringConverter(elementType); - return stringConverter.map(converter -> { + return stringConverter + .map(converter -> { + T convertedObject = createMultiValue(size, multiValueType); - T convertedObject = createMultiValue(size, multiValueType); + if (convertedObject instanceof Collection) { + Collection collection = (Collection) convertedObject; + for (int i = 0; i < size; i++) { + String segment = segments[i]; + Object element = converter.convert(segment); + collection.add(element); + } + return collection; + } - if (convertedObject instanceof Collection) { - Collection collection = (Collection) convertedObject; - for (int i = 0; i < size; i++) { - String segment = segments[i]; - Object element = converter.convert(segment); - collection.add(element); - } - return collection; - } - - return convertedObject; - }).orElse(null); + return convertedObject; + }) + .orElse(null); } protected abstract T createMultiValue(int size, Class multiValueType); @@ -80,8 +80,8 @@ public abstract class StringToIterableConverter implements S @Override public final int getPriority() { - int level = getAllInterfaces(getSupportedType(), type -> - isAssignableFrom(Iterable.class, type)).size(); + int level = getAllInterfaces(getSupportedType(), type -> isAssignableFrom(Iterable.class, type)) + .size(); return MIN_PRIORITY - level; } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToMultiValueConverter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToMultiValueConverter.java index 75fefe6a7e..f59fc5e906 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToMultiValueConverter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToMultiValueConverter.java @@ -40,7 +40,7 @@ public interface StringToMultiValueConverter extends MultiValueConverter String[] segments = split(source, ','); if (ArrayUtils.isEmpty(segments)) { // If empty array, create an array with only one element - segments = new String[]{source}; + segments = new String[] {source}; } int size = segments.length; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/AbstractDeployer.java b/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/AbstractDeployer.java index 04ae6826c7..554f7f9c85 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/AbstractDeployer.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/AbstractDeployer.java @@ -109,7 +109,12 @@ public abstract class AbstractDeployer implements Deployer try { listener.onStarting(scopeModel); } catch (Throwable e) { - logger.error(COMMON_MONITOR_EXCEPTION, "", "", getIdentifier() + " an exception occurred when handle starting event", e); + logger.error( + COMMON_MONITOR_EXCEPTION, + "", + "", + getIdentifier() + " an exception occurred when handle starting event", + e); } } } @@ -120,7 +125,12 @@ public abstract class AbstractDeployer implements Deployer try { listener.onStarted(scopeModel); } catch (Throwable e) { - logger.error(COMMON_MONITOR_EXCEPTION, "", "", getIdentifier() + " an exception occurred when handle started event", e); + logger.error( + COMMON_MONITOR_EXCEPTION, + "", + "", + getIdentifier() + " an exception occurred when handle started event", + e); } } } @@ -131,7 +141,12 @@ public abstract class AbstractDeployer implements Deployer try { listener.onStopping(scopeModel); } catch (Throwable e) { - logger.error(COMMON_MONITOR_EXCEPTION, "", "", getIdentifier() + " an exception occurred when handle stopping event", e); + logger.error( + COMMON_MONITOR_EXCEPTION, + "", + "", + getIdentifier() + " an exception occurred when handle stopping event", + e); } } } @@ -142,7 +157,12 @@ public abstract class AbstractDeployer implements Deployer try { listener.onStopped(scopeModel); } catch (Throwable e) { - logger.error(COMMON_MONITOR_EXCEPTION, "", "", getIdentifier() + " an exception occurred when handle stopped event", e); + logger.error( + COMMON_MONITOR_EXCEPTION, + "", + "", + getIdentifier() + " an exception occurred when handle stopped event", + e); } } } @@ -154,7 +174,12 @@ public abstract class AbstractDeployer implements Deployer try { listener.onFailure(scopeModel, error); } catch (Throwable e) { - logger.error(COMMON_MONITOR_EXCEPTION, "", "", getIdentifier() + " an exception occurred when handle failed event", e); + logger.error( + COMMON_MONITOR_EXCEPTION, + "", + "", + getIdentifier() + " an exception occurred when handle failed event", + e); } } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/ApplicationDeployListener.java b/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/ApplicationDeployListener.java index f045c4259d..4df97d8121 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/ApplicationDeployListener.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/ApplicationDeployListener.java @@ -26,7 +26,5 @@ import org.apache.dubbo.rpc.model.ApplicationModel; @SPI(scope = ExtensionScope.APPLICATION) public interface ApplicationDeployListener extends DeployListener { - default void onModuleStarted(ApplicationModel applicationModel) { - - } + default void onModuleStarted(ApplicationModel applicationModel) {} } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/DeployListener.java b/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/DeployListener.java index 94d31bbd64..b52455bbc4 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/DeployListener.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/DeployListener.java @@ -33,5 +33,4 @@ public interface DeployListener { void onStopped(E scopeModel); void onFailure(E scopeModel, Throwable cause); - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/DeployListenerAdapter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/DeployListenerAdapter.java index 925747dae4..6a34b7dced 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/DeployListenerAdapter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/DeployListenerAdapter.java @@ -18,29 +18,22 @@ package org.apache.dubbo.common.deploy; import org.apache.dubbo.rpc.model.ScopeModel; -public class DeployListenerAdapter implements DeployListener{ +public class DeployListenerAdapter implements DeployListener { @Override - public void onInitialize(E scopeModel) { - - } + public void onInitialize(E scopeModel) {} @Override - public void onStarting(E scopeModel) { - } + public void onStarting(E scopeModel) {} @Override - public void onStarted(E scopeModel) { - } + public void onStarted(E scopeModel) {} @Override - public void onStopping(E scopeModel) { - } + public void onStopping(E scopeModel) {} @Override - public void onStopped(E scopeModel) { - } + public void onStopped(E scopeModel) {} @Override - public void onFailure(E scopeModel, Throwable cause) { - } + public void onFailure(E scopeModel, Throwable cause) {} } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/ModuleDeployListener.java b/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/ModuleDeployListener.java index bf76984d25..06eadd3798 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/ModuleDeployListener.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/deploy/ModuleDeployListener.java @@ -24,6 +24,4 @@ import org.apache.dubbo.rpc.model.ModuleModel; * Module deploy listener */ @SPI(scope = ExtensionScope.MODULE) -public interface ModuleDeployListener extends DeployListener { - -} +public interface ModuleDeployListener extends DeployListener {} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/Activate.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/Activate.java index 9b13e7212d..53344314c7 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/Activate.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/Activate.java @@ -96,5 +96,5 @@ public @interface Activate { * Activate loadClass when the current extension when the specified className all match * @return className names to all match */ - String [] onClass() default {}; + String[] onClass() default {}; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/Adaptive.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/Adaptive.java index b209a2f93c..9e46831888 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/Adaptive.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/Adaptive.java @@ -56,5 +56,4 @@ public @interface Adaptive { * @return parameter names in URL */ String[] value() default {}; - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/AdaptiveClassCodeGenerator.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/AdaptiveClassCodeGenerator.java index 1c9517f7ae..fd51fa15cc 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/AdaptiveClassCodeGenerator.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/AdaptiveClassCodeGenerator.java @@ -54,21 +54,25 @@ public class AdaptiveClassCodeGenerator { private static final String CODE_METHOD_THROWS = "throws %s"; - private static final String CODE_UNSUPPORTED = "throw new UnsupportedOperationException(\"The method %s of interface %s is not adaptive method!\");\n"; + private static final String CODE_UNSUPPORTED = + "throw new UnsupportedOperationException(\"The method %s of interface %s is not adaptive method!\");\n"; - private static final String CODE_URL_NULL_CHECK = "if (arg%d == null) throw new IllegalArgumentException(\"url == null\");\n%s url = arg%d;\n"; + private static final String CODE_URL_NULL_CHECK = + "if (arg%d == null) throw new IllegalArgumentException(\"url == null\");\n%s url = arg%d;\n"; private static final String CODE_EXT_NAME_ASSIGNMENT = "String extName = %s;\n"; private static final String CODE_EXT_NAME_NULL_CHECK = "if(extName == null) " - + "throw new IllegalStateException(\"Failed to get extension (%s) name from url (\" + url.toString() + \") use keys(%s)\");\n"; + + "throw new IllegalStateException(\"Failed to get extension (%s) name from url (\" + url.toString() + \") use keys(%s)\");\n"; - private static final String CODE_INVOCATION_ARGUMENT_NULL_CHECK = "if (arg%d == null) throw new IllegalArgumentException(\"invocation == null\"); " + private static final String CODE_INVOCATION_ARGUMENT_NULL_CHECK = + "if (arg%d == null) throw new IllegalArgumentException(\"invocation == null\"); " + "String methodName = arg%d.getMethodName();\n"; - - private static final String CODE_SCOPE_MODEL_ASSIGNMENT = "ScopeModel scopeModel = ScopeModelUtil.getOrDefault(url.getScopeModel(), %s.class);\n"; - private static final String CODE_EXTENSION_ASSIGNMENT = "%s extension = (%[] pts = method.getParameterTypes(); return IntStream.range(0, pts.length) - .mapToObj(i -> String.format(CODE_METHOD_ARGUMENT, pts[i].getCanonicalName(), i)) - .collect(Collectors.joining(", ")); + .mapToObj(i -> String.format(CODE_METHOD_ARGUMENT, pts[i].getCanonicalName(), i)) + .collect(Collectors.joining(", ")); } /** @@ -271,17 +277,20 @@ public class AdaptiveClassCodeGenerator { if (null != defaultExtName) { if (!CommonConstants.PROTOCOL_KEY.equals(value[i])) { if (hasInvocation) { - getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName); + getNameCode = String.format( + "url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName); } else { getNameCode = String.format("url.getParameter(\"%s\", \"%s\")", value[i], defaultExtName); } } else { - getNameCode = String.format("( url.getProtocol() == null ? \"%s\" : url.getProtocol() )", defaultExtName); + getNameCode = String.format( + "( url.getProtocol() == null ? \"%s\" : url.getProtocol() )", defaultExtName); } } else { if (!CommonConstants.PROTOCOL_KEY.equals(value[i])) { if (hasInvocation) { - getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName); + getNameCode = String.format( + "url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName); } else { getNameCode = String.format("url.getParameter(\"%s\")", value[i]); } @@ -292,7 +301,8 @@ public class AdaptiveClassCodeGenerator { } else { if (!CommonConstants.PROTOCOL_KEY.equals(value[i])) { if (hasInvocation) { - getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName); + getNameCode = String.format( + "url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName); } else { getNameCode = String.format("url.getParameter(\"%s\", %s)", value[i], getNameCode); } @@ -342,9 +352,11 @@ public class AdaptiveClassCodeGenerator { */ private String generateInvocationArgumentNullCheck(Method method) { Class[] pts = method.getParameterTypes(); - return IntStream.range(0, pts.length).filter(i -> CLASS_NAME_INVOCATION.equals(pts[i].getName())) - .mapToObj(i -> String.format(CODE_INVOCATION_ARGUMENT_NULL_CHECK, i, i)) - .findFirst().orElse(""); + return IntStream.range(0, pts.length) + .filter(i -> CLASS_NAME_INVOCATION.equals(pts[i].getName())) + .mapToObj(i -> String.format(CODE_INVOCATION_ARGUMENT_NULL_CHECK, i, i)) + .findFirst() + .orElse(""); } /** @@ -355,7 +367,7 @@ public class AdaptiveClassCodeGenerator { // value is not set, use the value generated from class name as the key if (value.length == 0) { String splitName = StringUtils.camelToSplitName(type.getSimpleName(), "."); - value = new String[]{splitName}; + value = new String[] {splitName}; } return value; } @@ -395,7 +407,8 @@ public class AdaptiveClassCodeGenerator { if (index != null) { return generateGetUrlNullCheck(index, pts[index], "getUrl"); } else { - Map.Entry entry = getterReturnUrl.entrySet().iterator().next(); + Map.Entry entry = + getterReturnUrl.entrySet().iterator().next(); return generateGetUrlNullCheck(entry.getValue(), pts[entry.getValue()], entry.getKey()); } } @@ -408,13 +421,14 @@ public class AdaptiveClassCodeGenerator { private String generateGetUrlNullCheck(int index, Class type, String method) { // Null point check StringBuilder code = new StringBuilder(); - code.append(String.format("if (arg%d == null) throw new IllegalArgumentException(\"%s argument == null\");\n", + code.append(String.format( + "if (arg%d == null) throw new IllegalArgumentException(\"%s argument == null\");\n", index, type.getName())); - code.append(String.format("if (arg%d.%s() == null) throw new IllegalArgumentException(\"%s argument %s() == null\");\n", + code.append(String.format( + "if (arg%d.%s() == null) throw new IllegalArgumentException(\"%s argument %s() == null\");\n", index, method, type.getName(), method)); code.append(String.format("%s url = arg%d.%s();\n", URL.class.getName(), index, method)); return code.toString(); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/DisableInject.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/DisableInject.java index 577a28df6b..c207c9028a 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/DisableInject.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/DisableInject.java @@ -25,5 +25,4 @@ import java.lang.annotation.Target; @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) -public @interface DisableInject { -} +public @interface DisableInject {} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionAccessor.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionAccessor.java index be13080d37..14c4882b60 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionAccessor.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionAccessor.java @@ -41,5 +41,4 @@ public interface ExtensionAccessor { ExtensionLoader extensionLoader = getExtensionLoader(type); return extensionLoader != null ? extensionLoader.getDefaultExtension() : null; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionAccessorAware.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionAccessorAware.java index b0ca06ec2f..943cba0773 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionAccessorAware.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionAccessorAware.java @@ -22,5 +22,4 @@ package org.apache.dubbo.common.extension; public interface ExtensionAccessorAware { void setExtensionAccessor(final ExtensionAccessor extensionAccessor); - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionDirector.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionDirector.java index 9790be7ae4..ecf08eb995 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionDirector.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionDirector.java @@ -73,8 +73,8 @@ public class ExtensionDirector implements ExtensionAccessor { throw new IllegalArgumentException("Extension type (" + type + ") is not an interface!"); } if (!withExtensionAnnotation(type)) { - throw new IllegalArgumentException("Extension type (" + type + - ") is not an extension, because it is NOT annotated with @" + SPI.class.getSimpleName() + "!"); + throw new IllegalArgumentException("Extension type (" + type + + ") is not an extension, because it is NOT annotated with @" + SPI.class.getSimpleName() + "!"); } // 1. find in local cache @@ -138,8 +138,7 @@ public class ExtensionDirector implements ExtensionAccessor { return parent; } - public void removeAllCachedLoader() { - } + public void removeAllCachedLoader() {} public void destroy() { if (destroyed.compareAndSet(false, true)) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionInjector.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionInjector.java index 0441c120f7..d043b5d4dc 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionInjector.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionInjector.java @@ -32,6 +32,5 @@ public interface ExtensionInjector extends ExtensionAccessorAware { T getInstance(final Class type, final String name); @Override - default void setExtensionAccessor(final ExtensionAccessor extensionAccessor) { - } + default void setExtensionAccessor(final ExtensionAccessor extensionAccessor) {} } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java index 2c44831c54..35c190b5f8 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionLoader.java @@ -105,11 +105,9 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILE * @see org.apache.dubbo.common.extension.Adaptive * @see org.apache.dubbo.common.extension.Activate */ - public class ExtensionLoader { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger( - ExtensionLoader.class); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ExtensionLoader.class); private static final Pattern NAME_SEPARATOR = Pattern.compile("\\s*[,]+\\s*"); private static final String SPECIAL_SPI_PROPERTIES = "special_spi.properties"; @@ -124,12 +122,9 @@ public class ExtensionLoader { private final Holder>> cachedClasses = new Holder<>(); - private final Map cachedActivates = Collections.synchronizedMap( - new LinkedHashMap<>()); - private final Map> cachedActivateGroups = Collections.synchronizedMap( - new LinkedHashMap<>()); - private final Map cachedActivateValues = Collections.synchronizedMap( - new LinkedHashMap<>()); + private final Map cachedActivates = Collections.synchronizedMap(new LinkedHashMap<>()); + private final Map> cachedActivateGroups = Collections.synchronizedMap(new LinkedHashMap<>()); + private final Map cachedActivateValues = Collections.synchronizedMap(new LinkedHashMap<>()); private final ConcurrentMap> cachedInstances = new ConcurrentHashMap<>(); private final Holder cachedAdaptiveInstance = new Holder<>(); private volatile Class cachedAdaptiveClass = null; @@ -144,8 +139,8 @@ public class ExtensionLoader { private static final Map specialSPILoadingStrategyMap = getSpecialSPILoadingStrategyMap(); - private static SoftReference>> urlListMapCache = new SoftReference<>( - new ConcurrentHashMap<>()); + private static SoftReference>> urlListMapCache = + new SoftReference<>(new ConcurrentHashMap<>()); private static final List ignoredInjectMethodsDesc = getIgnoredInjectMethodsDesc(); @@ -153,6 +148,7 @@ public class ExtensionLoader { * Record all unacceptable exceptions when using SPI */ private final Set unacceptableExceptions = new ConcurrentHashSet<>(); + private final ExtensionDirector extensionDirector; private final List extensionPostProcessors; private InstantiationStrategy instantiationStrategy; @@ -173,8 +169,7 @@ public class ExtensionLoader { * @since 2.7.7 */ private static LoadingStrategy[] loadLoadingStrategies() { - return stream(load(LoadingStrategy.class).spliterator(), false).sorted() - .toArray(LoadingStrategy[]::new); + return stream(load(LoadingStrategy.class).spliterator(), false).sorted().toArray(LoadingStrategy[]::new); } /** @@ -185,8 +180,7 @@ public class ExtensionLoader { */ private static Map getSpecialSPILoadingStrategyMap() { Map map = new ConcurrentHashMap<>(); - Properties properties = loadProperties(ExtensionLoader.class.getClassLoader(), - SPECIAL_SPI_PROPERTIES); + Properties properties = loadProperties(ExtensionLoader.class.getClassLoader(), SPECIAL_SPI_PROPERTIES); map.putAll(properties); return map; } @@ -205,10 +199,12 @@ public class ExtensionLoader { private static List getIgnoredInjectMethodsDesc() { List ignoreInjectMethodsDesc = new ArrayList<>(); - Arrays.stream(ScopeModelAware.class.getMethods()).map(ReflectUtils::getDesc) - .forEach(ignoreInjectMethodsDesc::add); - Arrays.stream(ExtensionAccessorAware.class.getMethods()).map(ReflectUtils::getDesc) - .forEach(ignoreInjectMethodsDesc::add); + Arrays.stream(ScopeModelAware.class.getMethods()) + .map(ReflectUtils::getDesc) + .forEach(ignoreInjectMethodsDesc::add); + Arrays.stream(ExtensionAccessorAware.class.getMethods()) + .map(ReflectUtils::getDesc) + .forEach(ignoreInjectMethodsDesc::add); return ignoreInjectMethodsDesc; } @@ -217,19 +213,19 @@ public class ExtensionLoader { this.extensionDirector = extensionDirector; this.extensionPostProcessors = extensionDirector.getExtensionPostProcessors(); initInstantiationStrategy(); - this.injector = (type == ExtensionInjector.class ? - null : - extensionDirector.getExtensionLoader(ExtensionInjector.class).getAdaptiveExtension()); + this.injector = (type == ExtensionInjector.class + ? null + : extensionDirector.getExtensionLoader(ExtensionInjector.class).getAdaptiveExtension()); this.activateComparator = new ActivateComparator(extensionDirector); this.scopeModel = scopeModel; } private void initInstantiationStrategy() { instantiationStrategy = extensionPostProcessors.stream() - .filter(extensionPostProcessor -> extensionPostProcessor instanceof ScopeModelAccessor) - .map(extensionPostProcessor -> new InstantiationStrategy( - (ScopeModelAccessor) extensionPostProcessor)).findFirst() - .orElse(new InstantiationStrategy()); + .filter(extensionPostProcessor -> extensionPostProcessor instanceof ScopeModelAccessor) + .map(extensionPostProcessor -> new InstantiationStrategy((ScopeModelAccessor) extensionPostProcessor)) + .findFirst() + .orElse(new InstantiationStrategy()); } /** @@ -245,8 +241,7 @@ public class ExtensionLoader { } @Deprecated - public static void resetExtensionLoader(Class type) { - } + public static void resetExtensionLoader(Class type) {} public void destroy() { if (!destroyed.compareAndSet(false, true)) { @@ -259,8 +254,7 @@ public class ExtensionLoader { try { disposable.destroy(); } catch (Exception e) { - logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", - "Error destroying extension " + disposable, e); + logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", "Error destroying extension " + disposable, e); } } }); @@ -274,8 +268,7 @@ public class ExtensionLoader { try { disposable.destroy(); } catch (Exception e) { - logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", - "Error destroying extension " + disposable, e); + logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", "Error destroying extension " + disposable, e); } } } @@ -293,7 +286,7 @@ public class ExtensionLoader { } public String getExtensionName(Class extensionClass) { - getExtensionClasses();// load class + getExtensionClasses(); // load class return cachedNames.get(extensionClass); } @@ -332,8 +325,7 @@ public class ExtensionLoader { */ public List getActivateExtension(URL url, String key, String group) { String value = url.getParameter(key); - return getActivateExtension(url, - StringUtils.isEmpty(value) ? null : COMMA_SPLIT_PATTERN.split(value), group); + return getActivateExtension(url, StringUtils.isEmpty(value) ? null : COMMA_SPLIT_PATTERN.split(value), group); } /** @@ -350,9 +342,9 @@ public class ExtensionLoader { checkDestroyed(); // solve the bug of using @SPI's wrapper method to report a null pointer exception. Map, T> activateExtensionsMap = new TreeMap<>(activateComparator); - List names = values == null ? - new ArrayList<>(0) : - Arrays.stream(values).map(StringUtils::trim).collect(Collectors.toList()); + List names = values == null + ? new ArrayList<>(0) + : Arrays.stream(values).map(StringUtils::trim).collect(Collectors.toList()); Set namesSet = new HashSet<>(names); if (!namesSet.contains(REMOVE_VALUE_PREFIX + DEFAULT_KEY)) { if (cachedActivateGroups.size() == 0) { @@ -369,15 +361,15 @@ public class ExtensionLoader { if (activate instanceof Activate) { activateGroup = ((Activate) activate).group(); activateValue = ((Activate) activate).value(); - } else if (Dubbo2CompactUtils.isEnabled() && Dubbo2ActivateUtils.isActivateLoaded() - && Dubbo2ActivateUtils.getActivateClass().isAssignableFrom(activate.getClass())) { + } else if (Dubbo2CompactUtils.isEnabled() + && Dubbo2ActivateUtils.isActivateLoaded() + && Dubbo2ActivateUtils.getActivateClass().isAssignableFrom(activate.getClass())) { activateGroup = Dubbo2ActivateUtils.getGroup((Annotation) activate); activateValue = Dubbo2ActivateUtils.getValue((Annotation) activate); } else { continue; } - cachedActivateGroups.put(name, - new HashSet<>(Arrays.asList(activateGroup))); + cachedActivateGroups.put(name, new HashSet<>(Arrays.asList(activateGroup))); String[][] keyPairs = new String[activateValue.length][]; for (int i = 0; i < activateValue.length; i++) { if (activateValue[i].contains(":")) { @@ -398,9 +390,10 @@ public class ExtensionLoader { // traverse all cached extensions cachedActivateGroups.forEach((name, activateGroup) -> { - if (isMatchGroup(group, activateGroup) && !namesSet.contains( - name) && !namesSet.contains(REMOVE_VALUE_PREFIX + name) && isActive( - cachedActivateValues.get(name), url)) { + if (isMatchGroup(group, activateGroup) + && !namesSet.contains(name) + && !namesSet.contains(REMOVE_VALUE_PREFIX + name) + && isActive(cachedActivateValues.get(name), url)) { activateExtensionsMap.put(getExtensionClass(name), getExtension(name)); } @@ -409,12 +402,11 @@ public class ExtensionLoader { if (namesSet.contains(DEFAULT_KEY)) { // will affect order - // `ext1,default,ext2` means ext1 will happens before all of the default extensions while ext2 will after them - ArrayList extensionsResult = new ArrayList<>( - activateExtensionsMap.size() + names.size()); + // `ext1,default,ext2` means ext1 will happens before all of the default extensions while ext2 will after + // them + ArrayList extensionsResult = new ArrayList<>(activateExtensionsMap.size() + names.size()); for (String name : names) { - if (name.startsWith(REMOVE_VALUE_PREFIX) || namesSet.contains( - REMOVE_VALUE_PREFIX + name)) { + if (name.startsWith(REMOVE_VALUE_PREFIX) || namesSet.contains(REMOVE_VALUE_PREFIX + name)) { continue; } if (DEFAULT_KEY.equals(name)) { @@ -429,8 +421,7 @@ public class ExtensionLoader { } else { // add extensions, will be sorted by its order for (String name : names) { - if (name.startsWith(REMOVE_VALUE_PREFIX) || namesSet.contains( - REMOVE_VALUE_PREFIX + name)) { + if (name.startsWith(REMOVE_VALUE_PREFIX) || namesSet.contains(REMOVE_VALUE_PREFIX + name)) { continue; } if (DEFAULT_KEY.equals(name)) { @@ -493,8 +484,8 @@ public class ExtensionLoader { if (StringUtils.isEmpty(realValue)) { realValue = url.getAnyMethodParameter(key); } - if ((keyValue != null && keyValue.equals( - realValue)) || (keyValue == null && ConfigUtils.isNotEmpty(realValue))) { + if ((keyValue != null && keyValue.equals(realValue)) + || (keyValue == null && ConfigUtils.isNotEmpty(realValue))) { return true; } } @@ -657,8 +648,7 @@ public class ExtensionLoader { getExtensionClasses(); // load classes if (!type.isAssignableFrom(clazz)) { - throw new IllegalStateException( - "Input type " + clazz + " doesn't implement the Extension " + type); + throw new IllegalStateException("Input type " + clazz + " doesn't implement the Extension " + type); } if (clazz.isInterface()) { throw new IllegalStateException("Input type " + clazz + " can't be interface!"); @@ -666,20 +656,17 @@ public class ExtensionLoader { if (!clazz.isAnnotationPresent(Adaptive.class)) { if (StringUtils.isBlank(name)) { - throw new IllegalStateException( - "Extension name is blank (Extension " + type + ")!"); + throw new IllegalStateException("Extension name is blank (Extension " + type + ")!"); } if (cachedClasses.get().containsKey(name)) { - throw new IllegalStateException( - "Extension name " + name + " already exists (Extension " + type + ")!"); + throw new IllegalStateException("Extension name " + name + " already exists (Extension " + type + ")!"); } cachedNames.put(clazz, name); cachedClasses.get().put(name, clazz); } else { if (cachedAdaptiveClass != null) { - throw new IllegalStateException( - "Adaptive Extension already exists (Extension " + type + ")!"); + throw new IllegalStateException("Adaptive Extension already exists (Extension " + type + ")!"); } cachedAdaptiveClass = clazz; @@ -700,8 +687,7 @@ public class ExtensionLoader { getExtensionClasses(); // load classes if (!type.isAssignableFrom(clazz)) { - throw new IllegalStateException( - "Input type " + clazz + " doesn't implement Extension " + type); + throw new IllegalStateException("Input type " + clazz + " doesn't implement Extension " + type); } if (clazz.isInterface()) { throw new IllegalStateException("Input type " + clazz + " can't be interface!"); @@ -709,12 +695,10 @@ public class ExtensionLoader { if (!clazz.isAnnotationPresent(Adaptive.class)) { if (StringUtils.isBlank(name)) { - throw new IllegalStateException( - "Extension name is blank (Extension " + type + ")!"); + throw new IllegalStateException("Extension name is blank (Extension " + type + ")!"); } if (!cachedClasses.get().containsKey(name)) { - throw new IllegalStateException( - "Extension name " + name + " doesn't exist (Extension " + type + ")!"); + throw new IllegalStateException("Extension name " + name + " doesn't exist (Extension " + type + ")!"); } cachedNames.put(clazz, name); @@ -722,8 +706,7 @@ public class ExtensionLoader { cachedInstances.remove(name); } else { if (cachedAdaptiveClass == null) { - throw new IllegalStateException( - "Adaptive Extension doesn't exist (Extension " + type + ")!"); + throw new IllegalStateException("Adaptive Extension doesn't exist (Extension " + type + ")!"); } cachedAdaptiveClass = clazz; @@ -738,8 +721,8 @@ public class ExtensionLoader { if (instance == null) { if (createAdaptiveInstanceError != null) { throw new IllegalStateException( - "Failed to create adaptive instance: " + createAdaptiveInstanceError.toString(), - createAdaptiveInstanceError); + "Failed to create adaptive instance: " + createAdaptiveInstanceError.toString(), + createAdaptiveInstanceError); } synchronized (cachedAdaptiveInstance) { @@ -750,8 +733,7 @@ public class ExtensionLoader { cachedAdaptiveInstance.set(instance); } catch (Throwable t) { createAdaptiveInstanceError = t; - throw new IllegalStateException( - "Failed to create adaptive instance: " + t.toString(), t); + throw new IllegalStateException("Failed to create adaptive instance: " + t.toString(), t); } } } @@ -761,8 +743,7 @@ public class ExtensionLoader { } private IllegalStateException findException(String name) { - StringBuilder buf = new StringBuilder( - "No such extension " + type.getName() + " by name " + name); + StringBuilder buf = new StringBuilder("No such extension " + type.getName() + " by name " + name); int i = 1; for (Map.Entry entry : exceptions.entrySet()) { @@ -780,8 +761,7 @@ public class ExtensionLoader { } if (i == 1) { - buf.append( - ", no related exception was found, please check whether related SPI module is missing."); + buf.append(", no related exception was found, please check whether related SPI module is missing."); } return new IllegalStateException(buf.toString()); } @@ -813,25 +793,28 @@ public class ExtensionLoader { if (CollectionUtils.isNotEmpty(wrapperClassesList)) { for (Class wrapperClass : wrapperClassesList) { Wrapper wrapper = wrapperClass.getAnnotation(Wrapper.class); - boolean match = (wrapper == null) || ((ArrayUtils.isEmpty( - wrapper.matches()) || ArrayUtils.contains(wrapper.matches(), - name)) && !ArrayUtils.contains(wrapper.mismatches(), name)); + boolean match = (wrapper == null) + || ((ArrayUtils.isEmpty(wrapper.matches()) + || ArrayUtils.contains(wrapper.matches(), name)) + && !ArrayUtils.contains(wrapper.mismatches(), name)); if (match) { instance = injectExtension( - (T) wrapperClass.getConstructor(type).newInstance(instance)); + (T) wrapperClass.getConstructor(type).newInstance(instance)); instance = postProcessAfterInitialization(instance, name); } } } } - // Warning: After an instance of Lifecycle is wrapped by cachedWrapperClasses, it may not still be Lifecycle instance, this application may not invoke the lifecycle.initialize hook. + // Warning: After an instance of Lifecycle is wrapped by cachedWrapperClasses, it may not still be Lifecycle + // instance, this application may not invoke the lifecycle.initialize hook. initExtension(instance); return instance; } catch (Throwable t) { throw new IllegalStateException( - "Extension instance (name: " + name + ", class: " + type + ") couldn't be instantiated: " + t.getMessage(), - t); + "Extension instance (name: " + name + ", class: " + type + ") couldn't be instantiated: " + + t.getMessage(), + t); } } @@ -906,9 +889,13 @@ public class ExtensionLoader { method.invoke(instance, object); } } catch (Exception e) { - logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", - "Failed to inject via method " + method.getName() + " of interface " + type.getName() + ": " + e.getMessage(), - e); + logger.error( + COMMON_ERROR_LOAD_EXTENSION, + "", + "", + "Failed to inject via method " + method.getName() + " of interface " + type.getName() + ": " + + e.getMessage(), + e); } } } catch (Exception e) { @@ -930,9 +917,10 @@ public class ExtensionLoader { * return "", if setter name with length less than 3 */ private String getSetterProperty(Method method) { - return method.getName().length() > 3 ? - method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4) : - ""; + return method.getName().length() > 3 + ? method.getName().substring(3, 4).toLowerCase() + + method.getName().substring(4) + : ""; } /** @@ -945,9 +933,9 @@ public class ExtensionLoader { * 3, only has one parameter */ private boolean isSetter(Method method) { - return method.getName() - .startsWith("set") && method.getParameterTypes().length == 1 && Modifier.isPublic( - method.getModifiers()); + return method.getName().startsWith("set") + && method.getParameterTypes().length == 1 + && Modifier.isPublic(method.getModifiers()); } private Class getExtensionClass(String name) { @@ -969,12 +957,14 @@ public class ExtensionLoader { try { classes = loadExtensionClasses(); } catch (InterruptedException e) { - logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", - "Exception occurred when loading extension class (interface: " + type + ")", - e); + logger.error( + COMMON_ERROR_LOAD_EXTENSION, + "", + "", + "Exception occurred when loading extension class (interface: " + type + ")", + e); throw new IllegalStateException( - "Exception occurred when loading extension class (interface: " + type + ")", - e); + "Exception occurred when loading extension class (interface: " + type + ")", e); } cachedClasses.set(classes); } @@ -1005,8 +995,8 @@ public class ExtensionLoader { return extensionClasses; } - private void loadDirectory(Map> extensionClasses, LoadingStrategy strategy, - String type) throws InterruptedException { + private void loadDirectory(Map> extensionClasses, LoadingStrategy strategy, String type) + throws InterruptedException { loadDirectoryInternal(extensionClasses, strategy, type); if (Dubbo2CompactUtils.isEnabled()) { try { @@ -1014,7 +1004,7 @@ public class ExtensionLoader { if (oldType.equals(type)) { return; } - //if class not found,skip try to load resources + // if class not found,skip try to load resources ClassUtils.forName(oldType); loadDirectoryInternal(extensionClasses, strategy, oldType); } catch (ClassNotFoundException classNotFoundException) { @@ -1036,9 +1026,8 @@ public class ExtensionLoader { if ((value = value.trim()).length() > 0) { String[] names = NAME_SEPARATOR.split(value); if (names.length > 1) { - throw new IllegalStateException( - "More than 1 default extension name on extension " + type.getName() + ": " + Arrays.toString( - names)); + throw new IllegalStateException("More than 1 default extension name on extension " + type.getName() + + ": " + Arrays.toString(names)); } if (names.length == 1) { cachedDefaultName = names[0]; @@ -1046,9 +1035,9 @@ public class ExtensionLoader { } } - private void loadDirectoryInternal(Map> extensionClasses, - LoadingStrategy loadingStrategy, String type) - throws InterruptedException { + private void loadDirectoryInternal( + Map> extensionClasses, LoadingStrategy loadingStrategy, String type) + throws InterruptedException { String fileName = loadingStrategy.directory() + type; try { List classLoadersToLoad = new LinkedList<>(); @@ -1063,10 +1052,9 @@ public class ExtensionLoader { if (specialSPILoadingStrategyMap.containsKey(type)) { String internalDirectoryType = specialSPILoadingStrategyMap.get(type); - //skip to load spi when name don't match - if (!LoadingStrategy.ALL.equals( - internalDirectoryType) && !internalDirectoryType.equals( - loadingStrategy.getName())) { + // skip to load spi when name don't match + if (!LoadingStrategy.ALL.equals(internalDirectoryType) + && !internalDirectoryType.equals(loadingStrategy.getName())) { return; } classLoadersToLoad.clear(); @@ -1079,10 +1067,14 @@ public class ExtensionLoader { Enumeration resources = ClassLoader.getSystemResources(fileName); if (resources != null) { while (resources.hasMoreElements()) { - loadResource(extensionClasses, null, resources.nextElement(), - loadingStrategy.overridden(), loadingStrategy.includedPackages(), - loadingStrategy.excludedPackages(), - loadingStrategy.onlyExtensionClassLoaderPackages()); + loadResource( + extensionClasses, + null, + resources.nextElement(), + loadingStrategy.overridden(), + loadingStrategy.includedPackages(), + loadingStrategy.excludedPackages(), + loadingStrategy.onlyExtensionClassLoaderPackages()); } } } else { @@ -1090,38 +1082,61 @@ public class ExtensionLoader { } } - Map> resources = ClassLoaderResourceLoader.loadResources( - fileName, classLoadersToLoad); + Map> resources = + ClassLoaderResourceLoader.loadResources(fileName, classLoadersToLoad); resources.forEach(((classLoader, urls) -> { - loadFromClass(extensionClasses, loadingStrategy.overridden(), urls, classLoader, - loadingStrategy.includedPackages(), loadingStrategy.excludedPackages(), - loadingStrategy.onlyExtensionClassLoaderPackages()); + loadFromClass( + extensionClasses, + loadingStrategy.overridden(), + urls, + classLoader, + loadingStrategy.includedPackages(), + loadingStrategy.excludedPackages(), + loadingStrategy.onlyExtensionClassLoaderPackages()); })); } catch (InterruptedException e) { throw e; } catch (Throwable t) { - logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", - "Exception occurred when loading extension class (interface: " + type + ", description file: " + fileName + ").", - t); + logger.error( + COMMON_ERROR_LOAD_EXTENSION, + "", + "", + "Exception occurred when loading extension class (interface: " + type + ", description file: " + + fileName + ").", + t); } } - private void loadFromClass(Map> extensionClasses, boolean overridden, - Set urls, ClassLoader classLoader, - String[] includedPackages, String[] excludedPackages, - String[] onlyExtensionClassLoaderPackages) { + private void loadFromClass( + Map> extensionClasses, + boolean overridden, + Set urls, + ClassLoader classLoader, + String[] includedPackages, + String[] excludedPackages, + String[] onlyExtensionClassLoaderPackages) { if (CollectionUtils.isNotEmpty(urls)) { for (java.net.URL url : urls) { - loadResource(extensionClasses, classLoader, url, overridden, includedPackages, - excludedPackages, onlyExtensionClassLoaderPackages); + loadResource( + extensionClasses, + classLoader, + url, + overridden, + includedPackages, + excludedPackages, + onlyExtensionClassLoaderPackages); } } } - private void loadResource(Map> extensionClasses, ClassLoader classLoader, - java.net.URL resourceURL, boolean overridden, - String[] includedPackages, String[] excludedPackages, - String[] onlyExtensionClassLoaderPackages) { + private void loadResource( + Map> extensionClasses, + ClassLoader classLoader, + java.net.URL resourceURL, + boolean overridden, + String[] includedPackages, + String[] excludedPackages, + String[] onlyExtensionClassLoaderPackages) { try { List newContentList = getResourceContent(resourceURL); String clazz; @@ -1135,25 +1150,35 @@ public class ExtensionLoader { } else { clazz = line; } - if (StringUtils.isNotEmpty(clazz) && !isExcluded(clazz, - excludedPackages) && isIncluded(clazz, - includedPackages) && !isExcludedByClassLoader(clazz, classLoader, - onlyExtensionClassLoaderPackages)) { + if (StringUtils.isNotEmpty(clazz) + && !isExcluded(clazz, excludedPackages) + && isIncluded(clazz, includedPackages) + && !isExcludedByClassLoader(clazz, classLoader, onlyExtensionClassLoaderPackages)) { - loadClass(classLoader, extensionClasses, resourceURL, - Class.forName(clazz, true, classLoader), name, overridden); + loadClass( + classLoader, + extensionClasses, + resourceURL, + Class.forName(clazz, true, classLoader), + name, + overridden); } } catch (Throwable t) { IllegalStateException e = new IllegalStateException( - "Failed to load extension class (interface: " + type + ", class line: " + line + ") in " + resourceURL + ", cause: " + t.getMessage(), - t); + "Failed to load extension class (interface: " + type + ", class line: " + line + ") in " + + resourceURL + ", cause: " + t.getMessage(), + t); exceptions.put(line, e); } } } catch (Throwable t) { - logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", - "Exception occurred when loading extension class (interface: " + type + ", class file: " + resourceURL + ") in " + resourceURL, - t); + logger.error( + COMMON_ERROR_LOAD_EXTENSION, + "", + "", + "Exception occurred when loading extension class (interface: " + type + ", class file: " + + resourceURL + ") in " + resourceURL, + t); } } @@ -1171,8 +1196,8 @@ public class ExtensionLoader { List contentList = urlListMap.computeIfAbsent(resourceURL, key -> { List newContentList = new ArrayList<>(); - try (BufferedReader reader = new BufferedReader( - new InputStreamReader(resourceURL.openStream(), StandardCharsets.UTF_8))) { + try (BufferedReader reader = + new BufferedReader(new InputStreamReader(resourceURL.openStream(), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { final int ci = line.indexOf('#'); @@ -1218,8 +1243,8 @@ public class ExtensionLoader { return false; } - private boolean isExcludedByClassLoader(String className, ClassLoader classLoader, - String... onlyExtensionClassLoaderPackages) { + private boolean isExcludedByClassLoader( + String className, ClassLoader classLoader, String... onlyExtensionClassLoaderPackages) { if (onlyExtensionClassLoaderPackages != null) { for (String excludePackage : onlyExtensionClassLoaderPackages) { if (className.startsWith(excludePackage + ".")) { @@ -1231,12 +1256,17 @@ public class ExtensionLoader { return false; } - private void loadClass(ClassLoader classLoader, Map> extensionClasses, - java.net.URL resourceURL, Class clazz, String name, - boolean overridden) { + private void loadClass( + ClassLoader classLoader, + Map> extensionClasses, + java.net.URL resourceURL, + Class clazz, + String name, + boolean overridden) { if (!type.isAssignableFrom(clazz)) { throw new IllegalStateException( - "Error occurred when loading extension class (interface: " + type + ", class line: " + clazz.getName() + "), class " + clazz.getName() + " is not subtype of interface."); + "Error occurred when loading extension class (interface: " + type + ", class line: " + + clazz.getName() + "), class " + clazz.getName() + " is not subtype of interface."); } boolean isActive = loadClassIfActive(classLoader, clazz); @@ -1253,8 +1283,8 @@ public class ExtensionLoader { if (StringUtils.isEmpty(name)) { name = findAnnotationName(clazz); if (name.length() == 0) { - throw new IllegalStateException( - "No such extension name for the class " + clazz.getName() + " in the config " + resourceURL); + throw new IllegalStateException("No such extension name for the class " + clazz.getName() + + " in the config " + resourceURL); } } @@ -1279,16 +1309,18 @@ public class ExtensionLoader { if (activate instanceof Activate) { onClass = ((Activate) activate).onClass(); - } else if (Dubbo2CompactUtils.isEnabled() && Dubbo2ActivateUtils.isActivateLoaded() - && Dubbo2ActivateUtils.getActivateClass().isAssignableFrom(activate.getClass())) { + } else if (Dubbo2CompactUtils.isEnabled() + && Dubbo2ActivateUtils.isActivateLoaded() + && Dubbo2ActivateUtils.getActivateClass().isAssignableFrom(activate.getClass())) { onClass = Dubbo2ActivateUtils.getOnClass(activate); } boolean isActive = true; if (null != onClass && onClass.length > 0) { - isActive = Arrays.stream(onClass).filter(StringUtils::isNotBlank) - .allMatch(className -> ClassUtils.isPresent(className, classLoader)); + isActive = Arrays.stream(onClass) + .filter(StringUtils::isNotBlank) + .allMatch(className -> ClassUtils.isPresent(className, classLoader)); } return isActive; } @@ -1305,15 +1337,16 @@ public class ExtensionLoader { /** * put clazz in extensionClasses */ - private void saveInExtensionClass(Map> extensionClasses, Class clazz, - String name, boolean overridden) { + private void saveInExtensionClass( + Map> extensionClasses, Class clazz, String name, boolean overridden) { Class c = extensionClasses.get(name); if (c == null || overridden) { extensionClasses.put(name, clazz); } else if (c != clazz) { // duplicate implementation is unacceptable unacceptableExceptions.add(name); - String duplicateMsg = "Duplicate extension " + type.getName() + " name " + name + " on " + c.getName() + " and " + clazz.getName(); + String duplicateMsg = "Duplicate extension " + type.getName() + " name " + name + " on " + c.getName() + + " and " + clazz.getName(); logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", duplicateMsg); throw new IllegalStateException(duplicateMsg); } @@ -1329,10 +1362,9 @@ public class ExtensionLoader { Activate activate = clazz.getAnnotation(Activate.class); if (activate != null) { cachedActivates.put(name, activate); - } else if (Dubbo2CompactUtils.isEnabled() && Dubbo2ActivateUtils.isActivateLoaded()){ + } else if (Dubbo2CompactUtils.isEnabled() && Dubbo2ActivateUtils.isActivateLoaded()) { // support com.alibaba.dubbo.common.extension.Activate - Annotation oldActivate = clazz.getAnnotation( - Dubbo2ActivateUtils.getActivateClass()); + Annotation oldActivate = clazz.getAnnotation(Dubbo2ActivateUtils.getActivateClass()); if (oldActivate != null) { cachedActivates.put(name, oldActivate); } @@ -1347,7 +1379,7 @@ public class ExtensionLoader { cachedAdaptiveClass = clazz; } else if (!cachedAdaptiveClass.equals(clazz)) { throw new IllegalStateException( - "More than 1 adaptive class found: " + cachedAdaptiveClass.getName() + ", " + clazz.getName()); + "More than 1 adaptive class found: " + cachedAdaptiveClass.getName() + ", " + clazz.getName()); } } @@ -1403,7 +1435,7 @@ public class ExtensionLoader { return instance; } catch (Exception e) { throw new IllegalStateException( - "Can't create adaptive extension " + type + ", cause: " + e.getMessage(), e); + "Can't create adaptive extension " + type + ", cause: " + e.getMessage(), e); } } @@ -1426,8 +1458,9 @@ public class ExtensionLoader { } String code = new AdaptiveClassCodeGenerator(type, cachedDefaultName).generate(); - org.apache.dubbo.common.compiler.Compiler compiler = extensionDirector.getExtensionLoader( - org.apache.dubbo.common.compiler.Compiler.class).getAdaptiveExtension(); + org.apache.dubbo.common.compiler.Compiler compiler = extensionDirector + .getExtensionLoader(org.apache.dubbo.common.compiler.Compiler.class) + .getAdaptiveExtension(); return compiler.compile(type, code, classLoader); } @@ -1453,8 +1486,7 @@ public class ExtensionLoader { } } } catch (IOException ex) { - logger.error(CONFIG_FAILED_LOAD_ENV_VARIABLE, "", "", "load properties failed.", - ex); + logger.error(CONFIG_FAILED_LOAD_ENV_VARIABLE, "", "", "load properties failed.", ex); } } @@ -1480,5 +1512,4 @@ public class ExtensionLoader { } return properties; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionPostProcessor.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionPostProcessor.java index fcc4822809..af757e8221 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionPostProcessor.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/ExtensionPostProcessor.java @@ -28,5 +28,4 @@ public interface ExtensionPostProcessor { default Object postProcessAfterInitialization(Object instance, String name) throws Exception { return instance; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/LoadingStrategy.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/LoadingStrategy.java index 57a6e1750f..bbb2f82c5b 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/LoadingStrategy.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/LoadingStrategy.java @@ -64,7 +64,7 @@ public interface LoadingStrategy extends Prioritized { * @since 3.0.4 */ default String[] onlyExtensionClassLoaderPackages() { - return new String[]{}; + return new String[] {}; } /** diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/SPI.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/SPI.java index 47cd1fc646..970b443b96 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/SPI.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/SPI.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension; import java.lang.annotation.Documented; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/inject/AdaptiveExtensionInjector.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/inject/AdaptiveExtensionInjector.java index 8551338085..5531e8711c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/inject/AdaptiveExtensionInjector.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/inject/AdaptiveExtensionInjector.java @@ -36,8 +36,7 @@ public class AdaptiveExtensionInjector implements ExtensionInjector, Lifecycle { private Collection injectors = Collections.emptyList(); private ExtensionAccessor extensionAccessor; - public AdaptiveExtensionInjector() { - } + public AdaptiveExtensionInjector() {} @Override public void setExtensionAccessor(final ExtensionAccessor extensionAccessor) { @@ -48,24 +47,22 @@ public class AdaptiveExtensionInjector implements ExtensionInjector, Lifecycle { public void initialize() throws IllegalStateException { ExtensionLoader loader = extensionAccessor.getExtensionLoader(ExtensionInjector.class); injectors = loader.getSupportedExtensions().stream() - .map(loader::getExtension) - .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); + .map(loader::getExtension) + .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } @Override public T getInstance(final Class type, final String name) { return injectors.stream() - .map(injector -> injector.getInstance(type, name)) - .filter(Objects::nonNull) - .findFirst() - .orElse(null); + .map(injector -> injector.getInstance(type, name)) + .filter(Objects::nonNull) + .findFirst() + .orElse(null); } @Override - public void start() throws IllegalStateException { - } + public void start() throws IllegalStateException {} @Override - public void destroy() throws IllegalStateException { - } + public void destroy() throws IllegalStateException {} } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/inject/SpiExtensionInjector.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/inject/SpiExtensionInjector.java index e2bde42e3c..0350ffe6af 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/inject/SpiExtensionInjector.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/inject/SpiExtensionInjector.java @@ -25,7 +25,7 @@ import org.apache.dubbo.common.extension.SPI; * SpiExtensionInjector */ public class SpiExtensionInjector implements ExtensionInjector { - + private ExtensionAccessor extensionAccessor; @Override diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/support/ActivateComparator.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/support/ActivateComparator.java index 73016dcae9..400f2ea12b 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/support/ActivateComparator.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/support/ActivateComparator.java @@ -153,10 +153,10 @@ public class ActivateComparator implements Comparator> { info.before = activate.before(); info.after = activate.after(); info.order = activate.order(); - } else if (Dubbo2CompactUtils.isEnabled() && Dubbo2ActivateUtils.isActivateLoaded() && - clazz.isAnnotationPresent(Dubbo2ActivateUtils.getActivateClass())) { - Annotation activate = clazz.getAnnotation( - Dubbo2ActivateUtils.getActivateClass()); + } else if (Dubbo2CompactUtils.isEnabled() + && Dubbo2ActivateUtils.isActivateLoaded() + && clazz.isAnnotationPresent(Dubbo2ActivateUtils.getActivateClass())) { + Annotation activate = clazz.getAnnotation(Dubbo2ActivateUtils.getActivateClass()); info.before = Dubbo2ActivateUtils.getBefore(activate); info.after = Dubbo2ActivateUtils.getAfter(activate); info.order = Dubbo2ActivateUtils.getOrder(activate); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/support/WrapperComparator.java b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/support/WrapperComparator.java index 4fb19bf22b..6685675068 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/extension/support/WrapperComparator.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/extension/support/WrapperComparator.java @@ -66,11 +66,11 @@ public class WrapperComparator implements Comparator { // TODO: backward compatibility Activate activate = clazz.getAnnotation(Activate.class); info.order = activate.order(); - } else if (Dubbo2CompactUtils.isEnabled() && Dubbo2ActivateUtils.isActivateLoaded() && - clazz.isAnnotationPresent(Dubbo2ActivateUtils.getActivateClass())) { + } else if (Dubbo2CompactUtils.isEnabled() + && Dubbo2ActivateUtils.isActivateLoaded() + && clazz.isAnnotationPresent(Dubbo2ActivateUtils.getActivateClass())) { // TODO: backward compatibility - Annotation activate = clazz.getAnnotation( - Dubbo2ActivateUtils.getActivateClass()); + Annotation activate = clazz.getAnnotation(Dubbo2ActivateUtils.getActivateClass()); info.order = Dubbo2ActivateUtils.getOrder(activate); } else if (clazz.isAnnotationPresent(Wrapper.class)) { Wrapper wrapper = clazz.getAnnotation(Wrapper.class); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/function/Predicates.java b/dubbo-common/src/main/java/org/apache/dubbo/common/function/Predicates.java index f78a1ba3b8..af43c0723d 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/function/Predicates.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/function/Predicates.java @@ -70,5 +70,4 @@ public interface Predicates { static Predicate or(Predicate... predicates) { return of(predicates).reduce(Predicate::or).orElse(e -> true); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/function/Streams.java b/dubbo-common/src/main/java/org/apache/dubbo/common/function/Streams.java index 0c715a54c5..7940d56e3b 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/function/Streams.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/function/Streams.java @@ -68,5 +68,3 @@ public interface Streams { .orElse(null); } } - - diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/infra/InfraAdapter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/infra/InfraAdapter.java index 3784069d61..a30233c56e 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/infra/InfraAdapter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/infra/InfraAdapter.java @@ -26,7 +26,6 @@ import java.util.Map; * 1. get extra attributes from underlying infrastructures related to the instance on which Dubbo is currently deploying. * 2. get configurations from third-party systems which maybe useful for a specific component. */ - @SPI(scope = ExtensionScope.APPLICATION) public interface InfraAdapter { @@ -43,5 +42,4 @@ public interface InfraAdapter { * @return */ String getAttribute(String key); - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/io/Bytes.java b/dubbo-common/src/main/java/org/apache/dubbo/common/io/Bytes.java index 9e3a16a559..98007dffc7 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/io/Bytes.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/io/Bytes.java @@ -33,20 +33,20 @@ import java.util.zip.InflaterInputStream; /** * CodecUtils. */ - public class Bytes { - private static final String C64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; //default base64. - - private static final char[] BASE16 = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}, BASE64 = C64.toCharArray(); + private static final String C64 = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // default base64. + private static final char[] + BASE16 = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}, + BASE64 = C64.toCharArray(); private static final int MASK4 = 0x0f, MASK6 = 0x3f, MASK8 = 0xff; private static final Map DECODE_TABLE_MAP = new ConcurrentHashMap<>(); private static final ThreadLocal MD = new ThreadLocal<>(); - private Bytes() { - } + private Bytes() {} /** * byte array copy. @@ -266,8 +266,7 @@ public class Bytes { * @return short. */ public static short bytes2short(byte[] b, int off) { - return (short) (((b[off + 1] & 0xFF) << 0) + - ((b[off + 0]) << 8)); + return (short) (((b[off + 1] & 0xFF) << 0) + ((b[off + 0]) << 8)); } /** @@ -288,10 +287,10 @@ public class Bytes { * @return int. */ public static int bytes2int(byte[] b, int off) { - return ((b[off + 3] & 0xFF) << 0) + - ((b[off + 2] & 0xFF) << 8) + - ((b[off + 1] & 0xFF) << 16) + - ((b[off + 0]) << 24); + return ((b[off + 3] & 0xFF) << 0) + + ((b[off + 2] & 0xFF) << 8) + + ((b[off + 1] & 0xFF) << 16) + + ((b[off + 0]) << 24); } /** @@ -312,10 +311,10 @@ public class Bytes { * @return int. */ public static float bytes2float(byte[] b, int off) { - int i = ((b[off + 3] & 0xFF) << 0) + - ((b[off + 2] & 0xFF) << 8) + - ((b[off + 1] & 0xFF) << 16) + - ((b[off + 0]) << 24); + int i = ((b[off + 3] & 0xFF) << 0) + + ((b[off + 2] & 0xFF) << 8) + + ((b[off + 1] & 0xFF) << 16) + + ((b[off + 0]) << 24); return Float.intBitsToFloat(i); } @@ -337,14 +336,14 @@ public class Bytes { * @return long. */ public static long bytes2long(byte[] b, int off) { - return ((b[off + 7] & 0xFFL) << 0) + - ((b[off + 6] & 0xFFL) << 8) + - ((b[off + 5] & 0xFFL) << 16) + - ((b[off + 4] & 0xFFL) << 24) + - ((b[off + 3] & 0xFFL) << 32) + - ((b[off + 2] & 0xFFL) << 40) + - ((b[off + 1] & 0xFFL) << 48) + - (((long) b[off + 0]) << 56); + return ((b[off + 7] & 0xFFL) << 0) + + ((b[off + 6] & 0xFFL) << 8) + + ((b[off + 5] & 0xFFL) << 16) + + ((b[off + 4] & 0xFFL) << 24) + + ((b[off + 3] & 0xFFL) << 32) + + ((b[off + 2] & 0xFFL) << 40) + + ((b[off + 1] & 0xFFL) << 48) + + (((long) b[off + 0]) << 56); } /** @@ -365,14 +364,14 @@ public class Bytes { * @return double. */ public static double bytes2double(byte[] b, int off) { - long j = ((b[off + 7] & 0xFFL) << 0) + - ((b[off + 6] & 0xFFL) << 8) + - ((b[off + 5] & 0xFFL) << 16) + - ((b[off + 4] & 0xFFL) << 24) + - ((b[off + 3] & 0xFFL) << 32) + - ((b[off + 2] & 0xFFL) << 40) + - ((b[off + 1] & 0xFFL) << 48) + - (((long) b[off + 0]) << 56); + long j = ((b[off + 7] & 0xFFL) << 0) + + ((b[off + 6] & 0xFFL) << 8) + + ((b[off + 5] & 0xFFL) << 16) + + ((b[off + 4] & 0xFFL) << 24) + + ((b[off + 3] & 0xFFL) << 32) + + ((b[off + 2] & 0xFFL) << 40) + + ((b[off + 1] & 0xFFL) << 48) + + (((long) b[off + 0]) << 56); return Double.longBitsToDouble(j); } @@ -767,7 +766,9 @@ public class Bytes { b[w++] = (byte) ((c1 << 2) | (c2 >> 4)); } else if (rem == 3) { - int c1 = indexOf(code, str.charAt(r++)), c2 = indexOf(code, str.charAt(r++)), c3 = indexOf(code, str.charAt(r++)); + int c1 = indexOf(code, str.charAt(r++)), + c2 = indexOf(code, str.charAt(r++)), + c3 = indexOf(code, str.charAt(r++)); b[w++] = (byte) ((c1 << 2) | (c2 >> 4)); b[w++] = (byte) ((c2 << 4) | (c3 >> 2)); @@ -914,8 +915,7 @@ public class Bytes { break; } total += read; - } - while (total < bs); + } while (total < bs); md.update(buf); } return md.digest(); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/io/StreamUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/io/StreamUtils.java index bc0f958792..b0badff64e 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/io/StreamUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/io/StreamUtils.java @@ -23,8 +23,7 @@ import java.io.InputStream; * Stream utils. */ public class StreamUtils { - private StreamUtils() { - } + private StreamUtils() {} public static InputStream limitedInputStream(final InputStream is, final int limit) throws IOException { return new InputStream() { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeByteArrayInputStream.java b/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeByteArrayInputStream.java index df96a1c1d0..7a284224f4 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeByteArrayInputStream.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeByteArrayInputStream.java @@ -101,8 +101,7 @@ public class UnsafeByteArrayInputStream extends InputStream { } @Override - public void close() throws IOException { - } + public void close() throws IOException {} public int position() { return mPosition; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeByteArrayOutputStream.java b/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeByteArrayOutputStream.java index 8104ecaf9c..d06cce19dc 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeByteArrayOutputStream.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeByteArrayOutputStream.java @@ -96,6 +96,5 @@ public class UnsafeByteArrayOutputStream extends OutputStream { } @Override - public void close() throws IOException { - } + public void close() throws IOException {} } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeStringReader.java b/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeStringReader.java index ad37476bd7..d5be46be20 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeStringReader.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeStringReader.java @@ -46,8 +46,7 @@ public class UnsafeStringReader extends Reader { @Override public int read(char[] cs, int off, int len) throws IOException { ensureOpen(); - if ((off < 0) || (off > cs.length) || (len < 0) || - ((off + len) > cs.length) || ((off + len) < 0)) { + if ((off < 0) || (off > cs.length) || (len < 0) || ((off + len) > cs.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeStringWriter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeStringWriter.java index 4ee8a75e18..836a4ff14d 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeStringWriter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/io/UnsafeStringWriter.java @@ -49,8 +49,7 @@ public class UnsafeStringWriter extends Writer { @Override public void write(char[] cs, int off, int len) throws IOException { - if ((off < 0) || (off > cs.length) || (len < 0) || - ((off + len) > cs.length) || ((off + len) < 0)) { + if ((off < 0) || (off > cs.length) || (len < 0) || ((off + len) > cs.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } @@ -93,12 +92,10 @@ public class UnsafeStringWriter extends Writer { } @Override - public void close() { - } + public void close() {} @Override - public void flush() { - } + public void flush() {} @Override public String toString() { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/json/GsonUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/json/GsonUtils.java index 4072f023a8..dd44449f86 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/json/GsonUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/json/GsonUtils.java @@ -18,12 +18,12 @@ package org.apache.dubbo.common.json; import org.apache.dubbo.common.utils.ClassUtils; +import java.lang.reflect.Type; + import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; -import java.lang.reflect.Type; - import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_GSON; public class GsonUtils { @@ -56,7 +56,9 @@ public class GsonUtils { try { return getGson().fromJson(json, type); } catch (JsonSyntaxException ex) { - throw new RuntimeException(String.format("Generic serialization [%s] Json syntax exception thrown when parsing (message:%s type:%s) error:%s", GENERIC_SERIALIZATION_GSON, json, type.toString(), ex.getMessage())); + throw new RuntimeException(String.format( + "Generic serialization [%s] Json syntax exception thrown when parsing (message:%s type:%s) error:%s", + GENERIC_SERIALIZATION_GSON, json, type.toString(), ex.getMessage())); } } @@ -67,7 +69,9 @@ public class GsonUtils { try { return getGson().toJson(obj); } catch (JsonSyntaxException ex) { - throw new RuntimeException(String.format("Generic serialization [%s] Json syntax exception thrown when parsing (object:%s ) error:%s", GENERIC_SERIALIZATION_GSON, obj, ex.getMessage())); + throw new RuntimeException(String.format( + "Generic serialization [%s] Json syntax exception thrown when parsing (object:%s ) error:%s", + GENERIC_SERIALIZATION_GSON, obj, ex.getMessage())); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/AbstractJsonUtilImpl.java b/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/AbstractJsonUtilImpl.java index 7823353cf1..e2dbe59fc1 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/AbstractJsonUtilImpl.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/AbstractJsonUtilImpl.java @@ -51,8 +51,7 @@ public abstract class AbstractJsonUtilImpl implements JsonUtil { } Object value = obj.get(key); if (!(value instanceof List)) { - throw new ClassCastException( - String.format("value '%s' for key '%s' in '%s' is not List", value, key, obj)); + throw new ClassCastException(String.format("value '%s' for key '%s' in '%s' is not List", value, key, obj)); } return (List) value; } @@ -102,7 +101,7 @@ public abstract class AbstractJsonUtilImpl implements JsonUtil { Object value = obj.get(key); if (!(value instanceof Map)) { throw new ClassCastException( - String.format("value '%s' for key '%s' in '%s' is not object", value, key, obj)); + String.format("value '%s' for key '%s' in '%s' is not object", value, key, obj)); } return (Map) value; } @@ -127,11 +126,11 @@ public abstract class AbstractJsonUtilImpl implements JsonUtil { return Double.parseDouble((String) value); } catch (NumberFormatException e) { throw new IllegalArgumentException( - String.format("value '%s' for key '%s' is not a double", value, key)); + String.format("value '%s' for key '%s' is not a double", value, key)); } } throw new IllegalArgumentException( - String.format("value '%s' for key '%s' in '%s' is not a number", value, key, obj)); + String.format("value '%s' for key '%s' in '%s' is not a number", value, key, obj)); } /** @@ -159,11 +158,10 @@ public abstract class AbstractJsonUtilImpl implements JsonUtil { return Integer.parseInt((String) value); } catch (NumberFormatException e) { throw new IllegalArgumentException( - String.format("value '%s' for key '%s' is not an integer", value, key)); + String.format("value '%s' for key '%s' is not an integer", value, key)); } } - throw new IllegalArgumentException( - String.format("value '%s' for key '%s' is not an integer", value, key)); + throw new IllegalArgumentException(String.format("value '%s' for key '%s' is not an integer", value, key)); } /** @@ -192,11 +190,10 @@ public abstract class AbstractJsonUtilImpl implements JsonUtil { return Long.parseLong((String) value); } catch (NumberFormatException e) { throw new IllegalArgumentException( - String.format("value '%s' for key '%s' is not a long integer", value, key)); + String.format("value '%s' for key '%s' is not a long integer", value, key)); } } - throw new IllegalArgumentException( - String.format("value '%s' for key '%s' is not a long integer", value, key)); + throw new IllegalArgumentException(String.format("value '%s' for key '%s' is not a long integer", value, key)); } /** @@ -213,7 +210,7 @@ public abstract class AbstractJsonUtilImpl implements JsonUtil { Object value = obj.get(key); if (!(value instanceof String)) { throw new ClassCastException( - String.format("value '%s' for key '%s' in '%s' is not String", value, key, obj)); + String.format("value '%s' for key '%s' in '%s' is not String", value, key, obj)); } return (String) value; } @@ -229,13 +226,12 @@ public abstract class AbstractJsonUtilImpl implements JsonUtil { for (int i = 0; i < rawList.size(); i++) { if (!(rawList.get(i) instanceof Map)) { throw new ClassCastException( - String.format("value %s for idx %d in %s is not object", rawList.get(i), i, rawList)); + String.format("value %s for idx %d in %s is not object", rawList.get(i), i, rawList)); } } return (List>) rawList; } - /** * Casts a list of unchecked JSON values to a list of String. If the given list * contains a value that is not a String, throws an exception. @@ -247,11 +243,9 @@ public abstract class AbstractJsonUtilImpl implements JsonUtil { for (int i = 0; i < rawList.size(); i++) { if (!(rawList.get(i) instanceof String)) { throw new ClassCastException( - String.format( - "value '%s' for idx %d in '%s' is not string", rawList.get(i), i, rawList)); + String.format("value '%s' for idx %d in '%s' is not string", rawList.get(i), i, rawList)); } } return (List) rawList; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/FastJson2Impl.java b/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/FastJson2Impl.java index f12e76a292..f7741b229c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/FastJson2Impl.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/FastJson2Impl.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.common.json.impl; -import com.alibaba.fastjson2.JSONWriter; - import java.lang.reflect.Type; import java.util.List; +import com.alibaba.fastjson2.JSONWriter; + public class FastJson2Impl extends AbstractJsonUtilImpl { @Override public T toJavaObject(String json, Type type) { @@ -37,4 +37,3 @@ public class FastJson2Impl extends AbstractJsonUtilImpl { return com.alibaba.fastjson2.JSON.toJSONString(obj, JSONWriter.Feature.WriteEnumsUsingName); } } - diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/FastJsonImpl.java b/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/FastJsonImpl.java index d9560ed206..756dc9457c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/FastJsonImpl.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/FastJsonImpl.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.common.json.impl; -import com.alibaba.fastjson.serializer.SerializerFeature; - import java.lang.reflect.Type; import java.util.List; +import com.alibaba.fastjson.serializer.SerializerFeature; + public class FastJsonImpl extends AbstractJsonUtilImpl { @Override @@ -37,5 +37,4 @@ public class FastJsonImpl extends AbstractJsonUtilImpl { public String toJson(Object obj) { return com.alibaba.fastjson.JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/GsonImpl.java b/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/GsonImpl.java index 03bca670c9..2a0cad78fa 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/GsonImpl.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/GsonImpl.java @@ -16,12 +16,12 @@ */ package org.apache.dubbo.common.json.impl; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - import java.lang.reflect.Type; import java.util.List; +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; + public class GsonImpl extends AbstractJsonUtilImpl { // weak reference of com.google.gson.Gson, prevent throw exception when init private volatile Object gsonCache = null; @@ -33,7 +33,8 @@ public class GsonImpl extends AbstractJsonUtilImpl { @Override public List toJavaList(String json, Class clazz) { - return getGson().fromJson(json, TypeToken.getParameterized(List.class, clazz).getType()); + return getGson() + .fromJson(json, TypeToken.getParameterized(List.class, clazz).getType()); } @Override diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/JacksonImpl.java b/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/JacksonImpl.java index 51377d987f..3e21416dcf 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/JacksonImpl.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/JacksonImpl.java @@ -16,6 +16,8 @@ */ package org.apache.dubbo.common.json.impl; +import java.lang.reflect.Type; +import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -24,9 +26,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.json.JsonMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import java.lang.reflect.Type; -import java.util.List; - public class JacksonImpl extends AbstractJsonUtilImpl { private final ObjectMapper objectMapper = new ObjectMapper(); @@ -44,7 +43,8 @@ public class JacksonImpl extends AbstractJsonUtilImpl { @Override public List toJavaList(String json, Class clazz) { try { - return getJackson().readValue(json, getJackson().getTypeFactory().constructCollectionType(List.class, clazz)); + return getJackson() + .readValue(json, getJackson().getTypeFactory().constructCollectionType(List.class, clazz)); } catch (com.fasterxml.jackson.core.JsonProcessingException e) { throw new IllegalArgumentException(e); } @@ -64,11 +64,11 @@ public class JacksonImpl extends AbstractJsonUtilImpl { synchronized (this) { if (jacksonCache == null || !(jacksonCache instanceof JsonMapper)) { jacksonCache = JsonMapper.builder() - .configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true) - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - .serializationInclusion(Include.NON_NULL) - .addModule(new JavaTimeModule()) - .build(); + .configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .serializationInclusion(Include.NON_NULL) + .addModule(new JavaTimeModule()) + .build(); } } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/lang/Nullable.java b/dubbo-common/src/main/java/org/apache/dubbo/common/lang/Nullable.java index 1114492cc1..09992e7916 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/lang/Nullable.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/lang/Nullable.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.lang; import java.lang.annotation.Documented; @@ -23,9 +22,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - @Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Documented -public @interface Nullable { -} +public @interface Nullable {} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/lang/Prioritized.java b/dubbo-common/src/main/java/org/apache/dubbo/common/lang/Prioritized.java index 76a6a0b8af..c392efc5c0 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/lang/Prioritized.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/lang/Prioritized.java @@ -34,13 +34,13 @@ public interface Prioritized extends Comparable { Comparator COMPARATOR = (one, two) -> { boolean b1 = one instanceof Prioritized; boolean b2 = two instanceof Prioritized; - if (b1 && !b2) { // one is Prioritized, two is not + if (b1 && !b2) { // one is Prioritized, two is not return -1; } else if (b2 && !b1) { // two is Prioritized, one is not return 1; - } else if (b1 && b2) { // one and two both are Prioritized + } else if (b1 && b2) { // one and two both are Prioritized return ((Prioritized) one).compareTo((Prioritized) two); - } else { // no different + } else { // no different return 0; } }; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/lang/ShutdownHookCallbacks.java b/dubbo-common/src/main/java/org/apache/dubbo/common/lang/ShutdownHookCallbacks.java index 8392f23bdc..9834884290 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/lang/ShutdownHookCallbacks.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/lang/ShutdownHookCallbacks.java @@ -66,8 +66,7 @@ public class ShutdownHookCallbacks implements Disposable { } private void loadCallbacks() { - ExtensionLoader loader = - applicationModel.getExtensionLoader(ShutdownHookCallback.class); + ExtensionLoader loader = applicationModel.getExtensionLoader(ShutdownHookCallback.class); loader.getSupportedExtensionInstances().forEach(this::addCallback); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/ErrorTypeAwareLogger.java b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/ErrorTypeAwareLogger.java index 72db45e868..4d40f428db 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/ErrorTypeAwareLogger.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/ErrorTypeAwareLogger.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.logger; import org.apache.dubbo.common.constants.LoggerCodeConstants; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/Level.java b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/Level.java index 7e615de436..321ba7e57e 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/Level.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/Level.java @@ -55,5 +55,4 @@ public enum Level { * OFF */ OFF - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/ListenableLogger.java b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/ListenableLogger.java index e0d3c76cae..d41e2a9322 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/ListenableLogger.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/ListenableLogger.java @@ -14,13 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.logger; /** * Loggers that can register to listen to log messages. */ -public interface ListenableLogger extends ErrorTypeAwareLogger{ +public interface ListenableLogger extends ErrorTypeAwareLogger { /** * Register a listener to this logger,and get notified when a log happens. @@ -28,5 +27,4 @@ public interface ListenableLogger extends ErrorTypeAwareLogger{ * @param listener log listener */ void registerListen(LogListener listener); - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/LogListener.java b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/LogListener.java index c0308e8a41..79cd41b4c8 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/LogListener.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/LogListener.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.logger; /** @@ -23,5 +22,4 @@ package org.apache.dubbo.common.logger; public interface LogListener { void onMessage(String code, String msg); - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/Logger.java b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/Logger.java index f55646a6b2..1f2af9314e 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/Logger.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/Logger.java @@ -207,5 +207,4 @@ public interface Logger { * @return true if error is enabled */ boolean isErrorEnabled(); - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/LoggerFactory.java b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/LoggerFactory.java index 02e1cd7744..e52f2f4d62 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/LoggerFactory.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/LoggerFactory.java @@ -41,7 +41,8 @@ import java.util.concurrent.ConcurrentMap; public class LoggerFactory { private static final ConcurrentMap LOGGERS = new ConcurrentHashMap<>(); - private static final ConcurrentMap ERROR_TYPE_AWARE_LOGGERS = new ConcurrentHashMap<>(); + private static final ConcurrentMap ERROR_TYPE_AWARE_LOGGERS = + new ConcurrentHashMap<>(); private static volatile LoggerAdapter loggerAdapter; // search common-used logging frameworks @@ -65,17 +66,17 @@ public class LoggerFactory { break; default: List> candidates = Arrays.asList( - Log4jLoggerAdapter.class, - Slf4jLoggerAdapter.class, - Log4j2LoggerAdapter.class, - JclLoggerAdapter.class, - JdkLoggerAdapter.class - ); + Log4jLoggerAdapter.class, + Slf4jLoggerAdapter.class, + Log4j2LoggerAdapter.class, + JclLoggerAdapter.class, + JdkLoggerAdapter.class); boolean found = false; // try to use the first available adapter for (Class clazz : candidates) { try { - LoggerAdapter loggerAdapter = clazz.getDeclaredConstructor().newInstance(); + LoggerAdapter loggerAdapter = + clazz.getDeclaredConstructor().newInstance(); loggerAdapter.getLogger(LoggerFactory.class); if (loggerAdapter.isConfigured()) { setLoggerAdapter(loggerAdapter); @@ -93,7 +94,8 @@ public class LoggerFactory { System.err.println("Dubbo: Unable to find a proper configured logger to log out."); for (Class clazz : candidates) { try { - LoggerAdapter loggerAdapter = clazz.getDeclaredConstructor().newInstance(); + LoggerAdapter loggerAdapter = + clazz.getDeclaredConstructor().newInstance(); loggerAdapter.getLogger(LoggerFactory.class); setLoggerAdapter(loggerAdapter); found = true; @@ -103,21 +105,24 @@ public class LoggerFactory { } } if (found) { - System.err.println("Dubbo: Using default logger: " + loggerAdapter.getClass().getName() + ". " + - "If you cannot see any log, please configure -Ddubbo.application.logger property to your preferred logging framework."); + System.err.println( + "Dubbo: Using default logger: " + + loggerAdapter.getClass().getName() + ". " + + "If you cannot see any log, please configure -Ddubbo.application.logger property to your preferred logging framework."); } else { - System.err.println("Dubbo: Unable to find any available logger adapter to log out. Dubbo logs will be ignored. " + - "Please configure -Ddubbo.application.logger property and add corresponding logging library to classpath."); + System.err.println( + "Dubbo: Unable to find any available logger adapter to log out. Dubbo logs will be ignored. " + + "Please configure -Ddubbo.application.logger property and add corresponding logging library to classpath."); } } } - private LoggerFactory() { - } + private LoggerFactory() {} public static void setLoggerAdapter(FrameworkModel frameworkModel, String loggerAdapter) { if (loggerAdapter != null && loggerAdapter.length() > 0) { - setLoggerAdapter(frameworkModel.getExtensionLoader(LoggerAdapter.class).getExtension(loggerAdapter)); + setLoggerAdapter( + frameworkModel.getExtensionLoader(LoggerAdapter.class).getExtension(loggerAdapter)); } } @@ -146,7 +151,8 @@ public class LoggerFactory { * @return logger */ public static Logger getLogger(Class key) { - return ConcurrentHashMapUtils.computeIfAbsent(LOGGERS, key.getName(), name -> new FailsafeLogger(loggerAdapter.getLogger(name))); + return ConcurrentHashMapUtils.computeIfAbsent( + LOGGERS, key.getName(), name -> new FailsafeLogger(loggerAdapter.getLogger(name))); } /** @@ -156,7 +162,8 @@ public class LoggerFactory { * @return logger provider */ public static Logger getLogger(String key) { - return ConcurrentHashMapUtils.computeIfAbsent(LOGGERS, key, k -> new FailsafeLogger(loggerAdapter.getLogger(k))); + return ConcurrentHashMapUtils.computeIfAbsent( + LOGGERS, key, k -> new FailsafeLogger(loggerAdapter.getLogger(k))); } /** @@ -166,7 +173,10 @@ public class LoggerFactory { * @return error type aware logger */ public static ErrorTypeAwareLogger getErrorTypeAwareLogger(Class key) { - return ConcurrentHashMapUtils.computeIfAbsent(ERROR_TYPE_AWARE_LOGGERS, key.getName(), name -> new FailsafeErrorTypeAwareLogger(loggerAdapter.getLogger(name))); + return ConcurrentHashMapUtils.computeIfAbsent( + ERROR_TYPE_AWARE_LOGGERS, + key.getName(), + name -> new FailsafeErrorTypeAwareLogger(loggerAdapter.getLogger(name))); } /** @@ -176,7 +186,8 @@ public class LoggerFactory { * @return error type aware logger */ public static ErrorTypeAwareLogger getErrorTypeAwareLogger(String key) { - return ConcurrentHashMapUtils.computeIfAbsent(ERROR_TYPE_AWARE_LOGGERS, key, k -> new FailsafeErrorTypeAwareLogger(loggerAdapter.getLogger(k))); + return ConcurrentHashMapUtils.computeIfAbsent( + ERROR_TYPE_AWARE_LOGGERS, key, k -> new FailsafeErrorTypeAwareLogger(loggerAdapter.getLogger(k))); } /** @@ -221,7 +232,8 @@ public class LoggerFactory { List result = new LinkedList<>(); for (Map.Entry, String> entry : candidates.entrySet()) { try { - LoggerAdapter loggerAdapter = entry.getKey().getDeclaredConstructor().newInstance(); + LoggerAdapter loggerAdapter = + entry.getKey().getDeclaredConstructor().newInstance(); loggerAdapter.getLogger(LoggerFactory.class); result.add(entry.getValue()); } catch (Exception ignored) { @@ -250,5 +262,4 @@ public class LoggerFactory { } return name; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jcl/JclLogger.java b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jcl/JclLogger.java index 690f198360..02f2cafe81 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jcl/JclLogger.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jcl/JclLogger.java @@ -163,5 +163,4 @@ public class JclLogger implements Logger { public boolean isErrorEnabled() { return logger.isErrorEnabled(); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jcl/JclLoggerAdapter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jcl/JclLoggerAdapter.java index 1751c602e9..0249bb6c4a 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jcl/JclLoggerAdapter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jcl/JclLoggerAdapter.java @@ -20,10 +20,10 @@ import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerAdapter; -import org.apache.commons.logging.LogFactory; - import java.io.File; +import org.apache.commons.logging.LogFactory; + public class JclLoggerAdapter implements LoggerAdapter { public static final String NAME = "jcl"; private Level level; @@ -58,5 +58,4 @@ public class JclLoggerAdapter implements LoggerAdapter { public void setFile(File file) { this.file = file; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jdk/JdkLogger.java b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jdk/JdkLogger.java index 3e1c7194a8..69b5c930aa 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jdk/JdkLogger.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jdk/JdkLogger.java @@ -17,11 +17,12 @@ package org.apache.dubbo.common.logger.jdk; import org.apache.dubbo.common.logger.Logger; -import org.slf4j.helpers.FormattingTuple; -import org.slf4j.helpers.MessageFormatter; import java.util.logging.Level; +import org.slf4j.helpers.FormattingTuple; +import org.slf4j.helpers.MessageFormatter; + public class JdkLogger implements Logger { private final java.util.logging.Logger logger; @@ -159,5 +160,4 @@ public class JdkLogger implements Logger { public boolean isErrorEnabled() { return logger.isLoggable(Level.SEVERE); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jdk/JdkLoggerAdapter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jdk/JdkLoggerAdapter.java index 43f32b1728..c153db3d14 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jdk/JdkLoggerAdapter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/jdk/JdkLoggerAdapter.java @@ -46,10 +46,12 @@ public class JdkLoggerAdapter implements LoggerAdapter { System.err.println("No such logging.properties in classpath for jdk logging config!"); } } catch (Exception t) { - System.err.println("Failed to load logging.properties in classpath for jdk logging config, cause: " + t.getMessage()); + System.err.println( + "Failed to load logging.properties in classpath for jdk logging config, cause: " + t.getMessage()); } try { - Handler[] handlers = java.util.logging.Logger.getLogger(GLOBAL_LOGGER_NAME).getHandlers(); + Handler[] handlers = + java.util.logging.Logger.getLogger(GLOBAL_LOGGER_NAME).getHandlers(); for (Handler handler : handlers) { if (handler instanceof FileHandler) { FileHandler fileHandler = (FileHandler) handler; @@ -123,7 +125,8 @@ public class JdkLoggerAdapter implements LoggerAdapter { @Override public Level getLevel() { - return fromJdkLevel(java.util.logging.Logger.getLogger(GLOBAL_LOGGER_NAME).getLevel()); + return fromJdkLevel( + java.util.logging.Logger.getLogger(GLOBAL_LOGGER_NAME).getLevel()); } @Override diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/log4j/Log4jLoggerAdapter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/log4j/Log4jLoggerAdapter.java index fad4605fa5..1fdc8ac1bc 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/log4j/Log4jLoggerAdapter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/log4j/Log4jLoggerAdapter.java @@ -20,13 +20,13 @@ import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerAdapter; +import java.io.File; +import java.util.Enumeration; + import org.apache.log4j.Appender; import org.apache.log4j.FileAppender; import org.apache.log4j.LogManager; -import java.io.File; -import java.util.Enumeration; - public class Log4jLoggerAdapter implements LoggerAdapter { public static final String NAME = "log4j"; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/log4j2/Log4j2LoggerAdapter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/log4j2/Log4j2LoggerAdapter.java index c8f25d59e5..f30bbcb9fe 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/log4j2/Log4j2LoggerAdapter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/log4j2/Log4j2LoggerAdapter.java @@ -20,11 +20,11 @@ import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerAdapter; +import java.io.File; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.config.Configurator; -import java.io.File; - public class Log4j2LoggerAdapter implements LoggerAdapter { public static final String NAME = "log4j2"; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/slf4j/Slf4jLogger.java b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/slf4j/Slf4jLogger.java index 47ab865cab..8ce4233229 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/slf4j/Slf4jLogger.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/slf4j/Slf4jLogger.java @@ -54,7 +54,8 @@ public class Slf4jLogger implements Logger { public void trace(String msg, Object... arguments) { if (locationAwareLogger != null) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, arguments); - locationAwareLogger.log(null, FQCN, LocationAwareLogger.TRACE_INT, msg, ft.getArgArray(), ft.getThrowable()); + locationAwareLogger.log( + null, FQCN, LocationAwareLogger.TRACE_INT, msg, ft.getArgArray(), ft.getThrowable()); return; } logger.trace(msg, arguments); @@ -91,7 +92,8 @@ public class Slf4jLogger implements Logger { public void debug(String msg, Object... arguments) { if (locationAwareLogger != null) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, arguments); - locationAwareLogger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, msg, ft.getArgArray(), ft.getThrowable()); + locationAwareLogger.log( + null, FQCN, LocationAwareLogger.DEBUG_INT, msg, ft.getArgArray(), ft.getThrowable()); return; } logger.debug(msg, arguments); @@ -202,7 +204,8 @@ public class Slf4jLogger implements Logger { public void error(String msg, Object... arguments) { if (locationAwareLogger != null) { FormattingTuple ft = MessageFormatter.arrayFormat(msg, arguments); - locationAwareLogger.log(null, FQCN, LocationAwareLogger.ERROR_INT, msg, ft.getArgArray(), ft.getThrowable()); + locationAwareLogger.log( + null, FQCN, LocationAwareLogger.ERROR_INT, msg, ft.getArgArray(), ft.getThrowable()); return; } logger.error(msg, arguments); @@ -273,5 +276,4 @@ public class Slf4jLogger implements Logger { public Level getLevel() { return getLevel(logger); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/slf4j/Slf4jLoggerAdapter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/slf4j/Slf4jLoggerAdapter.java index 47f4c170c3..c249394f66 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/slf4j/Slf4jLoggerAdapter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/slf4j/Slf4jLoggerAdapter.java @@ -20,9 +20,11 @@ import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerAdapter; import org.apache.dubbo.common.utils.ClassUtils; -import org.slf4j.LoggerFactory; + import java.io.File; +import org.slf4j.LoggerFactory; + public class Slf4jLoggerAdapter implements LoggerAdapter { public static final String NAME = "slf4j"; @@ -52,7 +54,9 @@ public class Slf4jLoggerAdapter implements LoggerAdapter { @Override public void setLevel(Level level) { - System.err.printf("The level of slf4j logger current can not be set, using the default level: %s \n", Slf4jLogger.getLevel(ROOT_LOGGER)); + System.err.printf( + "The level of slf4j logger current can not be set, using the default level: %s \n", + Slf4jLogger.getLevel(ROOT_LOGGER)); this.level = level; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/support/FailsafeErrorTypeAwareLogger.java b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/support/FailsafeErrorTypeAwareLogger.java index f5b7d5ef5a..c9d7d2b303 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/support/FailsafeErrorTypeAwareLogger.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/support/FailsafeErrorTypeAwareLogger.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.logger.support; import org.apache.dubbo.common.Version; @@ -56,11 +55,12 @@ public class FailsafeErrorTypeAwareLogger extends FailsafeLogger implements List super(logger); } - private String appendContextMessageWithInstructions(String code, String cause, String extendedInformation, String msg) { - return " [DUBBO] " + msg + ", dubbo version: " + Version.getVersion() + - ", current host: " + NetUtils.getLocalHost() + ", error code: " + code + - ". This may be caused by " + cause + ", " + - "go to " + getErrorUrl(code) + " to find instructions. " + extendedInformation; + private String appendContextMessageWithInstructions( + String code, String cause, String extendedInformation, String msg) { + return " [DUBBO] " + msg + ", dubbo version: " + Version.getVersion() + ", current host: " + + NetUtils.getLocalHost() + ", error code: " + code + ". This may be caused by " + + cause + ", " + "go to " + + getErrorUrl(code) + " to find instructions. " + extendedInformation; } private String getErrorUrl(String code) { @@ -80,8 +80,9 @@ public class FailsafeErrorTypeAwareLogger extends FailsafeLogger implements List errorCodeSegments[0] = Integer.parseInt(segments[0]); errorCodeSegments[1] = Integer.parseInt(segments[1]); } catch (NumberFormatException numberFormatException) { - error("Invalid error code: " + code + ", the format of error code is: X-X (where X is a number).", - numberFormatException); + error( + "Invalid error code: " + code + ", the format of error code is: X-X (where X is a number).", + numberFormatException); return ""; } @@ -161,14 +162,14 @@ public class FailsafeErrorTypeAwareLogger extends FailsafeLogger implements List } private void onEvent(String code, String msg) { - Optional.ofNullable(listeners.get()).ifPresent( - logListeners -> logListeners.forEach(logListener -> { - try { - logListener.onMessage(code, msg); - } catch (Exception e) { - // ignored. - } - })); + Optional.ofNullable(listeners.get()) + .ifPresent(logListeners -> logListeners.forEach(logListener -> { + try { + logListener.onMessage(code, msg); + } catch (Exception e) { + // ignored. + } + })); GLOBAL_LISTENERS.forEach(logListener -> { try { @@ -178,5 +179,4 @@ public class FailsafeErrorTypeAwareLogger extends FailsafeLogger implements List } }); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/support/FailsafeLogger.java b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/support/FailsafeLogger.java index 79ab6ff640..d329fb2565 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/logger/support/FailsafeLogger.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/logger/support/FailsafeLogger.java @@ -47,7 +47,8 @@ public class FailsafeLogger implements Logger { } private String appendContextMessage(String msg) { - return " [DUBBO] " + msg + ", dubbo version: " + Version.getVersion() + ", current host: " + NetUtils.getLocalHost(); + return " [DUBBO] " + msg + ", dubbo version: " + Version.getVersion() + ", current host: " + + NetUtils.getLocalHost(); } @Override @@ -329,5 +330,4 @@ public class FailsafeLogger implements Logger { return false; } } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/profiler/Profiler.java b/dubbo-common/src/main/java/org/apache/dubbo/common/profiler/Profiler.java index 5d2c420180..d26fc8023f 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/profiler/Profiler.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/profiler/Profiler.java @@ -67,8 +67,8 @@ public class Profiler { public static String buildDetail(ProfilerEntry entry) { long totalUsageTime = entry.getEndTime() - entry.getStartTime(); - return "Start time: " + entry.getStartTime() + "\n" + - String.join("\n", buildDetail(entry, entry.getStartTime(), totalUsageTime, 0)); + return "Start time: " + entry.getStartTime() + "\n" + + String.join("\n", buildDetail(entry, entry.getStartTime(), totalUsageTime, 0)); } public static List buildDetail(ProfilerEntry entry, long startTime, long totalUsageTime, int depth) { @@ -78,14 +78,19 @@ public class Profiler { long offset = entry.getStartTime() - startTime; List lines = new LinkedList<>(); - stringBuilder.append("+-[ Offset: ") - .append(offset / 1000_000).append('.').append(String.format("%06d", offset % 1000_000)) - .append("ms; Usage: ") - .append(usage / 1000_000).append('.').append(String.format("%06d", usage % 1000_000)) - .append("ms, ") - .append(percent) - .append("% ] ") - .append(entry.getMessage()); + stringBuilder + .append("+-[ Offset: ") + .append(offset / 1000_000) + .append('.') + .append(String.format("%06d", offset % 1000_000)) + .append("ms; Usage: ") + .append(usage / 1000_000) + .append('.') + .append(String.format("%06d", usage % 1000_000)) + .append("ms, ") + .append(percent) + .append("% ] ") + .append(entry.getMessage()); lines.add(stringBuilder.toString()); List entrySub = entry.getSub(); for (int i = 0, entrySubSize = entrySub.size(); i < entrySubSize; i++) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/profiler/ProfilerSwitch.java b/dubbo-common/src/main/java/org/apache/dubbo/common/profiler/ProfilerSwitch.java index 2025550b14..998f92caf5 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/profiler/ProfilerSwitch.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/profiler/ProfilerSwitch.java @@ -23,11 +23,11 @@ import java.util.concurrent.atomic.AtomicReference; * TODO */ public class ProfilerSwitch { - private final static AtomicBoolean enableDetailProfiler = new AtomicBoolean(false); + private static final AtomicBoolean enableDetailProfiler = new AtomicBoolean(false); - private final static AtomicBoolean enableSimpleProfiler = new AtomicBoolean(true); + private static final AtomicBoolean enableSimpleProfiler = new AtomicBoolean(true); - private final static AtomicReference warnPercent = new AtomicReference<>(0.75); + private static final AtomicReference warnPercent = new AtomicReference<>(0.75); public static void enableSimpleProfiler() { enableSimpleProfiler.set(true); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/reference/ReferenceCountedResource.java b/dubbo-common/src/main/java/org/apache/dubbo/common/reference/ReferenceCountedResource.java index bc1f1cee88..5bf314a7f1 100755 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/reference/ReferenceCountedResource.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/reference/ReferenceCountedResource.java @@ -27,9 +27,10 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERR * inspired by Netty */ public abstract class ReferenceCountedResource implements AutoCloseable { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ReferenceCountedResource.class); - private static final AtomicLongFieldUpdater COUNTER_UPDATER - = AtomicLongFieldUpdater.newUpdater(ReferenceCountedResource.class, "counter"); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ReferenceCountedResource.class); + private static final AtomicLongFieldUpdater COUNTER_UPDATER = + AtomicLongFieldUpdater.newUpdater(ReferenceCountedResource.class, "counter"); private volatile long counter = 1; @@ -70,10 +71,8 @@ public abstract class ReferenceCountedResource implements AutoCloseable { release(); } - /** * This method will be invoked when counter reaches 0, override this method to destroy materials related to the specific resource. */ protected abstract void destroy(); - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/resource/Disposable.java b/dubbo-common/src/main/java/org/apache/dubbo/common/resource/Disposable.java index 78c075cdf3..6635af861f 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/resource/Disposable.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/resource/Disposable.java @@ -22,5 +22,4 @@ package org.apache.dubbo.common.resource; public interface Disposable { void destroy(); - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/resource/GlobalResourceInitializer.java b/dubbo-common/src/main/java/org/apache/dubbo/common/resource/GlobalResourceInitializer.java index 11b8a4556b..6014f707c4 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/resource/GlobalResourceInitializer.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/resource/GlobalResourceInitializer.java @@ -58,5 +58,4 @@ public class GlobalResourceInitializer extends CallableSafeInitializer { } return value; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/resource/GlobalResourcesRepository.java b/dubbo-common/src/main/java/org/apache/dubbo/common/resource/GlobalResourcesRepository.java index 4c265ab9b6..0d02d09128 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/resource/GlobalResourcesRepository.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/resource/GlobalResourcesRepository.java @@ -37,15 +37,15 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXP */ public class GlobalResourcesRepository { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(GlobalResourcesRepository.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(GlobalResourcesRepository.class); - private volatile static GlobalResourcesRepository instance; + private static volatile GlobalResourcesRepository instance; private volatile ExecutorService executorService; private final List oneoffDisposables = new CopyOnWriteArrayList<>(); private static final List globalReusedDisposables = new CopyOnWriteArrayList<>(); - private GlobalResourcesRepository() { - } + private GlobalResourcesRepository() {} public static GlobalResourcesRepository getInstance() { if (instance == null) { @@ -95,7 +95,8 @@ public class GlobalResourcesRepository { if (logger.isInfoEnabled()) { logger.info("Creating global shared handler ..."); } - executorService = Executors.newCachedThreadPool(new NamedThreadFactory("Dubbo-global-shared-handler", true)); + executorService = + Executors.newCachedThreadPool(new NamedThreadFactory("Dubbo-global-shared-handler", true)); } } } @@ -110,10 +111,9 @@ public class GlobalResourcesRepository { executorService.shutdownNow(); try { if (!executorService.awaitTermination( - ConfigurationUtils.reCalShutdownTime(DEFAULT_SERVER_SHUTDOWN_TIMEOUT), - TimeUnit.MILLISECONDS)) { - logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", - "Wait global executor service terminated timeout."); + ConfigurationUtils.reCalShutdownTime(DEFAULT_SERVER_SHUTDOWN_TIMEOUT), TimeUnit.MILLISECONDS)) { + logger.warn( + COMMON_UNEXPECTED_EXCEPTION, "", "", "Wait global executor service terminated timeout."); } } catch (InterruptedException e) { logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "destroy resources failed: " + e.getMessage(), e); @@ -171,7 +171,6 @@ public class GlobalResourcesRepository { } } - // for test public static List getGlobalReusedDisposables() { return globalReusedDisposables; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/CertManager.java b/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/CertManager.java index d906457d66..8bb0c492ec 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/CertManager.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/CertManager.java @@ -26,7 +26,8 @@ public class CertManager { private final List certProviders; public CertManager(FrameworkModel frameworkModel) { - this.certProviders = frameworkModel.getExtensionLoader(CertProvider.class).getActivateExtensions(); + this.certProviders = + frameworkModel.getExtensionLoader(CertProvider.class).getActivateExtensions(); } public ProviderCert getProviderConnectionConfig(URL localAddress, SocketAddress remoteAddress) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/ProviderCert.java b/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/ProviderCert.java index 81b9f9876f..6f7a95fe33 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/ProviderCert.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/ProviderCert.java @@ -24,7 +24,8 @@ public class ProviderCert extends Cert { this.authPolicy = authPolicy; } - public ProviderCert(byte[] keyCertChain, byte[] privateKey, byte[] trustCert, String password, AuthPolicy authPolicy) { + public ProviderCert( + byte[] keyCertChain, byte[] privateKey, byte[] trustCert, String password, AuthPolicy authPolicy) { super(keyCertChain, privateKey, trustCert, password); this.authPolicy = authPolicy; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/impl/SSLConfigCertProvider.java b/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/impl/SSLConfigCertProvider.java index b694ee3bef..23923c45ed 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/impl/SSLConfigCertProvider.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/ssl/impl/SSLConfigCertProvider.java @@ -36,45 +36,70 @@ public class SSLConfigCertProvider implements CertProvider { @Override public boolean isSupport(URL address) { - return address.getOrDefaultApplicationModel().getApplicationConfigManager().getSsl() - .isPresent(); + return address.getOrDefaultApplicationModel() + .getApplicationConfigManager() + .getSsl() + .isPresent(); } @Override public ProviderCert getProviderConnectionConfig(URL localAddress) { - return localAddress.getOrDefaultApplicationModel().getApplicationConfigManager().getSsl() - .filter(sslConfig -> Objects.nonNull(sslConfig.getServerKeyCertChainPath())) - .filter(sslConfig -> Objects.nonNull(sslConfig.getServerPrivateKeyPath())) - .map(sslConfig -> { - try { - return new ProviderCert( - IOUtils.toByteArray(sslConfig.getServerKeyCertChainPathStream()), - IOUtils.toByteArray(sslConfig.getServerPrivateKeyPathStream()), - sslConfig.getServerTrustCertCollectionPath() != null ? IOUtils.toByteArray(sslConfig.getServerTrustCertCollectionPathStream()) : null, - sslConfig.getServerKeyPassword(), AuthPolicy.CLIENT_AUTH); - } catch (IOException e) { - logger.warn(LoggerCodeConstants.CONFIG_SSL_PATH_LOAD_FAILED, "", "", "Failed to load ssl config.", e); - return null; - } - }).orElse(null); + return localAddress + .getOrDefaultApplicationModel() + .getApplicationConfigManager() + .getSsl() + .filter(sslConfig -> Objects.nonNull(sslConfig.getServerKeyCertChainPath())) + .filter(sslConfig -> Objects.nonNull(sslConfig.getServerPrivateKeyPath())) + .map(sslConfig -> { + try { + return new ProviderCert( + IOUtils.toByteArray(sslConfig.getServerKeyCertChainPathStream()), + IOUtils.toByteArray(sslConfig.getServerPrivateKeyPathStream()), + sslConfig.getServerTrustCertCollectionPath() != null + ? IOUtils.toByteArray(sslConfig.getServerTrustCertCollectionPathStream()) + : null, + sslConfig.getServerKeyPassword(), + AuthPolicy.CLIENT_AUTH); + } catch (IOException e) { + logger.warn( + LoggerCodeConstants.CONFIG_SSL_PATH_LOAD_FAILED, + "", + "", + "Failed to load ssl config.", + e); + return null; + } + }) + .orElse(null); } @Override public Cert getConsumerConnectionConfig(URL remoteAddress) { - return remoteAddress.getOrDefaultApplicationModel().getApplicationConfigManager().getSsl() - .filter(sslConfig -> Objects.nonNull(sslConfig.getClientKeyCertChainPath())) - .filter(sslConfig -> Objects.nonNull(sslConfig.getClientPrivateKeyPath())) - .map(sslConfig -> { - try { - return new Cert( - IOUtils.toByteArray(sslConfig.getClientKeyCertChainPathStream()), - IOUtils.toByteArray(sslConfig.getClientPrivateKeyPathStream()), - sslConfig.getClientTrustCertCollectionPath() != null ? IOUtils.toByteArray(sslConfig.getClientTrustCertCollectionPathStream()) : null, - sslConfig.getClientKeyPassword()); - } catch (IOException e) { - logger.warn(LoggerCodeConstants.CONFIG_SSL_PATH_LOAD_FAILED, "", "", "Failed to load ssl config.", e); - return null; - } - }).orElse(null); + return remoteAddress + .getOrDefaultApplicationModel() + .getApplicationConfigManager() + .getSsl() + .filter(sslConfig -> Objects.nonNull(sslConfig.getClientKeyCertChainPath())) + .filter(sslConfig -> Objects.nonNull(sslConfig.getClientPrivateKeyPath())) + .map(sslConfig -> { + try { + return new Cert( + IOUtils.toByteArray(sslConfig.getClientKeyCertChainPathStream()), + IOUtils.toByteArray(sslConfig.getClientPrivateKeyPathStream()), + sslConfig.getClientTrustCertCollectionPath() != null + ? IOUtils.toByteArray(sslConfig.getClientTrustCertCollectionPathStream()) + : null, + sslConfig.getClientKeyPassword()); + } catch (IOException e) { + logger.warn( + LoggerCodeConstants.CONFIG_SSL_PATH_LOAD_FAILED, + "", + "", + "Failed to load ssl config.", + e); + return null; + } + }) + .orElse(null); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/status/Status.java b/dubbo-common/src/main/java/org/apache/dubbo/common/status/Status.java index 57ae3727e2..33dc5ca6e7 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/status/Status.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/status/Status.java @@ -75,5 +75,4 @@ public class Status { */ UNKNOWN } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/status/StatusChecker.java b/dubbo-common/src/main/java/org/apache/dubbo/common/status/StatusChecker.java index 2ff75cfaa7..d6b2e5c0c8 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/status/StatusChecker.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/status/StatusChecker.java @@ -31,5 +31,4 @@ public interface StatusChecker { * @return status */ Status check(); - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/status/reporter/FrameworkStatusReportService.java b/dubbo-common/src/main/java/org/apache/dubbo/common/status/reporter/FrameworkStatusReportService.java index 8c8c65a8d3..ef953b443e 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/status/reporter/FrameworkStatusReportService.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/status/reporter/FrameworkStatusReportService.java @@ -39,7 +39,9 @@ public class FrameworkStatusReportService implements ScopeModelAware { @Override public void setApplicationModel(ApplicationModel applicationModel) { this.applicationModel = applicationModel; - reporters = applicationModel.getExtensionLoader(FrameworkStatusReporter.class).getSupportedExtensionInstances(); + reporters = applicationModel + .getExtensionLoader(FrameworkStatusReporter.class) + .getSupportedExtensionInstances(); } public void reportRegistrationStatus(Object obj) { @@ -89,7 +91,8 @@ public class FrameworkStatusReportService implements ScopeModelAware { return JsonUtils.toJson(migrationStatus); } - public String createMigrationStepReport(String interfaceName, String version, String group, String originStep, String newStep, String success) { + public String createMigrationStepReport( + String interfaceName, String version, String group, String originStep, String newStep, String success) { HashMap migrationStatus = new HashMap<>(); migrationStatus.put("type", "migrationStepStatus"); migrationStatus.put("application", applicationModel.getApplicationName()); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/status/reporter/FrameworkStatusReporter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/status/reporter/FrameworkStatusReporter.java index 293bb491bf..d8eb6ac53d 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/status/reporter/FrameworkStatusReporter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/status/reporter/FrameworkStatusReporter.java @@ -20,10 +20,8 @@ import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.rpc.model.ScopeModelAware; - @SPI(scope = ExtensionScope.APPLICATION) public interface FrameworkStatusReporter extends ScopeModelAware { void report(String type, Object obj); - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/status/support/LoadStatusChecker.java b/dubbo-common/src/main/java/org/apache/dubbo/common/status/support/LoadStatusChecker.java index c6a40d2b0a..a6f7432b7c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/status/support/LoadStatusChecker.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/status/support/LoadStatusChecker.java @@ -48,4 +48,3 @@ public class LoadStatusChecker implements StatusChecker { return new Status(level, message); } } - diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/status/support/MemoryStatusChecker.java b/dubbo-common/src/main/java/org/apache/dubbo/common/status/support/MemoryStatusChecker.java index 411fa2f3d9..a4cd0d3f42 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/status/support/MemoryStatusChecker.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/status/support/MemoryStatusChecker.java @@ -32,10 +32,10 @@ public class MemoryStatusChecker implements StatusChecker { long freeMemory = runtime.freeMemory(); long totalMemory = runtime.totalMemory(); long maxMemory = runtime.maxMemory(); - boolean ok = (maxMemory - (totalMemory - freeMemory) > 2*1024*1024); // Alarm when spare memory < 2M - String msg = "max:" + (maxMemory / 1024 / 1024) + "M,total:" - + (totalMemory / 1024 / 1024) + "M,used:" + ((totalMemory / 1024 / 1024) - (freeMemory / 1024 / 1024)) + "M,free:" + (freeMemory / 1024 / 1024) + "M"; + boolean ok = (maxMemory - (totalMemory - freeMemory) > 2 * 1024 * 1024); // Alarm when spare memory < 2M + String msg = "max:" + (maxMemory / 1024 / 1024) + "M,total:" + (totalMemory / 1024 / 1024) + "M,used:" + + ((totalMemory / 1024 / 1024) - (freeMemory / 1024 / 1024)) + "M,free:" + (freeMemory / 1024 / 1024) + + "M"; return new Status(ok ? Status.Level.OK : Status.Level.WARN, msg); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/status/support/StatusUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/status/support/StatusUtils.java index d70a219f18..18beaf3889 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/status/support/StatusUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/status/support/StatusUtils.java @@ -51,5 +51,4 @@ public class StatusUtils { } return new Status(level, msg.toString()); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/store/DataStore.java b/dubbo-common/src/main/java/org/apache/dubbo/common/store/DataStore.java index 59d7414f7b..4b8fc31ab6 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/store/DataStore.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/store/DataStore.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.store; import org.apache.dubbo.common.extension.ExtensionScope; @@ -35,5 +34,4 @@ public interface DataStore { void put(String componentName, String key, Object value); void remove(String componentName, String key); - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/store/support/SimpleDataStore.java b/dubbo-common/src/main/java/org/apache/dubbo/common/store/support/SimpleDataStore.java index 61c0956b44..cabb9e903d 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/store/support/SimpleDataStore.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/store/support/SimpleDataStore.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.store.support; import org.apache.dubbo.common.store.DataStore; @@ -28,8 +27,7 @@ import java.util.concurrent.ConcurrentMap; public class SimpleDataStore implements DataStore { // > - private final ConcurrentMap> data = - new ConcurrentHashMap<>(); + private final ConcurrentMap> data = new ConcurrentHashMap<>(); @Override public Map get(String componentName) { @@ -51,7 +49,8 @@ public class SimpleDataStore implements DataStore { @Override public void put(String componentName, String key, Object value) { - Map componentData = ConcurrentHashMapUtils.computeIfAbsent(data, componentName, k -> new ConcurrentHashMap<>()); + Map componentData = + ConcurrentHashMapUtils.computeIfAbsent(data, componentName, k -> new ConcurrentHashMap<>()); componentData.put(key, value); } @@ -62,5 +61,4 @@ public class SimpleDataStore implements DataStore { } data.get(componentName).remove(key); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/stream/StreamObserver.java b/dubbo-common/src/main/java/org/apache/dubbo/common/stream/StreamObserver.java index 89d7eed79c..1b4c2cb235 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/stream/StreamObserver.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/stream/StreamObserver.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.stream; /** @@ -25,7 +24,6 @@ package org.apache.dubbo.common.stream; */ public interface StreamObserver { - /** * onNext * diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/system/OperatingSystemBeanManager.java b/dubbo-common/src/main/java/org/apache/dubbo/common/system/OperatingSystemBeanManager.java index f3de66fa87..f241d75182 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/system/OperatingSystemBeanManager.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/system/OperatingSystemBeanManager.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.system; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -35,14 +34,15 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_CLASS */ public class OperatingSystemBeanManager { - private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(OperatingSystemBeanManager.class); + private static final ErrorTypeAwareLogger LOGGER = + LoggerFactory.getErrorTypeAwareLogger(OperatingSystemBeanManager.class); /** * com.ibm for J9 * com.sun for HotSpot */ - private static final List OPERATING_SYSTEM_BEAN_CLASS_NAMES = Arrays.asList( - "com.sun.management.OperatingSystemMXBean", "com.ibm.lang.management.OperatingSystemMXBean"); + private static final List OPERATING_SYSTEM_BEAN_CLASS_NAMES = + Arrays.asList("com.sun.management.OperatingSystemMXBean", "com.ibm.lang.management.OperatingSystemMXBean"); private static final OperatingSystemMXBean OPERATING_SYSTEM_BEAN; @@ -59,8 +59,7 @@ public class OperatingSystemBeanManager { PROCESS_CPU_USAGE_METHOD = deduceMethod("getProcessCpuLoad"); } - private OperatingSystemBeanManager() { - } + private OperatingSystemBeanManager() {} public static OperatingSystemMXBean getOperatingSystemBean() { return OPERATING_SYSTEM_BEAN; @@ -79,7 +78,12 @@ public class OperatingSystemBeanManager { try { return Class.forName(className); } catch (ClassNotFoundException e) { - LOGGER.warn(COMMON_CLASS_NOT_FOUND, "", "", "[OperatingSystemBeanManager] Failed to load operating system bean class.", e); + LOGGER.warn( + COMMON_CLASS_NOT_FOUND, + "", + "", + "[OperatingSystemBeanManager] Failed to load operating system bean class.", + e); } } return null; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalRunnable.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalRunnable.java index 22fde9a863..2d0b95144f 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalRunnable.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalRunnable.java @@ -14,21 +14,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.threadlocal; - /** * InternalRunnable * There is a risk of memory leak when using {@link InternalThreadLocal} without calling * {@link InternalThreadLocal#removeAll()}. * This design is learning from {@see io.netty.util.concurrent.FastThreadLocalRunnable} which is in Netty. */ -public class InternalRunnable implements Runnable{ +public class InternalRunnable implements Runnable { private final Runnable runnable; - public InternalRunnable(Runnable runnable){ - this.runnable=runnable; + public InternalRunnable(Runnable runnable) { + this.runnable = runnable; } /** @@ -37,9 +35,9 @@ public class InternalRunnable implements Runnable{ */ @Override public void run() { - try{ + try { runnable.run(); - }finally { + } finally { InternalThreadLocal.removeAll(); } } @@ -47,7 +45,7 @@ public class InternalRunnable implements Runnable{ /** * Wrap ordinary Runnable into {@link InternalThreadLocal}. */ - public static Runnable Wrap(Runnable runnable){ - return runnable instanceof InternalRunnable?runnable:new InternalRunnable(runnable); + public static Runnable Wrap(Runnable runnable) { + return runnable instanceof InternalRunnable ? runnable : new InternalRunnable(runnable); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThread.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThread.java index e891cd8f7f..dc6ed89625 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThread.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThread.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.threadlocal; /** @@ -24,8 +23,7 @@ public class InternalThread extends Thread { private InternalThreadLocalMap threadLocalMap; - public InternalThread() { - } + public InternalThread() {} public InternalThread(Runnable target) { super(target); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/NamedInternalThreadFactory.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/NamedInternalThreadFactory.java index 0bb305f03f..7b7f14aae0 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/NamedInternalThreadFactory.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/NamedInternalThreadFactory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.threadlocal; import org.apache.dubbo.common.utils.NamedThreadFactory; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemoryLimitCalculator.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemoryLimitCalculator.java index 1be3d6c5a1..474148561a 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemoryLimitCalculator.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemoryLimitCalculator.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.threadpool; import org.apache.dubbo.common.resource.GlobalResourcesRepository; @@ -50,9 +49,11 @@ public class MemoryLimitCalculator { // notice: refresh may be called for more than once because there is no lock refresh(); if (refreshStarted.compareAndSet(false, true)) { - ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-Memory-Calculator")); + ScheduledExecutorService scheduledExecutorService = + Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-Memory-Calculator")); // check every 50 ms to improve performance - scheduledExecutorService.scheduleWithFixedDelay(MemoryLimitCalculator::refresh, 50, 50, TimeUnit.MILLISECONDS); + scheduledExecutorService.scheduleWithFixedDelay( + MemoryLimitCalculator::refresh, 50, 50, TimeUnit.MILLISECONDS); GlobalResourcesRepository.registerGlobalDisposable(() -> { refreshStarted.set(false); scheduledExecutorService.shutdown(); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemoryLimitedLinkedBlockingQueue.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemoryLimitedLinkedBlockingQueue.java index f64a9f041e..e394aeb81f 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemoryLimitedLinkedBlockingQueue.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemoryLimitedLinkedBlockingQueue.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.threadpool; import java.lang.instrument.Instrumentation; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemoryLimiter.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemoryLimiter.java index b26e37eb27..9eb3ac77fb 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemoryLimiter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemoryLimiter.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.threadpool; import java.lang.instrument.Instrumentation; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemorySafeLinkedBlockingQueue.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemorySafeLinkedBlockingQueue.java index 31e24a5b34..0950362860 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemorySafeLinkedBlockingQueue.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/MemorySafeLinkedBlockingQueue.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.threadpool; import org.apache.dubbo.common.concurrent.DiscardPolicy; @@ -48,15 +47,14 @@ public class MemorySafeLinkedBlockingQueue extends LinkedBlockingQueue { public MemorySafeLinkedBlockingQueue(final long maxFreeMemory) { super(Integer.MAX_VALUE); this.maxFreeMemory = maxFreeMemory; - //default as DiscardPolicy to ensure compatibility with the old version + // default as DiscardPolicy to ensure compatibility with the old version this.rejector = new DiscardPolicy<>(); } - public MemorySafeLinkedBlockingQueue(final Collection c, - final int maxFreeMemory) { + public MemorySafeLinkedBlockingQueue(final Collection c, final int maxFreeMemory) { super(c); this.maxFreeMemory = maxFreeMemory; - //default as DiscardPolicy to ensure compatibility with the old version + // default as DiscardPolicy to ensure compatibility with the old version this.rejector = new DiscardPolicy<>(); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/ThreadPool.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/ThreadPool.java index b1ff4a8b08..d06e8ea508 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/ThreadPool.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/ThreadPool.java @@ -28,7 +28,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; /** * ThreadPool */ -//TODO which scope for ThreadPool? APPLICATION or FRAMEWORK +// TODO which scope for ThreadPool? APPLICATION or FRAMEWORK @SPI(value = "fixed", scope = ExtensionScope.FRAMEWORK) public interface ThreadPool { @@ -40,5 +40,4 @@ public interface ThreadPool { */ @Adaptive({THREADPOOL_KEY}) Executor getExecutor(URL url); - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/ThreadlessExecutor.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/ThreadlessExecutor.java index 5ff664bc0b..85e590ae4a 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/ThreadlessExecutor.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/ThreadlessExecutor.java @@ -105,7 +105,6 @@ public class ThreadlessExecutor extends AbstractExecutorService { /** * The following methods are still not supported */ - @Override public void shutdown() { shutdownNow(); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/concurrent/ScheduledCompletableFuture.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/concurrent/ScheduledCompletableFuture.java index 9dba74f897..215e1d139e 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/concurrent/ScheduledCompletableFuture.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/concurrent/ScheduledCompletableFuture.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.threadpool.concurrent; - import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @@ -25,11 +24,7 @@ import java.util.function.Supplier; public class ScheduledCompletableFuture { public static CompletableFuture schedule( - ScheduledExecutorService executor, - Supplier task, - long delay, - TimeUnit unit - ) { + ScheduledExecutorService executor, Supplier task, long delay, TimeUnit unit) { CompletableFuture completableFuture = new CompletableFuture<>(); executor.schedule( () -> { @@ -40,26 +35,19 @@ public class ScheduledCompletableFuture { } }, delay, - unit - ); + unit); return completableFuture; } - public static CompletableFuture submit( - ScheduledExecutorService executor, - Supplier task - ) { + public static CompletableFuture submit(ScheduledExecutorService executor, Supplier task) { CompletableFuture completableFuture = new CompletableFuture<>(); - executor.submit( - () -> { - try { - return completableFuture.complete(task.get()); - } catch (Throwable t) { - return completableFuture.completeExceptionally(t); - } - } - ); + executor.submit(() -> { + try { + return completableFuture.complete(task.get()); + } catch (Throwable t) { + return completableFuture.completeExceptionally(t); + } + }); return completableFuture; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/DefaultExecutorRepository.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/DefaultExecutorRepository.java index ae1c9aaacc..8bb1460011 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/DefaultExecutorRepository.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/DefaultExecutorRepository.java @@ -63,7 +63,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXP * Consider implementing {@code Lifecycle} to enable executors shutdown when the process stops. */ public class DefaultExecutorRepository implements ExecutorRepository, ExtensionAccessorAware { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DefaultExecutorRepository.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(DefaultExecutorRepository.class); private static final String MAX_KEY = String.valueOf(Integer.MAX_VALUE); @@ -84,7 +85,8 @@ public class DefaultExecutorRepository implements ExecutorRepository, ExtensionA public DefaultExecutorRepository(ApplicationModel applicationModel) { this.applicationModel = applicationModel; - this.frameworkExecutorRepository = applicationModel.getFrameworkModel().getBeanFactory().getBean(FrameworkExecutorRepository.class); + this.frameworkExecutorRepository = + applicationModel.getFrameworkModel().getBeanFactory().getBean(FrameworkExecutorRepository.class); this.dataStore = applicationModel.getExtensionLoader(DataStore.class).getDefaultExtension(); } @@ -97,14 +99,16 @@ public class DefaultExecutorRepository implements ExecutorRepository, ExtensionA @Override public synchronized ExecutorService createExecutorIfAbsent(URL url) { String executorKey = getExecutorKey(url); - ConcurrentMap executors = ConcurrentHashMapUtils.computeIfAbsent(data, executorKey, k -> new ConcurrentHashMap<>()); + ConcurrentMap executors = + ConcurrentHashMapUtils.computeIfAbsent(data, executorKey, k -> new ConcurrentHashMap<>()); String executorCacheKey = getExecutorSecondKey(url); url = setThreadNameIfAbsent(url, executorCacheKey); URL finalUrl = url; - ExecutorService executor = ConcurrentHashMapUtils.computeIfAbsent(executors, executorCacheKey, k -> createExecutor(finalUrl)); + ExecutorService executor = + ConcurrentHashMapUtils.computeIfAbsent(executors, executorCacheKey, k -> createExecutor(finalUrl)); // If executor has been shut down, create a new one if (executor.isShutdown() || executor.isTerminated()) { executors.remove(executorCacheKey); @@ -184,7 +188,10 @@ public class DefaultExecutorRepository implements ExecutorRepository, ExtensionA } protected ExecutorService createExecutor(URL url) { - return (ExecutorService) extensionAccessor.getExtensionLoader(ThreadPool.class).getAdaptiveExtension().getExecutor(url); + return (ExecutorService) extensionAccessor + .getExtensionLoader(ThreadPool.class) + .getAdaptiveExtension() + .getExecutor(url); } @Override @@ -196,8 +203,12 @@ public class DefaultExecutorRepository implements ExecutorRepository, ExtensionA * have Executor instances generated and stored. */ if (executors == null) { - logger.warn(COMMON_EXECUTORS_NO_FOUND, "", "", "No available executors, this is not expected, framework should call createExecutorIfAbsent first" + - "before coming to here."); + logger.warn( + COMMON_EXECUTORS_NO_FOUND, + "", + "", + "No available executors, this is not expected, framework should call createExecutorIfAbsent first" + + "before coming to here."); return null; } @@ -227,8 +238,12 @@ public class DefaultExecutorRepository implements ExecutorRepository, ExtensionA * have Executor instances generated and stored. */ if (executors == null) { - logger.warn(COMMON_EXECUTORS_NO_FOUND, "", "", "No available executors, this is not expected, framework should call createExecutorIfAbsent first" + - "before coming to here."); + logger.warn( + COMMON_EXECUTORS_NO_FOUND, + "", + "", + "No available executors, this is not expected, framework should call createExecutorIfAbsent first" + + "before coming to here."); return null; } @@ -252,8 +267,7 @@ public class DefaultExecutorRepository implements ExecutorRepository, ExtensionA @Override public void updateThreadpool(URL url, ExecutorService executor) { try { - if (url.hasParameter(THREADS_KEY) - && executor instanceof ThreadPoolExecutor && !executor.isShutdown()) { + if (url.hasParameter(THREADS_KEY) && executor instanceof ThreadPoolExecutor && !executor.isShutdown()) { ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor; int threads = url.getParameter(THREADS_KEY, 0); int max = threadPoolExecutor.getMaximumPoolSize(); @@ -284,8 +298,8 @@ public class DefaultExecutorRepository implements ExecutorRepository, ExtensionA int coreSize = getExportThreadNum(); String applicationName = applicationModel.tryGetApplicationName(); applicationName = StringUtils.isEmpty(applicationName) ? "app" : applicationName; - serviceExportExecutor = Executors.newScheduledThreadPool(coreSize, - new NamedThreadFactory("Dubbo-" + applicationName + "-service-export", true)); + serviceExportExecutor = Executors.newScheduledThreadPool( + coreSize, new NamedThreadFactory("Dubbo-" + applicationName + "-service-export", true)); } } return serviceExportExecutor; @@ -313,8 +327,8 @@ public class DefaultExecutorRepository implements ExecutorRepository, ExtensionA int coreSize = getReferThreadNum(); String applicationName = applicationModel.tryGetApplicationName(); applicationName = StringUtils.isEmpty(applicationName) ? "app" : applicationName; - serviceReferExecutor = Executors.newFixedThreadPool(coreSize, - new NamedThreadFactory("Dubbo-" + applicationName + "-service-refer", true)); + serviceReferExecutor = Executors.newFixedThreadPool( + coreSize, new NamedThreadFactory("Dubbo-" + applicationName + "-service-refer", true)); } } return serviceReferExecutor; @@ -344,7 +358,8 @@ public class DefaultExecutorRepository implements ExecutorRepository, ExtensionA } } if (threadNum == null) { - logger.info("Cannot get config `export-thread-num` from module config, using default: " + DEFAULT_EXPORT_THREAD_NUM); + logger.info("Cannot get config `export-thread-num` from module config, using default: " + + DEFAULT_EXPORT_THREAD_NUM); return DEFAULT_EXPORT_THREAD_NUM; } return threadNum; @@ -357,11 +372,11 @@ public class DefaultExecutorRepository implements ExecutorRepository, ExtensionA } Integer threadNum = moduleConfig.getExportThreadNum(); if (threadNum == null) { - threadNum = moduleModel.getConfigManager().getProviders() - .stream() - .map(ProviderConfig::getExportThreadNum) - .filter(k -> k != null && k > 0) - .findAny().orElse(null); + threadNum = moduleModel.getConfigManager().getProviders().stream() + .map(ProviderConfig::getExportThreadNum) + .filter(k -> k != null && k > 0) + .findAny() + .orElse(null); } return threadNum; } @@ -376,7 +391,8 @@ public class DefaultExecutorRepository implements ExecutorRepository, ExtensionA } } if (threadNum == null) { - logger.info("Cannot get config `refer-thread-num` from module config, using default: " + DEFAULT_REFER_THREAD_NUM); + logger.info("Cannot get config `refer-thread-num` from module config, using default: " + + DEFAULT_REFER_THREAD_NUM); return DEFAULT_REFER_THREAD_NUM; } return threadNum; @@ -389,11 +405,11 @@ public class DefaultExecutorRepository implements ExecutorRepository, ExtensionA } Integer threadNum = moduleConfig.getReferThreadNum(); if (threadNum == null) { - threadNum = moduleModel.getConfigManager().getConsumers() - .stream() - .map(ConsumerConfig::getReferThreadNum) - .filter(k -> k != null && k > 0) - .findAny().orElse(null); + threadNum = moduleModel.getConfigManager().getConsumers().stream() + .map(ConsumerConfig::getReferThreadNum) + .filter(k -> k != null && k > 0) + .findAny() + .orElse(null); } return threadNum; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/ExecutorRepository.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/ExecutorRepository.java index 67ab0cf2ab..9954937de1 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/ExecutorRepository.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/ExecutorRepository.java @@ -57,8 +57,6 @@ public interface ExecutorRepository { ExecutorService getExecutor(ServiceModel serviceModel, URL url); - - /** * Modify some of the threadpool's properties according to the url, for example, coreSize, maxSize, ... * @@ -183,14 +181,17 @@ public interface ExecutorRepository { ExecutorSupport getExecutorSupport(URL url); static ExecutorRepository getInstance(ApplicationModel applicationModel) { - ExtensionLoader extensionLoader = applicationModel.getExtensionLoader(ExecutorRepository.class); + ExtensionLoader extensionLoader = + applicationModel.getExtensionLoader(ExecutorRepository.class); String mode = getMode(applicationModel); - return StringUtils.isNotEmpty(mode) ? extensionLoader.getExtension(mode) : extensionLoader.getDefaultExtension(); + return StringUtils.isNotEmpty(mode) + ? extensionLoader.getExtension(mode) + : extensionLoader.getDefaultExtension(); } static String getMode(ApplicationModel applicationModel) { - Optional optional = applicationModel.getApplicationConfigManager().getApplication(); + Optional optional = + applicationModel.getApplicationConfigManager().getApplication(); return optional.map(ApplicationConfig::getExecutorManagementMode).orElse(EXECUTOR_MANAGEMENT_MODE_ISOLATION); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/FrameworkExecutorRepository.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/FrameworkExecutorRepository.java index 8cbc0b28d9..e3feee96f3 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/FrameworkExecutorRepository.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/manager/FrameworkExecutorRepository.java @@ -36,7 +36,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_SERVER_S import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN; public class FrameworkExecutorRepository implements Disposable { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FrameworkExecutorRepository.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(FrameworkExecutorRepository.class); private final ExecutorService sharedExecutor; private final ScheduledExecutorService sharedScheduledExecutor; @@ -63,40 +64,61 @@ public class FrameworkExecutorRepository implements Disposable { public FrameworkExecutorRepository() { sharedExecutor = Executors.newCachedThreadPool(new NamedThreadFactory("Dubbo-framework-shared-handler", true)); - sharedScheduledExecutor = Executors.newScheduledThreadPool(8, new NamedThreadFactory("Dubbo-framework-shared-scheduler", true)); + sharedScheduledExecutor = + Executors.newScheduledThreadPool(8, new NamedThreadFactory("Dubbo-framework-shared-scheduler", true)); int availableProcessors = Runtime.getRuntime().availableProcessors(); for (int i = 0; i < availableProcessors; i++) { ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor( - new NamedThreadFactory("Dubbo-framework-scheduler-" + i, true)); + new NamedThreadFactory("Dubbo-framework-scheduler-" + i, true)); scheduledExecutors.addItem(scheduler); - executorServiceRing.addItem(new ThreadPoolExecutor(1, 1, - 0L, TimeUnit.MILLISECONDS, - new LinkedBlockingQueue<>(1024), new NamedInternalThreadFactory("Dubbo-framework-state-router-loop-" + i, true) - , new ThreadPoolExecutor.AbortPolicy())); + executorServiceRing.addItem(new ThreadPoolExecutor( + 1, + 1, + 0L, + TimeUnit.MILLISECONDS, + new LinkedBlockingQueue<>(1024), + new NamedInternalThreadFactory("Dubbo-framework-state-router-loop-" + i, true), + new ThreadPoolExecutor.AbortPolicy())); } - connectivityScheduledExecutor = Executors.newScheduledThreadPool(availableProcessors, new NamedThreadFactory("Dubbo-framework-connectivity-scheduler", true)); - cacheRefreshingScheduledExecutor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-framework-cache-refreshing-scheduler", true)); - mappingRefreshingExecutor = Executors.newFixedThreadPool(availableProcessors, new NamedThreadFactory("Dubbo-framework-mapping-refreshing-scheduler", true)); - poolRouterExecutor = new ThreadPoolExecutor(1, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024), - new NamedInternalThreadFactory("Dubbo-framework-state-router-pool-router", true), new ThreadPoolExecutor.AbortPolicy()); + connectivityScheduledExecutor = Executors.newScheduledThreadPool( + availableProcessors, new NamedThreadFactory("Dubbo-framework-connectivity-scheduler", true)); + cacheRefreshingScheduledExecutor = Executors.newSingleThreadScheduledExecutor( + new NamedThreadFactory("Dubbo-framework-cache-refreshing-scheduler", true)); + mappingRefreshingExecutor = Executors.newFixedThreadPool( + availableProcessors, new NamedThreadFactory("Dubbo-framework-mapping-refreshing-scheduler", true)); + poolRouterExecutor = new ThreadPoolExecutor( + 1, + 10, + 0L, + TimeUnit.MILLISECONDS, + new LinkedBlockingQueue<>(1024), + new NamedInternalThreadFactory("Dubbo-framework-state-router-pool-router", true), + new ThreadPoolExecutor.AbortPolicy()); for (int i = 0; i < availableProcessors; i++) { ScheduledExecutorService serviceDiscoveryAddressNotificationExecutor = - Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-framework-SD-address-refresh-" + i)); - ScheduledExecutorService registryNotificationExecutor = - Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-framework-registry-notification-" + i)); + Executors.newSingleThreadScheduledExecutor( + new NamedThreadFactory("Dubbo-framework-SD-address-refresh-" + i)); + ScheduledExecutorService registryNotificationExecutor = Executors.newSingleThreadScheduledExecutor( + new NamedThreadFactory("Dubbo-framework-registry-notification-" + i)); serviceDiscoveryAddressNotificationExecutorRing.addItem(serviceDiscoveryAddressNotificationExecutor); registryNotificationExecutorRing.addItem(registryNotificationExecutor); } - metadataRetryExecutor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-framework-metadata-retry")); - internalServiceExecutor = new ThreadPoolExecutor(0, 100, 60L, TimeUnit.SECONDS, - new SynchronousQueue<>(), new NamedInternalThreadFactory("Dubbo-internal-service", true), - new ThreadPoolExecutor.AbortPolicy()); + metadataRetryExecutor = + Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-framework-metadata-retry")); + internalServiceExecutor = new ThreadPoolExecutor( + 0, + 100, + 60L, + TimeUnit.SECONDS, + new SynchronousQueue<>(), + new NamedInternalThreadFactory("Dubbo-internal-service", true), + new ThreadPoolExecutor.AbortPolicy()); } /** @@ -152,7 +174,6 @@ public class FrameworkExecutorRepository implements Disposable { return sharedScheduledExecutor; } - public ExecutorService getPoolRouterExecutor() { return poolRouterExecutor; } @@ -206,16 +227,15 @@ public class FrameworkExecutorRepository implements Disposable { shutdownExecutorService(sharedScheduledExecutor, "sharedScheduledExecutor"); // serviceDiscoveryAddressNotificationExecutorRing - shutdownExecutorServices(serviceDiscoveryAddressNotificationExecutorRing.listItems(), - "serviceDiscoveryAddressNotificationExecutorRing"); + shutdownExecutorServices( + serviceDiscoveryAddressNotificationExecutorRing.listItems(), + "serviceDiscoveryAddressNotificationExecutorRing"); // registryNotificationExecutorRing - shutdownExecutorServices(registryNotificationExecutorRing.listItems(), - "registryNotificationExecutorRing"); + shutdownExecutorServices(registryNotificationExecutorRing.listItems(), "registryNotificationExecutorRing"); // mappingRefreshingExecutor - shutdownExecutorService(mappingRefreshingExecutor, - "mappingRefreshingExecutor"); + shutdownExecutorService(mappingRefreshingExecutor, "mappingRefreshingExecutor"); } private void shutdownExecutorServices(List executorServices, String msg) { @@ -228,10 +248,12 @@ public class FrameworkExecutorRepository implements Disposable { try { executorService.shutdownNow(); if (!executorService.awaitTermination( - ConfigurationUtils.reCalShutdownTime(DEFAULT_SERVER_SHUTDOWN_TIMEOUT), - TimeUnit.MILLISECONDS)) { - logger.warn(COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN, "", "", - "Wait global executor service terminated timeout."); + ConfigurationUtils.reCalShutdownTime(DEFAULT_SERVER_SHUTDOWN_TIMEOUT), TimeUnit.MILLISECONDS)) { + logger.warn( + COMMON_UNEXPECTED_EXECUTORS_SHUTDOWN, + "", + "", + "Wait global executor service terminated timeout."); } } catch (Exception e) { String msg = "shutdown executor service [" + name + "] failed: "; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReport.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReport.java index 16c55331b5..223a72419d 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReport.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReport.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.threadpool.support; import org.apache.dubbo.common.URL; @@ -55,7 +54,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXP */ public class AbortPolicyWithReport extends ThreadPoolExecutor.AbortPolicy { - protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbortPolicyWithReport.class); + protected static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(AbortPolicyWithReport.class); private final String threadName; @@ -79,31 +79,42 @@ public class AbortPolicyWithReport extends ThreadPoolExecutor.AbortPolicy { this.threadName = threadName; this.url = url; - String threadPoolExhaustedListeners = - url.getParameter(THREAD_POOL_EXHAUSTED_LISTENERS_KEY, (String) url.getAttribute(THREAD_POOL_EXHAUSTED_LISTENERS_KEY)); + String threadPoolExhaustedListeners = url.getParameter( + THREAD_POOL_EXHAUSTED_LISTENERS_KEY, (String) url.getAttribute(THREAD_POOL_EXHAUSTED_LISTENERS_KEY)); Set listenerKeys = StringUtils.splitToSet(threadPoolExhaustedListeners, COMMA_SEPARATOR_CHAR, true); FrameworkModel frameworkModel = url.getOrDefaultFrameworkModel(); - ExtensionLoader extensionLoader = frameworkModel.getExtensionLoader(ThreadPoolExhaustedListener.class); + ExtensionLoader extensionLoader = + frameworkModel.getExtensionLoader(ThreadPoolExhaustedListener.class); listenerKeys.forEach(key -> { if (extensionLoader.hasExtension(key)) { addThreadPoolExhaustedEventListener(extensionLoader.getExtension(key)); } }); - } @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { - String msg = String.format("Thread pool is EXHAUSTED!" + - " Thread Name: %s, Pool Size: %d (active: %d, core: %d, max: %d, largest: %d)," + - " Task: %d (completed: %d)," + - " Executor status:(isShutdown:%s, isTerminated:%s, isTerminating:%s), in %s://%s:%d!", - threadName, e.getPoolSize(), e.getActiveCount(), e.getCorePoolSize(), e.getMaximumPoolSize(), - e.getLargestPoolSize(), - e.getTaskCount(), e.getCompletedTaskCount(), e.isShutdown(), e.isTerminated(), e.isTerminating(), - url.getProtocol(), url.getIp(), url.getPort()); + String msg = String.format( + "Thread pool is EXHAUSTED!" + + " Thread Name: %s, Pool Size: %d (active: %d, core: %d, max: %d, largest: %d)," + + " Task: %d (completed: %d)," + + " Executor status:(isShutdown:%s, isTerminated:%s, isTerminating:%s), in %s://%s:%d!", + threadName, + e.getPoolSize(), + e.getActiveCount(), + e.getCorePoolSize(), + e.getMaximumPoolSize(), + e.getLargestPoolSize(), + e.getTaskCount(), + e.getCompletedTaskCount(), + e.isShutdown(), + e.isTerminated(), + e.isTerminating(), + url.getProtocol(), + url.getIp(), + url.getPort()); // 0-1 - Thread pool is EXHAUSTED! logger.warn(COMMON_THREAD_POOL_EXHAUSTED, "too much client requesting provider", "", msg); @@ -137,7 +148,7 @@ public class AbortPolicyWithReport extends ThreadPoolExecutor.AbortPolicy { private void dumpJStack() { long now = System.currentTimeMillis(); - //dump every 10 minutes + // dump every 10 minutes if (now - lastPrintTime < TEN_MINUTES_MILLS) { return; } @@ -167,9 +178,9 @@ public class AbortPolicyWithReport extends ThreadPoolExecutor.AbortPolicy { } String dateStr = sdf.format(new Date()); - //try-with-resources - try (FileOutputStream jStackStream = new FileOutputStream( - new File(dumpPath, "Dubbo_JStack.log" + "." + dateStr))) { + // try-with-resources + try (FileOutputStream jStackStream = + new FileOutputStream(new File(dumpPath, "Dubbo_JStack.log" + "." + dateStr))) { jstack(jStackStream); } catch (Exception t) { logger.error(COMMON_UNEXPECTED_CREATE_DUMP, "", "", "dump jStack error", t); @@ -179,10 +190,9 @@ public class AbortPolicyWithReport extends ThreadPoolExecutor.AbortPolicy { } }); } finally { - //must shutdown thread pool ,if not will lead to OOM + // must shutdown thread pool ,if not will lead to OOM pool.shutdown(); } - } protected void jstack(FileOutputStream jStackStream) throws Exception { @@ -199,8 +209,13 @@ public class AbortPolicyWithReport extends ThreadPoolExecutor.AbortPolicy { if (dumpDirectory.mkdirs()) { logger.info(format("Dubbo dump directory[%s] created", dumpDirectory.getAbsolutePath())); } else { - logger.warn(COMMON_UNEXPECTED_CREATE_DUMP, "", "", format("Dubbo dump directory[%s] can't be created, use the 'user.home'[%s]", - dumpDirectory.getAbsolutePath(), USER_HOME)); + logger.warn( + COMMON_UNEXPECTED_CREATE_DUMP, + "", + "", + format( + "Dubbo dump directory[%s] can't be created, use the 'user.home'[%s]", + dumpDirectory.getAbsolutePath(), USER_HOME)); return USER_HOME; } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/cached/CachedThreadPool.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/cached/CachedThreadPool.java index 90419c4d90..11ee91656a 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/cached/CachedThreadPool.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/cached/CachedThreadPool.java @@ -49,7 +49,8 @@ public class CachedThreadPool implements ThreadPool { @Override public Executor getExecutor(URL url) { - String name = url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME)); + String name = + url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME)); int cores = url.getParameter(CORE_THREADS_KEY, DEFAULT_CORE_THREADS); int threads = url.getParameter(THREADS_KEY, Integer.MAX_VALUE); int queues = url.getParameter(QUEUES_KEY, DEFAULT_QUEUES); @@ -65,7 +66,13 @@ public class CachedThreadPool implements ThreadPool { blockingQueue = new LinkedBlockingQueue<>(queues); } - return new ThreadPoolExecutor(cores, threads, alive, TimeUnit.MILLISECONDS, blockingQueue, - new NamedInternalThreadFactory(name, true), new AbortPolicyWithReport(name, url)); + return new ThreadPoolExecutor( + cores, + threads, + alive, + TimeUnit.MILLISECONDS, + blockingQueue, + new NamedInternalThreadFactory(name, true), + new AbortPolicyWithReport(name, url)); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPool.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPool.java index 53ee25c0bb..71e1e096ef 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPool.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPool.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.threadpool.support.eager; import org.apache.dubbo.common.URL; @@ -44,7 +43,8 @@ public class EagerThreadPool implements ThreadPool { @Override public Executor getExecutor(URL url) { - String name = url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME)); + String name = + url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME)); int cores = url.getParameter(CORE_THREADS_KEY, DEFAULT_CORE_THREADS); int threads = url.getParameter(THREADS_KEY, Integer.MAX_VALUE); int queues = url.getParameter(QUEUES_KEY, DEFAULT_QUEUES); @@ -52,7 +52,8 @@ public class EagerThreadPool implements ThreadPool { // init queue and executor TaskQueue taskQueue = new TaskQueue<>(queues <= 0 ? 1 : queues); - EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor(cores, + EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor( + cores, threads, alive, TimeUnit.MILLISECONDS, diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolExecutor.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolExecutor.java index a0d2a34990..69fe89c21c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolExecutor.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolExecutor.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.threadpool.support.eager; import java.util.concurrent.RejectedExecutionException; @@ -28,12 +27,14 @@ import java.util.concurrent.TimeUnit; */ public class EagerThreadPoolExecutor extends ThreadPoolExecutor { - public EagerThreadPoolExecutor(int corePoolSize, - int maximumPoolSize, - long keepAliveTime, - TimeUnit unit, TaskQueue workQueue, - ThreadFactory threadFactory, - RejectedExecutionHandler handler) { + public EagerThreadPoolExecutor( + int corePoolSize, + int maximumPoolSize, + long keepAliveTime, + TimeUnit unit, + TaskQueue workQueue, + ThreadFactory threadFactory, + RejectedExecutionHandler handler) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/TaskQueue.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/TaskQueue.java index 30bb911392..17b804742b 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/TaskQueue.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/eager/TaskQueue.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.threadpool.support.eager; import java.util.concurrent.LinkedBlockingQueue; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/fixed/FixedThreadPool.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/fixed/FixedThreadPool.java index 06acc3961f..137f6af362 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/fixed/FixedThreadPool.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/fixed/FixedThreadPool.java @@ -45,7 +45,8 @@ public class FixedThreadPool implements ThreadPool { @Override public Executor getExecutor(URL url) { - String name = url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME)); + String name = + url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME)); int threads = url.getParameter(THREADS_KEY, DEFAULT_THREADS); int queues = url.getParameter(QUEUES_KEY, DEFAULT_QUEUES); @@ -59,8 +60,13 @@ public class FixedThreadPool implements ThreadPool { blockingQueue = new LinkedBlockingQueue<>(queues); } - return new ThreadPoolExecutor(threads, threads, 0, TimeUnit.MILLISECONDS, blockingQueue, - new NamedInternalThreadFactory(name, true), new AbortPolicyWithReport(name, url)); + return new ThreadPoolExecutor( + threads, + threads, + 0, + TimeUnit.MILLISECONDS, + blockingQueue, + new NamedInternalThreadFactory(name, true), + new AbortPolicyWithReport(name, url)); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/limited/LimitedThreadPool.java b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/limited/LimitedThreadPool.java index de70f3c512..919056fd26 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/limited/LimitedThreadPool.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/threadpool/support/limited/LimitedThreadPool.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.threadpool.support.limited; import org.apache.dubbo.common.URL; @@ -47,7 +46,8 @@ public class LimitedThreadPool implements ThreadPool { @Override public Executor getExecutor(URL url) { - String name = url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME)); + String name = + url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME)); int cores = url.getParameter(CORE_THREADS_KEY, DEFAULT_CORE_THREADS); int threads = url.getParameter(THREADS_KEY, DEFAULT_THREADS); int queues = url.getParameter(QUEUES_KEY, DEFAULT_QUEUES); @@ -62,8 +62,13 @@ public class LimitedThreadPool implements ThreadPool { blockingQueue = new LinkedBlockingQueue<>(queues); } - return new ThreadPoolExecutor(cores, threads, Long.MAX_VALUE, TimeUnit.MILLISECONDS, blockingQueue, - new NamedInternalThreadFactory(name, true), new AbortPolicyWithReport(name, url)); + return new ThreadPoolExecutor( + cores, + threads, + Long.MAX_VALUE, + TimeUnit.MILLISECONDS, + blockingQueue, + new NamedInternalThreadFactory(name, true), + new AbortPolicyWithReport(name, url)); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/DubboServiceAddressURL.java b/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/DubboServiceAddressURL.java index 1de2dfed4f..a7e9d9eef0 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/DubboServiceAddressURL.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/DubboServiceAddressURL.java @@ -41,7 +41,8 @@ public class DubboServiceAddressURL extends ServiceAddressURL { private ServiceConfigURL overrideURL; - public DubboServiceAddressURL(URLAddress urlAddress, URLParam urlParam, URL consumerURL, ServiceConfigURL overrideURL) { + public DubboServiceAddressURL( + URLAddress urlAddress, URLParam urlParam, URL consumerURL, ServiceConfigURL overrideURL) { super(urlAddress, urlParam, consumerURL); this.overrideURL = overrideURL; } @@ -98,7 +99,8 @@ public class DubboServiceAddressURL extends ServiceAddressURL { */ @Override public Map getAllParameters() { - Map allParameters = new HashMap<>((int)(super.getParameters().size()/.75 + 1)); + Map allParameters = + new HashMap<>((int) (super.getParameters().size() / .75 + 1)); allParameters.putAll(super.getParameters()); if (consumerURL != null) { allParameters.putAll(consumerURL.getParameters()); @@ -155,7 +157,8 @@ public class DubboServiceAddressURL extends ServiceAddressURL { return super.equals(obj); } else { DubboServiceAddressURL other = (DubboServiceAddressURL) obj; - boolean overrideEquals = Objects.equals(overrideURL.getParameters(), other.getOverrideURL().getParameters()); + boolean overrideEquals = Objects.equals( + overrideURL.getParameters(), other.getOverrideURL().getParameters()); if (!overrideEquals) { return false; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/PathURLAddress.java b/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/PathURLAddress.java index e072b61c3c..ad2c89845c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/PathURLAddress.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/PathURLAddress.java @@ -34,7 +34,8 @@ public class PathURLAddress extends URLAddress { this(protocol, username, password, path, host, port, null); } - public PathURLAddress(String protocol, String username, String password, String path, String host, int port, String rawAddress) { + public PathURLAddress( + String protocol, String username, String password, String path, String host, int port, String rawAddress) { super(host, port, rawAddress); this.protocol = protocol; @@ -130,12 +131,12 @@ public class PathURLAddress extends URLAddress { if (this == obj) return true; if (!(obj instanceof URLAddress)) return false; URLAddress that = (URLAddress) obj; - return Objects.equals(this.getProtocol(), that.getProtocol()) && - Objects.equals(this.getUsername(), that.getUsername()) && - Objects.equals(this.getPassword(), that.getPassword()) && - Objects.equals(this.getPath(), that.getPath()) && - Objects.equals(this.getHost(), that.getHost()) && - Objects.equals(this.getPort(), that.getPort()); + return Objects.equals(this.getProtocol(), that.getProtocol()) + && Objects.equals(this.getUsername(), that.getUsername()) + && Objects.equals(this.getPassword(), that.getPassword()) + && Objects.equals(this.getPath(), that.getPath()) + && Objects.equals(this.getHost(), that.getHost()) + && Objects.equals(this.getPort(), that.getPort()); } @Override @@ -149,15 +150,15 @@ public class PathURLAddress extends URLAddress { buf.append(protocol); buf.append("://"); } -// -// if (StringUtils.isNotEmpty(username)) { -// buf.append(username); -// if (StringUtils.isNotEmpty(password)) { -// buf.append(":"); -// buf.append(password); -// } -// buf.append("@"); -// } + // + // if (StringUtils.isNotEmpty(username)) { + // buf.append(username); + // if (StringUtils.isNotEmpty(password)) { + // buf.append(":"); + // buf.append(password); + // } + // buf.append("@"); + // } if (StringUtils.isNotEmpty(host)) { buf.append(host); @@ -174,5 +175,4 @@ public class PathURLAddress extends URLAddress { return buf.toString(); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/ServiceAddressURL.java b/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/ServiceAddressURL.java index cfef522832..811fd4b4ea 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/ServiceAddressURL.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/ServiceAddressURL.java @@ -35,9 +35,9 @@ import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATE public abstract class ServiceAddressURL extends URL { protected final transient URL consumerURL; - //cache + // cache private transient Map concatenatedPrams; -// private transient Map allParameters; + // private transient Map allParameters; public ServiceAddressURL( String protocol, @@ -47,8 +47,7 @@ public abstract class ServiceAddressURL extends URL { int port, String path, Map parameters, - URL consumerURL - ) { + URL consumerURL) { super(protocol, username, password, host, port, path, parameters); this.consumerURL = consumerURL; } @@ -173,8 +172,7 @@ public abstract class ServiceAddressURL extends URL { // Combine filters and listeners on Provider and Consumer String remoteValue = super.getParameter(key); String localValue = consumerURL.getParameter(key); - if (remoteValue != null && remoteValue.length() > 0 - && localValue != null && localValue.length() > 0) { + if (remoteValue != null && remoteValue.length() > 0 && localValue != null && localValue.length() > 0) { value = remoteValue + "," + localValue; concatenatedPrams.put(key, value); return value; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/ServiceConfigURL.java b/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/ServiceConfigURL.java index 9b73daf1c6..b16b5d0325 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/ServiceConfigURL.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/ServiceConfigURL.java @@ -28,14 +28,13 @@ import java.util.concurrent.ConcurrentMap; public class ServiceConfigURL extends URL { - - private volatile transient ConcurrentMap urls; - private volatile transient ConcurrentMap numbers; - private volatile transient ConcurrentMap> methodNumbers; - private volatile transient String full; - private volatile transient String string; - private volatile transient String identity; - private volatile transient String parameter; + private transient volatile ConcurrentMap urls; + private transient volatile ConcurrentMap numbers; + private transient volatile ConcurrentMap> methodNumbers; + private transient volatile String full; + private transient volatile String string; + private transient volatile String identity; + private transient volatile String parameter; public ServiceConfigURL() { super(); @@ -45,12 +44,15 @@ public class ServiceConfigURL extends URL { super(urlAddress, urlParam, attributes); } - public ServiceConfigURL(String protocol, String host, int port) { this(protocol, null, null, host, port, null, (Map) null); } - public ServiceConfigURL(String protocol, String host, int port, String[] pairs) { // varargs ... conflict with the following path argument, use array instead. + public ServiceConfigURL( + String protocol, + String host, + int port, + String[] pairs) { // varargs ... conflict with the following path argument, use array instead. this(protocol, null, null, host, port, null, CollectionUtils.toStringMap(pairs)); } @@ -74,29 +76,35 @@ public class ServiceConfigURL extends URL { this(protocol, username, password, host, port, path, (Map) null); } - public ServiceConfigURL(String protocol, String username, String password, String host, int port, String path, String... pairs) { + public ServiceConfigURL( + String protocol, String username, String password, String host, int port, String path, String... pairs) { this(protocol, username, password, host, port, path, CollectionUtils.toStringMap(pairs)); } - public ServiceConfigURL(String protocol, - String username, - String password, - String host, - int port, - String path, - Map parameters) { + public ServiceConfigURL( + String protocol, + String username, + String password, + String host, + int port, + String path, + Map parameters) { this(new PathURLAddress(protocol, username, password, path, host, port), URLParam.parse(parameters), null); } - public ServiceConfigURL(String protocol, - String username, - String password, - String host, - int port, - String path, - Map parameters, - Map attributes) { - this(new PathURLAddress(protocol, username, password, path, host, port), URLParam.parse(parameters), attributes); + public ServiceConfigURL( + String protocol, + String username, + String password, + String host, + int port, + String path, + Map parameters, + Map attributes) { + this( + new PathURLAddress(protocol, username, password, path, host, port), + URLParam.parse(parameters), + attributes); } @Override @@ -166,7 +174,6 @@ public class ServiceConfigURL extends URL { return parameter = super.toParameterString(); } - @Override public URL getUrlParameter(String key) { URL u = getUrls().get(key); @@ -527,7 +534,6 @@ public class ServiceConfigURL extends URL { return b; } - private Map getUrls() { // concurrent initialization is tolerant if (urls == null) { @@ -553,7 +559,8 @@ public class ServiceConfigURL extends URL { } private void updateCachedNumber(String method, String key, Number n) { - Map keyNumber = ConcurrentHashMapUtils.computeIfAbsent(getMethodNumbers(), method, m -> new HashMap<>()); + Map keyNumber = + ConcurrentHashMapUtils.computeIfAbsent(getMethodNumbers(), method, m -> new HashMap<>()); keyNumber.put(key, n); } @@ -571,5 +578,4 @@ public class ServiceConfigURL extends URL { protected Map> getServiceMethodNumbers(String service) { return getMethodNumbers(); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLAddress.java b/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLAddress.java index 0362af72de..bf6417e6b3 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLAddress.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLAddress.java @@ -138,12 +138,12 @@ public class URLAddress implements Serializable { if (this == obj) return true; if (!(obj instanceof URLAddress)) return false; URLAddress that = (URLAddress) obj; - return Objects.equals(this.getProtocol(), that.getProtocol()) && - Objects.equals(this.getUsername(), that.getUsername()) && - Objects.equals(this.getPassword(), that.getPassword()) && - Objects.equals(this.getPath(), that.getPath()) && - Objects.equals(this.getHost(), that.getHost()) && - Objects.equals(this.getPort(), that.getPort()); + return Objects.equals(this.getProtocol(), that.getProtocol()) + && Objects.equals(this.getUsername(), that.getUsername()) + && Objects.equals(this.getPassword(), that.getPassword()) + && Objects.equals(this.getPath(), that.getPath()) + && Objects.equals(this.getHost(), that.getHost()) + && Objects.equals(this.getPort(), that.getPort()); } @Override diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLParam.java b/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLParam.java index 1500787fda..e097ef4e40 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLParam.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLParam.java @@ -107,7 +107,8 @@ public class URLParam { */ protected boolean enableCompressed; - private final static URLParam EMPTY_PARAM = new URLParam(new BitSet(0), Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap(), ""); + private static final URLParam EMPTY_PARAM = + new URLParam(new BitSet(0), Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap(), ""); protected URLParam() { this.rawParam = null; @@ -118,7 +119,12 @@ public class URLParam { this.enableCompressed = true; } - protected URLParam(BitSet key, Map value, Map extraParams, Map> methodParameters, String rawParam) { + protected URLParam( + BitSet key, + Map value, + Map extraParams, + Map> methodParameters, + String rawParam) { this.KEY = key; this.VALUE = new int[value.size()]; for (int i = key.nextSetBit(0), offset = 0; i >= 0; i = key.nextSetBit(i + 1)) { @@ -128,19 +134,28 @@ public class URLParam { throw new IllegalArgumentException(); } } - this.EXTRA_PARAMS = Collections.unmodifiableMap((extraParams == null ? new HashMap<>() : new HashMap<>(extraParams))); - this.METHOD_PARAMETERS = Collections.unmodifiableMap((methodParameters == null) ? Collections.emptyMap() : new LinkedHashMap<>(methodParameters)); + this.EXTRA_PARAMS = + Collections.unmodifiableMap((extraParams == null ? new HashMap<>() : new HashMap<>(extraParams))); + this.METHOD_PARAMETERS = Collections.unmodifiableMap( + (methodParameters == null) ? Collections.emptyMap() : new LinkedHashMap<>(methodParameters)); this.rawParam = rawParam; this.timestamp = System.currentTimeMillis(); this.enableCompressed = true; } - protected URLParam(BitSet key, int[] value, Map extraParams, Map> methodParameters, String rawParam) { + protected URLParam( + BitSet key, + int[] value, + Map extraParams, + Map> methodParameters, + String rawParam) { this.KEY = key; this.VALUE = value; - this.EXTRA_PARAMS = Collections.unmodifiableMap((extraParams == null ? new HashMap<>() : new HashMap<>(extraParams))); - this.METHOD_PARAMETERS = Collections.unmodifiableMap((methodParameters == null) ? Collections.emptyMap() : new LinkedHashMap<>(methodParameters)); + this.EXTRA_PARAMS = + Collections.unmodifiableMap((extraParams == null ? new HashMap<>() : new HashMap<>(extraParams))); + this.METHOD_PARAMETERS = Collections.unmodifiableMap( + (methodParameters == null) ? Collections.emptyMap() : new LinkedHashMap<>(methodParameters)); this.rawParam = rawParam; this.timestamp = System.currentTimeMillis(); this.enableCompressed = true; @@ -360,7 +375,8 @@ public class URLParam { @Override public Set keySet() { - Set set = new LinkedHashSet<>((int) ((urlParam.VALUE.length + urlParam.EXTRA_PARAMS.size()) / 0.75) + 1); + Set set = + new LinkedHashSet<>((int) ((urlParam.VALUE.length + urlParam.EXTRA_PARAMS.size()) / 0.75) + 1); for (int i = urlParam.KEY.nextSetBit(0); i >= 0; i = urlParam.KEY.nextSetBit(i + 1)) { set.add(DynamicParamTable.getKey(i)); } @@ -372,7 +388,8 @@ public class URLParam { @Override public Collection values() { - Set set = new LinkedHashSet<>((int) ((urlParam.VALUE.length + urlParam.EXTRA_PARAMS.size()) / 0.75) + 1); + Set set = + new LinkedHashSet<>((int) ((urlParam.VALUE.length + urlParam.EXTRA_PARAMS.size()) / 0.75) + 1); for (int i = urlParam.KEY.nextSetBit(0); i >= 0; i = urlParam.KEY.nextSetBit(i + 1)) { String value; int offset = urlParam.keyIndexToOffset(i); @@ -388,7 +405,8 @@ public class URLParam { @Override public Set> entrySet() { - Set> set = new LinkedHashSet<>((int) ((urlParam.KEY.cardinality() + urlParam.EXTRA_PARAMS.size()) / 0.75) + 1); + Set> set = + new LinkedHashSet<>((int) ((urlParam.KEY.cardinality() + urlParam.EXTRA_PARAMS.size()) / 0.75) + 1); for (int i = urlParam.KEY.nextSetBit(0); i >= 0; i = urlParam.KEY.nextSetBit(i + 1)) { String value; int offset = urlParam.keyIndexToOffset(i); @@ -564,7 +582,8 @@ public class URLParam { if (newMethodParams == null) { newMethodParams = new HashMap<>(METHOD_PARAMETERS); } - Map methodMap = newMethodParams.computeIfAbsent(methodSplit[1], (k) -> new HashMap<>()); + Map methodMap = + newMethodParams.computeIfAbsent(methodSplit[1], (k) -> new HashMap<>()); methodMap.put(methodSplit[0], entry.getValue()); } } else { @@ -577,7 +596,10 @@ public class URLParam { } newValueMap.put(keyIndex, DynamicParamTable.getValueIndex(entry.getKey(), entry.getValue())); } else { - newValueArray = replaceOffset(VALUE, keyIndexToIndex(KEY, keyIndex), DynamicParamTable.getValueIndex(entry.getKey(), entry.getValue())); + newValueArray = replaceOffset( + VALUE, + keyIndexToIndex(KEY, keyIndex), + DynamicParamTable.getValueIndex(entry.getKey(), entry.getValue())); } } else { // key is absent, add it @@ -594,7 +616,10 @@ public class URLParam { newValueMap.put(keyIndex, DynamicParamTable.getValueIndex(entry.getKey(), entry.getValue())); } else { // add parameter by moving array, only support for adding once - newValueArray = addByMove(VALUE, keyIndexToIndex(newKey, keyIndex), DynamicParamTable.getValueIndex(entry.getKey(), entry.getValue())); + newValueArray = addByMove( + VALUE, + keyIndexToIndex(newKey, keyIndex), + DynamicParamTable.getValueIndex(entry.getKey(), entry.getValue())); } } } @@ -786,18 +811,17 @@ public class URLParam { value = DynamicParamTable.getValue(keyIndex, offset); return value; -// if (StringUtils.isEmpty(value)) { -// // Forward compatible, make sure key dynamic increment can work. -// // In that case, some values which are proceed before increment will set in EXTRA_PARAMS. -// return EXTRA_PARAMS.get(key); -// } else { -// return value; -// } + // if (StringUtils.isEmpty(value)) { + // // Forward compatible, make sure key dynamic increment can work. + // // In that case, some values which are proceed before increment will set in EXTRA_PARAMS. + // return EXTRA_PARAMS.get(key); + // } else { + // return value; + // } } return null; } - private int keyIndexToIndex(BitSet key, int keyIndex) { return key.get(0, keyIndex).cardinality(); } @@ -843,10 +867,10 @@ public class URLParam { } URLParam urlParam = (URLParam) o; - if (Objects.equals(KEY, urlParam.KEY) - && Arrays.equals(VALUE, urlParam.VALUE)) { + if (Objects.equals(KEY, urlParam.KEY) && Arrays.equals(VALUE, urlParam.VALUE)) { if (CollectionUtils.isNotEmptyMap(EXTRA_PARAMS)) { - if (CollectionUtils.isEmptyMap(urlParam.EXTRA_PARAMS) || EXTRA_PARAMS.size() != urlParam.EXTRA_PARAMS.size()) { + if (CollectionUtils.isEmptyMap(urlParam.EXTRA_PARAMS) + || EXTRA_PARAMS.size() != urlParam.EXTRA_PARAMS.size()) { return false; } for (Map.Entry entry : EXTRA_PARAMS.entrySet()) { @@ -963,7 +987,14 @@ public class URLParam { addParameter(keyBit, valueMap, extraParam, methodParameters, key, value, false); // compatible with lower versions registering "default." keys if (key.startsWith(DEFAULT_KEY_PREFIX)) { - addParameter(keyBit, valueMap, extraParam, methodParameters, key.substring(DEFAULT_KEY_PREFIX.length()), value, true); + addParameter( + keyBit, + valueMap, + extraParam, + methodParameters, + key.substring(DEFAULT_KEY_PREFIX.length()), + value, + true); } } else { addParameter(keyBit, valueMap, extraParam, methodParameters, part, part, false); @@ -1000,7 +1031,14 @@ public class URLParam { addParameter(keyBit, valueMap, extraParam, methodParameters, key, value, false); // compatible with lower versions registering "default." keys if (key.startsWith(DEFAULT_KEY_PREFIX)) { - addParameter(keyBit, valueMap, extraParam, methodParameters, key.substring(DEFAULT_KEY_PREFIX.length()), value, true); + addParameter( + keyBit, + valueMap, + extraParam, + methodParameters, + key.substring(DEFAULT_KEY_PREFIX.length()), + value, + true); } } return new URLParam(keyBit, valueMap, extraParam, methodParameters, rawParam); @@ -1009,8 +1047,14 @@ public class URLParam { } } - private static void addParameter(BitSet keyBit, Map valueMap, Map extraParam, - Map> methodParameters, String key, String value, boolean skipIfPresent) { + private static void addParameter( + BitSet keyBit, + Map valueMap, + Map extraParam, + Map> methodParameters, + String key, + String value, + boolean skipIfPresent) { int keyIndex = DynamicParamTable.getKeyIndex(true, key); if (skipIfPresent) { if (keyIndex < 0) { @@ -1028,7 +1072,8 @@ public class URLParam { extraParam.put(key, value); String[] methodSplit = key.split("\\.", 2); if (methodSplit.length == 2) { - Map methodMap = methodParameters.computeIfAbsent(methodSplit[1], (k) -> new HashMap<>()); + Map methodMap = + methodParameters.computeIfAbsent(methodSplit[1], (k) -> new HashMap<>()); methodMap.put(methodSplit[0], value); } } else { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLPlainParam.java b/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLPlainParam.java index b4fc76e10c..4702976f4f 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLPlainParam.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/URLPlainParam.java @@ -31,14 +31,19 @@ public class URLPlainParam extends URLParam implements Serializable { private static final long serialVersionUID = 4722019979665434393L; - protected URLPlainParam(BitSet key, int[] value, Map extraParams, Map> methodParameters, String rawParam) { + protected URLPlainParam( + BitSet key, + int[] value, + Map extraParams, + Map> methodParameters, + String rawParam) { super(key, value, extraParams, methodParameters, rawParam); this.enableCompressed = false; } public static URLPlainParam toURLPlainParam(URLParam urlParam) { Map params = Collections.unmodifiableMap(new HashMap<>(urlParam.getParameters())); - return new URLPlainParam(new BitSet(), new int[0], params, urlParam.getMethodParameters(), urlParam.getRawParam()); + return new URLPlainParam( + new BitSet(), new int[0], params, urlParam.getMethodParameters(), urlParam.getRawParam()); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/DynamicParamTable.java b/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/DynamicParamTable.java index c023e9c76f..3b5012e8e3 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/DynamicParamTable.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/DynamicParamTable.java @@ -34,6 +34,7 @@ public final class DynamicParamTable { * Keys array, value is string */ private static String[] ORIGIN_KEYS; + private static ParamValue[] VALUES; private static final Map KEY2INDEX = new HashMap<>(64); @@ -77,8 +78,10 @@ public final class DynamicParamTable { keys.add(""); values.add(new DynamicValues(null)); - FrameworkModel.defaultModel().getExtensionLoader(DynamicParamSource.class) - .getSupportedExtensionInstances().forEach(source -> source.init(keys, values)); + FrameworkModel.defaultModel() + .getExtensionLoader(DynamicParamSource.class) + .getSupportedExtensionInstances() + .forEach(source -> source.init(keys, values)); TreeMap resultMap = new TreeMap<>(Comparator.comparingInt(System::identityHashCode)); for (int i = 0; i < keys.size(); i++) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/FixedParamValue.java b/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/FixedParamValue.java index 6d6de7f459..1907da9113 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/FixedParamValue.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/FixedParamValue.java @@ -57,8 +57,8 @@ public class FixedParamValue implements ParamValue { Integer offset = val2Index.get(value.toLowerCase(Locale.ROOT)); if (offset == null) { throw new IllegalArgumentException("unrecognized value " + value - + " , please check if value is illegal. " + - "Permitted values: " + Arrays.asList(values)); + + " , please check if value is illegal. " + "Permitted values: " + + Arrays.asList(values)); } return offset; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/IgnoredParam.java b/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/IgnoredParam.java index cfc768f3b3..e6580d4582 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/IgnoredParam.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/IgnoredParam.java @@ -28,5 +28,4 @@ public class IgnoredParam { static boolean ignore(String key) { return IGNORED.contains(key); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/ParamValue.java b/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/ParamValue.java index 60c41e5e4a..e4164175c6 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/ParamValue.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/url/component/param/ParamValue.java @@ -25,7 +25,6 @@ public interface ParamValue { */ String getN(int n); - /** * max index is 2^31 - 1 * diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AnnotationUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AnnotationUtils.java index 8d9e441ef7..e3e53216b9 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AnnotationUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AnnotationUtils.java @@ -62,8 +62,8 @@ public interface AnnotationUtils { * @return If resolved, return the type of annotation, or null */ @SuppressWarnings("unchecked") - static Class resolveAnnotationType(AnnotatedElement annotatedElement, - String annotationClassName) { + static Class resolveAnnotationType( + AnnotatedElement annotatedElement, String annotationClassName) { ClassLoader classLoader = annotatedElement.getClass().getClassLoader(); Class annotationType = resolveClass(annotationClassName, classLoader); if (annotationType == null || !Annotation.class.isAssignableFrom(annotationType)) { @@ -162,7 +162,6 @@ public interface AnnotationUtils { } return null; - } /** @@ -192,8 +191,8 @@ public interface AnnotationUtils { * @param annotationsToFilter the annotations to filter * @return non-null read-only {@link List} */ - static List getDeclaredAnnotations(AnnotatedElement annotatedElement, - Predicate... annotationsToFilter) { + static List getDeclaredAnnotations( + AnnotatedElement annotatedElement, Predicate... annotationsToFilter) { if (annotatedElement == null) { return emptyList(); } @@ -209,8 +208,8 @@ public interface AnnotationUtils { * @param annotationsToFilter the annotations to filter * @return non-null read-only {@link List} */ - static List getAllDeclaredAnnotations(AnnotatedElement annotatedElement, - Predicate... annotationsToFilter) { + static List getAllDeclaredAnnotations( + AnnotatedElement annotatedElement, Predicate... annotationsToFilter) { if (isType(annotatedElement)) { return getAllDeclaredAnnotations((Class) annotatedElement, annotationsToFilter); } else { @@ -249,7 +248,6 @@ public interface AnnotationUtils { return unmodifiableList(allAnnotations); } - /** * Get the meta-annotated {@link Annotation annotations} directly, excluding {@link Target}, {@link Retention} * and {@link Documented} @@ -259,17 +257,17 @@ public interface AnnotationUtils { * @return non-null read-only {@link List} */ @SuppressWarnings("unchecked") - static List getMetaAnnotations(Class annotationType, - Predicate... metaAnnotationsToFilter) { - return getDeclaredAnnotations(annotationType, + static List getMetaAnnotations( + Class annotationType, Predicate... metaAnnotationsToFilter) { + return getDeclaredAnnotations( + annotationType, // Excludes the Java native annotation types or it causes the stack overflow, e.g, // @Target annotates itself excludedType(Target.class), excludedType(Retention.class), excludedType(Documented.class), // Add other predicates - and(metaAnnotationsToFilter) - ); + and(metaAnnotationsToFilter)); } /** @@ -280,8 +278,8 @@ public interface AnnotationUtils { * @return non-null read-only {@link List} */ @SuppressWarnings("unchecked") - static List getAllMetaAnnotations(Class annotationType, - Predicate... annotationsToFilter) { + static List getAllMetaAnnotations( + Class annotationType, Predicate... annotationsToFilter) { List allMetaAnnotations = new LinkedList<>(); @@ -331,8 +329,8 @@ public interface AnnotationUtils { * @return if found, return all matched results, or get an {@link Collections#emptyList() empty list} */ @SuppressWarnings("unchecked") - static List findMetaAnnotations(Class annotationType, - Class metaAnnotationType) { + static List findMetaAnnotations( + Class annotationType, Class metaAnnotationType) { return (List) getAllMetaAnnotations(annotationType, a -> isSameType(a, metaAnnotationType)); } @@ -345,8 +343,8 @@ public interface AnnotationUtils { * @return if found, return all matched results, or get an {@link Collections#emptyList() empty list} */ @SuppressWarnings("unchecked") - static List findMetaAnnotations(AnnotatedElement annotatedElement, - Class metaAnnotationType) { + static List findMetaAnnotations( + AnnotatedElement annotatedElement, Class metaAnnotationType) { List metaAnnotations = new LinkedList<>(); for (Annotation annotation : getAllDeclaredAnnotations(annotatedElement)) { @@ -364,8 +362,8 @@ public interface AnnotationUtils { * @param the type of required annotation * @return {@link #findMetaAnnotation(Class, Class)} */ - static A findMetaAnnotation(AnnotatedElement annotatedElement, - String metaAnnotationClassName) { + static A findMetaAnnotation( + AnnotatedElement annotatedElement, String metaAnnotationClassName) { return findMetaAnnotation(annotatedElement, resolveAnnotationType(annotatedElement, metaAnnotationClassName)); } @@ -379,8 +377,8 @@ public interface AnnotationUtils { * If it requires more result, please consider to use {@link #findMetaAnnotations(Class, Class)} * @see #findMetaAnnotations(Class, Class) */ - static A findMetaAnnotation(Class annotationType, - Class metaAnnotationType) { + static A findMetaAnnotation( + Class annotationType, Class metaAnnotationType) { return first(findMetaAnnotations(annotationType, metaAnnotationType)); } @@ -406,9 +404,8 @@ public interface AnnotationUtils { * @param annotationTypes the specified annotation types * @return If the specified annotation types are present, return true, or false */ - static boolean isAnnotationPresent(Class type, - boolean matchAll, - Class... annotationTypes) { + static boolean isAnnotationPresent( + Class type, boolean matchAll, Class... annotationTypes) { int size = annotationTypes == null ? 0 : annotationTypes.length; @@ -468,8 +465,8 @@ public interface AnnotationUtils { if (isType(annotatedElement)) { return isAnnotationPresent((Class) annotatedElement, annotationType); } else { - return annotatedElement.isAnnotationPresent(annotationType) || - findMetaAnnotation(annotatedElement, annotationType) != null; // to find meta-annotation + return annotatedElement.isAnnotationPresent(annotationType) + || findMetaAnnotation(annotatedElement, annotationType) != null; // to find meta-annotation } } @@ -491,12 +488,10 @@ public interface AnnotationUtils { * @param annotationTypes the specified annotation types * @return If any specified annotation types are present, return true */ - static boolean isAnyAnnotationPresent(Class type, - Class... annotationTypes) { + static boolean isAnyAnnotationPresent(Class type, Class... annotationTypes) { return isAnnotationPresent(type, false, annotationTypes); } - /** * Get the default value of attribute on the specified annotation * @@ -531,9 +526,10 @@ public interface AnnotationUtils { * @param attributes * @return */ - static Map filterDefaultValues(Class annotationType, Map attributes) { + static Map filterDefaultValues( + Class annotationType, Map attributes) { Map filteredAttributes = new LinkedHashMap<>(attributes.size()); - attributes.forEach((key,val) -> { + attributes.forEach((key, val) -> { if (!Objects.deepEquals(val, getDefaultValue(annotationType, key))) { filteredAttributes.put(key, val); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ArrayUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ArrayUtils.java index e648598867..92efcc2619 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ArrayUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ArrayUtils.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; /** @@ -22,8 +21,7 @@ package org.apache.dubbo.common.utils; */ public final class ArrayUtils { - private ArrayUtils() { - } + private ArrayUtils() {} /** *

Checks if the array is null or empty.

diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Assert.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Assert.java index 9c5ec040ac..f7a88f033b 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Assert.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Assert.java @@ -14,15 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; import java.util.function.Supplier; public abstract class Assert { - protected Assert() { - } + protected Assert() {} public static void notNull(Object obj, String message) { if (obj == null) { @@ -57,5 +55,4 @@ public abstract class Assert { private static String nullSafeGet(Supplier messageSupplier) { return (messageSupplier != null ? messageSupplier.get() : null); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AtomicPositiveInteger.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AtomicPositiveInteger.java index 7aff6303aa..da37834268 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AtomicPositiveInteger.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AtomicPositiveInteger.java @@ -28,8 +28,7 @@ public class AtomicPositiveInteger extends Number { @SuppressWarnings("unused") private volatile int index = 0; - public AtomicPositiveInteger() { - } + public AtomicPositiveInteger() {} public AtomicPositiveInteger(int initialValue) { INDEX_UPDATER.set(this, initialValue); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CacheableSupplier.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CacheableSupplier.java index cc81d34d05..b7443a896b 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CacheableSupplier.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CacheableSupplier.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; import java.util.function.Supplier; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CharSequenceComparator.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CharSequenceComparator.java index 055ba48e0a..e2bb2d484b 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CharSequenceComparator.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CharSequenceComparator.java @@ -25,10 +25,9 @@ import java.util.Comparator; */ public class CharSequenceComparator implements Comparator { - public final static CharSequenceComparator INSTANCE = new CharSequenceComparator(); + public static final CharSequenceComparator INSTANCE = new CharSequenceComparator(); - private CharSequenceComparator() { - } + private CharSequenceComparator() {} @Override public int compare(CharSequence c1, CharSequence c2) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassHelper.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassHelper.java index fe3a21586f..0fcb8ca71e 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassHelper.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassHelper.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.utils; - import java.lang.reflect.Method; /** @@ -85,8 +84,7 @@ public class ClassHelper { * @throws LinkageError if the class file could not be loaded * @see Class#forName(String, boolean, ClassLoader) */ - public static Class forName(String name, ClassLoader classLoader) - throws ClassNotFoundException, LinkageError { + public static Class forName(String name, ClassLoader classLoader) throws ClassNotFoundException, LinkageError { return ClassUtils.forName(name, classLoader); } @@ -108,7 +106,6 @@ public class ClassHelper { public static String toShortString(Object obj) { return ClassUtils.toShortString(obj); - } public static String simpleClassName(Class clazz) { @@ -136,10 +133,9 @@ public class ClassHelper { } public static Object convertPrimitive(Class type, String value) { - return ClassUtils.convertPrimitive(type,value); + return ClassUtils.convertPrimitive(type, value); } - /** * We only check boolean value at this moment. * @@ -148,6 +144,6 @@ public class ClassHelper { * @return */ public static boolean isTypeMatch(Class type, String value) { - return ClassUtils.isTypeMatch(type,value); + return ClassUtils.isTypeMatch(type, value); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassLoaderResourceLoader.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassLoaderResourceLoader.java index d8003d41c7..8c743c214f 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassLoaderResourceLoader.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassLoaderResourceLoader.java @@ -39,7 +39,8 @@ import java.util.concurrent.CountDownLatch; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_IO_EXCEPTION; public class ClassLoaderResourceLoader { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ClassLoaderResourceLoader.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ClassLoaderResourceLoader.class); private static SoftReference>>> classLoaderResourcesCache = null; static { @@ -47,7 +48,8 @@ public class ClassLoaderResourceLoader { GlobalResourcesRepository.registerGlobalDisposable(ClassLoaderResourceLoader::destroy); } - public static Map> loadResources(String fileName, Collection classLoaders) throws InterruptedException { + public static Map> loadResources(String fileName, Collection classLoaders) + throws InterruptedException { Map> resources = new ConcurrentHashMap<>(); CountDownLatch countDownLatch = new CountDownLatch(classLoaders.size()); for (ClassLoader classLoader : classLoaders) { @@ -84,14 +86,21 @@ public class ClassLoaderResourceLoader { while (urls.hasMoreElements()) { URL url = urls.nextElement(); if (isNative) { - //In native mode, the address of each URL is the same instead of different paths, so it is necessary to set the ref to make it different + // In native mode, the address of each URL is the same instead of different paths, so it is + // necessary to set the ref to make it different setRef(url); } set.add(url); } } } catch (IOException e) { - logger.error(COMMON_IO_EXCEPTION, "", "", "Exception occurred when reading SPI definitions. SPI path: " + fileName + " ClassLoader name: " + currentClassLoader, e); + logger.error( + COMMON_IO_EXCEPTION, + "", + "", + "Exception occurred when reading SPI definitions. SPI path: " + fileName + " ClassLoader name: " + + currentClassLoader, + e); } urlCache.put(fileName, set); } @@ -113,7 +122,6 @@ public class ClassLoaderResourceLoader { } } - // for test protected static SoftReference>>> getClassLoaderResourcesCache() { return classLoaderResourcesCache; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassUtils.java index 2ef19ba8fd..88eca7a2e4 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassUtils.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.utils; - import org.apache.dubbo.common.convert.ConverterUtil; import org.apache.dubbo.rpc.model.FrameworkModel; @@ -75,22 +74,21 @@ public class ClassUtils { * @since 2.7.6 */ public static final Set> SIMPLE_TYPES = ofSet( - Void.class, - Boolean.class, - Character.class, - Byte.class, - Short.class, - Integer.class, - Long.class, - Float.class, - Double.class, - String.class, - BigDecimal.class, - BigInteger.class, - Date.class, - Object.class, - Duration.class - ); + Void.class, + Boolean.class, + Character.class, + Byte.class, + Short.class, + Integer.class, + Long.class, + Float.class, + Double.class, + String.class, + BigDecimal.class, + BigInteger.class, + Date.class, + Object.class, + Duration.class); /** * Prefix for internal array class names: "[L" */ @@ -119,9 +117,15 @@ public class ClassUtils { Set> primitiveTypeNames = new HashSet<>(32); primitiveTypeNames.addAll(PRIMITIVE_WRAPPER_TYPE_MAP.values()); - primitiveTypeNames.addAll(Arrays - .asList(boolean[].class, byte[].class, char[].class, double[].class, - float[].class, int[].class, long[].class, short[].class)); + primitiveTypeNames.addAll(Arrays.asList( + boolean[].class, + byte[].class, + char[].class, + double[].class, + float[].class, + int[].class, + long[].class, + short[].class)); for (Class primitiveTypeName : primitiveTypeNames) { PRIMITIVE_TYPE_NAME_MAP.put(primitiveTypeName.getName(), primitiveTypeName); } @@ -138,13 +142,11 @@ public class ClassUtils { */ private static final char PACKAGE_SEPARATOR_CHAR = '.'; - public static Class forNameWithThreadContextClassLoader(String name) - throws ClassNotFoundException { + public static Class forNameWithThreadContextClassLoader(String name) throws ClassNotFoundException { return forName(name, Thread.currentThread().getContextClassLoader()); } - public static Class forNameWithCallerClassLoader(String name, Class caller) - throws ClassNotFoundException { + public static Class forNameWithCallerClassLoader(String name, Class caller) throws ClassNotFoundException { return forName(name, caller.getClassLoader()); } @@ -225,7 +227,6 @@ public class ClassUtils { } } - /** * Replacement for Class.forName() that also returns Class * instances for primitives (like "int") and array class names (like @@ -239,8 +240,7 @@ public class ClassUtils { * @throws LinkageError if the class file could not be loaded * @see Class#forName(String, boolean, ClassLoader) */ - public static Class forName(String name, ClassLoader classLoader) - throws ClassNotFoundException, LinkageError { + public static Class forName(String name, ClassLoader classLoader) throws ClassNotFoundException, LinkageError { Class clazz = resolvePrimitiveClassName(name); if (clazz != null) { @@ -259,8 +259,7 @@ public class ClassUtils { if (internalArrayMarker != -1 && name.endsWith(";")) { String elementClassName = null; if (internalArrayMarker == 0) { - elementClassName = name - .substring(INTERNAL_ARRAY_PREFIX.length(), name.length() - 1); + elementClassName = name.substring(INTERNAL_ARRAY_PREFIX.length(), name.length() - 1); } else if (name.startsWith("[")) { elementClassName = name.substring(1); } @@ -303,7 +302,6 @@ public class ClassUtils { return "null"; } return obj.getClass().getSimpleName() + "@" + System.identityHashCode(obj); - } public static String simpleClassName(Class clazz) { @@ -318,7 +316,6 @@ public class ClassUtils { return className; } - /** * The specified type is primitive type or simple type * @@ -353,14 +350,14 @@ public class ClassUtils { Class wrapperType = WRAPPER_PRIMITIVE_TYPE_MAP.getOrDefault(type, type); Object result = null; try { - result = frameworkModel.getBeanFactory().getBean(ConverterUtil.class).convertIfPossible(value, wrapperType); + result = + frameworkModel.getBeanFactory().getBean(ConverterUtil.class).convertIfPossible(value, wrapperType); } catch (Exception e) { // ignore exception } return result; } - /** * We only check boolean value at this moment. * @@ -369,8 +366,7 @@ public class ClassUtils { * @return */ public static boolean isTypeMatch(Class type, String value) { - if ((type == boolean.class || type == Boolean.class) - && !("true".equals(value) || "false".equals(value))) { + if ((type == boolean.class || type == Boolean.class) && !("true".equals(value) || "false".equals(value))) { return false; } return true; @@ -423,19 +419,14 @@ public class ClassUtils { if (isNotEmpty(interfaces)) { // add current interfaces - Arrays.stream(interfaces) - .filter(resolved::add) - .forEach(cls -> { - allInterfaces.add(cls); - waitResolve.add(cls); - }); + Arrays.stream(interfaces).filter(resolved::add).forEach(cls -> { + allInterfaces.add(cls); + waitResolve.add(cls); + }); } // add all super classes to waitResolve - getAllSuperClasses(clazz) - .stream() - .filter(resolved::add) - .forEach(waitResolve::add); + getAllSuperClasses(clazz).stream().filter(resolved::add).forEach(waitResolve::add); clazz = waitResolve.poll(); } @@ -459,7 +450,6 @@ public class ClassUtils { return unmodifiableSet(types); } - /** * the semantics is same as {@link Class#isAssignableFrom(Class)} * @@ -538,7 +528,7 @@ public class ClassUtils { return false; } - private static final String[] OBJECT_METHODS = new String[]{"getClass", "hashCode", "toString", "equals"}; + private static final String[] OBJECT_METHODS = new String[] {"getClass", "hashCode", "toString", "equals"}; /** * get method name array. @@ -549,14 +539,13 @@ public class ClassUtils { if (tClass == Object.class) { return OBJECT_METHODS; } - Method[] methods = Arrays.stream(tClass.getMethods()) - .collect(Collectors.toList()) - .toArray(new Method[]{}); + Method[] methods = + Arrays.stream(tClass.getMethods()).collect(Collectors.toList()).toArray(new Method[] {}); List mns = new ArrayList<>(); // method names. boolean hasMethod = hasMethods(methods); if (hasMethod) { for (Method m : methods) { - //ignore Object's method. + // ignore Object's method. if (m.getDeclaringClass() == Object.class) { continue; } @@ -586,21 +575,21 @@ public class ClassUtils { if (from == boolean.class) { return to == Boolean.class; } else if (from == byte.class) { - return to == Byte.class; + return to == Byte.class; } else if (from == char.class) { - return to == Character.class; + return to == Character.class; } else if (from == short.class) { - return to == Short.class; + return to == Short.class; } else if (from == int.class) { - return to == Integer.class; + return to == Integer.class; } else if (from == long.class) { - return to == Long.class; + return to == Long.class; } else if (from == float.class) { - return to == Float.class; + return to == Float.class; } else if (from == double.class) { - return to == Double.class; + return to == Double.class; } else if (from == void.class) { - return to == Void.class; + return to == Void.class; } return false; } @@ -614,14 +603,13 @@ public class ClassUtils { if (tClass == Object.class) { return OBJECT_METHODS; } - Method[] methods = Arrays.stream(tClass.getMethods()) - .collect(Collectors.toList()) - .toArray(new Method[]{}); + Method[] methods = + Arrays.stream(tClass.getMethods()).collect(Collectors.toList()).toArray(new Method[] {}); List dmns = new ArrayList<>(); // method names. boolean hasMethod = hasMethods(methods); if (hasMethod) { for (Method m : methods) { - //ignore Object's method. + // ignore Object's method. if (m.getDeclaringClass() == Object.class) { continue; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CollectionUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CollectionUtils.java index 52c6f07188..df6388c936 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CollectionUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CollectionUtils.java @@ -63,8 +63,7 @@ public class CollectionUtils { return s1.compareToIgnoreCase(s2); }; - private CollectionUtils() { - } + private CollectionUtils() {} @SuppressWarnings({"unchecked", "rawtypes"}) public static List sort(List list) { @@ -98,9 +97,7 @@ public class CollectionUtils { if (set.size() != map.size()) { throw new IllegalArgumentException("The map value must be unique."); } - return map.entrySet() - .stream() - .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey)); + return map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey)); } public static Map> splitAll(Map> list, String separator) { @@ -249,7 +246,7 @@ public class CollectionUtils { field.setAccessible(true); Object value = field.get(object); if (value != null) { - ret.put((K)field.getName(), (V)value); + ret.put((K) field.getName(), (V) value); } } } @@ -423,5 +420,4 @@ public class CollectionUtils { } return set; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CompatibleTypeUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CompatibleTypeUtils.java index fb4d53ccbd..3eb4e1860a 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CompatibleTypeUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CompatibleTypeUtils.java @@ -40,8 +40,7 @@ public class CompatibleTypeUtils { */ private static final int ISO_LOCAL_DATE_TIME_MIN_LEN = 19; - private CompatibleTypeUtils() { - } + private CompatibleTypeUtils() {} /** * Compatible type convert. Null value is allowed to pass in. If no conversion is needed, then the original value @@ -64,8 +63,10 @@ public class CompatibleTypeUtils { String string = (String) value; if (char.class.equals(type) || Character.class.equals(type)) { if (string.length() != 1) { - throw new IllegalArgumentException(String.format("CAN NOT convert String(%s) to char!" + - " when convert String to char, the String MUST only 1 char.", string)); + throw new IllegalArgumentException(String.format( + "CAN NOT convert String(%s) to char!" + + " when convert String to char, the String MUST only 1 char.", + string)); } return string.charAt(0); } @@ -99,7 +100,9 @@ public class CompatibleTypeUtils { if (type == Boolean.class || type == boolean.class) { return Boolean.valueOf(string); } - if (type == Date.class || type == java.sql.Date.class || type == java.sql.Timestamp.class + if (type == Date.class + || type == java.sql.Date.class + || type == java.sql.Timestamp.class || type == java.sql.Time.class) { try { Date date = new SimpleDateFormat(DATE_FORMAT).parse(string); @@ -114,8 +117,10 @@ public class CompatibleTypeUtils { } return date; } catch (ParseException e) { - throw new IllegalStateException("Failed to parse date " + value + " by format " - + DATE_FORMAT + ", cause: " + e.getMessage(), e); + throw new IllegalStateException( + "Failed to parse date " + value + " by format " + DATE_FORMAT + ", cause: " + + e.getMessage(), + e); } } if (type == java.time.LocalDateTime.class) { @@ -134,7 +139,7 @@ public class CompatibleTypeUtils { if (StringUtils.isEmpty(string)) { return null; } - + if (string.length() >= ISO_LOCAL_DATE_TIME_MIN_LEN) { return LocalDateTime.parse(string).toLocalTime(); } else { @@ -204,7 +209,8 @@ public class CompatibleTypeUtils { } if (!type.isInterface()) { try { - Collection result = (Collection) type.getDeclaredConstructor().newInstance(); + Collection result = + (Collection) type.getDeclaredConstructor().newInstance(); result.addAll(collection); return result; } catch (Throwable ignored) { @@ -227,7 +233,7 @@ public class CompatibleTypeUtils { collection = new ArrayList(length); } } else if (type == Set.class) { - collection = new HashSet(Math.max((int) (length/.75f) + 1, 16)); + collection = new HashSet(Math.max((int) (length / .75f) + 1, 16)); } else { collection = new ArrayList(length); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConcurrentHashMapUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConcurrentHashMapUtils.java index 7e71a1bab0..0800fb9ed3 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConcurrentHashMapUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConcurrentHashMapUtils.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; import java.util.Objects; @@ -24,7 +23,6 @@ import java.util.function.Function; /** * ConcurrentHashMap util */ - public class ConcurrentHashMapUtils { /** @@ -42,11 +40,11 @@ public class ConcurrentHashMapUtils { // this bug fix methods maybe cause `func.apply` multiple calls. v = func.apply(key); - if(null == v){ + if (null == v) { return null; } final V res = map.putIfAbsent(key, v); - if(null != res){ + if (null != res) { // if pre value present, means other thread put value already, and putIfAbsent not effect // return exist value return res; @@ -58,5 +56,4 @@ public class ConcurrentHashMapUtils { return map.computeIfAbsent(key, func); } } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConcurrentHashSet.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConcurrentHashSet.java index 1e8ea4cb53..e527d028de 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConcurrentHashSet.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConcurrentHashSet.java @@ -126,5 +126,4 @@ public class ConcurrentHashSet extends AbstractSet implements Set, java public void clear() { map.clear(); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.java index b45a57a2f7..74ad48add5 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ConfigUtils.java @@ -51,12 +51,10 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_IO_EX public class ConfigUtils { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ConfigUtils.class); - private static final Pattern VARIABLE_PATTERN = Pattern.compile( - "\\$\\s*\\{?\\s*([\\._0-9a-zA-Z]+)\\s*\\}?"); + private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\$\\s*\\{?\\s*([\\._0-9a-zA-Z]+)\\s*\\}?"); private static int PID = -1; - private ConfigUtils() { - } + private ConfigUtils() {} public static boolean isNotEmpty(String value) { return !isEmpty(value); @@ -64,15 +62,14 @@ public class ConfigUtils { public static boolean isEmpty(String value) { return StringUtils.isEmpty(value) - || "false".equalsIgnoreCase(value) - || "0".equalsIgnoreCase(value) - || "null".equalsIgnoreCase(value) - || "N/A".equalsIgnoreCase(value); + || "false".equalsIgnoreCase(value) + || "0".equalsIgnoreCase(value) + || "null".equalsIgnoreCase(value) + || "N/A".equalsIgnoreCase(value); } public static boolean isDefault(String value) { - return "true".equalsIgnoreCase(value) - || "default".equalsIgnoreCase(value); + return "true".equalsIgnoreCase(value) || "default".equalsIgnoreCase(value); } /** @@ -88,7 +85,8 @@ public class ConfigUtils { * @param def Default extension list * @return result extension list */ - public static List mergeValues(ExtensionDirector extensionDirector, Class type, String cfg, List def) { + public static List mergeValues( + ExtensionDirector extensionDirector, Class type, String cfg, List def) { List defaults = new ArrayList(); if (def != null) { for (String name : def) { @@ -210,7 +208,8 @@ public class ConfigUtils { * * @throws IllegalStateException not allow multi-file, but multi-file exist on class path. */ - public static Properties loadProperties(Set classLoaders, String fileName, boolean allowMultiFile, boolean optional) { + public static Properties loadProperties( + Set classLoaders, String fileName, boolean allowMultiFile, boolean optional) { Properties properties = new Properties(); // add scene judgement in windows environment Fix 2557 if (checkFileNameExist(fileName)) { @@ -222,7 +221,13 @@ public class ConfigUtils { input.close(); } } catch (Throwable e) { - logger.warn(COMMON_IO_EXCEPTION, "", "", "Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + e.getMessage(), e); + logger.warn( + COMMON_IO_EXCEPTION, + "", + "", + "Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + + e.getMessage(), + e); } return properties; } @@ -232,10 +237,11 @@ public class ConfigUtils { List classLoadersToLoad = new LinkedList<>(); classLoadersToLoad.add(ClassUtils.getClassLoader()); classLoadersToLoad.addAll(classLoaders); - set = ClassLoaderResourceLoader.loadResources(fileName, classLoadersToLoad).values().stream().reduce(new LinkedHashSet<>(), (a, i) -> { - a.addAll(i); - return a; - }); + set = ClassLoaderResourceLoader.loadResources(fileName, classLoadersToLoad).values().stream() + .reduce(new LinkedHashSet<>(), (a, i) -> { + a.addAll(i); + return a; + }); } catch (Throwable t) { logger.warn(COMMON_IO_EXCEPTION, "", "", "Fail to load " + fileName + " file: " + t.getMessage(), t); } @@ -249,8 +255,9 @@ public class ConfigUtils { if (!allowMultiFile) { if (set.size() > 1) { - String errMsg = String.format("only 1 %s file is expected, but %d dubbo.properties files found on class path: %s", - fileName, set.size(), set); + String errMsg = String.format( + "only 1 %s file is expected, but %d dubbo.properties files found on class path: %s", + fileName, set.size(), set); logger.warn(COMMON_IO_EXCEPTION, "", "", errMsg); } @@ -258,7 +265,13 @@ public class ConfigUtils { try { properties.load(ClassUtils.getClassLoader().getResourceAsStream(fileName)); } catch (Throwable e) { - logger.warn(COMMON_IO_EXCEPTION, "", "", "Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + e.getMessage(), e); + logger.warn( + COMMON_IO_EXCEPTION, + "", + "", + "Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + + e.getMessage(), + e); } return properties; } @@ -281,7 +294,12 @@ public class ConfigUtils { } } } catch (Throwable e) { - logger.warn(COMMON_IO_EXCEPTION, "", "", "Fail to load " + fileName + " file from " + url + "(ignore this file): " + e.getMessage(), e); + logger.warn( + COMMON_IO_EXCEPTION, + "", + "", + "Fail to load " + fileName + " file from " + url + "(ignore this file): " + e.getMessage(), + e); } } @@ -296,7 +314,13 @@ public class ConfigUtils { return readString(input); } } catch (Throwable e) { - logger.warn(COMMON_IO_EXCEPTION, "", "", "Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + e.getMessage(), e); + logger.warn( + COMMON_IO_EXCEPTION, + "", + "", + "Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + + e.getMessage(), + e); } } @@ -304,7 +328,8 @@ public class ConfigUtils { List classLoadersToLoad = new LinkedList<>(); classLoadersToLoad.add(ClassUtils.getClassLoader()); classLoadersToLoad.addAll(classLoaders); - for (Set urls : ClassLoaderResourceLoader.loadResources(fileName, classLoadersToLoad).values()) { + for (Set urls : ClassLoaderResourceLoader.loadResources(fileName, classLoadersToLoad) + .values()) { for (URL url : urls) { InputStream is = url.openStream(); if (is != null) { @@ -313,7 +338,12 @@ public class ConfigUtils { } } } catch (Throwable e) { - logger.warn(COMMON_IO_EXCEPTION, "", "", "Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + e.getMessage(), e); + logger.warn( + COMMON_IO_EXCEPTION, + "", + "", + "Failed to load " + fileName + " file from " + fileName + "(ignore this file): " + e.getMessage(), + e); } return rawRule; } @@ -348,7 +378,6 @@ public class ConfigUtils { return file.exists(); } - public static int getPid() { if (PID < 0) { try { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultSerializeClassChecker.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultSerializeClassChecker.java index 9c863d717e..798d3e4d23 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultSerializeClassChecker.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DefaultSerializeClassChecker.java @@ -16,14 +16,14 @@ */ package org.apache.dubbo.common.utils; -import java.io.Serializable; -import java.util.Arrays; -import java.util.Set; - import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.model.FrameworkModel; +import java.io.Serializable; +import java.util.Arrays; +import java.util.Set; + import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_UNTRUSTED_SERIALIZE_CLASS; /** @@ -34,7 +34,8 @@ public class DefaultSerializeClassChecker implements AllowClassNotifyListener { private static final long MAGIC_HASH_CODE = 0xcbf29ce484222325L; private static final long MAGIC_PRIME = 0x100000001b3L; - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DefaultSerializeClassChecker.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(DefaultSerializeClassChecker.class); private volatile SerializeCheckStatus checkStatus = AllowClassNotifyListener.DEFAULT_STATUS; private volatile boolean checkSerializable = true; @@ -93,7 +94,6 @@ public class DefaultSerializeClassChecker implements AllowClassNotifyListener { return array; } - /** * Try load class * @@ -103,8 +103,9 @@ public class DefaultSerializeClassChecker implements AllowClassNotifyListener { public Class loadClass(ClassLoader classLoader, String className) throws ClassNotFoundException { Class aClass = loadClass0(classLoader, className); if (checkSerializable && !aClass.isPrimitive() && !Serializable.class.isAssignableFrom(aClass)) { - String msg = "[Serialization Security] Serialized class " + className + " has not implement Serializable interface. " + - "Current mode is strict check, will disallow to deserialize it by default. "; + String msg = "[Serialization Security] Serialized class " + className + + " has not implement Serializable interface. " + + "Current mode is strict check, will disallow to deserialize it by default. "; if (serializeSecurityManager.getWarnedClasses().add(className)) { logger.error(PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, "", "", msg); } @@ -135,9 +136,9 @@ public class DefaultSerializeClassChecker implements AllowClassNotifyListener { } if (checkStatus == SerializeCheckStatus.STRICT) { - String msg = "[Serialization Security] Serialized class " + className + " is not in allow list. " + - "Current mode is `STRICT`, will disallow to deserialize it by default. " + - "Please add it into security/serialize.allowlist or follow FAQ to configure it."; + String msg = "[Serialization Security] Serialized class " + className + " is not in allow list. " + + "Current mode is `STRICT`, will disallow to deserialize it by default. " + + "Please add it into security/serialize.allowlist or follow FAQ to configure it."; if (serializeSecurityManager.getWarnedClasses().add(className)) { logger.error(PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, "", "", msg); } @@ -155,9 +156,9 @@ public class DefaultSerializeClassChecker implements AllowClassNotifyListener { hash *= MAGIC_PRIME; if (Arrays.binarySearch(disAllowPrefixes, hash) >= 0) { - String msg = "[Serialization Security] Serialized class " + className + " is in disallow list. " + - "Current mode is `WARN`, will disallow to deserialize it by default. " + - "Please add it into security/serialize.allowlist or follow FAQ to configure it."; + String msg = "[Serialization Security] Serialized class " + className + " is in disallow list. " + + "Current mode is `WARN`, will disallow to deserialize it by default. " + + "Please add it into security/serialize.allowlist or follow FAQ to configure it."; if (serializeSecurityManager.getWarnedClasses().add(className)) { logger.warn(PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, "", "", msg); } @@ -176,9 +177,9 @@ public class DefaultSerializeClassChecker implements AllowClassNotifyListener { hash *= MAGIC_PRIME; if (Arrays.binarySearch(disAllowPrefixes, hash) >= 0) { - String msg = "[Serialization Security] Serialized class " + className + " is in disallow list. " + - "Current mode is `WARN`, will disallow to deserialize it by default. " + - "Please add it into security/serialize.allowlist or follow FAQ to configure it."; + String msg = "[Serialization Security] Serialized class " + className + " is in disallow list. " + + "Current mode is `WARN`, will disallow to deserialize it by default. " + + "Please add it into security/serialize.allowlist or follow FAQ to configure it."; if (serializeSecurityManager.getWarnedClasses().add(className)) { logger.warn(PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, "", "", msg); } @@ -189,11 +190,14 @@ public class DefaultSerializeClassChecker implements AllowClassNotifyListener { Class clazz = ClassUtils.forName(className, classLoader); if (serializeSecurityManager.getWarnedClasses().add(className)) { - logger.warn(PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, "", "", - "[Serialization Security] Serialized class " + className + " is not in allow list. " + - "Current mode is `WARN`, will allow to deserialize it by default. " + - "Dubbo will set to `STRICT` mode by default in the future. " + - "Please add it into security/serialize.allowlist or follow FAQ to configure it."); + logger.warn( + PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, + "", + "", + "[Serialization Security] Serialized class " + className + " is not in allow list. " + + "Current mode is `WARN`, will allow to deserialize it by default. " + + "Dubbo will set to `STRICT` mode by default in the future. " + + "Please add it into security/serialize.allowlist or follow FAQ to configure it."); } return clazz; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DubboAppender.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DubboAppender.java index 4f9d72b4ed..f9ac324c67 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DubboAppender.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/DubboAppender.java @@ -16,12 +16,12 @@ */ package org.apache.dubbo.common.utils; -import org.apache.log4j.FileAppender; -import org.apache.log4j.spi.LoggingEvent; - import java.util.ArrayList; import java.util.List; +import org.apache.log4j.FileAppender; +import org.apache.log4j.spi.LoggingEvent; + public class DubboAppender extends FileAppender { private static final String DEFAULT_FILE_NAME = "dubbo.log"; @@ -64,5 +64,4 @@ public class DubboAppender extends FileAppender { log.setLogMessage(event.getMessage().toString()); return log; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ExecutorUtil.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ExecutorUtil.java index f6e1ce41ca..a5ca54ff13 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ExecutorUtil.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ExecutorUtil.java @@ -32,10 +32,13 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXP public class ExecutorUtil { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ExecutorUtil.class); - private static final ThreadPoolExecutor SHUTDOWN_EXECUTOR = new ThreadPoolExecutor(0, 1, - 0L, TimeUnit.MILLISECONDS, - new LinkedBlockingQueue(100), - new NamedThreadFactory("Close-ExecutorService-Timer", true)); + private static final ThreadPoolExecutor SHUTDOWN_EXECUTOR = new ThreadPoolExecutor( + 0, + 1, + 0L, + TimeUnit.MILLISECONDS, + new LinkedBlockingQueue(100), + new NamedThreadFactory("Close-ExecutorService-Timer", true)); public static boolean isTerminated(Executor executor) { if (!(executor instanceof ExecutorService)) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/FieldUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/FieldUtils.java index 99f47d7bd3..cc233eda25 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/FieldUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/FieldUtils.java @@ -153,5 +153,4 @@ public interface FieldUtils { } return (T) previousValue; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Holder.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Holder.java index 07c3e32ca4..e14f6e1da9 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Holder.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Holder.java @@ -30,5 +30,4 @@ public class Holder { public T get() { return value; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/IOUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/IOUtils.java index 2f79f6c1e0..0578feed90 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/IOUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/IOUtils.java @@ -49,8 +49,7 @@ public class IOUtils { private static final int BUFFER_SIZE = 1024 * 8; public static final int EOF = -1; - private IOUtils() { - } + private IOUtils() {} /** * write. @@ -87,7 +86,8 @@ public class IOUtils { * @return count. * @throws IOException If an I/O error occurs */ - public static long write(final InputStream input, final OutputStream output, final byte[] buffer) throws IOException { + public static long write(final InputStream input, final OutputStream output, final byte[] buffer) + throws IOException { long count = 0; int n; while (EOF != (n = input.read(buffer))) { @@ -245,7 +245,6 @@ public class IOUtils { writeLines(new FileOutputStream(file, true), lines); } - /** * use like spring code * @@ -260,8 +259,7 @@ public class IOUtils { URL url = (cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path)); if (url == null) { String description = "class path resource [" + path + "]"; - throw new FileNotFoundException(description + - " cannot be resolved to URL because it does not exist"); + throw new FileNotFoundException(description + " cannot be resolved to URL because it does not exist"); } return url; } @@ -273,8 +271,8 @@ public class IOUtils { try { return new File(resourceLocation).toURI().toURL(); } catch (MalformedURLException ex2) { - throw new FileNotFoundException("Resource location [" + resourceLocation + - "] is neither a URL not a well-formed file path"); + throw new FileNotFoundException( + "Resource location [" + resourceLocation + "] is neither a URL not a well-formed file path"); } } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JRE.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JRE.java index f656a6942c..6897bfae0a 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JRE.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JRE.java @@ -14,19 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; - import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; - /** * JRE version */ public enum JRE { - JAVA_8, JAVA_9, @@ -131,10 +127,11 @@ public enum JRE { return OTHER; } } catch (Exception e) { - logger.debug("Can't determine current JRE version (maybe java.version is null), assuming that JRE version is 8.", e); + logger.debug( + "Can't determine current JRE version (maybe java.version is null), assuming that JRE version is 8.", + e); } // default java 8 return JAVA_8; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JVMUtil.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JVMUtil.java index 2e8f912332..bbd6df09b7 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JVMUtil.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JVMUtil.java @@ -16,6 +16,8 @@ */ package org.apache.dubbo.common.utils; +import org.apache.dubbo.common.constants.CommonConstants; + import java.io.OutputStream; import java.lang.management.LockInfo; import java.lang.management.ManagementFactory; @@ -23,8 +25,6 @@ import java.lang.management.MonitorInfo; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; -import org.apache.dubbo.common.constants.CommonConstants; - import static java.lang.Thread.State.BLOCKED; import static java.lang.Thread.State.TIMED_WAITING; import static java.lang.Thread.State.WAITING; @@ -38,15 +38,13 @@ public class JVMUtil { } private static String getThreadDumpString(ThreadInfo threadInfo) { - StringBuilder sb = new StringBuilder("\"" + threadInfo.getThreadName() + "\"" + - " Id=" + threadInfo.getThreadId() + " " + - threadInfo.getThreadState()); + StringBuilder sb = new StringBuilder("\"" + threadInfo.getThreadName() + "\"" + " Id=" + + threadInfo.getThreadId() + " " + threadInfo.getThreadState()); if (threadInfo.getLockName() != null) { sb.append(" on " + threadInfo.getLockName()); } if (threadInfo.getLockOwnerName() != null) { - sb.append(" owned by \"" + threadInfo.getLockOwnerName() + - "\" Id=" + threadInfo.getLockOwnerId()); + sb.append(" owned by \"" + threadInfo.getLockOwnerName() + "\" Id=" + threadInfo.getLockOwnerId()); } if (threadInfo.isSuspended()) { sb.append(" (suspended)"); @@ -59,10 +57,11 @@ public class JVMUtil { // default is 32, means only print up to 32 lines int jstackMaxLine = 32; String jstackMaxLineStr = System.getProperty(CommonConstants.DUBBO_JSTACK_MAXLINE); - if(StringUtils.isNotEmpty(jstackMaxLineStr)) { + if (StringUtils.isNotEmpty(jstackMaxLineStr)) { try { jstackMaxLine = Integer.parseInt(jstackMaxLineStr); - }catch (Exception ignore) {} + } catch (Exception ignore) { + } } StackTraceElement[] stackTrace = threadInfo.getStackTrace(); MonitorInfo[] lockedMonitors = threadInfo.getLockedMonitors(); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JsonCompatibilityUtil.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JsonCompatibilityUtil.java index 61f4bd5ad3..f78eeafdee 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JsonCompatibilityUtil.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JsonCompatibilityUtil.java @@ -32,13 +32,16 @@ import java.util.HashSet; import java.util.List; import java.util.Set; - public class JsonCompatibilityUtil { private static final Logger logger = LoggerFactory.getLogger(JsonCompatibilityUtil.class); - private static final Set unsupportedClasses = new HashSet<>(Arrays.asList("java.util.Optional", "java.util.Calendar", "java.util.Iterator", "java.io.InputStream", "java.io.OutputStream")); - + private static final Set unsupportedClasses = new HashSet<>(Arrays.asList( + "java.util.Optional", + "java.util.Calendar", + "java.util.Iterator", + "java.io.InputStream", + "java.io.OutputStream")); /** * Determine whether a Class can be serialized by JSON. @@ -60,7 +63,6 @@ public class JsonCompatibilityUtil { return true; } - /** * Determine whether a Method can be serialized by JSON. * @param method Incoming Method. @@ -73,7 +75,7 @@ public class JsonCompatibilityUtil { Type[] types = method.getGenericParameterTypes(); List typeList = new ArrayList<>(Arrays.asList(types)); - Type returnType = method.getGenericReturnType(); + Type returnType = method.getGenericReturnType(); typeList.add(returnType); for (Type type : typeList) { result = checkType(type); @@ -85,7 +87,6 @@ public class JsonCompatibilityUtil { return true; } - /** * Get unsupported methods. * @param clazz @@ -106,7 +107,6 @@ public class JsonCompatibilityUtil { return unsupportedMethods.size() > 0 ? unsupportedMethods : null; } - /** * Determine whether a Type can be serialized by JSON. * @param classType Incoming Type. @@ -137,7 +137,7 @@ public class JsonCompatibilityUtil { Type componentType = ((GenericArrayType) classType).getGenericComponentType(); result = checkType(componentType); return result; - } else if (classType instanceof Class ) { + } else if (classType instanceof Class) { Class clazz = (Class) classType; String className = clazz.getName(); @@ -164,9 +164,9 @@ public class JsonCompatibilityUtil { return true; } // deal with case of record -// if (clazz.isRecord()) { -// return false; -// } + // if (clazz.isRecord()) { + // return false; + // } // deal with field one by one for (Field field : clazz.getDeclaredFields()) { Type type = field.getGenericType(); @@ -181,5 +181,4 @@ public class JsonCompatibilityUtil { return true; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JsonUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JsonUtils.java index 2513cb9cb3..05c3c40a8d 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JsonUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/JsonUtils.java @@ -62,10 +62,7 @@ public class JsonUtils { } if (jsonUtil == null) { List> jsonClasses = Arrays.asList( - FastJson2Impl.class, - FastJsonImpl.class, - GsonImpl.class, - JacksonImpl.class); + FastJson2Impl.class, FastJsonImpl.class, GsonImpl.class, JacksonImpl.class); for (Class jsonClass : jsonClasses) { try { JsonUtil instance = jsonClass.getConstructor().newInstance(); @@ -79,8 +76,9 @@ public class JsonUtils { } } if (jsonUtil == null) { - throw new IllegalStateException("Dubbo unable to find out any json framework (e.g. fastjson2, fastjson, gson, jackson) from jvm env. " + - "Please import at least one json framework."); + throw new IllegalStateException( + "Dubbo unable to find out any json framework (e.g. fastjson2, fastjson, gson, jackson) from jvm env. " + + "Please import at least one json framework."); } } } @@ -100,64 +98,51 @@ public class JsonUtils { return getJson().toJavaObject(json, type); } - public static List toJavaList(String json, Class clazz) { return getJson().toJavaList(json, clazz); } - public static String toJson(Object obj) { return getJson().toJson(obj); } - public static List getList(Map obj, String key) { return getJson().getList(obj, key); } - public static List> getListOfObjects(Map obj, String key) { return getJson().getListOfObjects(obj, key); } - public static List getListOfStrings(Map obj, String key) { return getJson().getListOfStrings(obj, key); } - public static Map getObject(Map obj, String key) { return getJson().getObject(obj, key); } - public static Double getNumberAsDouble(Map obj, String key) { return getJson().getNumberAsDouble(obj, key); } - public static Integer getNumberAsInteger(Map obj, String key) { return getJson().getNumberAsInteger(obj, key); } - public static Long getNumberAsLong(Map obj, String key) { return getJson().getNumberAsLong(obj, key); } - public static String getString(Map obj, String key) { return getJson().getString(obj, key); } - public static List> checkObjectList(List rawList) { return getJson().checkObjectList(rawList); } - public static List checkStringList(List rawList) { return getJson().checkStringList(rawList); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LFUCache.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LFUCache.java index dcc6a945b6..1e3965ec69 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LFUCache.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LFUCache.java @@ -49,13 +49,11 @@ public class LFUCache { @SuppressWarnings("unchecked") public LFUCache(final int maxCapacity, final float evictionFactor) { if (maxCapacity <= 0) { - throw new IllegalArgumentException("Illegal initial capacity: " + - maxCapacity); + throw new IllegalArgumentException("Illegal initial capacity: " + maxCapacity); } boolean factorInRange = evictionFactor <= 1 && evictionFactor > 0; if (!factorInRange || Float.isNaN(evictionFactor)) { - throw new IllegalArgumentException("Illegal eviction factor value:" - + evictionFactor); + throw new IllegalArgumentException("Illegal eviction factor value:" + evictionFactor); } this.capacity = maxCapacity; this.evictionCount = (int) (capacity * evictionFactor); @@ -172,8 +170,7 @@ public class LFUCache { V value; CacheDeque owner; - CacheNode() { - } + CacheNode() {} CacheNode(final K key, final V value) { this.key = key; @@ -190,8 +187,7 @@ public class LFUCache { * @param value * @return retrieved node */ - static CacheNode withdrawNode( - final CacheNode node) { + static CacheNode withdrawNode(final CacheNode node) { if (node != null && node.prev != null) { node.prev.next = node.next; if (node.next != null) { @@ -200,7 +196,6 @@ public class LFUCache { } return node; } - } /** @@ -280,7 +275,5 @@ public class LFUCache { boolean isEmpty() { return last.next == first; } - } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LRU2Cache.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LRU2Cache.java index 0602536402..2a725e9334 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LRU2Cache.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LRU2Cache.java @@ -157,5 +157,4 @@ public class LRU2Cache extends LinkedHashMap { this.maxCapacity = maxCapacity; } } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LRUCache.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LRUCache.java index 425e06491c..76d6c19cb7 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LRUCache.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LRUCache.java @@ -125,5 +125,4 @@ public class LRUCache extends LinkedHashMap { public void setMaxCapacity(int maxCapacity) { this.maxCapacity = maxCapacity; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Log.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Log.java index 7a3d028e7f..3943b67687 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Log.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Log.java @@ -16,10 +16,10 @@ */ package org.apache.dubbo.common.utils; -import org.apache.log4j.Level; - import java.io.Serializable; +import org.apache.log4j.Level; + public class Log implements Serializable { private static final long serialVersionUID = -534113138054377073L; private String logName; @@ -112,5 +112,4 @@ public class Log implements Serializable { } return true; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LogHelper.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LogHelper.java index 99ba5ab828..79855ab882 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LogHelper.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LogHelper.java @@ -20,8 +20,7 @@ import org.apache.dubbo.common.logger.Logger; public class LogHelper { - private LogHelper() { - } + private LogHelper() {} public static void trace(Logger logger, String msg) { if (logger == null) { @@ -172,5 +171,4 @@ public class LogHelper { logger.error(msg, e); } } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LogUtil.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LogUtil.java index 35c609bd11..5319206663 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LogUtil.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/LogUtil.java @@ -19,11 +19,11 @@ package org.apache.dubbo.common.utils; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.log4j.Level; - import java.util.Iterator; import java.util.List; +import org.apache.log4j.Level; + public class LogUtil { private static final Logger Log = LoggerFactory.getLogger(LogUtil.class); @@ -42,7 +42,6 @@ public class LogUtil { } else { return false; } - } public static int findName(String expectedLogName) { @@ -126,6 +125,5 @@ public class LogUtil { while (it.hasNext()) { Log.info(it.next().toString()); } - } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MD5Utils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MD5Utils.java index a79dffe811..288486da0b 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MD5Utils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MD5Utils.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -70,5 +69,4 @@ public class MD5Utils { } return new String(str); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MemberUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MemberUtils.java index daf9273020..a5a1655a61 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MemberUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MemberUtils.java @@ -58,5 +58,4 @@ public interface MemberUtils { static boolean isPublic(Member member) { return member != null && Modifier.isPublic(member.getModifiers()); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MethodComparator.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MethodComparator.java index 8270c1da67..715100c2ab 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MethodComparator.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MethodComparator.java @@ -32,10 +32,9 @@ import java.util.Comparator; */ public class MethodComparator implements Comparator { - public final static MethodComparator INSTANCE = new MethodComparator(); + public static final MethodComparator INSTANCE = new MethodComparator(); - private MethodComparator() { - } + private MethodComparator() {} @Override public int compare(Method m1, Method m2) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MethodUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MethodUtils.java index a5ea0d6bff..a4b829ce45 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MethodUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/MethodUtils.java @@ -19,6 +19,7 @@ package org.apache.dubbo.common.utils; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Elements; + import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; @@ -70,8 +71,10 @@ public interface MethodUtils { static boolean isGetter(Method method) { String name = method.getName(); return (name.startsWith("get") || name.startsWith("is")) - && !"get".equals(name) && !"is".equals(name) - && !"getClass".equals(name) && !"getObject".equals(name) + && !"get".equals(name) + && !"is".equals(name) + && !"getClass".equals(name) + && !"getObject".equals(name) && Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0 && ClassUtils.isPrimitive(method.getReturnType()); @@ -119,7 +122,6 @@ public interface MethodUtils { return method.getAnnotation(Deprecated.class) != null; } - /** * Create an instance of {@link Predicate} for {@link Method} to exclude the specified declared class * @@ -141,8 +143,11 @@ public interface MethodUtils { * @return non-null read-only {@link List} * @since 2.7.6 */ - static List getMethods(Class declaringClass, boolean includeInheritedTypes, boolean publicOnly, - Predicate... methodsToFilter) { + static List getMethods( + Class declaringClass, + boolean includeInheritedTypes, + boolean publicOnly, + Predicate... methodsToFilter) { if (declaringClass == null || declaringClass.isPrimitive()) { return emptyList(); @@ -223,11 +228,11 @@ public interface MethodUtils { return getMethods(declaringClass, true, true, methodsToFilter); } -// static List getOverriderMethods(Class implementationClass, Class... superTypes) { + // static List getOverriderMethods(Class implementationClass, Class... superTypes) { -// + // -// } + // } /** * Find the {@link Method} by the the specified type and method name without the parameter types @@ -278,7 +283,8 @@ public interface MethodUtils { T value = null; if (method == null) { - throw new IllegalStateException(String.format("cannot find method %s,class: %s", methodName, type.getName())); + throw new IllegalStateException( + String.format("cannot find method %s,class: %s", methodName, type.getName())); } try { @@ -296,7 +302,6 @@ public interface MethodUtils { return value; } - /** * Tests whether one method, as a member of a given type, * overrides another method. @@ -458,4 +463,3 @@ public interface MethodUtils { } } } - diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java index d33fcea5b0..6a04983b05 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/NetUtils.java @@ -23,6 +23,7 @@ import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.logger.support.FailsafeLogger; import org.apache.dubbo.rpc.model.ScopeModel; + import java.io.IOException; import java.net.Inet4Address; import java.net.Inet6Address; @@ -135,7 +136,6 @@ public final class NetUtils { return port; } - /** * Check the port whether is in use in os * @param port port to check @@ -173,9 +173,7 @@ public final class NetUtils { } public static boolean isLocalHost(String host) { - return host != null - && (LOCAL_IP_PATTERN.matcher(host).matches() - || host.equalsIgnoreCase(LOCALHOST_KEY)); + return host != null && (LOCAL_IP_PATTERN.matcher(host).matches() || host.equalsIgnoreCase(LOCALHOST_KEY)); } public static boolean isAnyHost(String host) { @@ -184,10 +182,10 @@ public final class NetUtils { public static boolean isInvalidLocalHost(String host) { return host == null - || host.length() == 0 - || host.equalsIgnoreCase(LOCALHOST_KEY) - || host.equals(ANYHOST_VALUE) - || host.startsWith("127."); + || host.length() == 0 + || host.equalsIgnoreCase(LOCALHOST_KEY) + || host.equals(ANYHOST_VALUE) + || host.startsWith("127."); } public static boolean isValidLocalHost(String host) { @@ -195,8 +193,7 @@ public final class NetUtils { } public static InetSocketAddress getLocalSocketAddress(String host, int port) { - return isInvalidLocalHost(host) ? - new InetSocketAddress(port) : new InetSocketAddress(host, port); + return isInvalidLocalHost(host) ? new InetSocketAddress(port) : new InetSocketAddress(host, port); } static boolean isValidV4Address(InetAddress address) { @@ -206,9 +203,9 @@ public final class NetUtils { String name = address.getHostAddress(); return (name != null - && IP_PATTERN.matcher(name).matches() - && !ANYHOST_VALUE.equals(name) - && !LOCALHOST_VALUE.equals(name)); + && IP_PATTERN.matcher(name).matches() + && !ANYHOST_VALUE.equals(name) + && !LOCALHOST_VALUE.equals(name)); } /** @@ -281,8 +278,8 @@ public final class NetUtils { if (StringUtils.isNotEmpty(HOST_ADDRESS_V6)) { return HOST_ADDRESS_V6; } - //avoid to search network interface card many times - if("".equals(HOST_ADDRESS_V6)){ + // avoid to search network interface card many times + if ("".equals(HOST_ADDRESS_V6)) { return null; } @@ -413,12 +410,12 @@ public final class NetUtils { while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); if (address instanceof Inet6Address) { - if (!address.isLoopbackAddress() //filter ::1 - && !address.isAnyLocalAddress() // filter ::/128 - && !address.isLinkLocalAddress() //filter fe80::/10 - && !address.isSiteLocalAddress()// filter fec0::/10 - && !isUniqueLocalAddress(address) //filter fd00::/8 - && address.getHostAddress().contains(":")) {//filter IPv6 + if (!address.isLoopbackAddress() // filter ::1 + && !address.isAnyLocalAddress() // filter ::/128 + && !address.isLinkLocalAddress() // filter fe80::/10 + && !address.isSiteLocalAddress() // filter fec0::/10 + && !isUniqueLocalAddress(address) // filter fd00::/8 + && address.getHostAddress().contains(":")) { // filter IPv6 return (Inet6Address) address; } } @@ -450,23 +447,26 @@ public final class NetUtils { */ private static boolean ignoreNetworkInterface(NetworkInterface networkInterface) throws SocketException { if (networkInterface == null - || networkInterface.isLoopback() - || networkInterface.isVirtual() - || !networkInterface.isUp()) { + || networkInterface.isLoopback() + || networkInterface.isVirtual() + || !networkInterface.isUp()) { return true; } String ignoredInterfaces = System.getProperty(DUBBO_NETWORK_IGNORED_INTERFACE); String networkInterfaceDisplayName; if (StringUtils.isNotEmpty(ignoredInterfaces) - && StringUtils.isNotEmpty(networkInterfaceDisplayName = networkInterface.getDisplayName())) { + && StringUtils.isNotEmpty(networkInterfaceDisplayName = networkInterface.getDisplayName())) { for (String ignoredInterface : ignoredInterfaces.split(",")) { String trimIgnoredInterface = ignoredInterface.trim(); boolean matched = false; try { matched = networkInterfaceDisplayName.matches(trimIgnoredInterface); } catch (PatternSyntaxException e) { - // if trimIgnoredInterface is an invalid regular expression, a PatternSyntaxException will be thrown out - logger.warn("exception occurred: " + networkInterfaceDisplayName + " matches " + trimIgnoredInterface, e); + // if trimIgnoredInterface is an invalid regular expression, a PatternSyntaxException will be thrown + // out + logger.warn( + "exception occurred: " + networkInterfaceDisplayName + " matches " + trimIgnoredInterface, + e); } finally { if (matched) { return true; @@ -590,9 +590,11 @@ public final class NetUtils { return HOST_NAME; } try { - HOST_NAME= InetAddress.getLocalHost().getHostName(); + HOST_NAME = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { - HOST_NAME= Optional.ofNullable(getLocalAddress()).map(k->k.getHostName()).orElse(null); + HOST_NAME = Optional.ofNullable(getLocalAddress()) + .map(k -> k.getHostName()) + .orElse(null); } return HOST_NAME; } @@ -639,8 +641,8 @@ public final class NetUtils { } @SuppressWarnings("deprecation") - public static void joinMulticastGroup(MulticastSocket multicastSocket, InetAddress multicastAddress) throws - IOException { + public static void joinMulticastGroup(MulticastSocket multicastSocket, InetAddress multicastAddress) + throws IOException { setInterface(multicastSocket, multicastAddress instanceof Inet6Address); // For the deprecation notice: the equivalent only appears in JDK 9+. @@ -734,7 +736,8 @@ public final class NetUtils { */ public static boolean matchIpRange(String pattern, String host, int port) throws UnknownHostException { if (pattern == null || host == null) { - throw new IllegalArgumentException("Illegal Argument pattern or hostName. Pattern:" + pattern + ", Host:" + host); + throw new IllegalArgumentException( + "Illegal Argument pattern or hostName. Pattern:" + pattern + ", Host:" + host); } pattern = pattern.trim(); if ("*.*.*.*".equals(pattern) || "*".equals(pattern)) { @@ -784,7 +787,11 @@ public final class NetUtils { if (ip < min || ip > max) { return false; } - } else if ("0".equals(ipAddress[i]) && ("0".equals(mask[i]) || "00".equals(mask[i]) || "000".equals(mask[i]) || "0000".equals(mask[i]))) { + } else if ("0".equals(ipAddress[i]) + && ("0".equals(mask[i]) + || "00".equals(mask[i]) + || "000".equals(mask[i]) + || "0000".equals(mask[i]))) { continue; } else if (!mask[i].equals(ipAddress[i])) { return false; @@ -818,14 +825,17 @@ public final class NetUtils { private static void checkHostPattern(String pattern, String[] mask, boolean isIpv4) { if (!isIpv4) { if (mask.length != 8 && ipPatternContainExpression(pattern)) { - throw new IllegalArgumentException("If you config ip expression that contains '*' or '-', please fill qualified ip pattern like 234e:0:4567:0:0:0:3d:*. "); + throw new IllegalArgumentException( + "If you config ip expression that contains '*' or '-', please fill qualified ip pattern like 234e:0:4567:0:0:0:3d:*. "); } if (mask.length != 8 && !pattern.contains("::")) { - throw new IllegalArgumentException("The host is ipv6, but the pattern is not ipv6 pattern : " + pattern); + throw new IllegalArgumentException( + "The host is ipv6, but the pattern is not ipv6 pattern : " + pattern); } } else { if (mask.length != 4) { - throw new IllegalArgumentException("The host is ipv4, but the pattern is not ipv4 pattern : " + pattern); + throw new IllegalArgumentException( + "The host is ipv4, but the pattern is not ipv4 pattern : " + pattern); } } } @@ -859,7 +869,6 @@ public final class NetUtils { return Integer.parseInt(ipSegment, 16); } - public static boolean isIPV6URLStdFormat(String ip) { if ((ip.charAt(0) == '[' && ip.indexOf(']') > 2)) { return true; @@ -871,7 +880,7 @@ public final class NetUtils { } public static String getLegalIP(String ip) { - //ipv6 [::FFFF:129.144.52.38]:80 + // ipv6 [::FFFF:129.144.52.38]:80 int ind; if ((ip.charAt(0) == '[' && (ind = ip.indexOf(']')) > 2)) { String nhost = ip; @@ -882,5 +891,4 @@ public final class NetUtils { return ip; } } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PathUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PathUtils.java index b40e26dceb..5975c8617e 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PathUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PathUtils.java @@ -39,9 +39,7 @@ public interface PathUtils { paths.add(rootPath); paths.addAll(asList(subPaths)); - return normalize(paths.stream() - .filter(StringUtils::isNotEmpty) - .collect(Collectors.joining(SLASH))); + return normalize(paths.stream().filter(StringUtils::isNotEmpty).collect(Collectors.joining(SLASH))); } /** @@ -69,5 +67,4 @@ public interface PathUtils { } return normalizedPath; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.java index 8dcea2fcef..cdf625049b 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.java @@ -81,16 +81,24 @@ public class PojoUtils { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PojoUtils.class); private static final ConcurrentMap NAME_METHODS_CACHE = new ConcurrentHashMap<>(); - private static final ConcurrentMap, ConcurrentMap> CLASS_FIELD_CACHE = new ConcurrentHashMap<>(); + private static final ConcurrentMap, ConcurrentMap> CLASS_FIELD_CACHE = + new ConcurrentHashMap<>(); private static final ConcurrentMap CLASS_NOT_FOUND_CACHE = new ConcurrentHashMap<>(); private static final Object NOT_FOUND_VALUE = new Object(); - private static final boolean GENERIC_WITH_CLZ = Boolean.parseBoolean( - ConfigurationUtils.getProperty(ApplicationModel.defaultModel(), CommonConstants.GENERIC_WITH_CLZ_KEY, "true")); + private static final boolean GENERIC_WITH_CLZ = Boolean.parseBoolean(ConfigurationUtils.getProperty( + ApplicationModel.defaultModel(), CommonConstants.GENERIC_WITH_CLZ_KEY, "true")); - private static final List> CLASS_CAN_BE_STRING = Arrays.asList(Byte.class, Short.class, Integer.class, - Long.class, Float.class, Double.class, Boolean.class, Character.class); + private static final List> CLASS_CAN_BE_STRING = Arrays.asList( + Byte.class, + Short.class, + Integer.class, + Long.class, + Float.class, + Double.class, + Boolean.class, + Character.class); public static Object[] generalize(Object[] objs) { Object[] dests = new Object[objs.length]; @@ -137,7 +145,8 @@ public class PojoUtils { if (pojo instanceof Enum) { return ((Enum) pojo).name(); } - if (pojo.getClass().isArray() && Enum.class.isAssignableFrom(pojo.getClass().getComponentType())) { + if (pojo.getClass().isArray() + && Enum.class.isAssignableFrom(pojo.getClass().getComponentType())) { int len = Array.getLength(pojo); String[] values = new String[len]; for (int i = 0; i < len; i++) { @@ -202,7 +211,9 @@ public class PojoUtils { if (ReflectUtils.isBeanPropertyReadMethod(method)) { ReflectUtils.makeAccessible(method); try { - map.put(ReflectUtils.getPropertyNameFromBeanReadMethod(method), generalize(method.invoke(pojo), history)); + map.put( + ReflectUtils.getPropertyNameFromBeanReadMethod(method), + generalize(method.invoke(pojo), history)); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } @@ -216,7 +227,7 @@ public class PojoUtils { if (history.containsKey(pojo)) { Object pojoGeneralizedValue = history.get(pojo); if (pojoGeneralizedValue instanceof Map - && ((Map) pojoGeneralizedValue).containsKey(field.getName())) { + && ((Map) pojoGeneralizedValue).containsKey(field.getName())) { continue; } } @@ -311,13 +322,17 @@ public class PojoUtils { } else { try { result = cl.getDeclaredConstructor().newInstance(); - } catch (Exception e) { /* ignore */ } + } catch (Exception e) { + /* ignore */ + } if (result == null) { try { Constructor constructor = cl.getConstructor(Map.class); result = (Map) constructor.newInstance(Collections.EMPTY_MAP); - } catch (Exception e) { /* ignore */ } + } catch (Exception e) { + /* ignore */ + } } } @@ -333,7 +348,12 @@ public class PojoUtils { return realize1(pojo, type, genericType, new HashMap<>(8), history); } - private static Object realize1(Object pojo, Class type, Type genericType, final Map mapParent, final Map history) { + private static Object realize1( + Object pojo, + Class type, + Type genericType, + final Map mapParent, + final Map history) { if (pojo == null) { return null; } @@ -343,9 +363,10 @@ public class PojoUtils { } if (ReflectUtils.isPrimitives(pojo.getClass()) - && !(type != null && type.isArray() - && type.getComponentType().isEnum() - && pojo.getClass() == String[].class)) { + && !(type != null + && type.isArray() + && type.getComponentType().isEnum() + && pojo.getClass() == String[].class)) { return CompatibleTypeUtils.compatibleTypeConvert(pojo, type); } @@ -383,7 +404,9 @@ public class PojoUtils { } return dest; } else { - Class ctype = (type != null && type.isArray() ? type.getComponentType() : pojo.getClass().getComponentType()); + Class ctype = (type != null && type.isArray() + ? type.getComponentType() + : pojo.getClass().getComponentType()); int len = Array.getLength(pojo); Object dest = Array.newInstance(ctype, len); history.put(pojo, dest); @@ -433,7 +456,8 @@ public class PojoUtils { if (className instanceof String) { if (!CLASS_NOT_FOUND_CACHE.containsKey(className)) { try { - type = DefaultSerializeClassChecker.getInstance().loadClass(ClassUtils.getClassLoader(), (String) className); + type = DefaultSerializeClassChecker.getInstance() + .loadClass(ClassUtils.getClassLoader(), (String) className); } catch (ClassNotFoundException e) { CLASS_NOT_FOUND_CACHE.put((String) className, NOT_FOUND_VALUE); } @@ -462,7 +486,7 @@ public class PojoUtils { map.remove("class"); } } catch (Exception e) { - //ignore error + // ignore error map = (Map) pojo; } } else { @@ -475,8 +499,8 @@ public class PojoUtils { Type mapKeyType = getKeyTypeForMap(map.getClass()); Type typeKeyType = getGenericClassByIndex(genericType, 0); boolean typeMismatch = mapKeyType instanceof Class - && typeKeyType instanceof Class - && !typeKeyType.getTypeName().equals(mapKeyType.getTypeName()); + && typeKeyType instanceof Class + && !typeKeyType.getTypeName().equals(mapKeyType.getTypeName()); if (typeMismatch) { result = createMap(new HashMap(0)); } else { @@ -493,7 +517,8 @@ public class PojoUtils { } else if (keyType instanceof ParameterizedType) { keyClazz = (Class) ((ParameterizedType) keyType).getRawType(); } else { - keyClazz = entry.getKey() == null ? null : entry.getKey().getClass(); + keyClazz = + entry.getKey() == null ? null : entry.getKey().getClass(); } Class valueClazz; if (valueType instanceof Class) { @@ -501,16 +526,25 @@ public class PojoUtils { } else if (valueType instanceof ParameterizedType) { valueClazz = (Class) ((ParameterizedType) valueType).getRawType(); } else { - valueClazz = entry.getValue() == null ? null : entry.getValue().getClass(); + valueClazz = entry.getValue() == null + ? null + : entry.getValue().getClass(); } - Object key = keyClazz == null ? entry.getKey() : realize1(entry.getKey(), keyClazz, keyType, mapGeneric, history); - Object value = valueClazz == null ? entry.getValue() : realize1(entry.getValue(), valueClazz, valueType, mapGeneric, history); + Object key = keyClazz == null + ? entry.getKey() + : realize1(entry.getKey(), keyClazz, keyType, mapGeneric, history); + Object value = valueClazz == null + ? entry.getValue() + : realize1(entry.getValue(), valueClazz, valueType, mapGeneric, history); result.put(key, value); } return result; } else if (type.isInterface()) { - Object dest = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{type}, new PojoInvocationHandler(map)); + Object dest = Proxy.newProxyInstance( + Thread.currentThread().getContextClassLoader(), + new Class[] {type}, + new PojoInvocationHandler(map)); history.put(pojo, dest); return dest; } else { @@ -541,19 +575,26 @@ public class PojoUtils { method.setAccessible(true); } Type containType = Optional.ofNullable(field) - .map(Field::getGenericType) - .map(Type::getTypeName) - .map(mapGeneric::get) - .orElse(null); + .map(Field::getGenericType) + .map(Type::getTypeName) + .map(mapGeneric::get) + .orElse(null); if (containType != null) { - //is generic + // is generic if (containType instanceof ParameterizedType) { - value = realize1(value, (Class) ((ParameterizedType) containType).getRawType(), containType, mapGeneric, history); + value = realize1( + value, + (Class) ((ParameterizedType) containType).getRawType(), + containType, + mapGeneric, + history); } else if (containType instanceof Class) { - value = realize1(value, (Class) containType, containType, mapGeneric, history); + value = realize1( + value, (Class) containType, containType, mapGeneric, history); } else { Type ptype = method.getGenericParameterTypes()[0]; - value = realize1(value, method.getParameterTypes()[0], ptype, mapGeneric, history); + value = realize1( + value, method.getParameterTypes()[0], ptype, mapGeneric, history); } } else { Type ptype = method.getGenericParameterTypes()[0]; @@ -562,8 +603,9 @@ public class PojoUtils { try { method.invoke(dest, value); } catch (Exception e) { - String exceptionDescription = "Failed to set pojo " + dest.getClass().getSimpleName() + " property " + name - + " value " + value.getClass() + ", cause: " + e.getMessage(); + String exceptionDescription = "Failed to set pojo " + + dest.getClass().getSimpleName() + " property " + name + " value " + + value.getClass() + ", cause: " + e.getMessage(); logger.error(COMMON_REFLECTIVE_OPERATION_FAILED, "", "", exceptionDescription, e); throw new RuntimeException(exceptionDescription, e); } @@ -572,7 +614,10 @@ public class PojoUtils { try { field.set(dest, value); } catch (IllegalAccessException e) { - throw new RuntimeException("Failed to set field " + name + " of pojo " + dest.getClass().getName() + " : " + e.getMessage(), e); + throw new RuntimeException( + "Failed to set field " + name + " of pojo " + + dest.getClass().getName() + " : " + e.getMessage(), + e); } } } @@ -639,12 +684,12 @@ public class PojoUtils { } catch (Exception t) { Constructor[] constructors = cls.getDeclaredConstructors(); /* - From Javadoc java.lang.Class#getDeclaredConstructors - This method returns an array of Constructor objects reflecting all the constructors - declared by the class represented by this Class object. - This method returns an array of length 0, - if this Class object represents an interface, a primitive type, an array class, or void. - */ + From Javadoc java.lang.Class#getDeclaredConstructors + This method returns an array of Constructor objects reflecting all the constructors + declared by the class represented by this Class object. + This method returns an array of length 0, + if this Class object represents an interface, a primitive type, an array class, or void. + */ if (constructors.length == 0) { throw new RuntimeException("Illegal constructor: " + cls.getName()); } @@ -653,7 +698,9 @@ public class PojoUtils { for (Constructor constructor : constructors) { try { constructor.setAccessible(true); - Object[] parameters = Arrays.stream(constructor.getParameterTypes()).map(PojoUtils::getDefaultValue).toArray(); + Object[] parameters = Arrays.stream(constructor.getParameterTypes()) + .map(PojoUtils::getDefaultValue) + .toArray(); return constructor.newInstance(parameters); } catch (Exception e) { lastError = e; @@ -715,7 +762,8 @@ public class PojoUtils { result = getField(cls, fieldName); if (result != null) { - ConcurrentMap fields = CLASS_FIELD_CACHE.computeIfAbsent(cls, k -> new ConcurrentHashMap<>()); + ConcurrentMap fields = + CLASS_FIELD_CACHE.computeIfAbsent(cls, k -> new ConcurrentHashMap<>()); fields.putIfAbsent(fieldName, result); } return result; @@ -745,8 +793,8 @@ public class PojoUtils { public static boolean isPojo(Class cls) { return !ReflectUtils.isPrimitives(cls) - && !Collection.class.isAssignableFrom(cls) - && !Map.class.isAssignableFrom(cls); + && !Collection.class.isAssignableFrom(cls) + && !Map.class.isAssignableFrom(cls); } /** @@ -798,7 +846,9 @@ public class PojoUtils { return convertClassType(mapObject, (Class) fieldType); } else if (fieldType instanceof ParameterizedType) { return convertParameterizedType(mapObject, (ParameterizedType) fieldType); - } else if (fieldType instanceof GenericArrayType || fieldType instanceof TypeVariable || fieldType instanceof WildcardType) { + } else if (fieldType instanceof GenericArrayType + || fieldType instanceof TypeVariable + || fieldType instanceof WildcardType) { // ignore these type currently return null; } else { @@ -823,7 +873,8 @@ public class PojoUtils { } @SuppressWarnings("unchecked") - private static Object convertParameterizedType(Object mapObject, ParameterizedType type) throws ReflectiveOperationException { + private static Object convertParameterizedType(Object mapObject, ParameterizedType type) + throws ReflectiveOperationException { Type rawType = type.getRawType(); if (!isAssignableFrom((Class) rawType, mapObject.getClass())) { return null; @@ -831,7 +882,8 @@ public class PojoUtils { Type[] actualTypeArguments = type.getActualTypeArguments(); if (isAssignableFrom(Map.class, (Class) rawType)) { - Map map = (Map) mapObject.getClass().getDeclaredConstructor().newInstance(); + Map map = (Map) + mapObject.getClass().getDeclaredConstructor().newInstance(); for (Map.Entry entry : ((Map) mapObject).entrySet()) { Object key = getFieldObject(entry.getKey(), actualTypeArguments[0]); Object value = getFieldObject(entry.getValue(), actualTypeArguments[1]); @@ -840,7 +892,8 @@ public class PojoUtils { return map; } else if (isAssignableFrom(Collection.class, (Class) rawType)) { - Collection collection = (Collection) mapObject.getClass().getDeclaredConstructor().newInstance(); + Collection collection = (Collection) + mapObject.getClass().getDeclaredConstructor().newInstance(); for (Object m : (Iterable) mapObject) { Object ele = getFieldObject(m, actualTypeArguments[0]); collection.add(ele); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java index b32cf2d1e4..aa0a04f75d 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectUtils.java @@ -16,11 +16,6 @@ */ package org.apache.dubbo.common.utils; -import javassist.CtClass; -import javassist.CtConstructor; -import javassist.CtMethod; -import javassist.NotFoundException; - import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.MethodDescriptor; @@ -52,6 +47,10 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; +import javassist.CtClass; +import javassist.CtConstructor; +import javassist.CtMethod; +import javassist.NotFoundException; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableSet; @@ -121,15 +120,19 @@ public final class ReflectUtils { public static final Pattern DESC_PATTERN = Pattern.compile(DESC_REGEX); - public static final String METHOD_DESC_REGEX = "(?:(" + JAVA_IDENT_REGEX + ")?\\((" + DESC_REGEX + "*)\\)(" + DESC_REGEX + ")?)"; + public static final String METHOD_DESC_REGEX = + "(?:(" + JAVA_IDENT_REGEX + ")?\\((" + DESC_REGEX + "*)\\)(" + DESC_REGEX + ")?)"; public static final Pattern METHOD_DESC_PATTERN = Pattern.compile(METHOD_DESC_REGEX); - public static final Pattern GETTER_METHOD_DESC_PATTERN = Pattern.compile("get([A-Z][_a-zA-Z0-9]*)\\(\\)(" + DESC_REGEX + ")"); + public static final Pattern GETTER_METHOD_DESC_PATTERN = + Pattern.compile("get([A-Z][_a-zA-Z0-9]*)\\(\\)(" + DESC_REGEX + ")"); - public static final Pattern SETTER_METHOD_DESC_PATTERN = Pattern.compile("set([A-Z][_a-zA-Z0-9]*)\\((" + DESC_REGEX + ")\\)V"); + public static final Pattern SETTER_METHOD_DESC_PATTERN = + Pattern.compile("set([A-Z][_a-zA-Z0-9]*)\\((" + DESC_REGEX + ")\\)V"); - public static final Pattern IS_HAS_CAN_METHOD_DESC_PATTERN = Pattern.compile("(?:is|has|can)([A-Z][_a-zA-Z0-9]*)\\(\\)Z"); + public static final Pattern IS_HAS_CAN_METHOD_DESC_PATTERN = + Pattern.compile("(?:is|has|can)([A-Z][_a-zA-Z0-9]*)\\(\\)Z"); private static Map, Object> primitiveDefaults = new HashMap<>(); @@ -145,8 +148,7 @@ public final class ReflectUtils { primitiveDefaults.put(void.class, null); } - private ReflectUtils() { - } + private ReflectUtils() {} public static boolean isPrimitives(Class cls) { while (cls.isArray()) { @@ -156,8 +158,12 @@ public final class ReflectUtils { } public static boolean isPrimitive(Class cls) { - return cls.isPrimitive() || cls == String.class || cls == Boolean.class || cls == Character.class - || Number.class.isAssignableFrom(cls) || Date.class.isAssignableFrom(cls); + return cls.isPrimitive() + || cls == String.class + || cls == Boolean.class + || cls == Character.class + || Number.class.isAssignableFrom(cls) + || Date.class.isAssignableFrom(cls); } public static Class getBoxedClass(Class c) { @@ -256,8 +262,7 @@ public final class ReflectUtils { do { sb.append("[]"); c = c.getComponentType(); - } - while (c.isArray()); + } while (c.isArray()); return c.getName() + sb.toString(); } @@ -910,7 +915,8 @@ public final class ReflectUtils { throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz); } if (finded.size() > 1) { - String msg = String.format("Not unique method for method name(%s) in class(%s), find %d methods.", + String msg = String.format( + "Not unique method for method name(%s) in class(%s), find %d methods.", methodName, clazz.getName(), finded.size()); throw new IllegalStateException(msg); } @@ -921,7 +927,6 @@ public final class ReflectUtils { types[i] = ReflectUtils.name2class(parameterTypes[i]); } method = clazz.getMethod(methodName, types); - } return method; } @@ -944,7 +949,7 @@ public final class ReflectUtils { public static Constructor findConstructor(Class clazz, Class paramType) throws NoSuchMethodException { Constructor targetConstructor; try { - targetConstructor = clazz.getConstructor(new Class[]{paramType}); + targetConstructor = clazz.getConstructor(new Class[] {paramType}); } catch (NoSuchMethodException e) { targetConstructor = null; Constructor[] constructors = clazz.getConstructors(); @@ -975,8 +980,8 @@ public final class ReflectUtils { */ public static boolean isInstance(Object obj, String interfaceClazzName) { for (Class clazz = obj.getClass(); - clazz != null && !clazz.equals(Object.class); - clazz = clazz.getSuperclass()) { + clazz != null && !clazz.equals(Object.class); + clazz = clazz.getSuperclass()) { Class[] interfaces = clazz.getInterfaces(); for (Class itf : interfaces) { if (itf.getName().equals(interfaceClazzName)) { @@ -1097,7 +1102,8 @@ public final class ReflectUtils { && method.getDeclaringClass() != Object.class && method.getParameterTypes().length == 0 && ((method.getName().startsWith("get") && method.getName().length() > 3) - || (method.getName().startsWith("is") && method.getName().length() > 2)); + || (method.getName().startsWith("is") + && method.getName().length() > 2)); } public static String getPropertyNameFromBeanReadMethod(Method method) { @@ -1144,8 +1150,7 @@ public final class ReflectUtils { for (; cl != null; cl = cl.getSuperclass()) { Field[] fields = cl.getDeclaredFields(); for (Field field : fields) { - if (Modifier.isTransient(field.getModifiers()) - || Modifier.isStatic(field.getModifiers())) { + if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) { continue; } @@ -1195,7 +1200,7 @@ public final class ReflectUtils { genericReturnType = null; } } - return new Type[]{returnType, genericReturnType}; + return new Type[] {returnType, genericReturnType}; } /** @@ -1212,8 +1217,8 @@ public final class ReflectUtils { genericTypes.add(sourceClass.getGenericSuperclass()); Set parameterizedTypes = genericTypes.stream() - .filter(type -> type instanceof ParameterizedType)// filter ParameterizedType - .map(ParameterizedType.class::cast) // cast to ParameterizedType + .filter(type -> type instanceof ParameterizedType) // filter ParameterizedType + .map(ParameterizedType.class::cast) // cast to ParameterizedType .collect(Collectors.toSet()); if (parameterizedTypes.isEmpty()) { // If not found, try to search super types recursively @@ -1223,8 +1228,7 @@ public final class ReflectUtils { .forEach(superClass -> parameterizedTypes.addAll(findParameterizedTypes(superClass))); } - return unmodifiableSet(parameterizedTypes); // build as a Set - + return unmodifiableSet(parameterizedTypes); // build as a Set } /** @@ -1276,10 +1280,11 @@ public final class ReflectUtils { try { return method.getMethod().invoke(bean); } catch (Exception e) { - //ignore + // ignore } return null; - }).get(); + }) + .get(); } catch (Exception e) { } @@ -1352,10 +1357,11 @@ public final class ReflectUtils { * @param method the method to make accessible * @see java.lang.reflect.Method#setAccessible */ - @SuppressWarnings("deprecation") // on JDK 9 + @SuppressWarnings("deprecation") // on JDK 9 public static void makeAccessible(Method method) { - if ((!Modifier.isPublic(method.getModifiers()) || - !Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible()) { + if ((!Modifier.isPublic(method.getModifiers()) + || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) + && !method.isAccessible()) { method.setAccessible(true); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectionUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectionUtils.java index bf5ec423e2..b1fbeb520b 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectionUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ReflectionUtils.java @@ -33,8 +33,7 @@ import java.util.stream.Collectors; */ public class ReflectionUtils { - private ReflectionUtils() { - } + private ReflectionUtils() {} /** * Retrieves the value of the specified field from the given object. @@ -65,8 +64,8 @@ public class ReflectionUtils { public static Object invoke(Object source, String methodName, Object... params) { try { Class[] classes = Arrays.stream(params) - .map(param -> param != null ? param.getClass() : null) - .toArray(Class[]::new); + .map(param -> param != null ? param.getClass() : null) + .toArray(Class[]::new); for (Method method : source.getClass().getDeclaredMethods()) { if (method.getName().equals(methodName) && matchParameters(method.getParameterTypes(), classes)) { @@ -151,5 +150,4 @@ public class ReflectionUtils { List> eventTypes = ReflectionUtils.getClassGenerics(clazz, interfaceClass); return eventTypes.stream().allMatch(eventType -> eventType.isInstance(event)); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/RegexProperties.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/RegexProperties.java index cb7f24c6c0..e91c91ff43 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/RegexProperties.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/RegexProperties.java @@ -37,17 +37,15 @@ public class RegexProperties extends Properties { } // Sort the keys to solve the problem of matching priority. - List sortedKeyList = keySet() - .stream() + List sortedKeyList = keySet().stream() .map(k -> (String) k) .sorted(Comparator.reverseOrder()) .collect(Collectors.toList()); - String keyPattern = sortedKeyList - .stream() + String keyPattern = sortedKeyList.stream() .filter(k -> { String matchingKey = k; - if(matchingKey.startsWith(CommonConstants.ANY_VALUE)){ + if (matchingKey.startsWith(CommonConstants.ANY_VALUE)) { matchingKey = CommonConstants.HIDE_KEY_PREFIX + matchingKey; } return Pattern.matches(matchingKey, key); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/SerializeSecurityConfigurator.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/SerializeSecurityConfigurator.java index ba7227a1ac..f49f7cfbfb 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/SerializeSecurityConfigurator.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/SerializeSecurityConfigurator.java @@ -50,7 +50,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_IO_EX public class SerializeSecurityConfigurator implements ScopeClassLoaderListener { private final SerializeSecurityManager serializeSecurityManager; - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SerializeSecurityConfigurator.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(SerializeSecurityConfigurator.class); private final ModuleModel moduleModel; @@ -73,10 +74,16 @@ public class SerializeSecurityConfigurator implements ScopeClassLoaderListener applicationConfig = moduleModel.getApplicationModel().getApplicationConfigManager().getApplication(); - autoTrustSerializeClass = applicationConfig.map(ApplicationConfig::getAutoTrustSerializeClass).orElse(true); - trustSerializeClassLevel = applicationConfig.map(ApplicationConfig::getTrustSerializeClassLevel).orElse(Integer.MAX_VALUE); - serializeSecurityManager.setCheckSerializable(applicationConfig.map(ApplicationConfig::getCheckSerializable).orElse(true)); + Optional applicationConfig = + moduleModel.getApplicationModel().getApplicationConfigManager().getApplication(); + autoTrustSerializeClass = applicationConfig + .map(ApplicationConfig::getAutoTrustSerializeClass) + .orElse(true); + trustSerializeClassLevel = applicationConfig + .map(ApplicationConfig::getTrustSerializeClassLevel) + .orElse(Integer.MAX_VALUE); + serializeSecurityManager.setCheckSerializable( + applicationConfig.map(ApplicationConfig::getCheckSerializable).orElse(true)); } @Override @@ -95,8 +102,10 @@ public class SerializeSecurityConfigurator implements ScopeClassLoaderListener application = moduleModel.getApplicationModel().getApplicationConfigManager().getApplication(); - String statusString = application.map(ApplicationConfig::getSerializeCheckStatus).orElse(null); + Optional application = + moduleModel.getApplicationModel().getApplicationConfigManager().getApplication(); + String statusString = + application.map(ApplicationConfig::getSerializeCheckStatus).orElse(null); SerializeCheckStatus checkStatus = null; if (StringUtils.isEmpty(statusString)) { @@ -275,8 +296,11 @@ public class SerializeSecurityConfigurator implements ScopeClassLoaderListener trustSerializeClassLevel) { - serializeSecurityManager.addToAllowed(Arrays.stream(subs) - .limit(trustSerializeClassLevel) - .collect(Collectors.joining(".")) + "."); + serializeSecurityManager.addToAllowed( + Arrays.stream(subs).limit(trustSerializeClassLevel).collect(Collectors.joining(".")) + "."); } else { serializeSecurityManager.addToAllowed(className); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/SerializeSecurityManager.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/SerializeSecurityManager.java index 66158ca0c2..1b07de5392 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/SerializeSecurityManager.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/SerializeSecurityManager.java @@ -24,7 +24,8 @@ import java.util.Objects; import java.util.Set; public class SerializeSecurityManager { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SerializeSecurityManager.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(SerializeSecurityManager.class); private final Set allowedPrefix = new ConcurrentHashSet<>(); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ServiceAnnotationResolver.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ServiceAnnotationResolver.java index 3bc86a869e..f2efa8ede1 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ServiceAnnotationResolver.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ServiceAnnotationResolver.java @@ -77,10 +77,9 @@ public class ServiceAnnotationResolver { } if (serviceAnnotation == null) { - throw new IllegalArgumentException(format("Any annotation of [%s] can't be annotated in the service type[%s].", - SERVICE_ANNOTATION_CLASSES, - serviceType.getName() - )); + throw new IllegalArgumentException(format( + "Any annotation of [%s] can't be annotated in the service type[%s].", + SERVICE_ANNOTATION_CLASSES, serviceType.getName())); } return serviceAnnotation; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Stack.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Stack.java index 58241aadba..13e7ae4e7d 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Stack.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/Stack.java @@ -23,14 +23,12 @@ import java.util.List; /** * Stack. */ - public class Stack { private int mSize = 0; private final List mElements = new ArrayList(); - public Stack() { - } + public Stack() {} /** * push. diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/StringConstantFieldValuePredicate.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/StringConstantFieldValuePredicate.java index 534a612bfd..bf671ddd18 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/StringConstantFieldValuePredicate.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/StringConstantFieldValuePredicate.java @@ -47,12 +47,12 @@ public class StringConstantFieldValuePredicate implements Predicate { private Set getConstantFieldValues(Class targetClass) { return Stream.of(targetClass.getFields()) - .filter(f -> isStatic(f.getModifiers())) // static - .filter(f -> isPublic(f.getModifiers())) // public - .filter(f -> isFinal(f.getModifiers())) // final + .filter(f -> isStatic(f.getModifiers())) // static + .filter(f -> isPublic(f.getModifiers())) // public + .filter(f -> isFinal(f.getModifiers())) // final .map(this::getConstantValue) - .filter(v -> v instanceof String) // filters String type - .map(String.class::cast) // Casts String type + .filter(v -> v instanceof String) // filters String type + .map(String.class::cast) // Casts String type .collect(Collectors.toSet()); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/StringUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/StringUtils.java index 34fa8b5403..0a8cba4bcd 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/StringUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/StringUtils.java @@ -51,7 +51,6 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_JSON_ /** * StringUtils */ - public final class StringUtils { public static final String EMPTY_STRING = ""; @@ -59,14 +58,16 @@ public final class StringUtils { public static final String[] EMPTY_STRING_ARRAY = new String[0]; private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(StringUtils.class); - private static final Pattern KVP_PATTERN = Pattern.compile("([_.a-zA-Z0-9][-_.a-zA-Z0-9]*)[=](.*)"); //key value pair pattern. + private static final Pattern KVP_PATTERN = + Pattern.compile("([_.a-zA-Z0-9][-_.a-zA-Z0-9]*)[=](.*)"); // key value pair pattern. private static final Pattern NUM_PATTERN = Pattern.compile("^\\d+$"); - private static final Pattern PARAMETERS_PATTERN = Pattern.compile("^\\[((\\s*\\{\\s*[\\w_\\-\\.]+\\s*:\\s*.+?\\s*\\}\\s*,?\\s*)+)\\s*\\]$"); - private static final Pattern PAIR_PARAMETERS_PATTERN = Pattern.compile("^\\{\\s*([\\w-_\\.]+)\\s*:\\s*(.+)\\s*\\}$"); + private static final Pattern PARAMETERS_PATTERN = + Pattern.compile("^\\[((\\s*\\{\\s*[\\w_\\-\\.]+\\s*:\\s*.+?\\s*\\}\\s*,?\\s*)+)\\s*\\]$"); + private static final Pattern PAIR_PARAMETERS_PATTERN = + Pattern.compile("^\\{\\s*([\\w-_\\.]+)\\s*:\\s*(.+)\\s*\\}$"); private static final int PAD_LIMIT = 8192; private static final byte[] HEX2B; - /** * @since 2.7.5 */ @@ -121,8 +122,7 @@ public final class StringUtils { HEX2B['f'] = (byte) 15; } - private StringUtils() { - } + private StringUtils() {} /** * Gets a CharSequence length or {@code 0} if the CharSequence is @@ -626,7 +626,6 @@ public final class StringUtils { return true; } - /** * @param e * @return string @@ -773,10 +772,7 @@ public final class StringUtils { return new LinkedHashSet(values); } - return unmodifiableSet(values - .stream() - .map(String::trim) - .collect(LinkedHashSet::new, Set::add, Set::addAll)); + return unmodifiableSet(values.stream().map(String::trim).collect(LinkedHashSet::new, Set::add, Set::addAll)); } /** @@ -993,9 +989,7 @@ public final class StringUtils { } private static boolean isWord(char ch) { - if ((ch >= 'A' && ch <= 'Z') || - (ch >= 'a' && ch <= 'z') || - (ch >= '0' && ch <= '9')) { + if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) { return true; } return false; @@ -1097,7 +1091,7 @@ public final class StringUtils { if (str == null) { return new String[0]; } else if (delimiter == null) { - return new String[]{str}; + return new String[] {str}; } else { List result = new ArrayList(); int pos; @@ -1241,8 +1235,8 @@ public final class StringUtils { int hi = decodeHexNibble(s.charAt(pos)); int lo = decodeHexNibble(s.charAt(pos + 1)); if (hi == -1 || lo == -1) { - throw new IllegalArgumentException(String.format( - "invalid hex byte '%s' at index %d of '%s'", s.subSequence(pos, pos + 2), pos, s)); + throw new IllegalArgumentException( + String.format("invalid hex byte '%s' at index %d of '%s'", s.subSequence(pos, pos + 2), pos, s)); } return (byte) ((hi << 4) + lo); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/TimeUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/TimeUtils.java index 0355b6cf9a..d6b18476f3 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/TimeUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/TimeUtils.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; import java.util.concurrent.TimeUnit; @@ -30,8 +29,7 @@ public final class TimeUtils { private static volatile boolean isFallback = false; - private TimeUtils() { - } + private TimeUtils() {} public static long currentTimeMillis() { // When an exception occurs in the Ticker mechanism, fall back. diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ToStringUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ToStringUtils.java index 507146736a..0c18a0b1b3 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ToStringUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/ToStringUtils.java @@ -24,8 +24,7 @@ import java.util.Map; public class ToStringUtils { - private ToStringUtils() { - } + private ToStringUtils() {} public static String printToString(Object obj) { if (obj == null) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/TypeUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/TypeUtils.java index 0555602e5c..7b45759ce3 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/TypeUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/TypeUtils.java @@ -121,13 +121,10 @@ public interface TypeUtils { genericTypes.add(rawClass.getGenericSuperclass()); genericTypes.addAll(asList(rawClass.getGenericInterfaces())); - return unmodifiableList( - filterList(genericTypes, TypeUtils::isParameterizedType) - .stream() - .map(ParameterizedType.class::cast) - .filter(and(typeFilters)) - .collect(toList()) - ); + return unmodifiableList(filterList(genericTypes, TypeUtils::isParameterizedType).stream() + .map(ParameterizedType.class::cast) + .filter(and(typeFilters)) + .collect(toList())); } /** @@ -168,8 +165,7 @@ public interface TypeUtils { // Add all super classes allTypes.addAll(getAllSuperClasses(rawClass, NON_OBJECT_TYPE_FILTER)); - List allGenericSuperClasses = allTypes - .stream() + List allGenericSuperClasses = allTypes.stream() .map(Class::getGenericSuperclass) .filter(TypeUtils::isParameterizedType) .map(ParameterizedType.class::cast) @@ -201,8 +197,7 @@ public interface TypeUtils { // Add all super interfaces allTypes.addAll(getAllInterfaces(rawClass)); - List allGenericInterfaces = allTypes - .stream() + List allGenericInterfaces = allTypes.stream() .map(Class::getGenericInterfaces) .map(Arrays::asList) .flatMap(Collection::stream) @@ -218,8 +213,6 @@ public interface TypeUtils { } static Set getClassNames(Iterable types) { - return stream(types.spliterator(), false) - .map(TypeUtils::getClassName) - .collect(toSet()); + return stream(types.spliterator(), false).map(TypeUtils::getClassName).collect(toSet()); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java index 0167438a1e..ec1745e431 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/UrlUtils.java @@ -178,7 +178,8 @@ public class UrlUtils { } String[] addresses = REGISTRY_SPLIT_PATTERN.split(address); if (addresses == null || addresses.length == 0) { - throw new IllegalArgumentException("Addresses is not allowed to be empty, please re-enter."); //here won't be empty + throw new IllegalArgumentException( + "Addresses is not allowed to be empty, please re-enter."); // here won't be empty } List registries = new ArrayList(); for (String addr : addresses) { @@ -199,8 +200,8 @@ public class UrlUtils { Map params = StringUtils.parseQueryString(serviceQuery); String group = params.get(GROUP_KEY); String version = params.get(VERSION_KEY); - //params.remove("group"); - //params.remove("version"); + // params.remove("group"); + // params.remove("version"); String name = serviceName; if (StringUtils.isNotEmpty(group)) { name = group + "/" + name; @@ -228,8 +229,8 @@ public class UrlUtils { Map params = StringUtils.parseQueryString(serviceQuery); String group = params.get(GROUP_KEY); String version = params.get(VERSION_KEY); - //params.remove("group"); - //params.remove("version"); + // params.remove("group"); + // params.remove("version"); String name = serviceName; if (StringUtils.isNotEmpty(group)) { name = group + "/" + name; @@ -343,7 +344,7 @@ public class UrlUtils { return notify; } - //compatible for dubbo-2.0.0 + // compatible for dubbo-2.0.0 public static List revertForbid(List forbid, Set subscribed) { if (CollectionUtils.isNotEmpty(forbid)) { List newForbid = new ArrayList<>(); @@ -378,9 +379,9 @@ public class UrlUtils { service = service.substring(0, i); } return URL.valueOf(EMPTY_PROTOCOL + "://0.0.0.0/" + service + URL_PARAM_STARTING_SYMBOL - + CATEGORY_KEY + "=" + category - + (group == null ? "" : "&" + GROUP_KEY + "=" + group) - + (version == null ? "" : "&" + VERSION_KEY + "=" + version)); + + CATEGORY_KEY + "=" + category + + (group == null ? "" : "&" + GROUP_KEY + "=" + group) + + (version == null ? "" : "&" + VERSION_KEY + "=" + version)); } public static boolean isMatchCategory(String category, String categories) { @@ -399,27 +400,28 @@ public class UrlUtils { String consumerInterface = consumerUrl.getServiceInterface(); String providerInterface = providerUrl.getServiceInterface(); - // FIXME accept providerUrl with '*' as interface name, after carefully thought about all possible scenarios I think it's ok to add this condition. + // FIXME accept providerUrl with '*' as interface name, after carefully thought about all possible scenarios I + // think it's ok to add this condition. // Return false if the consumer interface is not equals the provider interface, // except one of the interface configurations is equals '*' (i.e. any value). if (!(ANY_VALUE.equals(consumerInterface) - || ANY_VALUE.equals(providerInterface) - || StringUtils.isEquals(consumerInterface, providerInterface))) { + || ANY_VALUE.equals(providerInterface) + || StringUtils.isEquals(consumerInterface, providerInterface))) { return false; } // If the category of provider URL does not match the category of consumer URL. // Usually, the provider URL's category is empty, and the default category ('providers') is present. // Hence, the category of the provider URL is 'providers'. - // Through observing of debugging process, I found that the category of the consumer URL is 'providers,configurators,routers'. + // Through observing of debugging process, I found that the category of the consumer URL is + // 'providers,configurators,routers'. if (!isMatchCategory(providerUrl.getCategory(DEFAULT_CATEGORY), consumerUrl.getCategory(DEFAULT_CATEGORY))) { return false; } // If the provider is not enabled, return false. - if (!providerUrl.getParameter(ENABLED_KEY, true) - && !ANY_VALUE.equals(consumerUrl.getParameter(ENABLED_KEY))) { + if (!providerUrl.getParameter(ENABLED_KEY, true) && !ANY_VALUE.equals(consumerUrl.getParameter(ENABLED_KEY))) { return false; } @@ -434,9 +436,14 @@ public class UrlUtils { String providerClassifier = providerUrl.getParameter(CLASSIFIER_KEY, ANY_VALUE); // If Group, Version, Classifier all matches, return true. - boolean groupMatches = ANY_VALUE.equals(consumerGroup) || StringUtils.isEquals(consumerGroup, providerGroup) || StringUtils.isContains(consumerGroup, providerGroup); - boolean versionMatches = ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion); - boolean classifierMatches = consumerClassifier == null || ANY_VALUE.equals(consumerClassifier) || StringUtils.isEquals(consumerClassifier, providerClassifier); + boolean groupMatches = ANY_VALUE.equals(consumerGroup) + || StringUtils.isEquals(consumerGroup, providerGroup) + || StringUtils.isContains(consumerGroup, providerGroup); + boolean versionMatches = + ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion); + boolean classifierMatches = consumerClassifier == null + || ANY_VALUE.equals(consumerClassifier) + || StringUtils.isEquals(consumerClassifier, providerClassifier); return groupMatches && versionMatches && classifierMatches; } @@ -481,12 +488,9 @@ public class UrlUtils { } public static boolean isServiceKeyMatch(URL pattern, URL value) { - return pattern.getParameter(INTERFACE_KEY).equals( - value.getParameter(INTERFACE_KEY)) - && isItemMatch(pattern.getGroup(), - value.getGroup()) - && isItemMatch(pattern.getVersion(), - value.getVersion()); + return pattern.getParameter(INTERFACE_KEY).equals(value.getParameter(INTERFACE_KEY)) + && isItemMatch(pattern.getGroup(), value.getGroup()) + && isItemMatch(pattern.getVersion(), value.getVersion()); } public static List classifyUrls(List urls, Predicate predicate) { @@ -494,25 +498,24 @@ public class UrlUtils { } public static boolean isConfigurator(URL url) { - return OVERRIDE_PROTOCOL.equals(url.getProtocol()) || - CONFIGURATORS_CATEGORY.equals(url.getCategory(DEFAULT_CATEGORY)); + return OVERRIDE_PROTOCOL.equals(url.getProtocol()) + || CONFIGURATORS_CATEGORY.equals(url.getCategory(DEFAULT_CATEGORY)); } public static boolean isRoute(URL url) { - return ROUTE_PROTOCOL.equals(url.getProtocol()) || - ROUTERS_CATEGORY.equals(url.getCategory(DEFAULT_CATEGORY)); + return ROUTE_PROTOCOL.equals(url.getProtocol()) || ROUTERS_CATEGORY.equals(url.getCategory(DEFAULT_CATEGORY)); } public static boolean isProvider(URL url) { - return !OVERRIDE_PROTOCOL.equals(url.getProtocol()) && - !ROUTE_PROTOCOL.equals(url.getProtocol()) && - PROVIDERS_CATEGORY.equals(url.getCategory(PROVIDERS_CATEGORY)); + return !OVERRIDE_PROTOCOL.equals(url.getProtocol()) + && !ROUTE_PROTOCOL.equals(url.getProtocol()) + && PROVIDERS_CATEGORY.equals(url.getCategory(PROVIDERS_CATEGORY)); } public static boolean isRegistry(URL url) { return REGISTRY_PROTOCOL.equals(url.getProtocol()) - || SERVICE_REGISTRY_PROTOCOL.equalsIgnoreCase(url.getProtocol()) - || (url.getProtocol() != null && url.getProtocol().endsWith("-registry-protocol")); + || SERVICE_REGISTRY_PROTOCOL.equalsIgnoreCase(url.getProtocol()) + || (url.getProtocol() != null && url.getProtocol().endsWith("-registry-protocol")); } /** @@ -683,5 +686,4 @@ public class UrlUtils { public static boolean isConsumer(URL url) { return url.getProtocol().equalsIgnoreCase(CONSUMER) || url.getPort() == 0; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractConfig.java index 26eff722b9..2c481f7ca1 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractConfig.java @@ -95,7 +95,7 @@ public abstract class AbstractConfig implements Serializable { /** * The suffix container */ - private static final String[] SUFFIXES = new String[]{"Config", "Bean", "ConfigBase"}; + private static final String[] SUFFIXES = new String[] {"Config", "Bean", "ConfigBase"}; /** * Identifier for this configuration. @@ -177,11 +177,13 @@ public abstract class AbstractConfig implements Serializable { appendParameters0(parameters, config, prefix, false); } - private static void appendParameters0(Map parameters, Object config, String prefix, boolean asParameters) { + private static void appendParameters0( + Map parameters, Object config, String prefix, boolean asParameters) { if (config == null) { return; } - // If asParameters=false, it means append attributes, ignore @Parameter annotation's attributes except 'append' and 'attribute' + // If asParameters=false, it means append attributes, ignore @Parameter annotation's attributes except 'append' + // and 'attribute' // How to select the appropriate one from multiple getter methods of the property? // e.g. Using String getGeneric() or Boolean isGeneric()? Judge by field type ? @@ -228,7 +230,7 @@ public abstract class AbstractConfig implements Serializable { String pre = parameters.get(key); if (pre != null && pre.length() > 0) { str = pre + "," + str; - //Remove duplicate values + // Remove duplicate values Set set = StringUtils.splitToSet(str, ','); str = StringUtils.join(set, ","); } @@ -292,7 +294,8 @@ public abstract class AbstractConfig implements Serializable { private static void invokeSetParameters(Class c, Object o, Map map) { try { - Method method = ReflectUtils.findMethodByMethodSignature(c, "setParameters", new String[]{Map.class.getName()}); + Method method = + ReflectUtils.findMethodByMethodSignature(c, "setParameters", new String[] {Map.class.getName()}); if (method != null && isParametersSetter(method)) { method.invoke(o, map); } @@ -317,27 +320,29 @@ public abstract class AbstractConfig implements Serializable { private static boolean isParametersGetter(Method method) { String name = method.getName(); return ("getParameters".equals(name) - && Modifier.isPublic(method.getModifiers()) - && method.getParameterTypes().length == 0 - && method.getReturnType() == Map.class); + && Modifier.isPublic(method.getModifiers()) + && method.getParameterTypes().length == 0 + && method.getReturnType() == Map.class); } private static boolean isParametersSetter(Method method) { return ("setParameters".equals(method.getName()) - && Modifier.isPublic(method.getModifiers()) - && method.getParameterCount() == 1 - && Map.class == method.getParameterTypes()[0] - && method.getReturnType() == void.class); + && Modifier.isPublic(method.getModifiers()) + && method.getParameterCount() == 1 + && Map.class == method.getParameterTypes()[0] + && method.getReturnType() == void.class); } private static boolean isNestedGetter(Object obj, Method method) { String name = method.getName(); boolean isGetter = (name.startsWith("get") || name.startsWith("is")) - && !"get".equals(name) && !"is".equals(name) - && !"getClass".equals(name) && !"getObject".equals(name) - && Modifier.isPublic(method.getModifiers()) - && method.getParameterTypes().length == 0 - && (!method.getReturnType().isPrimitive() && !isSimpleType(method.getReturnType())); + && !"get".equals(name) + && !"is".equals(name) + && !"getClass".equals(name) + && !"getObject".equals(name) + && Modifier.isPublic(method.getModifiers()) + && method.getParameterTypes().length == 0 + && (!method.getReturnType().isPrimitive() && !isSimpleType(method.getReturnType())); if (!isGetter) { return false; @@ -351,11 +356,11 @@ public abstract class AbstractConfig implements Serializable { private static boolean isNestedSetter(Object obj, Method method) { boolean isSetter = method.getName().startsWith("set") - && !"set".equals(method.getName()) - && Modifier.isPublic(method.getModifiers()) - && method.getParameterCount() == 1 - && method.getParameterTypes()[0] != null - && (!method.getParameterTypes()[0].isPrimitive() && !isSimpleType(method.getParameterTypes()[0])); + && !"set".equals(method.getName()) + && Modifier.isPublic(method.getModifiers()) + && method.getParameterCount() == 1 + && method.getParameterTypes()[0] != null + && (!method.getParameterTypes()[0].isPrimitive() && !isSimpleType(method.getParameterTypes()[0])); if (!isSetter) { return false; @@ -431,7 +436,8 @@ public abstract class AbstractConfig implements Serializable { protected void checkScopeModel(ScopeModel scopeModel) { if (!(scopeModel instanceof ApplicationModel)) { - throw new IllegalArgumentException("Invalid scope model, expect to be a ApplicationModel but got: " + scopeModel); + throw new IllegalArgumentException( + "Invalid scope model, expect to be a ApplicationModel but got: " + scopeModel); } } @@ -456,9 +462,9 @@ public abstract class AbstractConfig implements Serializable { */ protected void postProcessAfterScopeModelChanged(ScopeModel oldScopeModel, ScopeModel newScopeModel) { // remove this config from old ConfigManager -// if (oldScopeModel != null && oldScopeModel instanceof ApplicationModel) { -// ((ApplicationModel)oldScopeModel).getApplicationConfigManager().removeConfig(this); -// } + // if (oldScopeModel != null && oldScopeModel instanceof ApplicationModel) { + // ((ApplicationModel)oldScopeModel).getApplicationConfigManager().removeConfig(this); + // } } protected ExtensionLoader getExtensionLoader(Class type) { @@ -487,11 +493,11 @@ public abstract class AbstractConfig implements Serializable { Method[] methods = annotationClass.getMethods(); for (Method method : methods) { if (method.getDeclaringClass() != Object.class - && method.getDeclaringClass() != Annotation.class - && method.getReturnType() != void.class - && method.getParameterTypes().length == 0 - && Modifier.isPublic(method.getModifiers()) - && !Modifier.isStatic(method.getModifiers())) { + && method.getDeclaringClass() != Annotation.class + && method.getReturnType() != void.class + && method.getParameterTypes().length == 0 + && Modifier.isPublic(method.getModifiers()) + && !Modifier.isStatic(method.getModifiers())) { try { String property = method.getName(); if ("interfaceClass".equals(property) || "interfaceName".equals(property)) { @@ -612,7 +618,8 @@ public abstract class AbstractConfig implements Serializable { return; } - List methods = MethodUtils.getMethods(this.getClass(), method -> method.getDeclaringClass() != Object.class); + List methods = + MethodUtils.getMethods(this.getClass(), method -> method.getDeclaringClass() != Object.class); for (Method method : methods) { try { Method getterMethod; @@ -661,7 +668,8 @@ public abstract class AbstractConfig implements Serializable { } // if mode is OVERRIDE_IF_ABSENT, put all old map entries to new map, will override the same key - // if mode is OVERRIDE_ALL, put all keyed entries not in new map from old map to new map (ignore the same key appeared in old map) + // if mode is OVERRIDE_ALL, put all keyed entries not in new map from old map to new map (ignore the + // same key appeared in old map) if (overrideAll) { oldMap.forEach(newMap::putIfAbsent); } else { @@ -674,7 +682,12 @@ public abstract class AbstractConfig implements Serializable { } } catch (Throwable t) { - logger.error(COMMON_FAILED_OVERRIDE_FIELD, "", "", "Failed to override field value of config bean: " + this, t); + logger.error( + COMMON_FAILED_OVERRIDE_FIELD, + "", + "", + "Failed to override field value of config bean: " + this, + t); throw new IllegalStateException("Failed to override field value of config bean: " + this, t); } } @@ -690,7 +703,12 @@ public abstract class AbstractConfig implements Serializable { preProcessRefresh(); refreshWithPrefixes(getPrefixes(), getConfigMode()); } catch (Exception e) { - logger.error(COMMON_FAILED_OVERRIDE_FIELD, "", "", "Failed to override field value of config bean: " + this, e); + logger.error( + COMMON_FAILED_OVERRIDE_FIELD, + "", + "", + "Failed to override field value of config bean: " + this, + e); throw new IllegalStateException("Failed to override field value of config bean: " + this, e); } @@ -729,9 +747,9 @@ public abstract class AbstractConfig implements Serializable { idOrName = "[name=" + name + "]"; } } - logger.debug("Refreshing " + this.getClass().getSimpleName() + idOrName + - " with prefix [" + preferredPrefix + - "], extracted props: " + subProperties); + logger.debug("Refreshing " + this.getClass().getSimpleName() + idOrName + " with prefix [" + + preferredPrefix + "], extracted props: " + + subProperties); } assignProperties(this, environment, subProperties, subPropsConfiguration, configMode); @@ -740,7 +758,12 @@ public abstract class AbstractConfig implements Serializable { processExtraRefresh(preferredPrefix, subPropsConfiguration); } - private void assignProperties(Object obj, Environment environment, Map properties, InmemoryConfiguration configuration, ConfigMode configMode) { + private void assignProperties( + Object obj, + Environment environment, + Map properties, + InmemoryConfiguration configuration, + ConfigMode configMode) { // if old one (this) contains non-null value, do not override boolean overrideIfAbsent = configMode == ConfigMode.OVERRIDE_IF_ABSENT; @@ -748,7 +771,8 @@ public abstract class AbstractConfig implements Serializable { boolean overrideAll = configMode == ConfigMode.OVERRIDE_ALL; // loop methods, get override value and set the new value back to method - List methods = MethodUtils.getMethods(obj.getClass(), method -> method.getDeclaringClass() != Object.class); + List methods = + MethodUtils.getMethods(obj.getClass(), method -> method.getDeclaringClass() != Object.class); for (Method method : methods) { if (MethodUtils.isSetter(method)) { String propertyName = extractPropertyName(method.getName()); @@ -763,22 +787,26 @@ public abstract class AbstractConfig implements Serializable { try { String value = StringUtils.trim(configuration.getString(kebabPropertyName)); - // isTypeMatch() is called to avoid duplicate and incorrect update, for example, we have two 'setGeneric' methods in ReferenceConfig. + // isTypeMatch() is called to avoid duplicate and incorrect update, for example, we have two + // 'setGeneric' methods in ReferenceConfig. if (StringUtils.hasText(value) - && ClassUtils.isTypeMatch(method.getParameterTypes()[0], value) - && !isIgnoredAttribute(obj.getClass(), propertyName)) { + && ClassUtils.isTypeMatch(method.getParameterTypes()[0], value) + && !isIgnoredAttribute(obj.getClass(), propertyName)) { value = environment.resolvePlaceholders(value); if (StringUtils.hasText(value)) { - Object arg = ClassUtils.convertPrimitive(ScopeModelUtil.getFrameworkModel(getScopeModel()), method.getParameterTypes()[0], value); + Object arg = ClassUtils.convertPrimitive( + ScopeModelUtil.getFrameworkModel(getScopeModel()), + method.getParameterTypes()[0], + value); if (arg != null) { method.invoke(obj, arg); } } } } catch (Exception e) { - logger.info("Failed to override the property " + method.getName() + " in " + - obj.getClass().getSimpleName() + - ", please make sure every property has getter/setter method provided."); + logger.info("Failed to override the property " + method.getName() + " in " + + obj.getClass().getSimpleName() + + ", please make sure every property has getter/setter method provided."); } } else if (isParametersSetter(method)) { String propertyName = extractPropertyName(method.getName()); @@ -816,7 +844,8 @@ public abstract class AbstractConfig implements Serializable { } // if mode is OVERRIDE_IF_ABSENT, put all old map entries to new map, will override the same key - // if mode is OVERRIDE_ALL, put all keyed entries not in new map from old map to new map (ignore the same key appeared in old map) + // if mode is OVERRIDE_ALL, put all keyed entries not in new map from old map to new map (ignore the + // same key appeared in old map) // if mode is others, override with new map if (overrideIfAbsent) { newMap.putAll(oldMap); @@ -835,7 +864,10 @@ public abstract class AbstractConfig implements Serializable { assignProperties(inner, environment, subProperties, subPropsConfiguration, configMode); method.invoke(obj, inner); } catch (ReflectiveOperationException e) { - throw new IllegalStateException("Cannot assign nested class when refreshing config: " + obj.getClass().getName(), e); + throw new IllegalStateException( + "Cannot assign nested class when refreshing config: " + + obj.getClass().getName(), + e); } } } @@ -931,8 +963,7 @@ public abstract class AbstractConfig implements Serializable { * @see AbstractConfig#getMetaData() * @see AbstractConfig#appendAttributes(Map, Object) */ - protected void checkDefault() { - } + protected void checkDefault() {} @Parameter(excluded = true, attribute = false) public boolean isRefreshed() { @@ -1040,7 +1071,7 @@ public abstract class AbstractConfig implements Serializable { hashCode = 31 * hashCode + value.hashCode(); } } catch (Exception ignored) { - //ignored + // ignored } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java index cad5d4f9e9..53b3eadb35 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractInterfaceConfig.java @@ -213,8 +213,7 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { */ private Boolean singleton; - public AbstractInterfaceConfig() { - } + public AbstractInterfaceConfig() {} public AbstractInterfaceConfig(ModuleModel moduleModel) { super(moduleModel); @@ -223,7 +222,7 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { /** * The url of the reference service */ - protected transient final List urls = new ArrayList(); + protected final transient List urls = new ArrayList(); @Transient public List getExportedUrls() { @@ -269,8 +268,8 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { for (RegistryConfig registryConfig : registries) { if (!registryConfig.isValid()) { - throw new IllegalStateException("No registry config found or it's not a valid config! " + - "The registry config is: " + registryConfig); + throw new IllegalStateException("No registry config found or it's not a valid config! " + + "The registry config is: " + registryConfig); } } } @@ -309,7 +308,9 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { */ protected String[] methods(Class interfaceClass) { if (NativeDetector.inNativeImage()) { - return Arrays.stream(interfaceClass.getMethods()).map(Method::getName).toArray(String[]::new); + return Arrays.stream(interfaceClass.getMethods()) + .map(Method::getName) + .toArray(String[]::new); } else { return ClassUtils.getMethodNames(interfaceClass); } @@ -357,8 +358,8 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { // dubbo.service.{interfaceName}.{methodName}.{arg-index}.xxx=xxx java.lang.reflect.Parameter[] arguments = method.getParameters(); for (int i = 0; i < arguments.length; i++) { - if (getArgumentByIndex(methodConfig, i) == null && - hasArgumentConfigProps(configProperties, methodConfig.getName(), i)) { + if (getArgumentByIndex(methodConfig, i) == null + && hasArgumentConfigProps(configProperties, methodConfig.getName(), i)) { ArgumentConfig argumentConfig = new ArgumentConfig(); argumentConfig.setIndex(i); @@ -372,22 +373,24 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { List methodConfigs = this.getMethods(); if (methodConfigs != null && methodConfigs.size() > 0) { // whether ignore invalid method config - Object ignoreInvalidMethodConfigVal = getEnvironment().getConfiguration() + Object ignoreInvalidMethodConfigVal = getEnvironment() + .getConfiguration() .getProperty(ConfigKeys.DUBBO_CONFIG_IGNORE_INVALID_METHOD_CONFIG, "false"); boolean ignoreInvalidMethodConfig = Boolean.parseBoolean(ignoreInvalidMethodConfigVal.toString()); Class finalInterfaceClass = interfaceClass; - List validMethodConfigs = methodConfigs.stream().filter(methodConfig -> { - methodConfig.setParentPrefix(preferredPrefix); - methodConfig.setScopeModel(getScopeModel()); - methodConfig.refresh(); - // verify method config - return verifyMethodConfig(methodConfig, finalInterfaceClass, ignoreInvalidMethodConfig); - }).collect(Collectors.toList()); + List validMethodConfigs = methodConfigs.stream() + .filter(methodConfig -> { + methodConfig.setParentPrefix(preferredPrefix); + methodConfig.setScopeModel(getScopeModel()); + methodConfig.refresh(); + // verify method config + return verifyMethodConfig(methodConfig, finalInterfaceClass, ignoreInvalidMethodConfig); + }) + .collect(Collectors.toList()); this.setMethods(validMethodConfigs); } } - } /** @@ -400,12 +403,12 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { return false; } - protected boolean verifyMethodConfig(MethodConfig methodConfig, Class interfaceClass, boolean ignoreInvalidMethodConfig) { + protected boolean verifyMethodConfig( + MethodConfig methodConfig, Class interfaceClass, boolean ignoreInvalidMethodConfig) { String methodName = methodConfig.getName(); if (StringUtils.isEmpty(methodName)) { - String msg = " name attribute is required! Please check: " + - "" + - ""; + String msg = " name attribute is required! Please check: " + "" + ""; if (ignoreInvalidMethodConfig) { logger.warn(CONFIG_NO_METHOD_FOUND, "", "", msg); return false; @@ -414,10 +417,11 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { } } - boolean hasMethod = Arrays.stream(interfaceClass.getMethods()).anyMatch(method -> method.getName().equals(methodName)); + boolean hasMethod = Arrays.stream(interfaceClass.getMethods()) + .anyMatch(method -> method.getName().equals(methodName)); if (!hasMethod) { - String msg = "Found invalid method config, the interface " + interfaceClass.getName() + " not found method \"" - + methodName + "\" : [" + methodConfig + "]"; + String msg = "Found invalid method config, the interface " + interfaceClass.getName() + + " not found method \"" + methodName + "\" : [" + methodConfig + "]"; if (ignoreInvalidMethodConfig) { logger.warn(CONFIG_NO_METHOD_FOUND, "", "", msg); return false; @@ -478,24 +482,25 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { private void verifyStubAndLocal(String className, String label, Class interfaceClass) { if (ConfigUtils.isNotEmpty(className)) { - Class localClass = ConfigUtils.isDefault(className) ? - ReflectUtils.forName(interfaceClass.getName() + label) : ReflectUtils.forName(className); + Class localClass = ConfigUtils.isDefault(className) + ? ReflectUtils.forName(interfaceClass.getName() + label) + : ReflectUtils.forName(className); verify(interfaceClass, localClass); } } private void verify(Class interfaceClass, Class localClass) { if (!interfaceClass.isAssignableFrom(localClass)) { - throw new IllegalStateException("The local implementation class " + localClass.getName() + - " not implement interface " + interfaceClass.getName()); + throw new IllegalStateException("The local implementation class " + localClass.getName() + + " not implement interface " + interfaceClass.getName()); } try { - //Check if the localClass a constructor with parameter whose type is interfaceClass + // Check if the localClass a constructor with parameter whose type is interfaceClass ReflectUtils.findConstructor(localClass, interfaceClass); } catch (NoSuchMethodException e) { - throw new IllegalStateException("No such constructor \"public " + localClass.getSimpleName() + - "(" + interfaceClass.getName() + ")\" in local implementation class " + localClass.getName()); + throw new IllegalStateException("No such constructor \"public " + localClass.getSimpleName() + "(" + + interfaceClass.getName() + ")\" in local implementation class " + localClass.getName()); } } @@ -522,7 +527,6 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { }); setRegistries(tmpRegistries); } - } protected boolean notHasSelfRegistryProperty() { @@ -862,7 +866,8 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { if (metadataReportConfig != null) { return metadataReportConfig; } - Collection metadataReportConfigs = getConfigManager().getMetadataConfigs(); + Collection metadataReportConfigs = + getConfigManager().getMetadataConfigs(); if (CollectionUtils.isNotEmpty(metadataReportConfigs)) { return metadataReportConfigs.iterator().next(); } @@ -917,11 +922,15 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { } public String getGroup(AbstractInterfaceConfig interfaceConfig) { - return StringUtils.isEmpty(getGroup()) ? (interfaceConfig != null ? interfaceConfig.getGroup() : getGroup()) : getGroup(); + return StringUtils.isEmpty(getGroup()) + ? (interfaceConfig != null ? interfaceConfig.getGroup() : getGroup()) + : getGroup(); } public String getVersion(AbstractInterfaceConfig interfaceConfig) { - return StringUtils.isEmpty(getVersion()) ? (interfaceConfig != null ? interfaceConfig.getVersion() : getVersion()) : getVersion(); + return StringUtils.isEmpty(getVersion()) + ? (interfaceConfig != null ? interfaceConfig.getVersion() : getVersion()) + : getVersion(); } public String getVersion() { @@ -956,5 +965,4 @@ public abstract class AbstractInterfaceConfig extends AbstractMethodConfig { public void setInterfaceClassLoader(ClassLoader interfaceClassLoader) { this.interfaceClassLoader = interfaceClassLoader; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractMethodConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractMethodConfig.java index 0e29d5a27b..08e71e9263 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractMethodConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractMethodConfig.java @@ -97,8 +97,7 @@ public abstract class AbstractMethodConfig extends AbstractConfig { */ protected Integer forks; - public AbstractMethodConfig() { - } + public AbstractMethodConfig() {} public AbstractMethodConfig(ModuleModel moduleModel) { super(moduleModel); @@ -119,7 +118,8 @@ public abstract class AbstractMethodConfig extends AbstractConfig { @Override protected void checkScopeModel(ScopeModel scopeModel) { if (!(scopeModel instanceof ModuleModel)) { - throw new IllegalArgumentException("Invalid scope model, expect to be a ModuleModel but got: " + scopeModel); + throw new IllegalArgumentException( + "Invalid scope model, expect to be a ModuleModel but got: " + scopeModel); } } @@ -240,5 +240,4 @@ public abstract class AbstractMethodConfig extends AbstractConfig { public void setParameters(Map parameters) { this.parameters = parameters; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java index 058f1d1622..cf07233b3f 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractReferenceConfig.java @@ -76,9 +76,8 @@ public abstract class AbstractReferenceConfig extends AbstractInterfaceConfig { /** * Whether to support event in stub. */ - //TODO solve merge problem - protected Boolean stubevent;//= Constants.DEFAULT_STUB_EVENT; - + // TODO solve merge problem + protected Boolean stubevent; // = Constants.DEFAULT_STUB_EVENT; /** * declares which app or service this interface belongs to @@ -120,8 +119,7 @@ public abstract class AbstractReferenceConfig extends AbstractInterfaceConfig { */ protected String protocol; - public AbstractReferenceConfig() { - } + public AbstractReferenceConfig() {} public AbstractReferenceConfig(ModuleModel moduleModel) { super(moduleModel); @@ -271,7 +269,6 @@ public abstract class AbstractReferenceConfig extends AbstractInterfaceConfig { this.sticky = sticky; } - @Parameter(key = PROVIDED_BY) public String getProvidedBy() { return providedBy; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java index 0034511483..bf30c66474 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/AbstractServiceConfig.java @@ -153,8 +153,7 @@ public abstract class AbstractServiceConfig extends AbstractInterfaceConfig { */ private Integer payload; - public AbstractServiceConfig() { - } + public AbstractServiceConfig() {} public AbstractServiceConfig(ModuleModel moduleModel) { super(moduleModel); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/ApplicationConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/ApplicationConfig.java index dde987ca1a..d143d9db25 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/ApplicationConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/ApplicationConfig.java @@ -297,8 +297,7 @@ public class ApplicationConfig extends AbstractConfig { */ private String executorManagementMode; - public ApplicationConfig() { - } + public ApplicationConfig() {} public ApplicationConfig(ApplicationModel applicationModel) { super(applicationModel); @@ -382,11 +381,13 @@ public class ApplicationConfig extends AbstractConfig { } public void setEnvironment(String environment) { - if (environment != null && !(DEVELOPMENT_ENVIRONMENT.equals(environment) - || TEST_ENVIRONMENT.equals(environment) - || PRODUCTION_ENVIRONMENT.equals(environment))) { + if (environment != null + && !(DEVELOPMENT_ENVIRONMENT.equals(environment) + || TEST_ENVIRONMENT.equals(environment) + || PRODUCTION_ENVIRONMENT.equals(environment))) { - throw new IllegalStateException(String.format("Unsupported environment: %s, only support %s/%s/%s, default is %s.", + throw new IllegalStateException(String.format( + "Unsupported environment: %s, only support %s/%s/%s, default is %s.", environment, DEVELOPMENT_ENVIRONMENT, TEST_ENVIRONMENT, @@ -802,8 +803,9 @@ public class ApplicationConfig extends AbstractConfig { if (StringUtils.isEmpty(getName())) { String defaultName = DEFAULT_NAME_PREFIX + UUID.randomUUID(); this.setName(defaultName); - LOGGER.info("No application name was set, '" + defaultName + "' will be used as the default application name," + - " it's highly recommended to set a unique and customized name for it can be critical for some service governance features."); + LOGGER.info( + "No application name was set, '" + defaultName + "' will be used as the default application name," + + " it's highly recommended to set a unique and customized name for it can be critical for some service governance features."); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/ArgumentConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/ArgumentConfig.java index 74d906cf2e..399807126a 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/ArgumentConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/ArgumentConfig.java @@ -45,8 +45,7 @@ public class ArgumentConfig implements Serializable { */ private Boolean callback; - public ArgumentConfig() { - } + public ArgumentConfig() {} public ArgumentConfig(Argument argument) { this.index = argument.index(); @@ -79,5 +78,4 @@ public class ArgumentConfig implements Serializable { public Boolean isCallback() { return callback; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/CommonConfigPostProcessor.java b/dubbo-common/src/main/java/org/apache/dubbo/config/CommonConfigPostProcessor.java index fff2a59727..f3a7e309b7 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/CommonConfigPostProcessor.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/CommonConfigPostProcessor.java @@ -22,15 +22,10 @@ import org.apache.dubbo.common.extension.SPI; /** * it will be call when reference or service config refresh */ - @SPI(scope = ExtensionScope.MODULE) public interface CommonConfigPostProcessor { - default void postProcessReferConfig(ReferenceConfigBase referenceConfig) { + default void postProcessReferConfig(ReferenceConfigBase referenceConfig) {} - } - - default void postProcessServiceConfig(ServiceConfigBase serviceConfig) { - - } + default void postProcessServiceConfig(ServiceConfigBase serviceConfig) {} } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java index eca4322be5..e854ef0d51 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/ConfigCenterConfig.java @@ -134,8 +134,7 @@ public class ConfigCenterConfig extends AbstractConfig { */ private Map appExternalConfiguration; - public ConfigCenterConfig() { - } + public ConfigCenterConfig() {} public ConfigCenterConfig(ApplicationModel applicationModel) { super(applicationModel); @@ -354,5 +353,4 @@ public class ConfigCenterConfig extends AbstractConfig { this.parameters.putAll(parameters); } } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/ConfigKeys.java b/dubbo-common/src/main/java/org/apache/dubbo/config/ConfigKeys.java index 4e3297bfbb..a3f20e0dc7 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/ConfigKeys.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/ConfigKeys.java @@ -47,5 +47,4 @@ public interface ConfigKeys { * Ignore duplicated interface (service/reference) config. Default value is false. */ String DUBBO_CONFIG_IGNORE_DUPLICATED_INTERFACE = "dubbo.config.ignore-duplicated-interface"; - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/Constants.java b/dubbo-common/src/main/java/org/apache/dubbo/config/Constants.java index d07ff02b79..10a7fc38ca 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/Constants.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/Constants.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP_COMPATIBLE; @@ -90,12 +89,10 @@ public interface Constants { String MULTICAST = "multicast"; - String DUBBO_IP_TO_REGISTRY = "DUBBO_IP_TO_REGISTRY"; String DUBBO_PORT_TO_REGISTRY = "DUBBO_PORT_TO_REGISTRY"; - String DUBBO_PORT_TO_BIND = "DUBBO_PORT_TO_BIND"; String SCOPE_NONE = "none"; @@ -124,14 +121,11 @@ public interface Constants { String ON_THROW_INSTANCE_ATTRIBUTE_KEY = "onthrow-instance"; - // FIXME: is this still useful? String SHUTDOWN_TIMEOUT_KEY = "shutdown.timeout"; - String PROTOCOLS_SUFFIX = "dubbo.protocols."; - String REGISTRIES_SUFFIX = "dubbo.registries."; String ZOOKEEPER_PROTOCOL = "zookeeper"; @@ -140,8 +134,14 @@ public interface Constants { String MULTI_SERIALIZATION_KEY = "serialize.multiple"; - String[] DOT_COMPATIBLE_KEYS = new String[]{QOS_ENABLE_COMPATIBLE, QOS_HOST_COMPATIBLE, QOS_PORT_COMPATIBLE, - ACCEPT_FOREIGN_IP_COMPATIBLE, ACCEPT_FOREIGN_IP_WHITELIST_COMPATIBLE, REGISTRY_TYPE_KEY}; + String[] DOT_COMPATIBLE_KEYS = new String[] { + QOS_ENABLE_COMPATIBLE, + QOS_HOST_COMPATIBLE, + QOS_PORT_COMPATIBLE, + ACCEPT_FOREIGN_IP_COMPATIBLE, + ACCEPT_FOREIGN_IP_WHITELIST_COMPATIBLE, + REGISTRY_TYPE_KEY + }; String IGNORE_CHECK_KEYS = "ignoreCheckKeys"; @@ -151,9 +151,9 @@ public interface Constants { String CLIENT_THREAD_POOL_NAME = "DubboClientHandler"; - String REST_PROTOCOL="rest"; + String REST_PROTOCOL = "rest"; - String DEFAULT_NATIVE_COMPILER="jdk"; + String DEFAULT_NATIVE_COMPILER = "jdk"; - String DEFAULT_NATIVE_PROXY="jdk"; + String DEFAULT_NATIVE_PROXY = "jdk"; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/ConsumerConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/ConsumerConfig.java index 10faac7015..b34ee3c140 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/ConsumerConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/ConsumerConfig.java @@ -85,9 +85,7 @@ public class ConsumerConfig extends AbstractReferenceConfig { */ private Boolean meshEnable; - - public ConsumerConfig() { - } + public ConsumerConfig() {} public ConsumerConfig(ModuleModel moduleModel) { super(moduleModel); @@ -97,8 +95,7 @@ public class ConsumerConfig extends AbstractReferenceConfig { public void setTimeout(Integer timeout) { super.setTimeout(timeout); String rmiTimeout = System.getProperty("sun.rmi.transport.tcp.responseTimeout"); - if (timeout != null && timeout > 0 - && (StringUtils.isEmpty(rmiTimeout))) { + if (timeout != null && timeout > 0 && (StringUtils.isEmpty(rmiTimeout))) { System.setProperty("sun.rmi.transport.tcp.responseTimeout", String.valueOf(timeout)); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/MetadataReportConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/MetadataReportConfig.java index 0e7d505272..b36bf2dcc4 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/MetadataReportConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/MetadataReportConfig.java @@ -138,8 +138,7 @@ public class MetadataReportConfig extends AbstractConfig { */ private Boolean reportDefinition; - public MetadataReportConfig() { - } + public MetadataReportConfig() {} public MetadataReportConfig(ApplicationModel applicationModel) { super(applicationModel); @@ -170,9 +169,15 @@ public class MetadataReportConfig extends AbstractConfig { map.putAll(convert(map, null)); // put the protocol of URL as the "metadata" map.put(METADATA, isEmpty(url.getProtocol()) ? map.get(PROTOCOL_KEY) : url.getProtocol()); - return new ServiceConfigURL(METADATA, StringUtils.isBlank(url.getUsername()) ? this.getUsername() : url.getUsername(), - StringUtils.isBlank(url.getPassword()) ? this.getPassword() : url.getPassword(), url.getHost(), - url.getPort(), url.getPath(), map).setScopeModel(getScopeModel()); + return new ServiceConfigURL( + METADATA, + StringUtils.isBlank(url.getUsername()) ? this.getUsername() : url.getUsername(), + StringUtils.isBlank(url.getPassword()) ? this.getPassword() : url.getPassword(), + url.getHost(), + url.getPort(), + url.getPath(), + map) + .setScopeModel(getScopeModel()); } public String getProtocol() { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/MethodConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/MethodConfig.java index 914002e1a4..000b447cac 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/MethodConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/MethodConfig.java @@ -128,6 +128,7 @@ public class MethodConfig extends AbstractMethodConfig { * These properties come from MethodConfig's parent Config module, they will neither be collected directly from xml or API nor be delivered to url */ private String service; + private String serviceId; /** @@ -135,9 +136,7 @@ public class MethodConfig extends AbstractMethodConfig { */ private String parentPrefix; - - public MethodConfig() { - } + public MethodConfig() {} public MethodConfig(ModuleModel moduleModel) { super(moduleModel); @@ -237,14 +236,13 @@ public class MethodConfig extends AbstractMethodConfig { if (argument.getIndex() != null && argument.getIndex() >= 0) { String prefix = argument.getIndex() + "."; Environment environment = getScopeModel().modelEnvironment(); - List methods = MethodUtils.getMethods(argument.getClass(), - method -> method.getDeclaringClass() != Object.class); + List methods = + MethodUtils.getMethods(argument.getClass(), method -> method.getDeclaringClass() != Object.class); for (java.lang.reflect.Method method : methods) { if (MethodUtils.isSetter(method)) { String propertyName = extractPropertyName(method.getName()); // ignore attributes: 'index' / 'type' - if (StringUtils.isEquals(propertyName, "index") || - StringUtils.isEquals(propertyName, "type")) { + if (StringUtils.isEquals(propertyName, "index") || StringUtils.isEquals(propertyName, "type")) { continue; } // convert camelCase/snake_case to kebab-case @@ -252,29 +250,35 @@ public class MethodConfig extends AbstractMethodConfig { try { String value = StringUtils.trim(subPropsConfiguration.getString(kebabPropertyName)); - if (StringUtils.hasText(value) && ClassUtils.isTypeMatch(method.getParameterTypes()[0], value)) { + if (StringUtils.hasText(value) + && ClassUtils.isTypeMatch(method.getParameterTypes()[0], value)) { value = environment.resolvePlaceholders(value); - method.invoke(argument, ClassUtils.convertPrimitive(ScopeModelUtil.getFrameworkModel(getScopeModel()), method.getParameterTypes()[0], value)); + method.invoke( + argument, + ClassUtils.convertPrimitive( + ScopeModelUtil.getFrameworkModel(getScopeModel()), + method.getParameterTypes()[0], + value)); } } catch (Exception e) { - logger.info("Failed to override the property " + method.getName() + " in " + - this.getClass().getSimpleName() + - ", please make sure every property has getter/setter method provided."); + logger.info("Failed to override the property " + method.getName() + " in " + + this.getClass().getSimpleName() + + ", please make sure every property has getter/setter method provided."); } } } } } - public AsyncMethodInfo convertMethodConfig2AsyncInfo() { if ((getOninvoke() == null && getOnreturn() == null && getOnthrow() == null)) { return null; } - //check config conflict + // check config conflict if (Boolean.FALSE.equals(isReturn()) && (getOnreturn() != null || getOnthrow() != null)) { - throw new IllegalStateException("method config error : return attribute must be set true when on-return or on-throw has been set."); + throw new IllegalStateException( + "method config error : return attribute must be set true when on-return or on-throw has been set."); } AsyncMethodInfo asyncMethodInfo = new AsyncMethodInfo(); @@ -339,9 +343,9 @@ public class MethodConfig extends AbstractMethodConfig { public void setName(String name) { this.name = name; // FIXME, add id strategy in ConfigManager -// if (StringUtils.isEmpty(id)) { -// id = name; -// } + // if (StringUtils.isEmpty(id)) { + // id = name; + // } } public Integer getStat() { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/MetricsConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/MetricsConfig.java index 7bf36399b1..9588bf70f2 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/MetricsConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/MetricsConfig.java @@ -133,8 +133,7 @@ public class MetricsConfig extends AbstractConfig { */ private String rpcLevel; - public MetricsConfig() { - } + public MetricsConfig() {} public MetricsConfig(ApplicationModel applicationModel) { super(applicationModel); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/ModuleConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/ModuleConfig.java index c88a52bce3..95a60249d1 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/ModuleConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/ModuleConfig.java @@ -128,7 +128,8 @@ public class ModuleConfig extends AbstractConfig { @Override protected void checkScopeModel(ScopeModel scopeModel) { if (!(scopeModel instanceof ModuleModel)) { - throw new IllegalArgumentException("Invalid scope model, expect to be a ModuleModel but got: " + scopeModel); + throw new IllegalArgumentException( + "Invalid scope model, expect to be a ModuleModel but got: " + scopeModel); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/MonitorConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/MonitorConfig.java index bebfc716c1..b5dd24dcb7 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/MonitorConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/MonitorConfig.java @@ -73,8 +73,7 @@ public class MonitorConfig extends AbstractConfig { */ private Map parameters; - public MonitorConfig() { - } + public MonitorConfig() {} public MonitorConfig(ApplicationModel applicationModel) { super(applicationModel); @@ -162,5 +161,4 @@ public class MonitorConfig extends AbstractConfig { public boolean isValid() { return StringUtils.isNotEmpty(address) || RegistryConstants.REGISTRY_PROTOCOL.equals(protocol); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/ProtocolConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/ProtocolConfig.java index d88d5e3ed9..eb358a79f7 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/ProtocolConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/ProtocolConfig.java @@ -236,8 +236,7 @@ public class ProtocolConfig extends AbstractConfig { */ private String jsonCheckLevel; - public ProtocolConfig() { - } + public ProtocolConfig() {} public ProtocolConfig(ApplicationModel applicationModel) { super(applicationModel); @@ -625,20 +624,20 @@ public class ProtocolConfig extends AbstractConfig { try { Map protocolConfigMap = CollectionUtils.objToMap(sourceConfig); for (Field targetField : targetFields) { - Optional.ofNullable(protocolConfigMap.get(targetField.getName())).ifPresent(value -> { - try { - targetField.setAccessible(true); - if (targetField.get(this) == null) { - targetField.set(this, value); - } - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - }); + Optional.ofNullable(protocolConfigMap.get(targetField.getName())) + .ifPresent(value -> { + try { + targetField.setAccessible(true); + if (targetField.get(this) == null) { + targetField.set(this, value); + } + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + }); } } catch (Exception e) { logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", "merge protocol config fail, error: ", e); } } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/ProviderConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/ProviderConfig.java index 1cbf3a5d01..1d63268e56 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/ProviderConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/ProviderConfig.java @@ -171,8 +171,7 @@ public class ProviderConfig extends AbstractServiceConfig { */ private Boolean exportBackground; - public ProviderConfig() { - } + public ProviderConfig() {} public ProviderConfig(ModuleModel moduleModel) { super(moduleModel); @@ -443,5 +442,4 @@ public class ProviderConfig extends AbstractServiceConfig { public void setExportBackground(Boolean exportBackground) { this.exportBackground = exportBackground; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/ReferenceConfigBase.java b/dubbo-common/src/main/java/org/apache/dubbo/config/ReferenceConfigBase.java index fab4930e2a..a168a8f53d 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/ReferenceConfigBase.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/ReferenceConfigBase.java @@ -133,8 +133,8 @@ public abstract class ReferenceConfigBase extends AbstractReferenceConfig { super.preProcessRefresh(); if (consumer == null) { consumer = getModuleConfigManager() - .getDefaultConsumer() - .orElseThrow(() -> new IllegalStateException("Default consumer is not initialized")); + .getDefaultConsumer() + .orElseThrow(() -> new IllegalStateException("Default consumer is not initialized")); } // try set properties from `dubbo.reference` if not set in current config refreshWithPrefixes(super.getPrefixes(), ConfigMode.OVERRIDE_IF_ABSENT); @@ -227,8 +227,9 @@ public abstract class ReferenceConfigBase extends AbstractReferenceConfig { public static Class determineInterfaceClass(String generic, String interfaceName, ClassLoader classLoader) { if (ProtocolUtils.isGeneric(generic)) { - return Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isGenericServiceClassLoaded() ? - Dubbo2CompactUtils.getGenericServiceClass() : GenericService.class; + return Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isGenericServiceClassLoaded() + ? Dubbo2CompactUtils.getGenericServiceClass() + : GenericService.class; } try { if (StringUtils.isNotEmpty(interfaceName)) { @@ -259,12 +260,15 @@ public abstract class ReferenceConfigBase extends AbstractReferenceConfig { } else { if (interfaceClass != null) { try { - if (!interfaceClass.equals(Class.forName(interfaceClass.getName(), false, getInterfaceClassLoader()))) { - // interfaceClass is not visible from origin classloader, override the classloader from interfaceClass into referenceConfig + if (!interfaceClass.equals( + Class.forName(interfaceClass.getName(), false, getInterfaceClassLoader()))) { + // interfaceClass is not visible from origin classloader, override the classloader from + // interfaceClass into referenceConfig setInterfaceClassLoader(interfaceClass.getClassLoader()); } } catch (ClassNotFoundException e) { - // class not found from origin classloader, override the classloader from interfaceClass into referenceConfig + // class not found from origin classloader, override the classloader from interfaceClass into + // referenceConfig setInterfaceClassLoader(interfaceClass.getClassLoader()); } } @@ -328,9 +332,18 @@ public abstract class ReferenceConfigBase extends AbstractReferenceConfig { url = resolve; if (logger.isWarnEnabled()) { if (resolveFile != null) { - logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "Using default dubbo resolve file " + resolveFile + " replace " + interfaceName + "" + resolve + " to p2p invoke remote service."); + logger.warn( + COMMON_UNEXPECTED_EXCEPTION, + "", + "", + "Using default dubbo resolve file " + resolveFile + " replace " + interfaceName + "" + + resolve + " to p2p invoke remote service."); } else { - logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "Using -D" + interfaceName + "=" + resolve + " to p2p invoke remote service."); + logger.warn( + COMMON_UNEXPECTED_EXCEPTION, + "", + "", + "Using -D" + interfaceName + "=" + resolve + " to p2p invoke remote service."); } } } @@ -352,7 +365,9 @@ public abstract class ReferenceConfigBase extends AbstractReferenceConfig { @Override public String getVersion() { - return StringUtils.isEmpty(this.version) ? (consumer != null ? consumer.getVersion() : this.version) : this.version; + return StringUtils.isEmpty(this.version) + ? (consumer != null ? consumer.getVersion() : this.version) + : this.version; } @Override @@ -383,5 +398,4 @@ public abstract class ReferenceConfigBase extends AbstractReferenceConfig { public void destroy() { getModuleConfigManager().removeConfig(this); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/RegistryConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/RegistryConfig.java index e264a425c4..933d0c3861 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/RegistryConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/RegistryConfig.java @@ -214,8 +214,7 @@ public class RegistryConfig extends AbstractConfig { this.secure = secure; } - public RegistryConfig() { - } + public RegistryConfig() {} public RegistryConfig(ApplicationModel applicationModel) { super(applicationModel); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/ServiceConfigBase.java b/dubbo-common/src/main/java/org/apache/dubbo/config/ServiceConfigBase.java index 228944dde6..d527618b6d 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/ServiceConfigBase.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/ServiceConfigBase.java @@ -144,14 +144,15 @@ public abstract class ServiceConfigBase extends AbstractServiceConfig { } if (!interfaceClass.isInstance(ref)) { throw new IllegalStateException("The class " - + getClassDesc(ref.getClass()) + " unimplemented interface " - + getClassDesc(interfaceClass) + "!"); + + getClassDesc(ref.getClass()) + " unimplemented interface " + + getClassDesc(interfaceClass) + "!"); } } private String getClassDesc(Class clazz) { ClassLoader classLoader = clazz.getClassLoader(); - return clazz.getName() + "[classloader=" + classLoader.getClass().getName() + "@" + classLoader.hashCode() + "]"; + return clazz.getName() + "[classloader=" + classLoader.getClass().getName() + "@" + classLoader.hashCode() + + "]"; } public Optional getContextPath(ProtocolConfig protocolConfig) { @@ -172,8 +173,8 @@ public abstract class ServiceConfigBase extends AbstractServiceConfig { convertProviderIdToProvider(); if (provider == null) { provider = getModuleConfigManager() - .getDefaultProvider() - .orElseThrow(() -> new IllegalStateException("Default provider is not initialized")); + .getDefaultProvider() + .orElseThrow(() -> new IllegalStateException("Default provider is not initialized")); } // try set properties from `dubbo.service` if not set in current config refreshWithPrefixes(super.getPrefixes(), ConfigMode.OVERRIDE_IF_ABSENT); @@ -227,8 +228,9 @@ public abstract class ServiceConfigBase extends AbstractServiceConfig { protected void convertProviderIdToProvider() { if (provider == null && StringUtils.hasText(providerIds)) { - provider = getModuleConfigManager().getProvider(providerIds) - .orElseThrow(() -> new IllegalStateException("Provider config not found: " + providerIds)); + provider = getModuleConfigManager() + .getProvider(providerIds) + .orElseThrow(() -> new IllegalStateException("Provider config not found: " + providerIds)); } } @@ -266,8 +268,8 @@ public abstract class ServiceConfigBase extends AbstractServiceConfig { } try { if (StringUtils.isNotEmpty(interfaceName)) { - this.interfaceClass = Class.forName(interfaceName, true, Thread.currentThread() - .getContextClassLoader()); + this.interfaceClass = Class.forName( + interfaceName, true, Thread.currentThread().getContextClassLoader()); } } catch (ClassNotFoundException t) { throw new IllegalStateException(t.getMessage(), t); @@ -391,7 +393,9 @@ public abstract class ServiceConfigBase extends AbstractServiceConfig { @Override public String getVersion() { - return StringUtils.isEmpty(this.version) ? (provider != null ? provider.getVersion() : this.version) : this.version; + return StringUtils.isEmpty(this.version) + ? (provider != null ? provider.getVersion() : this.version) + : this.version; } @Override diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/SslConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/SslConfig.java index 61d8d734c0..3491c6af35 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/SslConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/SslConfig.java @@ -139,8 +139,7 @@ public class SslConfig extends AbstractConfig { */ private String oidcTokenPath; - public SslConfig() { - } + public SslConfig() {} public SslConfig(ApplicationModel applicationModel) { super(applicationModel); @@ -253,7 +252,8 @@ public class SslConfig extends AbstractConfig { @Transient public InputStream getServerKeyCertChainPathStream() throws IOException { if (serverKeyCertChainPath != null) { - serverKeyCertChainPathStream = IOUtils.getURL(serverKeyCertChainPath).openStream(); + serverKeyCertChainPathStream = + IOUtils.getURL(serverKeyCertChainPath).openStream(); } return serverKeyCertChainPathStream; } @@ -277,7 +277,8 @@ public class SslConfig extends AbstractConfig { @Transient public InputStream getServerTrustCertCollectionPathStream() throws IOException { if (serverTrustCertCollectionPath != null) { - serverTrustCertCollectionPathStream = IOUtils.getURL(serverTrustCertCollectionPath).openStream(); + serverTrustCertCollectionPathStream = + IOUtils.getURL(serverTrustCertCollectionPath).openStream(); } return serverTrustCertCollectionPathStream; } @@ -289,7 +290,8 @@ public class SslConfig extends AbstractConfig { @Transient public InputStream getClientKeyCertChainPathStream() throws IOException { if (clientKeyCertChainPath != null) { - clientKeyCertChainPathStream = IOUtils.getURL(clientKeyCertChainPath).openStream(); + clientKeyCertChainPathStream = + IOUtils.getURL(clientKeyCertChainPath).openStream(); } return clientKeyCertChainPathStream; } @@ -313,7 +315,8 @@ public class SslConfig extends AbstractConfig { @Transient public InputStream getClientTrustCertCollectionPathStream() throws IOException { if (clientTrustCertCollectionPath != null) { - clientTrustCertCollectionPathStream = IOUtils.getURL(clientTrustCertCollectionPath).openStream(); + clientTrustCertCollectionPathStream = + IOUtils.getURL(clientTrustCertCollectionPath).openStream(); } return clientTrustCertCollectionPathStream; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/TracingConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/TracingConfig.java index f3170991ca..b19579c489 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/TracingConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/TracingConfig.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; import org.apache.dubbo.config.nested.BaggageConfig; @@ -60,8 +59,7 @@ public class TracingConfig extends AbstractConfig { @Nested private ExporterConfig tracingExporter = new ExporterConfig(); - public TracingConfig() { - } + public TracingConfig() {} public TracingConfig(ApplicationModel applicationModel) { super(applicationModel); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/TripleConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/TripleConfig.java index e5d80e4881..a10d909fbc 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/TripleConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/TripleConfig.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; import java.io.Serializable; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/Argument.java b/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/Argument.java index 6a0da8ea8d..238cbbc809 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/Argument.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/Argument.java @@ -33,12 +33,12 @@ import java.lang.annotation.Target; @Target({ElementType.ANNOTATION_TYPE}) @Inherited public @interface Argument { - //argument: index -1 represents not set + // argument: index -1 represents not set int index() default -1; - //argument type + // argument type String type() default ""; - //callback interface + // callback interface boolean callback() default false; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/Method.java b/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/Method.java index eb4bc74abf..94f3e78d55 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/Method.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/annotation/Method.java @@ -73,5 +73,4 @@ public @interface Method { * Customized parameter key-value pair, for example: {key1, value1, key2, value2} or {"key1=value1", "key2=value2"} */ String[] parameters() default {}; - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/context/AbstractConfigManager.java b/dubbo-common/src/main/java/org/apache/dubbo/config/context/AbstractConfigManager.java index 7ddbb73253..5a15b14ac2 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/context/AbstractConfigManager.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/context/AbstractConfigManager.java @@ -69,7 +69,8 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { private static final String CONFIG_NAME_READ_METHOD = "getName"; - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractConfigManager.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(AbstractConfigManager.class); private static final Set> uniqueConfigTypes = new ConcurrentHashSet<>(); final Map> configsCache = new ConcurrentHashMap<>(); @@ -100,7 +101,8 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { uniqueConfigTypes.add(ModuleConfig.class); } - public AbstractConfigManager(ScopeModel scopeModel, Collection> supportedConfigTypes) { + public AbstractConfigManager( + ScopeModel scopeModel, Collection> supportedConfigTypes) { this.scopeModel = scopeModel; this.applicationModel = ScopeModelUtil.getApplicationModel(scopeModel); this.supportedConfigTypes = supportedConfigTypes; @@ -121,14 +123,15 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { this.configMode = ConfigMode.valueOf(configModeStr.toUpperCase()); } } catch (Exception e) { - String msg = "Illegal '" + ConfigKeys.DUBBO_CONFIG_MODE + "' config value [" + configModeStr + "], available values " + Arrays.toString(ConfigMode.values()); + String msg = "Illegal '" + ConfigKeys.DUBBO_CONFIG_MODE + "' config value [" + configModeStr + + "], available values " + Arrays.toString(ConfigMode.values()); logger.error(COMMON_PROPERTY_TYPE_MISMATCH, "", "", msg, e); throw new IllegalArgumentException(msg, e); } // dubbo.config.ignore-duplicated-interface - String ignoreDuplicatedInterfaceStr = (String) configuration - .getProperty(ConfigKeys.DUBBO_CONFIG_IGNORE_DUPLICATED_INTERFACE); + String ignoreDuplicatedInterfaceStr = + (String) configuration.getProperty(ConfigKeys.DUBBO_CONFIG_IGNORE_DUPLICATED_INTERFACE); if (ignoreDuplicatedInterfaceStr != null) { this.ignoreDuplicatedInterface = Boolean.parseBoolean(ignoreDuplicatedInterfaceStr); } @@ -158,7 +161,8 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { config.setScopeModel(scopeModel); } - Map configsMap = configsCache.computeIfAbsent(getTagName(config.getClass()), type -> new ConcurrentHashMap<>()); + Map configsMap = + configsCache.computeIfAbsent(getTagName(config.getClass()), type -> new ConcurrentHashMap<>()); // fast check duplicated equivalent config before write lock if (!(config instanceof ReferenceConfigBase || config instanceof ServiceConfigBase)) { @@ -192,8 +196,7 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { * @return the existing equivalent config or the new adding config * @throws IllegalStateException */ - private C addIfAbsent(C config, Map configsMap) - throws IllegalStateException { + private C addIfAbsent(C config, Map configsMap) throws IllegalStateException { if (config == null || configsMap == null) { return config; @@ -216,9 +219,14 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { C existedConfig = configsMap.get(key); if (existedConfig != null && !isEquals(existedConfig, config)) { String type = config.getClass().getSimpleName(); - logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", String.format("Duplicate %s found, there already has one default %s or more than two %ss have the same id, " + - "you can try to give each %s a different id, override previous config with later config. id: %s, prev: %s, later: %s", - type, type, type, type, key, existedConfig, config)); + logger.warn( + COMMON_UNEXPECTED_EXCEPTION, + "", + "", + String.format( + "Duplicate %s found, there already has one default %s or more than two %ss have the same id, " + + "you can try to give each %s a different id, override previous config with later config. id: %s, prev: %s, later: %s", + type, type, type, type, key, existedConfig, config)); } // override existed config if any @@ -249,11 +257,11 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { Map configsMap = getConfigsMap(configType); int size = configsMap.size(); if (size < 1) { -// throw new IllegalStateException("No such " + configType.getName() + " is found"); + // throw new IllegalStateException("No such " + configType.getName() + " is found"); return null; } else if (size > 1) { - throw new IllegalStateException("Expected single instance of " + configType + ", but found " + size + - " instances, please remove redundant configs. instances: " + configsMap.values()); + throw new IllegalStateException("Expected single instance of " + configType + ", but found " + size + + " instances, please remove redundant configs. instances: " + configsMap.values()); } return (C) configsMap.values().iterator().next(); } @@ -339,8 +347,8 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { .filter(cfg -> name.equals(getConfigName(cfg))) .collect(Collectors.toList()); if (list.size() > 1) { - throw new IllegalStateException("Found more than one config by name: " + name + - ", instances: " + list + ". Please remove redundant configs or get config by id."); + throw new IllegalStateException("Found more than one config by name: " + name + ", instances: " + list + + ". Please remove redundant configs or get config by id."); } else if (list.size() == 1) { return list.get(0); } @@ -364,9 +372,7 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { } // 2. find equal config - prevConfig = values.stream() - .filter(val -> isEquals(val, config)) - .findFirst(); + prevConfig = values.stream().filter(val -> isEquals(val, config)).findFirst(); return prevConfig; } @@ -394,7 +400,9 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { protected String generateConfigId(C config) { String tagName = getTagName(config.getClass()); - int idx = configIdIndexes.computeIfAbsent(tagName, clazz -> new AtomicInteger(0)).incrementAndGet(); + int idx = configIdIndexes + .computeIfAbsent(tagName, clazz -> new AtomicInteger(0)) + .incrementAndGet(); return tagName + "#" + idx; } @@ -408,8 +416,7 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { static List getDefaultConfigs(Map configsMap) { // find isDefault() == true - List list = configsMap.values() - .stream() + List list = configsMap.values().stream() .filter(c -> TRUE.equals(AbstractConfigManager.isDefaultConfig(c))) .collect(Collectors.toList()); if (list.size() > 0) { @@ -417,8 +424,7 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { } // find isDefault() == null - list = configsMap.values() - .stream() + list = configsMap.values().stream() .filter(c -> AbstractConfigManager.isDefaultConfig(c) == null) .collect(Collectors.toList()); return list; @@ -430,19 +436,25 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { if (configsMap.size() > 0 && isUniqueConfig(config)) { C oldOne = configsMap.values().iterator().next(); String configName = oldOne.getClass().getSimpleName(); - String msgPrefix = "Duplicate Configs found for " + configName + ", only one unique " + configName + - " is allowed for one application. previous: " + oldOne + ", later: " + config + ". According to config mode [" + configMode + "], "; + String msgPrefix = "Duplicate Configs found for " + configName + ", only one unique " + configName + + " is allowed for one application. previous: " + oldOne + ", later: " + config + + ". According to config mode [" + configMode + "], "; switch (configMode) { case STRICT: { if (!isEquals(oldOne, config)) { - throw new IllegalStateException(msgPrefix + "please remove redundant configs and keep only one."); + throw new IllegalStateException( + msgPrefix + "please remove redundant configs and keep only one."); } break; } case IGNORE: { // ignore later config if (logger.isWarnEnabled() && duplicatedConfigs.add(config)) { - logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", msgPrefix + "keep previous config and ignore later config"); + logger.warn( + COMMON_UNEXPECTED_EXCEPTION, + "", + "", + msgPrefix + "keep previous config and ignore later config"); } return Optional.of(oldOne); } @@ -450,7 +462,11 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { // clear previous config, add new config configsMap.clear(); if (logger.isWarnEnabled() && duplicatedConfigs.add(config)) { - logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", msgPrefix + "override previous config with later config"); + logger.warn( + COMMON_UNEXPECTED_EXCEPTION, + "", + "", + msgPrefix + "override previous config with later config"); } break; } @@ -458,7 +474,11 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { // override old one's properties with the new one oldOne.overrideWithConfig(config, true); if (logger.isWarnEnabled() && duplicatedConfigs.add(config)) { - logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", msgPrefix + "override previous config with later config"); + logger.warn( + COMMON_UNEXPECTED_EXCEPTION, + "", + "", + msgPrefix + "override previous config with later config"); } return Optional.of(oldOne); } @@ -466,7 +486,11 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { // override old one's properties with the new one oldOne.overrideWithConfig(config, false); if (logger.isWarnEnabled() && duplicatedConfigs.add(config)) { - logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", msgPrefix + "override previous config with later config"); + logger.warn( + COMMON_UNEXPECTED_EXCEPTION, + "", + "", + msgPrefix + "override previous config with later config"); } return Optional.of(oldOne); } @@ -490,7 +514,8 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { config = createConfig(cls, scopeModel); config.setId(id); } catch (Exception e) { - throw new IllegalStateException("create config instance failed, id: " + id + ", type:" + cls.getSimpleName()); + throw new IllegalStateException( + "create config instance failed, id: " + id + ", type:" + cls.getSimpleName()); } String key = null; @@ -507,7 +532,12 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { this.addConfig(config); tmpConfigs.add(config); } catch (Exception e) { - logger.error(COMMON_PROPERTY_TYPE_MISMATCH, "", "", "load config failed, id: " + id + ", type:" + cls.getSimpleName(), e); + logger.error( + COMMON_PROPERTY_TYPE_MISMATCH, + "", + "", + "load config failed, id: " + id + ", type:" + cls.getSimpleName(), + e); throw new IllegalStateException("load config failed, id: " + id + ", type:" + cls.getSimpleName()); } finally { if (addDefaultNameConfig && key != null) { @@ -527,7 +557,8 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { config = createConfig(cls, scopeModel); config.refresh(); } catch (Exception e) { - throw new IllegalStateException("create default config instance failed, type:" + cls.getSimpleName()); + throw new IllegalStateException( + "create default config instance failed, type:" + cls.getSimpleName()); } this.addConfig(config); @@ -538,7 +569,8 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { return tmpConfigs; } - private T createConfig(Class cls, ScopeModel scopeModel) throws ReflectiveOperationException { + private T createConfig(Class cls, ScopeModel scopeModel) + throws ReflectiveOperationException { T config = cls.getDeclaredConstructor().newInstance(); config.setScopeModel(scopeModel); return config; @@ -624,11 +656,11 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { * @return */ protected boolean isRequired(Class clazz) { - if (clazz == RegistryConfig.class || - clazz == MetadataReportConfig.class || - clazz == MonitorConfig.class || - clazz == MetricsConfig.class || - clazz == TracingConfig.class) { + if (clazz == RegistryConfig.class + || clazz == MetadataReportConfig.class + || clazz == MonitorConfig.class + || clazz == MetricsConfig.class + || clazz == TracingConfig.class) { return false; } return true; @@ -642,9 +674,7 @@ public abstract class AbstractConfigManager extends LifecycleAdapter { return this.getDefaultConfigs(clazz).isEmpty(); } - public void refreshAll() { - - } + public void refreshAll() {} /** * In some scenario, we may need to add and remove ServiceConfig or ReferenceConfig dynamically. diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/context/ConfigManager.java b/dubbo-common/src/main/java/org/apache/dubbo/config/context/ConfigManager.java index d8b0e58b20..58d7abf7cb 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/context/ConfigManager.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/context/ConfigManager.java @@ -58,12 +58,21 @@ public class ConfigManager extends AbstractConfigManager implements ApplicationE public static final String DUBBO_CONFIG_MODE = ConfigKeys.DUBBO_CONFIG_MODE; public ConfigManager(ApplicationModel applicationModel) { - super(applicationModel, Arrays.asList(ApplicationConfig.class, MonitorConfig.class, - MetricsConfig.class, SslConfig.class, ProtocolConfig.class, RegistryConfig.class, ConfigCenterConfig.class, - MetadataReportConfig.class, TracingConfig.class)); + super( + applicationModel, + Arrays.asList( + ApplicationConfig.class, + MonitorConfig.class, + MetricsConfig.class, + SslConfig.class, + ProtocolConfig.class, + RegistryConfig.class, + ConfigCenterConfig.class, + MetadataReportConfig.class, + TracingConfig.class)); } -// ApplicationConfig correlative methods + // ApplicationConfig correlative methods /** * Set application config @@ -133,7 +142,8 @@ public class ConfigManager extends AbstractConfigManager implements ApplicationE } public Optional> getDefaultConfigCenter() { - Collection defaults = getDefaultConfigs(getConfigsMap(getTagName(ConfigCenterConfig.class))); + Collection defaults = + getDefaultConfigs(getConfigsMap(getTagName(ConfigCenterConfig.class))); if (CollectionUtils.isEmpty(defaults)) { defaults = getConfigCenters(); } @@ -163,7 +173,8 @@ public class ConfigManager extends AbstractConfigManager implements ApplicationE } public Collection getDefaultMetadataConfigs() { - Collection defaults = getDefaultConfigs(getConfigsMap(getTagName(MetadataReportConfig.class))); + Collection defaults = + getDefaultConfigs(getConfigsMap(getTagName(MetadataReportConfig.class))); if (CollectionUtils.isEmpty(defaults)) { return getMetadataConfigs(); } @@ -250,7 +261,7 @@ public class ConfigManager extends AbstractConfigManager implements ApplicationE // load dubbo.metrics.xxx loadConfigsOfTypeFromProps(MetricsConfig.class); - //load dubbo.tracing.xxx + // load dubbo.tracing.xxx loadConfigsOfTypeFromProps(TracingConfig.class); // load multiple config types: @@ -264,7 +275,7 @@ public class ConfigManager extends AbstractConfigManager implements ApplicationE loadConfigsOfTypeFromProps(MetadataReportConfig.class); // config centers has bean loaded before starting config center - //loadConfigsOfTypeFromProps(ConfigCenterConfig.class); + // loadConfigsOfTypeFromProps(ConfigCenterConfig.class); refreshAll(); @@ -300,8 +311,8 @@ public class ConfigManager extends AbstractConfigManager implements ApplicationE } ProtocolConfig prevProtocol = protocolPortMap.get(port); if (prevProtocol != null) { - throw new IllegalStateException("Duplicated port used by protocol configs, port: " + port + - ", configs: " + Arrays.asList(prevProtocol, protocol)); + throw new IllegalStateException("Duplicated port used by protocol configs, port: " + port + + ", configs: " + Arrays.asList(prevProtocol, protocol)); } protocolPortMap.put(port, protocol); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/context/ConfigValidator.java b/dubbo-common/src/main/java/org/apache/dubbo/config/context/ConfigValidator.java index 7d20b1b658..ea6b5e6661 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/context/ConfigValidator.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/context/ConfigValidator.java @@ -21,5 +21,4 @@ import org.apache.dubbo.config.AbstractConfig; public interface ConfigValidator { void validate(AbstractConfig config); - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/context/ModuleConfigManager.java b/dubbo-common/src/main/java/org/apache/dubbo/config/context/ModuleConfigManager.java index 6bdb2b4d09..03e873bd5b 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/context/ModuleConfigManager.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/context/ModuleConfigManager.java @@ -63,7 +63,14 @@ public class ModuleConfigManager extends AbstractConfigManager implements Module private final ConfigManager applicationConfigManager; public ModuleConfigManager(ModuleModel moduleModel) { - super(moduleModel, Arrays.asList(ModuleConfig.class, ServiceConfigBase.class, ReferenceConfigBase.class, ProviderConfig.class, ConsumerConfig.class)); + super( + moduleModel, + Arrays.asList( + ModuleConfig.class, + ServiceConfigBase.class, + ReferenceConfigBase.class, + ProviderConfig.class, + ConsumerConfig.class)); applicationConfigManager = moduleModel.getApplicationModel().getApplicationConfigManager(); } @@ -190,7 +197,8 @@ public class ModuleConfigManager extends AbstractConfigManager implements Module @Override protected Optional findDuplicatedConfig(Map configsMap, C config) { // check duplicated configs - // special check service and reference config by unique service name, speed up the processing of large number of instances + // special check service and reference config by unique service name, speed up the processing of large number of + // instances if (config instanceof ReferenceConfigBase || config instanceof ServiceConfigBase) { C existedConfig = (C) findDuplicatedInterfaceConfig((AbstractInterfaceConfig) config); if (existedConfig != null) { @@ -228,7 +236,8 @@ public class ModuleConfigManager extends AbstractConfigManager implements Module uniqueServiceName = serviceConfig.getUniqueServiceName(); configCache = serviceConfigCache; } else { - throw new IllegalArgumentException("Illegal type of parameter 'config' : " + config.getClass().getName()); + throw new IllegalArgumentException( + "Illegal type of parameter 'config' : " + config.getClass().getName()); } AbstractInterfaceConfig prevConfig = configCache.putIfAbsent(uniqueServiceName, config); @@ -246,10 +255,10 @@ public class ModuleConfigManager extends AbstractConfigManager implements Module } String configType = config.getClass().getSimpleName(); - String msg = "Found multiple " + configType + "s with unique service name [" + - uniqueServiceName + "], previous: " + prevConfig + ", later: " + config + ". " + - "There can only be one instance of " + configType + " with the same triple (group, interface, version). " + - "If multiple instances are required for the same interface, please use a different group or version."; + String msg = "Found multiple " + configType + "s with unique service name [" + uniqueServiceName + + "], previous: " + prevConfig + ", later: " + config + ". " + "There can only be one instance of " + + configType + " with the same triple (group, interface, version). " + + "If multiple instances are required for the same interface, please use a different group or version."; if (logger.isWarnEnabled() && duplicatedConfigs.add(config)) { logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", msg); @@ -271,7 +280,8 @@ public class ModuleConfigManager extends AbstractConfigManager implements Module uniqueServiceName = serviceConfig.getUniqueServiceName(); configCache = serviceConfigCache; } else { - throw new IllegalArgumentException("Illegal type of parameter 'config' : " + config.getClass().getName()); + throw new IllegalArgumentException( + "Illegal type of parameter 'config' : " + config.getClass().getName()); } configCache.remove(uniqueServiceName, config); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/nested/BaggageConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/nested/BaggageConfig.java index cd6e1b9ccc..45bea909de 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/nested/BaggageConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/nested/BaggageConfig.java @@ -45,8 +45,7 @@ public class BaggageConfig implements Serializable { */ private List remoteFields = new ArrayList<>(); - public BaggageConfig() { - } + public BaggageConfig() {} public BaggageConfig(Boolean enabled) { this.enabled = enabled; @@ -95,8 +94,7 @@ public class BaggageConfig implements Serializable { */ private List fields = new ArrayList<>(); - public Correlation() { - } + public Correlation() {} public Correlation(boolean enabled) { this.enabled = enabled; @@ -122,6 +120,5 @@ public class BaggageConfig implements Serializable { public void setFields(List fields) { this.fields = fields; } - } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/nested/ExporterConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/nested/ExporterConfig.java index 7ad3aa5eb4..6edfc53204 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/nested/ExporterConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/nested/ExporterConfig.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config.nested; import org.apache.dubbo.config.support.Nested; @@ -74,8 +73,7 @@ public class ExporterConfig implements Serializable { */ private Duration readTimeout = Duration.ofSeconds(10); - public ZipkinConfig() { - } + public ZipkinConfig() {} public ZipkinConfig(String endpoint) { this.endpoint = endpoint; @@ -132,8 +130,7 @@ public class ExporterConfig implements Serializable { private Map headers = new HashMap<>(); - public OtlpConfig() { - } + public OtlpConfig() {} public OtlpConfig(String endpoint) { this.endpoint = endpoint; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/nested/HistogramConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/nested/HistogramConfig.java index a92ec10910..504faf03c8 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/nested/HistogramConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/nested/HistogramConfig.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config.nested; import java.io.Serializable; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/nested/PropagationConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/nested/PropagationConfig.java index 8d7dc391a4..c7ee0ba7dd 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/nested/PropagationConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/nested/PropagationConfig.java @@ -32,8 +32,7 @@ public class PropagationConfig implements Serializable { */ private String type = W3C; - public PropagationConfig() { - } + public PropagationConfig() {} public PropagationConfig(String type) { this.type = type; @@ -46,5 +45,4 @@ public class PropagationConfig implements Serializable { public void setType(String type) { this.type = type; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/nested/SamplingConfig.java b/dubbo-common/src/main/java/org/apache/dubbo/config/nested/SamplingConfig.java index e4f5ea024f..26dc0c2ea2 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/nested/SamplingConfig.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/nested/SamplingConfig.java @@ -28,8 +28,7 @@ public class SamplingConfig implements Serializable { */ private float probability = 0.10f; - public SamplingConfig() { - } + public SamplingConfig() {} public SamplingConfig(float probability) { this.probability = probability; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/support/Nested.java b/dubbo-common/src/main/java/org/apache/dubbo/config/support/Nested.java index 454e798c4c..bf6ddd9aee 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/support/Nested.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/support/Nested.java @@ -28,5 +28,4 @@ import java.lang.annotation.Target; @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) -public @interface Nested { -} +public @interface Nested {} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/support/Parameter.java b/dubbo-common/src/main/java/org/apache/dubbo/config/support/Parameter.java index 9091100aa4..217ad69e9f 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/support/Parameter.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/support/Parameter.java @@ -59,5 +59,4 @@ public @interface Parameter { * If append=true, append new value to exist value instead of overriding it. */ boolean append() default false; - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/MethodDefinitionBuilder.java b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/MethodDefinitionBuilder.java index e7c18e6f6f..d54dce60df 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/MethodDefinitionBuilder.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/MethodDefinitionBuilder.java @@ -74,5 +74,4 @@ public class MethodDefinitionBuilder { return md; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/ServiceDefinitionBuilder.java b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/ServiceDefinitionBuilder.java index 1367b5d551..b7c9f51171 100755 --- a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/ServiceDefinitionBuilder.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/ServiceDefinitionBuilder.java @@ -117,8 +117,5 @@ public final class ServiceDefinitionBuilder { return JsonUtils.toJson(sd); } - private ServiceDefinitionBuilder() { - } + private ServiceDefinitionBuilder() {} } - - diff --git a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/TypeDefinitionBuilder.java b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/TypeDefinitionBuilder.java index a9f9d2d984..83f592910b 100755 --- a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/TypeDefinitionBuilder.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/TypeDefinitionBuilder.java @@ -31,7 +31,6 @@ import java.util.List; import java.util.Map; import java.util.Set; - /** * 2015/1/27. */ @@ -66,7 +65,7 @@ public class TypeDefinitionBuilder { return builder; } } catch (NoClassDefFoundError cnfe) { - //ignore + // ignore logger.info("Throw classNotFound (" + cnfe.getMessage() + ") in " + builder.getClass()); } } @@ -82,5 +81,4 @@ public class TypeDefinitionBuilder { public List getTypeDefinitions() { return new ArrayList<>(typeCache.values()); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/ArrayTypeBuilder.java b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/ArrayTypeBuilder.java index 78cc7a5a10..3bac0302a7 100755 --- a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/ArrayTypeBuilder.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/ArrayTypeBuilder.java @@ -52,5 +52,4 @@ public class ArrayTypeBuilder implements TypeBuilder { } return td; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/CollectionTypeBuilder.java b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/CollectionTypeBuilder.java index 6c6ee11010..232f6378f8 100755 --- a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/CollectionTypeBuilder.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/CollectionTypeBuilder.java @@ -52,7 +52,8 @@ public class CollectionTypeBuilder implements TypeBuilder { throw new IllegalArgumentException(MessageFormat.format( "[ServiceDefinitionBuilder] Collection type [{0}] with unexpected amount of arguments [{1}]." + Arrays.toString(actualTypeArgs), - type, actualTypeArgs)); + type, + actualTypeArgs)); } String colType = ClassUtils.getCanonicalNameForParameterizedType(parameterizedType); @@ -79,5 +80,4 @@ public class CollectionTypeBuilder implements TypeBuilder { return td; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/DefaultTypeBuilder.java b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/DefaultTypeBuilder.java index 4ac52a4d68..2da24303cb 100755 --- a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/DefaultTypeBuilder.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/DefaultTypeBuilder.java @@ -60,6 +60,5 @@ public final class DefaultTypeBuilder { return td; } - private DefaultTypeBuilder() { - } + private DefaultTypeBuilder() {} } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/EnumTypeBuilder.java b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/EnumTypeBuilder.java index ff926ca297..c107d2d884 100755 --- a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/EnumTypeBuilder.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/EnumTypeBuilder.java @@ -31,7 +31,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXP * 2015/1/27. */ public class EnumTypeBuilder implements TypeBuilder { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(TypeDefinitionBuilder.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(TypeDefinitionBuilder.class); @Override public boolean accept(Class clazz) { @@ -67,5 +68,4 @@ public class EnumTypeBuilder implements TypeBuilder { } return td; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/TypeBuilder.java b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/TypeBuilder.java index 8a8f830215..f31c177293 100755 --- a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/TypeBuilder.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/builder/TypeBuilder.java @@ -39,5 +39,4 @@ public interface TypeBuilder extends Prioritized { * Build type definition with the type or class. */ TypeDefinition build(Type type, Class clazz, Map typeCache); - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/FullServiceDefinition.java b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/FullServiceDefinition.java index fbebcf1ed6..d84fb2e38d 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/FullServiceDefinition.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/FullServiceDefinition.java @@ -35,9 +35,6 @@ public class FullServiceDefinition extends ServiceDefinition { @Override public String toString() { - return "FullServiceDefinition{" + - "parameters=" + parameters + - "} " + super.toString(); + return "FullServiceDefinition{" + "parameters=" + parameters + "} " + super.toString(); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/MethodDefinition.java b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/MethodDefinition.java index 305bfc3f0b..6177ef2b4c 100755 --- a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/MethodDefinition.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/MethodDefinition.java @@ -105,9 +105,9 @@ public class MethodDefinition implements Serializable { return false; } MethodDefinition that = (MethodDefinition) o; - return Objects.equals(getName(), that.getName()) && - Arrays.equals(getParameterTypes(), that.getParameterTypes()) && - Objects.equals(getReturnType(), that.getReturnType()); + return Objects.equals(getName(), that.getName()) + && Arrays.equals(getParameterTypes(), that.getParameterTypes()) + && Objects.equals(getReturnType(), that.getReturnType()); } @Override diff --git a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/ServiceDefinition.java b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/ServiceDefinition.java index a16eb6a2a4..cacd09ddd2 100755 --- a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/ServiceDefinition.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/ServiceDefinition.java @@ -123,10 +123,10 @@ public class ServiceDefinition implements Serializable { return false; } ServiceDefinition that = (ServiceDefinition) o; - return Objects.equals(getCanonicalName(), that.getCanonicalName()) && - Objects.equals(getCodeSource(), that.getCodeSource()) && - Objects.equals(getMethods(), that.getMethods()) && - Objects.equals(getTypes(), that.getTypes()); + return Objects.equals(getCanonicalName(), that.getCanonicalName()) + && Objects.equals(getCodeSource(), that.getCodeSource()) + && Objects.equals(getMethods(), that.getMethods()) + && Objects.equals(getTypes(), that.getTypes()); } @Override diff --git a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/TypeDefinition.java b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/TypeDefinition.java index 4962316daa..5a6ff70169 100755 --- a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/TypeDefinition.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/model/TypeDefinition.java @@ -35,7 +35,7 @@ public class TypeDefinition implements Serializable { * the name of type * * @see Class#getCanonicalName() - * @see org.apache.dubbo.metadata.definition.util.ClassUtils#getCanonicalNameForParameterizedType(ParameterizedType) + * @see org.apache.dubbo.metadata.definition.util.ClassUtils#getCanonicalNameForParameterizedType(ParameterizedType) */ private String type; @@ -59,8 +59,7 @@ public class TypeDefinition implements Serializable { */ private Map properties; - public TypeDefinition() { - } + public TypeDefinition() {} public TypeDefinition(String type) { this.setType(type); @@ -166,10 +165,10 @@ public class TypeDefinition implements Serializable { return false; } TypeDefinition that = (TypeDefinition) o; - return Objects.equals(getType(), that.getType()) && - Objects.equals(getItems(), that.getItems()) && - Objects.equals(getEnums(), that.getEnums()) && - Objects.equals(getProperties(), that.getProperties()); + return Objects.equals(getType(), that.getType()) + && Objects.equals(getItems(), that.getItems()) + && Objects.equals(getEnums(), that.getEnums()) + && Objects.equals(getProperties(), that.getProperties()); } @Override diff --git a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/util/ClassUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/util/ClassUtils.java index c6f13d5560..1115c451b2 100755 --- a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/util/ClassUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/util/ClassUtils.java @@ -126,8 +126,8 @@ public final class ClassUtils { if (ownerType instanceof ParameterizedType) { // Find simple name of nested type by removing the // shared prefix with owner. - sb.append(rawType.getName().replace(((Class) ((ParameterizedType) ownerType).getRawType()).getName() + "$", - "")); + sb.append(rawType.getName() + .replace(((Class) ((ParameterizedType) ownerType).getRawType()).getName() + "$", "")); } else { sb.append(rawType.getSimpleName()); } @@ -135,8 +135,7 @@ public final class ClassUtils { sb.append(rawType.getCanonicalName()); } - if (actualTypeArguments != null && - actualTypeArguments.length > 0) { + if (actualTypeArguments != null && actualTypeArguments.length > 0) { sb.append('<'); boolean first = true; for (Type t : actualTypeArguments) { @@ -159,6 +158,5 @@ public final class ClassUtils { return sb.toString(); } - private ClassUtils() { - } + private ClassUtils() {} } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/util/JaketConfigurationUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/util/JaketConfigurationUtils.java index a21de3f5dc..4372a40e73 100755 --- a/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/util/JaketConfigurationUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/metadata/definition/util/JaketConfigurationUtils.java @@ -98,5 +98,4 @@ public class JaketConfigurationUtils { return !isExcludedType(clazz); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/AbstractIsolationExecutorSupport.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/AbstractIsolationExecutorSupport.java index 1c78036a91..b188e14775 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/AbstractIsolationExecutorSupport.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/AbstractIsolationExecutorSupport.java @@ -67,4 +67,5 @@ public abstract class AbstractIsolationExecutorSupport implements ExecutorSuppor return null; } return frameworkServiceRepository.lookupExportedService(serviceKey.toString()); - }} + } +} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/DefaultExecutorSupport.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/DefaultExecutorSupport.java index 08dd4ebee7..1a33129e75 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/DefaultExecutorSupport.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/DefaultExecutorSupport.java @@ -34,5 +34,4 @@ public class DefaultExecutorSupport implements ExecutorSupport { public Executor getExecutor(Object data) { return executorRepository.getExecutor(url); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/IsolationExecutorSupportFactory.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/IsolationExecutorSupportFactory.java index b3f4a551d8..c978052ecf 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/IsolationExecutorSupportFactory.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/executor/IsolationExecutorSupportFactory.java @@ -28,9 +28,9 @@ public interface IsolationExecutorSupportFactory { static ExecutorSupport getIsolationExecutorSupport(URL url) { ApplicationModel applicationModel = url.getOrDefaultApplicationModel(); - ExtensionLoader extensionLoader = applicationModel.getExtensionLoader(IsolationExecutorSupportFactory.class); + ExtensionLoader extensionLoader = + applicationModel.getExtensionLoader(IsolationExecutorSupportFactory.class); IsolationExecutorSupportFactory factory = extensionLoader.getOrDefaultExtension(url.getProtocol()); return factory.createIsolationExecutorSupport(url); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java index 0544df59ed..1971cf25e7 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ApplicationModel.java @@ -50,7 +50,6 @@ import java.util.concurrent.locks.Lock; * and many Consumer Model which is about subscribed services. *

*/ - public class ApplicationModel extends ScopeModel { protected static final Logger LOGGER = LoggerFactory.getLogger(ApplicationModel.class); public static final String NAME = "ApplicationModel"; @@ -112,7 +111,8 @@ public class ApplicationModel extends ScopeModel { this.internalModule = new ModuleModel(this, true); this.serviceRepository = new ServiceRepository(this); - ExtensionLoader extensionLoader = this.getExtensionLoader(ApplicationInitListener.class); + ExtensionLoader extensionLoader = + this.getExtensionLoader(ApplicationInitListener.class); Set listenerNames = extensionLoader.getSupportedExtensions(); for (String listenerName : listenerNames) { extensionLoader.getExtension(listenerName).init(); @@ -120,7 +120,8 @@ public class ApplicationModel extends ScopeModel { initApplicationExts(); - ExtensionLoader initializerExtensionLoader = this.getExtensionLoader(ScopeModelInitializer.class); + ExtensionLoader initializerExtensionLoader = + this.getExtensionLoader(ScopeModelInitializer.class); Set initializers = initializerExtensionLoader.getSupportedExtensionInstances(); for (ScopeModelInitializer initializer : initializers) { initializer.initializeApplicationModel(this); @@ -128,7 +129,8 @@ public class ApplicationModel extends ScopeModel { Assert.notNull(getApplicationServiceRepository(), "ApplicationServiceRepository can not be null"); Assert.notNull(getApplicationConfigManager(), "ApplicationConfigManager can not be null"); - Assert.assertTrue(getApplicationConfigManager().isInitialized(), "ApplicationConfigManager can not be initialized"); + Assert.assertTrue( + getApplicationConfigManager().isInitialized(), "ApplicationConfigManager can not be initialized"); } } @@ -148,7 +150,8 @@ public class ApplicationModel extends ScopeModel { // 2. pre-destroy, set stopping if (deployer != null) { - // destroy registries and unregister services from registries first to notify consumers to stop consuming this instance. + // destroy registries and unregister services from registries first to notify consumers to stop + // consuming this instance. deployer.preDestroy(); } @@ -203,16 +206,16 @@ public class ApplicationModel extends ScopeModel { @Override public Environment modelEnvironment() { if (environment == null) { - environment = (Environment) this.getExtensionLoader(ApplicationExt.class) - .getExtension(Environment.NAME); + environment = + (Environment) this.getExtensionLoader(ApplicationExt.class).getExtension(Environment.NAME); } return environment; } public ConfigManager getApplicationConfigManager() { if (configManager == null) { - configManager = (ConfigManager) this.getExtensionLoader(ApplicationExt.class) - .getExtension(ConfigManager.NAME); + configManager = (ConfigManager) + this.getExtensionLoader(ApplicationExt.class).getExtension(ConfigManager.NAME); } return configManager; } @@ -238,7 +241,8 @@ public class ApplicationModel extends ScopeModel { } public String tryGetApplicationName() { - Optional appCfgOptional = getApplicationConfigManager().getApplication(); + Optional appCfgOptional = + getApplicationConfigManager().getApplication(); return appCfgOptional.isPresent() ? appCfgOptional.get().getName() : null; } @@ -268,7 +272,7 @@ public class ApplicationModel extends ScopeModel { void tryDestroy() { synchronized (instLock) { if (this.moduleModels.isEmpty() - || (this.moduleModels.size() == 1 && this.moduleModels.get(0) == internalModule)) { + || (this.moduleModels.size() == 1 && this.moduleModels.get(0) == internalModule)) { destroy(); } } @@ -339,7 +343,8 @@ public class ApplicationModel extends ScopeModel { } protected boolean containsClassLoader(ClassLoader classLoader) { - return moduleModels.stream().anyMatch(moduleModel -> moduleModel.getClassLoaders().contains(classLoader)); + return moduleModels.stream() + .anyMatch(moduleModel -> moduleModel.getClassLoaders().contains(classLoader)); } public ApplicationDeployer getDeployer() { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/BuiltinServiceDetector.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/BuiltinServiceDetector.java index ca27eb7f5b..5140c06056 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/BuiltinServiceDetector.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/BuiltinServiceDetector.java @@ -23,5 +23,4 @@ import org.apache.dubbo.common.extension.SPI; public interface BuiltinServiceDetector { Class getService(); - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ConsumerMethodModel.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ConsumerMethodModel.java index 7a4427f778..d002dcafca 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ConsumerMethodModel.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ConsumerMethodModel.java @@ -29,7 +29,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; public class ConsumerMethodModel { private final Method method; // private final boolean isCallBack; -// private final boolean isFuture; + // private final boolean isFuture; private final String[] parameterTypes; private final Class[] parameterClasses; private final Class returnClass; @@ -38,7 +38,6 @@ public class ConsumerMethodModel { private final ConcurrentMap attributeMap = new ConcurrentHashMap<>(); - public ConsumerMethodModel(Method method) { this.method = method; this.parameterClasses = method.getParameterTypes(); @@ -52,9 +51,9 @@ public class ConsumerMethodModel { return method; } -// public ConcurrentMap getAttributeMap() { -// return attributeMap; -// } + // public ConcurrentMap getAttributeMap() { + // return attributeMap; + // } public void addAttribute(String key, Object value) { this.attributeMap.put(key, value); @@ -64,7 +63,6 @@ public class ConsumerMethodModel { return this.attributeMap.get(key); } - public Class getReturnClass() { return returnClass; } @@ -79,7 +77,7 @@ public class ConsumerMethodModel { private String[] createParamSignature(Class[] args) { if (args == null || args.length == 0) { - return new String[]{}; + return new String[] {}; } String[] paramSig = new String[args.length]; for (int x = 0; x < args.length; x++) { @@ -88,7 +86,6 @@ public class ConsumerMethodModel { return paramSig; } - public boolean isGeneric() { return generic; } @@ -96,6 +93,4 @@ public class ConsumerMethodModel { public Class[] getParameterClasses() { return parameterClasses; } - - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ConsumerModel.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ConsumerModel.java index 24876bc196..1a1c5d2897 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ConsumerModel.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ConsumerModel.java @@ -46,11 +46,12 @@ public class ConsumerModel extends ServiceModel { * @param serviceKey Name of the service. * @param proxyObject Proxy object. */ - public ConsumerModel(String serviceKey, - Object proxyObject, - ServiceDescriptor serviceDescriptor, - Map methodConfigs, - ClassLoader interfaceClassLoader) { + public ConsumerModel( + String serviceKey, + Object proxyObject, + ServiceDescriptor serviceDescriptor, + Map methodConfigs, + ClassLoader interfaceClassLoader) { super(proxyObject, serviceKey, serviceDescriptor, null, interfaceClassLoader); Assert.notEmptyString(serviceKey, "Service name can't be null or blank"); @@ -58,12 +59,13 @@ public class ConsumerModel extends ServiceModel { this.methodConfigs = methodConfigs == null ? new HashMap<>() : methodConfigs; } - public ConsumerModel(String serviceKey, - Object proxyObject, - ServiceDescriptor serviceDescriptor, - ServiceMetadata metadata, - Map methodConfigs, - ClassLoader interfaceClassLoader) { + public ConsumerModel( + String serviceKey, + Object proxyObject, + ServiceDescriptor serviceDescriptor, + ServiceMetadata metadata, + Map methodConfigs, + ClassLoader interfaceClassLoader) { super(proxyObject, serviceKey, serviceDescriptor, null, metadata, interfaceClassLoader); Assert.notEmptyString(serviceKey, "Service name can't be null or blank"); @@ -71,13 +73,14 @@ public class ConsumerModel extends ServiceModel { this.methodConfigs = methodConfigs == null ? new HashMap<>() : methodConfigs; } - public ConsumerModel(String serviceKey, - Object proxyObject, - ServiceDescriptor serviceDescriptor, - ModuleModel moduleModel, - ServiceMetadata metadata, - Map methodConfigs, - ClassLoader interfaceClassLoader) { + public ConsumerModel( + String serviceKey, + Object proxyObject, + ServiceDescriptor serviceDescriptor, + ModuleModel moduleModel, + ServiceMetadata metadata, + Map methodConfigs, + ClassLoader interfaceClassLoader) { super(proxyObject, serviceKey, serviceDescriptor, moduleModel, metadata, interfaceClassLoader); Assert.notEmptyString(serviceKey, "Service name can't be null or blank"); @@ -102,7 +105,7 @@ public class ConsumerModel extends ServiceModel { if (getProxyObject() == null) { Class serviceInterfaceClass = getServiceInterfaceClass(); if (serviceInterfaceClass != null) { - interfaceList = new Class[]{serviceInterfaceClass}; + interfaceList = new Class[] {serviceInterfaceClass}; } else { interfaceList = new Class[0]; } @@ -133,7 +136,9 @@ public class ConsumerModel extends ServiceModel { * @return method model */ public ConsumerMethodModel getMethodModel(String method) { - Optional> consumerMethodModelEntry = methodModels.entrySet().stream().filter(entry -> entry.getKey().getName().equals(method)).findFirst(); + Optional> consumerMethodModelEntry = methodModels.entrySet().stream() + .filter(entry -> entry.getKey().getName().equals(method)) + .findFirst(); return consumerMethodModelEntry.map(Map.Entry::getValue).orElse(null); } @@ -144,9 +149,10 @@ public class ConsumerModel extends ServiceModel { */ public ConsumerMethodModel getMethodModel(String method, String[] argsType) { Optional consumerMethodModel = methodModels.entrySet().stream() - .filter(entry -> entry.getKey().getName().equals(method)) - .map(Map.Entry::getValue).filter(methodModel -> Arrays.equals(argsType, methodModel.getParameterTypes())) - .findFirst(); + .filter(entry -> entry.getKey().getName().equals(method)) + .map(Map.Entry::getValue) + .filter(methodModel -> Arrays.equals(argsType, methodModel.getParameterTypes())) + .findFirst(); return consumerMethodModel.orElse(null); } @@ -171,7 +177,9 @@ public class ConsumerModel extends ServiceModel { return false; } ConsumerModel that = (ConsumerModel) o; - return Objects.equals(apps, that.apps) && Objects.equals(methodConfigs, that.methodConfigs) && Objects.equals(methodModels, that.methodModels); + return Objects.equals(apps, that.apps) + && Objects.equals(methodConfigs, that.methodConfigs) + && Objects.equals(methodModels, that.methodModels); } @Override diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/DubboStub.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/DubboStub.java index 7047eeaa1d..5481c36471 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/DubboStub.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/DubboStub.java @@ -14,12 +14,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.model; /** * Marker interface implemented by all stub. Used to detect * whether objects are Dubbo-generated stub. */ -public interface DubboStub { -} +public interface DubboStub {} diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkModel.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkModel.java index 09a001f3bb..e5fb2b52ff 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkModel.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkModel.java @@ -51,7 +51,7 @@ public class FrameworkModel extends ScopeModel { private static final Object globalLock = new Object(); - private volatile static FrameworkModel defaultInstance; + private static volatile FrameworkModel defaultInstance; private static final List allInstances = new CopyOnWriteArrayList<>(); @@ -91,15 +91,18 @@ public class FrameworkModel extends ScopeModel { serviceRepository = new FrameworkServiceRepository(this); - ExtensionLoader initializerExtensionLoader = this.getExtensionLoader(ScopeModelInitializer.class); + ExtensionLoader initializerExtensionLoader = + this.getExtensionLoader(ScopeModelInitializer.class); Set initializers = initializerExtensionLoader.getSupportedExtensionInstances(); for (ScopeModelInitializer initializer : initializers) { initializer.initializeFrameworkModel(this); } internalApplicationModel = new ApplicationModel(this, true); - internalApplicationModel.getApplicationConfigManager().setApplication( - new ApplicationConfig(internalApplicationModel, CommonConstants.DUBBO_INTERNAL_APPLICATION)); + internalApplicationModel + .getApplicationConfigManager() + .setApplication(new ApplicationConfig( + internalApplicationModel, CommonConstants.DUBBO_INTERNAL_APPLICATION)); internalApplicationModel.setModelName(CommonConstants.DUBBO_INTERNAL_APPLICATION); } } @@ -109,7 +112,8 @@ public class FrameworkModel extends ScopeModel { protected void onDestroy() { synchronized (instLock) { if (defaultInstance == this) { - // NOTE: During destroying the default FrameworkModel, the FrameworkModel.defaultModel() or ApplicationModel.defaultModel() + // NOTE: During destroying the default FrameworkModel, the FrameworkModel.defaultModel() or + // ApplicationModel.defaultModel() // will return a broken model, maybe cause unpredictable problem. if (LOGGER.isInfoEnabled()) { LOGGER.info("Destroying default framework model: " + getDesc()); @@ -149,11 +153,11 @@ public class FrameworkModel extends ScopeModel { private void checkApplicationDestroy() { synchronized (instLock) { if (applicationModels.size() > 0) { - List remainApplications = applicationModels.stream() - .map(ScopeModel::getDesc) - .collect(Collectors.toList()); - throw new IllegalStateException("Not all application models are completely destroyed, remaining " + - remainApplications.size() + " application models may be created during destruction: " + remainApplications); + List remainApplications = + applicationModels.stream().map(ScopeModel::getDesc).collect(Collectors.toList()); + throw new IllegalStateException( + "Not all application models are completely destroyed, remaining " + remainApplications.size() + + " application models may be created during destruction: " + remainApplications); } } } @@ -305,7 +309,8 @@ public class FrameworkModel extends ScopeModel { } if (defaultInstance == this && oldDefaultAppModel != this.defaultAppModel) { if (LOGGER.isInfoEnabled()) { - LOGGER.info("Reset global default application from " + safeGetModelDesc(oldDefaultAppModel) + " to " + safeGetModelDesc(this.defaultAppModel)); + LOGGER.info("Reset global default application from " + safeGetModelDesc(oldDefaultAppModel) + " to " + + safeGetModelDesc(this.defaultAppModel)); } } } @@ -324,7 +329,8 @@ public class FrameworkModel extends ScopeModel { } if (oldDefaultFrameworkModel != defaultInstance) { if (LOGGER.isInfoEnabled()) { - LOGGER.info("Reset global default framework from " + safeGetModelDesc(oldDefaultFrameworkModel) + " to " + safeGetModelDesc(defaultInstance)); + LOGGER.info("Reset global default framework from " + safeGetModelDesc(oldDefaultFrameworkModel) + + " to " + safeGetModelDesc(defaultInstance)); } } } @@ -360,7 +366,6 @@ public class FrameworkModel extends ScopeModel { return serviceRepository; } - @Override protected Lock acquireDestroyLock() { return destroyLock; @@ -373,7 +378,8 @@ public class FrameworkModel extends ScopeModel { @Override protected boolean checkIfClassLoaderCanRemoved(ClassLoader classLoader) { - return super.checkIfClassLoaderCanRemoved(classLoader) && - applicationModels.stream().noneMatch(applicationModel -> applicationModel.containsClassLoader(classLoader)); + return super.checkIfClassLoaderCanRemoved(classLoader) + && applicationModels.stream() + .noneMatch(applicationModel -> applicationModel.containsClassLoader(classLoader)); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkServiceRepository.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkServiceRepository.java index 7aff29de0c..49a6d90185 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkServiceRepository.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/FrameworkServiceRepository.java @@ -56,7 +56,9 @@ public class FrameworkServiceRepository { // throw new IllegalStateException("Register duplicate provider for key: " + key); } String keyWithoutGroup = keyWithoutGroup(key); - ConcurrentHashMapUtils.computeIfAbsent(providersWithoutGroup, keyWithoutGroup, (k) -> new CopyOnWriteArrayList<>()).add(providerModel); + ConcurrentHashMapUtils.computeIfAbsent( + providersWithoutGroup, keyWithoutGroup, (k) -> new CopyOnWriteArrayList<>()) + .add(providerModel); } public void unregisterProvider(ProviderModel providerModel) { @@ -88,8 +90,10 @@ public class FrameworkServiceRepository { public List allConsumerModels() { List consumerModels = new LinkedList<>(); - frameworkModel.getApplicationModels().forEach(applicationModel -> - consumerModels.addAll(applicationModel.getApplicationServiceRepository().allConsumerModels())); + frameworkModel + .getApplicationModels() + .forEach(applicationModel -> consumerModels.addAll( + applicationModel.getApplicationServiceRepository().allConsumerModels())); return Collections.unmodifiableList(consumerModels); } @@ -101,5 +105,4 @@ public class FrameworkServiceRepository { } return interfaceName + CommonConstants.GROUP_CHAR_SEPARATOR + version; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/MethodDescriptor.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/MethodDescriptor.java index a9da7f7dd9..2496d2dea3 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/MethodDescriptor.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/MethodDescriptor.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.model; import java.lang.reflect.Method; @@ -53,6 +52,9 @@ public interface MethodDescriptor { Object getAttribute(String key); enum RpcType { - UNARY, CLIENT_STREAM, SERVER_STREAM, BI_STREAM + UNARY, + CLIENT_STREAM, + SERVER_STREAM, + BI_STREAM } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleModel.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleModel.java index 358868af69..9af38b0428 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleModel.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleModel.java @@ -69,7 +69,8 @@ public class ModuleModel extends ScopeModel { initModuleExt(); - ExtensionLoader initializerExtensionLoader = this.getExtensionLoader(ScopeModelInitializer.class); + ExtensionLoader initializerExtensionLoader = + this.getExtensionLoader(ScopeModelInitializer.class); Set initializers = initializerExtensionLoader.getSupportedExtensionInstances(); for (ScopeModelInitializer initializer : initializers) { initializer.initializeModuleModel(this); @@ -152,16 +153,16 @@ public class ModuleModel extends ScopeModel { @Override public ModuleEnvironment modelEnvironment() { if (moduleEnvironment == null) { - moduleEnvironment = (ModuleEnvironment) this.getExtensionLoader(ModuleExt.class) - .getExtension(ModuleEnvironment.NAME); + moduleEnvironment = + (ModuleEnvironment) this.getExtensionLoader(ModuleExt.class).getExtension(ModuleEnvironment.NAME); } return moduleEnvironment; } public ModuleConfigManager getConfigManager() { if (moduleConfigManager == null) { - moduleConfigManager = (ModuleConfigManager) this.getExtensionLoader(ModuleExt.class) - .getExtension(ModuleConfigManager.NAME); + moduleConfigManager = (ModuleConfigManager) + this.getExtensionLoader(ModuleExt.class).getExtension(ModuleConfigManager.NAME); } return moduleConfigManager; } @@ -197,8 +198,14 @@ public class ModuleModel extends ScopeModel { String serviceKey = URL.buildKey(internalService.getName(), url.getGroup(), url.getVersion()); serviceMetadata.setServiceKey(serviceKey); - ConsumerModel consumerModel = new ConsumerModel(serviceMetadata.getServiceKey(), "jdk", serviceRepository.lookupService(serviceMetadata.getServiceInterfaceName()), - this, serviceMetadata, new HashMap<>(0), ClassUtils.getClassLoader(internalService)); + ConsumerModel consumerModel = new ConsumerModel( + serviceMetadata.getServiceKey(), + "jdk", + serviceRepository.lookupService(serviceMetadata.getServiceInterfaceName()), + this, + serviceMetadata, + new HashMap<>(0), + ClassUtils.getClassLoader(internalService)); logger.info("Dynamically registering consumer model " + serviceKey + " into model " + this.getDesc()); serviceRepository.registerConsumer(consumerModel); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleServiceRepository.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleServiceRepository.java index c3b1d446c7..5a9092b4d9 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleServiceRepository.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ModuleServiceRepository.java @@ -52,11 +52,13 @@ public class ModuleServiceRepository { * providers */ private final ConcurrentMap providers = new ConcurrentHashMap<>(); + private final FrameworkServiceRepository frameworkServiceRepository; public ModuleServiceRepository(ModuleModel moduleModel) { this.moduleModel = moduleModel; - frameworkServiceRepository = ScopeModelUtil.getFrameworkModel(moduleModel).getServiceRepository(); + frameworkServiceRepository = + ScopeModelUtil.getFrameworkModel(moduleModel).getServiceRepository(); } public ModuleModel getModuleModel() { @@ -67,41 +69,45 @@ public class ModuleServiceRepository { * @deprecated Replaced to {@link ModuleServiceRepository#registerConsumer(ConsumerModel)} */ @Deprecated - public void registerConsumer(String serviceKey, - ServiceDescriptor serviceDescriptor, - ReferenceConfigBase rc, - Object proxy, - ServiceMetadata serviceMetadata) { + public void registerConsumer( + String serviceKey, + ServiceDescriptor serviceDescriptor, + ReferenceConfigBase rc, + Object proxy, + ServiceMetadata serviceMetadata) { ClassLoader classLoader = null; if (rc != null) { classLoader = rc.getInterfaceClassLoader(); } - ConsumerModel consumerModel = new ConsumerModel(serviceMetadata.getServiceKey(), proxy, serviceDescriptor, - serviceMetadata, null, classLoader); + ConsumerModel consumerModel = new ConsumerModel( + serviceMetadata.getServiceKey(), proxy, serviceDescriptor, serviceMetadata, null, classLoader); this.registerConsumer(consumerModel); } public void registerConsumer(ConsumerModel consumerModel) { - ConcurrentHashMapUtils.computeIfAbsent(consumers, consumerModel.getServiceKey(), (serviceKey) -> new CopyOnWriteArrayList<>()).add(consumerModel); + ConcurrentHashMapUtils.computeIfAbsent( + consumers, consumerModel.getServiceKey(), (serviceKey) -> new CopyOnWriteArrayList<>()) + .add(consumerModel); } /** * @deprecated Replaced to {@link ModuleServiceRepository#registerProvider(ProviderModel)} */ @Deprecated - public void registerProvider(String serviceKey, - Object serviceInstance, - ServiceDescriptor serviceModel, - ServiceConfigBase serviceConfig, - ServiceMetadata serviceMetadata) { + public void registerProvider( + String serviceKey, + Object serviceInstance, + ServiceDescriptor serviceModel, + ServiceConfigBase serviceConfig, + ServiceMetadata serviceMetadata) { ClassLoader classLoader = null; Class cla = null; if (serviceConfig != null) { classLoader = serviceConfig.getInterfaceClassLoader(); cla = serviceConfig.getInterfaceClass(); } - ProviderModel providerModel = new ProviderModel(serviceKey, serviceInstance, serviceModel, - serviceMetadata, classLoader); + ProviderModel providerModel = + new ProviderModel(serviceKey, serviceInstance, serviceModel, serviceMetadata, classLoader); this.registerProvider(providerModel); } @@ -120,11 +126,12 @@ public class ModuleServiceRepository { } public ServiceDescriptor registerService(Class interfaceClazz, ServiceDescriptor serviceDescriptor) { - List serviceDescriptors = ConcurrentHashMapUtils.computeIfAbsent(services, interfaceClazz.getName(), - k -> new CopyOnWriteArrayList<>()); + List serviceDescriptors = ConcurrentHashMapUtils.computeIfAbsent( + services, interfaceClazz.getName(), k -> new CopyOnWriteArrayList<>()); synchronized (serviceDescriptors) { Optional previous = serviceDescriptors.stream() - .filter(s -> s.getServiceInterfaceClass().equals(interfaceClazz)).findFirst(); + .filter(s -> s.getServiceInterfaceClass().equals(interfaceClazz)) + .findFirst(); if (previous.isPresent()) { return previous.get(); } else { @@ -150,11 +157,12 @@ public class ModuleServiceRepository { ServiceDescriptor serviceDescriptor = registerService(interfaceClass); // if path is different with interface name, add extra path mapping if (!interfaceClass.getName().equals(path)) { - List serviceDescriptors = ConcurrentHashMapUtils.computeIfAbsent(services, path, - _k -> new CopyOnWriteArrayList<>()); + List serviceDescriptors = + ConcurrentHashMapUtils.computeIfAbsent(services, path, _k -> new CopyOnWriteArrayList<>()); synchronized (serviceDescriptors) { Optional previous = serviceDescriptors.stream() - .filter(s -> s.getServiceInterfaceClass().equals(serviceDescriptor.getServiceInterfaceClass())).findFirst(); + .filter(s -> s.getServiceInterfaceClass().equals(serviceDescriptor.getServiceInterfaceClass())) + .findFirst(); if (previous.isPresent()) { return previous.get(); } else { @@ -180,7 +188,8 @@ public class ModuleServiceRepository { public void reRegisterConsumer(String newServiceKey, String serviceKey) { List consumerModel = this.consumers.get(serviceKey); consumerModel.forEach(c -> c.setServiceKey(newServiceKey)); - ConcurrentHashMapUtils.computeIfAbsent(this.consumers, newServiceKey, (k) -> new CopyOnWriteArrayList<>()).addAll(consumerModel); + ConcurrentHashMapUtils.computeIfAbsent(this.consumers, newServiceKey, (k) -> new CopyOnWriteArrayList<>()) + .addAll(consumerModel); this.consumers.remove(serviceKey); } @@ -203,7 +212,8 @@ public class ModuleServiceRepository { } public List getAllServices() { - List serviceDescriptors = services.values().stream().flatMap(Collection::stream).collect(Collectors.toList()); + List serviceDescriptors = + services.values().stream().flatMap(Collection::stream).collect(Collectors.toList()); return Collections.unmodifiableList(serviceDescriptors); } @@ -247,7 +257,8 @@ public class ModuleServiceRepository { } public List getReferredServices() { - List consumerModels = consumers.values().stream().flatMap(Collection::stream).collect(Collectors.toList()); + List consumerModels = + consumers.values().stream().flatMap(Collection::stream).collect(Collectors.toList()); return Collections.unmodifiableList(consumerModels); } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/Pack.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/Pack.java index 50f46c5f8b..340b668e42 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/Pack.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/Pack.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.model; public interface Pack { @@ -25,5 +24,4 @@ public interface Pack { * @throws Exception when error occurs */ byte[] pack(Object obj) throws Exception; - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/PackableMethod.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/PackableMethod.java index a9707bc073..90c931a7c1 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/PackableMethod.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/PackableMethod.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.model; /** @@ -47,7 +46,6 @@ public interface PackableMethod { return getResponsePack().pack(response); } - default boolean needWrapper() { return false; } @@ -59,5 +57,4 @@ public interface PackableMethod { UnPack getResponseUnpack(); UnPack getRequestUnpack(); - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/PackableMethodFactory.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/PackableMethodFactory.java index c3961a78c5..f5ca5ebca3 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/PackableMethodFactory.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/PackableMethodFactory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.model; import org.apache.dubbo.common.URL; @@ -25,5 +24,4 @@ import org.apache.dubbo.common.extension.SPI; public interface PackableMethodFactory { PackableMethod create(MethodDescriptor methodDescriptor, URL url, String contentType); - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ProviderModel.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ProviderModel.java index d578cef6fe..bb1f0ed8a0 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ProviderModel.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ProviderModel.java @@ -42,10 +42,11 @@ public class ProviderModel extends ServiceModel { private volatile long lastInvokeTime = 0; - public ProviderModel(String serviceKey, - Object serviceInstance, - ServiceDescriptor serviceDescriptor, - ClassLoader interfaceClassLoader) { + public ProviderModel( + String serviceKey, + Object serviceInstance, + ServiceDescriptor serviceDescriptor, + ClassLoader interfaceClassLoader) { super(serviceInstance, serviceKey, serviceDescriptor, null, interfaceClassLoader); if (null == serviceInstance) { throw new IllegalArgumentException("Service[" + serviceKey + "]Target is NULL."); @@ -54,11 +55,12 @@ public class ProviderModel extends ServiceModel { this.urls = new CopyOnWriteArrayList<>(); } - public ProviderModel(String serviceKey, - Object serviceInstance, - ServiceDescriptor serviceDescriptor, - ServiceMetadata serviceMetadata, - ClassLoader interfaceClassLoader) { + public ProviderModel( + String serviceKey, + Object serviceInstance, + ServiceDescriptor serviceDescriptor, + ServiceMetadata serviceMetadata, + ClassLoader interfaceClassLoader) { super(serviceInstance, serviceKey, serviceDescriptor, null, serviceMetadata, interfaceClassLoader); if (null == serviceInstance) { throw new IllegalArgumentException("Service[" + serviceKey + "]Target is NULL."); @@ -68,12 +70,13 @@ public class ProviderModel extends ServiceModel { this.urls = new ArrayList<>(1); } - public ProviderModel(String serviceKey, - Object serviceInstance, - ServiceDescriptor serviceModel, - ModuleModel moduleModel, - ServiceMetadata serviceMetadata, - ClassLoader interfaceClassLoader) { + public ProviderModel( + String serviceKey, + Object serviceInstance, + ServiceDescriptor serviceModel, + ModuleModel moduleModel, + ServiceMetadata serviceMetadata, + ClassLoader interfaceClassLoader) { super(serviceInstance, serviceKey, serviceModel, moduleModel, serviceMetadata, interfaceClassLoader); if (null == serviceInstance) { throw new IllegalArgumentException("Service[" + serviceKey + "]Target is NULL."); @@ -100,9 +103,7 @@ public class ProviderModel extends ServiceModel { private volatile URL providerUrl; private volatile boolean registered; - public RegisterStatedURL(URL providerUrl, - URL registryUrl, - boolean registered) { + public RegisterStatedURL(URL providerUrl, URL registryUrl, boolean registered) { this.providerUrl = providerUrl; this.registered = registered; this.registryUrl = registryUrl; @@ -177,7 +178,6 @@ public class ProviderModel extends ServiceModel { this.serviceUrls = urls; } - public long getLastInvokeTime() { return lastInvokeTime; } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ReflectionMethodDescriptor.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ReflectionMethodDescriptor.java index 4b447d5fc5..ea27aad53c 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ReflectionMethodDescriptor.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ReflectionMethodDescriptor.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.model; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -35,7 +34,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE_ASYNC; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_REFLECTIVE_OPERATION_FAILED; public class ReflectionMethodDescriptor implements MethodDescriptor { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ReflectionMethodDescriptor.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ReflectionMethodDescriptor.class); private final ConcurrentMap attributeMap = new ConcurrentHashMap<>(); public final String methodName; @@ -48,7 +48,6 @@ public class ReflectionMethodDescriptor implements MethodDescriptor { private final boolean generic; private final RpcType rpcType; - public ReflectionMethodDescriptor(Method method) { this.method = method; this.methodName = method.getName(); @@ -58,14 +57,19 @@ public class ReflectionMethodDescriptor implements MethodDescriptor { try { returnTypesResult = ReflectUtils.getReturnTypes(method); } catch (Throwable throwable) { - logger.error(COMMON_REFLECTIVE_OPERATION_FAILED, "", "", - "fail to get return types. Method name: " + methodName + " Declaring class:" + method.getDeclaringClass() - .getName(), throwable); - returnTypesResult = new Type[]{returnClass, returnClass}; + logger.error( + COMMON_REFLECTIVE_OPERATION_FAILED, + "", + "", + "fail to get return types. Method name: " + methodName + " Declaring class:" + + method.getDeclaringClass().getName(), + throwable); + returnTypesResult = new Type[] {returnClass, returnClass}; } this.returnTypes = returnTypesResult; this.paramDesc = ReflectUtils.getDesc(parameterClasses); - this.compatibleParamSignatures = Stream.of(parameterClasses).map(Class::getName).toArray(String[]::new); + this.compatibleParamSignatures = + Stream.of(parameterClasses).map(Class::getName).toArray(String[]::new); this.generic = (methodName.equals($INVOKE) || methodName.equals($INVOKE_ASYNC)) && parameterClasses.length == 3; this.rpcType = determineRpcType(); } @@ -80,13 +84,15 @@ public class ReflectionMethodDescriptor implements MethodDescriptor { if (parameterClasses.length == 1 && isStreamType(parameterClasses[0]) && isStreamType(returnClass)) { return RpcType.BI_STREAM; } - if (parameterClasses.length == 2 && !isStreamType(parameterClasses[0]) && isStreamType( - parameterClasses[1]) && returnClass.getName().equals(void.class.getName())) { + if (parameterClasses.length == 2 + && !isStreamType(parameterClasses[0]) + && isStreamType(parameterClasses[1]) + && returnClass.getName().equals(void.class.getName())) { return RpcType.SERVER_STREAM; } if (Arrays.stream(parameterClasses).anyMatch(this::isStreamType) || isStreamType(returnClass)) { throw new IllegalStateException( - "Bad stream method signature. method(" + methodName + ":" + paramDesc + ")"); + "Bad stream method signature. method(" + methodName + ":" + paramDesc + ")"); } // Can not determine client stream because it has same signature with bi_stream return RpcType.UNARY; @@ -158,11 +164,15 @@ public class ReflectionMethodDescriptor implements MethodDescriptor { return false; } ReflectionMethodDescriptor that = (ReflectionMethodDescriptor) o; - return generic == that.generic && Objects.equals(method, that.method) && Objects.equals(paramDesc, - that.paramDesc) && Arrays.equals(compatibleParamSignatures, - that.compatibleParamSignatures) && Arrays.equals(parameterClasses, that.parameterClasses) && Objects.equals( - returnClass, that.returnClass) && Arrays.equals(returnTypes, that.returnTypes) && Objects.equals(methodName, - that.methodName) && Objects.equals(attributeMap, that.attributeMap); + return generic == that.generic + && Objects.equals(method, that.method) + && Objects.equals(paramDesc, that.paramDesc) + && Arrays.equals(compatibleParamSignatures, that.compatibleParamSignatures) + && Arrays.equals(parameterClasses, that.parameterClasses) + && Objects.equals(returnClass, that.returnClass) + && Arrays.equals(returnTypes, that.returnTypes) + && Objects.equals(methodName, that.methodName) + && Objects.equals(attributeMap, that.attributeMap); } @Override @@ -173,5 +183,4 @@ public class ReflectionMethodDescriptor implements MethodDescriptor { result = 31 * result + Arrays.hashCode(returnTypes); return result; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ReflectionServiceDescriptor.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ReflectionServiceDescriptor.java index 489f7e4c6c..dc04146933 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ReflectionServiceDescriptor.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ReflectionServiceDescriptor.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.model; import org.apache.dubbo.common.utils.CollectionUtils; @@ -40,7 +39,8 @@ public class ReflectionServiceDescriptor implements ServiceDescriptor { // to accelerate search private final Map> methods = new HashMap<>(); private final Map> descToMethods = new HashMap<>(); - private final ConcurrentNavigableMap serviceDefinitions = new ConcurrentSkipListMap<>(); + private final ConcurrentNavigableMap serviceDefinitions = + new ConcurrentSkipListMap<>(); public ReflectionServiceDescriptor(String interfaceName, Class interfaceClass) { this.interfaceName = interfaceName; @@ -58,8 +58,9 @@ public class ReflectionServiceDescriptor implements ServiceDescriptor { } public FullServiceDefinition getFullServiceDefinition(String serviceKey) { - return serviceDefinitions.computeIfAbsent(serviceKey, - (k) -> ServiceDefinitionBuilder.buildFullDefinition(serviceInterfaceClass, Collections.emptyMap())); + return serviceDefinitions.computeIfAbsent( + serviceKey, + (k) -> ServiceDefinitionBuilder.buildFullDefinition(serviceInterfaceClass, Collections.emptyMap())); } private void initMethods() { @@ -78,15 +79,15 @@ public class ReflectionServiceDescriptor implements ServiceDescriptor { // not support BI_STREAM and SERVER_STREAM at the same time, for example, // void foo(Request, StreamObserver) ---> SERVER_STREAM // StreamObserver foo(StreamObserver) ---> BI_STREAM - long streamMethodCount = methodList.stream() - .peek(methodModel -> descMap.put(methodModel.getParamDesc(), methodModel)) - .map(MethodDescriptor::getRpcType) - .filter(rpcType -> rpcType == MethodDescriptor.RpcType.SERVER_STREAM - || rpcType == MethodDescriptor.RpcType.BI_STREAM) - .count(); + long streamMethodCount = methodList.stream() + .peek(methodModel -> descMap.put(methodModel.getParamDesc(), methodModel)) + .map(MethodDescriptor::getRpcType) + .filter(rpcType -> rpcType == MethodDescriptor.RpcType.SERVER_STREAM + || rpcType == MethodDescriptor.RpcType.BI_STREAM) + .count(); if (streamMethodCount > 1L) throw new IllegalStateException("Stream method could not be overloaded.There are " + streamMethodCount - +" stream method signatures. method(" + methodName + ")"); + + " stream method signatures. method(" + methodName + ")"); }); } @@ -151,9 +152,10 @@ public class ReflectionServiceDescriptor implements ServiceDescriptor { return false; } ReflectionServiceDescriptor that = (ReflectionServiceDescriptor) o; - return Objects.equals(interfaceName, that.interfaceName) && Objects.equals(serviceInterfaceClass, - that.serviceInterfaceClass) && Objects.equals(methods, that.methods) && Objects.equals(descToMethods, - that.descToMethods); + return Objects.equals(interfaceName, that.interfaceName) + && Objects.equals(serviceInterfaceClass, that.serviceInterfaceClass) + && Objects.equals(methods, that.methods) + && Objects.equals(descToMethods, that.descToMethods); } @Override diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModel.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModel.java index a96df0eb43..9e9d494a40 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModel.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModel.java @@ -98,7 +98,8 @@ public abstract class ScopeModel implements ExtensionAccessor { */ protected void initialize() { synchronized (instLock) { - this.extensionDirector = new ExtensionDirector(parent != null ? parent.getExtensionDirector() : null, scope, this); + this.extensionDirector = + new ExtensionDirector(parent != null ? parent.getExtensionDirector() : null, scope, this); this.extensionDirector.addExtensionPostProcessor(new ScopeModelAwareExtensionProcessor(this)); this.beanFactory = new ScopeBeanFactory(parent != null ? parent.getBeanFactory() : null, extensionDirector); diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelAccessor.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelAccessor.java index 9e9291e24b..7a213835dc 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelAccessor.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelAccessor.java @@ -34,5 +34,4 @@ public interface ScopeModelAccessor { default ModuleModel getModuleModel() { return ScopeModelUtil.getModuleModel(getScopeModel()); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelAware.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelAware.java index 6b60567965..bd03d97f30 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelAware.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ScopeModelAware.java @@ -25,28 +25,23 @@ public interface ScopeModelAware { * Override this method if you need get the scope model (maybe one of FrameworkModel/ApplicationModel/ModuleModel). * @param scopeModel */ - default void setScopeModel(ScopeModel scopeModel) { - } + default void setScopeModel(ScopeModel scopeModel) {} /** * Override this method if you just need framework model * @param frameworkModel */ - default void setFrameworkModel(FrameworkModel frameworkModel) { - } + default void setFrameworkModel(FrameworkModel frameworkModel) {} /** * Override this method if you just need application model * @param applicationModel */ - default void setApplicationModel(ApplicationModel applicationModel) { - } + default void setApplicationModel(ApplicationModel applicationModel) {} /** * Override this method if you just need module model * @param moduleModel */ - default void setModuleModel(ModuleModel moduleModel) { - } - + default void setModuleModel(ModuleModel moduleModel) {} } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceDescriptor.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceDescriptor.java index 2c00989c20..eba83d4702 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceDescriptor.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceDescriptor.java @@ -53,5 +53,4 @@ public interface ServiceDescriptor { MethodDescriptor getMethod(String methodName, Class[] paramTypes); List getMethods(String methodName); - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceMetadata.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceMetadata.java index 9111f80b51..7784cbfbcd 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceMetadata.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceMetadata.java @@ -52,8 +52,7 @@ public class ServiceMetadata extends BaseServiceMetadata { this.serviceType = serviceType; } - public ServiceMetadata() { - } + public ServiceMetadata() {} @Override public String getServiceKey() { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceModel.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceModel.java index afbc946abb..20692a08b6 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceModel.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceModel.java @@ -39,12 +39,22 @@ public class ServiceModel { private final ServiceMetadata serviceMetadata; - public ServiceModel(Object proxyObject, String serviceKey, ServiceDescriptor serviceModel, ModuleModel moduleModel, ClassLoader interfaceClassLoader) { + public ServiceModel( + Object proxyObject, + String serviceKey, + ServiceDescriptor serviceModel, + ModuleModel moduleModel, + ClassLoader interfaceClassLoader) { this(proxyObject, serviceKey, serviceModel, moduleModel, null, interfaceClassLoader); } - public ServiceModel(Object proxyObject, String serviceKey, ServiceDescriptor serviceModel, ModuleModel moduleModel, ServiceMetadata serviceMetadata, - ClassLoader interfaceClassLoader) { + public ServiceModel( + Object proxyObject, + String serviceKey, + ServiceDescriptor serviceModel, + ModuleModel moduleModel, + ServiceMetadata serviceMetadata, + ClassLoader interfaceClassLoader) { this.proxyObject = proxyObject; this.serviceKey = serviceKey; this.serviceModel = serviceModel; @@ -185,11 +195,26 @@ public class ServiceModel { return false; } ServiceModel that = (ServiceModel) o; - return Objects.equals(serviceKey, that.serviceKey) && Objects.equals(proxyObject, that.proxyObject) && Objects.equals(destroyRunner, that.destroyRunner) && Objects.equals(classLoader, that.classLoader) && Objects.equals(interfaceClassLoader, that.interfaceClassLoader) && Objects.equals(moduleModel, that.moduleModel) && Objects.equals(serviceModel, that.serviceModel) && Objects.equals(serviceMetadata, that.serviceMetadata); + return Objects.equals(serviceKey, that.serviceKey) + && Objects.equals(proxyObject, that.proxyObject) + && Objects.equals(destroyRunner, that.destroyRunner) + && Objects.equals(classLoader, that.classLoader) + && Objects.equals(interfaceClassLoader, that.interfaceClassLoader) + && Objects.equals(moduleModel, that.moduleModel) + && Objects.equals(serviceModel, that.serviceModel) + && Objects.equals(serviceMetadata, that.serviceMetadata); } @Override public int hashCode() { - return Objects.hash(serviceKey, proxyObject, destroyRunner, classLoader, interfaceClassLoader, moduleModel, serviceModel, serviceMetadata); + return Objects.hash( + serviceKey, + proxyObject, + destroyRunner, + classLoader, + interfaceClassLoader, + moduleModel, + serviceModel, + serviceMetadata); } } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceRepository.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceRepository.java index 204a5180de..b524b62281 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceRepository.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/ServiceRepository.java @@ -38,8 +38,9 @@ public class ServiceRepository { private void initialize() { if (initialized.compareAndSet(false, true)) { - Set builtinServices - = applicationModel.getExtensionLoader(BuiltinServiceDetector.class).getSupportedExtensionInstances(); + Set builtinServices = applicationModel + .getExtensionLoader(BuiltinServiceDetector.class) + .getSupportedExtensionInstances(); if (CollectionUtils.isNotEmpty(builtinServices)) { for (BuiltinServiceDetector service : builtinServices) { applicationModel.getInternalModule().getServiceRepository().registerService(service.getService()); @@ -49,7 +50,7 @@ public class ServiceRepository { } public void destroy() { - //TODO destroy application service repository + // TODO destroy application service repository } public Collection allConsumerModels() { @@ -69,5 +70,4 @@ public class ServiceRepository { } return allProviderModels; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/StubMethodDescriptor.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/StubMethodDescriptor.java index a98ef742f2..bfe497e2ee 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/StubMethodDescriptor.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/StubMethodDescriptor.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.model; import org.apache.dubbo.common.logger.Logger; @@ -43,15 +42,16 @@ public class StubMethodDescriptor implements MethodDescriptor, PackableMethod { private final UnPack requestUnpack; private final UnPack responseUnpack; - public StubMethodDescriptor(String methodName, - Class requestClass, - Class responseClass, - StubServiceDescriptor serviceDescriptor, - RpcType rpcType, - Pack requestPack, - Pack responsePack, - UnPack requestUnpack, - UnPack responseUnpack) { + public StubMethodDescriptor( + String methodName, + Class requestClass, + Class responseClass, + StubServiceDescriptor serviceDescriptor, + RpcType rpcType, + Pack requestPack, + Pack responsePack, + UnPack requestUnpack, + UnPack responseUnpack) { this.methodName = methodName; this.serviceDescriptor = serviceDescriptor; this.rpcType = rpcType; @@ -59,15 +59,15 @@ public class StubMethodDescriptor implements MethodDescriptor, PackableMethod { this.responsePack = responsePack; this.responseUnpack = responseUnpack; this.requestUnpack = requestUnpack; - this.parameterClasses = new Class[]{requestClass}; + this.parameterClasses = new Class[] {requestClass}; this.returnClass = responseClass; this.paramDesc = ReflectUtils.getDesc(parameterClasses); - this.compatibleParamSignatures = Stream.of(parameterClasses).map(Class::getName).toArray(String[]::new); - this.returnTypes = new Type[]{responseClass, responseClass}; + this.compatibleParamSignatures = + Stream.of(parameterClasses).map(Class::getName).toArray(String[]::new); + this.returnTypes = new Type[] {responseClass, responseClass}; serviceDescriptor.addMethod(this); } - @Override public String getMethodName() { return methodName; diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/StubServiceDescriptor.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/StubServiceDescriptor.java index d2ef41465c..1041bf7fa8 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/StubServiceDescriptor.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/StubServiceDescriptor.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.model; import org.apache.dubbo.common.utils.CollectionUtils; @@ -38,7 +37,8 @@ public class StubServiceDescriptor implements ServiceDescriptor { // to accelerate search private final Map> methods = new HashMap<>(); private final Map> descToMethods = new HashMap<>(); - private final ConcurrentNavigableMap serviceDefinitions = new ConcurrentSkipListMap<>(); + private final ConcurrentNavigableMap serviceDefinitions = + new ConcurrentSkipListMap<>(); public StubServiceDescriptor(String interfaceName, Class interfaceClass) { this.interfaceName = interfaceName; @@ -47,14 +47,15 @@ public class StubServiceDescriptor implements ServiceDescriptor { public void addMethod(MethodDescriptor methodDescriptor) { methods.put(methodDescriptor.getMethodName(), Collections.singletonList(methodDescriptor)); - Map descMap = descToMethods.computeIfAbsent(methodDescriptor.getMethodName(), - k -> new HashMap<>()); + Map descMap = + descToMethods.computeIfAbsent(methodDescriptor.getMethodName(), k -> new HashMap<>()); descMap.put(methodDescriptor.getParamDesc(), methodDescriptor); } public FullServiceDefinition getFullServiceDefinition(String serviceKey) { - return serviceDefinitions.computeIfAbsent(serviceKey, - (k) -> ServiceDefinitionBuilder.buildFullDefinition(serviceInterfaceClass, Collections.emptyMap())); + return serviceDefinitions.computeIfAbsent( + serviceKey, + (k) -> ServiceDefinitionBuilder.buildFullDefinition(serviceInterfaceClass, Collections.emptyMap())); } public String getInterfaceName() { @@ -118,9 +119,10 @@ public class StubServiceDescriptor implements ServiceDescriptor { return false; } StubServiceDescriptor that = (StubServiceDescriptor) o; - return Objects.equals(interfaceName, that.interfaceName) && Objects.equals(serviceInterfaceClass, - that.serviceInterfaceClass) && Objects.equals(methods, that.methods) && Objects.equals(descToMethods, - that.descToMethods); + return Objects.equals(interfaceName, that.interfaceName) + && Objects.equals(serviceInterfaceClass, that.serviceInterfaceClass) + && Objects.equals(methods, that.methods) + && Objects.equals(descToMethods, that.descToMethods); } @Override diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/UnPack.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/UnPack.java index b214e50ce0..d3c6b8ac6f 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/UnPack.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/UnPack.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.model; public interface UnPack { @@ -25,5 +24,4 @@ public interface UnPack { * @throws Exception exception */ Object unpack(byte[] data) throws Exception; - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/WrapperUnPack.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/WrapperUnPack.java index 444309689e..1fd216b807 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/WrapperUnPack.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/model/WrapperUnPack.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.model; public interface WrapperUnPack extends UnPack { @@ -24,5 +23,4 @@ public interface WrapperUnPack extends UnPack { } Object unpack(byte[] data, boolean isReturnTriException) throws Exception; - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/Destroyable.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/Destroyable.java index 2ad9489e3b..7e57cd5a4b 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/Destroyable.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/Destroyable.java @@ -19,5 +19,4 @@ package org.apache.dubbo.rpc.service; public interface Destroyable { void $destroy(); - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/EchoService.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/EchoService.java index 592469d5b9..6e7675fc7e 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/EchoService.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/EchoService.java @@ -29,5 +29,4 @@ public interface EchoService { * @return message. */ Object $echo(Object message); - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/EchoServiceDetector.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/EchoServiceDetector.java index fe3702aefd..948e0d9192 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/EchoServiceDetector.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/EchoServiceDetector.java @@ -24,5 +24,4 @@ public class EchoServiceDetector implements BuiltinServiceDetector { public Class getService() { return EchoService.class; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/GenericException.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/GenericException.java index 39860701f6..3e1920ac01 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/GenericException.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/GenericException.java @@ -31,8 +31,7 @@ public class GenericException extends RuntimeException { private String exceptionMessage; - public GenericException() { - } + public GenericException() {} public GenericException(String exceptionMessage) { super(exceptionMessage); @@ -72,5 +71,4 @@ public class GenericException extends RuntimeException { public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = exceptionMessage; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/GenericService.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/GenericService.java index 1f144eac69..888a92f17b 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/GenericService.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/GenericService.java @@ -37,12 +37,12 @@ public interface GenericService { */ Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException; - default CompletableFuture $invokeAsync(String method, String[] parameterTypes, Object[] args) throws GenericException { + default CompletableFuture $invokeAsync(String method, String[] parameterTypes, Object[] args) + throws GenericException { Object object = $invoke(method, parameterTypes, args); if (object instanceof CompletableFuture) { return (CompletableFuture) object; } return CompletableFuture.completedFuture(object); } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/GenericServiceDetector.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/GenericServiceDetector.java index 29b950e3c9..fbd4bcc532 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/GenericServiceDetector.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/GenericServiceDetector.java @@ -24,5 +24,4 @@ public class GenericServiceDetector implements BuiltinServiceDetector { public Class getService() { return GenericService.class; } - } diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/ServiceDescriptorInternalCache.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/ServiceDescriptorInternalCache.java index 77e55bc7eb..a0a9eac21a 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/ServiceDescriptorInternalCache.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/service/ServiceDescriptorInternalCache.java @@ -20,7 +20,8 @@ import org.apache.dubbo.rpc.model.ReflectionServiceDescriptor; import org.apache.dubbo.rpc.model.ServiceDescriptor; public class ServiceDescriptorInternalCache { - private static final ServiceDescriptor genericServiceDescriptor = new ReflectionServiceDescriptor(GenericService.class); + private static final ServiceDescriptor genericServiceDescriptor = + new ReflectionServiceDescriptor(GenericService.class); private static final ServiceDescriptor echoServiceDescriptor = new ReflectionServiceDescriptor(EchoService.class); public static ServiceDescriptor genericService() { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/support/GroupServiceKeyCache.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/support/GroupServiceKeyCache.java index f040f3c948..9972df84be 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/support/GroupServiceKeyCache.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/support/GroupServiceKeyCache.java @@ -25,7 +25,7 @@ public class GroupServiceKeyCache { private final String serviceGroup; - //ConcurrentMap>> + // ConcurrentMap>> private final ConcurrentMap>> serviceKeyMap; public GroupServiceKeyCache(String serviceGroup) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/rpc/support/ProtocolUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/rpc/support/ProtocolUtils.java index 7b983beed4..b8098ea52e 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/rpc/support/ProtocolUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/rpc/support/ProtocolUtils.java @@ -31,14 +31,13 @@ import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZ public class ProtocolUtils { - private static final ConcurrentMap groupServiceKeyCacheMap = new ConcurrentHashMap<>(); + private static final ConcurrentMap groupServiceKeyCacheMap = + new ConcurrentHashMap<>(); - private ProtocolUtils() { - } + private ProtocolUtils() {} public static String serviceKey(URL url) { - return serviceKey(url.getPort(), url.getPath(), url.getVersion(), - url.getGroup()); + return serviceKey(url.getPort(), url.getPath(), url.getVersion(), url.getGroup()); } public static String serviceKey(int port, String serviceName, String serviceVersion, String serviceGroup) { @@ -53,33 +52,29 @@ public class ProtocolUtils { public static boolean isGeneric(String generic) { return StringUtils.isNotEmpty(generic) - && (GENERIC_SERIALIZATION_DEFAULT.equalsIgnoreCase(generic) /* Normal generalization cal */ - || GENERIC_SERIALIZATION_NATIVE_JAVA.equalsIgnoreCase(generic) /* Streaming generalization call supporting jdk serialization */ - || GENERIC_SERIALIZATION_BEAN.equalsIgnoreCase(generic) - || GENERIC_SERIALIZATION_PROTOBUF.equalsIgnoreCase(generic) - || GENERIC_SERIALIZATION_GSON.equalsIgnoreCase(generic) - || GENERIC_RAW_RETURN.equalsIgnoreCase(generic)); - + && (GENERIC_SERIALIZATION_DEFAULT.equalsIgnoreCase(generic) /* Normal generalization cal */ + || GENERIC_SERIALIZATION_NATIVE_JAVA.equalsIgnoreCase( + generic) /* Streaming generalization call supporting jdk serialization */ + || GENERIC_SERIALIZATION_BEAN.equalsIgnoreCase(generic) + || GENERIC_SERIALIZATION_PROTOBUF.equalsIgnoreCase(generic) + || GENERIC_SERIALIZATION_GSON.equalsIgnoreCase(generic) + || GENERIC_RAW_RETURN.equalsIgnoreCase(generic)); } public static boolean isValidGenericValue(String generic) { return isGeneric(generic) || Boolean.FALSE.toString().equalsIgnoreCase(generic); - } public static boolean isDefaultGenericSerialization(String generic) { - return isGeneric(generic) - && GENERIC_SERIALIZATION_DEFAULT.equalsIgnoreCase(generic); + return isGeneric(generic) && GENERIC_SERIALIZATION_DEFAULT.equalsIgnoreCase(generic); } public static boolean isJavaGenericSerialization(String generic) { - return isGeneric(generic) - && GENERIC_SERIALIZATION_NATIVE_JAVA.equalsIgnoreCase(generic); + return isGeneric(generic) && GENERIC_SERIALIZATION_NATIVE_JAVA.equalsIgnoreCase(generic); } public static boolean isGsonGenericSerialization(String generic) { - return isGeneric(generic) - && GENERIC_SERIALIZATION_GSON.equalsIgnoreCase(generic); + return isGeneric(generic) && GENERIC_SERIALIZATION_GSON.equalsIgnoreCase(generic); } public static boolean isBeanGenericSerialization(String generic) { diff --git a/dubbo-common/src/test/java/com/pojo/Demo2.java b/dubbo-common/src/test/java/com/pojo/Demo2.java index 9f7f5620b9..3b4d8b537a 100644 --- a/dubbo-common/src/test/java/com/pojo/Demo2.java +++ b/dubbo-common/src/test/java/com/pojo/Demo2.java @@ -16,5 +16,4 @@ */ package com.pojo; -public class Demo2 { -} +public class Demo2 {} diff --git a/dubbo-common/src/test/java/com/pojo/Demo3.java b/dubbo-common/src/test/java/com/pojo/Demo3.java index ea1f65baff..1019d8cfe9 100644 --- a/dubbo-common/src/test/java/com/pojo/Demo3.java +++ b/dubbo-common/src/test/java/com/pojo/Demo3.java @@ -16,5 +16,4 @@ */ package com.pojo; -public class Demo3 { -} +public class Demo3 {} diff --git a/dubbo-common/src/test/java/com/pojo/Demo4.java b/dubbo-common/src/test/java/com/pojo/Demo4.java index 3f12cca518..d5ac7d38d4 100644 --- a/dubbo-common/src/test/java/com/pojo/Demo4.java +++ b/dubbo-common/src/test/java/com/pojo/Demo4.java @@ -16,5 +16,4 @@ */ package com.pojo; -public class Demo4 extends Demo3 { -} +public class Demo4 extends Demo3 {} diff --git a/dubbo-common/src/test/java/com/pojo/Demo5.java b/dubbo-common/src/test/java/com/pojo/Demo5.java index e306ed1af5..4db43bb850 100644 --- a/dubbo-common/src/test/java/com/pojo/Demo5.java +++ b/dubbo-common/src/test/java/com/pojo/Demo5.java @@ -16,5 +16,4 @@ */ package com.pojo; -public class Demo5 { -} +public class Demo5 {} diff --git a/dubbo-common/src/test/java/com/pojo/Demo6.java b/dubbo-common/src/test/java/com/pojo/Demo6.java index 890f6e2df8..0cca644b8e 100644 --- a/dubbo-common/src/test/java/com/pojo/Demo6.java +++ b/dubbo-common/src/test/java/com/pojo/Demo6.java @@ -16,5 +16,4 @@ */ package com.pojo; -public class Demo6 { -} +public class Demo6 {} diff --git a/dubbo-common/src/test/java/com/pojo/Demo7.java b/dubbo-common/src/test/java/com/pojo/Demo7.java index 06771c28a4..a45a26ad7f 100644 --- a/dubbo-common/src/test/java/com/pojo/Demo7.java +++ b/dubbo-common/src/test/java/com/pojo/Demo7.java @@ -16,5 +16,4 @@ */ package com.pojo; -public class Demo7 { -} +public class Demo7 {} diff --git a/dubbo-common/src/test/java/com/pojo/Demo8.java b/dubbo-common/src/test/java/com/pojo/Demo8.java index b991d5f3e2..8b873d880d 100644 --- a/dubbo-common/src/test/java/com/pojo/Demo8.java +++ b/dubbo-common/src/test/java/com/pojo/Demo8.java @@ -16,5 +16,4 @@ */ package com.pojo; -public class Demo8 { -} +public class Demo8 {} diff --git a/dubbo-common/src/test/java/com/pojo/DemoException1.java b/dubbo-common/src/test/java/com/pojo/DemoException1.java index 0555fc7207..ae161397cc 100644 --- a/dubbo-common/src/test/java/com/pojo/DemoException1.java +++ b/dubbo-common/src/test/java/com/pojo/DemoException1.java @@ -16,5 +16,4 @@ */ package com.pojo; -public class DemoException1 extends Exception{ -} +public class DemoException1 extends Exception {} diff --git a/dubbo-common/src/test/java/com/pojo/DemoException2.java b/dubbo-common/src/test/java/com/pojo/DemoException2.java index e880cfef7e..c157a53daf 100644 --- a/dubbo-common/src/test/java/com/pojo/DemoException2.java +++ b/dubbo-common/src/test/java/com/pojo/DemoException2.java @@ -16,5 +16,4 @@ */ package com.pojo; -public class DemoException2 extends Exception { -} +public class DemoException2 extends Exception {} diff --git a/dubbo-common/src/test/java/com/pojo/DemoException3.java b/dubbo-common/src/test/java/com/pojo/DemoException3.java index f842b0b4c7..8c6c9adcdd 100644 --- a/dubbo-common/src/test/java/com/pojo/DemoException3.java +++ b/dubbo-common/src/test/java/com/pojo/DemoException3.java @@ -16,5 +16,4 @@ */ package com.pojo; -public class DemoException3 extends DemoException2 { -} +public class DemoException3 extends DemoException2 {} diff --git a/dubbo-common/src/test/java/com/pojo/Simple.java b/dubbo-common/src/test/java/com/pojo/Simple.java index 62a1161292..f2aa52110d 100644 --- a/dubbo-common/src/test/java/com/pojo/Simple.java +++ b/dubbo-common/src/test/java/com/pojo/Simple.java @@ -16,5 +16,4 @@ */ package com.pojo; -public class Simple { -} +public class Simple {} diff --git a/dubbo-common/src/test/java/com/service/DemoService1.java b/dubbo-common/src/test/java/com/service/DemoService1.java index 139fb69624..1a5d631c2a 100644 --- a/dubbo-common/src/test/java/com/service/DemoService1.java +++ b/dubbo-common/src/test/java/com/service/DemoService1.java @@ -16,6 +16,13 @@ */ package com.service; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Vector; + import com.pojo.Demo1; import com.pojo.Demo2; import com.pojo.Demo4; @@ -26,13 +33,6 @@ import com.pojo.Demo8; import com.pojo.DemoException1; import com.pojo.DemoException3; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Vector; - public interface DemoService1 { Demo1 getDemo1(); diff --git a/dubbo-common/src/test/java/com/service/DemoService2.java b/dubbo-common/src/test/java/com/service/DemoService2.java index ac2910bf7c..9106c10e43 100644 --- a/dubbo-common/src/test/java/com/service/DemoService2.java +++ b/dubbo-common/src/test/java/com/service/DemoService2.java @@ -16,5 +16,4 @@ */ package com.service; -public interface DemoService2 extends DemoService1 { -} +public interface DemoService2 extends DemoService1 {} diff --git a/dubbo-common/src/test/java/com/service/DemoService4.java b/dubbo-common/src/test/java/com/service/DemoService4.java index 3df4506ce3..3378891bbe 100644 --- a/dubbo-common/src/test/java/com/service/DemoService4.java +++ b/dubbo-common/src/test/java/com/service/DemoService4.java @@ -17,11 +17,9 @@ package com.service; public abstract class DemoService4> { - public DemoService4() { - } + public DemoService4() {} public DemoService5 getWrapper() { return null; } - } diff --git a/dubbo-common/src/test/java/com/service/DemoService5.java b/dubbo-common/src/test/java/com/service/DemoService5.java index 00b56f7e93..28e61a6edc 100644 --- a/dubbo-common/src/test/java/com/service/DemoService5.java +++ b/dubbo-common/src/test/java/com/service/DemoService5.java @@ -16,5 +16,4 @@ */ package com.service; -public abstract class DemoService5> { -} +public abstract class DemoService5> {} diff --git a/dubbo-common/src/test/java/com/service/Params.java b/dubbo-common/src/test/java/com/service/Params.java index a6fca59845..290e651ea4 100644 --- a/dubbo-common/src/test/java/com/service/Params.java +++ b/dubbo-common/src/test/java/com/service/Params.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.service; import java.io.Serializable; diff --git a/dubbo-common/src/test/java/com/service/Service.java b/dubbo-common/src/test/java/com/service/Service.java index ea2dd950a7..01e5bc2f7c 100644 --- a/dubbo-common/src/test/java/com/service/Service.java +++ b/dubbo-common/src/test/java/com/service/Service.java @@ -1,22 +1,19 @@ /* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. + * 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 com.service; public interface Service { diff --git a/dubbo-common/src/test/java/com/service/User.java b/dubbo-common/src/test/java/com/service/User.java index 4c2b442c55..b2c6081b41 100644 --- a/dubbo-common/src/test/java/com/service/User.java +++ b/dubbo-common/src/test/java/com/service/User.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.service; import java.io.Serializable; diff --git a/dubbo-common/src/test/java/com/service/UserService.java b/dubbo-common/src/test/java/com/service/UserService.java index 65f81562fd..adfa677a18 100644 --- a/dubbo-common/src/test/java/com/service/UserService.java +++ b/dubbo-common/src/test/java/com/service/UserService.java @@ -1,24 +1,19 @@ /* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. + * 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 com.service; -public interface UserService extends Service { - -} +public interface UserService extends Service {} diff --git a/dubbo-common/src/test/java/com/service/deep1/deep2/deep3/DemoService3.java b/dubbo-common/src/test/java/com/service/deep1/deep2/deep3/DemoService3.java index 30b8b7922e..7ebe27fc17 100644 --- a/dubbo-common/src/test/java/com/service/deep1/deep2/deep3/DemoService3.java +++ b/dubbo-common/src/test/java/com/service/deep1/deep2/deep3/DemoService3.java @@ -16,5 +16,4 @@ */ package com.service.deep1.deep2.deep3; -public interface DemoService3 { -} +public interface DemoService3 {} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/BaseServiceMetadataTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/BaseServiceMetadataTest.java index 6a9ed6e8b1..cf0082f411 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/BaseServiceMetadataTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/BaseServiceMetadataTest.java @@ -30,7 +30,8 @@ class BaseServiceMetadataTest { baseServiceMetadata.setGroup("group1"); baseServiceMetadata.setServiceInterfaceName("org.apache.dubbo.common.TestInterface"); baseServiceMetadata.setVersion("1.0.0"); - baseServiceMetadata.setServiceKey(BaseServiceMetadata.buildServiceKey("org.apache.dubbo.common.TestInterface", "group1", "1.0.0")); + baseServiceMetadata.setServiceKey( + BaseServiceMetadata.buildServiceKey("org.apache.dubbo.common.TestInterface", "group1", "1.0.0")); assertEquals(baseServiceMetadata.getGroup(), "group1"); assertEquals(baseServiceMetadata.getServiceInterfaceName(), "org.apache.dubbo.common.TestInterface"); @@ -38,29 +39,43 @@ class BaseServiceMetadataTest { assertEquals(baseServiceMetadata.getServiceKey(), "group1/org.apache.dubbo.common.TestInterface:1.0.0"); assertEquals(baseServiceMetadata.getDisplayServiceKey(), "org.apache.dubbo.common.TestInterface:1.0.0"); - baseServiceMetadata.setServiceKey(BaseServiceMetadata.buildServiceKey("org.apache.dubbo.common.TestInterface", null, null)); + baseServiceMetadata.setServiceKey( + BaseServiceMetadata.buildServiceKey("org.apache.dubbo.common.TestInterface", null, null)); assertEquals(baseServiceMetadata.getServiceKey(), "org.apache.dubbo.common.TestInterface"); - baseServiceMetadata.setServiceKey(BaseServiceMetadata.buildServiceKey("org.apache.dubbo.common.TestInterface", "", "")); + baseServiceMetadata.setServiceKey( + BaseServiceMetadata.buildServiceKey("org.apache.dubbo.common.TestInterface", "", "")); assertEquals(baseServiceMetadata.getServiceKey(), "org.apache.dubbo.common.TestInterface"); - baseServiceMetadata.setVersion("2.0.0"); baseServiceMetadata.generateServiceKey(); assertEquals(baseServiceMetadata.getServiceKey(), "group1/org.apache.dubbo.common.TestInterface:2.0.0"); - assertEquals(BaseServiceMetadata.versionFromServiceKey("group1/org.apache.dubbo.common.TestInterface:1.0.0"), "1.0.0"); - assertEquals(BaseServiceMetadata.groupFromServiceKey("group1/org.apache.dubbo.common.TestInterface:1.0.0"), "group1"); - assertEquals(BaseServiceMetadata.interfaceFromServiceKey("group1/org.apache.dubbo.common.TestInterface:1.0.0"), "org.apache.dubbo.common.TestInterface"); + assertEquals( + BaseServiceMetadata.versionFromServiceKey("group1/org.apache.dubbo.common.TestInterface:1.0.0"), + "1.0.0"); + assertEquals( + BaseServiceMetadata.groupFromServiceKey("group1/org.apache.dubbo.common.TestInterface:1.0.0"), + "group1"); + assertEquals( + BaseServiceMetadata.interfaceFromServiceKey("group1/org.apache.dubbo.common.TestInterface:1.0.0"), + "org.apache.dubbo.common.TestInterface"); assertEquals(DEFAULT_VERSION, BaseServiceMetadata.versionFromServiceKey("")); assertNull(BaseServiceMetadata.groupFromServiceKey("")); assertEquals(BaseServiceMetadata.interfaceFromServiceKey(""), ""); - assertEquals(BaseServiceMetadata.revertDisplayServiceKey("org.apache.dubbo.common.TestInterface:1.0.0").getDisplayServiceKey(), + assertEquals( + BaseServiceMetadata.revertDisplayServiceKey("org.apache.dubbo.common.TestInterface:1.0.0") + .getDisplayServiceKey(), "org.apache.dubbo.common.TestInterface:1.0.0"); - assertEquals(BaseServiceMetadata.revertDisplayServiceKey("org.apache.dubbo.common.TestInterface").getDisplayServiceKey(), + assertEquals( + BaseServiceMetadata.revertDisplayServiceKey("org.apache.dubbo.common.TestInterface") + .getDisplayServiceKey(), "org.apache.dubbo.common.TestInterface:null"); - assertEquals(BaseServiceMetadata.revertDisplayServiceKey(null).getDisplayServiceKey(),"null:null"); - assertEquals(BaseServiceMetadata.revertDisplayServiceKey("org.apache.dubbo.common.TestInterface:1.0.0:1").getDisplayServiceKey(),"null:null"); + assertEquals(BaseServiceMetadata.revertDisplayServiceKey(null).getDisplayServiceKey(), "null:null"); + assertEquals( + BaseServiceMetadata.revertDisplayServiceKey("org.apache.dubbo.common.TestInterface:1.0.0:1") + .getDisplayServiceKey(), + "null:null"); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/InterfaceAddressURLTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/InterfaceAddressURLTest.java index 010edb1b3f..a9d78cdd97 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/InterfaceAddressURLTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/InterfaceAddressURLTest.java @@ -28,27 +28,33 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotSame; class InterfaceAddressURLTest { - private static final String rawURL = "dubbo://10.20.130.230:20880/context/path?version=1.0.0&group=g1&application=provider&timeout=1000&category=provider&side=provider&sayHello.weight=222"; - private static final URL overrideURL = URL.valueOf("override://10.20.130.230:20880/context/path?version=1.0.0&application=morgan&timeout=2000&category=configurators&sayHello.overrideKey=override"); - private static final URL consumerURL = URL.valueOf("consumer://10.20.130.230/context/path?version=2.0.0,1.0.0&group=g2&application=morgan&timeout=3000&side=consumer&sayHello.timeout=5000"); + private static final String rawURL = + "dubbo://10.20.130.230:20880/context/path?version=1.0.0&group=g1&application=provider&timeout=1000&category=provider&side=provider&sayHello.weight=222"; + private static final URL overrideURL = URL.valueOf( + "override://10.20.130.230:20880/context/path?version=1.0.0&application=morgan&timeout=2000&category=configurators&sayHello.overrideKey=override"); + private static final URL consumerURL = URL.valueOf( + "consumer://10.20.130.230/context/path?version=2.0.0,1.0.0&group=g2&application=morgan&timeout=3000&side=consumer&sayHello.timeout=5000"); @Test void testMergeOverriden() { URL url = URL.valueOf(rawURL); - ServiceAddressURL interfaceAddressURL = new DubboServiceAddressURL(url.getUrlAddress(), url.getUrlParam(), null, null); + ServiceAddressURL interfaceAddressURL = + new DubboServiceAddressURL(url.getUrlAddress(), url.getUrlParam(), null, null); assertEquals("1000", interfaceAddressURL.getParameter(TIMEOUT_KEY)); ServiceAddressURL withConsumer = DubboServiceAddressURL.valueOf(rawURL, consumerURL); assertEquals("3000", withConsumer.getParameter(TIMEOUT_KEY)); - ServiceAddressURL withOverriden = DubboServiceAddressURL.valueOf(rawURL, consumerURL, (ServiceConfigURL) overrideURL); + ServiceAddressURL withOverriden = + DubboServiceAddressURL.valueOf(rawURL, consumerURL, (ServiceConfigURL) overrideURL); assertEquals("2000", withOverriden.getParameter(TIMEOUT_KEY)); } @Test void testGetParameter() { URL url = URL.valueOf(rawURL); - ServiceAddressURL interfaceAddressURL = new DubboServiceAddressURL(url.getUrlAddress(), url.getUrlParam(), consumerURL, null); + ServiceAddressURL interfaceAddressURL = + new DubboServiceAddressURL(url.getUrlAddress(), url.getUrlParam(), consumerURL, null); assertEquals("3000", interfaceAddressURL.getParameter(TIMEOUT_KEY)); @@ -66,7 +72,8 @@ class InterfaceAddressURLTest { @Test void testGetMethodParameter() { URL url = URL.valueOf(rawURL); - ServiceAddressURL interfaceAddressURL = new DubboServiceAddressURL(url.getUrlAddress(), url.getUrlParam(), consumerURL, (ServiceConfigURL) overrideURL); + ServiceAddressURL interfaceAddressURL = new DubboServiceAddressURL( + url.getUrlAddress(), url.getUrlParam(), consumerURL, (ServiceConfigURL) overrideURL); assertEquals("5000", interfaceAddressURL.getMethodParameter("sayHello", TIMEOUT_KEY)); assertEquals("2000", interfaceAddressURL.getMethodParameter("non-exist-methods", TIMEOUT_KEY)); @@ -83,13 +90,17 @@ class InterfaceAddressURLTest { assertEquals(url1, url2); // with consumer - ServiceAddressURL withConsumer = new DubboServiceAddressURL(url1.getUrlAddress(), url1.getUrlParam(), consumerURL, null); - ServiceAddressURL withConsumer2 = new DubboServiceAddressURL(url1.getUrlAddress(), url1.getUrlParam(), consumerURL, null); + ServiceAddressURL withConsumer = + new DubboServiceAddressURL(url1.getUrlAddress(), url1.getUrlParam(), consumerURL, null); + ServiceAddressURL withConsumer2 = + new DubboServiceAddressURL(url1.getUrlAddress(), url1.getUrlParam(), consumerURL, null); assertEquals(withConsumer, withConsumer2); - ServiceAddressURL withOverride = new DubboServiceAddressURL(url1.getUrlAddress(), url1.getUrlParam(), consumerURL, (ServiceConfigURL) overrideURL); + ServiceAddressURL withOverride = new DubboServiceAddressURL( + url1.getUrlAddress(), url1.getUrlParam(), consumerURL, (ServiceConfigURL) overrideURL); url2 = url2.addParameter("timeout", "4444"); - ServiceAddressURL withOverride2 = new DubboServiceAddressURL(url2.getUrlAddress(), url2.getUrlParam(), consumerURL, (ServiceConfigURL) overrideURL); + ServiceAddressURL withOverride2 = new DubboServiceAddressURL( + url2.getUrlAddress(), url2.getUrlParam(), consumerURL, (ServiceConfigURL) overrideURL); assertNotEquals(url1, url2); assertEquals(withOverride, withOverride2); } @@ -98,9 +109,11 @@ class InterfaceAddressURLTest { void testToString() { URL url1 = URL.valueOf(rawURL); System.out.println(url1.toString()); - ServiceAddressURL withConsumer = new DubboServiceAddressURL(url1.getUrlAddress(), url1.getUrlParam(), consumerURL, null); + ServiceAddressURL withConsumer = + new DubboServiceAddressURL(url1.getUrlAddress(), url1.getUrlParam(), consumerURL, null); System.out.println(withConsumer.toString()); - ServiceAddressURL withOverride2 = new DubboServiceAddressURL(url1.getUrlAddress(), url1.getUrlParam(), consumerURL, (ServiceConfigURL) overrideURL); + ServiceAddressURL withOverride2 = new DubboServiceAddressURL( + url1.getUrlAddress(), url1.getUrlParam(), consumerURL, (ServiceConfigURL) overrideURL); System.out.println(withOverride2.toString()); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/PojoUtilsForNonPublicStaticTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/PojoUtilsForNonPublicStaticTest.java index 3b7a5fa057..2514695206 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/PojoUtilsForNonPublicStaticTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/PojoUtilsForNonPublicStaticTest.java @@ -47,4 +47,4 @@ class PojoUtilsForNonPublicStaticTest { this.name = name; } } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/ProtocolServiceKeyMatcherTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/ProtocolServiceKeyMatcherTest.java index 4b20f87d9d..61cc3b3e93 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/ProtocolServiceKeyMatcherTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/ProtocolServiceKeyMatcherTest.java @@ -24,84 +24,61 @@ class ProtocolServiceKeyMatcherTest { @Test void testProtocol() { Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( - new ProtocolServiceKey(null, null, null, "dubbo"), - new ProtocolServiceKey(null, null, null, "dubbo") - )); + new ProtocolServiceKey(null, null, null, "dubbo"), new ProtocolServiceKey(null, null, null, "dubbo"))); Assertions.assertFalse(ProtocolServiceKey.Matcher.isMatch( - new ProtocolServiceKey(null, null, null, "dubbo"), - new ProtocolServiceKey(null, null, null, null) - )); + new ProtocolServiceKey(null, null, null, "dubbo"), new ProtocolServiceKey(null, null, null, null))); Assertions.assertFalse(ProtocolServiceKey.Matcher.isMatch( - new ProtocolServiceKey(null, null, null, "dubbo"), - new ProtocolServiceKey("DemoService", null, null, "dubbo") - )); + new ProtocolServiceKey(null, null, null, "dubbo"), + new ProtocolServiceKey("DemoService", null, null, "dubbo"))); Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( - new ProtocolServiceKey(null, null, null, null), - new ProtocolServiceKey(null, null, null, "dubbo") - )); + new ProtocolServiceKey(null, null, null, null), new ProtocolServiceKey(null, null, null, "dubbo"))); Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( - new ProtocolServiceKey(null, null, null, ""), - new ProtocolServiceKey(null, null, null, "dubbo") - )); + new ProtocolServiceKey(null, null, null, ""), new ProtocolServiceKey(null, null, null, "dubbo"))); Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( - new ProtocolServiceKey(null, null, null, "*"), - new ProtocolServiceKey(null, null, null, "dubbo") - )); + new ProtocolServiceKey(null, null, null, "*"), new ProtocolServiceKey(null, null, null, "dubbo"))); Assertions.assertFalse(ProtocolServiceKey.Matcher.isMatch( - new ProtocolServiceKey(null, null, null, "dubbo1,dubbo2"), - new ProtocolServiceKey(null, null, null, "dubbo") - )); + new ProtocolServiceKey(null, null, null, "dubbo1,dubbo2"), + new ProtocolServiceKey(null, null, null, "dubbo"))); Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( - new ProtocolServiceKey(null, null, null, "dubbo1,dubbo2"), - new ProtocolServiceKey(null, null, null, "dubbo1") - )); + new ProtocolServiceKey(null, null, null, "dubbo1,dubbo2"), + new ProtocolServiceKey(null, null, null, "dubbo1"))); Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( - new ProtocolServiceKey(null, null, null, "dubbo1,dubbo2"), - new ProtocolServiceKey(null, null, null, "dubbo2") - )); + new ProtocolServiceKey(null, null, null, "dubbo1,dubbo2"), + new ProtocolServiceKey(null, null, null, "dubbo2"))); Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( - new ProtocolServiceKey(null, null, null, "dubbo1,,dubbo2"), - new ProtocolServiceKey(null, null, null, null) - )); + new ProtocolServiceKey(null, null, null, "dubbo1,,dubbo2"), + new ProtocolServiceKey(null, null, null, null))); Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( - new ProtocolServiceKey(null, null, null, "dubbo1,,dubbo2"), - new ProtocolServiceKey(null, null, null, "") - )); + new ProtocolServiceKey(null, null, null, "dubbo1,,dubbo2"), + new ProtocolServiceKey(null, null, null, ""))); Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( - new ProtocolServiceKey(null, null, null, ",dubbo1,dubbo2"), - new ProtocolServiceKey(null, null, null, null) - )); + new ProtocolServiceKey(null, null, null, ",dubbo1,dubbo2"), + new ProtocolServiceKey(null, null, null, null))); Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( - new ProtocolServiceKey(null, null, null, ",dubbo1,dubbo2"), - new ProtocolServiceKey(null, null, null, "") - )); + new ProtocolServiceKey(null, null, null, ",dubbo1,dubbo2"), + new ProtocolServiceKey(null, null, null, ""))); Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( - new ProtocolServiceKey(null, null, null, "dubbo1,dubbo2,"), - new ProtocolServiceKey(null, null, null, null) - )); + new ProtocolServiceKey(null, null, null, "dubbo1,dubbo2,"), + new ProtocolServiceKey(null, null, null, null))); Assertions.assertTrue(ProtocolServiceKey.Matcher.isMatch( - new ProtocolServiceKey(null, null, null, "dubbo1,dubbo2,"), - new ProtocolServiceKey(null, null, null, "") - )); + new ProtocolServiceKey(null, null, null, "dubbo1,dubbo2,"), + new ProtocolServiceKey(null, null, null, ""))); Assertions.assertFalse(ProtocolServiceKey.Matcher.isMatch( - new ProtocolServiceKey(null, null, null, "dubbo1,,dubbo2"), - new ProtocolServiceKey(null, null, null, "dubbo") - )); + new ProtocolServiceKey(null, null, null, "dubbo1,,dubbo2"), + new ProtocolServiceKey(null, null, null, "dubbo"))); Assertions.assertFalse(ProtocolServiceKey.Matcher.isMatch( - new ProtocolServiceKey(null, null, null, ",dubbo1,dubbo2"), - new ProtocolServiceKey(null, null, null, "dubbo") - )); + new ProtocolServiceKey(null, null, null, ",dubbo1,dubbo2"), + new ProtocolServiceKey(null, null, null, "dubbo"))); Assertions.assertFalse(ProtocolServiceKey.Matcher.isMatch( - new ProtocolServiceKey(null, null, null, "dubbo1,dubbo2,"), - new ProtocolServiceKey(null, null, null, "dubbo") - )); + new ProtocolServiceKey(null, null, null, "dubbo1,dubbo2,"), + new ProtocolServiceKey(null, null, null, "dubbo"))); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/ProtocolServiceKeyTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/ProtocolServiceKeyTest.java index 8d50abbd42..91ae0eaf66 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/ProtocolServiceKeyTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/ProtocolServiceKeyTest.java @@ -46,31 +46,43 @@ class ProtocolServiceKeyTest { ProtocolServiceKey protocolServiceKey4 = new ProtocolServiceKey("DemoService", "1.0.1", "group1", "protocol1"); Assertions.assertNotEquals(protocolServiceKey, protocolServiceKey4); - ProtocolServiceKey protocolServiceKey5 = new ProtocolServiceKey("DemoInterface", "1.0.0", "group1", "protocol1"); + ProtocolServiceKey protocolServiceKey5 = + new ProtocolServiceKey("DemoInterface", "1.0.0", "group1", "protocol1"); Assertions.assertNotEquals(protocolServiceKey, protocolServiceKey5); ServiceKey serviceKey = new ServiceKey("DemoService", "1.0.0", "group1"); Assertions.assertNotEquals(protocolServiceKey, serviceKey); Assertions.assertTrue(protocolServiceKey.isSameWith(protocolServiceKey)); - Assertions.assertTrue(protocolServiceKey.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", ""))); - Assertions.assertTrue(protocolServiceKey.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", null))); - - Assertions.assertFalse(protocolServiceKey.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group2", "protocol1"))); - Assertions.assertFalse(protocolServiceKey.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group2", ""))); - Assertions.assertFalse(protocolServiceKey.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group2", null))); + Assertions.assertTrue( + protocolServiceKey.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", ""))); + Assertions.assertTrue( + protocolServiceKey.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", null))); + Assertions.assertFalse( + protocolServiceKey.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group2", "protocol1"))); + Assertions.assertFalse( + protocolServiceKey.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group2", ""))); + Assertions.assertFalse( + protocolServiceKey.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group2", null))); ProtocolServiceKey protocolServiceKey6 = new ProtocolServiceKey("DemoService", "1.0.0", "group1", null); Assertions.assertTrue(protocolServiceKey6.isSameWith(protocolServiceKey6)); - Assertions.assertTrue(protocolServiceKey6.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", ""))); - Assertions.assertTrue(protocolServiceKey6.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", "protocol1"))); - Assertions.assertTrue(protocolServiceKey6.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", "protocol2"))); + Assertions.assertTrue( + protocolServiceKey6.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", ""))); + Assertions.assertTrue( + protocolServiceKey6.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", "protocol1"))); + Assertions.assertTrue( + protocolServiceKey6.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", "protocol2"))); ProtocolServiceKey protocolServiceKey7 = new ProtocolServiceKey("DemoService", "1.0.0", "group1", "*"); - Assertions.assertFalse(protocolServiceKey7.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", null))); - Assertions.assertFalse(protocolServiceKey7.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", ""))); - Assertions.assertFalse(protocolServiceKey7.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", "protocol1"))); - Assertions.assertFalse(protocolServiceKey7.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", "protocol2"))); + Assertions.assertFalse( + protocolServiceKey7.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", null))); + Assertions.assertFalse( + protocolServiceKey7.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", ""))); + Assertions.assertFalse( + protocolServiceKey7.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", "protocol1"))); + Assertions.assertFalse( + protocolServiceKey7.isSameWith(new ProtocolServiceKey("DemoService", "1.0.0", "group1", "protocol2"))); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/ServiceKeyMatcherTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/ServiceKeyMatcherTest.java index 180a1e21a0..f0c75ed416 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/ServiceKeyMatcherTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/ServiceKeyMatcherTest.java @@ -23,202 +23,117 @@ class ServiceKeyMatcherTest { @Test void testInterface() { - Assertions.assertTrue(ServiceKey.Matcher.isMatch( - new ServiceKey(null, null, null), - new ServiceKey(null, null, null) - )); + Assertions.assertTrue( + ServiceKey.Matcher.isMatch(new ServiceKey(null, null, null), new ServiceKey(null, null, null))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( - new ServiceKey("DemoService", null, null), - new ServiceKey(null, null, null) - )); + new ServiceKey("DemoService", null, null), new ServiceKey(null, null, null))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( - new ServiceKey(null, null, null), - new ServiceKey("DemoService", null, null) - )); + new ServiceKey(null, null, null), new ServiceKey("DemoService", null, null))); - - Assertions.assertFalse(ServiceKey.Matcher.isMatch( - new ServiceKey("*", null, null), - new ServiceKey("DemoService", null, null) - )); - Assertions.assertFalse(ServiceKey.Matcher.isMatch( - new ServiceKey("*", null, null), - new ServiceKey(null, null, null) - )); + Assertions.assertFalse( + ServiceKey.Matcher.isMatch(new ServiceKey("*", null, null), new ServiceKey("DemoService", null, null))); + Assertions.assertFalse( + ServiceKey.Matcher.isMatch(new ServiceKey("*", null, null), new ServiceKey(null, null, null))); } @Test void testVersion() { - Assertions.assertTrue(ServiceKey.Matcher.isMatch( - new ServiceKey(null, "1.0.0", null), - new ServiceKey(null, "1.0.0", null) - )); - Assertions.assertTrue(ServiceKey.Matcher.isMatch( - new ServiceKey(null, null, null), - new ServiceKey(null, null, null) - )); - Assertions.assertFalse(ServiceKey.Matcher.isMatch( - new ServiceKey(null, "1.0.0", null), - new ServiceKey(null, null, null) - )); - Assertions.assertFalse(ServiceKey.Matcher.isMatch( - new ServiceKey(null, null, null), - new ServiceKey(null, "1.0.0", null) - )); + Assertions.assertTrue( + ServiceKey.Matcher.isMatch(new ServiceKey(null, "1.0.0", null), new ServiceKey(null, "1.0.0", null))); + Assertions.assertTrue( + ServiceKey.Matcher.isMatch(new ServiceKey(null, null, null), new ServiceKey(null, null, null))); + Assertions.assertFalse( + ServiceKey.Matcher.isMatch(new ServiceKey(null, "1.0.0", null), new ServiceKey(null, null, null))); + Assertions.assertFalse( + ServiceKey.Matcher.isMatch(new ServiceKey(null, null, null), new ServiceKey(null, "1.0.0", null))); Assertions.assertTrue(ServiceKey.Matcher.isMatch( - new ServiceKey(null, "1.0.0,1.0.1", null), - new ServiceKey(null, "1.0.0", null) - )); + new ServiceKey(null, "1.0.0,1.0.1", null), new ServiceKey(null, "1.0.0", null))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( - new ServiceKey(null, "1.0.0,1.0.1", null), - new ServiceKey(null, "1.0.2", null) - )); - + new ServiceKey(null, "1.0.0,1.0.1", null), new ServiceKey(null, "1.0.2", null))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( - new ServiceKey(null, "1.0.0,1.0.1", null), - new ServiceKey(null, null, null) - )); + new ServiceKey(null, "1.0.0,1.0.1", null), new ServiceKey(null, null, null))); Assertions.assertTrue(ServiceKey.Matcher.isMatch( - new ServiceKey(null, ",1.0.0,1.0.1", null), - new ServiceKey(null, null, null) - )); - Assertions.assertTrue(ServiceKey.Matcher.isMatch( - new ServiceKey(null, ",1.0.0,1.0.1", null), - new ServiceKey(null, "", null) - )); + new ServiceKey(null, ",1.0.0,1.0.1", null), new ServiceKey(null, null, null))); + Assertions.assertTrue( + ServiceKey.Matcher.isMatch(new ServiceKey(null, ",1.0.0,1.0.1", null), new ServiceKey(null, "", null))); Assertions.assertTrue(ServiceKey.Matcher.isMatch( - new ServiceKey(null, "1.0.0,,1.0.1", null), - new ServiceKey(null, null, null) - )); - Assertions.assertTrue(ServiceKey.Matcher.isMatch( - new ServiceKey(null, "1.0.0,,1.0.1", null), - new ServiceKey(null, "", null) - )); + new ServiceKey(null, "1.0.0,,1.0.1", null), new ServiceKey(null, null, null))); + Assertions.assertTrue( + ServiceKey.Matcher.isMatch(new ServiceKey(null, "1.0.0,,1.0.1", null), new ServiceKey(null, "", null))); Assertions.assertTrue(ServiceKey.Matcher.isMatch( - new ServiceKey(null, "1.0.0,1.0.1,", null), - new ServiceKey(null, null, null) - )); - Assertions.assertTrue(ServiceKey.Matcher.isMatch( - new ServiceKey(null, "1.0.0,1.0.1,", null), - new ServiceKey(null, "", null) - )); + new ServiceKey(null, "1.0.0,1.0.1,", null), new ServiceKey(null, null, null))); + Assertions.assertTrue( + ServiceKey.Matcher.isMatch(new ServiceKey(null, "1.0.0,1.0.1,", null), new ServiceKey(null, "", null))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( - new ServiceKey(null, "1.0.0,1.0.1", null), - new ServiceKey(null, null, null) - )); - Assertions.assertFalse(ServiceKey.Matcher.isMatch( - new ServiceKey(null, "1.0.0,1.0.1", null), - new ServiceKey(null, "", null) - )); + new ServiceKey(null, "1.0.0,1.0.1", null), new ServiceKey(null, null, null))); + Assertions.assertFalse( + ServiceKey.Matcher.isMatch(new ServiceKey(null, "1.0.0,1.0.1", null), new ServiceKey(null, "", null))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( - new ServiceKey(null, ",1.0.0,1.0.1", null), - new ServiceKey(null, "1.0.2", null) - )); + new ServiceKey(null, ",1.0.0,1.0.1", null), new ServiceKey(null, "1.0.2", null))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( - new ServiceKey(null, ",1.0.0,1.0.1", null), - new ServiceKey(null, "1.0.2", null) - )); + new ServiceKey(null, ",1.0.0,1.0.1", null), new ServiceKey(null, "1.0.2", null))); - - Assertions.assertTrue(ServiceKey.Matcher.isMatch( - new ServiceKey(null, "*", null), - new ServiceKey(null, null, null) - )); - Assertions.assertTrue(ServiceKey.Matcher.isMatch( - new ServiceKey(null, "*", null), - new ServiceKey(null, "", null) - )); - Assertions.assertTrue(ServiceKey.Matcher.isMatch( - new ServiceKey(null, "*", null), - new ServiceKey(null, "1.0.0", null) - )); + Assertions.assertTrue( + ServiceKey.Matcher.isMatch(new ServiceKey(null, "*", null), new ServiceKey(null, null, null))); + Assertions.assertTrue( + ServiceKey.Matcher.isMatch(new ServiceKey(null, "*", null), new ServiceKey(null, "", null))); + Assertions.assertTrue( + ServiceKey.Matcher.isMatch(new ServiceKey(null, "*", null), new ServiceKey(null, "1.0.0", null))); } @Test void testGroup() { - Assertions.assertTrue(ServiceKey.Matcher.isMatch( - new ServiceKey(null, null, "group1"), - new ServiceKey(null, null, "group1") - )); - Assertions.assertFalse(ServiceKey.Matcher.isMatch( - new ServiceKey(null, null, "group1"), - new ServiceKey(null, null, null) - )); - Assertions.assertFalse(ServiceKey.Matcher.isMatch( - new ServiceKey(null, null, null), - new ServiceKey(null, null, "group1") - )); + Assertions.assertTrue( + ServiceKey.Matcher.isMatch(new ServiceKey(null, null, "group1"), new ServiceKey(null, null, "group1"))); + Assertions.assertFalse( + ServiceKey.Matcher.isMatch(new ServiceKey(null, null, "group1"), new ServiceKey(null, null, null))); + Assertions.assertFalse( + ServiceKey.Matcher.isMatch(new ServiceKey(null, null, null), new ServiceKey(null, null, "group1"))); Assertions.assertTrue(ServiceKey.Matcher.isMatch( - new ServiceKey(null, null, "group1, group2"), - new ServiceKey(null, null, "group1") - )); + new ServiceKey(null, null, "group1, group2"), new ServiceKey(null, null, "group1"))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( - new ServiceKey(null, null, "group2, group3"), - new ServiceKey(null, null, "group1") - )); + new ServiceKey(null, null, "group2, group3"), new ServiceKey(null, null, "group1"))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( - new ServiceKey(null, null, "group2, group3"), - new ServiceKey(null, null, null) - )); + new ServiceKey(null, null, "group2, group3"), new ServiceKey(null, null, null))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( - new ServiceKey(null, null, "group2, group3"), - new ServiceKey(null, null, "") - )); + new ServiceKey(null, null, "group2, group3"), new ServiceKey(null, null, ""))); + + Assertions.assertTrue( + ServiceKey.Matcher.isMatch(new ServiceKey(null, null, ",group2"), new ServiceKey(null, null, ""))); + + Assertions.assertTrue( + ServiceKey.Matcher.isMatch(new ServiceKey(null, null, "group2,"), new ServiceKey(null, null, ""))); Assertions.assertTrue(ServiceKey.Matcher.isMatch( - new ServiceKey(null, null, ",group2"), - new ServiceKey(null, null, "") - )); - - Assertions.assertTrue(ServiceKey.Matcher.isMatch( - new ServiceKey(null, null, "group2,"), - new ServiceKey(null, null, "") - )); - - Assertions.assertTrue(ServiceKey.Matcher.isMatch( - new ServiceKey(null, null, "group2, ,group3"), - new ServiceKey(null, null, "") - )); + new ServiceKey(null, null, "group2, ,group3"), new ServiceKey(null, null, ""))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( - new ServiceKey(null, null, ",group2"), - new ServiceKey(null, null, "group1") - )); + new ServiceKey(null, null, ",group2"), new ServiceKey(null, null, "group1"))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( - new ServiceKey(null, null, "group2,"), - new ServiceKey(null, null, "group1") - )); + new ServiceKey(null, null, "group2,"), new ServiceKey(null, null, "group1"))); Assertions.assertFalse(ServiceKey.Matcher.isMatch( - new ServiceKey(null, null, "group2, ,group3"), - new ServiceKey(null, null, "group1") - )); + new ServiceKey(null, null, "group2, ,group3"), new ServiceKey(null, null, "group1"))); - Assertions.assertTrue(ServiceKey.Matcher.isMatch( - new ServiceKey(null, null, "*"), - new ServiceKey(null, null, "") - )); + Assertions.assertTrue( + ServiceKey.Matcher.isMatch(new ServiceKey(null, null, "*"), new ServiceKey(null, null, ""))); - Assertions.assertTrue(ServiceKey.Matcher.isMatch( - new ServiceKey(null, null, "*"), - new ServiceKey(null, null, null) - )); + Assertions.assertTrue( + ServiceKey.Matcher.isMatch(new ServiceKey(null, null, "*"), new ServiceKey(null, null, null))); - Assertions.assertTrue(ServiceKey.Matcher.isMatch( - new ServiceKey(null, null, "*"), - new ServiceKey(null, null, "group1") - )); + Assertions.assertTrue( + ServiceKey.Matcher.isMatch(new ServiceKey(null, null, "*"), new ServiceKey(null, null, "group1"))); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/ServiceKeyTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/ServiceKeyTest.java index d0833c6029..24a47c4dff 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/ServiceKeyTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/ServiceKeyTest.java @@ -51,4 +51,4 @@ class ServiceKeyTest { ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey("DemoService", "1.0.0", "group1", "protocol1"); Assertions.assertNotEquals(serviceKey, protocolServiceKey); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/URLBuilderTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/URLBuilderTest.java index 219f9d9759..aa6cc9f641 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/URLBuilderTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/URLBuilderTest.java @@ -19,12 +19,12 @@ package org.apache.dubbo.common; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.NetUtils; -import org.junit.jupiter.api.Test; - import java.util.Arrays; import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Test; + import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; @@ -37,7 +37,8 @@ class URLBuilderTest { @Test void shouldAddParameter() { - URL url1 = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); + URL url1 = URL.valueOf( + "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); URL url2 = URLBuilder.from(url1) .addParameter("newKey1", "newValue1") // string .addParameter("newKey2", 2) // int @@ -51,16 +52,16 @@ class URLBuilderTest { @Test void testDefault() { ServiceConfigURL url1 = URLBuilder.from(URL.valueOf("")) - .addParameter("timeout", "1234") - .addParameter("default.timeout", "5678") - .build(); + .addParameter("timeout", "1234") + .addParameter("default.timeout", "5678") + .build(); assertThat(url1.getParameter("timeout"), equalTo("1234")); assertThat(url1.getParameter("default.timeout"), equalTo("5678")); ServiceConfigURL url2 = URLBuilder.from(URL.valueOf("")) - .addParameter("default.timeout", "5678") - .build(); + .addParameter("default.timeout", "5678") + .build(); assertThat(url2.getParameter("timeout"), equalTo("5678")); assertThat(url2.getParameter("default.timeout"), equalTo("5678")); @@ -68,7 +69,8 @@ class URLBuilderTest { @Test void shouldSet() { - URL url1 = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); + URL url1 = URL.valueOf( + "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); int port = NetUtils.getAvailablePort(); URL url2 = URLBuilder.from(url1) .setProtocol("rest") @@ -86,25 +88,23 @@ class URLBuilderTest { assertThat(url2.getPath(), equalTo("newContext")); int port2 = NetUtils.getAvailablePort(); - url2 = URLBuilder.from(url1) - .setAddress("newHost2:"+ port2) - .build(); + url2 = URLBuilder.from(url1).setAddress("newHost2:" + port2).build(); assertThat(url2.getHost(), equalTo("newHost2")); assertThat(url2.getPort(), equalTo(port2)); } @Test void shouldClearParameters() { - URL url1 = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); - URL url2 = URLBuilder.from(url1) - .clearParameters() - .build(); + URL url1 = URL.valueOf( + "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); + URL url2 = URLBuilder.from(url1).clearParameters().build(); assertThat(url2.getParameters().size(), equalTo(0)); } @Test void shouldRemoveParameters() { - URL url1 = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&key2=v2"); + URL url1 = URL.valueOf( + "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&key2=v2"); URL url2 = URLBuilder.from(url1) .removeParameters(Arrays.asList("key2", "application")) .build(); @@ -114,7 +114,8 @@ class URLBuilderTest { @Test void shouldAddIfAbsent() { - URL url1 = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&key2=v2"); + URL url1 = URL.valueOf( + "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&key2=v2"); URL url2 = URLBuilder.from(url1) .addParameterIfAbsent("absentKey", "absentValue") .addParameterIfAbsent("version", "2.0.0") // should not override @@ -125,7 +126,8 @@ class URLBuilderTest { @Test void shouldAddParameters() { - URL url1 = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&key2=v2"); + URL url1 = URL.valueOf( + "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&key2=v2"); // string pairs test URL url2 = URLBuilder.from(url1) @@ -135,32 +137,29 @@ class URLBuilderTest { assertThat(url2.getParameter("absentKey1"), equalTo("absentValue1")); // map test - Map parameters = new HashMap(){ + Map parameters = new HashMap() { { this.put("version", "2.0.0"); this.put("absentKey2", "absentValue2"); } }; - url2 = URLBuilder.from(url1) - .addParameters(parameters) - .build(); + url2 = URLBuilder.from(url1).addParameters(parameters).build(); assertThat(url2.getParameter("version"), equalTo("2.0.0")); assertThat(url2.getParameter("absentKey2"), equalTo("absentValue2")); } @Test void shouldAddParametersIfAbsent() { - URL url1 = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&key2=v2"); + URL url1 = URL.valueOf( + "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&key2=v2"); - Map parameters = new HashMap(){ + Map parameters = new HashMap() { { this.put("version", "2.0.0"); this.put("absentKey", "absentValue"); } }; - URL url2 = URLBuilder.from(url1) - .addParametersIfAbsent(parameters) - .build(); + URL url2 = URLBuilder.from(url1).addParametersIfAbsent(parameters).build(); assertThat(url2.getParameter("version"), equalTo("1.0.0")); assertThat(url2.getParameter("absentKey"), equalTo("absentValue")); } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/URLStrParserTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/URLStrParserTest.java index 67d13caa2b..4c4c218c35 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/URLStrParserTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/URLStrParserTest.java @@ -16,13 +16,13 @@ */ package org.apache.dubbo.common; +import java.util.HashSet; +import java.util.Set; + import net.bytebuddy.utility.RandomString; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.HashSet; -import java.util.Set; - import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; @@ -38,7 +38,8 @@ class URLStrParserTest { testCases.add("dubbo://192.168.1.1"); testCases.add("dubbo://192.168.1.1?"); testCases.add("dubbo://127.0.0.1?test=中文测试"); - testCases.add("dubbo://admin:admin123@192.168.1.41:28113/org.test.api.DemoService$Iface?anyhost=true&application=demo-service&dubbo=2.6.1&generic=false&interface=org.test.api.DemoService$Iface&methods=orbCompare,checkText,checkPicture&pid=65557&revision=1.4.17&service.filter=bootMetrics&side=provider&status=server&threads=200×tamp=1583136298859&version=1.0.0"); + testCases.add( + "dubbo://admin:admin123@192.168.1.41:28113/org.test.api.DemoService$Iface?anyhost=true&application=demo-service&dubbo=2.6.1&generic=false&interface=org.test.api.DemoService$Iface&methods=orbCompare,checkText,checkPicture&pid=65557&revision=1.4.17&service.filter=bootMetrics&side=provider&status=server&threads=200×tamp=1583136298859&version=1.0.0"); // super long text test testCases.add("dubbo://192.168.1.1/" + RandomString.make(10240)); testCases.add("file:/path/to/file.txt"); @@ -56,7 +57,8 @@ class URLStrParserTest { errorEncodedCases.add("dubbo%3a192.168.1.1%3fabc%3dabc"); errorEncodedCases.add("%3a%2f%2f192.168.1.1%3fabc%3dabc"); errorEncodedCases.add("%3a%2f192.168.1.1%3fabc%3dabc"); - errorEncodedCases.add("dubbo%3a%2f%2f127.0.0.1%3ftest%3d%e2%96%b2%e2%96%bc%e2%97%80%e2%96%b6%e2%86%90%e2%86%91%e2%86%92%e2%86%93%e2%86%94%e2%86%95%e2%88%9e%c2%b1%e9%be%98%e9%9d%90%e9%bd%89%9%d%b"); + errorEncodedCases.add( + "dubbo%3a%2f%2f127.0.0.1%3ftest%3d%e2%96%b2%e2%96%bc%e2%97%80%e2%96%b6%e2%86%90%e2%86%91%e2%86%92%e2%86%93%e2%86%94%e2%86%95%e2%88%9e%c2%b1%e9%be%98%e9%9d%90%e9%bd%89%9%d%b"); } @Test @@ -66,8 +68,7 @@ class URLStrParserTest { }); errorEncodedCases.forEach(errorCase -> { - Assertions.assertThrows(RuntimeException.class, - () -> URLStrParser.parseEncodedStr(errorCase)); + Assertions.assertThrows(RuntimeException.class, () -> URLStrParser.parseEncodedStr(errorCase)); }); } @@ -78,8 +79,7 @@ class URLStrParserTest { }); errorDecodedCases.forEach(errorCase -> { - Assertions.assertThrows(RuntimeException.class, - () -> URLStrParser.parseDecodedStr(errorCase)); + Assertions.assertThrows(RuntimeException.class, () -> URLStrParser.parseDecodedStr(errorCase)); }); } @@ -93,5 +93,4 @@ class URLStrParserTest { assertThat(url2.getParameter("timeout"), equalTo("5678")); assertThat(url2.getParameter("default.timeout"), equalTo("5678")); } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/URLTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/URLTest.java index 78c96e2891..ee03745d3d 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/URLTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/URLTest.java @@ -19,15 +19,15 @@ package org.apache.dubbo.common; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.CollectionUtils; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.function.Predicate; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.OS_NAME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.OS_WIN_PREFIX; import static org.hamcrest.CoreMatchers.anyOf; @@ -45,7 +45,8 @@ class URLTest { @Test void test_ignore_pond() { - URL url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path#index?version=1.0.0&id=org.apache.dubbo.config.RegistryConfig#0"); + URL url = URL.valueOf( + "dubbo://admin:hello1234@10.20.130.230:20880/context/path#index?version=1.0.0&id=org.apache.dubbo.config.RegistryConfig#0"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); @@ -193,7 +194,6 @@ class URLTest { assertEquals("user1/router.js", url.getPath()); assertEquals(0, url.getParameters().size()); - url = URL.valueOf("file:/home/user1/router.js"); assertURLStrDecoder(url); assertEquals("file", url.getProtocol()); @@ -307,7 +307,8 @@ class URLTest { assertEquals("1.0.0", url.getVersion()); assertEquals("morgan", url.getParameter("application")); - url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&noValue="); + url = URL.valueOf( + "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&noValue="); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); assertEquals("admin", url.getUsername()); @@ -369,7 +370,8 @@ class URLTest { @Test void test_getAddress() throws Exception { - URL url1 = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); + URL url1 = URL.valueOf( + "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url1); assertEquals("10.20.130.230:20880", url1.getAddress()); } @@ -387,7 +389,8 @@ class URLTest { @Test void test_equals() throws Exception { - URL url1 = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); + URL url1 = URL.valueOf( + "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url1); Map params = new HashMap(); @@ -401,27 +404,34 @@ class URLTest { @Test void test_toString() throws Exception { - URL url1 = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); + URL url1 = URL.valueOf( + "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url1); - assertThat(url1.toString(), anyOf( - equalTo("dubbo://10.20.130.230:20880/context/path?version=1.0.0&application=morgan"), - equalTo("dubbo://10.20.130.230:20880/context/path?application=morgan&version=1.0.0")) - ); + assertThat( + url1.toString(), + anyOf( + equalTo("dubbo://10.20.130.230:20880/context/path?version=1.0.0&application=morgan"), + equalTo("dubbo://10.20.130.230:20880/context/path?application=morgan&version=1.0.0"))); } @Test void test_toFullString() throws Exception { - URL url1 = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); + URL url1 = URL.valueOf( + "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url1); - assertThat(url1.toFullString(), anyOf( - equalTo("dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"), - equalTo("dubbo://admin:hello1234@10.20.130.230:20880/context/path?application=morgan&version=1.0.0")) - ); + assertThat( + url1.toFullString(), + anyOf( + equalTo( + "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"), + equalTo( + "dubbo://admin:hello1234@10.20.130.230:20880/context/path?application=morgan&version=1.0.0"))); } @Test void test_set_methods() throws Exception { - URL url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); + URL url = URL.valueOf( + "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); url = url.setHost("host"); @@ -511,7 +521,8 @@ class URLTest { @Test void test_removeParameters() throws Exception { - URL url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&k1=v1&k2=v2"); + URL url = URL.valueOf( + "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&k1=v1&k2=v2"); assertURLStrDecoder(url); url = url.removeParameter("version"); @@ -529,7 +540,8 @@ class URLTest { assertEquals("v2", url.getParameter("k2")); assertNull(url.getVersion()); - url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&k1=v1&k2=v2"); + url = URL.valueOf( + "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&k1=v1&k2=v2"); url = url.removeParameters("version", "application", "NotExistedKey"); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); @@ -545,7 +557,8 @@ class URLTest { assertNull(url.getVersion()); assertNull(url.getParameter("application")); - url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&k1=v1&k2=v2"); + url = URL.valueOf( + "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&k1=v1&k2=v2"); url = url.removeParameters(Arrays.asList("version", "application")); assertURLStrDecoder(url); assertEquals("dubbo", url.getProtocol()); @@ -589,7 +602,6 @@ class URLTest { assertSame(newUrl, url); } - @Test void test_addParameters() throws Exception { URL url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?application=morgan"); @@ -680,7 +692,8 @@ class URLTest { assertSame(url, newUrl); } { - URL url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?application=morgan&k1=v1&k2=v2"); + URL url = URL.valueOf( + "dubbo://admin:hello1234@10.20.130.230:20880/context/path?application=morgan&k1=v1&k2=v2"); URL newUrl = url.addParameters(CollectionUtils.toStringMap("k1", "v1", "k2", "v2")); assertURLStrDecoder(url); @@ -727,7 +740,8 @@ class URLTest { @Test void test_javaNetUrl() throws Exception { - java.net.URL url = new java.net.URL("http://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan#anchor1"); + java.net.URL url = new java.net.URL( + "http://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan#anchor1"); assertEquals("http", url.getProtocol()); assertEquals("admin:hello1234", url.getUserInfo()); @@ -805,11 +819,11 @@ class URLTest { assertEquals("morgan", url.getParameter("application")); } - @Test void testIpV6Address() { // Test username or password contains "@" - URL url = URL.valueOf("ad@min111:haha@1234@2001:0db8:85a3:08d3:1319:8a2e:0370:7344:20880/context/path?version=1.0.0&application=morgan"); + URL url = URL.valueOf( + "ad@min111:haha@1234@2001:0db8:85a3:08d3:1319:8a2e:0370:7344:20880/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertEquals("ad@min111", url.getUsername()); @@ -825,7 +839,8 @@ class URLTest { @Test void testIpV6AddressWithScopeId() { - URL url = URL.valueOf("2001:0db8:85a3:08d3:1319:8a2e:0370:7344%5/context/path?version=1.0.0&application=morgan"); + URL url = + URL.valueOf("2001:0db8:85a3:08d3:1319:8a2e:0370:7344%5/context/path?version=1.0.0&application=morgan"); assertURLStrDecoder(url); assertNull(url.getProtocol()); assertEquals("2001:0db8:85a3:08d3:1319:8a2e:0370:7344%5", url.getHost()); @@ -849,11 +864,13 @@ class URLTest { assertURLStrDecoder(url1); Assertions.assertEquals("org.apache.dubbo.test.interfaceName", url1.getServiceKey()); - URL url2 = URL.valueOf("10.20.130.230:20880/org.apache.dubbo.test.interfaceName?interface=org.apache.dubbo.test.interfaceName"); + URL url2 = URL.valueOf( + "10.20.130.230:20880/org.apache.dubbo.test.interfaceName?interface=org.apache.dubbo.test.interfaceName"); assertURLStrDecoder(url2); Assertions.assertEquals("org.apache.dubbo.test.interfaceName", url2.getServiceKey()); - URL url3 = URL.valueOf("10.20.130.230:20880/org.apache.dubbo.test.interfaceName?interface=org.apache.dubbo.test.interfaceName&group=group1&version=1.0.0"); + URL url3 = URL.valueOf( + "10.20.130.230:20880/org.apache.dubbo.test.interfaceName?interface=org.apache.dubbo.test.interfaceName&group=group1&version=1.0.0"); assertURLStrDecoder(url3); Assertions.assertEquals("group1/org.apache.dubbo.test.interfaceName:1.0.0", url3.getServiceKey()); @@ -861,22 +878,26 @@ class URLTest { assertURLStrDecoder(url4); Assertions.assertEquals("context/path", url4.getPathKey()); - URL url5 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group1&version=1.0.0"); + URL url5 = URL.valueOf( + "10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group1&version=1.0.0"); assertURLStrDecoder(url5); Assertions.assertEquals("group1/context/path:1.0.0", url5.getPathKey()); } @Test void testGetColonSeparatedKey() { - URL url1 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group&version=1.0.0"); + URL url1 = URL.valueOf( + "10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group&version=1.0.0"); assertURLStrDecoder(url1); Assertions.assertEquals("org.apache.dubbo.test.interfaceName:1.0.0:group", url1.getColonSeparatedKey()); - URL url2 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&version=1.0.0"); + URL url2 = URL.valueOf( + "10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&version=1.0.0"); assertURLStrDecoder(url2); Assertions.assertEquals("org.apache.dubbo.test.interfaceName:1.0.0:", url2.getColonSeparatedKey()); - URL url3 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group"); + URL url3 = URL.valueOf( + "10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group"); assertURLStrDecoder(url3); Assertions.assertEquals("org.apache.dubbo.test.interfaceName::group", url3.getColonSeparatedKey()); @@ -888,7 +909,8 @@ class URLTest { assertURLStrDecoder(url5); Assertions.assertEquals("org.apache.dubbo.test.interfaceName::", url5.getColonSeparatedKey()); - URL url6 = URL.valueOf("10.20.130.230:20880/org.apache.dubbo.test.interfaceName?interface=org.apache.dubbo.test.interfaceName1"); + URL url6 = URL.valueOf( + "10.20.130.230:20880/org.apache.dubbo.test.interfaceName?interface=org.apache.dubbo.test.interfaceName1"); assertURLStrDecoder(url6); Assertions.assertEquals("org.apache.dubbo.test.interfaceName1::", url6.getColonSeparatedKey()); } @@ -908,7 +930,6 @@ class URLTest { assertURLStrDecoder(url); } - /** * Test {@link URL#getParameters(Predicate)} method * @@ -916,7 +937,8 @@ class URLTest { */ @Test void testGetParameters() { - URL url = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group&version=1.0.0"); + URL url = URL.valueOf( + "10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group&version=1.0.0"); Map parameters = url.getParameters(i -> "version".equals(i)); String version = parameters.get("version"); assertEquals(1, parameters.size()); @@ -932,40 +954,43 @@ class URLTest { @Test void testEquals() { - URL url1 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group&version=1.0.0"); - URL url2 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group&version=1.0.0"); + URL url1 = URL.valueOf( + "10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group&version=1.0.0"); + URL url2 = URL.valueOf( + "10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group&version=1.0.0"); Assertions.assertEquals(url1, url2); - URL url3 = URL.valueOf("10.20.130.230:20881/context/path?interface=org.apache.dubbo.test.interfaceName&group=group&version=1.0.0"); + URL url3 = URL.valueOf( + "10.20.130.230:20881/context/path?interface=org.apache.dubbo.test.interfaceName&group=group&version=1.0.0"); Assertions.assertNotEquals(url1, url3); - URL url4 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&weight=10&group=group&version=1.0.0"); + URL url4 = URL.valueOf( + "10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&weight=10&group=group&version=1.0.0"); Assertions.assertNotEquals(url1, url4); - URL url5 = URL.valueOf("10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&weight=10&group=group&version=1.0.0"); + URL url5 = URL.valueOf( + "10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&weight=10&group=group&version=1.0.0"); Assertions.assertEquals(url4, url5); - URL url6 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + - "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&generic=true&interface=" + - "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false×tamp=1599556506417"); - URL url7 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + - "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&generic=true&interface=" + - "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false×tamp=2299556506417"); + URL url6 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&generic=true&interface=" + + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false×tamp=1599556506417"); + URL url7 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&generic=true&interface=" + + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false×tamp=2299556506417"); assertEquals(url6, url7); - URL url8 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + - "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&interface=" + - "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false×tamp=2299556506417"); + URL url8 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&interface=" + + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false×tamp=2299556506417"); assertNotEquals(url7, url8); - URL url9 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + - "dubbo-demo-api-consumer&category=consumers&check=true&dubbo=2.0.2&interface=" + - "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false×tamp=2299556506417"); + URL url9 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + + "dubbo-demo-api-consumer&category=consumers&check=true&dubbo=2.0.2&interface=" + + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false×tamp=2299556506417"); assertNotEquals(url8, url9); - } - @Test void testEqualsWithPassword() { URL url1 = URL.valueOf("ad@min:hello@1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); @@ -1004,9 +1029,12 @@ class URLTest { @Test void testEqualsWithProtocol() { - URL url1 = URL.valueOf("dubbo://ad@min:hello@1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); - URL url2 = URL.valueOf("file://ad@min:hello@1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); - URL url3 = URL.valueOf("dubbo://ad@min:hello@1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); + URL url1 = URL.valueOf( + "dubbo://ad@min:hello@1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); + URL url2 = URL.valueOf( + "file://ad@min:hello@1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); + URL url3 = URL.valueOf( + "dubbo://ad@min:hello@1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan"); boolean actual1 = url1.equals(url2); boolean actual2 = url1.equals(url3); @@ -1028,36 +1056,37 @@ class URLTest { @Test void testHashcode() { - URL url1 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + - "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&generic=true&interface=" + - "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false×tamp=1599556506417"); - URL url2 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + - "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&generic=true&interface=" + - "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false×tamp=2299556506417"); + URL url1 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&generic=true&interface=" + + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false×tamp=1599556506417"); + URL url2 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&generic=true&interface=" + + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false×tamp=2299556506417"); assertEquals(url1.hashCode(), url2.hashCode()); - URL url3 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + - "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&interface=" + - "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false×tamp=2299556506417"); + URL url3 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&interface=" + + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false×tamp=2299556506417"); assertNotEquals(url2.hashCode(), url3.hashCode()); - URL url4 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + - "dubbo-demo-api-consumer&category=consumers&check=true&dubbo=2.0.2&interface=" + - "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false×tamp=2299556506417"); + URL url4 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + + "dubbo-demo-api-consumer&category=consumers&check=true&dubbo=2.0.2&interface=" + + "org.apache.dubbo.demo.DemoService&pid=7375&side=consumer&sticky=false×tamp=2299556506417"); assertNotEquals(url3.hashCode(), url4.hashCode()); } @Test void testParameterContainPound() { URL url = URL.valueOf( - "dubbo://ad@min:hello@1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan£=abcd#efg&protocol=registry"); + "dubbo://ad@min:hello@1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan£=abcd#efg&protocol=registry"); Assertions.assertEquals("abcd#efg", url.getParameter("pound")); Assertions.assertEquals("registry", url.getParameter("protocol")); } @Test void test_valueOfHasNameWithoutValue() throws Exception { - URL url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&noValue"); + URL url = URL.valueOf( + "dubbo://admin:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=morgan&noValue"); Assertions.assertEquals("", url.getParameter("noValue")); } @@ -1066,7 +1095,8 @@ class URLTest { URL url = URL.valueOf("admin1:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=app1"); assertEquals("admin1:hello1234@10.20.130.230:20880", url.getAuthority()); - URL urlWithoutUsername = URL.valueOf(":hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=app1"); + URL urlWithoutUsername = + URL.valueOf(":hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=app1"); assertEquals(":hello1234@10.20.130.230:20880", urlWithoutUsername.getAuthority()); URL urlWithoutPassword = URL.valueOf("admin1:@10.20.130.230:20880/context/path?version=1.0.0&application=app1"); @@ -1084,7 +1114,8 @@ class URLTest { URL url = URL.valueOf("admin1:hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=app1"); assertEquals("admin1:hello1234", url.getUserInformation()); - URL urlWithoutUsername = URL.valueOf(":hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=app1"); + URL urlWithoutUsername = + URL.valueOf(":hello1234@10.20.130.230:20880/context/path?version=1.0.0&application=app1"); assertEquals(":hello1234@10.20.130.230:20880", urlWithoutUsername.getAuthority()); URL urlWithoutPassword = URL.valueOf("admin1:@10.20.130.230:20880/context/path?version=1.0.0&application=app1"); @@ -1094,7 +1125,6 @@ class URLTest { assertEquals("10.20.130.230:20880", urlWithoutUserInformation.getAuthority()); } - @Test void testIPV6() { URL url = URL.valueOf("dubbo://[2408:4004:194:8896:3e8a:82ae:814a:398]:20881?name=apache"); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/beans/InstantiationStrategyTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/beans/InstantiationStrategyTest.java index 69ba384612..cb70b704bf 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/beans/InstantiationStrategyTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/beans/InstantiationStrategyTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.beans; - import org.apache.dubbo.common.beans.model.FooBeanWithApplicationModel; import org.apache.dubbo.common.beans.model.FooBeanWithFrameworkModel; import org.apache.dubbo.common.beans.model.FooBeanWithModuleModel; @@ -44,10 +43,12 @@ class InstantiationStrategyTest { void testCreateBeanWithScopeModelArgument() throws ReflectiveOperationException { InstantiationStrategy instantiationStrategy = new InstantiationStrategy(scopeModelAccessor); - FooBeanWithFrameworkModel beanWithFrameworkModel = instantiationStrategy.instantiate(FooBeanWithFrameworkModel.class); + FooBeanWithFrameworkModel beanWithFrameworkModel = + instantiationStrategy.instantiate(FooBeanWithFrameworkModel.class); Assertions.assertSame(scopeModelAccessor.getFrameworkModel(), beanWithFrameworkModel.getFrameworkModel()); - FooBeanWithApplicationModel beanWithApplicationModel = instantiationStrategy.instantiate(FooBeanWithApplicationModel.class); + FooBeanWithApplicationModel beanWithApplicationModel = + instantiationStrategy.instantiate(FooBeanWithApplicationModel.class); Assertions.assertSame(scopeModelAccessor.getApplicationModel(), beanWithApplicationModel.getApplicationModel()); FooBeanWithModuleModel beanWithModuleModel = instantiationStrategy.instantiate(FooBeanWithModuleModel.class); @@ -61,10 +62,9 @@ class InstantiationStrategyTest { instantiationStrategy.instantiate(FooBeanWithoutUniqueConstructors.class); Assertions.fail("Expect throwing exception"); } catch (Exception e) { - Assertions.assertTrue(e.getMessage().contains("Expect only one but found 2 matched constructors"), StringUtils.toString(e)); + Assertions.assertTrue( + e.getMessage().contains("Expect only one but found 2 matched constructors"), + StringUtils.toString(e)); } - } - - -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/beans/ScopeBeanFactoryTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/beans/ScopeBeanFactoryTest.java index 0e51c9e609..10a2428688 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/beans/ScopeBeanFactoryTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/beans/ScopeBeanFactoryTest.java @@ -22,11 +22,11 @@ import org.apache.dubbo.common.beans.model.FooBeanWithFrameworkModel; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; +import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.List; - class ScopeBeanFactoryTest { @Test @@ -34,15 +34,18 @@ class ScopeBeanFactoryTest { ApplicationModel applicationModel = ApplicationModel.defaultModel(); ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); - FooBeanWithApplicationModel beanWithApplicationModel = beanFactory.registerBean(FooBeanWithApplicationModel.class); + FooBeanWithApplicationModel beanWithApplicationModel = + beanFactory.registerBean(FooBeanWithApplicationModel.class); Assertions.assertSame(applicationModel, beanWithApplicationModel.getApplicationModel()); FrameworkModel frameworkModel = applicationModel.getFrameworkModel(); - FooBeanWithFrameworkModel beanWithFrameworkModel = frameworkModel.getBeanFactory().registerBean(FooBeanWithFrameworkModel.class); + FooBeanWithFrameworkModel beanWithFrameworkModel = + frameworkModel.getBeanFactory().registerBean(FooBeanWithFrameworkModel.class); Assertions.assertSame(frameworkModel, beanWithFrameworkModel.getFrameworkModel()); // child bean factory can obtain bean from parent bean factory - FooBeanWithFrameworkModel beanWithFrameworkModelFromApp = applicationModel.getBeanFactory().getBean(FooBeanWithFrameworkModel.class); + FooBeanWithFrameworkModel beanWithFrameworkModelFromApp = + applicationModel.getBeanFactory().getBean(FooBeanWithFrameworkModel.class); Assertions.assertSame(beanWithFrameworkModel, beanWithFrameworkModelFromApp); Object objectBean = applicationModel.getBeanFactory().getBean(Object.class); @@ -58,7 +61,6 @@ class ScopeBeanFactoryTest { List testBeans_1 = frameworkModel.getBeanFactory().getBeansOfType(TestBean.class); Assertions.assertEquals(testBeans_1.size(), 1); - Assertions.assertFalse(beanWithApplicationModel.isDestroyed()); Assertions.assertFalse(beanWithFrameworkModel.isDestroyed()); @@ -68,8 +70,5 @@ class ScopeBeanFactoryTest { Assertions.assertTrue(beanWithFrameworkModel.isDestroyed()); } - - static class TestBean { - - } + static class TestBean {} } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/Bean.java b/dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/Bean.java index 4e32514bea..a049e63687 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/Bean.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/Bean.java @@ -16,15 +16,15 @@ */ package org.apache.dubbo.common.beanutil; +import org.apache.dubbo.rpc.model.person.FullAddress; +import org.apache.dubbo.rpc.model.person.PersonStatus; +import org.apache.dubbo.rpc.model.person.Phone; + import java.io.Serializable; import java.util.Collection; import java.util.Date; import java.util.Map; -import org.apache.dubbo.rpc.model.person.FullAddress; -import org.apache.dubbo.rpc.model.person.PersonStatus; -import org.apache.dubbo.rpc.model.person.Phone; - public class Bean implements Serializable { private Class type; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/JavaBeanAccessorTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/JavaBeanAccessorTest.java index eb1118479f..d5f165623e 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/JavaBeanAccessorTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/JavaBeanAccessorTest.java @@ -22,16 +22,16 @@ import org.junit.jupiter.api.Test; class JavaBeanAccessorTest { @Test - void testIsAccessByMethod(){ + void testIsAccessByMethod() { Assertions.assertTrue(JavaBeanAccessor.isAccessByMethod(JavaBeanAccessor.METHOD)); Assertions.assertTrue(JavaBeanAccessor.isAccessByMethod(JavaBeanAccessor.ALL)); Assertions.assertFalse(JavaBeanAccessor.isAccessByMethod(JavaBeanAccessor.FIELD)); } @Test - void testIsAccessByField(){ + void testIsAccessByField() { Assertions.assertTrue(JavaBeanAccessor.isAccessByField(JavaBeanAccessor.FIELD)); Assertions.assertTrue(JavaBeanAccessor.isAccessByField(JavaBeanAccessor.ALL)); Assertions.assertFalse(JavaBeanAccessor.isAccessByField(JavaBeanAccessor.METHOD)); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java index 64fcf7ade4..65de6beb1c 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java @@ -22,9 +22,6 @@ import org.apache.dubbo.rpc.model.person.PersonInfo; import org.apache.dubbo.rpc.model.person.PersonStatus; import org.apache.dubbo.rpc.model.person.Phone; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.lang.reflect.Array; import java.math.BigDecimal; import java.util.ArrayList; @@ -34,6 +31,9 @@ import java.util.HashMap; import java.util.Map; import java.util.UUID; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class JavaBeanSerializeUtilTest { @Test @@ -74,8 +74,8 @@ class JavaBeanSerializeUtilTest { @Test void testDeserialize_Primitive0() { Assertions.assertThrows(IllegalArgumentException.class, () -> { - JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), - JavaBeanDescriptor.TYPE_BEAN + 1); + JavaBeanDescriptor descriptor = + new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_BEAN + 1); }); } @@ -89,8 +89,8 @@ class JavaBeanSerializeUtilTest { @Test void testDeserialize_containsProperty() { Assertions.assertThrows(IllegalArgumentException.class, () -> { - JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), - JavaBeanDescriptor.TYPE_PRIMITIVE); + JavaBeanDescriptor descriptor = + new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE); descriptor.containsProperty(null); }); } @@ -98,13 +98,13 @@ class JavaBeanSerializeUtilTest { @Test void testSetEnumNameProperty() { Assertions.assertThrows(IllegalStateException.class, () -> { - JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), - JavaBeanDescriptor.TYPE_PRIMITIVE); + JavaBeanDescriptor descriptor = + new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE); descriptor.setEnumNameProperty(JavaBeanDescriptor.class.getName()); }); - JavaBeanDescriptor descriptor = new JavaBeanDescriptor(JavaBeanDescriptor.class.getName(), - JavaBeanDescriptor.TYPE_ENUM); + JavaBeanDescriptor descriptor = + new JavaBeanDescriptor(JavaBeanDescriptor.class.getName(), JavaBeanDescriptor.TYPE_ENUM); String oldValueOrigin = descriptor.setEnumNameProperty(JavaBeanDescriptor.class.getName()); Assertions.assertNull(oldValueOrigin); @@ -116,8 +116,8 @@ class JavaBeanSerializeUtilTest { @Test void testGetEnumNameProperty() { Assertions.assertThrows(IllegalStateException.class, () -> { - JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), - JavaBeanDescriptor.TYPE_PRIMITIVE); + JavaBeanDescriptor descriptor = + new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE); descriptor.getEnumPropertyName(); }); } @@ -126,13 +126,13 @@ class JavaBeanSerializeUtilTest { void testSetClassNameProperty() { Assertions.assertThrows(IllegalStateException.class, () -> { - JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), - JavaBeanDescriptor.TYPE_PRIMITIVE); + JavaBeanDescriptor descriptor = + new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE); descriptor.setClassNameProperty(JavaBeanDescriptor.class.getName()); }); - JavaBeanDescriptor descriptor = new JavaBeanDescriptor(JavaBeanDescriptor.class.getName(), - JavaBeanDescriptor.TYPE_CLASS); + JavaBeanDescriptor descriptor = + new JavaBeanDescriptor(JavaBeanDescriptor.class.getName(), JavaBeanDescriptor.TYPE_CLASS); String oldValue1 = descriptor.setClassNameProperty(JavaBeanDescriptor.class.getName()); Assertions.assertNull(oldValue1); @@ -144,8 +144,8 @@ class JavaBeanSerializeUtilTest { @Test void testGetClassNameProperty() { Assertions.assertThrows(IllegalStateException.class, () -> { - JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), - JavaBeanDescriptor.TYPE_PRIMITIVE); + JavaBeanDescriptor descriptor = + new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE); descriptor.getClassNameProperty(); }); } @@ -153,8 +153,8 @@ class JavaBeanSerializeUtilTest { @Test void testSetPrimitiveProperty() { Assertions.assertThrows(IllegalStateException.class, () -> { - JavaBeanDescriptor descriptor = new JavaBeanDescriptor(JavaBeanDescriptor.class.getName(), - JavaBeanDescriptor.TYPE_BEAN); + JavaBeanDescriptor descriptor = + new JavaBeanDescriptor(JavaBeanDescriptor.class.getName(), JavaBeanDescriptor.TYPE_BEAN); descriptor.setPrimitiveProperty(JavaBeanDescriptor.class.getName()); }); } @@ -162,8 +162,8 @@ class JavaBeanSerializeUtilTest { @Test void testGetPrimitiveProperty() { Assertions.assertThrows(IllegalStateException.class, () -> { - JavaBeanDescriptor descriptor = new JavaBeanDescriptor(JavaBeanDescriptor.class.getName(), - JavaBeanDescriptor.TYPE_BEAN); + JavaBeanDescriptor descriptor = + new JavaBeanDescriptor(JavaBeanDescriptor.class.getName(), JavaBeanDescriptor.TYPE_BEAN); descriptor.getPrimitiveProperty(); }); } @@ -184,11 +184,10 @@ class JavaBeanSerializeUtilTest { Assertions.assertTrue(descriptor.isArrayType()); Assertions.assertEquals(int.class.getName(), descriptor.getClassName()); for (int i = 0; i < array.length; i++) { - Assertions.assertEquals(array[i], - ((JavaBeanDescriptor) descriptor.getProperty(i)).getPrimitiveProperty()); + Assertions.assertEquals(array[i], ((JavaBeanDescriptor) descriptor.getProperty(i)).getPrimitiveProperty()); } - Integer[] integers = new Integer[]{1, 2, 3, 4, null, null, null}; + Integer[] integers = new Integer[] {1, 2, 3, 4, null, null, null}; descriptor = JavaBeanSerializeUtil.serialize(integers, JavaBeanAccessor.METHOD); Assertions.assertTrue(descriptor.isArrayType()); Assertions.assertEquals(Integer.class.getName(), descriptor.getClassName()); @@ -197,8 +196,8 @@ class JavaBeanSerializeUtilTest { if (integers[i] == null) { Assertions.assertSame(integers[i], descriptor.getProperty(i)); } else { - Assertions.assertEquals(integers[i], ((JavaBeanDescriptor) descriptor.getProperty(i)) - .getPrimitiveProperty()); + Assertions.assertEquals( + integers[i], ((JavaBeanDescriptor) descriptor.getProperty(i)).getPrimitiveProperty()); } } @@ -211,11 +210,12 @@ class JavaBeanSerializeUtilTest { JavaBeanDescriptor item = (((JavaBeanDescriptor) descriptor.getProperty(i))); Assertions.assertTrue(item.isArrayType()); Assertions.assertEquals(int.class.getName(), item.getClassName()); - Assertions.assertEquals(second[i][j], ((JavaBeanDescriptor) item.getProperty(j)).getPrimitiveProperty()); + Assertions.assertEquals( + second[i][j], ((JavaBeanDescriptor) item.getProperty(j)).getPrimitiveProperty()); } } - BigPerson[] persons = new BigPerson[]{createBigPerson(), createBigPerson()}; + BigPerson[] persons = new BigPerson[] {createBigPerson(), createBigPerson()}; descriptor = JavaBeanSerializeUtil.serialize(persons); Assertions.assertTrue(descriptor.isArrayType()); Assertions.assertEquals(BigPerson.class.getName(), descriptor.getClassName()); @@ -281,8 +281,8 @@ class JavaBeanSerializeUtilTest { } descriptor = new JavaBeanDescriptor(BigPerson[].class.getName(), JavaBeanDescriptor.TYPE_ARRAY); - JavaBeanDescriptor innerDescriptor = new JavaBeanDescriptor(BigPerson.class.getName(), - JavaBeanDescriptor.TYPE_ARRAY); + JavaBeanDescriptor innerDescriptor = + new JavaBeanDescriptor(BigPerson.class.getName(), JavaBeanDescriptor.TYPE_ARRAY); innerDescriptor.setProperty(0, JavaBeanSerializeUtil.serialize(createBigPerson(), JavaBeanAccessor.METHOD)); descriptor.setProperty(0, innerDescriptor); @@ -414,7 +414,7 @@ class JavaBeanSerializeUtilTest { bean.setDate(new Date()); bean.setStatus(PersonStatus.ENABLED); bean.setType(Bean.class); - bean.setArray(new Phone[]{}); + bean.setArray(new Phone[] {}); Collection collection = new ArrayList(); bean.setCollection(collection); @@ -431,8 +431,8 @@ class JavaBeanSerializeUtilTest { assertEqualsPrimitive(bean.getDate(), descriptor.getProperty("date")); assertEqualsEnum(bean.getStatus(), descriptor.getProperty("status")); Assertions.assertTrue(((JavaBeanDescriptor) descriptor.getProperty("type")).isClassType()); - Assertions.assertEquals(Bean.class.getName(), ((JavaBeanDescriptor) descriptor.getProperty("type")) - .getClassNameProperty()); + Assertions.assertEquals( + Bean.class.getName(), ((JavaBeanDescriptor) descriptor.getProperty("type")).getClassNameProperty()); Assertions.assertTrue(((JavaBeanDescriptor) descriptor.getProperty("array")).isArrayType()); Assertions.assertEquals(0, ((JavaBeanDescriptor) descriptor.getProperty("array")).propertySize()); @@ -464,7 +464,7 @@ class JavaBeanSerializeUtilTest { bean.setDate(new Date()); bean.setStatus(PersonStatus.ENABLED); bean.setType(Bean.class); - bean.setArray(new Phone[]{}); + bean.setArray(new Phone[] {}); Collection collection = new ArrayList(); bean.setCollection(collection); @@ -483,13 +483,18 @@ class JavaBeanSerializeUtilTest { Assertions.assertEquals(bean.getDate(), deserBean.getDate()); Assertions.assertEquals(bean.getStatus(), deserBean.getStatus()); Assertions.assertEquals(bean.getType(), deserBean.getType()); - Assertions.assertEquals(bean.getCollection().size(), deserBean.getCollection().size()); - Assertions.assertEquals(bean.getCollection().iterator().next().getClass(), + Assertions.assertEquals( + bean.getCollection().size(), deserBean.getCollection().size()); + Assertions.assertEquals( + bean.getCollection().iterator().next().getClass(), deserBean.getCollection().iterator().next().getClass()); - Assertions.assertEquals(bean.getAddresses().size(), deserBean.getAddresses().size()); - Assertions.assertEquals(bean.getAddresses().entrySet().iterator().next().getKey(), + Assertions.assertEquals( + bean.getAddresses().size(), deserBean.getAddresses().size()); + Assertions.assertEquals( + bean.getAddresses().entrySet().iterator().next().getKey(), deserBean.getAddresses().entrySet().iterator().next().getKey()); - Assertions.assertEquals(bean.getAddresses().entrySet().iterator().next().getValue().getClass(), + Assertions.assertEquals( + bean.getAddresses().entrySet().iterator().next().getValue().getClass(), deserBean.getAddresses().entrySet().iterator().next().getValue().getClass()); } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/ClassGeneratorTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/ClassGeneratorTest.java index 2eed4129aa..9d760b6d90 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/ClassGeneratorTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/ClassGeneratorTest.java @@ -16,10 +16,6 @@ */ package org.apache.dubbo.common.bytecode; -import javassist.ClassPool; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; @@ -27,6 +23,10 @@ import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; +import javassist.ClassPool; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; interface Builder { T getName(Bean bean); @@ -36,9 +36,7 @@ interface Builder { class BaseClass { - public BaseClass() { - - } + public BaseClass() {} public BaseClass(StringBuilder sb) { sb.append("constructor comes from BaseClass"); @@ -49,9 +47,8 @@ class BaseClass { } } -interface BaseInterface { +interface BaseInterface {} -} class ClassGeneratorTest { @Test @@ -66,19 +63,48 @@ class ClassGeneratorTest { // add constructor cg.addDefaultConstructor(); - cg.addConstructor(Modifier.PUBLIC, new Class[]{String.class, int.class}, new Class[]{Throwable.class, RuntimeException.class}, "this.strAttr = arg0;this.intAttr = arg1;"); + cg.addConstructor( + Modifier.PUBLIC, + new Class[] {String.class, int.class}, + new Class[] {Throwable.class, RuntimeException.class}, + "this.strAttr = arg0;this.intAttr = arg1;"); cg.addConstructor(BaseClass.class.getConstructor(StringBuilder.class)); // add field - cg.addField("staticAttr", Modifier.PUBLIC | Modifier.STATIC | Modifier.VOLATILE, String.class, "\"defaultVal\""); + cg.addField( + "staticAttr", Modifier.PUBLIC | Modifier.STATIC | Modifier.VOLATILE, String.class, "\"defaultVal\""); cg.addField("strAttr", Modifier.PROTECTED | Modifier.VOLATILE, String.class); cg.addField("intAttr", Modifier.PRIVATE | Modifier.VOLATILE, int.class); // add method - cg.addMethod("setStrAttr", Modifier.PUBLIC, void.class, new Class[]{String.class, int.class}, new Class[]{Throwable.class, RuntimeException.class}, "this.strAttr = arg0;"); - cg.addMethod("setIntAttr", Modifier.PUBLIC, void.class, new Class[]{String.class, int.class}, new Class[]{Throwable.class, RuntimeException.class}, "this.intAttr = arg1;"); - cg.addMethod("getStrAttr", Modifier.PUBLIC, String.class, new Class[]{}, new Class[]{Throwable.class, RuntimeException.class}, "return this.strAttr;"); - cg.addMethod("getIntAttr", Modifier.PUBLIC, int.class, new Class[]{}, new Class[]{Throwable.class, RuntimeException.class}, "return this.intAttr;"); + cg.addMethod( + "setStrAttr", + Modifier.PUBLIC, + void.class, + new Class[] {String.class, int.class}, + new Class[] {Throwable.class, RuntimeException.class}, + "this.strAttr = arg0;"); + cg.addMethod( + "setIntAttr", + Modifier.PUBLIC, + void.class, + new Class[] {String.class, int.class}, + new Class[] {Throwable.class, RuntimeException.class}, + "this.intAttr = arg1;"); + cg.addMethod( + "getStrAttr", + Modifier.PUBLIC, + String.class, + new Class[] {}, + new Class[] {Throwable.class, RuntimeException.class}, + "return this.strAttr;"); + cg.addMethod( + "getIntAttr", + Modifier.PUBLIC, + int.class, + new Class[] {}, + new Class[] {Throwable.class, RuntimeException.class}, + "return this.intAttr;"); cg.addMethod(BaseClass.class.getMethod("baseClassMethod")); // cg.toClass @@ -90,16 +116,17 @@ class ClassGeneratorTest { Assertions.assertTrue(ClassGenerator.isDynamicClass(clz)); Assertions.assertEquals(clz.getName(), className); Assertions.assertEquals(clz.getSuperclass(), BaseClass.class); - Assertions.assertArrayEquals(clz.getInterfaces(), new Class[]{ClassGenerator.DC.class, BaseInterface.class}); + Assertions.assertArrayEquals(clz.getInterfaces(), new Class[] {ClassGenerator.DC.class, BaseInterface.class}); // get constructors Constructor[] constructors = clz.getConstructors(); Assertions.assertEquals(constructors.length, 3); Constructor constructor0 = clz.getConstructor(); - Constructor constructor1 = clz.getConstructor(new Class[]{String.class, int.class}); - Constructor constructor2 = clz.getConstructor(new Class[]{StringBuilder.class}); + Constructor constructor1 = clz.getConstructor(new Class[] {String.class, int.class}); + Constructor constructor2 = clz.getConstructor(new Class[] {StringBuilder.class}); Assertions.assertEquals(constructor1.getModifiers(), Modifier.PUBLIC); - Assertions.assertArrayEquals(constructor1.getExceptionTypes(), new Class[]{Throwable.class, RuntimeException.class}); + Assertions.assertArrayEquals( + constructor1.getExceptionTypes(), new Class[] {Throwable.class, RuntimeException.class}); // get fields Field staticAttrField = clz.getDeclaredField("staticAttr"); @@ -111,8 +138,8 @@ class ClassGeneratorTest { Assertions.assertEquals(staticAttrField.get(null), "defaultVal"); // get methods - Method setStrAttrMethod = clz.getMethod("setStrAttr", new Class[]{String.class, int.class}); - Method setIntAttrMethod = clz.getMethod("setIntAttr", new Class[]{String.class, int.class}); + Method setStrAttrMethod = clz.getMethod("setStrAttr", new Class[] {String.class, int.class}); + Method setIntAttrMethod = clz.getMethod("setIntAttr", new Class[] {String.class, int.class}); Method getStrAttrMethod = clz.getMethod("getStrAttr"); Method getIntAttrMethod = clz.getMethod("getIntAttr"); Method baseClassMethod = clz.getMethod("baseClassMethod"); @@ -141,10 +168,10 @@ class ClassGeneratorTest { // verify constructor and method witch comes from baseClass StringBuilder sb = new StringBuilder(); Object objByConstructor2 = constructor2.newInstance(sb); - Assertions.assertEquals(sb.toString(),"constructor comes from BaseClass"); + Assertions.assertEquals(sb.toString(), "constructor comes from BaseClass"); Object res = baseClassMethod.invoke(objByConstructor2); - Assertions.assertEquals(res,"method comes from BaseClass"); + Assertions.assertEquals(res, "method comes from BaseClass"); cg.release(); } @@ -162,7 +189,8 @@ class ClassGeneratorTest { cg.addField("public static java.lang.reflect.Field FNAME;"); - cg.addMethod("public Object getName(" + Bean.class.getName() + " o){ boolean[][][] bs = new boolean[0][][]; return (String)FNAME.get($1); }"); + cg.addMethod("public Object getName(" + Bean.class.getName() + + " o){ boolean[][][] bs = new boolean[0][][]; return (String)FNAME.get($1); }"); cg.addMethod("public void setName(" + Bean.class.getName() + " o, Object name){ FNAME.set($1, $2); }"); cg.addDefaultConstructor(); @@ -188,7 +216,8 @@ class ClassGeneratorTest { cg.addField("FNAME", Modifier.PUBLIC | Modifier.STATIC, java.lang.reflect.Field.class); - cg.addMethod("public Object getName(" + Bean.class.getName() + " o){ boolean[][][] bs = new boolean[0][][]; return (String)FNAME.get($1); }"); + cg.addMethod("public Object getName(" + Bean.class.getName() + + " o){ boolean[][][] bs = new boolean[0][][]; return (String)FNAME.get($1); }"); cg.addMethod("public void setName(" + Bean.class.getName() + " o, Object name){ FNAME.set($1, $2); }"); cg.addDefaultConstructor(); @@ -210,15 +239,16 @@ class ClassGeneratorTest { List hashCodeList = new ArrayList<>(); for (int i = 0; i < threadCount; i++) { new Thread(new Runnable() { - @Override - public void run() { - ClassPool classPool = ClassGenerator.getClassPool(loader); - int currentHashCode = classPool.hashCode(); - hashCodeList.add(currentHashCode); - System.out.println(currentHashCode); - LATCH.countDown(); - } - }).start(); + @Override + public void run() { + ClassPool classPool = ClassGenerator.getClassPool(loader); + int currentHashCode = classPool.hashCode(); + hashCodeList.add(currentHashCode); + System.out.println(currentHashCode); + LATCH.countDown(); + } + }) + .start(); } LATCH.await(); Integer firstHashCode = null; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/MixinTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/MixinTest.java index 2ad7ab35ae..ce81aebf1b 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/MixinTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/MixinTest.java @@ -24,8 +24,8 @@ class MixinTest { @Test void testMain() { - Mixin mixin = Mixin.mixin(new Class[]{I1.class, I2.class, I3.class}, new Class[]{C1.class, C2.class}); - Object o = mixin.newInstance(new Object[]{new C1(), new C2()}); + Mixin mixin = Mixin.mixin(new Class[] {I1.class, I2.class, I3.class}, new Class[] {C1.class, C2.class}); + Object o = mixin.newInstance(new Object[] {new C1(), new C2()}); assertTrue(o instanceof I1); assertTrue(o instanceof I2); assertTrue(o instanceof I3); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/ProxyTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/ProxyTest.java index 6a6e1df794..a18a30c988 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/ProxyTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/ProxyTest.java @@ -74,4 +74,4 @@ class ProxyTest { return "Bye!"; } } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/WrapperTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/WrapperTest.java index 8268494421..35b7c767c8 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/WrapperTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/bytecode/WrapperTest.java @@ -41,10 +41,10 @@ class WrapperTest { w.setPropertyValue(obj, "name", "changed"); assertEquals(w.getPropertyValue(obj, "name"), "changed"); - w.invokeMethod(obj, "hello", new Class[]{String.class}, new Object[]{"qianlei"}); + w.invokeMethod(obj, "hello", new Class[] {String.class}, new Object[] {"qianlei"}); - w.setPropertyValues(obj, new String[]{"name", "float"}, new Object[]{"mrh", 1.0f}); - Object[] propertyValues = w.getPropertyValues(obj, new String[]{"name", "float"}); + w.setPropertyValues(obj, new String[] {"name", "float"}, new Object[] {"mrh", 1.0f}); + Object[] propertyValues = w.getPropertyValues(obj, new String[] {"name", "float"}); Assertions.assertEquals(propertyValues.length, 2); Assertions.assertEquals(propertyValues[0], "mrh"); Assertions.assertEquals(propertyValues[1], 1.0f); @@ -56,14 +56,14 @@ class WrapperTest { Wrapper w = Wrapper.getWrapper(I1.class); Object obj = new Impl1(); try { - w.invokeMethod(obj, "hello", new Class[]{String.class, String.class}, - new Object[]{"qianlei", "badboy"}); + w.invokeMethod( + obj, "hello", new Class[] {String.class, String.class}, new Object[] {"qianlei", "badboy"}); fail(); } catch (NoSuchMethodException expected) { } } - //bug: DUBBO-425 + // bug: DUBBO-425 @Test void test_makeEmptyClass() throws Exception { Wrapper.getWrapper(EmptyServiceImpl.class); @@ -112,7 +112,7 @@ class WrapperTest { Wrapper.getWrapper(Byte.TYPE); }); } - + @Test void testInvokeWrapperObject() throws Exception { Wrapper w = Wrapper.getWrapper(Object.class); @@ -120,9 +120,12 @@ class WrapperTest { Assertions.assertEquals(instance.getClass(), w.invokeMethod(instance, "getClass", null, null)); Assertions.assertEquals(instance.hashCode(), (int) w.invokeMethod(instance, "hashCode", null, null)); Assertions.assertEquals(instance.toString(), w.invokeMethod(instance, "toString", null, null)); - Assertions.assertTrue((boolean) w.invokeMethod(instance, "equals", new Class[]{instance.getClass()}, new Object[]{instance})); - Assertions.assertThrows(IllegalArgumentException.class, - () -> w.invokeMethod(instance, "equals", new Class[]{instance.getClass()}, new Object[]{instance, instance})); + Assertions.assertTrue((boolean) + w.invokeMethod(instance, "equals", new Class[] {instance.getClass()}, new Object[] {instance})); + Assertions.assertThrows( + IllegalArgumentException.class, + () -> w.invokeMethod( + instance, "equals", new Class[] {instance.getClass()}, new Object[] {instance, instance})); } @Test @@ -140,40 +143,49 @@ class WrapperTest { Impl2 impl = new Impl2(); - w.invokeMethod(impl, "setFloat", new Class[]{float.class}, new Object[]{1F}); + w.invokeMethod(impl, "setFloat", new Class[] {float.class}, new Object[] {1F}); assertEquals(1F, impl.getFloat1()); assertNull(impl.getFloat2()); - w.invokeMethod(impl, "setFloat", new Class[]{Float.class}, new Object[]{2f}); + w.invokeMethod(impl, "setFloat", new Class[] {Float.class}, new Object[] {2f}); assertEquals(1F, impl.getFloat1()); assertEquals(2F, impl.getFloat2()); - w.invokeMethod(impl, "setFloat", new Class[]{Float.class}, new Object[]{null}); + w.invokeMethod(impl, "setFloat", new Class[] {Float.class}, new Object[] {null}); assertEquals(1F, impl.getFloat1()); assertNull(impl.getFloat2()); } @Test void test_getDeclaredMethodNames_ContainExtendsParentMethods() throws Exception { - assertArrayEquals(new String[]{"hello",}, Wrapper.getWrapper(Parent1.class).getMethodNames()); - assertArrayEquals(new String[]{"hello",}, ClassUtils.getMethodNames(Parent1.class)); + assertArrayEquals( + new String[] { + "hello", + }, + Wrapper.getWrapper(Parent1.class).getMethodNames()); + assertArrayEquals( + new String[] { + "hello", + }, + ClassUtils.getMethodNames(Parent1.class)); - assertArrayEquals(new String[]{}, Wrapper.getWrapper(Son.class).getDeclaredMethodNames()); - assertArrayEquals(new String[]{}, ClassUtils.getDeclaredMethodNames(Son.class)); + assertArrayEquals(new String[] {}, Wrapper.getWrapper(Son.class).getDeclaredMethodNames()); + assertArrayEquals(new String[] {}, ClassUtils.getDeclaredMethodNames(Son.class)); } @Test void test_getMethodNames_ContainExtendsParentMethods() throws Exception { - assertArrayEquals(new String[]{"hello", "world"}, Wrapper.getWrapper(Son.class).getMethodNames()); - assertArrayEquals(new String[]{"hello", "world"}, ClassUtils.getMethodNames(Son.class)); + assertArrayEquals( + new String[] {"hello", "world"}, Wrapper.getWrapper(Son.class).getMethodNames()); + assertArrayEquals(new String[] {"hello", "world"}, ClassUtils.getMethodNames(Son.class)); } @Test - void testWrapImplClass(){ + void testWrapImplClass() { Wrapper w = Wrapper.getWrapper(Impl0.class); String[] propertyNames = w.getPropertyNames(); - Assertions.assertArrayEquals(propertyNames, new String[]{"a", "b", "c"}); + Assertions.assertArrayEquals(propertyNames, new String[] {"a", "b", "c"}); // fields that do not contain the static|final|transient modifier Assertions.assertFalse(w.hasProperty("f")); Assertions.assertFalse(w.hasProperty("l")); @@ -207,21 +219,17 @@ class WrapperTest { void setFloat(Float f); } - public interface EmptyService { - } + public interface EmptyService {} public interface Parent1 { void hello(); } - public interface Parent2 { void world(); } - public interface Son extends Parent1, Parent2 { - - } + public interface Son extends Parent1, Parent2 {} public static class Impl0 { public float a, b, c; @@ -229,13 +237,9 @@ class WrapperTest { public static long l = 1; public final char ch = 'c'; - private void privateMethod() { + private void privateMethod() {} - } - - public void publicMethod() { - - } + public void publicMethod() {} } public static class Impl1 implements I1 { @@ -291,6 +295,5 @@ class WrapperTest { } } - public static class EmptyServiceImpl implements EmptyService { - } -} \ No newline at end of file + public static class EmptyServiceImpl implements EmptyService {} +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/cache/FileCacheStoreFactoryTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/cache/FileCacheStoreFactoryTest.java index a19bf98619..4eec702f72 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/cache/FileCacheStoreFactoryTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/cache/FileCacheStoreFactoryTest.java @@ -16,9 +16,6 @@ */ package org.apache.dubbo.common.cache; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.io.File; import java.io.IOException; import java.lang.reflect.Field; @@ -27,16 +24,21 @@ import java.net.URL; import java.nio.file.Paths; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class FileCacheStoreFactoryTest { @Test void testSafeName() throws URISyntaxException { FileCacheStore store1 = FileCacheStoreFactory.getInstance(getDirectoryOfClassPath(), "../../../dubbo"); - Assertions.assertEquals(getDirectoryOfClassPath() + "..%002f..%002f..%002fdubbo.dubbo.cache", getCacheFilePath(store1)); + Assertions.assertEquals( + getDirectoryOfClassPath() + "..%002f..%002f..%002fdubbo.dubbo.cache", getCacheFilePath(store1)); store1.destroy(); FileCacheStore store2 = FileCacheStoreFactory.getInstance(getDirectoryOfClassPath(), "../../../中文"); - Assertions.assertEquals(getDirectoryOfClassPath() + "..%002f..%002f..%002f%4e2d%6587.dubbo.cache", getCacheFilePath(store2)); + Assertions.assertEquals( + getDirectoryOfClassPath() + "..%002f..%002f..%002f%4e2d%6587.dubbo.cache", getCacheFilePath(store2)); store2.destroy(); } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/cache/FileCacheStoreTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/cache/FileCacheStoreTest.java index bdfcc3b022..fd2798ad33 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/cache/FileCacheStoreTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/cache/FileCacheStoreTest.java @@ -16,14 +16,14 @@ */ package org.apache.dubbo.common.cache; -import org.junit.jupiter.api.Test; - import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; class FileCacheStoreTest { @@ -74,5 +74,4 @@ class FileCacheStoreTest { String directoryPath = path.substring(0, index); return directoryPath; } - -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/AdaptiveCompilerTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/AdaptiveCompilerTest.java index 9edc55804a..31fb7f0702 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/AdaptiveCompilerTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/AdaptiveCompilerTest.java @@ -29,8 +29,8 @@ class AdaptiveCompilerTest extends JavaCodeTest { AdaptiveCompiler compiler = new AdaptiveCompiler(); compiler.setFrameworkModel(FrameworkModel.defaultModel()); Class clazz = compiler.compile(JavaCodeTest.class, getSimpleCode(), AdaptiveCompiler.class.getClassLoader()); - HelloService helloService = (HelloService) clazz.getDeclaredConstructor().newInstance(); + HelloService helloService = + (HelloService) clazz.getDeclaredConstructor().newInstance(); Assertions.assertEquals("Hello world!", helloService.sayHello()); } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/ClassUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/ClassUtilsTest.java index 0e7c6b7a73..5023ff7640 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/ClassUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/ClassUtilsTest.java @@ -16,15 +16,15 @@ */ package org.apache.dubbo.common.compiler.support; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class ClassUtilsTest { @Test @@ -35,27 +35,36 @@ class ClassUtilsTest { @Test void testNewInstance0() { - Assertions.assertThrows(IllegalStateException.class, () -> ClassUtils.newInstance(PrivateHelloServiceImpl.class.getName())); + Assertions.assertThrows( + IllegalStateException.class, () -> ClassUtils.newInstance(PrivateHelloServiceImpl.class.getName())); } @Test void testNewInstance1() { - Assertions.assertThrows(IllegalStateException.class, () -> ClassUtils.newInstance("org.apache.dubbo.common.compiler.support.internal.HelloServiceInternalImpl")); + Assertions.assertThrows( + IllegalStateException.class, + () -> ClassUtils.newInstance( + "org.apache.dubbo.common.compiler.support.internal.HelloServiceInternalImpl")); } @Test void testNewInstance2() { - Assertions.assertThrows(IllegalStateException.class, () -> ClassUtils.newInstance("org.apache.dubbo.common.compiler.support.internal.NotExistsImpl")); + Assertions.assertThrows( + IllegalStateException.class, + () -> ClassUtils.newInstance("org.apache.dubbo.common.compiler.support.internal.NotExistsImpl")); } @Test void testForName() { - ClassUtils.forName(new String[]{"org.apache.dubbo.common.compiler.support"}, "HelloServiceImpl0"); + ClassUtils.forName(new String[] {"org.apache.dubbo.common.compiler.support"}, "HelloServiceImpl0"); } @Test void testForName1() { - Assertions.assertThrows(IllegalStateException.class, () -> ClassUtils.forName(new String[]{"org.apache.dubbo.common.compiler.support"}, "HelloServiceImplXX")); + Assertions.assertThrows( + IllegalStateException.class, + () -> ClassUtils.forName( + new String[] {"org.apache.dubbo.common.compiler.support"}, "HelloServiceImplXX")); } @Test @@ -108,8 +117,8 @@ class ClassUtilsTest { Assertions.assertEquals((short) 0, ClassUtils.unboxed(Short.valueOf((short) 0))); Assertions.assertEquals(0, ClassUtils.unboxed(Integer.valueOf((int) 0))); Assertions.assertEquals((long) 0, ClassUtils.unboxed(Long.valueOf((long) 0))); -// Assertions.assertEquals((float) 0, ClassUtils.unboxed(Float.valueOf((float) 0)), ((float) 0)); -// Assertions.assertEquals((double) 0, ClassUtils.unboxed(Double.valueOf((double) 0)), ((double) 0)); + // Assertions.assertEquals((float) 0, ClassUtils.unboxed(Float.valueOf((float) 0)), ((float) 0)); + // Assertions.assertEquals((double) 0, ClassUtils.unboxed(Double.valueOf((double) 0)), ((double) 0)); } @Test @@ -135,7 +144,7 @@ class ClassUtilsTest { void testGetSizeMethod() { Assertions.assertEquals("getLength()", ClassUtils.getSizeMethod(GenericClass3.class)); } - + @Test void testGetSimpleClassName() { Assertions.assertNull(ClassUtils.getSimpleClassName(null)); @@ -143,20 +152,15 @@ class ClassUtilsTest { Assertions.assertEquals("Map", ClassUtils.getSimpleClassName(Map.class.getSimpleName())); } - private interface GenericInterface { - } + private interface GenericInterface {} - private class GenericClass implements GenericInterface { - } + private class GenericClass implements GenericInterface {} - private class GenericClass0 implements GenericInterface { - } + private class GenericClass0 implements GenericInterface {} - private class GenericClass1 implements GenericInterface> { - } + private class GenericClass1 implements GenericInterface> {} - private class GenericClass2 implements GenericInterface { - } + private class GenericClass2 implements GenericInterface {} private class GenericClass3 implements GenericInterface { public int getLength() { @@ -165,13 +169,11 @@ class ClassUtilsTest { } private class PrivateHelloServiceImpl implements HelloService { - private PrivateHelloServiceImpl() { - } + private PrivateHelloServiceImpl() {} @Override public String sayHello() { return "Hello world!"; } } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/HelloService.java b/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/HelloService.java index ae9c23bd81..a711a124c2 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/HelloService.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/HelloService.java @@ -19,5 +19,4 @@ package org.apache.dubbo.common.compiler.support; public interface HelloService { String sayHello(); - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/JavaCodeTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/JavaCodeTest.java index 16686cde7f..1af4ea3b26 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/JavaCodeTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/JavaCodeTest.java @@ -20,7 +20,7 @@ import java.util.concurrent.atomic.AtomicInteger; class JavaCodeTest { - public final static AtomicInteger SUBFIX = new AtomicInteger(8); + public static final AtomicInteger SUBFIX = new AtomicInteger(8); boolean shouldIgnoreWithoutPackage() { String jdkVersion = System.getProperty("java.specification.version"); @@ -43,9 +43,10 @@ class JavaCodeTest { return code.toString(); } - String getSimpleCodeWithoutPackage(){ + String getSimpleCodeWithoutPackage() { StringBuilder code = new StringBuilder(); - code.append("public class HelloServiceImpl" + SUBFIX.getAndIncrement() + "implements org.apache.dubbo.common.compiler.support.HelloService.HelloService {"); + code.append("public class HelloServiceImpl" + SUBFIX.getAndIncrement() + + "implements org.apache.dubbo.common.compiler.support.HelloService.HelloService {"); code.append(" public String sayHello() { "); code.append(" return \"Hello world!\"; "); code.append(" }"); @@ -53,7 +54,7 @@ class JavaCodeTest { return code.toString(); } - String getSimpleCodeWithSyntax(){ + String getSimpleCodeWithSyntax() { StringBuilder code = new StringBuilder(); code.append("package org.apache.dubbo.common.compiler.support;"); @@ -66,7 +67,7 @@ class JavaCodeTest { } // only used for javassist - String getSimpleCodeWithSyntax0(){ + String getSimpleCodeWithSyntax0() { StringBuilder code = new StringBuilder(); code.append("package org.apache.dubbo.common.compiler.support;"); @@ -100,11 +101,12 @@ class JavaCodeTest { code.append("import java.lang.*;\n"); code.append("import org.apache.dubbo.common.compiler.support;\n"); - code.append("public class HelloServiceImpl" + SUBFIX.getAndIncrement() + " extends org.apache.dubbo.common.compiler.support.HelloServiceImpl0 {\n"); + code.append("public class HelloServiceImpl" + SUBFIX.getAndIncrement() + + " extends org.apache.dubbo.common.compiler.support.HelloServiceImpl0 {\n"); code.append(" public String sayHello() { "); code.append(" return \"Hello world3!\"; "); code.append(" }"); code.append('}'); return code.toString(); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/JavassistCompilerTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/JavassistCompilerTest.java index 9cfb667b39..18ac8852c3 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/JavassistCompilerTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/JavassistCompilerTest.java @@ -16,18 +16,19 @@ */ package org.apache.dubbo.common.compiler.support; +import java.lang.reflect.Method; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.DisabledForJreRange; import org.junit.jupiter.api.condition.JRE; -import java.lang.reflect.Method; - class JavassistCompilerTest extends JavaCodeTest { @Test void testCompileJavaClass() throws Exception { JavassistCompiler compiler = new JavassistCompiler(); - Class clazz = compiler.compile(JavaCodeTest.class, getSimpleCode(), JavassistCompiler.class.getClassLoader()); + Class clazz = + compiler.compile(JavaCodeTest.class, getSimpleCode(), JavassistCompiler.class.getClassLoader()); // Because javassist compiles using the caller class loader, we should't use HelloService directly Object instance = clazz.getDeclaredConstructor().newInstance(); @@ -45,9 +46,13 @@ class JavassistCompilerTest extends JavaCodeTest { JavassistCompiler compiler = new JavassistCompiler(); if (ignoreWithoutPackage) { - Assertions.assertThrows(RuntimeException.class, () -> compiler.compile(null, getSimpleCodeWithoutPackage(), JavassistCompiler.class.getClassLoader())); + Assertions.assertThrows( + RuntimeException.class, + () -> compiler.compile( + null, getSimpleCodeWithoutPackage(), JavassistCompiler.class.getClassLoader())); } else { - Class clazz = compiler.compile(null, getSimpleCodeWithoutPackage(), JavassistCompiler.class.getClassLoader()); + Class clazz = + compiler.compile(null, getSimpleCodeWithoutPackage(), JavassistCompiler.class.getClassLoader()); Object instance = clazz.getDeclaredConstructor().newInstance(); Method sayHello = instance.getClass().getMethod("sayHello"); Assertions.assertEquals("Hello world!", sayHello.invoke(instance)); @@ -58,7 +63,8 @@ class JavassistCompilerTest extends JavaCodeTest { void testCompileJavaClass1() { Assertions.assertThrows(IllegalStateException.class, () -> { JavassistCompiler compiler = new JavassistCompiler(); - Class clazz = compiler.compile(JavaCodeTest.class, getSimpleCodeWithSyntax0(), JavassistCompiler.class.getClassLoader()); + Class clazz = compiler.compile( + JavaCodeTest.class, getSimpleCodeWithSyntax0(), JavassistCompiler.class.getClassLoader()); Object instance = clazz.getDeclaredConstructor().newInstance(); Method sayHello = instance.getClass().getMethod("sayHello"); Assertions.assertEquals("Hello world!", sayHello.invoke(instance)); @@ -68,7 +74,8 @@ class JavassistCompilerTest extends JavaCodeTest { @Test void testCompileJavaClassWithImport() throws Exception { JavassistCompiler compiler = new JavassistCompiler(); - Class clazz = compiler.compile(JavaCodeTest.class, getSimpleCodeWithImports(), JavassistCompiler.class.getClassLoader()); + Class clazz = compiler.compile( + JavaCodeTest.class, getSimpleCodeWithImports(), JavassistCompiler.class.getClassLoader()); Object instance = clazz.getDeclaredConstructor().newInstance(); Method sayHello = instance.getClass().getMethod("sayHello"); Assertions.assertEquals("Hello world!", sayHello.invoke(instance)); @@ -77,7 +84,8 @@ class JavassistCompilerTest extends JavaCodeTest { @Test void testCompileJavaClassWithExtends() throws Exception { JavassistCompiler compiler = new JavassistCompiler(); - Class clazz = compiler.compile(JavaCodeTest.class, getSimpleCodeWithWithExtends(), JavassistCompiler.class.getClassLoader()); + Class clazz = compiler.compile( + JavaCodeTest.class, getSimpleCodeWithWithExtends(), JavassistCompiler.class.getClassLoader()); Object instance = clazz.getDeclaredConstructor().newInstance(); Method sayHello = instance.getClass().getMethod("sayHello"); Assertions.assertEquals("Hello world3!", sayHello.invoke(instance)); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/JdkCompilerTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/JdkCompilerTest.java index 61b8b81967..315c587f13 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/JdkCompilerTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/JdkCompilerTest.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.common.compiler.support; +import java.lang.reflect.Method; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.lang.reflect.Method; - class JdkCompilerTest extends JavaCodeTest { @Test @@ -36,7 +36,8 @@ class JdkCompilerTest extends JavaCodeTest { void test_compileJavaClass0() { Assertions.assertThrows(IllegalStateException.class, () -> { JdkCompiler compiler = new JdkCompiler(); - Class clazz = compiler.compile(JavaCodeTest.class, getSimpleCodeWithoutPackage(), JdkCompiler.class.getClassLoader()); + Class clazz = compiler.compile( + JavaCodeTest.class, getSimpleCodeWithoutPackage(), JdkCompiler.class.getClassLoader()); Object instance = clazz.getDeclaredConstructor().newInstance(); Method sayHello = instance.getClass().getMethod("sayHello"); Assertions.assertEquals("Hello world!", sayHello.invoke(instance)); @@ -47,7 +48,8 @@ class JdkCompilerTest extends JavaCodeTest { void test_compileJavaClass1() { Assertions.assertThrows(IllegalStateException.class, () -> { JdkCompiler compiler = new JdkCompiler(); - Class clazz = compiler.compile(JavaCodeTest.class, getSimpleCodeWithSyntax(), JdkCompiler.class.getClassLoader()); + Class clazz = + compiler.compile(JavaCodeTest.class, getSimpleCodeWithSyntax(), JdkCompiler.class.getClassLoader()); Object instance = clazz.getDeclaredConstructor().newInstance(); Method sayHello = instance.getClass().getMethod("sayHello"); Assertions.assertEquals("Hello world!", sayHello.invoke(instance)); @@ -67,7 +69,8 @@ class JdkCompilerTest extends JavaCodeTest { void test_compileJavaClass0_java8() { Assertions.assertThrows(IllegalStateException.class, () -> { JdkCompiler compiler = new JdkCompiler("1.8"); - Class clazz = compiler.compile(JavaCodeTest.class, getSimpleCodeWithoutPackage(), JdkCompiler.class.getClassLoader()); + Class clazz = compiler.compile( + JavaCodeTest.class, getSimpleCodeWithoutPackage(), JdkCompiler.class.getClassLoader()); Object instance = clazz.getDeclaredConstructor().newInstance(); Method sayHello = instance.getClass().getMethod("sayHello"); Assertions.assertEquals("Hello world!", sayHello.invoke(instance)); @@ -78,7 +81,8 @@ class JdkCompilerTest extends JavaCodeTest { void test_compileJavaClass1_java8() { Assertions.assertThrows(IllegalStateException.class, () -> { JdkCompiler compiler = new JdkCompiler("1.8"); - Class clazz = compiler.compile(JavaCodeTest.class, getSimpleCodeWithSyntax(), JdkCompiler.class.getClassLoader()); + Class clazz = + compiler.compile(JavaCodeTest.class, getSimpleCodeWithSyntax(), JdkCompiler.class.getClassLoader()); Object instance = clazz.getDeclaredConstructor().newInstance(); Method sayHello = instance.getClass().getMethod("sayHello"); Assertions.assertEquals("Hello world!", sayHello.invoke(instance)); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/internal/HelloServiceInternalImpl.java b/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/internal/HelloServiceInternalImpl.java index 4e37b0bad5..7ba2ae47db 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/internal/HelloServiceInternalImpl.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/compiler/support/internal/HelloServiceInternalImpl.java @@ -16,5 +16,4 @@ */ package org.apache.dubbo.common.compiler.support.internal; -final class HelloServiceInternalImpl { -} +final class HelloServiceInternalImpl {} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/concurrent/CompletableFutureTaskTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/concurrent/CompletableFutureTaskTest.java index a1a8fd70ae..92b0a2c123 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/concurrent/CompletableFutureTaskTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/concurrent/CompletableFutureTaskTest.java @@ -18,9 +18,6 @@ package org.apache.dubbo.common.concurrent; import org.apache.dubbo.common.utils.NamedThreadFactory; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; @@ -31,6 +28,9 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.any; @@ -38,33 +38,42 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; - class CompletableFutureTaskTest { - private static final ExecutorService executor = new ThreadPoolExecutor(0, 10, 60L, TimeUnit.SECONDS, new SynchronousQueue(), new NamedThreadFactory("DubboMonitorCreator", true)); + private static final ExecutorService executor = new ThreadPoolExecutor( + 0, + 10, + 60L, + TimeUnit.SECONDS, + new SynchronousQueue(), + new NamedThreadFactory("DubboMonitorCreator", true)); @Test void testCreate() throws InterruptedException { final CountDownLatch countDownLatch = new CountDownLatch(1); - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> { - countDownLatch.countDown(); - return true; - }, executor); + CompletableFuture completableFuture = CompletableFuture.supplyAsync( + () -> { + countDownLatch.countDown(); + return true; + }, + executor); countDownLatch.await(); } @Test void testRunnableResponse() throws ExecutionException, InterruptedException { CountDownLatch latch = new CountDownLatch(1); - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> { - try { - latch.await(); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - return true; - }, executor); + CompletableFuture completableFuture = CompletableFuture.supplyAsync( + () -> { + try { + latch.await(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + return true; + }, + executor); Assertions.assertNull(completableFuture.getNow(null)); latch.countDown(); Boolean result = completableFuture.get(); @@ -74,25 +83,26 @@ class CompletableFutureTaskTest { @Test void testListener() throws InterruptedException { AtomicBoolean run = new AtomicBoolean(false); - CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> { - run.set(true); - return "hello"; - - }, executor); + CompletableFuture completableFuture = CompletableFuture.supplyAsync( + () -> { + run.set(true); + return "hello"; + }, + executor); final CountDownLatch countDownLatch = new CountDownLatch(1); completableFuture.thenRunAsync(countDownLatch::countDown); countDownLatch.await(); Assertions.assertTrue(run.get()); } - @Test void testCustomExecutor() { Executor mockedExecutor = mock(Executor.class); CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> { return 0; }); - completableFuture.thenRunAsync(mock(Runnable.class), mockedExecutor).whenComplete((s, e) -> - verify(mockedExecutor, times(1)).execute(any(Runnable.class))); + completableFuture + .thenRunAsync(mock(Runnable.class), mockedExecutor) + .whenComplete((s, e) -> verify(mockedExecutor, times(1)).execute(any(Runnable.class))); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/CompositeConfigurationTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/config/CompositeConfigurationTest.java index 09d4ca7fa7..e760388abd 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/config/CompositeConfigurationTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/config/CompositeConfigurationTest.java @@ -29,7 +29,7 @@ class CompositeConfigurationTest { InmemoryConfiguration inmemoryConfiguration1 = new InmemoryConfiguration(); InmemoryConfiguration inmemoryConfiguration2 = new InmemoryConfiguration(); InmemoryConfiguration inmemoryConfiguration3 = new InmemoryConfiguration(); - CompositeConfiguration configuration = new CompositeConfiguration(new Configuration[]{inmemoryConfiguration1}); + CompositeConfiguration configuration = new CompositeConfiguration(new Configuration[] {inmemoryConfiguration1}); configuration.addConfiguration(inmemoryConfiguration2); configuration.addConfigurationFirst(inmemoryConfiguration3); @@ -39,4 +39,4 @@ class CompositeConfigurationTest { Assertions.assertEquals(configuration.getInternalProperty("k"), "v3"); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/ConfigurationCacheTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/config/ConfigurationCacheTest.java index acf6a3b229..9db46866fd 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/config/ConfigurationCacheTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/config/ConfigurationCacheTest.java @@ -32,4 +32,4 @@ class ConfigurationCacheTest { value = configurationCache.computeIfAbsent("k1", k -> "v2"); Assertions.assertEquals(value, "v1"); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/ConfigurationUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/config/ConfigurationUtilsTest.java index 16853eb32e..4879c9de9d 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/config/ConfigurationUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/config/ConfigurationUtilsTest.java @@ -20,12 +20,12 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; +import java.util.Map; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.Map; - import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; /** @@ -72,16 +72,17 @@ class ConfigurationUtilsTest { } @Test - void testGetServerShutdownTimeout () { + void testGetServerShutdownTimeout() { System.setProperty(SHUTDOWN_WAIT_KEY, " 10000"); Assertions.assertEquals(10000, ConfigurationUtils.getServerShutdownTimeout(ApplicationModel.defaultModel())); System.clearProperty(SHUTDOWN_WAIT_KEY); } @Test - void testGetProperty () { + void testGetProperty() { System.setProperty(SHUTDOWN_WAIT_KEY, " 10000"); - Assertions.assertEquals("10000", ConfigurationUtils.getProperty(ApplicationModel.defaultModel(), SHUTDOWN_WAIT_KEY)); + Assertions.assertEquals( + "10000", ConfigurationUtils.getProperty(ApplicationModel.defaultModel(), SHUTDOWN_WAIT_KEY)); System.clearProperty(SHUTDOWN_WAIT_KEY); } @@ -107,6 +108,7 @@ class ConfigurationUtilsTest { String p1 = "dubbo.registry.address=zookeeper://127.0.0.1:2181\\\\ndubbo.protocol.port=20880"; Map result = ConfigurationUtils.parseProperties(p1); Assertions.assertEquals(1, result.size()); - Assertions.assertEquals("zookeeper://127.0.0.1:2181\\ndubbo.protocol.port=20880", result.get("dubbo.registry.address")); + Assertions.assertEquals( + "zookeeper://127.0.0.1:2181\\ndubbo.protocol.port=20880", result.get("dubbo.registry.address")); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/EnvironmentConfigurationTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/config/EnvironmentConfigurationTest.java index f6806b7ab4..7ff12664f6 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/config/EnvironmentConfigurationTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/config/EnvironmentConfigurationTest.java @@ -16,12 +16,12 @@ */ package org.apache.dubbo.common.config; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + /** * The type Environment configuration test. */ diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/EnvironmentTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/config/EnvironmentTest.java index e0a1204193..81e940f95c 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/config/EnvironmentTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/config/EnvironmentTest.java @@ -22,14 +22,14 @@ import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; /** @@ -58,7 +58,6 @@ class EnvironmentTest { System.clearProperty(key); } } - } @Test diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/InmemoryConfigurationTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/config/InmemoryConfigurationTest.java index 50c55c00fe..d5d3cc1cab 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/config/InmemoryConfigurationTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/config/InmemoryConfigurationTest.java @@ -18,15 +18,15 @@ package org.apache.dubbo.common.config; import org.apache.dubbo.common.beanutil.JavaBeanAccessor; +import java.util.HashMap; +import java.util.Map; +import java.util.NoSuchElementException; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.HashMap; -import java.util.Map; -import java.util.NoSuchElementException; - /** * Unit test of class InmemoryConfiguration, and interface Configuration. */ @@ -82,7 +82,6 @@ class InmemoryConfigurationTest { Assertions.assertNotNull(memConfig.getInternalProperty(MOCK_THREE_KEY)); Assertions.assertNull(memConfig.getInternalProperty(MOCK_ONE_KEY)); Assertions.assertNull(memConfig.getInternalProperty(MOCK_TWO_KEY)); - } @Test @@ -155,8 +154,5 @@ class InmemoryConfigurationTest { * Clean. */ @AfterEach - public void clean() { - - } - -} \ No newline at end of file + public void clean() {} +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/OrderedPropertiesConfigurationTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/config/OrderedPropertiesConfigurationTest.java index 45525c7191..8fc082de28 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/config/OrderedPropertiesConfigurationTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/config/OrderedPropertiesConfigurationTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.config; - import org.apache.dubbo.rpc.model.ApplicationModel; import org.junit.jupiter.api.Assertions; @@ -29,8 +28,8 @@ class OrderedPropertiesConfigurationTest { @Test void testOrderPropertiesProviders() { - OrderedPropertiesConfiguration configuration = new OrderedPropertiesConfiguration(ApplicationModel.defaultModel().getDefaultModule()); + OrderedPropertiesConfiguration configuration = new OrderedPropertiesConfiguration( + ApplicationModel.defaultModel().getDefaultModule()); Assertions.assertEquals("999", configuration.getInternalProperty("testKey")); } - -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/PrefixedConfigurationTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/config/PrefixedConfigurationTest.java index 8f7d89fb0a..7d6f7da649 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/config/PrefixedConfigurationTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/config/PrefixedConfigurationTest.java @@ -16,17 +16,17 @@ */ package org.apache.dubbo.common.config; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.LinkedHashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class PrefixedConfigurationTest { @Test void testPrefixedConfiguration() { - Map props = new LinkedHashMap<>(); + Map props = new LinkedHashMap<>(); props.put("dubbo.protocol.name", "dubbo"); props.put("dubbo.protocol.port", "1234"); props.put("dubbo.protocols.rest.port", "2345"); @@ -34,7 +34,8 @@ class PrefixedConfigurationTest { inmemoryConfiguration.addProperties(props); // prefixed over InmemoryConfiguration - PrefixedConfiguration prefixedConfiguration = new PrefixedConfiguration(inmemoryConfiguration, "dubbo.protocol"); + PrefixedConfiguration prefixedConfiguration = + new PrefixedConfiguration(inmemoryConfiguration, "dubbo.protocol"); Assertions.assertEquals("dubbo", prefixedConfiguration.getProperty("name")); Assertions.assertEquals("1234", prefixedConfiguration.getProperty("port")); @@ -46,6 +47,5 @@ class PrefixedConfigurationTest { compositeConfiguration.addConfiguration(inmemoryConfiguration); prefixedConfiguration = new PrefixedConfiguration(compositeConfiguration, "dubbo.protocols.rest"); Assertions.assertEquals("2345", prefixedConfiguration.getProperty("port")); - } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/PropertiesConfigurationTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/config/PropertiesConfigurationTest.java index 9394a6cacf..4f0ba07705 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/config/PropertiesConfigurationTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/config/PropertiesConfigurationTest.java @@ -18,11 +18,11 @@ package org.apache.dubbo.common.config; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.Map; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.Map; - /** * {@link PropertiesConfiguration} */ @@ -45,4 +45,4 @@ class PropertiesConfigurationTest { propertiesConfiguration.remove("k1"); Assertions.assertNull(propertiesConfiguration.getProperty("k1")); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/SystemConfigurationTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/config/SystemConfigurationTest.java index 39fb018695..c9aa6583b6 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/config/SystemConfigurationTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/config/SystemConfigurationTest.java @@ -68,8 +68,7 @@ class SystemConfigurationTest { */ @Test void testConvert() { - Assertions.assertEquals( - MOCK_STRING_VALUE, sysConfig.convert(String.class, NOT_EXIST_KEY, MOCK_STRING_VALUE)); + Assertions.assertEquals(MOCK_STRING_VALUE, sysConfig.convert(String.class, NOT_EXIST_KEY, MOCK_STRING_VALUE)); System.setProperty(MOCK_KEY, String.valueOf(MOCK_BOOL_VALUE)); Assertions.assertEquals(MOCK_BOOL_VALUE, sysConfig.convert(Boolean.class, MOCK_KEY, null)); System.setProperty(MOCK_KEY, String.valueOf(MOCK_STRING_VALUE)); @@ -113,5 +112,4 @@ class SystemConfigurationTest { */ MockTwo } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfigurationFactoryTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfigurationFactoryTest.java index 4633dd3ec8..09535c7caf 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfigurationFactoryTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfigurationFactoryTest.java @@ -49,4 +49,4 @@ class AbstractDynamicConfigurationFactoryTest { URL url = URL.valueOf("nop://127.0.0.1"); assertEquals(factory.getDynamicConfiguration(url), factory.getDynamicConfiguration(url)); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfigurationTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfigurationTest.java index 15367ec83c..1429f30eeb 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfigurationTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfigurationTest.java @@ -18,13 +18,13 @@ package org.apache.dubbo.common.config.configcenter; import org.apache.dubbo.common.URL; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.config.configcenter.AbstractDynamicConfiguration.DEFAULT_THREAD_POOL_KEEP_ALIVE_TIME; import static org.apache.dubbo.common.config.configcenter.AbstractDynamicConfiguration.DEFAULT_THREAD_POOL_PREFIX; import static org.apache.dubbo.common.config.configcenter.AbstractDynamicConfiguration.DEFAULT_THREAD_POOL_SIZE; @@ -57,9 +57,7 @@ class AbstractDynamicConfigurationTest { } @Override - protected void doClose() { - - } + protected void doClose() {} @Override protected boolean doRemoveConfig(String key, String group) { @@ -98,9 +96,7 @@ class AbstractDynamicConfigurationTest { } @Override - protected void doClose() { - - } + protected void doClose() {} @Override protected boolean doRemoveConfig(String key, String group) { @@ -111,8 +107,7 @@ class AbstractDynamicConfigurationTest { ThreadPoolExecutor threadPoolExecutor = configuration.getWorkersThreadPool(); ThreadFactory threadFactory = threadPoolExecutor.getThreadFactory(); - Thread thread = threadFactory.newThread(() -> { - }); + Thread thread = threadFactory.newThread(() -> {}); assertEquals(10, threadPoolExecutor.getCorePoolSize()); assertEquals(10, threadPoolExecutor.getMaximumPoolSize()); @@ -125,11 +120,11 @@ class AbstractDynamicConfigurationTest { assertFalse(configuration.publishConfig(null, null)); assertFalse(configuration.publishConfig(null, null, null)); } -// -// @Test -// public void testGetConfigKeys() { -// assertTrue(configuration.getConfigKeys(null).isEmpty()); -// } + // + // @Test + // public void testGetConfigKeys() { + // assertTrue(configuration.getConfigKeys(null).isEmpty()); + // } @Test void testGetConfig() { diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/ConfigChangeTypeTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/ConfigChangeTypeTest.java index 8b3224b13e..b315bf08a0 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/ConfigChangeTypeTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/ConfigChangeTypeTest.java @@ -33,6 +33,6 @@ class ConfigChangeTypeTest { @Test void testMembers() { - assertArrayEquals(new ConfigChangeType[]{ADDED, MODIFIED, DELETED}, ConfigChangeType.values()); + assertArrayEquals(new ConfigChangeType[] {ADDED, MODIFIED, DELETED}, ConfigChangeType.values()); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/ConfigChangedEventTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/ConfigChangedEventTest.java index 55183f3cd0..dd298cedd9 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/ConfigChangedEventTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/ConfigChangedEventTest.java @@ -57,9 +57,15 @@ class ConfigChangedEventTest { @Test void testEqualsAndHashCode() { for (ConfigChangeType type : ConfigChangeType.values()) { - assertEquals(new ConfigChangedEvent(KEY, GROUP, CONTENT, type), new ConfigChangedEvent(KEY, GROUP, CONTENT, type)); - assertEquals(new ConfigChangedEvent(KEY, GROUP, CONTENT, type).hashCode(), new ConfigChangedEvent(KEY, GROUP, CONTENT, type).hashCode()); - assertEquals(new ConfigChangedEvent(KEY, GROUP, CONTENT, type).toString(), new ConfigChangedEvent(KEY, GROUP, CONTENT, type).toString()); + assertEquals( + new ConfigChangedEvent(KEY, GROUP, CONTENT, type), + new ConfigChangedEvent(KEY, GROUP, CONTENT, type)); + assertEquals( + new ConfigChangedEvent(KEY, GROUP, CONTENT, type).hashCode(), + new ConfigChangedEvent(KEY, GROUP, CONTENT, type).hashCode()); + assertEquals( + new ConfigChangedEvent(KEY, GROUP, CONTENT, type).toString(), + new ConfigChangedEvent(KEY, GROUP, CONTENT, type).toString()); } } @@ -68,4 +74,4 @@ class ConfigChangedEventTest { ConfigChangedEvent event = new ConfigChangedEvent(KEY, GROUP, CONTENT); assertNotNull(event.toString()); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/DynamicConfigurationFactoryTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/DynamicConfigurationFactoryTest.java index c5ef627379..baeb9fd118 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/DynamicConfigurationFactoryTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/DynamicConfigurationFactoryTest.java @@ -33,9 +33,14 @@ class DynamicConfigurationFactoryTest { @Test void testDefaultExtension() { - DynamicConfigurationFactory factory = getExtensionLoader(DynamicConfigurationFactory.class).getDefaultExtension(); + DynamicConfigurationFactory factory = + getExtensionLoader(DynamicConfigurationFactory.class).getDefaultExtension(); assertEquals(NopDynamicConfigurationFactory.class, factory.getClass()); - assertEquals(NopDynamicConfigurationFactory.class, getExtensionLoader(DynamicConfigurationFactory.class).getExtension("nop").getClass()); + assertEquals( + NopDynamicConfigurationFactory.class, + getExtensionLoader(DynamicConfigurationFactory.class) + .getExtension("nop") + .getClass()); } private ExtensionLoader getExtensionLoader(Class extClass) { diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/constants/CommonConstantsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/constants/CommonConstantsTest.java index 7ab68f44b5..694124cc7d 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/constants/CommonConstantsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/constants/CommonConstantsTest.java @@ -38,4 +38,4 @@ class CommonConstantsTest { assertEquals("service-name-mapping.properties-path", SERVICE_NAME_MAPPING_PROPERTIES_FILE_KEY); assertEquals("META-INF/dubbo/service-name-mapping.properties", DEFAULT_SERVICE_NAME_MAPPING_PROPERTIES_PATH); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/ConverterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/ConverterTest.java index 3a1407c2d6..c01a5323c5 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/ConverterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/ConverterTest.java @@ -48,11 +48,9 @@ class ConverterTest { @Test void testGetConverter() { - getExtensionLoader(Converter.class) - .getSupportedExtensionInstances() - .forEach(converter -> { - assertSame(converter, converterUtil.getConverter(converter.getSourceType(), converter.getTargetType())); - }); + getExtensionLoader(Converter.class).getSupportedExtensionInstances().forEach(converter -> { + assertSame(converter, converterUtil.getConverter(converter.getSourceType(), converter.getTargetType())); + }); } @Test diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToBooleanConverterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToBooleanConverterTest.java index 64dbe23e86..8b0c69d0fd 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToBooleanConverterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToBooleanConverterTest.java @@ -35,7 +35,8 @@ class StringToBooleanConverterTest { @BeforeEach public void init() { - converter = (StringToBooleanConverter) getExtensionLoader(Converter.class).getExtension("string-to-boolean"); + converter = + (StringToBooleanConverter) getExtensionLoader(Converter.class).getExtension("string-to-boolean"); } @Test @@ -52,4 +53,4 @@ class StringToBooleanConverterTest { assertNull(converter.convert("")); assertNull(converter.convert(null)); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToCharArrayConverterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToCharArrayConverterTest.java index e05a315b57..bbc6733c0e 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToCharArrayConverterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToCharArrayConverterTest.java @@ -35,7 +35,8 @@ class StringToCharArrayConverterTest { @BeforeEach public void init() { - converter = (StringToCharArrayConverter) getExtensionLoader(Converter.class).getExtension("string-to-char-array"); + converter = + (StringToCharArrayConverter) getExtensionLoader(Converter.class).getExtension("string-to-char-array"); } @Test @@ -45,7 +46,7 @@ class StringToCharArrayConverterTest { @Test void testConvert() { - assertArrayEquals(new char[]{'1', '2', '3'}, converter.convert("123")); + assertArrayEquals(new char[] {'1', '2', '3'}, converter.convert("123")); assertNull(converter.convert(null)); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToCharacterConverterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToCharacterConverterTest.java index c5c321397b..289cd31cf6 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToCharacterConverterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToCharacterConverterTest.java @@ -36,7 +36,8 @@ class StringToCharacterConverterTest { @BeforeEach public void init() { - converter = (StringToCharacterConverter) getExtensionLoader(Converter.class).getExtension("string-to-character"); + converter = + (StringToCharacterConverter) getExtensionLoader(Converter.class).getExtension("string-to-character"); } @Test @@ -52,4 +53,4 @@ class StringToCharacterConverterTest { converter.convert("ttt"); }); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToDoubleConverterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToDoubleConverterTest.java index ae92ee6151..586533cf10 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToDoubleConverterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToDoubleConverterTest.java @@ -36,7 +36,8 @@ class StringToDoubleConverterTest { @BeforeEach public void init() { - converter = (StringToDoubleConverter) getExtensionLoader(Converter.class).getExtension("string-to-double"); + converter = + (StringToDoubleConverter) getExtensionLoader(Converter.class).getExtension("string-to-double"); } @Test @@ -52,4 +53,4 @@ class StringToDoubleConverterTest { converter.convert("ttt"); }); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToDurationConverterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToDurationConverterTest.java index b8fe980dc0..f31f974969 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToDurationConverterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToDurationConverterTest.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.common.convert; +import java.time.Duration; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.time.Duration; - import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; @@ -38,7 +38,8 @@ class StringToDurationConverterTest { @BeforeEach public void init() { - converter = (StringToDurationConverter) getExtensionLoader(Converter.class).getExtension("string-to-duration"); + converter = + (StringToDurationConverter) getExtensionLoader(Converter.class).getExtension("string-to-duration"); } @Test @@ -59,4 +60,4 @@ class StringToDurationConverterTest { converter.convert("ttt"); }); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToFloatConverterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToFloatConverterTest.java index 794e7ca325..9b2924b8c0 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToFloatConverterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToFloatConverterTest.java @@ -52,4 +52,4 @@ class StringToFloatConverterTest { converter.convert("ttt"); }); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToIntegerConverterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToIntegerConverterTest.java index 5a648d9fe1..ddd6d6bfc0 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToIntegerConverterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToIntegerConverterTest.java @@ -36,7 +36,8 @@ class StringToIntegerConverterTest { @BeforeEach public void init() { - converter = (StringToIntegerConverter) getExtensionLoader(Converter.class).getExtension("string-to-integer"); + converter = + (StringToIntegerConverter) getExtensionLoader(Converter.class).getExtension("string-to-integer"); } @Test @@ -52,4 +53,4 @@ class StringToIntegerConverterTest { converter.convert("ttt"); }); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToOptionalConverterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToOptionalConverterTest.java index f2edaeac93..1f3cccf10f 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToOptionalConverterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToOptionalConverterTest.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.common.convert; +import java.util.Optional; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Optional; - import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -36,7 +36,8 @@ class StringToOptionalConverterTest { @BeforeEach public void init() { - converter = (StringToOptionalConverter) getExtensionLoader(Converter.class).getExtension("string-to-optional"); + converter = + (StringToOptionalConverter) getExtensionLoader(Converter.class).getExtension("string-to-optional"); } @Test @@ -49,4 +50,4 @@ class StringToOptionalConverterTest { assertEquals(Optional.of("1"), converter.convert("1")); assertEquals(Optional.empty(), converter.convert(null)); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToShortConverterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToShortConverterTest.java index b349d1cef2..4bd74ca69e 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToShortConverterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToShortConverterTest.java @@ -52,4 +52,4 @@ class StringToShortConverterTest { converter.convert("ttt"); }); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToStringConverterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToStringConverterTest.java index aeada364ed..22a21d751f 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToStringConverterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/StringToStringConverterTest.java @@ -35,7 +35,8 @@ class StringToStringConverterTest { @BeforeEach public void init() { - converter = (StringToStringConverter) getExtensionLoader(Converter.class).getExtension("string-to-string"); + converter = + (StringToStringConverter) getExtensionLoader(Converter.class).getExtension("string-to-string"); } @Test @@ -48,4 +49,4 @@ class StringToStringConverterTest { assertEquals("1", converter.convert("1")); assertNull(converter.convert(null)); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/MultiValueConverterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/MultiValueConverterTest.java index ac904bbc8f..c15b8403ec 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/MultiValueConverterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/MultiValueConverterTest.java @@ -16,8 +16,6 @@ */ package org.apache.dubbo.common.convert.multiple; -import org.junit.jupiter.api.Test; - import java.util.Collection; import java.util.Deque; import java.util.List; @@ -28,6 +26,8 @@ import java.util.concurrent.BlockingDeque; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TransferQueue; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; /** @@ -69,4 +69,4 @@ class MultiValueConverterTest { converter = MultiValueConverter.find(String.class, TransferQueue.class); assertEquals(StringToTransferQueueConverter.class, converter.getClass()); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToArrayConverterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToArrayConverterTest.java index 0565c290d0..26be6d3e55 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToArrayConverterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToArrayConverterTest.java @@ -52,8 +52,8 @@ class StringToArrayConverterTest { @Test void testConvert() { - assertTrue(deepEquals(new Integer[]{123}, converter.convert("123", Integer[].class, Integer.class))); - assertTrue(deepEquals(new Integer[]{1, 2, 3}, converter.convert("1,2,3", Integer[].class, null))); + assertTrue(deepEquals(new Integer[] {123}, converter.convert("123", Integer[].class, Integer.class))); + assertTrue(deepEquals(new Integer[] {1, 2, 3}, converter.convert("1,2,3", Integer[].class, null))); assertNull(converter.convert("", Integer[].class, null)); assertNull(converter.convert(null, Integer[].class, null)); } @@ -67,4 +67,4 @@ class StringToArrayConverterTest { void testGetPriority() { assertEquals(Integer.MAX_VALUE, converter.getPriority()); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToBlockingDequeConverterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToBlockingDequeConverterTest.java index a884972cdf..d7667db33b 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToBlockingDequeConverterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToBlockingDequeConverterTest.java @@ -19,9 +19,6 @@ package org.apache.dubbo.common.convert.multiple; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.JRE; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; @@ -39,6 +36,9 @@ import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TransferQueue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static java.util.Arrays.asList; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -94,7 +94,8 @@ class StringToBlockingDequeConverterTest { BlockingQueue values = new LinkedBlockingDeque(asList(1, 2, 3)); - BlockingDeque result = (BlockingDeque) converter.convert("1,2,3", BlockingDeque.class, Integer.class); + BlockingDeque result = + (BlockingDeque) converter.convert("1,2,3", BlockingDeque.class, Integer.class); assertTrue(CollectionUtils.equals(values, result)); @@ -106,7 +107,6 @@ class StringToBlockingDequeConverterTest { assertNull(converter.convert(null, Collection.class, null)); assertNull(converter.convert("", Collection.class, null)); - } @Test @@ -117,7 +117,8 @@ class StringToBlockingDequeConverterTest { @Test void testGetPriority() { // Since JDK21, add SequencedCollection - assertEquals(Integer.MAX_VALUE - (JRE.currentVersion().compareTo(JRE.JAVA_21) >= 0 ? 6 : 5), + assertEquals( + Integer.MAX_VALUE - (JRE.currentVersion().compareTo(JRE.JAVA_21) >= 0 ? 6 : 5), converter.getPriority()); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToBlockingQueueConverterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToBlockingQueueConverterTest.java index 2c830782ea..294bd47ee4 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToBlockingQueueConverterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToBlockingQueueConverterTest.java @@ -18,9 +18,6 @@ package org.apache.dubbo.common.convert.multiple; import org.apache.dubbo.common.utils.CollectionUtils; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; @@ -38,6 +35,9 @@ import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.TransferQueue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -95,7 +95,8 @@ class StringToBlockingQueueConverterTest { values.offer(2); values.offer(3); - BlockingQueue result = (BlockingQueue) converter.convert("1,2,3", BlockingDeque.class, Integer.class); + BlockingQueue result = + (BlockingQueue) converter.convert("1,2,3", BlockingDeque.class, Integer.class); assertTrue(CollectionUtils.equals(values, result)); @@ -108,7 +109,6 @@ class StringToBlockingQueueConverterTest { assertNull(converter.convert(null, Collection.class, null)); assertNull(converter.convert("", Collection.class, null)); - } @Test @@ -120,4 +120,4 @@ class StringToBlockingQueueConverterTest { void testGetPriority() { assertEquals(Integer.MAX_VALUE - 3, converter.getPriority()); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToCollectionConverterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToCollectionConverterTest.java index 37a3aa145c..b70f73390e 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToCollectionConverterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToCollectionConverterTest.java @@ -16,9 +16,6 @@ */ package org.apache.dubbo.common.convert.multiple; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; @@ -35,6 +32,9 @@ import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.TransferQueue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static java.util.Arrays.asList; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -101,7 +101,6 @@ class StringToCollectionConverterTest { assertNull(converter.convert(null, Collection.class, Integer.class)); assertNull(converter.convert("", Collection.class, Integer.class)); - } @Test @@ -113,4 +112,4 @@ class StringToCollectionConverterTest { void testGetPriority() { assertEquals(Integer.MAX_VALUE - 1, converter.getPriority()); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToDequeConverterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToDequeConverterTest.java index dd1800358b..f6a2e6d194 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToDequeConverterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToDequeConverterTest.java @@ -19,9 +19,6 @@ package org.apache.dubbo.common.convert.multiple; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.JRE; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.AbstractList; import java.util.ArrayDeque; import java.util.ArrayList; @@ -39,6 +36,9 @@ import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.TransferQueue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static java.util.Arrays.asList; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -115,7 +115,8 @@ class StringToDequeConverterTest { @Test void testGetPriority() { // Since JDK21, add SequencedCollection - assertEquals(Integer.MAX_VALUE - (JRE.currentVersion().compareTo(JRE.JAVA_21) >= 0 ? 4 : 3), + assertEquals( + Integer.MAX_VALUE - (JRE.currentVersion().compareTo(JRE.JAVA_21) >= 0 ? 4 : 3), converter.getPriority()); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToListConverterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToListConverterTest.java index cf3c4237fa..d88ad51846 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToListConverterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToListConverterTest.java @@ -19,9 +19,6 @@ package org.apache.dubbo.common.convert.multiple; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.JRE; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; @@ -38,6 +35,9 @@ import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.TransferQueue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static java.util.Arrays.asList; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -114,7 +114,8 @@ class StringToListConverterTest { @Test void testGetPriority() { // Since JDK21, add SequencedCollection - assertEquals(Integer.MAX_VALUE - (JRE.currentVersion().compareTo(JRE.JAVA_21) >= 0 ? 3 : 2), + assertEquals( + Integer.MAX_VALUE - (JRE.currentVersion().compareTo(JRE.JAVA_21) >= 0 ? 3 : 2), converter.getPriority()); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToNavigableSetConverterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToNavigableSetConverterTest.java index 95a7c59ee5..8f7b9ecde0 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToNavigableSetConverterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToNavigableSetConverterTest.java @@ -19,9 +19,6 @@ package org.apache.dubbo.common.convert.multiple; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.JRE; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; @@ -38,6 +35,9 @@ import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.TransferQueue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static java.util.Arrays.asList; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -114,7 +114,8 @@ class StringToNavigableSetConverterTest { @Test void testGetPriority() { // Since JDK21, add SequencedCollection, SequencedSet - assertEquals(Integer.MAX_VALUE - (JRE.currentVersion().compareTo(JRE.JAVA_21) >= 0 ? 6 : 4), + assertEquals( + Integer.MAX_VALUE - (JRE.currentVersion().compareTo(JRE.JAVA_21) >= 0 ? 6 : 4), converter.getPriority()); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToQueueConverterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToQueueConverterTest.java index 014b069bfe..f277cff506 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToQueueConverterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToQueueConverterTest.java @@ -19,9 +19,6 @@ package org.apache.dubbo.common.convert.multiple; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.AbstractList; import java.util.ArrayDeque; import java.util.ArrayList; @@ -39,6 +36,9 @@ import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.TransferQueue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static java.util.Arrays.asList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -116,4 +116,4 @@ class StringToQueueConverterTest { void testGetPriority() { assertEquals(Integer.MAX_VALUE - 2, converter.getPriority()); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToSetConverterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToSetConverterTest.java index 4c1c251ddc..f1295d2e83 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToSetConverterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToSetConverterTest.java @@ -19,9 +19,6 @@ package org.apache.dubbo.common.convert.multiple; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; @@ -39,6 +36,9 @@ import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.TransferQueue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static java.util.Arrays.asList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -115,4 +115,4 @@ class StringToSetConverterTest { void testGetPriority() { assertEquals(Integer.MAX_VALUE - 2, converter.getPriority()); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToSortedSetConverterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToSortedSetConverterTest.java index 2a18ea8e42..d84eb6a2c4 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToSortedSetConverterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToSortedSetConverterTest.java @@ -19,9 +19,6 @@ package org.apache.dubbo.common.convert.multiple; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.JRE; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; @@ -38,6 +35,9 @@ import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.TransferQueue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static java.util.Arrays.asList; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -114,7 +114,8 @@ class StringToSortedSetConverterTest { @Test void testGetPriority() { // Since JDK21, add SequencedCollection, SequencedSet - assertEquals(Integer.MAX_VALUE - (JRE.currentVersion().compareTo(JRE.JAVA_21) >= 0 ? 5 : 3), + assertEquals( + Integer.MAX_VALUE - (JRE.currentVersion().compareTo(JRE.JAVA_21) >= 0 ? 5 : 3), converter.getPriority()); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToTransferQueueConverterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToTransferQueueConverterTest.java index 3e46ef1c8c..c2fc0c6d9a 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToTransferQueueConverterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/convert/multiple/StringToTransferQueueConverterTest.java @@ -18,9 +18,6 @@ package org.apache.dubbo.common.convert.multiple; import org.apache.dubbo.common.utils.CollectionUtils; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; @@ -38,6 +35,9 @@ import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.LinkedTransferQueue; import java.util.concurrent.TransferQueue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static java.util.Arrays.asList; import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -117,4 +117,4 @@ class StringToTransferQueueConverterTest { void testGetPriority() { assertEquals(Integer.MAX_VALUE - 4, converter.getPriority()); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/AdaptiveClassCodeGeneratorTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/AdaptiveClassCodeGeneratorTest.java index 830e612c61..0cb05ff678 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/AdaptiveClassCodeGeneratorTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/AdaptiveClassCodeGeneratorTest.java @@ -19,14 +19,14 @@ package org.apache.dubbo.common.extension; import org.apache.dubbo.common.extension.adaptive.HasAdaptiveExt; import org.apache.dubbo.common.utils.IOUtils; -import org.junit.jupiter.api.Test; - import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertTrue; /** @@ -44,8 +44,8 @@ class AdaptiveClassCodeGeneratorTest { try (InputStream inputStream = url.openStream()) { String content = IOUtils.read(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); // in Windows platform content get from resource contains \r delimiter - content = content.replaceAll("\r",""); + content = content.replaceAll("\r", ""); assertTrue(content.contains(value)); } } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionDirectorTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionDirectorTest.java index ad1c7beb95..13f1945d18 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionDirectorTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionDirectorTest.java @@ -26,11 +26,11 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; +import java.util.Collection; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.Collection; - class ExtensionDirectorTest { String testFwSrvName = "testFwSrv"; @@ -45,21 +45,29 @@ class ExtensionDirectorTest { // 2. Child ExtensionDirector can get extension instance from parent // 3. Parent ExtensionDirector can't get extension instance from child - ExtensionDirector fwExtensionDirector = new ExtensionDirector(null, ExtensionScope.FRAMEWORK, FrameworkModel.defaultModel()); - ExtensionDirector appExtensionDirector = new ExtensionDirector(fwExtensionDirector, ExtensionScope.APPLICATION, ApplicationModel.defaultModel()); - ExtensionDirector moduleExtensionDirector = new ExtensionDirector(appExtensionDirector, ExtensionScope.MODULE, ApplicationModel.defaultModel().getDefaultModule()); + ExtensionDirector fwExtensionDirector = + new ExtensionDirector(null, ExtensionScope.FRAMEWORK, FrameworkModel.defaultModel()); + ExtensionDirector appExtensionDirector = + new ExtensionDirector(fwExtensionDirector, ExtensionScope.APPLICATION, ApplicationModel.defaultModel()); + ExtensionDirector moduleExtensionDirector = new ExtensionDirector( + appExtensionDirector, + ExtensionScope.MODULE, + ApplicationModel.defaultModel().getDefaultModule()); // test module extension loader - FooFrameworkService testFwSrvFromModule = moduleExtensionDirector.getExtension(FooFrameworkService.class, testFwSrvName); + FooFrameworkService testFwSrvFromModule = + moduleExtensionDirector.getExtension(FooFrameworkService.class, testFwSrvName); FooAppService testAppSrvFromModule = moduleExtensionDirector.getExtension(FooAppService.class, testAppSrvName); - FooModuleService testMdSrvFromModule = moduleExtensionDirector.getExtension(FooModuleService.class, testMdSrvName); + FooModuleService testMdSrvFromModule = + moduleExtensionDirector.getExtension(FooModuleService.class, testMdSrvName); Assertions.assertNotNull(testFwSrvFromModule); Assertions.assertNotNull(testAppSrvFromModule); Assertions.assertNotNull(testMdSrvFromModule); // test app extension loader - FooFrameworkService testFwSrvFromApp = appExtensionDirector.getExtension(FooFrameworkService.class, testFwSrvName); + FooFrameworkService testFwSrvFromApp = + appExtensionDirector.getExtension(FooFrameworkService.class, testFwSrvName); FooAppService testAppSrvFromApp = appExtensionDirector.getExtension(FooAppService.class, testAppSrvName); FooModuleService testMdSrvFromApp = appExtensionDirector.getExtension(FooModuleService.class, testMdSrvName); @@ -68,7 +76,8 @@ class ExtensionDirectorTest { Assertions.assertNull(testMdSrvFromApp); // test framework extension loader - FooFrameworkService testFwSrvFromFw = fwExtensionDirector.getExtension(FooFrameworkService.class, testFwSrvName); + FooFrameworkService testFwSrvFromFw = + fwExtensionDirector.getExtension(FooFrameworkService.class, testFwSrvName); FooAppService testAppSrvFromFw = fwExtensionDirector.getExtension(FooAppService.class, testAppSrvName); FooModuleService testMdSrvFromFw = fwExtensionDirector.getExtension(FooModuleService.class, testMdSrvName); @@ -78,9 +87,7 @@ class ExtensionDirectorTest { } @Test - void testPostProcessor() { - - } + void testPostProcessor() {} @Test void testModelAware() { @@ -103,9 +110,12 @@ class ExtensionDirectorTest { Assertions.assertSame(null, fwExtensionDirector.getParent()); // check module extension aware - TestFrameworkService testFwSrvFromModule = (TestFrameworkService) moduleExtensionDirector.getExtension(FooFrameworkService.class, testFwSrvName); - TestAppService testAppSrvFromModule = (TestAppService) moduleExtensionDirector.getExtension(FooAppService.class, testAppSrvName); - TestModuleService testMdSrvFromModule = (TestModuleService) moduleExtensionDirector.getExtension(FooModuleService.class, testMdSrvName); + TestFrameworkService testFwSrvFromModule = + (TestFrameworkService) moduleExtensionDirector.getExtension(FooFrameworkService.class, testFwSrvName); + TestAppService testAppSrvFromModule = + (TestAppService) moduleExtensionDirector.getExtension(FooAppService.class, testAppSrvName); + TestModuleService testMdSrvFromModule = + (TestModuleService) moduleExtensionDirector.getExtension(FooModuleService.class, testMdSrvName); Assertions.assertSame(frameworkModel, testFwSrvFromModule.getFrameworkModel()); Assertions.assertSame(null, testFwSrvFromModule.getApplicationModel()); @@ -120,16 +130,20 @@ class ExtensionDirectorTest { Assertions.assertSame(moduleModel, testMdSrvFromModule.getModuleModel()); // check app extension aware - TestFrameworkService testFwSrvFromApp = (TestFrameworkService) appExtensionDirector.getExtension(FooFrameworkService.class, testFwSrvName); - TestAppService testAppSrvFromApp = (TestAppService) appExtensionDirector.getExtension(FooAppService.class, testAppSrvName); - TestModuleService testMdSrvFromApp = (TestModuleService) appExtensionDirector.getExtension(FooModuleService.class, testMdSrvName); + TestFrameworkService testFwSrvFromApp = + (TestFrameworkService) appExtensionDirector.getExtension(FooFrameworkService.class, testFwSrvName); + TestAppService testAppSrvFromApp = + (TestAppService) appExtensionDirector.getExtension(FooAppService.class, testAppSrvName); + TestModuleService testMdSrvFromApp = + (TestModuleService) appExtensionDirector.getExtension(FooModuleService.class, testMdSrvName); Assertions.assertSame(testFwSrvFromApp, testFwSrvFromModule); Assertions.assertSame(testAppSrvFromApp, testAppSrvFromModule); Assertions.assertNull(testMdSrvFromApp); // check framework extension aware - FooFrameworkService testFwSrvFromFw = fwExtensionDirector.getExtension(FooFrameworkService.class, testFwSrvName); + FooFrameworkService testFwSrvFromFw = + fwExtensionDirector.getExtension(FooFrameworkService.class, testFwSrvName); FooAppService testAppSrvFromFw = fwExtensionDirector.getExtension(FooAppService.class, testAppSrvName); FooModuleService testMdSrvFromFw = fwExtensionDirector.getExtension(FooModuleService.class, testMdSrvName); @@ -140,14 +154,14 @@ class ExtensionDirectorTest { @Test void testModelDataIsolation() { - //Model Tree - //├─frameworkModel1 - //│ ├─applicationModel11 - //│ │ ├─moduleModel111 - //│ │ └─moduleModel112 - //│ └─applicationModel12 - //│ └─moduleModel121 - //└─frameworkModel2 + // Model Tree + // ├─frameworkModel1 + // │ ├─applicationModel11 + // │ │ ├─moduleModel111 + // │ │ └─moduleModel112 + // │ └─applicationModel12 + // │ └─moduleModel121 + // └─frameworkModel2 // └─applicationModel21 // └─moduleModel211 @@ -175,52 +189,70 @@ class ExtensionDirectorTest { Assertions.assertTrue(modulesOfApp11.contains(moduleModel112)); // test isolation of FrameworkModel - FooFrameworkService frameworkService1 = frameworkModel1.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); - FooFrameworkService frameworkService2 = frameworkModel2.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); + FooFrameworkService frameworkService1 = + frameworkModel1.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); + FooFrameworkService frameworkService2 = + frameworkModel2.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); Assertions.assertNotSame(frameworkService1, frameworkService2); // test isolation of ApplicationModel // applicationModel11 and applicationModel12 are shared frameworkModel1 - FooFrameworkService frameworkService11 = applicationModel11.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); - FooFrameworkService frameworkService12 = applicationModel12.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); + FooFrameworkService frameworkService11 = + applicationModel11.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); + FooFrameworkService frameworkService12 = + applicationModel12.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); Assertions.assertSame(frameworkService1, frameworkService11); Assertions.assertSame(frameworkService1, frameworkService12); // applicationModel11 and applicationModel12 are isolated in application scope - FooAppService applicationService11 = applicationModel11.getExtensionDirector().getExtension(FooAppService.class, testAppSrvName); - FooAppService applicationService12 = applicationModel12.getExtensionDirector().getExtension(FooAppService.class, testAppSrvName); + FooAppService applicationService11 = + applicationModel11.getExtensionDirector().getExtension(FooAppService.class, testAppSrvName); + FooAppService applicationService12 = + applicationModel12.getExtensionDirector().getExtension(FooAppService.class, testAppSrvName); Assertions.assertNotSame(applicationService11, applicationService12); // applicationModel11 and applicationModel21 are isolated in both framework and application scope - FooFrameworkService frameworkService21 = applicationModel21.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); - FooAppService applicationService21 = applicationModel21.getExtensionDirector().getExtension(FooAppService.class, testAppSrvName); + FooFrameworkService frameworkService21 = + applicationModel21.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); + FooAppService applicationService21 = + applicationModel21.getExtensionDirector().getExtension(FooAppService.class, testAppSrvName); Assertions.assertNotSame(frameworkService11, frameworkService21); Assertions.assertNotSame(applicationService11, applicationService21); // test isolation of ModuleModel - FooModuleService moduleService111 = moduleModel111.getExtensionDirector().getExtension(FooModuleService.class, testMdSrvName); - FooModuleService moduleService112 = moduleModel112.getExtensionDirector().getExtension(FooModuleService.class, testMdSrvName); + FooModuleService moduleService111 = + moduleModel111.getExtensionDirector().getExtension(FooModuleService.class, testMdSrvName); + FooModuleService moduleService112 = + moduleModel112.getExtensionDirector().getExtension(FooModuleService.class, testMdSrvName); // moduleModel111 and moduleModel112 are isolated in module scope Assertions.assertNotSame(moduleService111, moduleService112); // moduleModel111 and moduleModel112 are shared applicationModel11 - FooAppService applicationService111 = moduleModel111.getExtensionDirector().getExtension(FooAppService.class, testAppSrvName); - FooAppService applicationService112 = moduleModel112.getExtensionDirector().getExtension(FooAppService.class, testAppSrvName); + FooAppService applicationService111 = + moduleModel111.getExtensionDirector().getExtension(FooAppService.class, testAppSrvName); + FooAppService applicationService112 = + moduleModel112.getExtensionDirector().getExtension(FooAppService.class, testAppSrvName); Assertions.assertSame(applicationService111, applicationService112); // moduleModel111 and moduleModel121 are isolated in application scope, but shared frameworkModel1 - FooAppService applicationService121 = moduleModel121.getExtensionDirector().getExtension(FooAppService.class, testAppSrvName); + FooAppService applicationService121 = + moduleModel121.getExtensionDirector().getExtension(FooAppService.class, testAppSrvName); Assertions.assertNotSame(applicationService111, applicationService121); - FooFrameworkService frameworkService111 = moduleModel111.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); - FooFrameworkService frameworkService121 = moduleModel121.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); + FooFrameworkService frameworkService111 = + moduleModel111.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); + FooFrameworkService frameworkService121 = + moduleModel121.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); Assertions.assertSame(frameworkService111, frameworkService121); // moduleModel111 and moduleModel211 are isolated in both framework and application scope - FooModuleService moduleService211 = moduleModel211.getExtensionDirector().getExtension(FooModuleService.class, testMdSrvName); - FooAppService applicationService211 = moduleModel211.getExtensionDirector().getExtension(FooAppService.class, testAppSrvName); - FooFrameworkService frameworkService211 = moduleModel211.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); + FooModuleService moduleService211 = + moduleModel211.getExtensionDirector().getExtension(FooModuleService.class, testMdSrvName); + FooAppService applicationService211 = + moduleModel211.getExtensionDirector().getExtension(FooAppService.class, testAppSrvName); + FooFrameworkService frameworkService211 = + moduleModel211.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); Assertions.assertNotSame(moduleService111, moduleService211); Assertions.assertNotSame(applicationService111, applicationService211); Assertions.assertNotSame(frameworkService111, frameworkService211); @@ -231,7 +263,8 @@ class ExtensionDirectorTest { // Expect: // 1. Framework scope extension can be injected to extensions of Framework/Application/Module scope - // 2. Application scope extension can be injected to extensions of Application/Module scope, but not Framework scope + // 2. Application scope extension can be injected to extensions of Application/Module scope, but not Framework + // scope // 3. Module scope extension can be injected to extensions of Module scope, but not Framework/Application scope FrameworkModel frameworkModel = new FrameworkModel(); @@ -239,8 +272,8 @@ class ExtensionDirectorTest { ModuleModel moduleModel = applicationModel.newModule(); // check module service - TestModuleService moduleService = (TestModuleService) moduleModel.getExtensionDirector() - .getExtension(FooModuleService.class, testMdSrvName); + TestModuleService moduleService = (TestModuleService) + moduleModel.getExtensionDirector().getExtension(FooModuleService.class, testMdSrvName); Assertions.assertNotNull(moduleService.getFrameworkService()); Assertions.assertNotNull(moduleService.getFrameworkProvider()); Assertions.assertNotNull(moduleService.getAppService()); @@ -248,16 +281,16 @@ class ExtensionDirectorTest { Assertions.assertNotNull(moduleService.getModuleProvider()); // check app service - TestAppService appService = (TestAppService) applicationModel.getExtensionDirector() - .getExtension(FooAppService.class, testAppSrvName); + TestAppService appService = (TestAppService) + applicationModel.getExtensionDirector().getExtension(FooAppService.class, testAppSrvName); Assertions.assertNotNull(appService.getFrameworkService()); Assertions.assertNotNull(appService.getFrameworkProvider()); Assertions.assertNotNull(appService.getAppProvider()); Assertions.assertNull(appService.getModuleProvider()); // check framework service - TestFrameworkService frameworkService = (TestFrameworkService) frameworkModel.getExtensionDirector() - .getExtension(FooFrameworkService.class, testFwSrvName); + TestFrameworkService frameworkService = (TestFrameworkService) + frameworkModel.getExtensionDirector().getExtension(FooFrameworkService.class, testFwSrvName); Assertions.assertNotNull(frameworkService.getFrameworkProvider()); Assertions.assertNull(frameworkService.getAppProvider()); Assertions.assertNull(frameworkService.getModuleProvider()); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java index bbf27a61e1..cbcac7c8d7 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java @@ -71,14 +71,14 @@ import org.apache.dubbo.common.lang.Prioritized; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.extension.ExtensionLoader.getLoadingStrategies; import static org.hamcrest.CoreMatchers.allOf; @@ -107,8 +107,7 @@ class ExtensionLoaderTest { getExtensionLoader(null); fail(); } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage(), - containsString("Extension type == null")); + assertThat(expected.getMessage(), containsString("Extension type == null")); } } @@ -118,8 +117,10 @@ class ExtensionLoaderTest { getExtensionLoader(ExtensionLoaderTest.class); fail(); } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage(), - containsString("Extension type (class org.apache.dubbo.common.extension.ExtensionLoaderTest) is not an interface")); + assertThat( + expected.getMessage(), + containsString( + "Extension type (class org.apache.dubbo.common.extension.ExtensionLoaderTest) is not an interface")); } } @@ -129,10 +130,12 @@ class ExtensionLoaderTest { getExtensionLoader(NoSpiExt.class); fail(); } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage(), - allOf(containsString("org.apache.dubbo.common.extension.NoSpiExt"), - containsString("is not an extension"), - containsString("NOT annotated with @SPI"))); + assertThat( + expected.getMessage(), + allOf( + containsString("org.apache.dubbo.common.extension.NoSpiExt"), + containsString("is not an extension"), + containsString("NOT annotated with @SPI"))); } } @@ -177,11 +180,9 @@ class ExtensionLoaderTest { assertNotSame(unwrappedImpl1, impl1); assertSame(unwrappedImpl1, originImpl1); - WrappedExt impl2 = getExtensionLoader(WrappedExt.class).getExtension("impl2"); assertThat(impl2, anyOf(instanceOf(Ext6Wrapper1.class), instanceOf(Ext6Wrapper2.class))); - URL url = new ServiceConfigURL("p1", "1.2.3.4", 1010, "path1"); int echoCount1 = Ext6Wrapper1.echoCount.get(); int echoCount2 = Ext6Wrapper2.echoCount.get(); @@ -221,8 +222,8 @@ class ExtensionLoaderTest { @Test void test_getActivateExtension_WithWrapper1() { URL url = URL.valueOf("test://localhost/test"); - List list = getExtensionLoader(ActivateExt1.class) - .getActivateExtension(url, new String[]{}, "order"); + List list = + getExtensionLoader(ActivateExt1.class).getActivateExtension(url, new String[] {}, "order"); assertEquals(2, list.size()); } @@ -232,7 +233,9 @@ class ExtensionLoaderTest { getExtensionLoader(SimpleExt.class).getExtension("XXX"); fail(); } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("No such extension org.apache.dubbo.common.extension.ext1.SimpleExt by name XXX")); + assertThat( + expected.getMessage(), + containsString("No such extension org.apache.dubbo.common.extension.ext1.SimpleExt by name XXX")); } } @@ -242,7 +245,10 @@ class ExtensionLoaderTest { getExtensionLoader(WrappedExt.class).getExtension("XXX"); fail(); } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("No such extension org.apache.dubbo.common.extension.ext6_wrap.WrappedExt by name XXX")); + assertThat( + expected.getMessage(), + containsString( + "No such extension org.apache.dubbo.common.extension.ext6_wrap.WrappedExt by name XXX")); } } @@ -317,7 +323,10 @@ class ExtensionLoaderTest { getExtensionLoader(AddExt1.class).getExtension("Manual1"); fail(); } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("No such extension org.apache.dubbo.common.extension.ext8_add.AddExt1 by name Manual")); + assertThat( + expected.getMessage(), + containsString( + "No such extension org.apache.dubbo.common.extension.ext8_add.AddExt1 by name Manual")); } getExtensionLoader(AddExt1.class).addExtension("Manual1", AddExt1_ManualAdd1.class); @@ -344,7 +353,10 @@ class ExtensionLoaderTest { getExtensionLoader(AddExt1.class).addExtension("impl1", AddExt1_ManualAdd1.class); fail(); } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("Extension name impl1 already exists (Extension interface org.apache.dubbo.common.extension.ext8_add.AddExt1)!")); + assertThat( + expected.getMessage(), + containsString( + "Extension name impl1 already exists (Extension interface org.apache.dubbo.common.extension.ext8_add.AddExt1)!")); } } @@ -367,7 +379,10 @@ class ExtensionLoaderTest { loader.addExtension(null, AddExt1_ManualAdaptive.class); fail(); } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("Adaptive Extension already exists (Extension interface org.apache.dubbo.common.extension.ext8_add.AddExt1)!")); + assertThat( + expected.getMessage(), + containsString( + "Adaptive Extension already exists (Extension interface org.apache.dubbo.common.extension.ext8_add.AddExt1)!")); } } @@ -376,9 +391,11 @@ class ExtensionLoaderTest { try { getExtensionLoader(SimpleExt.class).addExtension("impl1", ExtensionLoaderTest.class); } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), - containsString("Input type class org.apache.dubbo.common.extension.ExtensionLoaderTest " + - "doesn't implement the Extension interface org.apache.dubbo.common.extension.ext1.SimpleExt")); + assertThat( + expected.getMessage(), + containsString( + "Input type class org.apache.dubbo.common.extension.ExtensionLoaderTest " + + "doesn't implement the Extension interface org.apache.dubbo.common.extension.ext1.SimpleExt")); } } @@ -387,9 +404,10 @@ class ExtensionLoaderTest { try { getExtensionLoader(SimpleExt.class).addExtension("impl1", SimpleExt.class); } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), - containsString("Input type interface org.apache.dubbo.common.extension.ext1.SimpleExt " + - "can't be interface!")); + assertThat( + expected.getMessage(), + containsString("Input type interface org.apache.dubbo.common.extension.ext1.SimpleExt " + + "can't be interface!")); } } @@ -398,9 +416,11 @@ class ExtensionLoaderTest { try { getExtensionLoader(NoAdaptiveExt.class).addExtension(null, NoAdaptiveExtImpl.class); } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), - containsString("Extension name is blank " + - "(Extension interface org.apache.dubbo.common.extension.ext11_no_adaptive.NoAdaptiveExt)!")); + assertThat( + expected.getMessage(), + containsString( + "Extension name is blank " + + "(Extension interface org.apache.dubbo.common.extension.ext11_no_adaptive.NoAdaptiveExt)!")); } } @@ -448,7 +468,8 @@ class ExtensionLoaderTest { SimpleExt simpleExt2 = getExtensionLoader(SimpleExt.class).getExtension("impl2"); assertThat(simpleExt2, instanceOf(SimpleExtImpl2.class)); - List loadedExtensionInstances = getExtensionLoader(SimpleExt.class).getLoadedExtensionInstances(); + List loadedExtensionInstances = + getExtensionLoader(SimpleExt.class).getLoadedExtensionInstances(); Assertions.assertNotNull(loadedExtensionInstances); } @@ -457,9 +478,11 @@ class ExtensionLoaderTest { try { getExtensionLoader(SimpleExt.class).replaceExtension("impl1", ExtensionLoaderTest.class); } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), - containsString("Input type class org.apache.dubbo.common.extension.ExtensionLoaderTest " + - "doesn't implement Extension interface org.apache.dubbo.common.extension.ext1.SimpleExt")); + assertThat( + expected.getMessage(), + containsString( + "Input type class org.apache.dubbo.common.extension.ExtensionLoaderTest " + + "doesn't implement Extension interface org.apache.dubbo.common.extension.ext1.SimpleExt")); } } @@ -468,9 +491,10 @@ class ExtensionLoaderTest { try { getExtensionLoader(SimpleExt.class).replaceExtension("impl1", SimpleExt.class); } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), - containsString("Input type interface org.apache.dubbo.common.extension.ext1.SimpleExt " + - "can't be interface!")); + assertThat( + expected.getMessage(), + containsString("Input type interface org.apache.dubbo.common.extension.ext1.SimpleExt " + + "can't be interface!")); } } @@ -480,7 +504,10 @@ class ExtensionLoaderTest { getExtensionLoader(AddExt1.class).getExtension("Manual2"); fail(); } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("No such extension org.apache.dubbo.common.extension.ext8_add.AddExt1 by name Manual")); + assertThat( + expected.getMessage(), + containsString( + "No such extension org.apache.dubbo.common.extension.ext8_add.AddExt1 by name Manual")); } { @@ -519,7 +546,10 @@ class ExtensionLoaderTest { getExtensionLoader(AddExt1.class).replaceExtension("NotExistedExtension", AddExt1_ManualAdd1.class); fail(); } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("Extension name NotExistedExtension doesn't exist (Extension interface org.apache.dubbo.common.extension.ext8_add.AddExt1)")); + assertThat( + expected.getMessage(), + containsString( + "Extension name NotExistedExtension doesn't exist (Extension interface org.apache.dubbo.common.extension.ext8_add.AddExt1)")); } } @@ -531,7 +561,10 @@ class ExtensionLoaderTest { loader.replaceExtension(null, AddExt4_ManualAdaptive.class); fail(); } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("Adaptive Extension doesn't exist (Extension interface org.apache.dubbo.common.extension.ext8_add.AddExt4)")); + assertThat( + expected.getMessage(), + containsString( + "Adaptive Extension doesn't exist (Extension interface org.apache.dubbo.common.extension.ext8_add.AddExt4)")); } } @@ -545,7 +578,10 @@ class ExtensionLoaderTest { loader.getExtension("error"); fail(); } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("Failed to load extension class (interface: interface org.apache.dubbo.common.extension.ext7.InitErrorExt")); + assertThat( + expected.getMessage(), + containsString( + "Failed to load extension class (interface: interface org.apache.dubbo.common.extension.ext7.InitErrorExt")); assertThat(expected.getMessage(), containsString("java.lang.ExceptionInInitializerError")); } } @@ -554,15 +590,14 @@ class ExtensionLoaderTest { void testLoadActivateExtension() { // test default URL url = URL.valueOf("test://localhost/test"); - List list = getExtensionLoader(ActivateExt1.class) - .getActivateExtension(url, new String[]{}, "default_group"); + List list = + getExtensionLoader(ActivateExt1.class).getActivateExtension(url, new String[] {}, "default_group"); Assertions.assertEquals(1, list.size()); assertSame(list.get(0).getClass(), ActivateExt1Impl1.class); // test group url = url.addParameter(GROUP_KEY, "group1"); - list = getExtensionLoader(ActivateExt1.class) - .getActivateExtension(url, new String[]{}, "group1"); + list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, new String[] {}, "group1"); Assertions.assertEquals(1, list.size()); assertSame(list.get(0).getClass(), GroupActivateExtImpl.class); @@ -570,16 +605,14 @@ class ExtensionLoaderTest { url = url.removeParameter(GROUP_KEY); url = url.addParameter(GROUP_KEY, "value"); url = url.addParameter("value", "value"); - list = getExtensionLoader(ActivateExt1.class) - .getActivateExtension(url, new String[]{}, "value"); + list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, new String[] {}, "value"); Assertions.assertEquals(1, list.size()); assertSame(list.get(0).getClass(), ValueActivateExtImpl.class); // test order url = URL.valueOf("test://localhost/test"); url = url.addParameter(GROUP_KEY, "order"); - list = getExtensionLoader(ActivateExt1.class) - .getActivateExtension(url, new String[]{}, "order"); + list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, new String[] {}, "order"); Assertions.assertEquals(2, list.size()); assertSame(list.get(0).getClass(), OrderActivateExtImpl1.class); assertSame(list.get(1).getClass(), OrderActivateExtImpl2.class); @@ -589,22 +622,20 @@ class ExtensionLoaderTest { void testLoadDefaultActivateExtension1() { // test default URL url = URL.valueOf("test://localhost/test?ext=order1,default"); - List list = getExtensionLoader(ActivateExt1.class) - .getActivateExtension(url, "ext", "default_group"); + List list = + getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group"); Assertions.assertEquals(2, list.size()); assertSame(list.get(0).getClass(), OrderActivateExtImpl1.class); assertSame(list.get(1).getClass(), ActivateExt1Impl1.class); url = URL.valueOf("test://localhost/test?ext=default,order1"); - list = getExtensionLoader(ActivateExt1.class) - .getActivateExtension(url, "ext", "default_group"); + list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group"); Assertions.assertEquals(2, list.size()); assertSame(list.get(0).getClass(), ActivateExt1Impl1.class); assertSame(list.get(1).getClass(), OrderActivateExtImpl1.class); url = URL.valueOf("test://localhost/test?ext=order1"); - list = getExtensionLoader(ActivateExt1.class) - .getActivateExtension(url, "ext", "default_group"); + list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group"); Assertions.assertEquals(2, list.size()); assertSame(list.get(0).getClass(), ActivateExt1Impl1.class); assertSame(list.get(1).getClass(), OrderActivateExtImpl1.class); @@ -614,22 +645,20 @@ class ExtensionLoaderTest { void testLoadDefaultActivateExtension2() { // test default URL url = URL.valueOf("test://localhost/test?ext=order1 , default"); - List list = getExtensionLoader(ActivateExt1.class) - .getActivateExtension(url, "ext", "default_group"); + List list = + getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group"); Assertions.assertEquals(2, list.size()); assertSame(list.get(0).getClass(), OrderActivateExtImpl1.class); assertSame(list.get(1).getClass(), ActivateExt1Impl1.class); url = URL.valueOf("test://localhost/test?ext=default, order1"); - list = getExtensionLoader(ActivateExt1.class) - .getActivateExtension(url, "ext", "default_group"); + list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group"); Assertions.assertEquals(2, list.size()); assertSame(list.get(0).getClass(), ActivateExt1Impl1.class); assertSame(list.get(1).getClass(), OrderActivateExtImpl1.class); url = URL.valueOf("test://localhost/test?ext=order1"); - list = getExtensionLoader(ActivateExt1.class) - .getActivateExtension(url, "ext", "default_group"); + list = getExtensionLoader(ActivateExt1.class).getActivateExtension(url, "ext", "default_group"); Assertions.assertEquals(2, list.size()); assertSame(list.get(0).getClass(), ActivateExt1Impl1.class); assertSame(list.get(1).getClass(), OrderActivateExtImpl1.class); @@ -651,14 +680,13 @@ class ExtensionLoaderTest { @Test void testMultiNames() { - Ext10MultiNames ext10MultiNames = getExtensionLoader(Ext10MultiNames.class).getExtension("impl"); + Ext10MultiNames ext10MultiNames = + getExtensionLoader(Ext10MultiNames.class).getExtension("impl"); Assertions.assertNotNull(ext10MultiNames); ext10MultiNames = getExtensionLoader(Ext10MultiNames.class).getExtension("implMultiName"); Assertions.assertNotNull(ext10MultiNames); - Assertions.assertThrows( - IllegalStateException.class, - () -> getExtensionLoader(Ext10MultiNames.class).getExtension("impl,implMultiName") - ); + Assertions.assertThrows(IllegalStateException.class, () -> getExtensionLoader(Ext10MultiNames.class) + .getExtension("impl,implMultiName")); } @Test @@ -666,7 +694,8 @@ class ExtensionLoaderTest { ExtensionLoader loader = getExtensionLoader(InjectExt.class); InjectExt injectExt = loader.getOrDefaultExtension("non-exists"); assertEquals(InjectExtImpl.class, injectExt.getClass()); - assertEquals(InjectExtImpl.class, loader.getOrDefaultExtension("injection").getClass()); + assertEquals( + InjectExtImpl.class, loader.getOrDefaultExtension("injection").getClass()); } @Test @@ -721,7 +750,6 @@ class ExtensionLoaderTest { assertEquals(DubboExternalLoadingStrategy.class, loadingStrategy.getClass()); assertEquals(Prioritized.MAX_PRIORITY + 1, loadingStrategy.getPriority()); - loadingStrategy = strategies.get(i++); assertEquals(DubboLoadingStrategy.class, loadingStrategy.getClass()); assertEquals(Prioritized.NORMAL_PRIORITY, loadingStrategy.getPriority()); @@ -734,30 +762,38 @@ class ExtensionLoaderTest { @Test void testDuplicatedImplWithoutOverriddenStrategy() { List loadingStrategies = ExtensionLoader.getLoadingStrategies(); - ExtensionLoader.setLoadingStrategies(new DubboExternalLoadingStrategyTest(false), - new DubboInternalLoadingStrategyTest(false)); - ExtensionLoader extensionLoader = getExtensionLoader(DuplicatedWithoutOverriddenExt.class); + ExtensionLoader.setLoadingStrategies( + new DubboExternalLoadingStrategyTest(false), new DubboInternalLoadingStrategyTest(false)); + ExtensionLoader extensionLoader = + getExtensionLoader(DuplicatedWithoutOverriddenExt.class); try { extensionLoader.getExtension("duplicated"); fail(); } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("Failed to load extension class (interface: interface org.apache.dubbo.common.extension.duplicated.DuplicatedWithoutOverriddenExt")); - assertThat(expected.getMessage(), containsString("cause: Duplicate extension org.apache.dubbo.common.extension.duplicated.DuplicatedWithoutOverriddenExt name duplicated")); + assertThat( + expected.getMessage(), + containsString( + "Failed to load extension class (interface: interface org.apache.dubbo.common.extension.duplicated.DuplicatedWithoutOverriddenExt")); + assertThat( + expected.getMessage(), + containsString( + "cause: Duplicate extension org.apache.dubbo.common.extension.duplicated.DuplicatedWithoutOverriddenExt name duplicated")); } finally { - //recover the loading strategies - ExtensionLoader.setLoadingStrategies(loadingStrategies.toArray(new LoadingStrategy[loadingStrategies.size()])); + // recover the loading strategies + ExtensionLoader.setLoadingStrategies( + loadingStrategies.toArray(new LoadingStrategy[loadingStrategies.size()])); } } @Test void testDuplicatedImplWithOverriddenStrategy() { List loadingStrategies = ExtensionLoader.getLoadingStrategies(); - ExtensionLoader.setLoadingStrategies(new DubboExternalLoadingStrategyTest(true), - new DubboInternalLoadingStrategyTest(true)); + ExtensionLoader.setLoadingStrategies( + new DubboExternalLoadingStrategyTest(true), new DubboInternalLoadingStrategyTest(true)); ExtensionLoader extensionLoader = getExtensionLoader(DuplicatedOverriddenExt.class); DuplicatedOverriddenExt duplicatedOverriddenExt = extensionLoader.getExtension("duplicated"); assertEquals("DuplicatedOverriddenExt1", duplicatedOverriddenExt.echo()); - //recover the loading strategies + // recover the loading strategies ExtensionLoader.setLoadingStrategies(loadingStrategies.toArray(new LoadingStrategy[loadingStrategies.size()])); } @@ -784,7 +820,6 @@ class ExtensionLoaderTest { ExtensionLoader extensionLoader4 = getExtensionLoader(SPI4.class); SPI4 spi4 = extensionLoader4.getExtension("4", true); assertNotNull(spi4); - } @Test diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoader_Activate_Test.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoader_Activate_Test.java index 5dfe1b79f3..b810b836ed 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoader_Activate_Test.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoader_Activate_Test.java @@ -14,15 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.activate.ActivateExt1; -import org.junit.jupiter.api.Test; import java.util.List; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertTrue; public class ExtensionLoader_Activate_Test { @@ -35,5 +35,4 @@ public class ExtensionLoader_Activate_Test { assertTrue(list == null || list.size() == 0); } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoader_Adaptive_Test.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoader_Adaptive_Test.java index 52755a8bf4..dc58d75fcc 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoader_Adaptive_Test.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoader_Adaptive_Test.java @@ -30,12 +30,12 @@ import org.apache.dubbo.common.extension.ext6_inject.impl.Ext6Impl2; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.LogUtil; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; @@ -95,7 +95,8 @@ class ExtensionLoader_Adaptive_Test { @Test void test_getAdaptiveExtension_protocolKey() throws Exception { - UseProtocolKeyExt ext = ExtensionLoader.getExtensionLoader(UseProtocolKeyExt.class).getAdaptiveExtension(); + UseProtocolKeyExt ext = + ExtensionLoader.getExtensionLoader(UseProtocolKeyExt.class).getAdaptiveExtension(); { String echo = ext.echo(URL.valueOf("1.2.3.4:20880"), "s"); @@ -113,7 +114,6 @@ class ExtensionLoader_Adaptive_Test { } { - Map map = new HashMap(); URL url = new ServiceConfigURL(null, "1.2.3.4", 1010, "path1", map); String yell = ext.yell(url, "s"); @@ -147,18 +147,26 @@ class ExtensionLoader_Adaptive_Test { ExtensionLoader.getExtensionLoader(NoAdaptiveMethodExt.class).getAdaptiveExtension(); fail(); } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), - allOf(containsString("Can't create adaptive extension interface org.apache.dubbo.common.extension.ext5.NoAdaptiveMethodExt"), - containsString("No adaptive method exist on extension org.apache.dubbo.common.extension.ext5.NoAdaptiveMethodExt, refuse to create the adaptive class"))); + assertThat( + expected.getMessage(), + allOf( + containsString( + "Can't create adaptive extension interface org.apache.dubbo.common.extension.ext5.NoAdaptiveMethodExt"), + containsString( + "No adaptive method exist on extension org.apache.dubbo.common.extension.ext5.NoAdaptiveMethodExt, refuse to create the adaptive class"))); } // report same error when get is invoked for multiple times try { ExtensionLoader.getExtensionLoader(NoAdaptiveMethodExt.class).getAdaptiveExtension(); fail(); } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), - allOf(containsString("Can't create adaptive extension interface org.apache.dubbo.common.extension.ext5.NoAdaptiveMethodExt"), - containsString("No adaptive method exist on extension org.apache.dubbo.common.extension.ext5.NoAdaptiveMethodExt, refuse to create the adaptive class"))); + assertThat( + expected.getMessage(), + allOf( + containsString( + "Can't create adaptive extension interface org.apache.dubbo.common.extension.ext5.NoAdaptiveMethodExt"), + containsString( + "No adaptive method exist on extension org.apache.dubbo.common.extension.ext5.NoAdaptiveMethodExt, refuse to create the adaptive class"))); } } @@ -176,7 +184,8 @@ class ExtensionLoader_Adaptive_Test { assertThat(expected.getMessage(), containsString("method ")); assertThat( expected.getMessage(), - containsString("of interface org.apache.dubbo.common.extension.ext1.SimpleExt is not adaptive method!")); + containsString( + "of interface org.apache.dubbo.common.extension.ext1.SimpleExt is not adaptive method!")); } } @@ -187,7 +196,9 @@ class ExtensionLoader_Adaptive_Test { fail(); } catch (Exception expected) { assertThat(expected.getMessage(), containsString("Failed to create adaptive class for interface ")); - assertThat(expected.getMessage(), containsString(": not found url parameter or url attribute in parameters of method ")); + assertThat( + expected.getMessage(), + containsString(": not found url parameter or url attribute in parameters of method ")); } } @@ -291,7 +302,10 @@ class ExtensionLoader_Adaptive_Test { ext.echo(holder, "haha"); fail(); } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("Failed to get extension (org.apache.dubbo.common.extension.ext2.Ext2) name from url")); + assertThat( + expected.getMessage(), + containsString( + "Failed to get extension (org.apache.dubbo.common.extension.ext2.Ext2) name from url")); } } @@ -310,7 +324,6 @@ class ExtensionLoader_Adaptive_Test { url = url.addParameters("simple.ext", "impl2"); assertEquals("Ext6Impl1-echo-Ext1Impl2-echo", ext.echo(url, "ha")); - } @Test @@ -320,4 +333,4 @@ class ExtensionLoader_Adaptive_Test { Ext6Impl2 impl = (Ext6Impl2) ext; assertNull(impl.getList()); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoader_Adaptive_UseJdkCompiler_Test.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoader_Adaptive_UseJdkCompiler_Test.java index 0848c01a43..4e474d7957 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoader_Adaptive_UseJdkCompiler_Test.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoader_Adaptive_UseJdkCompiler_Test.java @@ -31,4 +31,4 @@ class ExtensionLoader_Adaptive_UseJdkCompiler_Test extends ExtensionLoader_Adapt public static void tearDown() throws Exception { AdaptiveCompiler.setDefaultCompiler("javassist"); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoader_Compatible_Test.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoader_Compatible_Test.java index 83596edb95..5757064aa3 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoader_Compatible_Test.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoader_Compatible_Test.java @@ -33,7 +33,11 @@ class ExtensionLoader_Compatible_Test { ModuleModel moduleModel = ApplicationModel.defaultModel().getDefaultModule(); - assertTrue(moduleModel.getExtensionLoader(CompatibleExt.class).getExtension("impl1") instanceof CompatibleExtImpl1); - assertTrue(moduleModel.getExtensionLoader(CompatibleExt.class).getExtension("impl2") instanceof CompatibleExtImpl2); + assertTrue( + moduleModel.getExtensionLoader(CompatibleExt.class).getExtension("impl1") + instanceof CompatibleExtImpl1); + assertTrue( + moduleModel.getExtensionLoader(CompatibleExt.class).getExtension("impl2") + instanceof CompatibleExtImpl2); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI1Impl.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI1Impl.java index b0de9d439a..2342c2bd24 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI1Impl.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI1Impl.java @@ -17,7 +17,7 @@ package org.apache.dubbo.common.extension; @Activate -public class SPI1Impl implements SPI1{ +public class SPI1Impl implements SPI1 { @Override public String sayHello() { return null; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI2Impl.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI2Impl.java index 25aa7e7e83..91e097988c 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI2Impl.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI2Impl.java @@ -17,7 +17,7 @@ package org.apache.dubbo.common.extension; @Activate -public class SPI2Impl implements SPI2{ +public class SPI2Impl implements SPI2 { @Override public String sayHello() { return null; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI3Impl.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI3Impl.java index e2ca5bd087..4c8ad8e5c1 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI3Impl.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI3Impl.java @@ -17,7 +17,7 @@ package org.apache.dubbo.common.extension; @Activate -public class SPI3Impl implements SPI3{ +public class SPI3Impl implements SPI3 { @Override public String sayHello() { return null; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI4Impl.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI4Impl.java index fda49370c8..920808a50a 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI4Impl.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/SPI4Impl.java @@ -17,7 +17,7 @@ package org.apache.dubbo.common.extension; @Activate -public class SPI4Impl implements SPI4{ +public class SPI4Impl implements SPI4 { @Override public String sayHello() { return null; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/ActivateExt1.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/ActivateExt1.java index c00a988577..e828f7775d 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/ActivateExt1.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/ActivateExt1.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension.activate; import org.apache.dubbo.common.extension.SPI; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/ActivateWrapperExt1.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/ActivateWrapperExt1.java index 1ae23227c7..b83d10fb19 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/ActivateWrapperExt1.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/ActivateWrapperExt1.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension.activate; import org.apache.dubbo.common.extension.SPI; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateExt1Impl1.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateExt1Impl1.java index fe3e082d49..8c62c2462f 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateExt1Impl1.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateExt1Impl1.java @@ -14,13 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension.activate.impl; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.extension.activate.ActivateExt1; -@Activate(order = 1, group = {"default_group"}) +@Activate( + order = 1, + group = {"default_group"}) public class ActivateExt1Impl1 implements ActivateExt1 { public String echo(String msg) { return msg; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateOnClassExt1Impl.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateOnClassExt1Impl.java index 8a2558c20b..b4736ab250 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateOnClassExt1Impl.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateOnClassExt1Impl.java @@ -14,14 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension.activate.impl; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.extension.activate.ActivateExt1; -@Activate(group = {"onClass"}, - onClass = "org.springframework.security.core.context.SecurityContextHolder") +@Activate( + group = {"onClass"}, + onClass = "org.springframework.security.core.context.SecurityContextHolder") public class ActivateOnClassExt1Impl implements ActivateExt1 { @Override public String echo(String msg) { diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateWrapperExt1Impl1.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateWrapperExt1Impl1.java index 0ff2ef44f4..41ab1f55b2 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateWrapperExt1Impl1.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateWrapperExt1Impl1.java @@ -14,13 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension.activate.impl; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.extension.activate.ActivateWrapperExt1; -@Activate(order = 1, group = {"order"}) +@Activate( + order = 1, + group = {"order"}) public class ActivateWrapperExt1Impl1 implements ActivateWrapperExt1 { public String echo(String msg) { return msg; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateWrapperExt1Impl2.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateWrapperExt1Impl2.java index 716d815040..a9e53c7445 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateWrapperExt1Impl2.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateWrapperExt1Impl2.java @@ -14,13 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension.activate.impl; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.extension.activate.ActivateWrapperExt1; -@Activate(order = 2, group = {"order"}) +@Activate( + order = 2, + group = {"order"}) public class ActivateWrapperExt1Impl2 implements ActivateWrapperExt1 { public String echo(String msg) { return msg; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateWrapperExt1Wrapper.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateWrapperExt1Wrapper.java index 671a3b9c00..70b3c1a60e 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateWrapperExt1Wrapper.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateWrapperExt1Wrapper.java @@ -14,12 +14,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension.activate.impl; import org.apache.dubbo.common.extension.activate.ActivateWrapperExt1; - public class ActivateWrapperExt1Wrapper implements ActivateWrapperExt1 { private ActivateWrapperExt1 activateWrapperExt1; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/GroupActivateExtImpl.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/GroupActivateExtImpl.java index 89ca54caa0..7593a01490 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/GroupActivateExtImpl.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/GroupActivateExtImpl.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension.activate.impl; import org.apache.dubbo.common.extension.Activate; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/OrderActivateExtImpl1.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/OrderActivateExtImpl1.java index 3af7a39b8d..b420e7d586 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/OrderActivateExtImpl1.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/OrderActivateExtImpl1.java @@ -14,13 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension.activate.impl; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.extension.activate.ActivateExt1; -@Activate(order = 2, group = {"order"}) +@Activate( + order = 2, + group = {"order"}) public class OrderActivateExtImpl1 implements ActivateExt1 { public String echo(String msg) { diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/OrderActivateExtImpl2.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/OrderActivateExtImpl2.java index 46c7d42b94..13a57a8462 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/OrderActivateExtImpl2.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/OrderActivateExtImpl2.java @@ -14,13 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension.activate.impl; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.extension.activate.ActivateExt1; -@Activate(order = 100, group = {"order"}) +@Activate( + order = 100, + group = {"order"}) public class OrderActivateExtImpl2 implements ActivateExt1 { public String echo(String msg) { diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ValueActivateExtImpl.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ValueActivateExtImpl.java index 85d2e5be59..9194fcfdd6 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ValueActivateExtImpl.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/activate/impl/ValueActivateExtImpl.java @@ -14,13 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension.activate.impl; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.extension.activate.ActivateExt1; -@Activate(value = {"value"}, group = {"value"}) +@Activate( + value = {"value"}, + group = {"value"}) public class ValueActivateExtImpl implements ActivateExt1 { public String echo(String msg) { diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/adaptive/HasAdaptiveExt.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/adaptive/HasAdaptiveExt.java index 534edd8690..e2b462d84f 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/adaptive/HasAdaptiveExt.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/adaptive/HasAdaptiveExt.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension.adaptive; import org.apache.dubbo.common.URL; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/adaptive/impl/HasAdaptiveExt_ManualAdaptive.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/adaptive/impl/HasAdaptiveExt_ManualAdaptive.java index 3f273f55bc..f55fde545e 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/adaptive/impl/HasAdaptiveExt_ManualAdaptive.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/adaptive/impl/HasAdaptiveExt_ManualAdaptive.java @@ -24,7 +24,8 @@ import org.apache.dubbo.common.extension.adaptive.HasAdaptiveExt; @Adaptive public class HasAdaptiveExt_ManualAdaptive implements HasAdaptiveExt { public String echo(URL url, String s) { - HasAdaptiveExt addExt1 = ExtensionLoader.getExtensionLoader(HasAdaptiveExt.class).getExtension(url.getParameter("key")); + HasAdaptiveExt addExt1 = + ExtensionLoader.getExtensionLoader(HasAdaptiveExt.class).getExtension(url.getParameter("key")); return addExt1.echo(url, s); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/compatible/impl/CompatibleExtImpl2.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/compatible/impl/CompatibleExtImpl2.java index 27d92a1da6..99bc330b9a 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/compatible/impl/CompatibleExtImpl2.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/compatible/impl/CompatibleExtImpl2.java @@ -31,5 +31,4 @@ public class CompatibleExtImpl2 implements CompatibleExt { public String bang(URL url, int i) { return "bang2"; } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/convert/String2BooleanConverter.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/convert/String2BooleanConverter.java index 399822a1f6..63aa2b5c79 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/convert/String2BooleanConverter.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/convert/String2BooleanConverter.java @@ -24,5 +24,4 @@ import org.apache.dubbo.common.convert.StringToBooleanConverter; * * @since 2.7.7 */ -public class String2BooleanConverter extends StringToBooleanConverter { -} +public class String2BooleanConverter extends StringToBooleanConverter {} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/convert/String2DoubleConverter.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/convert/String2DoubleConverter.java index c231495de2..048496faef 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/convert/String2DoubleConverter.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/convert/String2DoubleConverter.java @@ -24,5 +24,4 @@ import org.apache.dubbo.common.convert.StringToDoubleConverter; * * @since 2.7.7 */ -public class String2DoubleConverter extends StringToDoubleConverter { -} +public class String2DoubleConverter extends StringToDoubleConverter {} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/convert/String2IntegerConverter.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/convert/String2IntegerConverter.java index 85f51ab039..6e27f0472d 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/convert/String2IntegerConverter.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/convert/String2IntegerConverter.java @@ -24,5 +24,4 @@ import org.apache.dubbo.common.convert.StringToIntegerConverter; * * @since 2.7.7 */ -public class String2IntegerConverter extends StringToIntegerConverter { -} +public class String2IntegerConverter extends StringToIntegerConverter {} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/FooAppProvider.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/FooAppProvider.java index e88527123c..52336f7a85 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/FooAppProvider.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/FooAppProvider.java @@ -26,5 +26,4 @@ public interface FooAppProvider { @Adaptive void process(URL url); - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/FooFrameworkProvider.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/FooFrameworkProvider.java index 194c818279..a5523d59a0 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/FooFrameworkProvider.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/FooFrameworkProvider.java @@ -26,5 +26,4 @@ public interface FooFrameworkProvider { @Adaptive void process(URL url); - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/FooModuleProvider.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/FooModuleProvider.java index 9d4b81ed8a..b045d63819 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/FooModuleProvider.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/FooModuleProvider.java @@ -26,5 +26,4 @@ public interface FooModuleProvider { @Adaptive void process(URL url); - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/FooModuleService.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/FooModuleService.java index 87ce080a7e..5ea8e73050 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/FooModuleService.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/FooModuleService.java @@ -26,5 +26,4 @@ public interface FooModuleService { @Adaptive void process(URL url); - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestAppProvider.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestAppProvider.java index cf60246b2c..df00aa0130 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestAppProvider.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestAppProvider.java @@ -21,7 +21,5 @@ import org.apache.dubbo.common.extension.director.FooAppProvider; public class TestAppProvider implements FooAppProvider { @Override - public void process(URL url) { - - } + public void process(URL url) {} } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestAppService.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestAppService.java index ed5aec4eda..1670acb011 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestAppService.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestAppService.java @@ -66,7 +66,5 @@ public class TestAppService extends BaseTestService implements FooAppService { } @Override - public void process(URL url) { - - } + public void process(URL url) {} } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestFrameworkProvider.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestFrameworkProvider.java index 25dcb66dcf..94fce92e86 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestFrameworkProvider.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestFrameworkProvider.java @@ -21,7 +21,5 @@ import org.apache.dubbo.common.extension.director.FooFrameworkProvider; public class TestFrameworkProvider implements FooFrameworkProvider { @Override - public void process(URL url) { - - } + public void process(URL url) {} } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestFrameworkService.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestFrameworkService.java index 45b71b1b1b..ee1db514d6 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestFrameworkService.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestFrameworkService.java @@ -55,7 +55,5 @@ public class TestFrameworkService extends BaseTestService implements FooFramewor } @Override - public void process(URL url) { - - } + public void process(URL url) {} } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestModuleProvider.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestModuleProvider.java index 604c2919d1..50f897ee21 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestModuleProvider.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestModuleProvider.java @@ -21,8 +21,5 @@ import org.apache.dubbo.common.extension.director.FooModuleProvider; public class TestModuleProvider implements FooModuleProvider { - public void process(URL url) { - - } - + public void process(URL url) {} } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestModuleService.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestModuleService.java index d7c0ad79b0..3d6bf60bfb 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestModuleService.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/director/impl/TestModuleService.java @@ -77,7 +77,5 @@ public class TestModuleService extends BaseTestService implements FooModuleServi } @Override - public void process(URL url) { - - } + public void process(URL url) {} } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext1/impl/SimpleExtImpl2.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext1/impl/SimpleExtImpl2.java index 33e63bb40f..c8a05597c9 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext1/impl/SimpleExtImpl2.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext1/impl/SimpleExtImpl2.java @@ -31,5 +31,4 @@ public class SimpleExtImpl2 implements SimpleExt { public String bang(URL url, int i) { return "bang2"; } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext1/impl/SimpleExtImpl3.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext1/impl/SimpleExtImpl3.java index dd78351a2e..a5051086ad 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext1/impl/SimpleExtImpl3.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext1/impl/SimpleExtImpl3.java @@ -31,5 +31,4 @@ public class SimpleExtImpl3 implements SimpleExt { public String bang(URL url, int i) { return "bang3"; } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext10_multi_names/Ext10MultiNames.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext10_multi_names/Ext10MultiNames.java index 33492ce171..d849666f90 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext10_multi_names/Ext10MultiNames.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext10_multi_names/Ext10MultiNames.java @@ -19,5 +19,4 @@ package org.apache.dubbo.common.extension.ext10_multi_names; import org.apache.dubbo.common.extension.SPI; @SPI -public interface Ext10MultiNames { -} +public interface Ext10MultiNames {} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext10_multi_names/impl/Ext10MultiNamesImpl.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext10_multi_names/impl/Ext10MultiNamesImpl.java index 1d7862b94b..05cfcc53fd 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext10_multi_names/impl/Ext10MultiNamesImpl.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext10_multi_names/impl/Ext10MultiNamesImpl.java @@ -18,5 +18,4 @@ package org.apache.dubbo.common.extension.ext10_multi_names.impl; import org.apache.dubbo.common.extension.ext10_multi_names.Ext10MultiNames; -public class Ext10MultiNamesImpl implements Ext10MultiNames { -} +public class Ext10MultiNamesImpl implements Ext10MultiNames {} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext2/impl/Ext2Impl2.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext2/impl/Ext2Impl2.java index 34077b2cfb..24cae3c383 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext2/impl/Ext2Impl2.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext2/impl/Ext2Impl2.java @@ -28,5 +28,4 @@ public class Ext2Impl2 implements Ext2 { public String bang(URL url, int i) { return "bang2"; } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext2/impl/Ext2Impl3.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext2/impl/Ext2Impl3.java index d308b36b4f..81e883c111 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext2/impl/Ext2Impl3.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext2/impl/Ext2Impl3.java @@ -28,5 +28,4 @@ public class Ext2Impl3 implements Ext2 { public String bang(URL url, int i) { return "bang3"; } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext4/impl/Ext4Impl2.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext4/impl/Ext4Impl2.java index 539342e89d..667c3c3346 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext4/impl/Ext4Impl2.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext4/impl/Ext4Impl2.java @@ -24,5 +24,4 @@ public class Ext4Impl2 implements NoUrlParamExt { public String bark(String name, List list) { return null; } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_inject/Dao.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_inject/Dao.java index 9d024f930f..eb76e7bdcf 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_inject/Dao.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_inject/Dao.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension.ext6_inject; public interface Dao { diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_inject/impl/DaoImpl.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_inject/impl/DaoImpl.java index 525bba8928..b14f5f3deb 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_inject/impl/DaoImpl.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_inject/impl/DaoImpl.java @@ -14,13 +14,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension.ext6_inject.impl; import org.apache.dubbo.common.extension.ext6_inject.Dao; public class DaoImpl implements Dao { - public void update() { - - } + public void update() {} } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_inject/impl/Ext6Impl1.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_inject/impl/Ext6Impl1.java index 2b11b8cc59..bb1d628730 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_inject/impl/Ext6Impl1.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_inject/impl/Ext6Impl1.java @@ -39,6 +39,4 @@ public class Ext6Impl1 implements Ext6 { public String echo(URL url, String s) { return "Ext6Impl1-echo-" + ext1.echo(url, s); } - - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_inject/impl/Ext6Impl2.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_inject/impl/Ext6Impl2.java index b704cde273..928c393f68 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_inject/impl/Ext6Impl2.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_inject/impl/Ext6Impl2.java @@ -35,5 +35,4 @@ public class Ext6Impl2 implements Ext6 { public String echo(URL url, String s) { throw new UnsupportedOperationException(); } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_wrap/impl/Ext6Wrapper3.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_wrap/impl/Ext6Wrapper3.java index 40b5978dc2..bf0006ac3f 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_wrap/impl/Ext6Wrapper3.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_wrap/impl/Ext6Wrapper3.java @@ -23,7 +23,9 @@ import org.apache.dubbo.common.extension.ext6_wrap.WrappedExtWrapper; import java.util.concurrent.atomic.AtomicInteger; -@Wrapper(matches = {"impl3"}, order = 3) +@Wrapper( + matches = {"impl3"}, + order = 3) public class Ext6Wrapper3 implements WrappedExt, WrappedExtWrapper { public static AtomicInteger echoCount = new AtomicInteger(); WrappedExt origin; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_wrap/impl/Ext6Wrapper4.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_wrap/impl/Ext6Wrapper4.java index f214c5db92..7cf3706355 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_wrap/impl/Ext6Wrapper4.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext6_wrap/impl/Ext6Wrapper4.java @@ -23,7 +23,9 @@ import org.apache.dubbo.common.extension.ext6_wrap.WrappedExtWrapper; import java.util.concurrent.atomic.AtomicInteger; -@Wrapper(mismatches = {"impl1", "impl2"}, order = 4) +@Wrapper( + mismatches = {"impl1", "impl2"}, + order = 4) public class Ext6Wrapper4 implements WrappedExt, WrappedExtWrapper { public static AtomicInteger echoCount = new AtomicInteger(); WrappedExt origin; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext7/impl/Ext7Impl.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext7/impl/Ext7Impl.java index fe64029e5f..eadb7e2b3a 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext7/impl/Ext7Impl.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext7/impl/Ext7Impl.java @@ -23,5 +23,4 @@ public class Ext7Impl implements InitErrorExt { public String echo(URL url, String s) { return ""; } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext7/impl/Ext7InitErrorImpl.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext7/impl/Ext7InitErrorImpl.java index 4b54f649bd..df5fed6d3e 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext7/impl/Ext7InitErrorImpl.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext7/impl/Ext7InitErrorImpl.java @@ -30,5 +30,4 @@ public class Ext7InitErrorImpl implements InitErrorExt { public String echo(URL url, String s) { return ""; } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext9_empty/impl/Ext9EmptyImpl.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext9_empty/impl/Ext9EmptyImpl.java index bea7fa8216..b3b1ba3270 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext9_empty/impl/Ext9EmptyImpl.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/ext9_empty/impl/Ext9EmptyImpl.java @@ -20,7 +20,5 @@ import org.apache.dubbo.common.extension.ext9_empty.Ext9Empty; public class Ext9EmptyImpl implements Ext9Empty { @Override - public void empty() { - - } + public void empty() {} } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/inject/AdaptiveExtensionInjectorTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/inject/AdaptiveExtensionInjectorTest.java index 7e3fc696f4..f24b26551d 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/inject/AdaptiveExtensionInjectorTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/inject/AdaptiveExtensionInjectorTest.java @@ -42,15 +42,19 @@ class AdaptiveExtensionInjectorTest { ExtensionInjector scopeExtensionInjector = extensionLoader.getExtension("scopeBean"); ExtensionInjector spiExtensionInjector = extensionLoader.getExtension("spi"); - FooFrameworkProvider testFrameworkProvider = adaptiveExtensionInjector.getInstance(FooFrameworkProvider.class, "testFrameworkProvider"); + FooFrameworkProvider testFrameworkProvider = + adaptiveExtensionInjector.getInstance(FooFrameworkProvider.class, "testFrameworkProvider"); Assertions.assertNotNull(testFrameworkProvider); Assertions.assertTrue(testFrameworkProvider.getClass().getName().endsWith("$Adaptive")); - Assertions.assertEquals(spiExtensionInjector.getInstance(FooFrameworkProvider.class, "testFrameworkProvider"), testFrameworkProvider); + Assertions.assertEquals( + spiExtensionInjector.getInstance(FooFrameworkProvider.class, "testFrameworkProvider"), + testFrameworkProvider); ScopeBeanFactory beanFactory = frameworkModel.getBeanFactory(); AdaptiveExtensionInjectorTest obj = new AdaptiveExtensionInjectorTest(); beanFactory.registerBean("bean", obj); - AdaptiveExtensionInjectorTest bean = adaptiveExtensionInjector.getInstance(AdaptiveExtensionInjectorTest.class, "bean"); + AdaptiveExtensionInjectorTest bean = + adaptiveExtensionInjector.getInstance(AdaptiveExtensionInjectorTest.class, "bean"); Assertions.assertEquals(bean, obj); Assertions.assertEquals(scopeExtensionInjector.getInstance(AdaptiveExtensionInjectorTest.class, "bean"), bean); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/ActivateComparatorTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/ActivateComparatorTest.java index 6bf8cdfbf1..9ecb7a1bba 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/ActivateComparatorTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/ActivateComparatorTest.java @@ -18,25 +18,26 @@ package org.apache.dubbo.common.extension.support; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.Collections; import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + class ActivateComparatorTest { private ActivateComparator activateComparator; @BeforeEach public void setup() { - activateComparator = new ActivateComparator(ApplicationModel.defaultModel().getExtensionDirector()); + activateComparator = + new ActivateComparator(ApplicationModel.defaultModel().getExtensionDirector()); } @Test - void testActivateComparator(){ + void testActivateComparator() { Filter1 f1 = new Filter1(); Filter2 f2 = new Filter2(); Filter3 f3 = new Filter3(); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Filter0.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Filter0.java index 612440894d..1a08826412 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Filter0.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Filter0.java @@ -19,5 +19,4 @@ package org.apache.dubbo.common.extension.support; import org.apache.dubbo.common.extension.SPI; @SPI -public interface Filter0 { -} +public interface Filter0 {} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Filter1.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Filter1.java index 5f30dd650e..b1408919bf 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Filter1.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Filter1.java @@ -19,5 +19,4 @@ package org.apache.dubbo.common.extension.support; import org.apache.dubbo.common.extension.Activate; @Activate -public class Filter1 implements Filter0{ -} +public class Filter1 implements Filter0 {} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Filter2.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Filter2.java index df93fa6eaf..3b9b9e27c8 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Filter2.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Filter2.java @@ -19,5 +19,4 @@ package org.apache.dubbo.common.extension.support; import org.apache.dubbo.common.extension.Activate; @Activate(before = "_1") -public class Filter2 implements Filter0{ -} +public class Filter2 implements Filter0 {} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Filter3.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Filter3.java index c02aaa13c2..38f787a306 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Filter3.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Filter3.java @@ -19,5 +19,4 @@ package org.apache.dubbo.common.extension.support; import org.apache.dubbo.common.extension.Activate; @Activate(after = "_4") -public class Filter3 implements Filter0{ -} +public class Filter3 implements Filter0 {} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Filter4.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Filter4.java index 353874bc9a..fdca0bcff5 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Filter4.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Filter4.java @@ -19,5 +19,4 @@ package org.apache.dubbo.common.extension.support; import org.apache.dubbo.common.extension.Activate; @Activate(before = "_2") -public class Filter4 implements Filter0{ -} +public class Filter4 implements Filter0 {} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter0.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter0.java index 634e92f12f..c900d47480 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter0.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter0.java @@ -14,11 +14,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension.support; import org.apache.dubbo.common.extension.SPI; @SPI -public interface Order0Filter0 { -} +public interface Order0Filter0 {} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter1.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter1.java index cf23ffee94..a58500f413 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter1.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter1.java @@ -14,11 +14,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension.support; import org.apache.dubbo.common.extension.Activate; @Activate -public class Order0Filter1 implements Order0Filter0 { -} +public class Order0Filter1 implements Order0Filter0 {} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter2.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter2.java index b09ed993a9..99b08f9ebb 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter2.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter2.java @@ -14,11 +14,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension.support; import org.apache.dubbo.common.extension.Activate; @Activate -public class Order0Filter2 implements Order0Filter0 { -} +public class Order0Filter2 implements Order0Filter0 {} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/wrapper/WrapperTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/wrapper/WrapperTest.java index f17543d1c4..d1e97a2052 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/wrapper/WrapperTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/wrapper/WrapperTest.java @@ -38,4 +38,4 @@ class WrapperTest { Demo demoWrapper2 = ExtensionLoader.getExtensionLoader(Demo.class).getExtension("demo2"); assertTrue(demoWrapper2 instanceof DemoWrapper2); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/wrapper/impl/DemoImpl.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/wrapper/impl/DemoImpl.java index dd594249b9..28cb8b0abe 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/wrapper/impl/DemoImpl.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/wrapper/impl/DemoImpl.java @@ -24,9 +24,7 @@ public class DemoImpl implements Demo { return msg; } - public DemoImpl() { - } + public DemoImpl() {} - public DemoImpl(String test) { - } + public DemoImpl(String test) {} } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/wrapper/impl/DemoWrapper.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/wrapper/impl/DemoWrapper.java index 44ec737a1f..5a9e5b159a 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/wrapper/impl/DemoWrapper.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/wrapper/impl/DemoWrapper.java @@ -19,7 +19,9 @@ package org.apache.dubbo.common.extension.wrapper.impl; import org.apache.dubbo.common.extension.Wrapper; import org.apache.dubbo.common.extension.wrapper.Demo; -@Wrapper(matches = {"demo"}, mismatches = "demo2") +@Wrapper( + matches = {"demo"}, + mismatches = "demo2") public class DemoWrapper implements Demo { private Demo demo; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/wrapper/impl/DemoWrapper2.java b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/wrapper/impl/DemoWrapper2.java index c8e4385474..25662b02a8 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/extension/wrapper/impl/DemoWrapper2.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/extension/wrapper/impl/DemoWrapper2.java @@ -19,7 +19,9 @@ package org.apache.dubbo.common.extension.wrapper.impl; import org.apache.dubbo.common.extension.Wrapper; import org.apache.dubbo.common.extension.wrapper.Demo; -@Wrapper(matches = {"demo2"}, mismatches = {"demo"}) +@Wrapper( + matches = {"demo2"}, + mismatches = {"demo"}) public class DemoWrapper2 implements Demo { private Demo demo; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/function/PredicatesTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/function/PredicatesTest.java index b1dc5de727..2ab493327b 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/function/PredicatesTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/function/PredicatesTest.java @@ -57,4 +57,4 @@ class PredicatesTest { assertTrue(or(alwaysTrue(), alwaysFalse(), alwaysFalse()).test(null)); assertFalse(or(alwaysFalse(), alwaysFalse(), alwaysFalse()).test(null)); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/function/StreamsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/function/StreamsTest.java index d8fde23d22..6f8973642f 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/function/StreamsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/function/StreamsTest.java @@ -16,13 +16,13 @@ */ package org.apache.dubbo.common.function; -import org.junit.jupiter.api.Test; - import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.stream.Stream; +import org.junit.jupiter.api.Test; + import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import static org.apache.dubbo.common.function.Streams.filterList; @@ -54,4 +54,4 @@ class StreamsTest { Set set = filterSet(asList(1, 2, 3, 4, 5), i -> i % 2 == 0); assertEquals(new LinkedHashSet<>(asList(2, 4)), set); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/function/ThrowableActionTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/function/ThrowableActionTest.java index 5a608eb3ea..f31624fa9c 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/function/ThrowableActionTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/function/ThrowableActionTest.java @@ -30,8 +30,11 @@ class ThrowableActionTest { @Test void testExecute() { - Assertions.assertThrows(RuntimeException.class, () -> execute(() -> { - throw new Exception("Test"); - }), "Test"); + Assertions.assertThrows( + RuntimeException.class, + () -> execute(() -> { + throw new Exception("Test"); + }), + "Test"); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/function/ThrowableConsumerTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/function/ThrowableConsumerTest.java index 57e515eef0..5d1e24ecab 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/function/ThrowableConsumerTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/function/ThrowableConsumerTest.java @@ -30,8 +30,11 @@ class ThrowableConsumerTest { @Test void testExecute() { - assertThrows(RuntimeException.class, () -> execute("Hello,World", m -> { - throw new Exception(m); - }), "Hello,World"); + assertThrows( + RuntimeException.class, + () -> execute("Hello,World", m -> { + throw new Exception(m); + }), + "Hello,World"); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/function/ThrowableFunctionTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/function/ThrowableFunctionTest.java index 08b9d72a31..b58f516967 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/function/ThrowableFunctionTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/function/ThrowableFunctionTest.java @@ -30,8 +30,11 @@ class ThrowableFunctionTest { @Test void testExecute() { - assertThrows(RuntimeException.class, () -> execute("Hello,World", m -> { - throw new Exception(m); - }), "Hello,World"); + assertThrows( + RuntimeException.class, + () -> execute("Hello,World", m -> { + throw new Exception(m); + }), + "Hello,World"); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/io/BytesTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/io/BytesTest.java index eb075f65ab..29e6d31fe4 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/io/BytesTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/io/BytesTest.java @@ -16,18 +16,20 @@ */ package org.apache.dubbo.common.io; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.io.File; import java.io.IOException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; class BytesTest { - private final byte[] b1 = "adpfioha;eoh;aldfadl;kfadslkfdajfio123431241235123davas;odvwe;lmzcoqpwoewqogineopwqihwqetup\n\tejqf;lajsfd中文字符0da0gsaofdsf==adfasdfs".getBytes(); - private final String C64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; //default base64. + private final byte[] b1 = + "adpfioha;eoh;aldfadl;kfadslkfdajfio123431241235123davas;odvwe;lmzcoqpwoewqogineopwqihwqetup\n\tejqf;lajsfd中文字符0da0gsaofdsf==adfasdfs" + .getBytes(); + private final String C64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // default base64. private byte[] bytes1 = {3, 12, 14, 41, 12, 2, 3, 12, 4, 67, 23}; private byte[] bytes2 = {3, 12, 14, 41, 12, 2, 3, 12, 4, 67}; @@ -67,7 +69,8 @@ class BytesTest { @Test void testWrongBase64Code() { - Assertions.assertThrows(IllegalArgumentException.class, () -> Bytes.bytes2base64("dubbo".getBytes(), 0, 1, new char[]{'a'})); + Assertions.assertThrows( + IllegalArgumentException.class, () -> Bytes.bytes2base64("dubbo".getBytes(), 0, 1, new char[] {'a'})); } @Test @@ -77,7 +80,8 @@ class BytesTest { @Test void testLargeLength() { - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> Bytes.bytes2base64("dubbo".getBytes(), 0, 100000)); + Assertions.assertThrows( + IndexOutOfBoundsException.class, () -> Bytes.bytes2base64("dubbo".getBytes(), 0, 100000)); } @Test @@ -118,7 +122,8 @@ class BytesTest { @Test void testMD5ForFile() throws IOException { - byte[] md5 = Bytes.getMD5(new File(getClass().getClassLoader().getResource("md5.testfile.txt").getFile())); + byte[] md5 = Bytes.getMD5(new File( + getClass().getClassLoader().getResource("md5.testfile.txt").getFile())); assertThat(md5, is(Bytes.base642bytes("iNZ+5qHafVNPLJxHwLKJ3w=="))); } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/io/StreamUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/io/StreamUtilsTest.java index 21c63cc488..c2fe38e18c 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/io/StreamUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/io/StreamUtilsTest.java @@ -16,13 +16,13 @@ */ package org.apache.dubbo.common.io; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -177,4 +177,4 @@ class StreamUtilsTest { } }); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeByteArrayInputStreamTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeByteArrayInputStreamTest.java index a60a6af585..6192ebfe87 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeByteArrayInputStreamTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeByteArrayInputStreamTest.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.common.io; +import java.io.IOException; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.io.IOException; - import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -91,4 +91,4 @@ class UnsafeByteArrayInputStreamTest { assertThat(skip, is(0L)); assertThat(stream.position(), is(0)); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeByteArrayOutputStreamTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeByteArrayOutputStreamTest.java index ad733e017f..6cb0be0f36 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeByteArrayOutputStreamTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeByteArrayOutputStreamTest.java @@ -16,14 +16,14 @@ */ package org.apache.dubbo.common.io; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.any; @@ -76,4 +76,4 @@ class UnsafeByteArrayOutputStreamTest { assertThat(outputStream.toString("UTF-8"), is("Hòa Bình")); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeStringReaderTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeStringReaderTest.java index 2911c64bfa..160e562e2e 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeStringReaderTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeStringReaderTest.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.common.io; +import java.io.IOException; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.io.IOException; - import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -72,4 +72,4 @@ class UnsafeStringReaderTest { reader.read(chars, 0, 2); }); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeStringWriterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeStringWriterTest.java index bb054b3e50..1cd4776891 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeStringWriterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/io/UnsafeStringWriterTest.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.common.io; +import java.io.IOException; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.io.IOException; - import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -96,4 +96,4 @@ class UnsafeStringWriterTest { writer.write(chars, 1, 1); }); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/json/GsonUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/json/GsonUtilsTest.java index 468374d6ba..c28f4ad8da 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/json/GsonUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/json/GsonUtilsTest.java @@ -16,13 +16,13 @@ */ package org.apache.dubbo.common.json; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class GsonUtilsTest { @Test void test1() { @@ -35,7 +35,9 @@ class GsonUtilsTest { GsonUtils.fromJson("{'name':'Tom','age':}", User.class); Assertions.fail(); } catch (RuntimeException ex) { - Assertions.assertEquals("Generic serialization [gson] Json syntax exception thrown when parsing (message:{'name':'Tom','age':} type:class org.apache.dubbo.common.json.GsonUtilsTest$User) error:com.google.gson.stream.MalformedJsonException: Expected value at line 1 column 21 path $.age", ex.getMessage()); + Assertions.assertEquals( + "Generic serialization [gson] Json syntax exception thrown when parsing (message:{'name':'Tom','age':} type:class org.apache.dubbo.common.json.GsonUtilsTest$User) error:com.google.gson.stream.MalformedJsonException: Expected value at line 1 column 21 path $.age", + ex.getMessage()); } } @@ -90,4 +92,4 @@ class GsonUtilsTest { this.age = age; } } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/json/impl/FastJson2ImplTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/json/impl/FastJson2ImplTest.java index bbed68afb1..a372a2fee3 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/json/impl/FastJson2ImplTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/json/impl/FastJson2ImplTest.java @@ -16,6 +16,8 @@ */ package org.apache.dubbo.common.json.impl; +import java.lang.reflect.Type; + import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONWriter; import org.junit.jupiter.api.AfterAll; @@ -25,8 +27,6 @@ import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; -import java.lang.reflect.Type; - import static org.mockito.Answers.CALLS_REAL_METHODS; class FastJson2ImplTest { @@ -46,19 +46,27 @@ class FastJson2ImplTest { void testSupported() { Assertions.assertTrue(new FastJson2Impl().isSupport()); - fastjson2Mock.when(() -> JSON.toJSONString(Mockito.any(), (JSONWriter.Feature) Mockito.any())).thenThrow(new RuntimeException()); + fastjson2Mock + .when(() -> JSON.toJSONString(Mockito.any(), (JSONWriter.Feature) Mockito.any())) + .thenThrow(new RuntimeException()); Assertions.assertFalse(new FastJson2Impl().isSupport()); fastjson2Mock.reset(); - fastjson2Mock.when(() -> JSON.toJSONString(Mockito.any(), (JSONWriter.Feature) Mockito.any())).thenReturn(null); + fastjson2Mock + .when(() -> JSON.toJSONString(Mockito.any(), (JSONWriter.Feature) Mockito.any())) + .thenReturn(null); Assertions.assertFalse(new FastJson2Impl().isSupport()); fastjson2Mock.reset(); - fastjson2Mock.when(() -> JSON.parseObject((String) Mockito.any(), (Type) Mockito.any())).thenReturn(null); + fastjson2Mock + .when(() -> JSON.parseObject((String) Mockito.any(), (Type) Mockito.any())) + .thenReturn(null); Assertions.assertFalse(new FastJson2Impl().isSupport()); fastjson2Mock.reset(); - fastjson2Mock.when(() -> JSON.parseArray(Mockito.any(), (Class) Mockito.any())).thenReturn(null); + fastjson2Mock + .when(() -> JSON.parseArray(Mockito.any(), (Class) Mockito.any())) + .thenReturn(null); Assertions.assertFalse(new FastJson2Impl().isSupport()); fastjson2Mock.reset(); } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/json/impl/FastJsonImplTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/json/impl/FastJsonImplTest.java index a3fd701c97..889af34cfa 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/json/impl/FastJsonImplTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/json/impl/FastJsonImplTest.java @@ -18,6 +18,7 @@ package org.apache.dubbo.common.json.impl; import java.lang.reflect.Type; +import com.alibaba.fastjson.JSON; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -25,8 +26,6 @@ import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; -import com.alibaba.fastjson.JSON; - import static org.mockito.Answers.CALLS_REAL_METHODS; class FastJsonImplTest { @@ -54,11 +53,15 @@ class FastJsonImplTest { Assertions.assertFalse(new FastJsonImpl().isSupport()); fastjsonMock.reset(); - fastjsonMock.when(() -> JSON.parseObject((String) Mockito.any(), (Type) Mockito.any())).thenReturn(null); + fastjsonMock + .when(() -> JSON.parseObject((String) Mockito.any(), (Type) Mockito.any())) + .thenReturn(null); Assertions.assertFalse(new FastJsonImpl().isSupport()); fastjsonMock.reset(); - fastjsonMock.when(() -> JSON.parseArray(Mockito.any(), (Class) Mockito.any())).thenReturn(null); + fastjsonMock + .when(() -> JSON.parseArray(Mockito.any(), (Class) Mockito.any())) + .thenReturn(null); Assertions.assertFalse(new FastJsonImpl().isSupport()); fastjsonMock.reset(); } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/json/impl/GsonImplTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/json/impl/GsonImplTest.java index 0ebf9cb1eb..0852c230ed 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/json/impl/GsonImplTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/json/impl/GsonImplTest.java @@ -16,6 +16,10 @@ */ package org.apache.dubbo.common.json.impl; +import java.lang.reflect.Type; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; + import com.google.gson.Gson; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; @@ -24,10 +28,6 @@ import org.junit.jupiter.api.Test; import org.mockito.MockedConstruction; import org.mockito.Mockito; -import java.lang.reflect.Type; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Consumer; - public class GsonImplTest { private static Gson gson = new Gson(); @@ -37,16 +37,18 @@ public class GsonImplTest { @BeforeAll static void setup() { - gsonMock = Mockito.mockConstruction(Gson.class, - (mock, context) -> { - gsonReference.set(mock); - Mockito.when(mock.toJson((Object) Mockito.any())).thenAnswer(invocation -> gson.toJson((Object) invocation.getArgument(0))); - Mockito.when(mock.fromJson(Mockito.anyString(), (Type) Mockito.any())).thenAnswer(invocation -> gson.fromJson((String) invocation.getArgument(0), (Type) invocation.getArgument(1))); - Consumer gsonConsumer = gsonInit.get(); - if (gsonConsumer != null) { - gsonConsumer.accept(mock); - } - }); + gsonMock = Mockito.mockConstruction(Gson.class, (mock, context) -> { + gsonReference.set(mock); + Mockito.when(mock.toJson((Object) Mockito.any())) + .thenAnswer(invocation -> gson.toJson((Object) invocation.getArgument(0))); + Mockito.when(mock.fromJson(Mockito.anyString(), (Type) Mockito.any())) + .thenAnswer(invocation -> + gson.fromJson((String) invocation.getArgument(0), (Type) invocation.getArgument(1))); + Consumer gsonConsumer = gsonInit.get(); + if (gsonConsumer != null) { + gsonConsumer.accept(mock); + } + }); } @AfterAll @@ -62,7 +64,8 @@ public class GsonImplTest { Assertions.assertFalse(new GsonImpl().isSupport()); gsonInit.set(null); - gsonInit.set(g -> Mockito.when(g.fromJson(Mockito.anyString(), (Type) Mockito.any())).thenThrow(new RuntimeException())); + gsonInit.set(g -> Mockito.when(g.fromJson(Mockito.anyString(), (Type) Mockito.any())) + .thenThrow(new RuntimeException())); Assertions.assertFalse(new GsonImpl().isSupport()); gsonInit.set(null); @@ -70,11 +73,13 @@ public class GsonImplTest { Assertions.assertFalse(new GsonImpl().isSupport()); gsonInit.set(null); - gsonInit.set(g -> Mockito.when(g.fromJson(Mockito.anyString(), (Type) Mockito.any())).thenReturn(null)); + gsonInit.set(g -> Mockito.when(g.fromJson(Mockito.anyString(), (Type) Mockito.any())) + .thenReturn(null)); Assertions.assertFalse(new GsonImpl().isSupport()); gsonInit.set(null); - gsonInit.set(g -> Mockito.when(g.fromJson(Mockito.eq("[\"json\"]"), (Type) Mockito.any())).thenReturn(null)); + gsonInit.set(g -> Mockito.when(g.fromJson(Mockito.eq("[\"json\"]"), (Type) Mockito.any())) + .thenReturn(null)); Assertions.assertFalse(new GsonImpl().isSupport()); gsonInit.set(null); } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/lang/PrioritizedTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/lang/PrioritizedTest.java index c65de4d736..67424e297a 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/lang/PrioritizedTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/lang/PrioritizedTest.java @@ -16,12 +16,12 @@ */ package org.apache.dubbo.common.lang; -import org.junit.jupiter.api.Test; - import java.util.LinkedList; import java.util.List; import java.util.Objects; +import org.junit.jupiter.api.Test; + import static java.util.Arrays.asList; import static java.util.Collections.sort; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -41,8 +41,7 @@ class PrioritizedTest { @Test void testGetPriority() { - assertEquals(Prioritized.NORMAL_PRIORITY, new Prioritized() { - }.getPriority()); + assertEquals(Prioritized.NORMAL_PRIORITY, new Prioritized() {}.getPriority()); } @Test @@ -85,7 +84,6 @@ class PrioritizedTest { copy = asList(1, 2, 3); assertEquals(copy, list); - } public static PrioritizedValue of(int value) { @@ -123,4 +121,4 @@ class PrioritizedTest { return Objects.hash(value); } } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/lang/ShutdownHookCallbacksTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/lang/ShutdownHookCallbacksTest.java index 035f118172..dd38bc770a 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/lang/ShutdownHookCallbacksTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/lang/ShutdownHookCallbacksTest.java @@ -47,7 +47,8 @@ class ShutdownHookCallbacksTest { @Test void testCallback() { callbacks.callback(); - DefaultShutdownHookCallback callback = (DefaultShutdownHookCallback) callbacks.getCallbacks().iterator().next(); + DefaultShutdownHookCallback callback = (DefaultShutdownHookCallback) + callbacks.getCallbacks().iterator().next(); assertTrue(callback.isExecuted()); } @@ -56,4 +57,4 @@ class ShutdownHookCallbacksTest { callbacks.destroy(); assertTrue(callbacks.getCallbacks().isEmpty()); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/logger/LoggerAdapterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/logger/LoggerAdapterTest.java index afab9e4c7b..75465b6a3d 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/logger/LoggerAdapterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/logger/LoggerAdapterTest.java @@ -27,13 +27,13 @@ import org.apache.dubbo.common.logger.log4j2.Log4j2LoggerAdapter; import org.apache.dubbo.common.logger.slf4j.Slf4jLogger; import org.apache.dubbo.common.logger.slf4j.Slf4jLoggerAdapter; +import java.lang.reflect.InvocationTargetException; +import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import java.lang.reflect.InvocationTargetException; -import java.util.stream.Stream; - import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -44,26 +44,28 @@ class LoggerAdapterTest { Arguments.of(JdkLoggerAdapter.class, JdkLogger.class), Arguments.of(Log4jLoggerAdapter.class, Log4jLogger.class), Arguments.of(Slf4jLoggerAdapter.class, Slf4jLogger.class), - Arguments.of(Log4j2LoggerAdapter.class, Log4j2Logger.class) - ); + Arguments.of(Log4j2LoggerAdapter.class, Log4j2Logger.class)); } @ParameterizedTest @MethodSource("data") - void testGetLogger(Class loggerAdapterClass, Class loggerClass) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { - LoggerAdapter loggerAdapter = loggerAdapterClass.getDeclaredConstructor().newInstance(); + void testGetLogger(Class loggerAdapterClass, Class loggerClass) + throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { + LoggerAdapter loggerAdapter = + loggerAdapterClass.getDeclaredConstructor().newInstance(); Logger logger = loggerAdapter.getLogger(this.getClass()); assertThat(logger.getClass().isAssignableFrom(loggerClass), is(true)); logger = loggerAdapter.getLogger(this.getClass().getSimpleName()); assertThat(logger.getClass().isAssignableFrom(loggerClass), is(true)); - } @ParameterizedTest @MethodSource("data") - void testLevel(Class loggerAdapterClass) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { - LoggerAdapter loggerAdapter = loggerAdapterClass.getDeclaredConstructor().newInstance(); + void testLevel(Class loggerAdapterClass) + throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { + LoggerAdapter loggerAdapter = + loggerAdapterClass.getDeclaredConstructor().newInstance(); for (Level targetLevel : Level.values()) { loggerAdapter.setLevel(targetLevel); assertThat(loggerAdapter.getLevel(), is(targetLevel)); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/logger/LoggerFactoryTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/logger/LoggerFactoryTest.java index 4b5dc7d9e4..94ff33102d 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/logger/LoggerFactoryTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/logger/LoggerFactoryTest.java @@ -18,10 +18,10 @@ package org.apache.dubbo.common.logger; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.junit.jupiter.api.Test; - import java.io.File; +import org.junit.jupiter.api.Test; + import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; @@ -71,9 +71,11 @@ class LoggerFactoryTest { @Test void shouldReturnSameErrorTypeAwareLogger() { - ErrorTypeAwareLogger logger1 = LoggerFactory.getErrorTypeAwareLogger(this.getClass().getName()); - ErrorTypeAwareLogger logger2 = LoggerFactory.getErrorTypeAwareLogger(this.getClass().getName()); + ErrorTypeAwareLogger logger1 = + LoggerFactory.getErrorTypeAwareLogger(this.getClass().getName()); + ErrorTypeAwareLogger logger2 = + LoggerFactory.getErrorTypeAwareLogger(this.getClass().getName()); assertThat(logger1, is(logger2)); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/logger/LoggerTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/logger/LoggerTest.java index e4d8d8551c..0cac24d2e6 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/logger/LoggerTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/logger/LoggerTest.java @@ -22,18 +22,17 @@ import org.apache.dubbo.common.logger.log4j.Log4jLoggerAdapter; import org.apache.dubbo.common.logger.log4j2.Log4j2LoggerAdapter; import org.apache.dubbo.common.logger.slf4j.Slf4jLoggerAdapter; +import java.lang.reflect.InvocationTargetException; +import java.util.stream.Stream; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import java.lang.reflect.InvocationTargetException; -import java.util.stream.Stream; - import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; - class LoggerTest { static Stream data() { @@ -42,8 +41,7 @@ class LoggerTest { Arguments.of(JdkLoggerAdapter.class), Arguments.of(Log4jLoggerAdapter.class), Arguments.of(Slf4jLoggerAdapter.class), - Arguments.of(Log4j2LoggerAdapter.class) - ); + Arguments.of(Log4j2LoggerAdapter.class)); } @ParameterizedTest @@ -76,7 +74,7 @@ class LoggerTest { logger.debug("debug", new Exception("debug")); logger.trace("trace", new Exception("trace")); - logger.error("error:{}","arg1", new Exception("error")); + logger.error("error:{}", "arg1", new Exception("error")); logger.warn("warn:{}", "arg1", new Exception("warn")); logger.info("info:{}", "arg1", new Exception("info")); logger.debug("debug:{}", "arg1", new Exception("debug")); @@ -85,7 +83,8 @@ class LoggerTest { @ParameterizedTest @MethodSource("data") - void testLevelEnable(Class loggerAdapter) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { + void testLevelEnable(Class loggerAdapter) + throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { LoggerAdapter adapter = loggerAdapter.getDeclaredConstructor().newInstance(); adapter.setLevel(Level.ALL); Logger logger = adapter.getLogger(this.getClass()); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/logger/slf4j/Slf4jLoggerTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/logger/slf4j/Slf4jLoggerTest.java index ce8f5b5fe0..47ed54c0fe 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/logger/slf4j/Slf4jLoggerTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/logger/slf4j/Slf4jLoggerTest.java @@ -36,8 +36,7 @@ class Slf4jLoggerTest { logger.debug("debug"); logger.trace("info"); - verify(locationAwareLogger, times(5)).log(isNull(), anyString(), - anyInt(), anyString(), isNull(), isNull()); + verify(locationAwareLogger, times(5)).log(isNull(), anyString(), anyInt(), anyString(), isNull(), isNull()); logger.error("error:{}", "arg1"); logger.warn("warn:{}", "arg1"); @@ -45,8 +44,8 @@ class Slf4jLoggerTest { logger.debug("debug:{}", "arg1"); logger.trace("info:{}", "arg1"); - verify(locationAwareLogger, times(5)).log(isNull(), anyString(), - anyInt(), anyString(), eq(new String[]{"arg1"}), isNull()); + verify(locationAwareLogger, times(5)) + .log(isNull(), anyString(), anyInt(), anyString(), eq(new String[] {"arg1"}), isNull()); logger.error(new Exception("error")); logger.warn(new Exception("warn")); @@ -60,16 +59,16 @@ class Slf4jLoggerTest { logger.debug("debug", new Exception("debug")); logger.trace("trace", new Exception("trace")); - verify(locationAwareLogger, times(10)).log(isNull(), anyString(), - anyInt(), anyString(), isNull(), any(Throwable.class)); + verify(locationAwareLogger, times(10)) + .log(isNull(), anyString(), anyInt(), anyString(), isNull(), any(Throwable.class)); - logger.error("error:{}","arg1", new Exception("error")); + logger.error("error:{}", "arg1", new Exception("error")); logger.warn("warn:{}", "arg1", new Exception("warn")); logger.info("info:{}", "arg1", new Exception("info")); logger.debug("debug:{}", "arg1", new Exception("debug")); logger.trace("trace:{}", "arg1", new Exception("trace")); - verify(locationAwareLogger, times(5)).log(isNull(), anyString(), - anyInt(), anyString(), eq(new String[]{"arg1"}), any(Throwable.class)); + verify(locationAwareLogger, times(5)) + .log(isNull(), anyString(), anyInt(), anyString(), eq(new String[] {"arg1"}), any(Throwable.class)); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/logger/support/FailsafeErrorTypeAwareLoggerTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/logger/support/FailsafeErrorTypeAwareLoggerTest.java index 78c20457dc..898d4c44c4 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/logger/support/FailsafeErrorTypeAwareLoggerTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/logger/support/FailsafeErrorTypeAwareLoggerTest.java @@ -55,8 +55,10 @@ class FailsafeErrorTypeAwareLoggerTest { doThrow(new RuntimeException()).when(failLogger).debug(any(Throwable.class)); doThrow(new RuntimeException()).when(failLogger).trace(any(Throwable.class)); - failsafeLogger.error(REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "error", new Exception("error")); - failsafeLogger.warn(REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "warn", new Exception("warn")); + failsafeLogger.error( + REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "error", new Exception("error")); + failsafeLogger.warn( + REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "warn", new Exception("warn")); } @Test @@ -70,8 +72,10 @@ class FailsafeErrorTypeAwareLoggerTest { verify(successLogger).error(anyString()); verify(successLogger).warn(anyString()); - failsafeLogger.error(REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "error", new Exception("error")); - failsafeLogger.warn(REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "warn", new Exception("warn")); + failsafeLogger.error( + REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "error", new Exception("error")); + failsafeLogger.warn( + REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", "warn", new Exception("warn")); } @Test @@ -91,10 +95,18 @@ class FailsafeErrorTypeAwareLoggerTest { ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FailsafeErrorTypeAwareLoggerTest.class); - logger.error(REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", - "error message", new Exception("error")); + logger.error( + REGISTRY_ADDRESS_INVALID, + "Registry center", + "May be it's offline.", + "error message", + new Exception("error")); - logger.error(REGISTRY_ADDRESS_INVALID, "Registry center", "May be it's offline.", - "error message", new Exception("error")); + logger.error( + REGISTRY_ADDRESS_INVALID, + "Registry center", + "May be it's offline.", + "error message", + new Exception("error")); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/logger/support/FailsafeLoggerTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/logger/support/FailsafeLoggerTest.java index 52abadc0c7..df8afe0394 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/logger/support/FailsafeLoggerTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/logger/support/FailsafeLoggerTest.java @@ -103,4 +103,4 @@ class FailsafeLoggerTest { failsafeLogger.getLogger().error("should get error"); }); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/model/Person.java b/dubbo-common/src/test/java/org/apache/dubbo/common/model/Person.java index 1dc2dba7c4..d331d0fd9c 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/model/Person.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/model/Person.java @@ -75,22 +75,15 @@ public class Person implements Serializable { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; Person other = (Person) obj; - if (age != other.age) - return false; + if (age != other.age) return false; if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (!Arrays.equals(value, other.value)) - return false; + if (other.name != null) return false; + } else if (!name.equals(other.name)) return false; + if (!Arrays.equals(value, other.value)) return false; return true; } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/model/SerializablePerson.java b/dubbo-common/src/test/java/org/apache/dubbo/common/model/SerializablePerson.java index 730d2cb319..e5c3e0c3f6 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/model/SerializablePerson.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/model/SerializablePerson.java @@ -27,9 +27,8 @@ public class SerializablePerson implements Serializable { private String[] value = {"value1", "value2"}; - public SerializablePerson(char description , boolean adult){ + public SerializablePerson(char description, boolean adult) {} - } public String getName() { return name; } @@ -79,22 +78,15 @@ public class SerializablePerson implements Serializable { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; SerializablePerson other = (SerializablePerson) obj; - if (age != other.age) - return false; + if (age != other.age) return false; if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (!Arrays.equals(value, other.value)) - return false; + if (other.name != null) return false; + } else if (!name.equals(other.name)) return false; + if (!Arrays.equals(value, other.value)) return false; return true; } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/model/User.java b/dubbo-common/src/test/java/org/apache/dubbo/common/model/User.java index 3fca20d634..b4c850905a 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/model/User.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/model/User.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.model; import java.io.Serializable; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/model/media/Image.java b/dubbo-common/src/test/java/org/apache/dubbo/common/model/media/Image.java index e83b2a7f28..999d9c7d40 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/model/media/Image.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/model/media/Image.java @@ -16,17 +16,15 @@ */ package org.apache.dubbo.common.model.media; - public class Image implements java.io.Serializable { private static final long serialVersionUID = 1L; public String uri; - public String title; // Can be null + public String title; // Can be null public int width; public int height; public Size size; - public Image() { - } + public Image() {} public Image(String uri, String title, int width, int height, Size size) { this.height = height; @@ -115,6 +113,7 @@ public class Image implements java.io.Serializable { } public enum Size { - SMALL, LARGE + SMALL, + LARGE } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/model/media/Media.java b/dubbo-common/src/test/java/org/apache/dubbo/common/model/media/Media.java index 1ad1744420..76f01f86d4 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/model/media/Media.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/model/media/Media.java @@ -21,22 +21,33 @@ import java.util.List; @SuppressWarnings("serial") public class Media implements java.io.Serializable { public String uri; - public String title; // Can be unset. + public String title; // Can be unset. public int width; public int height; public String format; public long duration; public long size; - public int bitrate; // Can be unset. + public int bitrate; // Can be unset. public boolean hasBitrate; public List persons; public Player player; - public String copyright; // Can be unset. + public String copyright; // Can be unset. - public Media() { - } + public Media() {} - public Media(String uri, String title, int width, int height, String format, long duration, long size, int bitrate, boolean hasBitrate, List persons, Player player, String copyright) { + public Media( + String uri, + String title, + int width, + int height, + String format, + long duration, + long size, + int bitrate, + boolean hasBitrate, + List persons, + Player player, + String copyright) { this.uri = uri; this.title = title; this.width = width; @@ -200,6 +211,7 @@ public class Media implements java.io.Serializable { } public enum Player { - JAVA, FLASH + JAVA, + FLASH } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/BigPerson.java b/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/BigPerson.java index 9a653e2988..15e84765f7 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/BigPerson.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/BigPerson.java @@ -33,9 +33,7 @@ public class BigPerson implements Serializable { PersonInfo infoProfile; - public BigPerson() { - - } + public BigPerson() {} public BigPerson(String id) { this.personId = id; @@ -104,40 +102,26 @@ public class BigPerson implements Serializable { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; BigPerson other = (BigPerson) obj; if (email == null) { - if (other.email != null) - return false; - } else if (!email.equals(other.email)) - return false; + if (other.email != null) return false; + } else if (!email.equals(other.email)) return false; if (infoProfile == null) { - if (other.infoProfile != null) - return false; - } else if (!infoProfile.equals(other.infoProfile)) - return false; + if (other.infoProfile != null) return false; + } else if (!infoProfile.equals(other.infoProfile)) return false; if (loginName == null) { - if (other.loginName != null) - return false; - } else if (!loginName.equals(other.loginName)) - return false; + if (other.loginName != null) return false; + } else if (!loginName.equals(other.loginName)) return false; if (penName == null) { - if (other.penName != null) - return false; - } else if (!penName.equals(other.penName)) - return false; + if (other.penName != null) return false; + } else if (!penName.equals(other.penName)) return false; if (personId == null) { - if (other.personId != null) - return false; - } else if (!personId.equals(other.personId)) - return false; - if (status != other.status) - return false; + if (other.personId != null) return false; + } else if (!personId.equals(other.personId)) return false; + if (status != other.status) return false; return true; } @@ -147,5 +131,4 @@ public class BigPerson implements Serializable { + status + ", email=" + email + ", penName=" + penName + ", infoProfile=" + infoProfile + "]"; } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/Dgeneric.java b/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/Dgeneric.java index 0aaabd87a5..b98e7b0d16 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/Dgeneric.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/Dgeneric.java @@ -18,7 +18,7 @@ package org.apache.dubbo.common.model.person; import java.io.Serializable; -public class Dgeneric implements Serializable { +public class Dgeneric implements Serializable { public static String NAME = "D"; private String name = NAME; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/FullAddress.java b/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/FullAddress.java index 6d1bed43f3..5c25a474d6 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/FullAddress.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/FullAddress.java @@ -36,11 +36,9 @@ public class FullAddress implements Serializable { private String zipCode; - public FullAddress() { - } + public FullAddress() {} - public FullAddress(String countryId, String provinceName, String cityId, String streetAddress, - String zipCode) { + public FullAddress(String countryId, String provinceName, String cityId, String streetAddress, String zipCode) { this.countryId = countryId; this.countryName = countryId; this.provinceName = provinceName; @@ -50,8 +48,14 @@ public class FullAddress implements Serializable { this.zipCode = zipCode; } - public FullAddress(String countryId, String countryName, String provinceName, String cityId, - String cityName, String streetAddress, String zipCode) { + public FullAddress( + String countryId, + String countryName, + String provinceName, + String cityId, + String cityName, + String streetAddress, + String zipCode) { this.countryId = countryId; this.countryName = countryName; this.provinceName = provinceName; @@ -133,48 +137,31 @@ public class FullAddress implements Serializable { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; FullAddress other = (FullAddress) obj; if (cityId == null) { - if (other.cityId != null) - return false; - } else if (!cityId.equals(other.cityId)) - return false; + if (other.cityId != null) return false; + } else if (!cityId.equals(other.cityId)) return false; if (cityName == null) { - if (other.cityName != null) - return false; - } else if (!cityName.equals(other.cityName)) - return false; + if (other.cityName != null) return false; + } else if (!cityName.equals(other.cityName)) return false; if (countryId == null) { - if (other.countryId != null) - return false; - } else if (!countryId.equals(other.countryId)) - return false; + if (other.countryId != null) return false; + } else if (!countryId.equals(other.countryId)) return false; if (countryName == null) { - if (other.countryName != null) - return false; - } else if (!countryName.equals(other.countryName)) - return false; + if (other.countryName != null) return false; + } else if (!countryName.equals(other.countryName)) return false; if (provinceName == null) { - if (other.provinceName != null) - return false; - } else if (!provinceName.equals(other.provinceName)) - return false; + if (other.provinceName != null) return false; + } else if (!provinceName.equals(other.provinceName)) return false; if (streetAddress == null) { - if (other.streetAddress != null) - return false; - } else if (!streetAddress.equals(other.streetAddress)) - return false; + if (other.streetAddress != null) return false; + } else if (!streetAddress.equals(other.streetAddress)) return false; if (zipCode == null) { - if (other.zipCode != null) - return false; - } else if (!zipCode.equals(other.zipCode)) - return false; + if (other.zipCode != null) return false; + } else if (!zipCode.equals(other.zipCode)) return false; return true; } @@ -198,5 +185,4 @@ public class FullAddress implements Serializable { } return sb.toString(); } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/PersonInfo.java b/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/PersonInfo.java index 15f1238fe8..3b46b3b93c 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/PersonInfo.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/PersonInfo.java @@ -141,57 +141,36 @@ public class PersonInfo implements Serializable { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; PersonInfo other = (PersonInfo) obj; if (department == null) { - if (other.department != null) - return false; - } else if (!department.equals(other.department)) - return false; + if (other.department != null) return false; + } else if (!department.equals(other.department)) return false; if (fax == null) { - if (other.fax != null) - return false; - } else if (!fax.equals(other.fax)) - return false; - if (female != other.female) - return false; + if (other.fax != null) return false; + } else if (!fax.equals(other.fax)) return false; + if (female != other.female) return false; if (fullAddress == null) { - if (other.fullAddress != null) - return false; - } else if (!fullAddress.equals(other.fullAddress)) - return false; + if (other.fullAddress != null) return false; + } else if (!fullAddress.equals(other.fullAddress)) return false; if (homepageUrl == null) { - if (other.homepageUrl != null) - return false; - } else if (!homepageUrl.equals(other.homepageUrl)) - return false; + if (other.homepageUrl != null) return false; + } else if (!homepageUrl.equals(other.homepageUrl)) return false; if (jobTitle == null) { - if (other.jobTitle != null) - return false; - } else if (!jobTitle.equals(other.jobTitle)) - return false; - if (male != other.male) - return false; + if (other.jobTitle != null) return false; + } else if (!jobTitle.equals(other.jobTitle)) return false; + if (male != other.male) return false; if (mobileNo == null) { - if (other.mobileNo != null) - return false; - } else if (!mobileNo.equals(other.mobileNo)) - return false; + if (other.mobileNo != null) return false; + } else if (!mobileNo.equals(other.mobileNo)) return false; if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; + if (other.name != null) return false; + } else if (!name.equals(other.name)) return false; if (phones == null) { - if (other.phones != null) - return false; - } else if (!phones.equals(other.phones)) - return false; + if (other.phones != null) return false; + } else if (!phones.equals(other.phones)) return false; return true; } @@ -202,5 +181,4 @@ public class PersonInfo implements Serializable { + female + ", department=" + department + ", jobTitle=" + jobTitle + ", homepageUrl=" + homepageUrl + "]"; } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/PersonMap.java b/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/PersonMap.java index 2217d6a46e..7725418eb1 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/PersonMap.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/PersonMap.java @@ -42,4 +42,3 @@ public class PersonMap extends HashMap { this.personName = personName; } } - diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/Phone.java b/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/Phone.java index 6c25ec89b4..11595ee148 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/Phone.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/model/person/Phone.java @@ -30,8 +30,7 @@ public class Phone implements Serializable { private String extensionNumber; - public Phone() { - } + public Phone() {} public Phone(String country, String area, String number, String extensionNumber) { this.country = country; @@ -85,33 +84,22 @@ public class Phone implements Serializable { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; Phone other = (Phone) obj; if (area == null) { - if (other.area != null) - return false; - } else if (!area.equals(other.area)) - return false; + if (other.area != null) return false; + } else if (!area.equals(other.area)) return false; if (country == null) { - if (other.country != null) - return false; - } else if (!country.equals(other.country)) - return false; + if (other.country != null) return false; + } else if (!country.equals(other.country)) return false; if (extensionNumber == null) { - if (other.extensionNumber != null) - return false; - } else if (!extensionNumber.equals(other.extensionNumber)) - return false; + if (other.extensionNumber != null) return false; + } else if (!extensionNumber.equals(other.extensionNumber)) return false; if (number == null) { - if (other.number != null) - return false; - } else if (!number.equals(other.number)) - return false; + if (other.number != null) return false; + } else if (!number.equals(other.number)) return false; return true; } @@ -135,5 +123,4 @@ public class Phone implements Serializable { } return sb.toString(); } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/profiler/ProfilerTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/profiler/ProfilerTest.java index 42c52f8519..6b7bc48348 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/profiler/ProfilerTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/profiler/ProfilerTest.java @@ -94,4 +94,4 @@ class ProfilerTest { Profiler.removeBizProfiler(); Assertions.assertNull(Profiler.getBizProfiler()); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/resource/GlobalResourcesRepositoryTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/resource/GlobalResourcesRepositoryTest.java index e163dfbde1..31c9d378bb 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/resource/GlobalResourcesRepositoryTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/resource/GlobalResourcesRepositoryTest.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.common.resource; +import java.util.concurrent.ExecutorService; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.concurrent.ExecutorService; - /** * {@link GlobalResourcesRepository} */ @@ -43,8 +43,10 @@ class GlobalResourcesRepositoryTest { Assertions.assertTrue(globalExecutorService.isShutdown()); Assertions.assertTrue(globalDisposable.isDestroyed()); Assertions.assertTrue(oneOffDisposable.isDestroyed()); - Assertions.assertTrue(!GlobalResourcesRepository.getGlobalReusedDisposables().isEmpty()); - Assertions.assertTrue(GlobalResourcesRepository.getGlobalReusedDisposables().contains(globalDisposable)); + Assertions.assertTrue( + !GlobalResourcesRepository.getGlobalReusedDisposables().isEmpty()); + Assertions.assertTrue( + GlobalResourcesRepository.getGlobalReusedDisposables().contains(globalDisposable)); Assertions.assertTrue(repository.getOneoffDisposables().isEmpty()); } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/CertManagerTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/CertManagerTest.java index d586abbfa8..67dab91873 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/CertManagerTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/CertManagerTest.java @@ -28,6 +28,7 @@ import org.mockito.Mockito; class CertManagerTest { private FrameworkModel frameworkModel; private URL url; + @BeforeEach void setup() { FirstCertProvider.setProviderCert(null); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/FirstCertProvider.java b/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/FirstCertProvider.java index 99153771e0..76560f961f 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/FirstCertProvider.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/FirstCertProvider.java @@ -27,6 +27,7 @@ public class FirstCertProvider implements CertProvider { private static final AtomicBoolean isSupport = new AtomicBoolean(false); private static final AtomicReference providerCert = new AtomicReference<>(); private static final AtomicReference cert = new AtomicReference<>(); + @Override public boolean isSupport(URL address) { return isSupport.get(); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/SSLConfigCertProviderTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/SSLConfigCertProviderTest.java index f7a1c02ef7..b5334a5e9c 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/SSLConfigCertProviderTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/SSLConfigCertProviderTest.java @@ -23,11 +23,11 @@ import org.apache.dubbo.config.SslConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; +import java.io.IOException; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.io.IOException; - class SSLConfigCertProviderTest { @Test void testSupported() { @@ -61,24 +61,32 @@ class SSLConfigCertProviderTest { ProviderCert providerCert = sslConfigCertProvider.getProviderConnectionConfig(url); Assertions.assertNull(providerCert); - sslConfig.setServerKeyCertChainPath(this.getClass().getClassLoader().getResource("certs/cert.pem").getFile()); - sslConfig.setServerPrivateKeyPath(this.getClass().getClassLoader().getResource("certs/key.pem").getFile()); + sslConfig.setServerKeyCertChainPath( + this.getClass().getClassLoader().getResource("certs/cert.pem").getFile()); + sslConfig.setServerPrivateKeyPath( + this.getClass().getClassLoader().getResource("certs/key.pem").getFile()); providerCert = sslConfigCertProvider.getProviderConnectionConfig(url); Assertions.assertNotNull(providerCert); - Assertions.assertArrayEquals(IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/cert.pem")), + Assertions.assertArrayEquals( + IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/cert.pem")), providerCert.getKeyCertChain()); - Assertions.assertArrayEquals(IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/key.pem")), + Assertions.assertArrayEquals( + IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/key.pem")), providerCert.getPrivateKey()); Assertions.assertNull(providerCert.getTrustCert()); - sslConfig.setServerTrustCertCollectionPath(this.getClass().getClassLoader().getResource("certs/ca.pem").getFile()); + sslConfig.setServerTrustCertCollectionPath( + this.getClass().getClassLoader().getResource("certs/ca.pem").getFile()); providerCert = sslConfigCertProvider.getProviderConnectionConfig(url); Assertions.assertNotNull(providerCert); - Assertions.assertArrayEquals(IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/cert.pem")), + Assertions.assertArrayEquals( + IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/cert.pem")), providerCert.getKeyCertChain()); - Assertions.assertArrayEquals(IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/key.pem")), + Assertions.assertArrayEquals( + IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/key.pem")), providerCert.getPrivateKey()); - Assertions.assertArrayEquals(IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/ca.pem")), + Assertions.assertArrayEquals( + IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/ca.pem")), providerCert.getTrustCert()); frameworkModel.destroy(); @@ -100,23 +108,31 @@ class SSLConfigCertProviderTest { Cert cert = sslConfigCertProvider.getConsumerConnectionConfig(url); Assertions.assertNull(cert); - sslConfig.setClientKeyCertChainPath(this.getClass().getClassLoader().getResource("certs/cert.pem").getFile()); - sslConfig.setClientPrivateKeyPath(this.getClass().getClassLoader().getResource("certs/key.pem").getFile()); + sslConfig.setClientKeyCertChainPath( + this.getClass().getClassLoader().getResource("certs/cert.pem").getFile()); + sslConfig.setClientPrivateKeyPath( + this.getClass().getClassLoader().getResource("certs/key.pem").getFile()); cert = sslConfigCertProvider.getConsumerConnectionConfig(url); Assertions.assertNotNull(cert); - Assertions.assertArrayEquals(IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/cert.pem")), + Assertions.assertArrayEquals( + IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/cert.pem")), cert.getKeyCertChain()); - Assertions.assertArrayEquals(IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/key.pem")), + Assertions.assertArrayEquals( + IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/key.pem")), cert.getPrivateKey()); - sslConfig.setClientTrustCertCollectionPath(this.getClass().getClassLoader().getResource("certs/ca.pem").getFile()); + sslConfig.setClientTrustCertCollectionPath( + this.getClass().getClassLoader().getResource("certs/ca.pem").getFile()); cert = sslConfigCertProvider.getConsumerConnectionConfig(url); Assertions.assertNotNull(cert); - Assertions.assertArrayEquals(IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/cert.pem")), + Assertions.assertArrayEquals( + IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/cert.pem")), cert.getKeyCertChain()); - Assertions.assertArrayEquals(IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/key.pem")), + Assertions.assertArrayEquals( + IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/key.pem")), cert.getPrivateKey()); - Assertions.assertArrayEquals(IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/ca.pem")), + Assertions.assertArrayEquals( + IOUtils.toByteArray(this.getClass().getClassLoader().getResourceAsStream("certs/ca.pem")), cert.getTrustCert()); frameworkModel.destroy(); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/SecondCertProvider.java b/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/SecondCertProvider.java index 950b5cb8ee..20c82057b8 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/SecondCertProvider.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/ssl/SecondCertProvider.java @@ -27,6 +27,7 @@ public class SecondCertProvider implements CertProvider { private static final AtomicBoolean isSupport = new AtomicBoolean(false); private static final AtomicReference providerCert = new AtomicReference<>(); private static final AtomicReference cert = new AtomicReference<>(); + @Override public boolean isSupport(URL address) { return isSupport.get(); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/status/StatusTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/status/StatusTest.java index 188b9692b0..1013ef9dfb 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/status/StatusTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/status/StatusTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.status; import org.junit.jupiter.api.Test; @@ -49,4 +48,4 @@ class StatusTest { assertThat(status.getMessage(), isEmptyOrNullString()); assertThat(status.getDescription(), isEmptyOrNullString()); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/status/reporter/FrameworkStatusReportServiceTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/status/reporter/FrameworkStatusReportServiceTest.java index beb9e25fde..dfc9534df0 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/status/reporter/FrameworkStatusReportServiceTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/status/reporter/FrameworkStatusReportServiceTest.java @@ -22,12 +22,12 @@ import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; +import java.util.Map; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.Map; - import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTER_MODE_INSTANCE; import static org.apache.dubbo.common.status.reporter.FrameworkStatusReportService.ADDRESS_CONSUMPTION_STATUS; import static org.apache.dubbo.common.status.reporter.FrameworkStatusReportService.MIGRATION_STEP_STATUS; @@ -44,7 +44,8 @@ class FrameworkStatusReportServiceTest { ApplicationModel applicationModel = frameworkModel.newApplication(); ApplicationConfig app = new ApplicationConfig("APP"); applicationModel.getApplicationConfigManager().setApplication(app); - FrameworkStatusReportService reportService = applicationModel.getBeanFactory().getBean(FrameworkStatusReportService.class); + FrameworkStatusReportService reportService = + applicationModel.getBeanFactory().getBean(FrameworkStatusReportService.class); // 1. reportRegistrationStatus reportService.reportRegistrationStatus(reportService.createRegistrationReport(DEFAULT_REGISTER_MODE_INSTANCE)); @@ -56,20 +57,26 @@ class FrameworkStatusReportServiceTest { Mockito.when(consumerURL.getVersion()).thenReturn("0.0.0"); Mockito.when(consumerURL.getServiceKey()).thenReturn("Group/Test:0.0.0"); Mockito.when(consumerURL.getDisplayServiceKey()).thenReturn("Test:0.0.0"); - reportService.reportConsumptionStatus( - reportService.createConsumptionReport(consumerURL.getServiceInterface(), consumerURL.getVersion(), consumerURL.getGroup(), "status") - ); + reportService.reportConsumptionStatus(reportService.createConsumptionReport( + consumerURL.getServiceInterface(), consumerURL.getVersion(), consumerURL.getGroup(), "status")); // 3. reportMigrationStepStatus - reportService.reportMigrationStepStatus( - reportService.createMigrationStepReport(consumerURL.getServiceInterface(), consumerURL.getVersion(), - consumerURL.getGroup(), "FORCE_INTERFACE", "FORCE_APPLICATION", "ture")); + reportService.reportMigrationStepStatus(reportService.createMigrationStepReport( + consumerURL.getServiceInterface(), + consumerURL.getVersion(), + consumerURL.getGroup(), + "FORCE_INTERFACE", + "FORCE_APPLICATION", + "ture")); - MockFrameworkStatusReporter statusReporter = (MockFrameworkStatusReporter) applicationModel.getExtension(FrameworkStatusReporter.class, "mock"); + MockFrameworkStatusReporter statusReporter = + (MockFrameworkStatusReporter) applicationModel.getExtension(FrameworkStatusReporter.class, "mock"); - //"migrationStepStatus" -> "{"originStep":"FORCE_INTERFACE","application":"APP","service":"Test","success":"ture","newStep":"FORCE_APPLICATION","type":"migrationStepStatus","version":"0.0.0","group":"Group"}" - //"registration" -> "{"application":"APP","status":"instance"}" - //"consumption" -> "{"application":"APP","service":"Test","type":"consumption","version":"0.0.0","group":"Group","status":"status"}" + // "migrationStepStatus" -> + // "{"originStep":"FORCE_INTERFACE","application":"APP","service":"Test","success":"ture","newStep":"FORCE_APPLICATION","type":"migrationStepStatus","version":"0.0.0","group":"Group"}" + // "registration" -> "{"application":"APP","status":"instance"}" + // "consumption" -> + // "{"application":"APP","service":"Test","type":"consumption","version":"0.0.0","group":"Group","status":"status"}" Map reportContent = statusReporter.getReportContent(); Assertions.assertEquals(reportContent.size(), 3); @@ -81,7 +88,8 @@ class FrameworkStatusReportServiceTest { // verify addressConsumptionStatus Object addressConsumptionStatus = reportContent.get(ADDRESS_CONSUMPTION_STATUS); - Map consumptionMap = JsonUtils.toJavaObject(String.valueOf(addressConsumptionStatus), Map.class); + Map consumptionMap = + JsonUtils.toJavaObject(String.valueOf(addressConsumptionStatus), Map.class); Assertions.assertEquals(consumptionMap.get("application"), "APP"); Assertions.assertEquals(consumptionMap.get("service"), "Test"); Assertions.assertEquals(consumptionMap.get("status"), "status"); @@ -91,7 +99,8 @@ class FrameworkStatusReportServiceTest { // verify migrationStepStatus Object migrationStepStatus = reportContent.get(MIGRATION_STEP_STATUS); - Map migrationStepStatusMap = JsonUtils.toJavaObject(String.valueOf(migrationStepStatus), Map.class); + Map migrationStepStatusMap = + JsonUtils.toJavaObject(String.valueOf(migrationStepStatus), Map.class); Assertions.assertEquals(migrationStepStatusMap.get("originStep"), "FORCE_INTERFACE"); Assertions.assertEquals(migrationStepStatusMap.get("application"), "APP"); Assertions.assertEquals(migrationStepStatusMap.get("service"), "Test"); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/status/support/LoadStatusCheckerTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/status/support/LoadStatusCheckerTest.java index 4d34e69a65..e87337d472 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/status/support/LoadStatusCheckerTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/status/support/LoadStatusCheckerTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.status.support; import org.apache.dubbo.common.logger.Logger; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/status/support/MemoryStatusCheckerTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/status/support/MemoryStatusCheckerTest.java index 951cae0cc9..ad5b1938a2 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/status/support/MemoryStatusCheckerTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/status/support/MemoryStatusCheckerTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.status.support; import org.apache.dubbo.common.logger.Logger; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/status/support/StatusUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/status/support/StatusUtilsTest.java index d5c3b39e18..1857bbf6f8 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/status/support/StatusUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/status/support/StatusUtilsTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,16 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.status.support; import org.apache.dubbo.common.status.Status; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; @@ -69,4 +68,4 @@ class StatusUtilsTest { assertThat(status.getLevel(), is(Status.Level.OK)); assertThat(status.getMessage(), isEmptyOrNullString()); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/store/support/SimpleDataStoreTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/store/support/SimpleDataStoreTest.java index 7b9e7ca225..fa9470426c 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/store/support/SimpleDataStoreTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/store/support/SimpleDataStoreTest.java @@ -16,10 +16,10 @@ */ package org.apache.dubbo.common.store.support; -import org.junit.jupiter.api.Test; - import java.util.Map; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; @@ -57,4 +57,4 @@ class SimpleDataStoreTest { dataStore.remove("component", "key"); assertNotEquals(map, dataStore.get("component")); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadlocal/InternalThreadLocalTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadlocal/InternalThreadLocalTest.java index 5be0f0b579..7dd93dbf7b 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadlocal/InternalThreadLocalTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadlocal/InternalThreadLocalTest.java @@ -14,13 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.threadlocal; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.lang.reflect.Field; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -28,6 +23,10 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.LockSupport; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.awaitility.Awaitility.await; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; @@ -74,7 +73,7 @@ class InternalThreadLocalTest { void testRemoveAll() { final InternalThreadLocal internalThreadLocal = new InternalThreadLocal(); internalThreadLocal.set(1); - Assertions.assertEquals(1, (int)internalThreadLocal.get(), "set failed"); + Assertions.assertEquals(1, (int) internalThreadLocal.get(), "set failed"); final InternalThreadLocal internalThreadLocalString = new InternalThreadLocal(); internalThreadLocalString.set("value"); @@ -109,7 +108,7 @@ class InternalThreadLocalTest { void testRemove() { final InternalThreadLocal internalThreadLocal = new InternalThreadLocal(); internalThreadLocal.set(1); - Assertions.assertEquals(1, (int)internalThreadLocal.get(), "get method false!"); + Assertions.assertEquals(1, (int) internalThreadLocal.get(), "get method false!"); internalThreadLocal.remove(); Assertions.assertNull(internalThreadLocal.get(), "remove failed!"); @@ -121,15 +120,15 @@ class InternalThreadLocalTest { final InternalThreadLocal internalThreadLocal = new InternalThreadLocal() { @Override protected void onRemoval(Integer value) { - //value calculate + // value calculate valueToRemove[0] = value + 1; } }; internalThreadLocal.set(1); - Assertions.assertEquals(1, (int)internalThreadLocal.get(), "get method false!"); + Assertions.assertEquals(1, (int) internalThreadLocal.get(), "get method false!"); internalThreadLocal.remove(); - Assertions.assertEquals(2, (int)valueToRemove[0], "onRemove method failed!"); + Assertions.assertEquals(2, (int) valueToRemove[0], "onRemove method failed!"); } @Test @@ -187,8 +186,7 @@ class InternalThreadLocalTest { } } long end = System.nanoTime(); - System.out.println("take[" + TimeUnit.NANOSECONDS.toMillis(end - start) + - "]ms"); + System.out.println("take[" + TimeUnit.NANOSECONDS.toMillis(end - start) + "]ms"); LockSupport.unpark(mainThread); } }); @@ -222,8 +220,7 @@ class InternalThreadLocalTest { } } long end = System.nanoTime(); - System.out.println("take[" + TimeUnit.NANOSECONDS.toMillis(end - start) + - "]ms"); + System.out.println("take[" + TimeUnit.NANOSECONDS.toMillis(end - start) + "]ms"); LockSupport.unpark(mainThread); } }); @@ -235,8 +232,7 @@ class InternalThreadLocalTest { void testConstructionWithIndex() throws Exception { // reset ARRAY_LIST_CAPACITY_MAX_SIZE to speed up int NEW_ARRAY_LIST_CAPACITY_MAX_SIZE = 8; - Field nextIndexField = - InternalThreadLocalMap.class.getDeclaredField("NEXT_INDEX"); + Field nextIndexField = InternalThreadLocalMap.class.getDeclaredField("NEXT_INDEX"); nextIndexField.setAccessible(true); AtomicInteger nextIndex = (AtomicInteger) nextIndexField.get(AtomicInteger.class); @@ -245,7 +241,7 @@ class InternalThreadLocalTest { nextIndex.set(0); final AtomicReference throwable = new AtomicReference(); try { - InternalThreadLocalMap.ARRAY_LIST_CAPACITY_MAX_SIZE = NEW_ARRAY_LIST_CAPACITY_MAX_SIZE; + InternalThreadLocalMap.ARRAY_LIST_CAPACITY_MAX_SIZE = NEW_ARRAY_LIST_CAPACITY_MAX_SIZE; while (nextIndex.get() < NEW_ARRAY_LIST_CAPACITY_MAX_SIZE) { new InternalThreadLocal(); } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadlocal/NamedInternalThreadFactoryTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadlocal/NamedInternalThreadFactoryTest.java index 3d0e34cacc..30364e771a 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadlocal/NamedInternalThreadFactoryTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadlocal/NamedInternalThreadFactoryTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.threadlocal; import org.junit.jupiter.api.Assertions; @@ -25,7 +24,7 @@ class NamedInternalThreadFactoryTest { @Test void newThread() throws Exception { NamedInternalThreadFactory namedInternalThreadFactory = new NamedInternalThreadFactory(); - Thread t = namedInternalThreadFactory.newThread(() -> { }); + Thread t = namedInternalThreadFactory.newThread(() -> {}); Assertions.assertEquals(t.getClass(), InternalThread.class, "thread is not InternalThread"); } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/MemoryLimitedLinkedBlockingQueueTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/MemoryLimitedLinkedBlockingQueueTest.java index 5b5405f535..456853c89f 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/MemoryLimitedLinkedBlockingQueueTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/MemoryLimitedLinkedBlockingQueueTest.java @@ -14,14 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.threadpool; +import java.lang.instrument.Instrumentation; + import net.bytebuddy.agent.ByteBuddyAgent; import org.junit.jupiter.api.Test; -import java.lang.instrument.Instrumentation; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -31,10 +30,10 @@ class MemoryLimitedLinkedBlockingQueueTest { ByteBuddyAgent.install(); final Instrumentation instrumentation = ByteBuddyAgent.getInstrumentation(); MemoryLimitedLinkedBlockingQueue queue = new MemoryLimitedLinkedBlockingQueue<>(1, instrumentation); - //an object needs more than 1 byte of space, so it will fail here + // an object needs more than 1 byte of space, so it will fail here assertThat(queue.offer(() -> System.out.println("add fail")), is(false)); - //will success + // will success queue.setMemoryLimit(Integer.MAX_VALUE); assertThat(queue.offer(() -> System.out.println("add success")), is(true)); } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/MemorySafeLinkedBlockingQueueTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/MemorySafeLinkedBlockingQueueTest.java index 0722a35346..b659e4c2b5 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/MemorySafeLinkedBlockingQueueTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/MemorySafeLinkedBlockingQueueTest.java @@ -14,20 +14,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.threadpool; import org.apache.dubbo.common.concurrent.AbortPolicy; import org.apache.dubbo.common.concurrent.RejectException; +import java.lang.instrument.Instrumentation; +import java.util.concurrent.LinkedBlockingQueue; + import net.bytebuddy.agent.ByteBuddyAgent; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import java.lang.instrument.Instrumentation; -import java.util.concurrent.LinkedBlockingQueue; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -37,43 +36,42 @@ class MemorySafeLinkedBlockingQueueTest { void test() { ByteBuddyAgent.install(); final Instrumentation instrumentation = ByteBuddyAgent.getInstrumentation(); - final long objectSize = instrumentation.getObjectSize((Runnable) () -> { - }); + final long objectSize = instrumentation.getObjectSize((Runnable) () -> {}); long maxFreeMemory = (long) MemoryLimitCalculator.maxAvailable(); MemorySafeLinkedBlockingQueue queue = new MemorySafeLinkedBlockingQueue<>(maxFreeMemory); // all memory is reserved for JVM, so it will fail here - assertThat(queue.offer(() -> { - }), is(false)); + assertThat(queue.offer(() -> {}), is(false)); // maxFreeMemory-objectSize Byte memory is reserved for the JVM, so this will succeed queue.setMaxFreeMemory((int) (MemoryLimitCalculator.maxAvailable() - objectSize)); - assertThat(queue.offer(() -> { - }), is(true)); + assertThat(queue.offer(() -> {}), is(true)); } @Test void testCustomReject() { MemorySafeLinkedBlockingQueue queue = new MemorySafeLinkedBlockingQueue<>(Long.MAX_VALUE); queue.setRejector(new AbortPolicy<>()); - assertThrows(RejectException.class, () -> queue.offer(() -> { - })); + assertThrows(RejectException.class, () -> queue.offer(() -> {})); } @Test @Disabled("This test is not stable, it may fail due to performance (C1, C2)") void testEfficiency() throws InterruptedException { - // if length is vert large(unit test may runs for a long time), so you may need to modify JVM param such as : -Xms=1024m -Xmx=2048m - // if you want to test efficiency of MemorySafeLinkedBlockingQueue, you may modify following param: length and times + // if length is vert large(unit test may runs for a long time), so you may need to modify JVM param such as : + // -Xms=1024m -Xmx=2048m + // if you want to test efficiency of MemorySafeLinkedBlockingQueue, you may modify following param: length and + // times int length = 1000, times = 1; // LinkedBlockingQueue insert Integer: 500W * 20 times long spent1 = spend(new LinkedBlockingQueue<>(), length, times); // MemorySafeLinkedBlockingQueue insert Integer: 500W * 20 times - long spent2 = spend(newMemorySafeLinkedBlockingQueue(), length, times); + long spent2 = spend(newMemorySafeLinkedBlockingQueue(), length, times); System.gc(); - System.out.println(String.format("LinkedBlockingQueue spent %s millis, MemorySafeLinkedBlockingQueue spent %s millis", spent1, spent2)); + System.out.println(String.format( + "LinkedBlockingQueue spent %s millis, MemorySafeLinkedBlockingQueue spent %s millis", spent1, spent2)); // efficiency between LinkedBlockingQueue and MemorySafeLinkedBlockingQueue is very nearly the same Assertions.assertTrue(spent1 - spent2 <= 1); } @@ -107,7 +105,7 @@ class MemorySafeLinkedBlockingQueueTest { private static MemorySafeLinkedBlockingQueue newMemorySafeLinkedBlockingQueue() { ByteBuddyAgent.install(); final Instrumentation instrumentation = ByteBuddyAgent.getInstrumentation(); - final long objectSize = instrumentation.getObjectSize((Runnable) () -> { }); + final long objectSize = instrumentation.getObjectSize((Runnable) () -> {}); int maxFreeMemory = (int) MemoryLimitCalculator.maxAvailable(); MemorySafeLinkedBlockingQueue queue = new MemorySafeLinkedBlockingQueue<>(maxFreeMemory); queue.setMaxFreeMemory((int) (MemoryLimitCalculator.maxAvailable() - objectSize)); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/ThreadlessExecutorTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/ThreadlessExecutorTest.java index 6c726b0702..bd658e3ff7 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/ThreadlessExecutorTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/ThreadlessExecutorTest.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.common.threadpool; +import java.util.concurrent.atomic.AtomicBoolean; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.concurrent.atomic.AtomicBoolean; - class ThreadlessExecutorTest { private static final ThreadlessExecutor executor; @@ -31,13 +31,17 @@ class ThreadlessExecutorTest { @Test void test() throws InterruptedException { for (int i = 0; i < 10; i++) { - executor.execute(()->{throw new RuntimeException("test");}); + executor.execute(() -> { + throw new RuntimeException("test"); + }); } executor.waitAndDrain(123); AtomicBoolean invoked = new AtomicBoolean(false); - executor.execute(()->{invoked.set(true);}); + executor.execute(() -> { + invoked.set(true); + }); executor.waitAndDrain(123); Assertions.assertTrue(invoked.get()); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/event/ThreadPoolExhaustedEventListenerTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/event/ThreadPoolExhaustedEventListenerTest.java index d064730f6b..edd5c648e8 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/event/ThreadPoolExhaustedEventListenerTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/event/ThreadPoolExhaustedEventListenerTest.java @@ -26,7 +26,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; */ class ThreadPoolExhaustedEventListenerTest { - private MyListener listener; @BeforeEach @@ -36,7 +35,8 @@ class ThreadPoolExhaustedEventListenerTest { @Test void testOnEvent() { - String msg = "Thread pool is EXHAUSTED! Thread Name: DubboServerHandler-127.0.0.1:12345, Pool Size: 1 (active: 0, core: 1, max: 1, largest: 1), Task: 6 (completed: 6), Executor status:(isShutdown:false, isTerminated:false, isTerminating:false), in dubbo://127.0.0.1:12345!, dubbo version: 2.7.3, current host: 127.0.0.1"; + String msg = + "Thread pool is EXHAUSTED! Thread Name: DubboServerHandler-127.0.0.1:12345, Pool Size: 1 (active: 0, core: 1, max: 1, largest: 1), Task: 6 (completed: 6), Executor status:(isShutdown:false, isTerminated:false, isTerminating:false), in dubbo://127.0.0.1:12345!, dubbo version: 2.7.3, current host: 127.0.0.1"; ThreadPoolExhaustedEvent exhaustedEvent = new ThreadPoolExhaustedEvent(msg); listener.onEvent(exhaustedEvent); assertEquals(exhaustedEvent, listener.getThreadPoolExhaustedEvent()); @@ -55,4 +55,4 @@ class ThreadPoolExhaustedEventListenerTest { return threadPoolExhaustedEvent; } } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/event/ThreadPoolExhaustedEventTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/event/ThreadPoolExhaustedEventTest.java index 8570b24af8..72f2497b7c 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/event/ThreadPoolExhaustedEventTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/event/ThreadPoolExhaustedEventTest.java @@ -27,9 +27,10 @@ class ThreadPoolExhaustedEventTest { @Test void test() { - String msg = "Thread pool is EXHAUSTED! Thread Name: DubboServerHandler-127.0.0.1:12345, Pool Size: 1 (active: 0, core: 1, max: 1, largest: 1), Task: 6 (completed: 6), Executor status:(isShutdown:false, isTerminated:false, isTerminating:false), in dubbo://127.0.0.1:12345!, dubbo version: 2.7.3, current host: 127.0.0.1"; + String msg = + "Thread pool is EXHAUSTED! Thread Name: DubboServerHandler-127.0.0.1:12345, Pool Size: 1 (active: 0, core: 1, max: 1, largest: 1), Task: 6 (completed: 6), Executor status:(isShutdown:false, isTerminated:false, isTerminating:false), in dubbo://127.0.0.1:12345!, dubbo version: 2.7.3, current host: 127.0.0.1"; ThreadPoolExhaustedEvent event = new ThreadPoolExhaustedEvent(msg); assertEquals(msg, event.getMsg()); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/manager/ExecutorRepositoryTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/manager/ExecutorRepositoryTest.java index be301d71a6..2f5b7cb1cd 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/manager/ExecutorRepositoryTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/manager/ExecutorRepositoryTest.java @@ -20,15 +20,15 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ThreadPoolExecutor; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ThreadPoolExecutor; - import static org.awaitility.Awaitility.await; class ExecutorRepositoryTest { @@ -97,7 +97,7 @@ class ExecutorRepositoryTest { ExecutorService sharedExecutor = executorRepository.getSharedExecutor(); CountDownLatch latch = new CountDownLatch(3); CountDownLatch latch1 = new CountDownLatch(1); - sharedExecutor.execute(()->{ + sharedExecutor.execute(() -> { latch.countDown(); try { latch1.await(); @@ -105,7 +105,7 @@ class ExecutorRepositoryTest { throw new RuntimeException(e); } }); - sharedExecutor.execute(()->{ + sharedExecutor.execute(() -> { latch.countDown(); try { latch1.await(); @@ -113,7 +113,7 @@ class ExecutorRepositoryTest { throw new RuntimeException(e); } }); - sharedExecutor.submit(()->{ + sharedExecutor.submit(() -> { latch.countDown(); try { latch1.await(); @@ -122,10 +122,10 @@ class ExecutorRepositoryTest { } }); - await().until(()->latch.getCount() == 0); - Assertions.assertEquals(3, ((ThreadPoolExecutor)sharedExecutor).getActiveCount()); + await().until(() -> latch.getCount() == 0); + Assertions.assertEquals(3, ((ThreadPoolExecutor) sharedExecutor).getActiveCount()); latch1.countDown(); - await().until(()->((ThreadPoolExecutor)sharedExecutor).getActiveCount() == 0); - Assertions.assertEquals(3, ((ThreadPoolExecutor)sharedExecutor).getCompletedTaskCount()); + await().until(() -> ((ThreadPoolExecutor) sharedExecutor).getActiveCount() == 0); + Assertions.assertEquals(3, ((ThreadPoolExecutor) sharedExecutor).getCompletedTaskCount()); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/manager/FrameworkExecutorRepositoryTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/manager/FrameworkExecutorRepositoryTest.java index 7090f1f157..5414a8f978 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/manager/FrameworkExecutorRepositoryTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/manager/FrameworkExecutorRepositoryTest.java @@ -18,15 +18,15 @@ package org.apache.dubbo.common.threadpool.manager; import org.apache.dubbo.rpc.model.FrameworkModel; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ThreadPoolExecutor; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ThreadPoolExecutor; - import static org.awaitility.Awaitility.await; class FrameworkExecutorRepositoryTest { @@ -56,7 +56,7 @@ class FrameworkExecutorRepositoryTest { ExecutorService sharedExecutor = frameworkExecutorRepository.getSharedExecutor(); CountDownLatch latch = new CountDownLatch(3); CountDownLatch latch1 = new CountDownLatch(1); - sharedExecutor.execute(()->{ + sharedExecutor.execute(() -> { latch.countDown(); try { latch1.await(); @@ -64,7 +64,7 @@ class FrameworkExecutorRepositoryTest { throw new RuntimeException(e); } }); - sharedExecutor.execute(()->{ + sharedExecutor.execute(() -> { latch.countDown(); try { latch1.await(); @@ -72,7 +72,7 @@ class FrameworkExecutorRepositoryTest { throw new RuntimeException(e); } }); - sharedExecutor.submit(()->{ + sharedExecutor.submit(() -> { latch.countDown(); try { latch1.await(); @@ -81,10 +81,10 @@ class FrameworkExecutorRepositoryTest { } }); - await().until(()->latch.getCount() == 0); - Assertions.assertEquals(3, ((ThreadPoolExecutor)sharedExecutor).getActiveCount()); + await().until(() -> latch.getCount() == 0); + Assertions.assertEquals(3, ((ThreadPoolExecutor) sharedExecutor).getActiveCount()); latch1.countDown(); - await().until(()->((ThreadPoolExecutor)sharedExecutor).getActiveCount() == 0); - Assertions.assertEquals(3, ((ThreadPoolExecutor)sharedExecutor).getCompletedTaskCount()); + await().until(() -> ((ThreadPoolExecutor) sharedExecutor).getActiveCount() == 0); + Assertions.assertEquals(3, ((ThreadPoolExecutor) sharedExecutor).getCompletedTaskCount()); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/serial/SerializingExecutorTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/serial/SerializingExecutorTest.java index 660c0c926c..90afb75155 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/serial/SerializingExecutorTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/serial/SerializingExecutorTest.java @@ -14,13 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.threadpool.serial; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; @@ -30,6 +25,10 @@ import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.awaitility.Awaitility.await; class SerializingExecutorTest { diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReportTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReportTest.java index 1bf52c2f02..8179d42f0a 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReportTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/AbortPolicyWithReportTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -20,9 +20,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadpool.event.ThreadPoolExhaustedEvent; import org.apache.dubbo.common.threadpool.event.ThreadPoolExhaustedListener; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.io.FileOutputStream; import java.util.UUID; import java.util.concurrent.ExecutorService; @@ -31,6 +28,9 @@ import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.OS_NAME_KEY; import static org.apache.dubbo.common.constants.CommonConstants.OS_WIN_PREFIX; import static org.awaitility.Awaitility.await; @@ -39,7 +39,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; class AbortPolicyWithReportTest { @Test void jStackDumpTest() { - URL url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?dump.directory=/tmp&version=1.0.0&application=morgan&noValue="); + URL url = URL.valueOf( + "dubbo://admin:hello1234@10.20.130.230:20880/context/path?dump.directory=/tmp&version=1.0.0&application=morgan&noValue="); AtomicReference fileOutputStream = new AtomicReference<>(); AbortPolicyWithReport abortPolicyWithReport = new AbortPolicyWithReport("Test", url) { @@ -51,7 +52,8 @@ class AbortPolicyWithReportTest { ExecutorService executorService = Executors.newFixedThreadPool(1); AbortPolicyWithReport.lastPrintTime = 0; Assertions.assertThrows(RejectedExecutionException.class, () -> { - abortPolicyWithReport.rejectedExecution(() -> System.out.println("hello"), (ThreadPoolExecutor) executorService); + abortPolicyWithReport.rejectedExecution( + () -> System.out.println("hello"), (ThreadPoolExecutor) executorService); }); await().until(() -> AbortPolicyWithReport.guard.availablePermits() == 1); @@ -63,8 +65,8 @@ class AbortPolicyWithReportTest { final String dumpDirectory = dumpDirectoryCannotBeCreated(); URL url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?dump.directory=" - + dumpDirectory - + "&version=1.0.0&application=morgan&noValue=true"); + + dumpDirectory + + "&version=1.0.0&application=morgan&noValue=true"); AbortPolicyWithReport abortPolicyWithReport = new AbortPolicyWithReport("Test", url); Assertions.assertEquals(System.getProperty("user.home"), abortPolicyWithReport.getDumpPath()); @@ -73,7 +75,8 @@ class AbortPolicyWithReportTest { private String dumpDirectoryCannotBeCreated() { final String os = System.getProperty(OS_NAME_KEY).toLowerCase(); if (os.contains(OS_WIN_PREFIX)) { - // "con" is one of Windows reserved names, https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file + // "con" is one of Windows reserved names, + // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file return "con"; } else { return "/dev/full/" + UUID.randomUUID().toString(); @@ -85,8 +88,8 @@ class AbortPolicyWithReportTest { final String dumpDirectory = UUID.randomUUID().toString(); URL url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?dump.directory=" - + dumpDirectory - + "&version=1.0.0&application=morgan&noValue=true"); + + dumpDirectory + + "&version=1.0.0&application=morgan&noValue=true"); AbortPolicyWithReport abortPolicyWithReport = new AbortPolicyWithReport("Test", url); Assertions.assertNotEquals(System.getProperty("user.home"), abortPolicyWithReport.getDumpPath()); @@ -94,9 +97,11 @@ class AbortPolicyWithReportTest { @Test void test_dispatchThreadPoolExhaustedEvent() { - URL url = URL.valueOf("dubbo://admin:hello1234@10.20.130.230:20880/context/path?dump.directory=/tmp&version=1.0.0&application=morgan&noValue="); + URL url = URL.valueOf( + "dubbo://admin:hello1234@10.20.130.230:20880/context/path?dump.directory=/tmp&version=1.0.0&application=morgan&noValue="); AbortPolicyWithReport abortPolicyWithReport = new AbortPolicyWithReport("Test", url); - String msg = "Thread pool is EXHAUSTED! Thread Name: DubboServerHandler-127.0.0.1:12345, Pool Size: 1 (active: 0, core: 1, max: 1, largest: 1), Task: 6 (completed: 6), Executor status:(isShutdown:false, isTerminated:false, isTerminating:false), in dubbo://127.0.0.1:12345!, dubbo version: 2.7.3, current host: 127.0.0.1"; + String msg = + "Thread pool is EXHAUSTED! Thread Name: DubboServerHandler-127.0.0.1:12345, Pool Size: 1 (active: 0, core: 1, max: 1, largest: 1), Task: 6 (completed: 6), Executor status:(isShutdown:false, isTerminated:false, isTerminating:false), in dubbo://127.0.0.1:12345!, dubbo version: 2.7.3, current host: 127.0.0.1"; MyListener listener = new MyListener(); abortPolicyWithReport.addThreadPoolExhaustedEventListener(listener); abortPolicyWithReport.dispatchThreadPoolExhaustedEvent(msg); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/cached/CachedThreadPoolTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/cached/CachedThreadPoolTest.java index e85bb6c0c6..bfec72a233 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/cached/CachedThreadPoolTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/cached/CachedThreadPoolTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.threadpool.support.cached; import org.apache.dubbo.common.URL; @@ -22,9 +21,6 @@ import org.apache.dubbo.common.threadlocal.InternalThread; import org.apache.dubbo.common.threadpool.ThreadPool; import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport; -import org.hamcrest.Matchers; -import org.junit.jupiter.api.Test; - import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; @@ -32,6 +28,9 @@ import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY; @@ -45,18 +44,19 @@ import static org.hamcrest.Matchers.startsWith; class CachedThreadPoolTest { @Test void getExecutor1() throws Exception { - URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + - THREAD_NAME_KEY + "=demo&" + - CORE_THREADS_KEY + "=1&" + - THREADS_KEY + "=2&" + - ALIVE_KEY + "=1000&" + - QUEUES_KEY + "=0"); + URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + THREAD_NAME_KEY + + "=demo&" + CORE_THREADS_KEY + + "=1&" + THREADS_KEY + + "=2&" + ALIVE_KEY + + "=1000&" + QUEUES_KEY + + "=0"); ThreadPool threadPool = new CachedThreadPool(); ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url); assertThat(executor.getCorePoolSize(), is(1)); assertThat(executor.getMaximumPoolSize(), is(2)); assertThat(executor.getQueue(), Matchers.>instanceOf(SynchronousQueue.class)); - assertThat(executor.getRejectedExecutionHandler(), + assertThat( + executor.getRejectedExecutionHandler(), Matchers.instanceOf(AbortPolicyWithReport.class)); final CountDownLatch latch = new CountDownLatch(1); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolExecutorTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolExecutorTest.java index 03e90eddc1..52db48a824 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolExecutorTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolExecutorTest.java @@ -24,10 +24,6 @@ import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionException; @@ -36,6 +32,10 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + import static org.awaitility.Awaitility.await; class EagerThreadPoolExecutorTest { @@ -73,22 +73,24 @@ class EagerThreadPoolExecutorTest { // alive 1 second long alive = 1000; - //init queue and executor + // init queue and executor TaskQueue taskQueue = new TaskQueue(queues); - final EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor(cores, - threads, - alive, - TimeUnit.MILLISECONDS, - taskQueue, - new NamedThreadFactory(name, true), - new AbortPolicyWithReport(name, URL)); + final EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor( + cores, + threads, + alive, + TimeUnit.MILLISECONDS, + taskQueue, + new NamedThreadFactory(name, true), + new AbortPolicyWithReport(name, URL)); taskQueue.setExecutor(executor); for (int i = 0; i < 15; i++) { Thread.sleep(50); executor.execute(() -> { - System.out.println("thread number in current pool:" + executor.getPoolSize() + ", task number in task queue:" + executor.getQueue() - .size() + " executor size: " + executor.getPoolSize()); + System.out.println( + "thread number in current pool:" + executor.getPoolSize() + ", task number in task queue:" + + executor.getQueue().size() + " executor size: " + executor.getPoolSize()); try { Thread.sleep(1000); } catch (InterruptedException e) { @@ -110,15 +112,16 @@ class EagerThreadPoolExecutorTest { // alive 1 second long alive = 1000; - //init queue and executor + // init queue and executor TaskQueue taskQueue = new TaskQueue<>(queues); - final EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor(cores, - threads, - alive, - TimeUnit.MILLISECONDS, - taskQueue, - new NamedThreadFactory(name, true), - new AbortPolicyWithReport(name, URL)); + final EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor( + cores, + threads, + alive, + TimeUnit.MILLISECONDS, + taskQueue, + new NamedThreadFactory(name, true), + new AbortPolicyWithReport(name, URL)); taskQueue.setExecutor(executor); CountDownLatch countDownLatch1 = new CountDownLatch(1); @@ -164,14 +167,14 @@ class EagerThreadPoolExecutorTest { @Test void testSPI() { - ExtensionLoader extensionLoader = ApplicationModel.defaultModel().getDefaultModule().getExtensionLoader(ThreadPool.class); + ExtensionLoader extensionLoader = + ApplicationModel.defaultModel().getDefaultModule().getExtensionLoader(ThreadPool.class); - ExecutorService executorService = (ExecutorService) extensionLoader - .getExtension("eager") - .getExecutor(URL); + ExecutorService executorService = + (ExecutorService) extensionLoader.getExtension("eager").getExecutor(URL); - Assertions.assertEquals("EagerThreadPoolExecutor", executorService.getClass() - .getSimpleName(), "test spi fail!"); + Assertions.assertEquals( + "EagerThreadPoolExecutor", executorService.getClass().getSimpleName(), "test spi fail!"); } @Test @@ -184,12 +187,14 @@ class EagerThreadPoolExecutorTest { // init queue and executor TaskQueue taskQueue = new TaskQueue<>(queues); - final EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor(cores, - threads, - alive, TimeUnit.MILLISECONDS, - taskQueue, - new NamedThreadFactory(name, true), - new AbortPolicyWithReport(name, URL)); + final EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor( + cores, + threads, + alive, + TimeUnit.MILLISECONDS, + taskQueue, + new NamedThreadFactory(name, true), + new AbortPolicyWithReport(name, URL)); taskQueue.setExecutor(executor); CountDownLatch countDownLatch = new CountDownLatch(1); @@ -215,7 +220,6 @@ class EagerThreadPoolExecutorTest { executor.execute(runnable); } - @Test void testEagerThreadPool_rejectExecution2() { String name = "eager-tf"; @@ -235,12 +239,14 @@ class EagerThreadPoolExecutorTest { return super.retryOffer(o, timeout, unit); } }; - final EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor(cores, - threads, - alive, TimeUnit.MILLISECONDS, - taskQueue, - new NamedThreadFactory(name, true), - new AbortPolicyWithReport(name, URL)); + final EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor( + cores, + threads, + alive, + TimeUnit.MILLISECONDS, + taskQueue, + new NamedThreadFactory(name, true), + new AbortPolicyWithReport(name, URL)); taskQueue.setExecutor(executor); Semaphore semaphore = new Semaphore(0); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolTest.java index 440d0156e6..ace59c4a40 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/EagerThreadPoolTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.threadpool.support.eager; import org.apache.dubbo.common.URL; @@ -22,15 +21,15 @@ import org.apache.dubbo.common.threadlocal.InternalThread; import org.apache.dubbo.common.threadpool.ThreadPool; import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport; -import org.hamcrest.Matchers; -import org.junit.jupiter.api.Test; - import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.ALIVE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY; @@ -44,12 +43,12 @@ import static org.hamcrest.Matchers.startsWith; class EagerThreadPoolTest { @Test void getExecutor1() throws Exception { - URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + - THREAD_NAME_KEY + "=demo&" + - CORE_THREADS_KEY + "=1&" + - THREADS_KEY + "=2&" + - ALIVE_KEY + "=1000&" + - QUEUES_KEY + "=0"); + URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + THREAD_NAME_KEY + + "=demo&" + CORE_THREADS_KEY + + "=1&" + THREADS_KEY + + "=2&" + ALIVE_KEY + + "=1000&" + QUEUES_KEY + + "=0"); ThreadPool threadPool = new EagerThreadPool(); ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url); assertThat(executor, instanceOf(EagerThreadPoolExecutor.class)); @@ -58,7 +57,8 @@ class EagerThreadPoolTest { assertThat(executor.getKeepAliveTime(TimeUnit.MILLISECONDS), is(1000L)); assertThat(executor.getQueue().remainingCapacity(), is(1)); assertThat(executor.getQueue(), Matchers.>instanceOf(TaskQueue.class)); - assertThat(executor.getRejectedExecutionHandler(), + assertThat( + executor.getRejectedExecutionHandler(), Matchers.instanceOf(AbortPolicyWithReport.class)); final CountDownLatch latch = new CountDownLatch(1); @@ -80,5 +80,4 @@ class EagerThreadPoolTest { ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url); assertThat(executor.getQueue().remainingCapacity(), is(2)); } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/TaskQueueTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/TaskQueueTest.java index 42c4bf6c23..a61e59a218 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/TaskQueueTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/eager/TaskQueueTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,16 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.threadpool.support.eager; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.TimeUnit; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.mock; @@ -81,7 +80,6 @@ class TaskQueueTest { }); } - @Test void testRetryOffer2() throws Exception { TaskQueue queue = new TaskQueue(1); @@ -90,5 +88,4 @@ class TaskQueueTest { queue.setExecutor(executor); assertThat(queue.retryOffer(mock(Runnable.class), 1000, TimeUnit.MILLISECONDS), is(true)); } - -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/fixed/FixedThreadPoolTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/fixed/FixedThreadPoolTest.java index 5a10dd934c..a12bcc0f3f 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/fixed/FixedThreadPoolTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/fixed/FixedThreadPoolTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.threadpool.support.fixed; import org.apache.dubbo.common.URL; @@ -22,9 +21,6 @@ import org.apache.dubbo.common.threadlocal.InternalThread; import org.apache.dubbo.common.threadpool.ThreadPool; import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport; -import org.hamcrest.Matchers; -import org.junit.jupiter.api.Test; - import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; @@ -33,6 +29,9 @@ import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; @@ -45,18 +44,19 @@ import static org.hamcrest.Matchers.startsWith; class FixedThreadPoolTest { @Test void getExecutor1() throws Exception { - URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + - THREAD_NAME_KEY + "=demo&" + - CORE_THREADS_KEY + "=1&" + - THREADS_KEY + "=2&" + - QUEUES_KEY + "=0"); + URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + THREAD_NAME_KEY + + "=demo&" + CORE_THREADS_KEY + + "=1&" + THREADS_KEY + + "=2&" + QUEUES_KEY + + "=0"); ThreadPool threadPool = new FixedThreadPool(); ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url); assertThat(executor.getCorePoolSize(), is(2)); assertThat(executor.getMaximumPoolSize(), is(2)); assertThat(executor.getKeepAliveTime(TimeUnit.MILLISECONDS), is(0L)); assertThat(executor.getQueue(), Matchers.>instanceOf(SynchronousQueue.class)); - assertThat(executor.getRejectedExecutionHandler(), + assertThat( + executor.getRejectedExecutionHandler(), Matchers.instanceOf(AbortPolicyWithReport.class)); final CountDownLatch latch = new CountDownLatch(1); @@ -81,4 +81,4 @@ class FixedThreadPoolTest { ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url); assertThat(executor.getQueue(), Matchers.>instanceOf(LinkedBlockingQueue.class)); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/limited/LimitedThreadPoolTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/limited/LimitedThreadPoolTest.java index 66ef2cac84..5d562b4cd2 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/limited/LimitedThreadPoolTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/threadpool/support/limited/LimitedThreadPoolTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.threadpool.support.limited; import org.apache.dubbo.common.URL; @@ -22,9 +21,6 @@ import org.apache.dubbo.common.threadlocal.InternalThread; import org.apache.dubbo.common.threadpool.ThreadPool; import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport; -import org.hamcrest.Matchers; -import org.junit.jupiter.api.Test; - import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; @@ -32,6 +28,9 @@ import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; @@ -44,17 +43,18 @@ import static org.hamcrest.Matchers.startsWith; class LimitedThreadPoolTest { @Test void getExecutor1() throws Exception { - URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + - THREAD_NAME_KEY + "=demo&" + - CORE_THREADS_KEY + "=1&" + - THREADS_KEY + "=2&" + - QUEUES_KEY + "=0"); + URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + THREAD_NAME_KEY + + "=demo&" + CORE_THREADS_KEY + + "=1&" + THREADS_KEY + + "=2&" + QUEUES_KEY + + "=0"); ThreadPool threadPool = new LimitedThreadPool(); ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url); assertThat(executor.getCorePoolSize(), is(1)); assertThat(executor.getMaximumPoolSize(), is(2)); assertThat(executor.getQueue(), Matchers.>instanceOf(SynchronousQueue.class)); - assertThat(executor.getRejectedExecutionHandler(), + assertThat( + executor.getRejectedExecutionHandler(), Matchers.instanceOf(AbortPolicyWithReport.class)); final CountDownLatch latch = new CountDownLatch(1); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/timer/HashedWheelTimerTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/timer/HashedWheelTimerTest.java index 3c3396a111..46fd9ea0e2 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/timer/HashedWheelTimerTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/timer/HashedWheelTimerTest.java @@ -14,20 +14,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.timer; import org.apache.dubbo.common.utils.NamedThreadFactory; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.lang.ref.WeakReference; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.awaitility.Awaitility.await; class HashedWheelTimerTest { @@ -36,8 +35,7 @@ class HashedWheelTimerTest { private static class EmptyTask implements TimerTask { @Override - public void run(Timeout timeout) { - } + public void run(Timeout timeout) {} } private static class BlockTask implements TimerTask { @@ -79,27 +77,25 @@ class HashedWheelTimerTest { // to cover arg check branches Assertions.assertThrows(RuntimeException.class, () -> { - new HashedWheelTimer( - null, - 100, - TimeUnit.MILLISECONDS, - 8, -1); + new HashedWheelTimer(null, 100, TimeUnit.MILLISECONDS, 8, -1); + }); + + Assertions.assertThrows(RuntimeException.class, () -> { + new HashedWheelTimer(new NamedThreadFactory("dubbo-future-timeout", true), 0, TimeUnit.MILLISECONDS, 8, -1); + }); + + Assertions.assertThrows(RuntimeException.class, () -> { + new HashedWheelTimer(new NamedThreadFactory("dubbo-future-timeout", true), 100, null, 8, -1); }); Assertions.assertThrows(RuntimeException.class, () -> { new HashedWheelTimer( - new NamedThreadFactory("dubbo-future-timeout", true), - 0, - TimeUnit.MILLISECONDS, - 8, -1); + new NamedThreadFactory("dubbo-future-timeout", true), 100, TimeUnit.MILLISECONDS, 0, -1); }); Assertions.assertThrows(RuntimeException.class, () -> { new HashedWheelTimer( - new NamedThreadFactory("dubbo-future-timeout", true), - 100, - null, - 8, -1); + new NamedThreadFactory("dubbo-future-timeout", true), Long.MAX_VALUE, TimeUnit.MILLISECONDS, 8, -1); }); Assertions.assertThrows(RuntimeException.class, () -> { @@ -107,23 +103,8 @@ class HashedWheelTimerTest { new NamedThreadFactory("dubbo-future-timeout", true), 100, TimeUnit.MILLISECONDS, - 0, -1); - }); - - Assertions.assertThrows(RuntimeException.class, () -> { - new HashedWheelTimer( - new NamedThreadFactory("dubbo-future-timeout", true), - Long.MAX_VALUE, - TimeUnit.MILLISECONDS, - 8, -1); - }); - - Assertions.assertThrows(RuntimeException.class, () -> { - new HashedWheelTimer( - new NamedThreadFactory("dubbo-future-timeout", true), - 100, - TimeUnit.MILLISECONDS, - Integer.MAX_VALUE, -1); + Integer.MAX_VALUE, + -1); }); for (int i = 0; i < 128; i++) { @@ -137,16 +118,11 @@ class HashedWheelTimerTest { @Test void createTaskTest() throws InterruptedException { HashedWheelTimer timer = new HashedWheelTimer( - new NamedThreadFactory("dubbo-future-timeout", true), - 10, - TimeUnit.MILLISECONDS, - 8, 8); + new NamedThreadFactory("dubbo-future-timeout", true), 10, TimeUnit.MILLISECONDS, 8, 8); EmptyTask emptyTask = new EmptyTask(); - Assertions.assertThrows(RuntimeException.class, - () -> timer.newTimeout(null, 5, TimeUnit.SECONDS)); - Assertions.assertThrows(RuntimeException.class, - () -> timer.newTimeout(emptyTask, 5, null)); + Assertions.assertThrows(RuntimeException.class, () -> timer.newTimeout(null, 5, TimeUnit.SECONDS)); + Assertions.assertThrows(RuntimeException.class, () -> timer.newTimeout(emptyTask, 5, null)); Timeout timeout = timer.newTimeout(new ErrorTask(), 10, TimeUnit.MILLISECONDS); errorTaskCountDownLatch.await(); @@ -170,8 +146,7 @@ class HashedWheelTimerTest { Assertions.assertEquals(8, timer.pendingTimeouts()); // this will throw an exception because of maxPendingTimeouts - Assertions.assertThrows(RuntimeException.class, - () -> timer.newTimeout(blockTask, 1, TimeUnit.MILLISECONDS)); + Assertions.assertThrows(RuntimeException.class, () -> timer.newTimeout(blockTask, 1, TimeUnit.MILLISECONDS)); Timeout secondTimeout = timeouts.get(2); // wait until the task expired @@ -194,8 +169,6 @@ class HashedWheelTimerTest { Assertions.assertTrue(timer.isStop()); // this will throw an exception - Assertions.assertThrows(RuntimeException.class, - () -> timer.newTimeout(new EmptyTask(), 5, TimeUnit.SECONDS)); - + Assertions.assertThrows(RuntimeException.class, () -> timer.newTimeout(new EmptyTask(), 5, TimeUnit.SECONDS)); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/url/URLParamTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/url/URLParamTest.java index 3c1665cd79..bf8c04157e 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/url/URLParamTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/url/URLParamTest.java @@ -19,15 +19,15 @@ package org.apache.dubbo.common.url; import org.apache.dubbo.common.url.component.URLParam; import org.apache.dubbo.common.utils.CollectionUtils; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class URLParamTest { @Test void testParseWithRawParam() { @@ -121,7 +121,6 @@ class URLParamTest { URLParam urlParam4 = URLParam.parse("aaa=aaa&side=provider"); Assertions.assertEquals("provider", urlParam4.getParameter("side")); - } @Test @@ -208,8 +207,7 @@ class URLParamTest { URLParam urlParam10 = urlParam8.addParametersIfAbsent(map); Assertions.assertEquals("provider", urlParam10.getParameter("side")); - Assertions.assertThrows(IllegalArgumentException.class, - () -> urlParam1.addParameter("side", "unrecognized")); + Assertions.assertThrows(IllegalArgumentException.class, () -> urlParam1.addParameter("side", "unrecognized")); } @Test @@ -220,7 +218,9 @@ class URLParamTest { Assertions.assertFalse(urlParam1.getParameters().containsKey("aaa")); Assertions.assertFalse(urlParam1.getParameters().containsKey("version")); Assertions.assertFalse(urlParam1.getParameters().containsKey(new Object())); - Assertions.assertEquals(new HashMap<>(urlParam1.getParameters()).toString(), urlParam1.getParameters().toString()); + Assertions.assertEquals( + new HashMap<>(urlParam1.getParameters()).toString(), + urlParam1.getParameters().toString()); URLParam urlParam2 = URLParam.parse("aaa=aaa&version=1.0"); URLParam.URLParamMap urlParam2Map = (URLParam.URLParamMap) urlParam2.getParameters(); @@ -267,39 +267,45 @@ class URLParamTest { URLParam urlParam3 = URLParam.parse("aaa=aaa&version=1.0"); Assertions.assertTrue(CollectionUtils.mapEquals(urlParam2Map, urlParam3.getParameters())); - Assertions.assertTrue(CollectionUtils.equals(urlParam2Map.entrySet(), urlParam3.getParameters().entrySet())); - Assertions.assertTrue(CollectionUtils.equals(urlParam2Map.keySet(), urlParam3.getParameters().keySet())); - Assertions.assertTrue(CollectionUtils.equals(urlParam2Map.values(), urlParam3.getParameters().values())); + Assertions.assertTrue(CollectionUtils.equals( + urlParam2Map.entrySet(), urlParam3.getParameters().entrySet())); + Assertions.assertTrue(CollectionUtils.equals( + urlParam2Map.keySet(), urlParam3.getParameters().keySet())); + Assertions.assertTrue(CollectionUtils.equals( + urlParam2Map.values(), urlParam3.getParameters().values())); URLParam urlParam4 = URLParam.parse("aaa=aaa&version=1.0&side=consumer"); Assertions.assertFalse(CollectionUtils.mapEquals(urlParam2Map, urlParam4.getParameters())); - Assertions.assertFalse(CollectionUtils.equals(urlParam2Map.entrySet(), urlParam4.getParameters().entrySet())); - Assertions.assertFalse(CollectionUtils.equals(urlParam2Map.keySet(), urlParam4.getParameters().keySet())); - Assertions.assertFalse(CollectionUtils.equals(urlParam2Map.values(), urlParam4.getParameters().values())); + Assertions.assertFalse(CollectionUtils.equals( + urlParam2Map.entrySet(), urlParam4.getParameters().entrySet())); + Assertions.assertFalse(CollectionUtils.equals( + urlParam2Map.keySet(), urlParam4.getParameters().keySet())); + Assertions.assertFalse(CollectionUtils.equals( + urlParam2Map.values(), urlParam4.getParameters().values())); - Set> set = new HashSet<>(); + Set> set = new HashSet<>(); set.add(urlParam2Map); set.add(urlParam3.getParameters()); - Assertions.assertEquals(1,set.size()); + Assertions.assertEquals(1, set.size()); set.add(urlParam4.getParameters()); - Assertions.assertEquals(2,set.size()); + Assertions.assertEquals(2, set.size()); URLParam urlParam5 = URLParam.parse("version=1.0"); - Assertions.assertEquals(new HashMap<>(urlParam5.getParameters()).toString(), urlParam5.getParameters().toString()); - + Assertions.assertEquals( + new HashMap<>(urlParam5.getParameters()).toString(), + urlParam5.getParameters().toString()); } @Test void testMethodParameters() { URLParam urlParam1 = URLParam.parse("aaa.method1=aaa&bbb.method2=bbb"); - Assertions.assertEquals("aaa",urlParam1.getAnyMethodParameter("method1")); - Assertions.assertEquals("bbb",urlParam1.getAnyMethodParameter("method2")); - + Assertions.assertEquals("aaa", urlParam1.getAnyMethodParameter("method1")); + Assertions.assertEquals("bbb", urlParam1.getAnyMethodParameter("method2")); URLParam urlParam2 = URLParam.parse("methods=aaa&aaa.method1=aaa&bbb.method2=bbb"); - Assertions.assertEquals("aaa",urlParam2.getAnyMethodParameter("method1")); + Assertions.assertEquals("aaa", urlParam2.getAnyMethodParameter("method1")); Assertions.assertNull(urlParam2.getAnyMethodParameter("method2")); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/AnnotationUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/AnnotationUtilsTest.java index ceadeaf4f3..25114a4291 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/AnnotationUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/AnnotationUtilsTest.java @@ -20,8 +20,6 @@ import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.config.annotation.Service; -import org.junit.jupiter.api.Test; - import java.lang.annotation.Annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; @@ -34,6 +32,8 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Test; + import static java.util.Arrays.asList; import static org.apache.dubbo.common.utils.AnnotationUtils.excludedType; import static org.apache.dubbo.common.utils.AnnotationUtils.filterDefaultValues; @@ -160,11 +160,11 @@ class AnnotationUtilsTest { annotations = getAllDeclaredAnnotations(findMethod(A.class, "execute")); MyAdaptive myAdaptive = (MyAdaptive) annotations.get(0); - assertArrayEquals(new String[]{"e"}, myAdaptive.value()); + assertArrayEquals(new String[] {"e"}, myAdaptive.value()); annotations = getAllDeclaredAnnotations(findMethod(B.class, "execute")); Adaptive adaptive = (Adaptive) annotations.get(0); - assertArrayEquals(new String[]{"f"}, adaptive.value()); + assertArrayEquals(new String[] {"f"}, adaptive.value()); } @Test @@ -210,34 +210,38 @@ class AnnotationUtilsTest { assertEquals(set3, set4); } - @Test void testIsAnnotationPresent() { assertTrue(isAnnotationPresent(A.class, true, Service.class)); -// assertTrue(isAnnotationPresent(A.class, true, Service.class, com.alibaba.dubbo.config.annotation.Service.class)); + // assertTrue(isAnnotationPresent(A.class, true, Service.class, + // com.alibaba.dubbo.config.annotation.Service.class)); assertTrue(isAnnotationPresent(A.class, Service.class)); assertTrue(isAnnotationPresent(A.class, "org.apache.dubbo.config.annotation.Service")); -// assertTrue(AnnotationUtils.isAllAnnotationPresent(A.class, Service.class, Service.class, com.alibaba.dubbo.config.annotation.Service.class)); + // assertTrue(AnnotationUtils.isAllAnnotationPresent(A.class, Service.class, Service.class, + // com.alibaba.dubbo.config.annotation.Service.class)); assertTrue(AnnotationUtils.isAllAnnotationPresent(A.class, Service.class, Service.class)); assertTrue(isAnnotationPresent(A.class, Deprecated.class)); } @Test void testIsAnyAnnotationPresent() { -// assertTrue(isAnyAnnotationPresent(A.class, Service.class, com.alibaba.dubbo.config.annotation.Service.class, Deprecated.class)); -// assertTrue(isAnyAnnotationPresent(A.class, Service.class, com.alibaba.dubbo.config.annotation.Service.class)); + // assertTrue(isAnyAnnotationPresent(A.class, Service.class, + // com.alibaba.dubbo.config.annotation.Service.class, Deprecated.class)); + // assertTrue(isAnyAnnotationPresent(A.class, Service.class, + // com.alibaba.dubbo.config.annotation.Service.class)); assertTrue(isAnyAnnotationPresent(A.class, Service.class, Deprecated.class)); -// assertTrue(isAnyAnnotationPresent(A.class, com.alibaba.dubbo.config.annotation.Service.class, Deprecated.class)); + // assertTrue(isAnyAnnotationPresent(A.class, com.alibaba.dubbo.config.annotation.Service.class, + // Deprecated.class)); assertTrue(isAnyAnnotationPresent(A.class, Deprecated.class)); assertTrue(isAnyAnnotationPresent(A.class, Service.class)); -// assertTrue(isAnyAnnotationPresent(A.class, com.alibaba.dubbo.config.annotation.Service.class)); + // assertTrue(isAnyAnnotationPresent(A.class, com.alibaba.dubbo.config.annotation.Service.class)); assertTrue(isAnyAnnotationPresent(A.class, Deprecated.class)); } @Test void testGetAnnotation() { assertNotNull(getAnnotation(A.class, "org.apache.dubbo.config.annotation.Service")); -// assertNotNull(getAnnotation(A.class, "com.alibaba.dubbo.config.annotation.Service")); + // assertNotNull(getAnnotation(A.class, "com.alibaba.dubbo.config.annotation.Service")); assertNotNull(getAnnotation(A.class, "org.apache.dubbo.common.extension.Adaptive")); assertNull(getAnnotation(A.class, "java.lang.Deprecated")); assertNull(getAnnotation(A.class, "java.lang.String")); @@ -288,11 +292,7 @@ class AnnotationUtilsTest { static class A { @MyAdaptive("e") - public void execute() { - - } - - + public void execute() {} } @Documented @@ -300,40 +300,28 @@ class AnnotationUtilsTest { @Target({ElementType.TYPE}) @Inherited @DubboService(interfaceClass = Cloneable.class) - @interface Service2 { - - - } + @interface Service2 {} @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Inherited @Service2 - @interface Service3 { - - - } + @interface Service3 {} @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Inherited @Service3 - @interface Service4 { - - - } + @interface Service4 {} @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Inherited @Service4 - @interface Service5 { - - - } + @interface Service5 {} @Documented @Retention(RetentionPolicy.RUNTIME) @@ -343,7 +331,6 @@ class AnnotationUtilsTest { @interface MyAdaptive { String[] value() default {}; - } @Service5 @@ -351,17 +338,11 @@ class AnnotationUtilsTest { @Adaptive("f") @Override - public void execute() { - - } - - + public void execute() {} } @MyAdaptive - static class C extends B { - - } + static class C extends B {} private void assertADeclaredAnnotations(List annotations, int offset) { int size = 2 + offset; @@ -369,15 +350,15 @@ class AnnotationUtilsTest { boolean apacheServiceFound = false; boolean adaptiveFound = false; - for (Annotation annotation: annotations) { + for (Annotation annotation : annotations) { if (!apacheServiceFound && (annotation instanceof Service)) { - assertEquals("java.lang.CharSequence", ((Service)annotation).interfaceName()); - assertEquals(CharSequence.class, ((Service)annotation).interfaceClass()); + assertEquals("java.lang.CharSequence", ((Service) annotation).interfaceName()); + assertEquals(CharSequence.class, ((Service) annotation).interfaceClass()); apacheServiceFound = true; continue; } if (!adaptiveFound && (annotation instanceof Adaptive)) { - assertArrayEquals(new String[]{"a", "b", "c"}, ((Adaptive)annotation).value()); + assertArrayEquals(new String[] {"a", "b", "c"}, ((Adaptive) annotation).value()); adaptiveFound = true; continue; } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ArrayUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ArrayUtilsTest.java index 164329bea0..364336e4af 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ArrayUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ArrayUtilsTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; import org.junit.jupiter.api.Test; @@ -28,14 +27,13 @@ class ArrayUtilsTest { void isEmpty() { assertTrue(ArrayUtils.isEmpty(null)); assertTrue(ArrayUtils.isEmpty(new Object[0])); - assertFalse(ArrayUtils.isEmpty(new Object[]{"abc"})); + assertFalse(ArrayUtils.isEmpty(new Object[] {"abc"})); } @Test void isNotEmpty() { assertFalse(ArrayUtils.isNotEmpty(null)); assertFalse(ArrayUtils.isNotEmpty(new Object[0])); - assertTrue(ArrayUtils.isNotEmpty(new Object[]{"abc"})); + assertTrue(ArrayUtils.isNotEmpty(new Object[] {"abc"})); } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/AssertTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/AssertTest.java index c8c9385b05..d5cfb54a60 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/AssertTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/AssertTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; import org.junit.jupiter.api.Assertions; @@ -31,7 +30,8 @@ class AssertTest { @Test void testNotNull2() { - Assertions.assertThrows(IllegalStateException.class, () -> notNull(null, new IllegalStateException("null object"))); + Assertions.assertThrows( + IllegalStateException.class, () -> notNull(null, new IllegalStateException("null object"))); } @Test @@ -51,11 +51,12 @@ class AssertTest { @Test void testNotEmptyString() { - Assertions.assertThrows(IllegalArgumentException.class, () -> notEmptyString("", "Message can't be null or empty")); + Assertions.assertThrows( + IllegalArgumentException.class, () -> notEmptyString("", "Message can't be null or empty")); } @Test void testNotNullNotEmptyString() { notEmptyString("abcd", "Message can'be null or empty"); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/AtomicPositiveIntegerTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/AtomicPositiveIntegerTest.java index bc7b23fca8..716ac89c77 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/AtomicPositiveIntegerTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/AtomicPositiveIntegerTest.java @@ -50,8 +50,7 @@ class AtomicPositiveIntegerTest { i1.set(-1); fail(); } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage(), - allOf(containsString("new value"), containsString("< 0"))); + assertThat(expected.getMessage(), allOf(containsString("new value"), containsString("< 0"))); } } @@ -124,8 +123,7 @@ class AtomicPositiveIntegerTest { try { i1.getAndSet(-1); } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage(), - allOf(containsString("new value"), containsString("< 0"))); + assertThat(expected.getMessage(), allOf(containsString("new value"), containsString("< 0"))); } } @@ -144,7 +142,6 @@ class AtomicPositiveIntegerTest { assertEquals(2, i3.get()); } - @Test void testAddAndGet() { int get = i1.addAndGet(3); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CIDRUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CIDRUtilsTest.java index 2264cb795a..83f65d7f73 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CIDRUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CIDRUtilsTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -16,11 +16,11 @@ */ package org.apache.dubbo.common.utils; +import java.net.UnknownHostException; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.net.UnknownHostException; - class CIDRUtilsTest { @Test @@ -50,4 +50,4 @@ class CIDRUtilsTest { Assertions.assertFalse(cidrUtils.isInRange("3EFE:FFFE:0:C107::dd")); Assertions.assertFalse(cidrUtils.isInRange("1FFE:FFFE:0:CC00::dd")); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ClassLoaderResourceLoaderTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ClassLoaderResourceLoaderTest.java index 09dcfd8e67..cf5b028240 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ClassLoaderResourceLoaderTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ClassLoaderResourceLoaderTest.java @@ -20,14 +20,14 @@ import org.apache.dubbo.common.extension.DubboInternalLoadingStrategy; import org.apache.dubbo.common.extension.director.FooAppProvider; import org.apache.dubbo.common.resource.GlobalResourcesRepository; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.net.URL; import java.util.Arrays; import java.util.Map; import java.util.Set; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + /** * {@link ClassLoaderResourceLoader} */ @@ -41,7 +41,8 @@ class ClassLoaderResourceLoaderTest { String fileName = directory + type; ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); - Map> loadResources = ClassLoaderResourceLoader.loadResources(fileName, Arrays.asList(contextClassLoader)); + Map> loadResources = + ClassLoaderResourceLoader.loadResources(fileName, Arrays.asList(contextClassLoader)); Assertions.assertTrue(loadResources.containsKey(contextClassLoader)); Assertions.assertTrue(!loadResources.get(contextClassLoader).isEmpty()); @@ -56,4 +57,4 @@ class ClassLoaderResourceLoaderTest { ClassLoaderResourceLoader.destroy(); Assertions.assertNull(ClassLoaderResourceLoader.getClassLoaderResourcesCache()); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ClassUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ClassUtilsTest.java index 2df753bcb4..36ae28ae5f 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ClassUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ClassUtilsTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; import org.junit.jupiter.api.Test; @@ -49,7 +48,9 @@ class ClassUtilsTest { @Test void testGetCallerClassLoader() { - assertThat(ClassUtils.getCallerClassLoader(ClassUtilsTest.class), sameInstance(ClassUtilsTest.class.getClassLoader())); + assertThat( + ClassUtils.getCallerClassLoader(ClassUtilsTest.class), + sameInstance(ClassUtilsTest.class.getClassLoader())); } @Test @@ -58,7 +59,9 @@ class ClassUtilsTest { try { assertThat(ClassUtils.getClassLoader(ClassUtilsTest.class), sameInstance(oldClassLoader)); Thread.currentThread().setContextClassLoader(null); - assertThat(ClassUtils.getClassLoader(ClassUtilsTest.class), sameInstance(ClassUtilsTest.class.getClassLoader())); + assertThat( + ClassUtils.getClassLoader(ClassUtilsTest.class), + sameInstance(ClassUtilsTest.class.getClassLoader())); } finally { Thread.currentThread().setContextClassLoader(oldClassLoader); } @@ -129,7 +132,6 @@ class ClassUtilsTest { assertThat(ClassUtils.convertPrimitive(byte.class, null), equalTo(null)); assertThat(ClassUtils.convertPrimitive(byte.class, "127"), equalTo(Byte.MAX_VALUE)); - assertThat(ClassUtils.convertPrimitive(short.class, ""), equalTo(null)); assertThat(ClassUtils.convertPrimitive(short.class, null), equalTo(null)); assertThat(ClassUtils.convertPrimitive(short.class, "32767"), equalTo(Short.MAX_VALUE)); @@ -150,5 +152,4 @@ class ClassUtilsTest { assertThat(ClassUtils.convertPrimitive(double.class, null), equalTo(null)); assertThat(ClassUtils.convertPrimitive(double.class, "10.1"), equalTo(Double.valueOf(10.1))); } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CollectionUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CollectionUtilsTest.java index 8df47daf4a..0a23526151 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CollectionUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CollectionUtilsTest.java @@ -18,9 +18,6 @@ package org.apache.dubbo.common.utils; import org.apache.dubbo.config.ProtocolConfig; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -31,6 +28,9 @@ import java.util.List; import java.util.Map; import java.util.Set; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static java.util.Collections.emptyList; import static java.util.Collections.emptySet; import static java.util.Collections.singleton; @@ -114,7 +114,8 @@ class CollectionUtilsTest { assertNull(CollectionUtils.splitAll(null, null)); assertNull(CollectionUtils.splitAll(null, "-")); - assertTrue(CollectionUtils.splitAll(new HashMap>(), "-").isEmpty()); + assertTrue(CollectionUtils.splitAll(new HashMap>(), "-") + .isEmpty()); Map> input = new HashMap>(); input.put("key1", Arrays.asList("1:a", "2:b", "3:c")); @@ -150,8 +151,7 @@ class CollectionUtilsTest { Map> output = CollectionUtils.joinAll(input, ":"); for (Map.Entry> entry : output.entrySet()) { - if (entry.getValue() == null) - continue; + if (entry.getValue() == null) continue; Collections.sort(entry.getValue()); } @@ -176,8 +176,10 @@ class CollectionUtilsTest { assertFalse(CollectionUtils.mapEquals(null, new HashMap())); assertFalse(CollectionUtils.mapEquals(new HashMap(), null)); - assertTrue(CollectionUtils.mapEquals(CollectionUtils.toStringMap("1", "a", "2", "b"), CollectionUtils.toStringMap("1", "a", "2", "b"))); - assertFalse(CollectionUtils.mapEquals(CollectionUtils.toStringMap("1", "a"), CollectionUtils.toStringMap("1", "a", "2", "b"))); + assertTrue(CollectionUtils.mapEquals( + CollectionUtils.toStringMap("1", "a", "2", "b"), CollectionUtils.toStringMap("1", "a", "2", "b"))); + assertFalse(CollectionUtils.mapEquals( + CollectionUtils.toStringMap("1", "a"), CollectionUtils.toStringMap("1", "a", "2", "b"))); } @Test @@ -204,7 +206,7 @@ class CollectionUtilsTest { @Test void testObjectToMap() throws Exception { - ProtocolConfig protocolConfig=new ProtocolConfig(); + ProtocolConfig protocolConfig = new ProtocolConfig(); protocolConfig.setSerialization("fastjson2"); assertFalse(CollectionUtils.objToMap(protocolConfig).isEmpty()); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CompatibleTypeUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CompatibleTypeUtilsTest.java index 1599d25a4f..cf1c4436c0 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CompatibleTypeUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/CompatibleTypeUtilsTest.java @@ -16,8 +16,6 @@ */ package org.apache.dubbo.common.utils; -import org.junit.jupiter.api.Test; - import java.math.BigDecimal; import java.math.BigInteger; import java.text.SimpleDateFormat; @@ -29,6 +27,8 @@ import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; @@ -76,10 +76,15 @@ class CompatibleTypeUtilsTest { assertEquals(new SimpleDateFormat("HH:mm:ss").format((java.sql.Time) result), "12:24:12"); result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11 12:24:12", java.sql.Timestamp.class); - assertEquals(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((java.sql.Timestamp) result), "2011-12-11 12:24:12"); + assertEquals( + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((java.sql.Timestamp) result), + "2011-12-11 12:24:12"); - result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11T12:24:12.047", java.time.LocalDateTime.class); - assertEquals(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format((java.time.LocalDateTime) result), "2011-12-11 12:24:12"); + result = + CompatibleTypeUtils.compatibleTypeConvert("2011-12-11T12:24:12.047", java.time.LocalDateTime.class); + assertEquals( + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format((java.time.LocalDateTime) result), + "2011-12-11 12:24:12"); result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11T12:24:12.047", java.time.LocalTime.class); assertEquals(DateTimeFormatter.ofPattern("HH:mm:ss").format((java.time.LocalTime) result), "12:24:12"); @@ -154,7 +159,7 @@ class CompatibleTypeUtilsTest { set.add("a"); set.add("b"); - String[] array = new String[]{"a", "b"}; + String[] array = new String[] {"a", "b"}; result = CompatibleTypeUtils.compatibleTypeConvert(array, List.class); assertEquals(ArrayList.class, result.getClass()); @@ -215,8 +220,6 @@ class CompatibleTypeUtilsTest { assertEquals(2, ((String[]) result).length); assertTrue(((String[]) result)[0].equals("a")); assertTrue(((String[]) result)[1].equals("b")); - } - } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ConcurrentHashMapUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ConcurrentHashMapUtilsTest.java index 66c1ae462d..45ce4e1b09 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ConcurrentHashMapUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ConcurrentHashMapUtilsTest.java @@ -14,18 +14,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; +import java.util.concurrent.ConcurrentHashMap; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledForJreRange; -import java.util.concurrent.ConcurrentHashMap; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; - class ConcurrentHashMapUtilsTest { @Test @@ -42,14 +40,14 @@ class ConcurrentHashMapUtilsTest { @Test @EnabledForJreRange(max = org.junit.jupiter.api.condition.JRE.JAVA_8) - public void issue11986ForJava8Test(){ + public void issue11986ForJava8Test() { // https://github.com/apache/dubbo/issues/11986 - final ConcurrentHashMap map=new ConcurrentHashMap<>(); + final ConcurrentHashMap map = new ConcurrentHashMap<>(); // // map.computeIfAbsent("AaAa", key->map.computeIfAbsent("BBBB",key2->42)); // In JDK8,for the bug of JDK-8161372,may cause dead cycle when use computeIfAbsent // ConcurrentHashMapUtils.computeIfAbsent method to resolve this bug - ConcurrentHashMapUtils.computeIfAbsent(map, "AaAa", key->map.computeIfAbsent("BBBB",key2->42)); + ConcurrentHashMapUtils.computeIfAbsent(map, "AaAa", key -> map.computeIfAbsent("BBBB", key2 -> 42)); assertEquals(2, map.size()); assertEquals(Integer.valueOf(42), map.get("AaAa")); assertEquals(Integer.valueOf(42), map.get("BBBB")); @@ -57,13 +55,13 @@ class ConcurrentHashMapUtilsTest { @Test @EnabledForJreRange(min = org.junit.jupiter.api.condition.JRE.JAVA_9) - public void issue11986ForJava17Test(){ + public void issue11986ForJava17Test() { // https://github.com/apache/dubbo/issues/11986 - final ConcurrentHashMap map=new ConcurrentHashMap<>(); + final ConcurrentHashMap map = new ConcurrentHashMap<>(); // JDK9+ has been resolved JDK-8161372 bug, when cause dead then throw IllegalStateException - assertThrows(IllegalStateException.class, ()->{ - ConcurrentHashMapUtils.computeIfAbsent(map, "AaAa", key->map.computeIfAbsent("BBBB",key2->42)); + assertThrows(IllegalStateException.class, () -> { + ConcurrentHashMapUtils.computeIfAbsent(map, "AaAa", key -> map.computeIfAbsent("BBBB", key2 -> 42)); }); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ConfigUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ConfigUtilsTest.java index b63aa5322e..8905610b80 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ConfigUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ConfigUtilsTest.java @@ -22,18 +22,18 @@ import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.threadpool.ThreadPool; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -44,15 +44,14 @@ import static org.junit.jupiter.api.Assertions.assertEquals; class ConfigUtilsTest { private Properties properties; - + @BeforeEach public void setUp() throws Exception { properties = ConfigUtils.getProperties(Collections.emptySet()); } @AfterEach - public void tearDown() throws Exception { - } + public void tearDown() throws Exception {} @Test void testIsNotEmpty() throws Exception { @@ -82,27 +81,41 @@ class ConfigUtilsTest { @Test void testMergeValues() { - List merged = ConfigUtils.mergeValues(ApplicationModel.defaultModel().getExtensionDirector(), ThreadPool.class, "aaa,bbb,default.custom", + List merged = ConfigUtils.mergeValues( + ApplicationModel.defaultModel().getExtensionDirector(), + ThreadPool.class, + "aaa,bbb,default.custom", asList("fixed", "default.limited", "cached")); assertEquals(asList("fixed", "cached", "aaa", "bbb", "default.custom"), merged); } @Test void testMergeValuesAddDefault() { - List merged = ConfigUtils.mergeValues(ApplicationModel.defaultModel().getExtensionDirector(), ThreadPool.class, "aaa,bbb,default,zzz", + List merged = ConfigUtils.mergeValues( + ApplicationModel.defaultModel().getExtensionDirector(), + ThreadPool.class, + "aaa,bbb,default,zzz", asList("fixed", "default.limited", "cached")); assertEquals(asList("aaa", "bbb", "fixed", "cached", "zzz"), merged); } @Test void testMergeValuesDeleteDefault() { - List merged = ConfigUtils.mergeValues(ApplicationModel.defaultModel().getExtensionDirector(), ThreadPool.class, "-default", asList("fixed", "default.limited", "cached")); + List merged = ConfigUtils.mergeValues( + ApplicationModel.defaultModel().getExtensionDirector(), + ThreadPool.class, + "-default", + asList("fixed", "default.limited", "cached")); assertEquals(Collections.emptyList(), merged); } @Test void testMergeValuesDeleteDefault_2() { - List merged = ConfigUtils.mergeValues(ApplicationModel.defaultModel().getExtensionDirector(), ThreadPool.class, "-default,aaa", asList("fixed", "default.limited", "cached")); + List merged = ConfigUtils.mergeValues( + ApplicationModel.defaultModel().getExtensionDirector(), + ThreadPool.class, + "-default,aaa", + asList("fixed", "default.limited", "cached")); assertEquals(asList("aaa"), merged); } @@ -111,14 +124,18 @@ class ConfigUtilsTest { */ @Test void testMergeValuesDelete() { - List merged = ConfigUtils.mergeValues(ApplicationModel.defaultModel().getExtensionDirector(), ThreadPool.class, "-fixed,aaa", asList("fixed", "default.limited", "cached")); + List merged = ConfigUtils.mergeValues( + ApplicationModel.defaultModel().getExtensionDirector(), + ThreadPool.class, + "-fixed,aaa", + asList("fixed", "default.limited", "cached")); assertEquals(asList("cached", "aaa"), merged); } @Test void testReplaceProperty() throws Exception { String s = ConfigUtils.replaceProperty("1${a.b.c}2${a.b.c}3", Collections.singletonMap("a.b.c", "ABC")); - assertEquals( "1ABC2ABC3", s); + assertEquals("1ABC2ABC3", s); s = ConfigUtils.replaceProperty("1${a.b.c}2${a.b.c}3", Collections.emptyMap()); assertEquals("1${a.b.c}2${a.b.c}3", s); } @@ -136,7 +153,8 @@ class ConfigUtilsTest { compositeConfiguration.addConfiguration(configuration1); compositeConfiguration.addConfiguration(configuration2); - String s = ConfigUtils.replaceProperty("zookeeper://${zookeeper.address}:${zookeeper.port}", compositeConfiguration); + String s = ConfigUtils.replaceProperty( + "zookeeper://${zookeeper.address}:${zookeeper.port}", compositeConfiguration); assertEquals("zookeeper://127.0.0.1:2181", s); // should not replace inner class name @@ -198,7 +216,7 @@ class ConfigUtilsTest { @Test void testLoadProperties() throws Exception { Properties p = ConfigUtils.loadProperties(Collections.emptySet(), "dubbo.properties"); - assertThat((String)p.get("dubbo"), equalTo("properties")); + assertThat((String) p.get("dubbo"), equalTo("properties")); } @Test @@ -227,7 +245,8 @@ class ConfigUtilsTest { @Test void testLoadPropertiesOneFileNotRootPath() throws Exception { - Properties p = ConfigUtils.loadProperties(Collections.emptySet(), "META-INF/dubbo/internal/org.apache.dubbo.common.threadpool.ThreadPool", false); + Properties p = ConfigUtils.loadProperties( + Collections.emptySet(), "META-INF/dubbo/internal/org.apache.dubbo.common.threadpool.ThreadPool", false); Properties expected = new Properties(); expected.put("fixed", "org.apache.dubbo.common.threadpool.support.fixed.FixedThreadPool"); @@ -238,22 +257,26 @@ class ConfigUtilsTest { assertEquals(expected, p); } - @Disabled("Not know why disabled, the original link explaining this was reachable.") @Test void testLoadPropertiesMultiFileNotRootPathException() throws Exception { try { - ConfigUtils.loadProperties(Collections.emptySet(), "META-INF/services/org.apache.dubbo.common.status.StatusChecker", false); + ConfigUtils.loadProperties( + Collections.emptySet(), "META-INF/services/org.apache.dubbo.common.status.StatusChecker", false); Assertions.fail(); } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("only 1 META-INF/services/org.apache.dubbo.common.status.StatusChecker file is expected, but 2 dubbo.properties files found on class path:")); + assertThat( + expected.getMessage(), + containsString( + "only 1 META-INF/services/org.apache.dubbo.common.status.StatusChecker file is expected, but 2 dubbo.properties files found on class path:")); } } @Test void testLoadPropertiesMultiFileNotRootPath() throws Exception { - Properties p = ConfigUtils.loadProperties(Collections.emptySet(), "META-INF/dubbo/internal/org.apache.dubbo.common.status.StatusChecker", true); + Properties p = ConfigUtils.loadProperties( + Collections.emptySet(), "META-INF/dubbo/internal/org.apache.dubbo.common.status.StatusChecker", true); Properties expected = new Properties(); expected.put("memory", "org.apache.dubbo.common.status.support.MemoryStatusChecker"); @@ -285,4 +308,4 @@ class ConfigUtilsTest { String rule = ConfigUtils.loadMigrationRule(classLoaderSet, "dubbo-migration.yaml"); Assertions.assertNotNull(rule); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/DefaultPageTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/DefaultPageTest.java index 72b30db554..596164adc5 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/DefaultPageTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/DefaultPageTest.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.common.utils; +import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.List; - import static java.util.Arrays.asList; /** @@ -41,4 +41,4 @@ class DefaultPageTest { Assertions.assertEquals(page.getTotalPages(), 5); Assertions.assertTrue(page.hasNext()); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/DefaultSerializeClassCheckerTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/DefaultSerializeClassCheckerTest.java index 6998ef010c..29d116b7d6 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/DefaultSerializeClassCheckerTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/DefaultSerializeClassCheckerTest.java @@ -16,12 +16,13 @@ */ package org.apache.dubbo.common.utils; +import org.apache.dubbo.common.constants.CommonConstants; +import org.apache.dubbo.rpc.model.FrameworkModel; + import java.net.Socket; import java.util.LinkedList; import java.util.concurrent.locks.ReentrantReadWriteLock; -import org.apache.dubbo.common.constants.CommonConstants; -import org.apache.dubbo.rpc.model.FrameworkModel; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -41,31 +42,46 @@ class DefaultSerializeClassCheckerTest { @Test void testCommon() throws ClassNotFoundException { - FrameworkModel.defaultModel().getBeanFactory().getBean(SerializeSecurityManager.class).setCheckStatus(SerializeCheckStatus.WARN); + FrameworkModel.defaultModel() + .getBeanFactory() + .getBean(SerializeSecurityManager.class) + .setCheckStatus(SerializeCheckStatus.WARN); DefaultSerializeClassChecker defaultSerializeClassChecker = DefaultSerializeClassChecker.getInstance(); for (int i = 0; i < 10; i++) { - defaultSerializeClassChecker.loadClass(Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.ReadLock.class.getName()); - defaultSerializeClassChecker.loadClass(Thread.currentThread().getContextClassLoader(), LinkedList.class.getName()); - defaultSerializeClassChecker.loadClass(Thread.currentThread().getContextClassLoader(), Integer.class.getName()); + defaultSerializeClassChecker.loadClass( + Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.ReadLock.class.getName()); + defaultSerializeClassChecker.loadClass( + Thread.currentThread().getContextClassLoader(), LinkedList.class.getName()); + defaultSerializeClassChecker.loadClass( + Thread.currentThread().getContextClassLoader(), Integer.class.getName()); defaultSerializeClassChecker.loadClass(Thread.currentThread().getContextClassLoader(), int.class.getName()); } Assertions.assertThrows(IllegalArgumentException.class, () -> { - defaultSerializeClassChecker.loadClass(Thread.currentThread().getContextClassLoader(), Socket.class.getName()); + defaultSerializeClassChecker.loadClass( + Thread.currentThread().getContextClassLoader(), Socket.class.getName()); }); - Assertions.assertTrue(FrameworkModel.defaultModel().getBeanFactory().getBean(SerializeSecurityManager.class) - .getWarnedClasses().contains(Socket.class.getName())); + Assertions.assertTrue(FrameworkModel.defaultModel() + .getBeanFactory() + .getBean(SerializeSecurityManager.class) + .getWarnedClasses() + .contains(Socket.class.getName())); } @Test void testAddAllow() throws ClassNotFoundException { - System.setProperty(CommonConstants.CLASS_DESERIALIZE_ALLOWED_LIST, ReentrantReadWriteLock.WriteLock.class.getName() + "," + ReentrantReadWriteLock.ReadLock.class.getName()); + System.setProperty( + CommonConstants.CLASS_DESERIALIZE_ALLOWED_LIST, + ReentrantReadWriteLock.WriteLock.class.getName() + "," + + ReentrantReadWriteLock.ReadLock.class.getName()); DefaultSerializeClassChecker defaultSerializeClassChecker = DefaultSerializeClassChecker.getInstance(); for (int i = 0; i < 10; i++) { - defaultSerializeClassChecker.loadClass(Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.WriteLock.class.getName()); - defaultSerializeClassChecker.loadClass(Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.ReadLock.class.getName()); + defaultSerializeClassChecker.loadClass( + Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.WriteLock.class.getName()); + defaultSerializeClassChecker.loadClass( + Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.ReadLock.class.getName()); } System.clearProperty(CommonConstants.CLASS_DESERIALIZE_ALLOWED_LIST); @@ -73,20 +89,29 @@ class DefaultSerializeClassCheckerTest { @Test void testAddBlock() { - System.setProperty(CommonConstants.CLASS_DESERIALIZE_BLOCKED_LIST, Runtime.class.getName() + "," + Thread.class.getName()); + System.setProperty( + CommonConstants.CLASS_DESERIALIZE_BLOCKED_LIST, Runtime.class.getName() + "," + Thread.class.getName()); DefaultSerializeClassChecker defaultSerializeClassChecker = DefaultSerializeClassChecker.getInstance(); for (int i = 0; i < 10; i++) { Assertions.assertThrows(IllegalArgumentException.class, () -> { - defaultSerializeClassChecker.loadClass(Thread.currentThread().getContextClassLoader(), Runtime.class.getName()); + defaultSerializeClassChecker.loadClass( + Thread.currentThread().getContextClassLoader(), Runtime.class.getName()); }); - Assertions.assertTrue(FrameworkModel.defaultModel().getBeanFactory().getBean(SerializeSecurityManager.class) - .getWarnedClasses().contains(Runtime.class.getName())); + Assertions.assertTrue(FrameworkModel.defaultModel() + .getBeanFactory() + .getBean(SerializeSecurityManager.class) + .getWarnedClasses() + .contains(Runtime.class.getName())); Assertions.assertThrows(IllegalArgumentException.class, () -> { - defaultSerializeClassChecker.loadClass(Thread.currentThread().getContextClassLoader(), Thread.class.getName()); + defaultSerializeClassChecker.loadClass( + Thread.currentThread().getContextClassLoader(), Thread.class.getName()); }); - Assertions.assertTrue(FrameworkModel.defaultModel().getBeanFactory().getBean(SerializeSecurityManager.class) - .getWarnedClasses().contains(Thread.class.getName())); + Assertions.assertTrue(FrameworkModel.defaultModel() + .getBeanFactory() + .getBean(SerializeSecurityManager.class) + .getWarnedClasses() + .contains(Thread.class.getName())); } System.clearProperty(CommonConstants.CLASS_DESERIALIZE_BLOCKED_LIST); @@ -95,16 +120,23 @@ class DefaultSerializeClassCheckerTest { @Test void testBlockAll() throws ClassNotFoundException { System.setProperty(CommonConstants.CLASS_DESERIALIZE_BLOCK_ALL, "true"); - System.setProperty(CommonConstants.CLASS_DESERIALIZE_ALLOWED_LIST, ReentrantReadWriteLock.WriteLock.class.getName()); + System.setProperty( + CommonConstants.CLASS_DESERIALIZE_ALLOWED_LIST, ReentrantReadWriteLock.WriteLock.class.getName()); DefaultSerializeClassChecker defaultSerializeClassChecker = DefaultSerializeClassChecker.getInstance(); for (int i = 0; i < 10; i++) { - defaultSerializeClassChecker.loadClass(Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.WriteLock.class.getName()); + defaultSerializeClassChecker.loadClass( + Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.WriteLock.class.getName()); Assertions.assertThrows(IllegalArgumentException.class, () -> { - defaultSerializeClassChecker.loadClass(Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.ReadLock.class.getName()); + defaultSerializeClassChecker.loadClass( + Thread.currentThread().getContextClassLoader(), + ReentrantReadWriteLock.ReadLock.class.getName()); }); - Assertions.assertTrue(FrameworkModel.defaultModel().getBeanFactory().getBean(SerializeSecurityManager.class) - .getWarnedClasses().contains(ReentrantReadWriteLock.ReadLock.class.getName())); + Assertions.assertTrue(FrameworkModel.defaultModel() + .getBeanFactory() + .getBean(SerializeSecurityManager.class) + .getWarnedClasses() + .contains(ReentrantReadWriteLock.ReadLock.class.getName())); } System.clearProperty(CommonConstants.CLASS_DESERIALIZE_BLOCK_ALL); @@ -118,17 +150,30 @@ class DefaultSerializeClassCheckerTest { ssm.setCheckStatus(SerializeCheckStatus.STRICT); DefaultSerializeClassChecker defaultSerializeClassChecker = DefaultSerializeClassChecker.getInstance(); - Assertions.assertEquals(Integer.class, defaultSerializeClassChecker.loadClass(Thread.currentThread().getContextClassLoader(), Integer.class.getName())); + Assertions.assertEquals( + Integer.class, + defaultSerializeClassChecker.loadClass( + Thread.currentThread().getContextClassLoader(), Integer.class.getName())); Assertions.assertThrows(IllegalArgumentException.class, () -> { - defaultSerializeClassChecker.loadClass(Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.class.getName()); + defaultSerializeClassChecker.loadClass( + Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.class.getName()); }); - Assertions.assertTrue(FrameworkModel.defaultModel().getBeanFactory().getBean(SerializeSecurityManager.class) - .getWarnedClasses().contains(ReentrantReadWriteLock.class.getName())); + Assertions.assertTrue(FrameworkModel.defaultModel() + .getBeanFactory() + .getBean(SerializeSecurityManager.class) + .getWarnedClasses() + .contains(ReentrantReadWriteLock.class.getName())); ssm.setCheckStatus(SerializeCheckStatus.WARN); - Assertions.assertEquals(ReentrantReadWriteLock.class, defaultSerializeClassChecker.loadClass(Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.class.getName())); + Assertions.assertEquals( + ReentrantReadWriteLock.class, + defaultSerializeClassChecker.loadClass( + Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.class.getName())); ssm.setCheckStatus(SerializeCheckStatus.DISABLE); - Assertions.assertEquals(ReentrantReadWriteLock.class, defaultSerializeClassChecker.loadClass(Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.class.getName())); + Assertions.assertEquals( + ReentrantReadWriteLock.class, + defaultSerializeClassChecker.loadClass( + Thread.currentThread().getContextClassLoader(), ReentrantReadWriteLock.class.getName())); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/DubboAppenderTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/DubboAppenderTest.java index 4528f9ad7e..8b4d6c4f44 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/DubboAppenderTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/DubboAppenderTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; import org.apache.log4j.Category; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ExecutorUtilTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ExecutorUtilTest.java index 4aa272b7e6..8924f78c1a 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ExecutorUtilTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ExecutorUtilTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,19 +14,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.url.component.ServiceConfigURL; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; import static org.awaitility.Awaitility.await; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/FieldUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/FieldUtilsTest.java index 8266e70521..a9a452d032 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/FieldUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/FieldUtilsTest.java @@ -73,16 +73,14 @@ class FieldUtilsTest { class A { private String a = "a"; - } class B extends A { private String b = "b"; - } class C extends B { private String c = "c"; -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/HolderTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/HolderTest.java index d6fc36bcb6..653c939cad 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/HolderTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/HolderTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; import org.junit.jupiter.api.Test; @@ -30,4 +29,4 @@ class HolderTest { holder.set(message); assertThat(holder.get(), is(message)); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/IOUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/IOUtilsTest.java index c23d3b2427..1e05c07c9d 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/IOUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/IOUtilsTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,15 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -35,6 +28,11 @@ import java.io.Writer; import java.nio.charset.StandardCharsets; import java.nio.file.Path; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -90,7 +88,7 @@ class IOUtilsTest { @Test void testLines(@TempDir Path tmpDir) throws Exception { File file = tmpDir.getFileName().toAbsolutePath().toFile(); - IOUtils.writeLines(file, new String[]{TEXT}); + IOUtils.writeLines(file, new String[] {TEXT}); String[] lines = IOUtils.readLines(file); assertThat(lines.length, equalTo(1)); assertThat(lines[0], equalTo(TEXT)); @@ -106,7 +104,7 @@ class IOUtilsTest { @Test void testWriteLines() throws Exception { - IOUtils.writeLines(os, new String[]{TEXT}); + IOUtils.writeLines(os, new String[] {TEXT}); ByteArrayOutputStream bos = (ByteArrayOutputStream) os; assertThat(new String(bos.toByteArray()), equalTo(TEXT + System.lineSeparator())); } @@ -119,7 +117,7 @@ class IOUtilsTest { @Test void testAppendLines(@TempDir Path tmpDir) throws Exception { File file = tmpDir.getFileName().toAbsolutePath().toFile(); - IOUtils.appendLines(file, new String[]{"a", "b", "c"}); + IOUtils.appendLines(file, new String[] {"a", "b", "c"}); String[] lines = IOUtils.readLines(file); assertThat(lines.length, equalTo(3)); assertThat(lines[0], equalTo("a")); @@ -127,4 +125,4 @@ class IOUtilsTest { assertThat(lines[2], equalTo("c")); tmpDir.getFileName().toAbsolutePath().toFile().delete(); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JRETest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JRETest.java index ec5f34b1c0..a42e1ae368 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JRETest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JRETest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,16 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; +import javax.lang.model.SourceVersion; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import javax.lang.model.SourceVersion; - - class JRETest { @Test @@ -38,7 +36,8 @@ class JRETest { void testCurrentVersion() { // SourceVersion is an enum, which member name is RELEASE_XX. - Assertions.assertEquals(SourceVersion.latest().name().split("_")[1], - JRE.currentVersion().name().split("_")[1]); + Assertions.assertEquals( + SourceVersion.latest().name().split("_")[1], + JRE.currentVersion().name().split("_")[1]); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JVMUtilTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JVMUtilTest.java index 5276dabf70..93813108bb 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JVMUtilTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JVMUtilTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,8 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; -class JVMUtilTest { -} \ No newline at end of file +class JVMUtilTest {} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JsonCompatibilityUtilTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JsonCompatibilityUtilTest.java index 965f73f9d2..820abef1e5 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JsonCompatibilityUtilTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JsonCompatibilityUtilTest.java @@ -18,12 +18,12 @@ package org.apache.dubbo.common.utils; import org.apache.dubbo.common.utils.json.Service; +import java.util.List; + import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.List; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -107,7 +107,6 @@ public class JsonCompatibilityUtilTest { assertTrue(res); } - @Test public void testByte() throws NoSuchMethodException { boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testByte")); @@ -120,7 +119,6 @@ public class JsonCompatibilityUtilTest { assertTrue(res); } - @Test public void testBByte() throws NoSuchMethodException { boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testBByte")); @@ -139,7 +137,6 @@ public class JsonCompatibilityUtilTest { assertTrue(res); } - @Test public void testFloat() throws NoSuchMethodException { boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testFloat")); @@ -158,14 +155,12 @@ public class JsonCompatibilityUtilTest { assertTrue(res); } - @Test public void testFloatArray() throws NoSuchMethodException { boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testFloatArray")); assertTrue(res); } - @Test public void testFloatList() throws NoSuchMethodException { boolean res = JsonCompatibilityUtil.checkMethodCompatibility(service.getDeclaredMethod("testFloatList")); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JsonUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JsonUtilsTest.java index 4cdfa212d9..0988992894 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JsonUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/JsonUtilsTest.java @@ -25,12 +25,6 @@ import org.apache.dubbo.common.utils.json.TestEnum; import org.apache.dubbo.common.utils.json.TestObjectA; import org.apache.dubbo.common.utils.json.TestObjectB; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.mockito.MockedConstruction; -import org.mockito.Mockito; - import java.lang.reflect.Field; import java.util.Collections; import java.util.HashMap; @@ -39,6 +33,12 @@ import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.MockedConstruction; +import org.mockito.Mockito; + class JsonUtilsTest { private AtomicBoolean allowFastjson2 = new AtomicBoolean(true); private AtomicBoolean allowFastjson = new AtomicBoolean(true); @@ -74,14 +74,16 @@ class JsonUtilsTest { map.put("a", "a"); Assertions.assertEquals("{\"a\":\"a\"}", JsonUtils.getJson().toJson(map)); Assertions.assertEquals(map, JsonUtils.getJson().toJavaObject("{\"a\":\"a\"}", Map.class)); - Assertions.assertEquals(Collections.singletonList(map), JsonUtils.getJson().toJavaList("[{\"a\":\"a\"}]", Map.class)); + Assertions.assertEquals( + Collections.singletonList(map), JsonUtils.getJson().toJavaList("[{\"a\":\"a\"}]", Map.class)); // prefer use fastjson2 setJson(null); System.setProperty("dubbo.json-framework.prefer", "fastjson2"); Assertions.assertEquals("{\"a\":\"a\"}", JsonUtils.getJson().toJson(map)); Assertions.assertEquals(map, JsonUtils.getJson().toJavaObject("{\"a\":\"a\"}", Map.class)); - Assertions.assertEquals(Collections.singletonList(map), JsonUtils.getJson().toJavaList("[{\"a\":\"a\"}]", Map.class)); + Assertions.assertEquals( + Collections.singletonList(map), JsonUtils.getJson().toJavaList("[{\"a\":\"a\"}]", Map.class)); System.clearProperty("dubbo.json-framework.prefer"); // prefer use fastjson @@ -89,7 +91,8 @@ class JsonUtilsTest { System.setProperty("dubbo.json-framework.prefer", "fastjson"); Assertions.assertEquals("{\"a\":\"a\"}", JsonUtils.getJson().toJson(map)); Assertions.assertEquals(map, JsonUtils.getJson().toJavaObject("{\"a\":\"a\"}", Map.class)); - Assertions.assertEquals(Collections.singletonList(map), JsonUtils.getJson().toJavaList("[{\"a\":\"a\"}]", Map.class)); + Assertions.assertEquals( + Collections.singletonList(map), JsonUtils.getJson().toJavaList("[{\"a\":\"a\"}]", Map.class)); System.clearProperty("dubbo.json-framework.prefer"); // prefer use gson @@ -97,7 +100,8 @@ class JsonUtilsTest { System.setProperty("dubbo.json-framework.prefer", "gson"); Assertions.assertEquals("{\"a\":\"a\"}", JsonUtils.getJson().toJson(map)); Assertions.assertEquals(map, JsonUtils.getJson().toJavaObject("{\"a\":\"a\"}", Map.class)); - Assertions.assertEquals(Collections.singletonList(map), JsonUtils.getJson().toJavaList("[{\"a\":\"a\"}]", Map.class)); + Assertions.assertEquals( + Collections.singletonList(map), JsonUtils.getJson().toJavaList("[{\"a\":\"a\"}]", Map.class)); System.clearProperty("dubbo.json-framework.prefer"); // prefer use jackson @@ -105,7 +109,8 @@ class JsonUtilsTest { System.setProperty("dubbo.json-framework.prefer", "jackson"); Assertions.assertEquals("{\"a\":\"a\"}", JsonUtils.getJson().toJson(map)); Assertions.assertEquals(map, JsonUtils.getJson().toJavaObject("{\"a\":\"a\"}", Map.class)); - Assertions.assertEquals(Collections.singletonList(map), JsonUtils.getJson().toJavaList("[{\"a\":\"a\"}]", Map.class)); + Assertions.assertEquals( + Collections.singletonList(map), JsonUtils.getJson().toJavaList("[{\"a\":\"a\"}]", Map.class)); System.clearProperty("dubbo.json-framework.prefer"); setJson(null); @@ -210,14 +215,14 @@ class JsonUtilsTest { @Test void testGetJson2() { - fastjson2Mock = Mockito.mockConstruction(FastJson2Impl.class, - (mock, context) -> Mockito.when(mock.isSupport()).thenAnswer(invocation -> allowFastjson2.get())); - fastjsonMock = Mockito.mockConstruction(FastJsonImpl.class, - (mock, context) -> Mockito.when(mock.isSupport()).thenAnswer(invocation -> allowFastjson.get())); - gsonMock = Mockito.mockConstruction(GsonImpl.class, - (mock, context) -> Mockito.when(mock.isSupport()).thenAnswer(invocation -> allowGson.get())); - jacksonMock = Mockito.mockConstruction(JacksonImpl.class, - (mock, context) -> Mockito.when(mock.isSupport()).thenAnswer(invocation -> allowJackson.get())); + fastjson2Mock = Mockito.mockConstruction(FastJson2Impl.class, (mock, context) -> Mockito.when(mock.isSupport()) + .thenAnswer(invocation -> allowFastjson2.get())); + fastjsonMock = Mockito.mockConstruction(FastJsonImpl.class, (mock, context) -> Mockito.when(mock.isSupport()) + .thenAnswer(invocation -> allowFastjson.get())); + gsonMock = Mockito.mockConstruction(GsonImpl.class, (mock, context) -> Mockito.when(mock.isSupport()) + .thenAnswer(invocation -> allowGson.get())); + jacksonMock = Mockito.mockConstruction(JacksonImpl.class, (mock, context) -> Mockito.when(mock.isSupport()) + .thenAnswer(invocation -> allowJackson.get())); // default use fastjson2 setJson(null); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LFUCacheTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LFUCacheTest.java index 9dbf00c6d8..1bfd51d62d 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LFUCacheTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LFUCacheTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -19,8 +19,6 @@ package org.apache.dubbo.common.utils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.io.IOException; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LRU2CacheTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LRU2CacheTest.java index 8d03fe30a6..04fe0f94ed 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LRU2CacheTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LRU2CacheTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; import org.junit.jupiter.api.Test; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LogHelperTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LogHelperTest.java index a5fef528e9..cbd4bcdad4 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LogHelperTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LogHelperTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; import org.apache.dubbo.common.logger.Logger; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LogTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LogTest.java index 0dfede0887..391312dab3 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LogTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LogTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; import org.apache.log4j.Level; @@ -81,5 +80,4 @@ class LogTest { Assertions.assertEquals(log1.hashCode(), log2.hashCode()); Assertions.assertNotEquals(log1, log3); } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LogUtilTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LogUtilTest.java index 7183ffd998..e88e866956 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LogUtilTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/LogUtilTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; import org.apache.log4j.Level; @@ -109,5 +108,4 @@ class LogUtilTest { when(log.getLogLevel()).thenReturn(Level.INFO); assertThat(LogUtil.findMessage(Level.ERROR, "message"), equalTo(1)); } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MD5UtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MD5UtilsTest.java index d5a0a46d0d..f69b82c910 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MD5UtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MD5UtilsTest.java @@ -16,9 +16,6 @@ */ package org.apache.dubbo.common.utils; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -27,13 +24,18 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class MD5UtilsTest { @Test void test() { MD5Utils sharedMd5Utils = new MD5Utils(); - final String[] input = {"provider-appgroup-one/org.apache.dubbo.config.spring.api.HelloService:dubboorg.apache.dubbo.config.spring.api.HelloService{REGISTRY_CLUSTER=registry-one, anyhost=true, application=provider-app, background=false, compiler=javassist, deprecated=false, dubbo=2.0.2, dynamic=true, file.cache=false, generic=false, group=group-one, interface=org.apache.dubbo.config.spring.api.HelloService, logger=slf4j, metadata-type=remote, methods=sayHello, organization=test, owner=com.test, release=, service-name-mapping=true, side=provider}", - "provider-appgroup-two/org.apache.dubbo.config.spring.api.DemoService:dubboorg.apache.dubbo.config.spring.api.DemoService{REGISTRY_CLUSTER=registry-two, anyhost=true, application=provider-app, background=false, compiler=javassist, deprecated=false, dubbo=2.0.2, dynamic=true, file.cache=false, generic=false, group=group-two, interface=org.apache.dubbo.config.spring.api.DemoService, logger=slf4j, metadata-type=remote, methods=sayName,getBox, organization=test, owner=com.test, release=, service-name-mapping=true, side=provider}"}; + final String[] input = { + "provider-appgroup-one/org.apache.dubbo.config.spring.api.HelloService:dubboorg.apache.dubbo.config.spring.api.HelloService{REGISTRY_CLUSTER=registry-one, anyhost=true, application=provider-app, background=false, compiler=javassist, deprecated=false, dubbo=2.0.2, dynamic=true, file.cache=false, generic=false, group=group-one, interface=org.apache.dubbo.config.spring.api.HelloService, logger=slf4j, metadata-type=remote, methods=sayHello, organization=test, owner=com.test, release=, service-name-mapping=true, side=provider}", + "provider-appgroup-two/org.apache.dubbo.config.spring.api.DemoService:dubboorg.apache.dubbo.config.spring.api.DemoService{REGISTRY_CLUSTER=registry-two, anyhost=true, application=provider-app, background=false, compiler=javassist, deprecated=false, dubbo=2.0.2, dynamic=true, file.cache=false, generic=false, group=group-two, interface=org.apache.dubbo.config.spring.api.DemoService, logger=slf4j, metadata-type=remote, methods=sayName,getBox, organization=test, owner=com.test, release=, service-name-mapping=true, side=provider}" + }; final String[] result = {sharedMd5Utils.getMd5(input[0]), new MD5Utils().getMd5(input[1])}; System.out.println("Expected result: " + Arrays.asList(result)); @@ -65,7 +67,12 @@ class MD5UtilsTest { private final CountDownLatch latch; private final List errorCollector; - public Md5Task(String input, String expected, MD5Utils md5Utils, CountDownLatch latch, List errorCollector) { + public Md5Task( + String input, + String expected, + MD5Utils md5Utils, + CountDownLatch latch, + List errorCollector) { this.input = input; this.expected = expected; this.md5Utils = md5Utils; @@ -92,4 +99,4 @@ class MD5UtilsTest { } } } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MemberUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MemberUtilsTest.java index 6b6b45109a..13bcd79912 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MemberUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MemberUtilsTest.java @@ -40,19 +40,11 @@ class MemberUtilsTest { assertTrue(isPublic(getClass().getMethod("publicMethod"))); } - public void noStatic() { + public void noStatic() {} - } + public static void staticMethod() {} - public static void staticMethod() { + private void privateMethod() {} - } - - private void privateMethod() { - - } - - public void publicMethod() { - - } + public void publicMethod() {} } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MethodUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MethodUtilsTest.java index b986c3d662..702306d3ae 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MethodUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MethodUtilsTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -16,11 +16,11 @@ */ package org.apache.dubbo.common.utils; +import java.lang.reflect.Method; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.lang.reflect.Method; - import static org.apache.dubbo.common.utils.MethodUtils.excludedDeclaredClass; import static org.apache.dubbo.common.utils.MethodUtils.findMethod; import static org.apache.dubbo.common.utils.MethodUtils.findNearestOverriddenMethod; @@ -77,7 +77,9 @@ class MethodUtilsTest { @Test void testGetMethods() throws NoSuchMethodException { - Assertions.assertTrue(getDeclaredMethods(MethodTestClazz.class, excludedDeclaredClass(String.class)).size() > 0); + Assertions.assertTrue(getDeclaredMethods(MethodTestClazz.class, excludedDeclaredClass(String.class)) + .size() + > 0); Assertions.assertTrue(getMethods(MethodTestClazz.class).size() > 0); Assertions.assertTrue(getAllDeclaredMethods(MethodTestClazz.class).size() > 0); Assertions.assertTrue(getAllMethods(MethodTestClazz.class).size() > 0); @@ -87,13 +89,14 @@ class MethodUtilsTest { invokeMethod(methodTestClazz, "setValue", "Test"); Assertions.assertEquals(methodTestClazz.getValue(), "Test"); - Assertions.assertTrue(overrides(MethodOverrideClazz.class.getMethod("get"), - MethodTestClazz.class.getMethod("get"))); - Assertions.assertEquals(findNearestOverriddenMethod(MethodOverrideClazz.class.getMethod("get")), + Assertions.assertTrue( + overrides(MethodOverrideClazz.class.getMethod("get"), MethodTestClazz.class.getMethod("get"))); + Assertions.assertEquals( + findNearestOverriddenMethod(MethodOverrideClazz.class.getMethod("get")), MethodTestClazz.class.getMethod("get")); - Assertions.assertEquals(findOverriddenMethod(MethodOverrideClazz.class.getMethod("get"), MethodOverrideClazz.class), + Assertions.assertEquals( + findOverriddenMethod(MethodOverrideClazz.class.getMethod("get"), MethodOverrideClazz.class), MethodTestClazz.class.getMethod("get")); - } @Test @@ -139,7 +142,6 @@ class MethodUtilsTest { public String isFieldName3() { return ""; } - } public class MethodTestClazz { @@ -169,5 +171,4 @@ class MethodUtilsTest { return this; } } - -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MyEnum.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MyEnum.java index 2d501e542d..d24950b5c4 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MyEnum.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/MyEnum.java @@ -20,7 +20,6 @@ package org.apache.dubbo.common.utils; * MyEnum */ public enum MyEnum { - - A, B - + A, + B } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NamedThreadFactoryTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NamedThreadFactoryTest.java index 57a0303134..5498a333cc 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NamedThreadFactoryTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NamedThreadFactoryTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,14 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; +import java.util.concurrent.atomic.AtomicInteger; + import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.concurrent.atomic.AtomicInteger; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsString; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NetUtilsInterfaceDisplayNameHasMetaCharactersTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NetUtilsInterfaceDisplayNameHasMetaCharactersTest.java index 4e835745ae..e35933531c 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NetUtilsInterfaceDisplayNameHasMetaCharactersTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NetUtilsInterfaceDisplayNameHasMetaCharactersTest.java @@ -16,15 +16,15 @@ */ package org.apache.dubbo.common.utils; -import org.junit.jupiter.api.Test; -import org.mockito.MockedStatic; -import org.mockito.Mockito; - import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Enumeration; import java.util.NoSuchElementException; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_NETWORK_IGNORED_INTERFACE; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -40,9 +40,10 @@ class NetUtilsInterfaceDisplayNameHasMetaCharactersTest { try (MockedStatic mockedStaticNetif = Mockito.mockStatic(NetworkInterface.class)) { NetworkInterface mockIgnoredNetif = Mockito.mock(NetworkInterface.class); NetworkInterface mockSelectedNetif = Mockito.mock(NetworkInterface.class); - NetworkInterface[] mockNetifs = { mockIgnoredNetif, mockSelectedNetif }; + NetworkInterface[] mockNetifs = {mockIgnoredNetif, mockSelectedNetif}; Enumeration mockEnumIfs = new Enumeration() { private int i = 0; + public NetworkInterface nextElement() { if (mockNetifs != null && i < mockNetifs.length) { NetworkInterface netif = mockNetifs[i++]; @@ -58,9 +59,10 @@ class NetUtilsInterfaceDisplayNameHasMetaCharactersTest { }; InetAddress mockSelectedAddr = Mockito.mock(InetAddress.class); - InetAddress[] mockAddrs = { mockSelectedAddr }; + InetAddress[] mockAddrs = {mockSelectedAddr}; Enumeration mockEnumAddrs = new Enumeration() { private int i = 0; + public InetAddress nextElement() { if (mockAddrs != null && i < mockAddrs.length) { InetAddress addr = mockAddrs[i++]; @@ -76,7 +78,11 @@ class NetUtilsInterfaceDisplayNameHasMetaCharactersTest { }; // mock static method getNetworkInterfaces - mockedStaticNetif.when(() -> { NetworkInterface.getNetworkInterfaces(); }).thenReturn(mockEnumIfs); + mockedStaticNetif + .when(() -> { + NetworkInterface.getNetworkInterfaces(); + }) + .thenReturn(mockEnumIfs); Mockito.when(mockIgnoredNetif.isUp()).thenReturn(true); Mockito.when(mockIgnoredNetif.getDisplayName()).thenReturn(IGNORED_DISPLAY_NAME_HAS_METACHARACTERS); @@ -98,16 +104,15 @@ class NetUtilsInterfaceDisplayNameHasMetaCharactersTest { } } - private String getIgnoredInterfaces(){ + private String getIgnoredInterfaces() { return System.getProperty(DUBBO_NETWORK_IGNORED_INTERFACE); } - private void setIgnoredInterfaces(String ignoredInterfaces){ - if(ignoredInterfaces!=null){ - System.setProperty(DUBBO_NETWORK_IGNORED_INTERFACE,ignoredInterfaces); - }else{ - System.setProperty(DUBBO_NETWORK_IGNORED_INTERFACE,""); + private void setIgnoredInterfaces(String ignoredInterfaces) { + if (ignoredInterfaces != null) { + System.setProperty(DUBBO_NETWORK_IGNORED_INTERFACE, ignoredInterfaces); + } else { + System.setProperty(DUBBO_NETWORK_IGNORED_INTERFACE, ""); } } - -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NetUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NetUtilsTest.java index f3856f0957..95eea9bca5 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NetUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/NetUtilsTest.java @@ -16,10 +16,6 @@ */ package org.apache.dubbo.common.utils; - -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -27,6 +23,9 @@ import java.net.NetworkInterface; import java.net.UnknownHostException; import java.util.regex.Pattern; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_NETWORK_IGNORED_INTERFACE; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -249,26 +248,25 @@ class NetUtilsTest { @Test void testMatchIpRangeMatchWhenIpv6Exception() { - IllegalArgumentException thrown = - assertThrows(IllegalArgumentException.class, () -> - NetUtils.matchIpRange("234e:0:4567::3d:*", "234e:0:4567::3d:ff", 90)); + IllegalArgumentException thrown = assertThrows( + IllegalArgumentException.class, + () -> NetUtils.matchIpRange("234e:0:4567::3d:*", "234e:0:4567::3d:ff", 90)); assertTrue(thrown.getMessage().contains("If you config ip expression that contains '*'")); - thrown = assertThrows(IllegalArgumentException.class, () -> - NetUtils.matchIpRange("234e:0:4567:3d", "234e:0:4567::3d:ff", 90)); + thrown = assertThrows( + IllegalArgumentException.class, + () -> NetUtils.matchIpRange("234e:0:4567:3d", "234e:0:4567::3d:ff", 90)); assertTrue(thrown.getMessage().contains("The host is ipv6, but the pattern is not ipv6 pattern")); - thrown = - assertThrows(IllegalArgumentException.class, () -> - NetUtils.matchIpRange("192.168.1.1-65-3", "192.168.1.63", 90)); + thrown = assertThrows( + IllegalArgumentException.class, () -> NetUtils.matchIpRange("192.168.1.1-65-3", "192.168.1.63", 90)); assertTrue(thrown.getMessage().contains("There is wrong format of ip Address")); } @Test void testMatchIpRangeMatchWhenIpWrongException() { - UnknownHostException thrown = - assertThrows(UnknownHostException.class, () -> - NetUtils.matchIpRange("192.168.1.63", "192.168.1.ff", 90)); + UnknownHostException thrown = assertThrows( + UnknownHostException.class, () -> NetUtils.matchIpRange("192.168.1.63", "192.168.1.ff", 90)); assertTrue(thrown.getMessage().contains("192.168.1.ff")); } @@ -293,8 +291,9 @@ class NetUtilsTest { @Test void testMatchIpv4WithIpPort() throws UnknownHostException { - NumberFormatException thrown = - assertThrows(NumberFormatException.class, () -> NetUtils.matchIpExpression("192.168.1.192/26:90", "192.168.1.199", 90)); + NumberFormatException thrown = assertThrows( + NumberFormatException.class, + () -> NetUtils.matchIpExpression("192.168.1.192/26:90", "192.168.1.199", 90)); assertTrue(thrown instanceof NumberFormatException); assertTrue(NetUtils.matchIpRange("*.*.*.*:90", "192.168.1.63", 90)); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/PojoUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/PojoUtilsTest.java index 2066142c11..67e3584e1b 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/PojoUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/PojoUtilsTest.java @@ -30,11 +30,6 @@ import org.apache.dubbo.common.model.person.PersonMap; import org.apache.dubbo.common.model.person.PersonStatus; import org.apache.dubbo.common.model.person.Phone; -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.Type; @@ -54,6 +49,11 @@ import java.util.Map; import java.util.Objects; import java.util.UUID; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.assertArrayEquals; @@ -170,51 +170,50 @@ class PojoUtilsTest { @Test void test_PrimitiveArray() throws Exception { - assertObject(new boolean[]{true, false}); - assertObject(new Boolean[]{true, false, true}); + assertObject(new boolean[] {true, false}); + assertObject(new Boolean[] {true, false, true}); - assertObject(new byte[]{1, 12, 28, 78}); - assertObject(new Byte[]{1, 12, 28, 78}); + assertObject(new byte[] {1, 12, 28, 78}); + assertObject(new Byte[] {1, 12, 28, 78}); - assertObject(new char[]{'a', '中', '无'}); - assertObject(new Character[]{'a', '中', '无'}); + assertObject(new char[] {'a', '中', '无'}); + assertObject(new Character[] {'a', '中', '无'}); - assertObject(new short[]{37, 39, 12}); - assertObject(new Short[]{37, 39, 12}); + assertObject(new short[] {37, 39, 12}); + assertObject(new Short[] {37, 39, 12}); - assertObject(new int[]{37, -39, 12456}); - assertObject(new Integer[]{37, -39, 12456}); + assertObject(new int[] {37, -39, 12456}); + assertObject(new Integer[] {37, -39, 12456}); - assertObject(new long[]{37L, -39L, 123456789L}); - assertObject(new Long[]{37L, -39L, 123456789L}); + assertObject(new long[] {37L, -39L, 123456789L}); + assertObject(new Long[] {37L, -39L, 123456789L}); - assertObject(new float[]{37F, -3.14F, 123456.7F}); - assertObject(new Float[]{37F, -39F, 123456.7F}); + assertObject(new float[] {37F, -3.14F, 123456.7F}); + assertObject(new Float[] {37F, -39F, 123456.7F}); - assertObject(new double[]{37D, -3.14D, 123456.7D}); - assertObject(new Double[]{37D, -39D, 123456.7D}); + assertObject(new double[] {37D, -3.14D, 123456.7D}); + assertObject(new Double[] {37D, -39D, 123456.7D}); + assertArrayObject(new Boolean[] {true, false, true}); - assertArrayObject(new Boolean[]{true, false, true}); + assertArrayObject(new Byte[] {1, 12, 28, 78}); - assertArrayObject(new Byte[]{1, 12, 28, 78}); + assertArrayObject(new Character[] {'a', '中', '无'}); - assertArrayObject(new Character[]{'a', '中', '无'}); + assertArrayObject(new Short[] {37, 39, 12}); - assertArrayObject(new Short[]{37, 39, 12}); + assertArrayObject(new Integer[] {37, -39, 12456}); - assertArrayObject(new Integer[]{37, -39, 12456}); + assertArrayObject(new Long[] {37L, -39L, 123456789L}); - assertArrayObject(new Long[]{37L, -39L, 123456789L}); + assertArrayObject(new Float[] {37F, -39F, 123456.7F}); - assertArrayObject(new Float[]{37F, -39F, 123456.7F}); + assertArrayObject(new Double[] {37D, -39D, 123456.7D}); - assertArrayObject(new Double[]{37D, -39D, 123456.7D}); + assertObject(new int[][] {{37, -39, 12456}}); + assertObject(new Integer[][][] {{{37, -39, 12456}}}); - assertObject(new int[][]{{37, -39, 12456}}); - assertObject(new Integer[][][]{{{37, -39, 12456}}}); - - assertArrayObject(new Integer[]{37, -39, 12456}); + assertArrayObject(new Integer[] {37, -39, 12456}); } @Test @@ -269,7 +268,7 @@ class PojoUtilsTest { @Test void testGeneralizeEnumArray() throws Exception { - Object days = new Enum[]{Day.FRIDAY, Day.SATURDAY}; + Object days = new Enum[] {Day.FRIDAY, Day.SATURDAY}; Object o = PojoUtils.generalize(days); assertTrue(o instanceof String[]); assertEquals(((String[]) o)[0], "FRIDAY"); @@ -278,7 +277,7 @@ class PojoUtilsTest { @Test void testGeneralizePersons() throws Exception { - Object persons = new Person[]{new Person(), new Person()}; + Object persons = new Person[] {new Person(), new Person()}; Object o = PojoUtils.generalize(persons); assertTrue(o instanceof Object[]); assertEquals(((Object[]) o).length, 2); @@ -304,9 +303,8 @@ class PojoUtilsTest { JSONObject jsonObject = new JSONObject(); jsonObject.put("1", "test"); @SuppressWarnings("unchecked") - Map value = (Map) PojoUtils.realize(jsonObject, - method.getParameterTypes()[0], - method.getGenericParameterTypes()[0]); + Map value = (Map) + PojoUtils.realize(jsonObject, method.getParameterTypes()[0], method.getGenericParameterTypes()[0]); method.invoke(new PojoUtilsTest(), value); assertEquals("test", value.get(1)); } @@ -320,19 +318,15 @@ class PojoUtilsTest { List list = new ArrayList<>(1); list.add(jsonObject); @SuppressWarnings("unchecked") - List> result = (List>) PojoUtils.realize( - list, - method.getParameterTypes()[0], - method.getGenericParameterTypes()[0]); + List> result = (List>) + PojoUtils.realize(list, method.getParameterTypes()[0], method.getGenericParameterTypes()[0]); method.invoke(new PojoUtilsTest(), result); assertEquals("test", result.get(0).get(1)); } - public void setMap(Map map) { - } + public void setMap(Map map) {} - public void setListMap(List> list) { - } + public void setListMap(List> list) {} @Test void testException() throws Exception { @@ -361,7 +355,7 @@ class PojoUtilsTest { public Type getType(String methodName) { Method method; try { - method = getClass().getDeclaredMethod(methodName, new Class[]{}); + method = getClass().getDeclaredMethod(methodName, new Class[] {}); } catch (Exception e) { throw new IllegalStateException(e); } @@ -392,7 +386,7 @@ class PojoUtilsTest { @Test void test_total_Array() throws Exception { - Object[] persons = new Object[]{bigPerson, bigPerson, bigPerson}; + Object[] persons = new Object[] {bigPerson, bigPerson, bigPerson}; Object generalize = PojoUtils.generalize(persons); Object[] realize = (Object[]) PojoUtils.realize(generalize, Object[].class); @@ -456,7 +450,8 @@ class PojoUtilsTest { Object generalize = PojoUtils.generalize(map); @SuppressWarnings("unchecked") - Map realize = (Map) PojoUtils.realize(generalize, Map.class, getType("getMapGenericType")); + Map realize = + (Map) PojoUtils.realize(generalize, Map.class, getType("getMapGenericType")); Parent parent = (Parent) realize.get("k"); @@ -494,7 +489,8 @@ class PojoUtilsTest { assertEquals("haha", parent.getChild().getToy()); assertSame(parent, parent.getChild().getParent()); - Object[] objects = PojoUtils.realize(new Object[]{generalize}, new Class[]{List.class}, new Type[]{getType("getListGenericType")}); + Object[] objects = PojoUtils.realize( + new Object[] {generalize}, new Class[] {List.class}, new Type[] {getType("getListGenericType")}); assertTrue(((List) objects[0]).get(0) instanceof Parent); } @@ -517,11 +513,9 @@ class PojoUtilsTest { assertEquals("jerry", parent.getName()); } - public void setLong(long l) { - } + public void setLong(long l) {} - public void setInt(int l) { - } + public void setInt(int l) {} public List getListGenericType() { return null; @@ -537,7 +531,8 @@ class PojoUtilsTest { Method method = PojoUtilsTest.class.getMethod("setLong", long.class); assertNotNull(method); - Object value = PojoUtils.realize("563439743927993", method.getParameterTypes()[0], method.getGenericParameterTypes()[0]); + Object value = PojoUtils.realize( + "563439743927993", method.getParameterTypes()[0], method.getGenericParameterTypes()[0]); method.invoke(new PojoUtilsTest(), value); } @@ -622,8 +617,10 @@ class PojoUtilsTest { assertSame(data.getList().get(0).getClass(), Child.class); TestData realizadData = (TestData) PojoUtils.realize(obj, TestData.class); - Assertions.assertEquals(data.getChildren().size(), realizadData.getChildren().size()); - Assertions.assertEquals(data.getChildren().keySet(), realizadData.getChildren().keySet()); + Assertions.assertEquals( + data.getChildren().size(), realizadData.getChildren().size()); + Assertions.assertEquals( + data.getChildren().keySet(), realizadData.getChildren().keySet()); for (Map.Entry entry : data.getChildren().entrySet()) { Child c = realizadData.getChildren().get(entry.getKey()); Assertions.assertNotNull(c); @@ -632,8 +629,10 @@ class PojoUtilsTest { } Assertions.assertEquals(1, realizadData.getList().size()); - Assertions.assertEquals(data.getList().get(0).getName(), realizadData.getList().get(0).getName()); - Assertions.assertEquals(data.getList().get(0).getAge(), realizadData.getList().get(0).getAge()); + Assertions.assertEquals( + data.getList().get(0).getName(), realizadData.getList().get(0).getName()); + Assertions.assertEquals( + data.getList().get(0).getAge(), realizadData.getList().get(0).getAge()); } @Test @@ -644,7 +643,7 @@ class PojoUtilsTest { assertTrue(obj instanceof LinkedHashMap); Object outputObject = PojoUtils.realize(map, LinkedHashMap.class); assertTrue(outputObject instanceof LinkedHashMap); - Object[] objects = PojoUtils.realize(new Object[]{map}, new Class[]{LinkedHashMap.class}); + Object[] objects = PojoUtils.realize(new Object[] {map}, new Class[] {LinkedHashMap.class}); assertTrue(objects[0] instanceof LinkedHashMap); assertEquals(objects[0], outputObject); } @@ -716,24 +715,24 @@ class PojoUtilsTest { String dateStr = "2018-09-12"; String timeStr = "10:12:33"; String dateTimeStr = "2018-09-12 10:12:33"; - String[] dateFormat = new String[]{"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd", "HH:mm:ss"}; + String[] dateFormat = new String[] {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd", "HH:mm:ss"}; - //java.util.Date + // java.util.Date Object date = PojoUtils.realize(dateTimeStr, Date.class, (Type) Date.class); assertEquals(Date.class, date.getClass()); assertEquals(dateTimeStr, new SimpleDateFormat(dateFormat[0]).format(date)); - //java.sql.Time + // java.sql.Time Object time = PojoUtils.realize(dateTimeStr, java.sql.Time.class, (Type) java.sql.Time.class); assertEquals(java.sql.Time.class, time.getClass()); assertEquals(timeStr, new SimpleDateFormat(dateFormat[2]).format(time)); - //java.sql.Date + // java.sql.Date Object sqlDate = PojoUtils.realize(dateTimeStr, java.sql.Date.class, (Type) java.sql.Date.class); assertEquals(java.sql.Date.class, sqlDate.getClass()); assertEquals(dateStr, new SimpleDateFormat(dateFormat[1]).format(sqlDate)); - //java.sql.Timestamp + // java.sql.Timestamp Object timestamp = PojoUtils.realize(dateTimeStr, java.sql.Timestamp.class, (Type) java.sql.Timestamp.class); assertEquals(java.sql.Timestamp.class, timestamp.getClass()); assertEquals(dateTimeStr, new SimpleDateFormat(dateFormat[0]).format(timestamp)); @@ -796,7 +795,6 @@ class PojoUtilsTest { assertEquals(PersonMap.class, result.getClass()); } - protected PersonInfo createPersonInfoByName(String name) { PersonInfo dataPerson = new PersonInfo(); dataPerson.setName(name); @@ -830,12 +828,14 @@ class PojoUtilsTest { assertTrue(personInfo.getData() instanceof Map); } { - Type[] createGenericPersonInfos = ReflectUtils.getReturnTypes(PojoUtilsTest.class.getDeclaredMethod("createAGenericPersonInfo", String.class)); - Ageneric personInfo = (Ageneric) PojoUtils.realize(o, (Class)createGenericPersonInfos[0], createGenericPersonInfos[1]); + Type[] createGenericPersonInfos = ReflectUtils.getReturnTypes( + PojoUtilsTest.class.getDeclaredMethod("createAGenericPersonInfo", String.class)); + Ageneric personInfo = (Ageneric) + PojoUtils.realize(o, (Class) createGenericPersonInfos[0], createGenericPersonInfos[1]); assertEquals(Ageneric.NAME, personInfo.getName()); assertEquals(personInfo.getData().getClass(), PersonInfo.class); - assertEquals(personName, ((PersonInfo)personInfo.getData()).getName()); + assertEquals(personName, ((PersonInfo) personInfo.getData()).getName()); } } { @@ -849,12 +849,14 @@ class PojoUtilsTest { assertTrue(personInfo.getData() instanceof Map); } { - Type[] createGenericPersonInfos = ReflectUtils.getReturnTypes(PojoUtilsTest.class.getDeclaredMethod("createBGenericPersonInfo", String.class)); - Bgeneric personInfo = (Bgeneric) PojoUtils.realize(o, (Class)createGenericPersonInfos[0], createGenericPersonInfos[1]); + Type[] createGenericPersonInfos = ReflectUtils.getReturnTypes( + PojoUtilsTest.class.getDeclaredMethod("createBGenericPersonInfo", String.class)); + Bgeneric personInfo = (Bgeneric) + PojoUtils.realize(o, (Class) createGenericPersonInfos[0], createGenericPersonInfos[1]); assertEquals(Bgeneric.NAME, personInfo.getName()); assertEquals(personInfo.getData().getClass(), PersonInfo.class); - assertEquals(personName, ((PersonInfo)personInfo.getData()).getName()); + assertEquals(personName, ((PersonInfo) personInfo.getData()).getName()); } } } @@ -885,18 +887,19 @@ class PojoUtilsTest { assertTrue(personInfo.getData() instanceof Map); } { - Type[] createGenericPersonInfos = ReflectUtils.getReturnTypes(PojoUtilsTest.class.getDeclaredMethod("createAGenericLoop", String.class)); - Ageneric personInfo = (Ageneric) PojoUtils.realize(o, (Class)createGenericPersonInfos[0], createGenericPersonInfos[1]); + Type[] createGenericPersonInfos = ReflectUtils.getReturnTypes( + PojoUtilsTest.class.getDeclaredMethod("createAGenericLoop", String.class)); + Ageneric personInfo = (Ageneric) + PojoUtils.realize(o, (Class) createGenericPersonInfos[0], createGenericPersonInfos[1]); assertEquals(Ageneric.NAME, personInfo.getName()); assertEquals(personInfo.getData().getClass(), Ageneric.class); - assertEquals(Ageneric.NAME, ((Ageneric)personInfo.getData()).getName()); - assertEquals(((Ageneric)personInfo.getData()).getData().getClass(), PersonInfo.class); - assertEquals(personName, ((PersonInfo)((Ageneric)personInfo.getData()).getData()).getName()); + assertEquals(Ageneric.NAME, ((Ageneric) personInfo.getData()).getName()); + assertEquals(((Ageneric) personInfo.getData()).getData().getClass(), PersonInfo.class); + assertEquals(personName, ((PersonInfo) ((Ageneric) personInfo.getData()).getData()).getName()); } } { - Bgeneric> generic = createBGenericWithAgeneric(personName); Object o = JSON.toJSON(generic); { @@ -906,14 +909,16 @@ class PojoUtilsTest { assertTrue(personInfo.getData() instanceof Map); } { - Type[] createGenericPersonInfos = ReflectUtils.getReturnTypes(PojoUtilsTest.class.getDeclaredMethod("createBGenericWithAgeneric", String.class)); - Bgeneric personInfo = (Bgeneric) PojoUtils.realize(o, (Class)createGenericPersonInfos[0], createGenericPersonInfos[1]); + Type[] createGenericPersonInfos = ReflectUtils.getReturnTypes( + PojoUtilsTest.class.getDeclaredMethod("createBGenericWithAgeneric", String.class)); + Bgeneric personInfo = (Bgeneric) + PojoUtils.realize(o, (Class) createGenericPersonInfos[0], createGenericPersonInfos[1]); assertEquals(Bgeneric.NAME, personInfo.getName()); assertEquals(personInfo.getData().getClass(), Ageneric.class); - assertEquals(Ageneric.NAME, ((Ageneric)personInfo.getData()).getName()); - assertEquals(((Ageneric)personInfo.getData()).getData().getClass(), PersonInfo.class); - assertEquals(personName, ((PersonInfo)((Ageneric)personInfo.getData()).getData()).getName()); + assertEquals(Ageneric.NAME, ((Ageneric) personInfo.getData()).getName()); + assertEquals(((Ageneric) personInfo.getData()).getData().getClass(), PersonInfo.class); + assertEquals(personName, ((PersonInfo) ((Ageneric) personInfo.getData()).getData()).getName()); } } } @@ -939,15 +944,16 @@ class PojoUtilsTest { assertTrue(personInfo.getData() instanceof Map); assertTrue(personInfo.getA().getData() instanceof Map); assertTrue(personInfo.getB().getData() instanceof PersonInfo); - } { - Type[] createGenericPersonInfos = ReflectUtils.getReturnTypes(PojoUtilsTest.class.getDeclaredMethod("createCGenericPersonInfo", String.class)); - Cgeneric personInfo = (Cgeneric) PojoUtils.realize(o, (Class)createGenericPersonInfos[0], createGenericPersonInfos[1]); + Type[] createGenericPersonInfos = ReflectUtils.getReturnTypes( + PojoUtilsTest.class.getDeclaredMethod("createCGenericPersonInfo", String.class)); + Cgeneric personInfo = + (Cgeneric) PojoUtils.realize(o, (Class) createGenericPersonInfos[0], createGenericPersonInfos[1]); assertEquals(Cgeneric.NAME, personInfo.getName()); assertEquals(personInfo.getData().getClass(), PersonInfo.class); - assertEquals(personName, ((PersonInfo)personInfo.getData()).getName()); + assertEquals(personName, ((PersonInfo) personInfo.getData()).getName()); assertEquals(personInfo.getA().getClass(), Ageneric.class); assertEquals(personInfo.getA().getData().getClass(), PersonInfo.class); @@ -956,7 +962,8 @@ class PojoUtilsTest { } } - protected Dgeneric, Bgeneric, Cgeneric> createDGenericPersonInfo(String name) { + protected Dgeneric, Bgeneric, Cgeneric> createDGenericPersonInfo( + String name) { Dgeneric, Bgeneric, Cgeneric> ret = new Dgeneric(); ret.setT(createAGenericPersonInfo(name)); ret.setY(createBGenericPersonInfo(name)); @@ -979,23 +986,25 @@ class PojoUtilsTest { assertTrue(personInfo.getZ() instanceof Map); } { - Type[] createGenericPersonInfos = ReflectUtils.getReturnTypes(PojoUtilsTest.class.getDeclaredMethod("createDGenericPersonInfo", String.class)); - Dgeneric personInfo = (Dgeneric) PojoUtils.realize(o, (Class)createGenericPersonInfos[0], createGenericPersonInfos[1]); + Type[] createGenericPersonInfos = ReflectUtils.getReturnTypes( + PojoUtilsTest.class.getDeclaredMethod("createDGenericPersonInfo", String.class)); + Dgeneric personInfo = + (Dgeneric) PojoUtils.realize(o, (Class) createGenericPersonInfos[0], createGenericPersonInfos[1]); assertEquals(Dgeneric.NAME, personInfo.getName()); assertEquals(personInfo.getT().getClass(), Ageneric.class); - assertEquals(((Ageneric)personInfo.getT()).getData().getClass(), PersonInfo.class); + assertEquals(((Ageneric) personInfo.getT()).getData().getClass(), PersonInfo.class); assertEquals(personInfo.getY().getClass(), Bgeneric.class); - assertEquals(((Bgeneric)personInfo.getY()).getData().getClass(), PersonInfo.class); + assertEquals(((Bgeneric) personInfo.getY()).getData().getClass(), PersonInfo.class); assertEquals(personInfo.getZ().getClass(), Cgeneric.class); - assertEquals(((Cgeneric)personInfo.getZ()).getData().getClass(), PersonInfo.class); + assertEquals(((Cgeneric) personInfo.getZ()).getData().getClass(), PersonInfo.class); assertEquals(personInfo.getZ().getClass(), Cgeneric.class); - assertEquals(((Cgeneric)personInfo.getZ()).getA().getClass(), Ageneric.class); - assertEquals(((Cgeneric)personInfo.getZ()).getA().getData().getClass(), PersonInfo.class); - assertEquals(((Cgeneric)personInfo.getZ()).getB().getClass(), Bgeneric.class); - assertEquals(((Cgeneric)personInfo.getZ()).getB().getData().getClass(), PersonInfo.class); + assertEquals(((Cgeneric) personInfo.getZ()).getA().getClass(), Ageneric.class); + assertEquals(((Cgeneric) personInfo.getZ()).getA().getData().getClass(), PersonInfo.class); + assertEquals(((Cgeneric) personInfo.getZ()).getB().getClass(), Bgeneric.class); + assertEquals(((Cgeneric) personInfo.getZ()).getB().getData().getClass(), PersonInfo.class); } } @@ -1008,10 +1017,11 @@ class PojoUtilsTest { Object generalized = PojoUtils.generalize(origin); Assertions.assertInstanceOf(Map.class, generalized); - Assertions.assertEquals("test123", ((Map)generalized).get("nameA")); - Assertions.assertEquals("test234", ((Map)generalized).get("nameB")); + Assertions.assertEquals("test123", ((Map) generalized).get("nameA")); + Assertions.assertEquals("test234", ((Map) generalized).get("nameB")); - NameNotMatch target1 = (NameNotMatch) PojoUtils.realize(PojoUtils.generalize(origin), NameNotMatch.class, NameNotMatch.class); + NameNotMatch target1 = + (NameNotMatch) PojoUtils.realize(PojoUtils.generalize(origin), NameNotMatch.class, NameNotMatch.class); Assertions.assertEquals(origin, target1); Map map = new HashMap<>(); @@ -1057,7 +1067,13 @@ class PojoUtilsTest { } public enum Day { - SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY + SUNDAY, + MONDAY, + TUESDAY, + WEDNESDAY, + THURSDAY, + FRIDAY, + SATURDAY } public static class BasicTestData implements Serializable { @@ -1099,12 +1115,9 @@ class PojoUtilsTest { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; BasicTestData other = (BasicTestData) obj; if (a != other.a) { return false; @@ -1129,7 +1142,6 @@ class PojoUtilsTest { } return true; } - } public static class Parent implements Serializable { diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ReflectUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ReflectUtilsTest.java index 2da5fabfb1..c987b81c30 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ReflectUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/ReflectUtilsTest.java @@ -14,12 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; @@ -32,6 +28,9 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; @@ -88,9 +87,9 @@ class ReflectUtilsTest { @Test void testIsCompatibleWithArray() { - assertFalse(ReflectUtils.isCompatible(new Class[]{short.class, int.class}, new Object[]{(short) 1})); - assertFalse(ReflectUtils.isCompatible(new Class[]{double.class}, new Object[]{"hello"})); - assertTrue(ReflectUtils.isCompatible(new Class[]{double.class}, new Object[]{1.2})); + assertFalse(ReflectUtils.isCompatible(new Class[] {short.class, int.class}, new Object[] {(short) 1})); + assertFalse(ReflectUtils.isCompatible(new Class[] {double.class}, new Object[] {"hello"})); + assertTrue(ReflectUtils.isCompatible(new Class[] {double.class}, new Object[] {1.2})); } @Test @@ -157,8 +156,9 @@ class ReflectUtilsTest { @Test void testGetMethodName() throws Exception { - assertThat(ReflectUtils.getName(Foo2.class.getDeclaredMethod("hello", int[].class)), - equalTo("java.util.List hello(int[])")); + assertThat( + ReflectUtils.getName(Foo2.class.getDeclaredMethod("hello", int[].class)), + equalTo("java.util.List hello(int[])")); } @Test @@ -183,8 +183,9 @@ class ReflectUtilsTest { @Test void testGetDescMethod() throws Exception { - assertThat(ReflectUtils.getDesc(Foo2.class.getDeclaredMethod("hello", int[].class)), - equalTo("hello([I)Ljava/util/List;")); + assertThat( + ReflectUtils.getDesc(Foo2.class.getDeclaredMethod("hello", int[].class)), + equalTo("hello([I)Ljava/util/List;")); } @Test @@ -194,8 +195,9 @@ class ReflectUtilsTest { @Test void testGetDescWithoutMethodName() throws Exception { - assertThat(ReflectUtils.getDescWithoutMethodName(Foo2.class.getDeclaredMethod("hello", int[].class)), - equalTo("([I)Ljava/util/List;")); + assertThat( + ReflectUtils.getDescWithoutMethodName(Foo2.class.getDeclaredMethod("hello", int[].class)), + equalTo("([I)Ljava/util/List;")); } @Test @@ -208,7 +210,6 @@ class ReflectUtilsTest { Assertions.assertThrows(IllegalStateException.class, () -> { ReflectUtils.findMethodByMethodName(Foo2.class, "hello"); }); - } @Test @@ -309,23 +310,22 @@ class ReflectUtilsTest { String desc; Class[] cs; - cs = new Class[]{int.class, getClass(), String.class, int[][].class, boolean[].class}; + cs = new Class[] {int.class, getClass(), String.class, int[][].class, boolean[].class}; desc = ReflectUtils.getDesc(cs); assertSame(cs, ReflectUtils.desc2classArray(desc)); - cs = new Class[]{}; + cs = new Class[] {}; desc = ReflectUtils.getDesc(cs); assertSame(cs, ReflectUtils.desc2classArray(desc)); - cs = new Class[]{void.class, String[].class, int[][].class, ReflectUtilsTest[][].class}; + cs = new Class[] {void.class, String[].class, int[][].class, ReflectUtilsTest[][].class}; desc = ReflectUtils.getDesc(cs); assertSame(cs, ReflectUtils.desc2classArray(desc)); } protected void assertSame(Class[] cs1, Class[] cs2) throws Exception { assertEquals(cs1.length, cs2.length); - for (int i = 0; i < cs1.length; i++) - assertEquals(cs1[i], cs2[i]); + for (int i = 0; i < cs1.length; i++) assertEquals(cs1[i], cs2[i]); } @Test @@ -341,8 +341,8 @@ class ReflectUtilsTest { @Test void testFindMethodByMethodSignature_override() throws Exception { { - Method m = ReflectUtils.findMethodByMethodSignature(TestedClass.class, - "overrideMethod", new String[]{"int"}); + Method m = + ReflectUtils.findMethodByMethodSignature(TestedClass.class, "overrideMethod", new String[] {"int"}); assertEquals("overrideMethod", m.getName()); Class[] parameterTypes = m.getParameterTypes(); @@ -350,8 +350,8 @@ class ReflectUtilsTest { assertEquals(int.class, parameterTypes[0]); } { - Method m = ReflectUtils.findMethodByMethodSignature(TestedClass.class, - "overrideMethod", new String[]{"java.lang.Integer"}); + Method m = ReflectUtils.findMethodByMethodSignature( + TestedClass.class, "overrideMethod", new String[] {"java.lang.Integer"}); assertEquals("overrideMethod", m.getName()); Class[] parameterTypes = m.getParameterTypes(); @@ -486,9 +486,7 @@ class ReflectUtilsTest { return null; } - public void isProperty() { - - } + public void isProperty() {} public boolean isSet() { return set; @@ -503,27 +501,20 @@ class ReflectUtilsTest { } } - public static class EmptyProperty { - } + public static class EmptyProperty {} static class TestedClass { - public void method1(int x) { - } + public void method1(int x) {} - public void overrideMethod(int x) { - } + public void overrideMethod(int x) {} - public void overrideMethod(Integer x) { - } + public void overrideMethod(Integer x) {} - public void overrideMethod(String s) { - } + public void overrideMethod(String s) {} - public void overrideMethod(String s1, String s2) { - } + public void overrideMethod(String s1, String s2) {} } - interface Foo { A hello(B b); } @@ -536,8 +527,7 @@ class ReflectUtilsTest { } static class Foo2 implements Foo, int[]> { - public Foo2(List list, int[] ints) { - } + public Foo2(List list, int[] ints) {} @Override public List hello(int[] ints) { @@ -546,8 +536,7 @@ class ReflectUtilsTest { } static class Foo3 implements Foo { - public Foo3(Foo foo) { - } + public Foo3(Foo foo) {} @Override public Foo1 hello(Foo2 foo2) { diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/RegexPropertiesTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/RegexPropertiesTest.java index 8afcb0dff1..348de678d9 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/RegexPropertiesTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/RegexPropertiesTest.java @@ -21,7 +21,7 @@ import org.junit.jupiter.api.Test; class RegexPropertiesTest { @Test - void testGetProperty(){ + void testGetProperty() { RegexProperties regexProperties = new RegexProperties(); regexProperties.setProperty("org.apache.dubbo.provider.*", "http://localhost:20880"); regexProperties.setProperty("org.apache.dubbo.provider.config.*", "http://localhost:30880"); @@ -29,10 +29,14 @@ class RegexPropertiesTest { regexProperties.setProperty("org.apache.dubbo.consumer.*.demo", "http://localhost:50880"); regexProperties.setProperty("*.service", "http://localhost:60880"); - Assertions.assertEquals("http://localhost:20880", regexProperties.getProperty("org.apache.dubbo.provider.cluster")); - Assertions.assertEquals("http://localhost:30880", regexProperties.getProperty("org.apache.dubbo.provider.config.cluster")); - Assertions.assertEquals("http://localhost:40880", regexProperties.getProperty("org.apache.dubbo.provider.config.demo")); - Assertions.assertEquals("http://localhost:50880", regexProperties.getProperty("org.apache.dubbo.consumer.service.demo")); + Assertions.assertEquals( + "http://localhost:20880", regexProperties.getProperty("org.apache.dubbo.provider.cluster")); + Assertions.assertEquals( + "http://localhost:30880", regexProperties.getProperty("org.apache.dubbo.provider.config.cluster")); + Assertions.assertEquals( + "http://localhost:40880", regexProperties.getProperty("org.apache.dubbo.provider.config.demo")); + Assertions.assertEquals( + "http://localhost:50880", regexProperties.getProperty("org.apache.dubbo.consumer.service.demo")); Assertions.assertEquals("http://localhost:60880", regexProperties.getProperty("org.apache.dubbo.service")); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/SerializeSecurityConfiguratorTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/SerializeSecurityConfiguratorTest.java index 37397638eb..1b9e9e3e65 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/SerializeSecurityConfiguratorTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/SerializeSecurityConfiguratorTest.java @@ -22,6 +22,13 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Vector; + import com.service.DemoService1; import com.service.DemoService2; import com.service.DemoService4; @@ -33,13 +40,6 @@ import com.service.deep1.deep2.deep3.DemoService3; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Vector; - import static org.apache.dubbo.common.constants.CommonConstants.CLASS_DESERIALIZE_ALLOWED_LIST; import static org.apache.dubbo.common.constants.CommonConstants.CLASS_DESERIALIZE_BLOCKED_LIST; @@ -53,7 +53,8 @@ class SerializeSecurityConfiguratorTest { SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel); - serializeSecurityConfigurator.onAddClassLoader(moduleModel, Thread.currentThread().getContextClassLoader()); + serializeSecurityConfigurator.onAddClassLoader( + moduleModel, Thread.currentThread().getContextClassLoader()); Assertions.assertTrue(ssm.getAllowedPrefix().contains("java.util.HashMap")); Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.example.DemoInterface")); @@ -77,7 +78,8 @@ class SerializeSecurityConfiguratorTest { SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel); - serializeSecurityConfigurator.onAddClassLoader(moduleModel, Thread.currentThread().getContextClassLoader()); + serializeSecurityConfigurator.onAddClassLoader( + moduleModel, Thread.currentThread().getContextClassLoader()); Assertions.assertEquals(SerializeCheckStatus.DISABLE, ssm.getCheckStatus()); @@ -96,7 +98,8 @@ class SerializeSecurityConfiguratorTest { SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel); - serializeSecurityConfigurator.onAddClassLoader(moduleModel, Thread.currentThread().getContextClassLoader()); + serializeSecurityConfigurator.onAddClassLoader( + moduleModel, Thread.currentThread().getContextClassLoader()); Assertions.assertEquals(SerializeCheckStatus.WARN, ssm.getCheckStatus()); @@ -115,7 +118,8 @@ class SerializeSecurityConfiguratorTest { SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel); - serializeSecurityConfigurator.onAddClassLoader(moduleModel, Thread.currentThread().getContextClassLoader()); + serializeSecurityConfigurator.onAddClassLoader( + moduleModel, Thread.currentThread().getContextClassLoader()); Assertions.assertEquals(SerializeCheckStatus.STRICT, ssm.getCheckStatus()); @@ -132,7 +136,8 @@ class SerializeSecurityConfiguratorTest { SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel); - serializeSecurityConfigurator.onAddClassLoader(moduleModel, Thread.currentThread().getContextClassLoader()); + serializeSecurityConfigurator.onAddClassLoader( + moduleModel, Thread.currentThread().getContextClassLoader()); Assertions.assertEquals(SerializeCheckStatus.DISABLE, ssm.getCheckStatus()); @@ -150,7 +155,8 @@ class SerializeSecurityConfiguratorTest { SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel); - serializeSecurityConfigurator.onAddClassLoader(moduleModel, Thread.currentThread().getContextClassLoader()); + serializeSecurityConfigurator.onAddClassLoader( + moduleModel, Thread.currentThread().getContextClassLoader()); Assertions.assertEquals(SerializeCheckStatus.STRICT, ssm.getCheckStatus()); @@ -168,14 +174,14 @@ class SerializeSecurityConfiguratorTest { SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel); - serializeSecurityConfigurator.onAddClassLoader(moduleModel, Thread.currentThread().getContextClassLoader()); + serializeSecurityConfigurator.onAddClassLoader( + moduleModel, Thread.currentThread().getContextClassLoader()); Assertions.assertTrue(ssm.getAllowedPrefix().contains("test.package1")); Assertions.assertTrue(ssm.getAllowedPrefix().contains("test.package2")); System.clearProperty(CommonConstants.CLASS_DESERIALIZE_ALLOWED_LIST); frameworkModel.destroy(); - } @Test @@ -188,14 +194,14 @@ class SerializeSecurityConfiguratorTest { SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel); - serializeSecurityConfigurator.onAddClassLoader(moduleModel, Thread.currentThread().getContextClassLoader()); + serializeSecurityConfigurator.onAddClassLoader( + moduleModel, Thread.currentThread().getContextClassLoader()); Assertions.assertTrue(ssm.getDisAllowedPrefix().contains("test.package1")); Assertions.assertTrue(ssm.getDisAllowedPrefix().contains("test.package2")); System.clearProperty(CommonConstants.CLASS_DESERIALIZE_BLOCK_ALL); frameworkModel.destroy(); - } @Test @@ -209,7 +215,8 @@ class SerializeSecurityConfiguratorTest { SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel); - serializeSecurityConfigurator.onAddClassLoader(moduleModel, Thread.currentThread().getContextClassLoader()); + serializeSecurityConfigurator.onAddClassLoader( + moduleModel, Thread.currentThread().getContextClassLoader()); Assertions.assertTrue(ssm.getAllowedPrefix().contains("test.package1")); Assertions.assertTrue(ssm.getAllowedPrefix().contains("test.package2")); @@ -217,7 +224,6 @@ class SerializeSecurityConfiguratorTest { System.clearProperty(CommonConstants.CLASS_DESERIALIZE_ALLOWED_LIST); System.clearProperty(CommonConstants.CLASS_DESERIALIZE_BLOCK_ALL); frameworkModel.destroy(); - } @Test @@ -232,12 +238,12 @@ class SerializeSecurityConfiguratorTest { SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel); - serializeSecurityConfigurator.onAddClassLoader(moduleModel, Thread.currentThread().getContextClassLoader()); + serializeSecurityConfigurator.onAddClassLoader( + moduleModel, Thread.currentThread().getContextClassLoader()); Assertions.assertFalse(ssm.isCheckSerializable()); frameworkModel.destroy(); - } @Test @@ -249,12 +255,12 @@ class SerializeSecurityConfiguratorTest { SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel); - serializeSecurityConfigurator.onAddClassLoader(moduleModel, Thread.currentThread().getContextClassLoader()); + serializeSecurityConfigurator.onAddClassLoader( + moduleModel, Thread.currentThread().getContextClassLoader()); Assertions.assertTrue(ssm.isCheckSerializable()); frameworkModel.destroy(); - } @Test @@ -266,7 +272,8 @@ class SerializeSecurityConfiguratorTest { SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel); - serializeSecurityConfigurator.onAddClassLoader(moduleModel, Thread.currentThread().getContextClassLoader()); + serializeSecurityConfigurator.onAddClassLoader( + moduleModel, Thread.currentThread().getContextClassLoader()); serializeSecurityConfigurator.registerInterface(DemoService4.class); Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.service.DemoService4")); @@ -283,7 +290,8 @@ class SerializeSecurityConfiguratorTest { SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel); - serializeSecurityConfigurator.onAddClassLoader(moduleModel, Thread.currentThread().getContextClassLoader()); + serializeSecurityConfigurator.onAddClassLoader( + moduleModel, Thread.currentThread().getContextClassLoader()); serializeSecurityConfigurator.registerInterface(UserService.class); Assertions.assertTrue(ssm.getAllowedPrefix().contains(UserService.class.getName())); @@ -294,7 +302,6 @@ class SerializeSecurityConfiguratorTest { frameworkModel.destroy(); } - @Test void testRegister1() { FrameworkModel frameworkModel = new FrameworkModel(); @@ -304,7 +311,8 @@ class SerializeSecurityConfiguratorTest { SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel); - serializeSecurityConfigurator.onAddClassLoader(moduleModel, Thread.currentThread().getContextClassLoader()); + serializeSecurityConfigurator.onAddClassLoader( + moduleModel, Thread.currentThread().getContextClassLoader()); serializeSecurityConfigurator.registerInterface(DemoService1.class); Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.service.DemoService1")); @@ -328,7 +336,6 @@ class SerializeSecurityConfiguratorTest { frameworkModel.destroy(); } - @Test void testRegister2() { FrameworkModel frameworkModel = new FrameworkModel(); @@ -338,7 +345,8 @@ class SerializeSecurityConfiguratorTest { SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel); - serializeSecurityConfigurator.onAddClassLoader(moduleModel, Thread.currentThread().getContextClassLoader()); + serializeSecurityConfigurator.onAddClassLoader( + moduleModel, Thread.currentThread().getContextClassLoader()); serializeSecurityConfigurator.registerInterface(DemoService2.class); Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.service.DemoService2")); @@ -374,7 +382,8 @@ class SerializeSecurityConfiguratorTest { SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel); - serializeSecurityConfigurator.onAddClassLoader(moduleModel, Thread.currentThread().getContextClassLoader()); + serializeSecurityConfigurator.onAddClassLoader( + moduleModel, Thread.currentThread().getContextClassLoader()); serializeSecurityConfigurator.registerInterface(DemoService1.class); Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.service.DemoService1")); @@ -403,7 +412,8 @@ class SerializeSecurityConfiguratorTest { SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel); - serializeSecurityConfigurator.onAddClassLoader(moduleModel, Thread.currentThread().getContextClassLoader()); + serializeSecurityConfigurator.onAddClassLoader( + moduleModel, Thread.currentThread().getContextClassLoader()); serializeSecurityConfigurator.registerInterface(DemoService3.class); Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.service.deep1.deep2.")); @@ -423,7 +433,8 @@ class SerializeSecurityConfiguratorTest { SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); SerializeSecurityConfigurator serializeSecurityConfigurator = new SerializeSecurityConfigurator(moduleModel); - serializeSecurityConfigurator.onAddClassLoader(moduleModel, Thread.currentThread().getContextClassLoader()); + serializeSecurityConfigurator.onAddClassLoader( + moduleModel, Thread.currentThread().getContextClassLoader()); serializeSecurityConfigurator.registerInterface(DemoService3.class); Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.service.deep1.deep2.deep3.DemoService3")); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StackTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StackTest.java index 80d4109952..3e183d9e21 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StackTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StackTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,14 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; +import java.util.EmptyStackException; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.EmptyStackException; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; @@ -126,4 +125,4 @@ class StackTest { stack.remove(-2); }); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StringConstantFieldValuePredicateTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StringConstantFieldValuePredicateTest.java index c788d8f7e3..b8748971af 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StringConstantFieldValuePredicateTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StringConstantFieldValuePredicateTest.java @@ -16,10 +16,10 @@ */ package org.apache.dubbo.common.utils; -import org.junit.jupiter.api.Test; - import java.util.function.Predicate; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.utils.StringConstantFieldValuePredicate.of; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -44,4 +44,4 @@ class StringConstantFieldValuePredicateTest { assertTrue(predicate.test("2")); assertFalse(predicate.test("3")); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StringUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StringUtilsTest.java index 2ac7ccc411..3be95a78ed 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StringUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/StringUtilsTest.java @@ -16,8 +16,6 @@ */ package org.apache.dubbo.common.utils; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -27,6 +25,8 @@ import java.util.List; import java.util.Map; import java.util.Set; +import org.junit.jupiter.api.Test; + import static java.util.Arrays.asList; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; @@ -185,7 +185,8 @@ class StringUtilsTest { @Test void testExceptionToString() throws Exception { - assertThat(StringUtils.toString(new RuntimeException("abc")), containsString("java.lang.RuntimeException: abc")); + assertThat( + StringUtils.toString(new RuntimeException("abc")), containsString("java.lang.RuntimeException: abc")); } @Test @@ -279,7 +280,6 @@ class StringUtilsTest { assertEquals(ofSet("1", "2", "3", "4"), values); } - @Test void testTranslate() throws Exception { String s = "16314"; @@ -291,7 +291,7 @@ class StringUtilsTest { void testIsContains() throws Exception { assertThat(StringUtils.isContains("a,b, c", "b"), is(true)); assertThat(StringUtils.isContains("", "b"), is(false)); - assertThat(StringUtils.isContains(new String[]{"a", "b", "c"}, "b"), is(true)); + assertThat(StringUtils.isContains(new String[] {"a", "b", "c"}, "b"), is(true)); assertThat(StringUtils.isContains((String[]) null, null), is(false)); assertTrue(StringUtils.isContains("abc", 'a')); @@ -322,7 +322,6 @@ class StringUtilsTest { assertThat(StringUtils.isNumeric("123.", true), is(true)); assertThat(StringUtils.isNumeric(".123", true), is(true)); assertThat(StringUtils.isNumeric("..123", true), is(false)); - } @Test @@ -344,7 +343,7 @@ class StringUtilsTest { assertEquals("ab-cd-ef", StringUtils.camelToSplitName("abCdEf", "-")); assertEquals("ab-cd-ef", StringUtils.camelToSplitName("AbCdEf", "-")); assertEquals("abcdef", StringUtils.camelToSplitName("abcdef", "-")); - //assertEquals("name", StringUtils.camelToSplitName("NAME", "-")); + // assertEquals("name", StringUtils.camelToSplitName("NAME", "-")); assertEquals("ab-cd-ef", StringUtils.camelToSplitName("ab-cd-ef", "-")); assertEquals("ab-cd-ef", StringUtils.camelToSplitName("Ab-Cd-Ef", "-")); @@ -352,7 +351,7 @@ class StringUtilsTest { assertEquals("AB_CD_EF", StringUtils.camelToSplitName("AB_CD_EF", "-")); assertEquals("ab.cd.ef", StringUtils.camelToSplitName("AbCdEf", ".")); - //assertEquals("ab.cd.ef", StringUtils.camelToSplitName("ab-cd-ef", ".")); + // assertEquals("ab.cd.ef", StringUtils.camelToSplitName("ab-cd-ef", ".")); } @Test @@ -385,7 +384,7 @@ class StringUtilsTest { @Test void testToArgumentString() throws Exception { - String s = StringUtils.toArgumentString(new Object[]{"a", 0, Collections.singletonMap("enabled", true)}); + String s = StringUtils.toArgumentString(new Object[] {"a", 0, Collections.singletonMap("enabled", true)}); assertThat(s, containsString("a,")); assertThat(s, containsString("0,")); assertThat(s, containsString("{\"enabled\":true}")); @@ -467,7 +466,6 @@ class StringUtilsTest { blankValueMap.put("client", ""); str = StringUtils.encodeParameters(nullValueMap); assertEquals("[]", str); - } private void assertEqualsWithoutSpaces(String expect, String actual) { @@ -504,6 +502,5 @@ class StringUtilsTest { assertTrue(startsWithIgnoreCase("dubbo.application.name", "dubbo.application.")); assertTrue(startsWithIgnoreCase("dubbo.Application.name", "dubbo.application.")); assertTrue(startsWithIgnoreCase("Dubbo.application.name", "dubbo.application.")); - } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/TestAllowClassNotifyListener.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/TestAllowClassNotifyListener.java index c0b2bcd3c8..38cf84cd9e 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/TestAllowClassNotifyListener.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/TestAllowClassNotifyListener.java @@ -22,12 +22,12 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; public class TestAllowClassNotifyListener implements AllowClassNotifyListener { - private final static AtomicReference status = new AtomicReference<>(); - private final static AtomicReference> allowedList = new AtomicReference<>(); - private final static AtomicReference> disAllowedList = new AtomicReference<>(); - private final static AtomicBoolean checkSerializable = new AtomicBoolean(); + private static final AtomicReference status = new AtomicReference<>(); + private static final AtomicReference> allowedList = new AtomicReference<>(); + private static final AtomicReference> disAllowedList = new AtomicReference<>(); + private static final AtomicBoolean checkSerializable = new AtomicBoolean(); - private final static AtomicInteger count = new AtomicInteger(0); + private static final AtomicInteger count = new AtomicInteger(0); @Override public void notifyPrefix(Set allowedList, Set disAllowedList) { diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/TimeUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/TimeUtilsTest.java index c51e8786a7..466e6ba9c1 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/TimeUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/TimeUtilsTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.utils; import org.junit.jupiter.api.Test; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/UrlUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/UrlUtilsTest.java index 71d10302b8..fbba7a2039 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/UrlUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/UrlUtilsTest.java @@ -18,8 +18,6 @@ package org.apache.dubbo.common.utils; import org.apache.dubbo.common.URL; -import org.junit.jupiter.api.Test; - import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; @@ -30,6 +28,8 @@ import java.util.List; import java.util.Map; import java.util.Set; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; @@ -41,10 +41,6 @@ class UrlUtilsTest { String localAddress = "127.0.0.1"; - - - - @Test void testAddressNull() { String exceptionMessage = "Address is not allowed to be empty, please re-enter."; @@ -187,7 +183,9 @@ class UrlUtilsTest { Map subscribe = new HashMap(); subscribe.put(key, "version=1.0.0&group=test&dubbo.version=2.0.0"); Map newSubscribe = UrlUtils.convertSubscribe(subscribe); - assertEquals("dubbo.version=2.0.0&group=test&version=1.0.0", newSubscribe.get("test/dubbo.test.api.HelloService:1.0.0")); + assertEquals( + "dubbo.version=2.0.0&group=test&version=1.0.0", + newSubscribe.get("test/dubbo.test.api.HelloService:1.0.0")); } @Test @@ -387,7 +385,8 @@ class UrlUtilsTest { URL consumerUrl = URL.valueOf("consumer://127.0.0.1/com.xxx.XxxService?version=1.0.0&group=test"); assertTrue(UrlUtils.isMatch(consumerUrl, url)); - URL consumerUrl1 = URL.valueOf("consumer://127.0.0.1/com.xxx.XxxService?default.version=1.0.0&default.group=test"); + URL consumerUrl1 = + URL.valueOf("consumer://127.0.0.1/com.xxx.XxxService?default.version=1.0.0&default.group=test"); assertTrue(UrlUtils.isMatch(consumerUrl1, url)); } @@ -403,7 +402,6 @@ class UrlUtilsTest { assertFalse(UrlUtils.isConsumer(url1)); assertTrue(UrlUtils.isConsumer(url2)); assertTrue(UrlUtils.isConsumer(url3)); - } @Test @@ -416,7 +414,6 @@ class UrlUtilsTest { }); } - @Test public void testClassifyUrls() { @@ -457,7 +454,6 @@ class UrlUtilsTest { assertTrue(UrlUtils.hasServiceDiscoveryRegistryProtocol(url2)); } - private static final String SERVICE_REGISTRY_TYPE = "service"; private static final String REGISTRY_TYPE_KEY = "registry-type"; @@ -514,7 +510,6 @@ class UrlUtilsTest { String address5 = "http://example.com?category=something-else"; URL url5 = UrlUtils.parseURL(address5, null); - assertTrue(UrlUtils.isProvider(url1)); assertFalse(UrlUtils.isProvider(url2)); assertFalse(UrlUtils.isProvider(url3)); @@ -522,7 +517,6 @@ class UrlUtilsTest { assertFalse(UrlUtils.isProvider(url5)); } - @Test public void testIsRegistry() { String address1 = "http://example.com"; @@ -540,8 +534,6 @@ class UrlUtilsTest { assertTrue(UrlUtils.isRegistry(url4)); } - - @Test public void testIsServiceDiscoveryURL() { String address1 = "http://example.com"; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Color.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Color.java index bae247de99..9648a3531a 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Color.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Color.java @@ -17,7 +17,10 @@ package org.apache.dubbo.common.utils.json; public enum Color { - RED("红色", 1), GREEN("绿色", 2), BLANK("白色", 3), YELLO("黄色", 4); + RED("红色", 1), + GREEN("绿色", 2), + BLANK("白色", 3), + YELLO("黄色", 4); private String name; private int index; @@ -39,12 +42,15 @@ public enum Color { public String getName() { return name; } + public void setName(String name) { this.name = name; } + public int getIndex() { return index; } + public void setIndex(int index) { this.index = index; } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Range.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Range.java index 77725bf3a6..c3aa62c1bf 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Range.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Range.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.common.utils.json; -//public record Range(Integer left, Integer right) { +// public record Range(Integer left, Integer right) { // public Integer sum() { // return left + right; // } -//} +// } public class Range { private Integer left; @@ -28,8 +28,9 @@ public class Range { public Range(Integer left, Integer right) { this.left = left; - this.right =right; + this.right = right; } + public Integer sum() { return left + right; } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Service.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Service.java index b963e6d40b..453e71b129 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Service.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Service.java @@ -147,5 +147,4 @@ public interface Service { Iterator testIterator(); AbstractObject testAbstract(); - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Student.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Student.java index 992f24dd7e..9378d0bd62 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Student.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Student.java @@ -37,9 +37,6 @@ public class Student implements Serializable { @Override public String toString() { - return "Student{" + - "type=" + type + - ", name='" + name + '\'' + - '}'; + return "Student{" + "type=" + type + ", name='" + name + '\'' + '}'; } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Teacher.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Teacher.java index 5a95e17ba0..0d6d6cae85 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Teacher.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/Teacher.java @@ -45,9 +45,6 @@ public class Teacher implements Serializable { @Override public String toString() { - return "Teacher{" + - "name='" + name + '\'' + - ", age=" + age + - '}'; + return "Teacher{" + "name='" + name + '\'' + ", age=" + age + '}'; } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/TestEnum.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/TestEnum.java index f00aa81dd9..80fffb19ed 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/TestEnum.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/TestEnum.java @@ -17,5 +17,7 @@ package org.apache.dubbo.common.utils.json; public enum TestEnum { - TYPE_A, TYPE_B, TYPE_C + TYPE_A, + TYPE_B, + TYPE_C } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/TestObjectA.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/TestObjectA.java index 436d8a12b8..94bdf75bc8 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/TestObjectA.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/TestObjectA.java @@ -21,8 +21,7 @@ public class TestObjectA { private int age; private TestEnum testEnum; - public TestObjectA() { - } + public TestObjectA() {} public TestObjectA(String name, int age, TestEnum testEnum) { this.name = name; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/TestObjectB.java b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/TestObjectB.java index e15a9a1e89..16ea006e24 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/TestObjectB.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/utils/json/TestObjectB.java @@ -20,7 +20,6 @@ public class TestObjectB { private Inner innerA; private Inner innerB; - public Inner getInnerA() { return innerA; } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/version/VersionTest.java b/dubbo-common/src/test/java/org/apache/dubbo/common/version/VersionTest.java index f9781e4471..69dd5dbb08 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/version/VersionTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/version/VersionTest.java @@ -16,18 +16,17 @@ */ package org.apache.dubbo.common.version; - import org.apache.dubbo.common.Version; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.io.FileInputStream; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.util.Enumeration; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class VersionTest { @Test @@ -99,9 +98,11 @@ class VersionTest { } @Test - void testGetVersion() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { + void testGetVersion() + throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { Class versionClass = reloadVersionClass(); - Assertions.assertEquals("1.0.0", versionClass.getDeclaredMethod("getVersion").invoke(null)); + Assertions.assertEquals( + "1.0.0", versionClass.getDeclaredMethod("getVersion").invoke(null)); } private static Class reloadVersionClass() throws ClassNotFoundException { @@ -125,10 +126,13 @@ class VersionTest { } } - public byte[] loadClassData(String className) throws IOException { className = className.replaceAll("\\.", "/"); - String path = Version.class.getProtectionDomain().getCodeSource().getLocation().getPath() + className + ".class"; + String path = Version.class + .getProtectionDomain() + .getCodeSource() + .getLocation() + .getPath() + className + ".class"; FileInputStream fileInputStream; byte[] classBytes; fileInputStream = new FileInputStream(path); @@ -153,8 +157,11 @@ class VersionTest { } @Test - void testGetLastCommitId() throws NoSuchMethodException, ClassNotFoundException, InvocationTargetException, IllegalAccessException { + void testGetLastCommitId() + throws NoSuchMethodException, ClassNotFoundException, InvocationTargetException, IllegalAccessException { Class versionClass = reloadVersionClass(); - Assertions.assertEquals("82a29fcd674216fe9bea10b6efef3196929dd7ca", versionClass.getDeclaredMethod("getLastCommitId").invoke(null)); + Assertions.assertEquals( + "82a29fcd674216fe9bea10b6efef3196929dd7ca", + versionClass.getDeclaredMethod("getLastCommitId").invoke(null)); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/common/vo/UserVo.java b/dubbo-common/src/test/java/org/apache/dubbo/common/vo/UserVo.java index 336a0562ad..b71b53b8d5 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/common/vo/UserVo.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/common/vo/UserVo.java @@ -29,8 +29,7 @@ public class UserVo { this.age = age; } - public UserVo() { - } + public UserVo() {} public String getName() { return name; @@ -62,11 +61,7 @@ public class UserVo { @Override public String toString() { - return "UserVo{" + - "name='" + name + '\'' + - ", addr='" + addr + '\'' + - ", age=" + age + - '}'; + return "UserVo{" + "name='" + name + '\'' + ", addr='" + addr + '\'' + ", age=" + age + '}'; } @Override diff --git a/dubbo-common/src/test/java/org/apache/dubbo/config/AbstractInterfaceConfigTest.java b/dubbo-common/src/test/java/org/apache/dubbo/config/AbstractInterfaceConfigTest.java index 44a330aad1..1d852d3248 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/config/AbstractInterfaceConfigTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/config/AbstractInterfaceConfigTest.java @@ -16,23 +16,24 @@ */ package org.apache.dubbo.config; - import org.apache.dubbo.common.constants.CommonConstants; + +import java.io.File; +import java.nio.file.Path; +import java.util.Collections; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import java.io.File; -import java.nio.file.Path; -import java.util.Collections; - class AbstractInterfaceConfigTest { @BeforeAll public static void setUp(@TempDir Path folder) { - File dubboProperties = folder.resolve(CommonConstants.DUBBO_PROPERTIES_KEY).toFile(); + File dubboProperties = + folder.resolve(CommonConstants.DUBBO_PROPERTIES_KEY).toFile(); System.setProperty(CommonConstants.DUBBO_PROPERTIES_KEY, dubboProperties.getAbsolutePath()); } @@ -41,7 +42,6 @@ class AbstractInterfaceConfigTest { System.clearProperty(CommonConstants.DUBBO_PROPERTIES_KEY); } - @Test void checkStub1() { Assertions.assertThrows(IllegalStateException.class, () -> { @@ -256,7 +256,5 @@ class AbstractInterfaceConfigTest { } } - public static class InterfaceConfig extends AbstractInterfaceConfig { - - } + public static class InterfaceConfig extends AbstractInterfaceConfig {} } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/config/Greeting.java b/dubbo-common/src/test/java/org/apache/dubbo/config/Greeting.java index 4ee8fc5bd8..a1c1b49837 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/config/Greeting.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/config/Greeting.java @@ -6,7 +6,7 @@ * (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 + * 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, diff --git a/dubbo-common/src/test/java/org/apache/dubbo/config/GreetingLocal1.java b/dubbo-common/src/test/java/org/apache/dubbo/config/GreetingLocal1.java index 212758ec0f..fb8ad262f6 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/config/GreetingLocal1.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/config/GreetingLocal1.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -16,6 +16,4 @@ */ package org.apache.dubbo.config; -public class GreetingLocal1 { - -} +public class GreetingLocal1 {} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/config/GreetingLocal2.java b/dubbo-common/src/test/java/org/apache/dubbo/config/GreetingLocal2.java index e25653c514..7c48c9fba0 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/config/GreetingLocal2.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/config/GreetingLocal2.java @@ -6,7 +6,7 @@ * (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 + * 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, diff --git a/dubbo-common/src/test/java/org/apache/dubbo/config/GreetingLocal3.java b/dubbo-common/src/test/java/org/apache/dubbo/config/GreetingLocal3.java index 37e2bf9b3d..87c9cd4de7 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/config/GreetingLocal3.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/config/GreetingLocal3.java @@ -6,7 +6,7 @@ * (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 + * 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, diff --git a/dubbo-common/src/test/java/org/apache/dubbo/config/context/ConfigConfigurationAdapterTest.java b/dubbo-common/src/test/java/org/apache/dubbo/config/context/ConfigConfigurationAdapterTest.java index 826560831f..58d229c6bb 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/config/context/ConfigConfigurationAdapterTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/config/context/ConfigConfigurationAdapterTest.java @@ -38,4 +38,4 @@ class ConfigConfigurationAdapterTest { Assertions.assertEquals(configConfigurationAdapter.getInternalProperty(prefix + "." + "address"), "127.0.0.1"); Assertions.assertEquals(configConfigurationAdapter.getInternalProperty(prefix + "." + "port"), "2181"); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/config/context/ConfigManagerTest.java b/dubbo-common/src/test/java/org/apache/dubbo/config/context/ConfigManagerTest.java index 5ddd74aad4..ae74fc11a4 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/config/context/ConfigManagerTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/config/context/ConfigManagerTest.java @@ -28,13 +28,13 @@ import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.Collection; +import java.util.Optional; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Collection; -import java.util.Optional; - import static java.util.Arrays.asList; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS; @@ -194,13 +194,13 @@ class ConfigManagerTest { assertFalse(configManager.getDefaultProtocols().isEmpty()); assertEquals(configs, moduleConfigManager.getProtocols()); assertNotEquals(20881, config.getPort()); - assertNotEquals(config.getSerialization(),"fastjson2"); + assertNotEquals(config.getSerialization(), "fastjson2"); ProtocolConfig defaultConfig = new ProtocolConfig(); defaultConfig.setPort(20881); defaultConfig.setSerialization("fastjson2"); config.mergeProtocol(defaultConfig); - assertEquals(config.getPort(),20881); - assertEquals(config.getSerialization(),"fastjson2"); + assertEquals(config.getPort(), 20881); + assertEquals(config.getSerialization(), "fastjson2"); } // Test RegistryConfig correlative methods @@ -306,7 +306,6 @@ class ConfigManagerTest { configManager.addConfig(applicationConfig2); assertEquals(applicationConfig2, configManager.getApplicationOrElseThrow()); - // test ignore mode System.setProperty(DUBBO_CONFIG_MODE, ConfigMode.IGNORE.name()); ApplicationModel.reset(); @@ -332,7 +331,9 @@ class ConfigManagerTest { assertEquals(applicationConfig11, configManager.getApplicationOrElseThrow()); assertEquals(applicationConfig11.getName(), "app22"); - assertEquals(applicationConfig11.getParameters(), CollectionUtils.toStringMap("k1", "v11", "k2", "v22", "k3", "v3")); + assertEquals( + applicationConfig11.getParameters(), + CollectionUtils.toStringMap("k1", "v11", "k2", "v22", "k3", "v3")); // test OVERRIDE_IF_ABSENT mode System.setProperty(DUBBO_CONFIG_MODE, ConfigMode.OVERRIDE_IF_ABSENT.name()); @@ -349,7 +350,9 @@ class ConfigManagerTest { assertEquals(applicationConfig33, configManager.getApplicationOrElseThrow()); assertEquals("app33", applicationConfig33.getName()); - assertEquals(CollectionUtils.toStringMap("k1", "v1", "k2", "v2", "k3", "v3"), applicationConfig33.getParameters()); + assertEquals( + CollectionUtils.toStringMap("k1", "v1", "k2", "v2", "k3", "v3"), + applicationConfig33.getParameters()); } finally { System.clearProperty(DUBBO_CONFIG_MODE); } @@ -360,7 +363,8 @@ class ConfigManagerTest { RegistryConfig registryConfig = new RegistryConfig(); registryConfig.setId("registryID_1"); configManager.addRegistry(registryConfig); - Optional registryConfigOptional = configManager.getConfig(RegistryConfig.class, registryConfig.getId()); + Optional registryConfigOptional = + configManager.getConfig(RegistryConfig.class, registryConfig.getId()); if (registryConfigOptional.isPresent()) { Assertions.assertEquals(registryConfigOptional.get(), registryConfig); @@ -370,7 +374,8 @@ class ConfigManagerTest { ProtocolConfig protocolConfig = new ProtocolConfig("dubbo"); configManager.addProtocol(protocolConfig); - Optional protocolConfigOptional = configManager.getConfig(ProtocolConfig.class, protocolConfig.getName()); + Optional protocolConfigOptional = + configManager.getConfig(ProtocolConfig.class, protocolConfig.getName()); if (protocolConfigOptional.isPresent()) { Assertions.assertEquals(protocolConfigOptional.get(), protocolConfig); @@ -387,15 +392,18 @@ class ConfigManagerTest { Assertions.fail(); } catch (Exception e) { Assertions.assertTrue(e instanceof IllegalStateException); - Assertions.assertEquals(e.getMessage(), "Found more than one config by name: dubbo, instances: " + - "[, ]. " + - "Please remove redundant configs or get config by id."); + Assertions.assertEquals( + e.getMessage(), + "Found more than one config by name: dubbo, instances: " + + "[, ]. " + + "Please remove redundant configs or get config by id."); } ModuleConfig moduleConfig = new ModuleConfig(); moduleConfig.setId("moduleID_1"); moduleConfigManager.setModule(moduleConfig); - Optional moduleConfigOptional = moduleConfigManager.getConfig(ModuleConfig.class, moduleConfig.getId()); + Optional moduleConfigOptional = + moduleConfigManager.getConfig(ModuleConfig.class, moduleConfig.getId()); Assertions.assertEquals(moduleConfig, moduleConfigOptional.get()); Optional config = moduleConfigManager.getConfig(RegistryConfig.class, registryConfig.getId()); @@ -435,7 +443,6 @@ class ConfigManagerTest { System.clearProperty("dubbo.applications.app1.name"); System.clearProperty("dubbo.applications.app2.name"); } - } @Test @@ -466,6 +473,5 @@ class ConfigManagerTest { Assertions.assertTrue(moduleConfigManager.getModule().isPresent()); Assertions.assertFalse(moduleConfigManager.getProviders().isEmpty()); Assertions.assertFalse(moduleConfigManager.getConsumers().isEmpty()); - } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/MetadataTest.java b/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/MetadataTest.java index d66136ad1c..77278b6c56 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/MetadataTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/MetadataTest.java @@ -58,7 +58,8 @@ class MetadataTest { System.out.println(">> testInnerClassType: " + JsonUtils.toJson(sd)); Assertions.assertEquals(TestService.class.getName(), sd.getCanonicalName()); - Assertions.assertEquals(TestService.class.getMethods().length, sd.getMethods().size()); + Assertions.assertEquals( + TestService.class.getMethods().length, sd.getMethods().size()); boolean containsType = false; for (TypeDefinition type : sd.getTypes()) { if (type.getType().equals("org.apache.dubbo.metadata.definition.common.OuterClass.InnerClass")) { @@ -87,7 +88,8 @@ class MetadataTest { System.out.println(">> testRawMap: " + JsonUtils.toJson(sd)); Assertions.assertEquals(TestService.class.getName(), sd.getCanonicalName()); - Assertions.assertEquals(TestService.class.getMethods().length, sd.getMethods().size()); + Assertions.assertEquals( + TestService.class.getMethods().length, sd.getMethods().size()); boolean containsType = false; for (TypeDefinition type : sd.getTypes()) { if (type.getType().equals("org.apache.dubbo.metadata.definition.common.ResultWithRawCollections")) { @@ -114,7 +116,8 @@ class MetadataTest { System.out.println(">> testEnum: " + JsonUtils.toJson(sd)); Assertions.assertEquals(TestService.class.getName(), sd.getCanonicalName()); - Assertions.assertEquals(TestService.class.getMethods().length, sd.getMethods().size()); + Assertions.assertEquals( + TestService.class.getMethods().length, sd.getMethods().size()); boolean containsType = false; for (TypeDefinition type : sd.getTypes()) { if (type.getType().equals("org.apache.dubbo.metadata.definition.common.ColorEnum")) { @@ -138,7 +141,8 @@ class MetadataTest { System.out.println(">> testExtendsMap: " + JsonUtils.toJson(sd)); Assertions.assertEquals(TestService.class.getName(), sd.getCanonicalName()); - Assertions.assertEquals(TestService.class.getMethods().length, sd.getMethods().size()); + Assertions.assertEquals( + TestService.class.getMethods().length, sd.getMethods().size()); boolean containsType = false; for (TypeDefinition type : sd.getTypes()) { if (type.getType().equals("org.apache.dubbo.metadata.definition.common.ClassExtendsMap")) { diff --git a/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/ServiceDefinitionBuilderTest.java b/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/ServiceDefinitionBuilderTest.java index 1fe844ac2c..16fa17164d 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/ServiceDefinitionBuilderTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/ServiceDefinitionBuilderTest.java @@ -22,20 +22,20 @@ import org.apache.dubbo.metadata.definition.model.TypeDefinition; import org.apache.dubbo.metadata.definition.service.ComplexObject; import org.apache.dubbo.metadata.definition.service.DemoService; import org.apache.dubbo.rpc.model.FrameworkModel; + +import java.util.Arrays; +import java.util.List; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.List; - /** * 2018/11/6 */ class ServiceDefinitionBuilderTest { - private static FrameworkModel frameworkModel; @BeforeAll @@ -56,11 +56,15 @@ class ServiceDefinitionBuilderTest { checkComplexObjectAsParam(fullServiceDefinition); } - void checkComplexObjectAsParam(FullServiceDefinition fullServiceDefinition) { - Assertions.assertTrue(fullServiceDefinition.getAnnotations().contains("@org.apache.dubbo.metadata.definition.service.annotation.MockTypeAnnotation(value=666)") - // JDK 17 style - || fullServiceDefinition.getAnnotations().contains("@org.apache.dubbo.metadata.definition.service.annotation.MockTypeAnnotation(666)")); + Assertions.assertTrue(fullServiceDefinition + .getAnnotations() + .contains( + "@org.apache.dubbo.metadata.definition.service.annotation.MockTypeAnnotation(value=666)") + // JDK 17 style + || fullServiceDefinition + .getAnnotations() + .contains("@org.apache.dubbo.metadata.definition.service.annotation.MockTypeAnnotation(666)")); List methodDefinitions = fullServiceDefinition.getMethods(); MethodDefinition complexCompute = null; @@ -75,23 +79,37 @@ class ServiceDefinitionBuilderTest { testAnnotation = methodDefinition; } } - Assertions.assertTrue(Arrays.equals(complexCompute.getParameterTypes(), new String[]{String.class.getName(), ComplexObject.class.getName()})); + Assertions.assertTrue(Arrays.equals( + complexCompute.getParameterTypes(), + new String[] {String.class.getName(), ComplexObject.class.getName()})); Assertions.assertEquals(complexCompute.getReturnType(), String.class.getName()); - Assertions.assertTrue(Arrays.equals(findComplexObject.getParameterTypes(), new String[]{String.class.getName(), "int", "long", - String[].class.getCanonicalName(), "java.util.List", ComplexObject.TestEnum.class.getCanonicalName()})); + Assertions.assertTrue(Arrays.equals(findComplexObject.getParameterTypes(), new String[] { + String.class.getName(), + "int", + "long", + String[].class.getCanonicalName(), + "java.util.List", + ComplexObject.TestEnum.class.getCanonicalName() + })); Assertions.assertEquals(findComplexObject.getReturnType(), ComplexObject.class.getCanonicalName()); - Assertions.assertTrue(testAnnotation.getAnnotations().equals(Arrays.asList( - "@org.apache.dubbo.metadata.definition.service.annotation.MockMethodAnnotation(value=777)", - "@org.apache.dubbo.metadata.definition.service.annotation.MockMethodAnnotation2(value=888)")) - // JDK 17 style - || testAnnotation.getAnnotations().equals(Arrays.asList( - "@org.apache.dubbo.metadata.definition.service.annotation.MockMethodAnnotation(777)", - "@org.apache.dubbo.metadata.definition.service.annotation.MockMethodAnnotation2(888)"))); + Assertions.assertTrue( + testAnnotation + .getAnnotations() + .equals( + Arrays.asList( + "@org.apache.dubbo.metadata.definition.service.annotation.MockMethodAnnotation(value=777)", + "@org.apache.dubbo.metadata.definition.service.annotation.MockMethodAnnotation2(value=888)")) + // JDK 17 style + || testAnnotation + .getAnnotations() + .equals( + Arrays.asList( + "@org.apache.dubbo.metadata.definition.service.annotation.MockMethodAnnotation(777)", + "@org.apache.dubbo.metadata.definition.service.annotation.MockMethodAnnotation2(888)"))); Assertions.assertEquals(testAnnotation.getReturnType(), "void"); - List typeDefinitions = fullServiceDefinition.getTypes(); TypeDefinition topTypeDefinition = null; @@ -113,23 +131,39 @@ class ServiceDefinitionBuilderTest { } } Assertions.assertEquals("long", topTypeDefinition.getProperties().get("v")); - Assertions.assertEquals("java.util.Map", topTypeDefinition.getProperties().get("maps")); - Assertions.assertEquals(ComplexObject.InnerObject.class.getCanonicalName(), topTypeDefinition.getProperties().get("innerObject")); - Assertions.assertEquals("java.util.List", topTypeDefinition.getProperties().get("intList")); - Assertions.assertEquals("java.lang.String[]", topTypeDefinition.getProperties().get("strArrays")); - Assertions.assertEquals("org.apache.dubbo.metadata.definition.service.ComplexObject.InnerObject3[]", topTypeDefinition.getProperties().get("innerObject3")); - Assertions.assertEquals("org.apache.dubbo.metadata.definition.service.ComplexObject.TestEnum", topTypeDefinition.getProperties().get("testEnum")); - Assertions.assertEquals("java.util.Set", topTypeDefinition.getProperties().get("innerObject2")); + Assertions.assertEquals( + "java.util.Map", + topTypeDefinition.getProperties().get("maps")); + Assertions.assertEquals( + ComplexObject.InnerObject.class.getCanonicalName(), + topTypeDefinition.getProperties().get("innerObject")); + Assertions.assertEquals( + "java.util.List", + topTypeDefinition.getProperties().get("intList")); + Assertions.assertEquals( + "java.lang.String[]", topTypeDefinition.getProperties().get("strArrays")); + Assertions.assertEquals( + "org.apache.dubbo.metadata.definition.service.ComplexObject.InnerObject3[]", + topTypeDefinition.getProperties().get("innerObject3")); + Assertions.assertEquals( + "org.apache.dubbo.metadata.definition.service.ComplexObject.TestEnum", + topTypeDefinition.getProperties().get("testEnum")); + Assertions.assertEquals( + "java.util.Set", + topTypeDefinition.getProperties().get("innerObject2")); - Assertions.assertSame("java.lang.String", innerTypeDefinition.getProperties().get("innerA")); + Assertions.assertSame( + "java.lang.String", innerTypeDefinition.getProperties().get("innerA")); Assertions.assertSame("int", innerTypeDefinition.getProperties().get("innerB")); - Assertions.assertSame("java.lang.String", inner2TypeDefinition.getProperties().get("innerA2")); + Assertions.assertSame( + "java.lang.String", inner2TypeDefinition.getProperties().get("innerA2")); Assertions.assertSame("int", inner2TypeDefinition.getProperties().get("innerB2")); - Assertions.assertSame("java.lang.String", inner3TypeDefinition.getProperties().get("innerA3")); + Assertions.assertSame( + "java.lang.String", inner3TypeDefinition.getProperties().get("innerA3")); - Assertions.assertEquals(Integer.class.getCanonicalName(), listTypeDefinition.getItems().get(0)); + Assertions.assertEquals( + Integer.class.getCanonicalName(), listTypeDefinition.getItems().get(0)); } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/Test3TypeBuilder.java b/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/Test3TypeBuilder.java index e142786120..ba227891a4 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/Test3TypeBuilder.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/Test3TypeBuilder.java @@ -28,12 +28,12 @@ import java.util.Map; public class Test3TypeBuilder implements TypeBuilder { // it is smaller than the implements of TypeBuilder @Override - public int getPriority(){ + public int getPriority() { return 10; } @Override - public boolean accept (Class clazz) { + public boolean accept(Class clazz) { return false; } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/TestTypeBuilder.java b/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/TestTypeBuilder.java index 393e773405..5902af8201 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/TestTypeBuilder.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/TestTypeBuilder.java @@ -28,7 +28,7 @@ import java.util.Map; public class TestTypeBuilder implements TypeBuilder { // it is smaller than the implements of TypeBuilder @Override - public int getPriority(){ + public int getPriority() { return -3; } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/common/ClassExtendsMap.java b/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/common/ClassExtendsMap.java index eacd1244cf..cfe413dab0 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/common/ClassExtendsMap.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/common/ClassExtendsMap.java @@ -23,8 +23,7 @@ public class ClassExtendsMap extends HashMap { private static final long serialVersionUID = 5108356684263812575L; private ClassExtendsMap resultMap; - public ClassExtendsMap() { - } + public ClassExtendsMap() {} public ClassExtendsMap getResultMap() { return resultMap; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/common/ColorEnum.java b/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/common/ColorEnum.java index db00d58610..a48e6d05d6 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/common/ColorEnum.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/common/ColorEnum.java @@ -17,6 +17,7 @@ package org.apache.dubbo.metadata.definition.common; public enum ColorEnum { - - RED, YELLOW, BLUE + RED, + YELLOW, + BLUE } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/common/ResultWithRawCollections.java b/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/common/ResultWithRawCollections.java index 07f1711b72..34c152c7fa 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/common/ResultWithRawCollections.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/common/ResultWithRawCollections.java @@ -28,8 +28,7 @@ public class ResultWithRawCollections { private Map map; private List list; - public ResultWithRawCollections() { - } + public ResultWithRawCollections() {} public ResultWithRawCollections(Map map, List list) { this.map = map; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/service/ComplexObject.java b/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/service/ComplexObject.java index b984dee76e..d1e083fcea 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/service/ComplexObject.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/service/ComplexObject.java @@ -29,8 +29,7 @@ import java.util.Set; */ public class ComplexObject { - public ComplexObject() { - } + public ComplexObject() {} public ComplexObject(String var1, int var2, long l, String[] var3, List var4, TestEnum testEnum) { this.setInnerObject(new InnerObject()); @@ -54,7 +53,7 @@ public class ComplexObject { io32.setInnerA3(var1 + "_32"); InnerObject3 io33 = new InnerObject3(); io33.setInnerA3(var1 + "_33"); - this.setInnerObject3(new InnerObject3[]{io31, io32, io33}); + this.setInnerObject3(new InnerObject3[] {io31, io32, io33}); this.maps = new HashMap<>(4); this.maps.put(var1 + "_k1", var1 + "_v1"); this.maps.put(var1 + "_k2", var1 + "_v2"); @@ -135,16 +134,15 @@ public class ComplexObject { @Override public String toString() { - return "ComplexObject{" + - "innerObject=" + innerObject + - ", innerObject2=" + innerObject2 + - ", innerObject3=" + Arrays.toString(innerObject3) + - ", strArrays=" + Arrays.toString(strArrays) + - ", intList=" + intList + - ", v=" + v + - ", testEnum=" + testEnum + - ", maps=" + maps + - '}'; + return "ComplexObject{" + "innerObject=" + + innerObject + ", innerObject2=" + + innerObject2 + ", innerObject3=" + + Arrays.toString(innerObject3) + ", strArrays=" + + Arrays.toString(strArrays) + ", intList=" + + intList + ", v=" + + v + ", testEnum=" + + testEnum + ", maps=" + + maps + '}'; } @Override @@ -152,14 +150,14 @@ public class ComplexObject { if (this == o) return true; if (!(o instanceof ComplexObject)) return false; ComplexObject that = (ComplexObject) o; - return getV() == that.getV() && - Objects.equals(getInnerObject(), that.getInnerObject()) && - Objects.equals(getInnerObject2(), that.getInnerObject2()) && - Arrays.equals(getInnerObject3(), that.getInnerObject3()) && - Arrays.equals(getStrArrays(), that.getStrArrays()) && - Objects.equals(getIntList(), that.getIntList()) && - getTestEnum() == that.getTestEnum() && - Objects.equals(getMaps(), that.getMaps()); + return getV() == that.getV() + && Objects.equals(getInnerObject(), that.getInnerObject()) + && Objects.equals(getInnerObject2(), that.getInnerObject2()) + && Arrays.equals(getInnerObject3(), that.getInnerObject3()) + && Arrays.equals(getStrArrays(), that.getStrArrays()) + && Objects.equals(getIntList(), that.getIntList()) + && getTestEnum() == that.getTestEnum() + && Objects.equals(getMaps(), that.getMaps()); } @Override @@ -171,10 +169,11 @@ public class ComplexObject { } public enum TestEnum { - VALUE1, VALUE2 + VALUE1, + VALUE2 } - static public class InnerObject { + public static class InnerObject { String innerA; int innerB; @@ -196,10 +195,7 @@ public class ComplexObject { @Override public String toString() { - return "InnerObject{" + - "innerA='" + innerA + '\'' + - ", innerB=" + innerB + - '}'; + return "InnerObject{" + "innerA='" + innerA + '\'' + ", innerB=" + innerB + '}'; } @Override @@ -207,8 +203,7 @@ public class ComplexObject { if (this == o) return true; if (!(o instanceof InnerObject)) return false; InnerObject that = (InnerObject) o; - return getInnerB() == that.getInnerB() && - Objects.equals(getInnerA(), that.getInnerA()); + return getInnerB() == that.getInnerB() && Objects.equals(getInnerA(), that.getInnerA()); } @Override @@ -217,7 +212,7 @@ public class ComplexObject { } } - static public class InnerObject2 { + public static class InnerObject2 { String innerA2; int innerB2; @@ -239,10 +234,7 @@ public class ComplexObject { @Override public String toString() { - return "InnerObject{" + - "innerA='" + innerA2 + '\'' + - ", innerB=" + innerB2 + - '}'; + return "InnerObject{" + "innerA='" + innerA2 + '\'' + ", innerB=" + innerB2 + '}'; } @Override @@ -250,8 +242,7 @@ public class ComplexObject { if (this == o) return true; if (!(o instanceof InnerObject2)) return false; InnerObject2 that = (InnerObject2) o; - return getInnerB2() == that.getInnerB2() && - Objects.equals(getInnerA2(), that.getInnerA2()); + return getInnerB2() == that.getInnerB2() && Objects.equals(getInnerA2(), that.getInnerA2()); } @Override @@ -260,7 +251,7 @@ public class ComplexObject { } } - static public class InnerObject3 { + public static class InnerObject3 { String innerA3; public String getInnerA3() { @@ -273,9 +264,7 @@ public class ComplexObject { @Override public String toString() { - return "InnerObject3{" + - "innerA3='" + innerA3 + '\'' + - '}'; + return "InnerObject3{" + "innerA3='" + innerA3 + '\'' + '}'; } @Override @@ -292,5 +281,3 @@ public class ComplexObject { } } } - - diff --git a/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/service/DemoService.java b/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/service/DemoService.java index cd24b03e62..4dba2b24c8 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/service/DemoService.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/service/DemoService.java @@ -30,7 +30,8 @@ public interface DemoService { String complexCompute(String input, ComplexObject co); - ComplexObject findComplexObject(String var1, int var2, long l, String[] var3, List var4, ComplexObject.TestEnum testEnum); + ComplexObject findComplexObject( + String var1, int var2, long l, String[] var3, List var4, ComplexObject.TestEnum testEnum); @MockMethodAnnotation(777) @MockMethodAnnotation2(888) diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/IsolationExecutorSupportFactoryTest.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/IsolationExecutorSupportFactoryTest.java index a0608064ed..a4c87d6560 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/IsolationExecutorSupportFactoryTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/executor/IsolationExecutorSupportFactoryTest.java @@ -24,11 +24,23 @@ import org.junit.jupiter.api.Test; class IsolationExecutorSupportFactoryTest { @Test void test() { - Assertions.assertInstanceOf(DefaultExecutorSupport.class, IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("dubbo://"))); - Assertions.assertInstanceOf(DefaultExecutorSupport.class, IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("empty://"))); - Assertions.assertInstanceOf(DefaultExecutorSupport.class, IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("exchange://"))); - Assertions.assertInstanceOf(Mock1ExecutorSupport.class, IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("mock1://"))); - Assertions.assertInstanceOf(Mock2ExecutorSupport.class, IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("mock2://"))); - Assertions.assertInstanceOf(DefaultExecutorSupport.class, IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("mock3://"))); + Assertions.assertInstanceOf( + DefaultExecutorSupport.class, + IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("dubbo://"))); + Assertions.assertInstanceOf( + DefaultExecutorSupport.class, + IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("empty://"))); + Assertions.assertInstanceOf( + DefaultExecutorSupport.class, + IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("exchange://"))); + Assertions.assertInstanceOf( + Mock1ExecutorSupport.class, + IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("mock1://"))); + Assertions.assertInstanceOf( + Mock2ExecutorSupport.class, + IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("mock2://"))); + Assertions.assertInstanceOf( + DefaultExecutorSupport.class, + IsolationExecutorSupportFactory.getIsolationExecutorSupport(URL.valueOf("mock3://"))); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ApplicationModelTest.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ApplicationModelTest.java index 6735caa5f5..65ce53287c 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ApplicationModelTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ApplicationModelTest.java @@ -24,14 +24,14 @@ import org.apache.dubbo.common.status.reporter.FrameworkStatusReportService; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.support.MockScopeModelDestroyListener; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + /** * {@link ApplicationModel} */ @@ -146,7 +146,6 @@ class ApplicationModelTest { } catch (Exception e) { Assertions.assertEquals("ApplicationModel is destroyed", e.getMessage(), StringUtils.toString(e)); } - } @Test @@ -172,5 +171,4 @@ class ApplicationModelTest { threads.forEach(Thread::start); endLatch.await(); } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/FrameworkModelTest.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/FrameworkModelTest.java index 3359c73525..73e6f21a42 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/FrameworkModelTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/FrameworkModelTest.java @@ -104,5 +104,4 @@ class FrameworkModelTest { Assertions.assertEquals("FrameworkModel is destroyed", e.getMessage(), StringUtils.toString(e)); } } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/FrameworkServiceRepositoryTest.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/FrameworkServiceRepositoryTest.java index 408fbc13c5..f67a3479fa 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/FrameworkServiceRepositoryTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/FrameworkServiceRepositoryTest.java @@ -21,13 +21,13 @@ import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.support.DemoService; import org.apache.dubbo.rpc.support.DemoServiceImpl; +import java.util.List; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.List; - import static org.apache.dubbo.common.BaseServiceMetadata.interfaceFromServiceKey; import static org.apache.dubbo.common.BaseServiceMetadata.versionFromServiceKey; @@ -56,14 +56,17 @@ class FrameworkServiceRepositoryTest { FrameworkServiceRepository frameworkServiceRepository = frameworkModel.getServiceRepository(); ModuleServiceRepository moduleServiceRepository = moduleModel.getServiceRepository(); - ServiceMetadata serviceMetadata = new ServiceMetadata(DemoService.class.getName(), "GROUP", "1.0.0", DemoService.class); + ServiceMetadata serviceMetadata = + new ServiceMetadata(DemoService.class.getName(), "GROUP", "1.0.0", DemoService.class); ServiceDescriptor serviceDescriptor = moduleServiceRepository.registerService(DemoService.class); String serviceKey = serviceMetadata.getServiceKey(); - ProviderModel providerModel = new ProviderModel(serviceKey, - new DemoServiceImpl(), - serviceDescriptor, - moduleModel, - serviceMetadata, ClassUtils.getClassLoader(DemoService.class)); + ProviderModel providerModel = new ProviderModel( + serviceKey, + new DemoServiceImpl(), + serviceDescriptor, + moduleModel, + serviceMetadata, + ClassUtils.getClassLoader(DemoService.class)); frameworkServiceRepository.registerProvider(providerModel); ProviderModel lookupExportedService = frameworkServiceRepository.lookupExportedService(serviceKey); @@ -74,16 +77,23 @@ class FrameworkServiceRepositoryTest { Assertions.assertEquals(allProviderModels.get(0), providerModel); String keyWithoutGroup = keyWithoutGroup(serviceKey); - ProviderModel exportedServiceWithoutGroup = frameworkServiceRepository.lookupExportedServiceWithoutGroup(keyWithoutGroup); + ProviderModel exportedServiceWithoutGroup = + frameworkServiceRepository.lookupExportedServiceWithoutGroup(keyWithoutGroup); Assertions.assertEquals(exportedServiceWithoutGroup, providerModel); - List providerModels = frameworkServiceRepository.lookupExportedServicesWithoutGroup(keyWithoutGroup); + List providerModels = + frameworkServiceRepository.lookupExportedServicesWithoutGroup(keyWithoutGroup); Assertions.assertEquals(providerModels.size(), 1); Assertions.assertEquals(providerModels.get(0), providerModel); ConsumerModel consumerModel = new ConsumerModel( - serviceMetadata.getServiceKey(), new DemoServiceImpl(), serviceDescriptor, - moduleModel, serviceMetadata, null, ClassUtils.getClassLoader(DemoService.class)); + serviceMetadata.getServiceKey(), + new DemoServiceImpl(), + serviceDescriptor, + moduleModel, + serviceMetadata, + null, + ClassUtils.getClassLoader(DemoService.class)); moduleServiceRepository.registerConsumer(consumerModel); List consumerModels = frameworkServiceRepository.allConsumerModels(); Assertions.assertEquals(consumerModels.size(), 1); @@ -92,7 +102,6 @@ class FrameworkServiceRepositoryTest { frameworkServiceRepository.unregisterProvider(providerModel); Assertions.assertNull(frameworkServiceRepository.lookupExportedService(serviceKey)); Assertions.assertNull(frameworkServiceRepository.lookupExportedServiceWithoutGroup(keyWithoutGroup)); - } private static String keyWithoutGroup(String serviceKey) { diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ModuleModelTest.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ModuleModelTest.java index 4bf1b6f748..7ba7ccc296 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ModuleModelTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ModuleModelTest.java @@ -86,6 +86,5 @@ class ModuleModelTest { // trigger tryDestroy Assertions.assertTrue(applicationModel.isDestroyed()); Assertions.assertTrue(frameworkModel.isDestroyed()); - } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ModuleServiceRepositoryTest.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ModuleServiceRepositoryTest.java index b78e6cbe82..b62ed7f3a7 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ModuleServiceRepositoryTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ModuleServiceRepositoryTest.java @@ -20,13 +20,13 @@ import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.rpc.support.DemoService; import org.apache.dubbo.rpc.support.DemoServiceImpl; +import java.util.List; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.List; - /** * {@link ModuleServiceRepository} */ @@ -55,7 +55,8 @@ class ModuleServiceRepositoryTest { ModuleServiceRepository repository = moduleModel.getServiceRepository(); // 1.test service - ServiceMetadata serviceMetadata = new ServiceMetadata(DemoService.class.getName(), null, null, DemoService.class); + ServiceMetadata serviceMetadata = + new ServiceMetadata(DemoService.class.getName(), null, null, DemoService.class); ServiceDescriptor serviceDescriptor = repository.registerService(DemoService.class); ServiceDescriptor lookupServiceResult = repository.lookupService(DemoService.class.getName()); @@ -65,14 +66,19 @@ class ModuleServiceRepositoryTest { Assertions.assertEquals(1, allServices.size()); Assertions.assertEquals(allServices.get(0), serviceDescriptor); - ServiceDescriptor serviceDescriptor1 = repository.registerService(DemoService.class.getSimpleName(), DemoService.class); + ServiceDescriptor serviceDescriptor1 = + repository.registerService(DemoService.class.getSimpleName(), DemoService.class); Assertions.assertEquals(serviceDescriptor1, serviceDescriptor); - // 2.test consumerModule ConsumerModel consumerModel = new ConsumerModel( - serviceMetadata.getServiceKey(), new DemoServiceImpl(), serviceDescriptor, - moduleModel, serviceMetadata, null, ClassUtils.getClassLoader(DemoService.class)); + serviceMetadata.getServiceKey(), + new DemoServiceImpl(), + serviceDescriptor, + moduleModel, + serviceMetadata, + null, + ClassUtils.getClassLoader(DemoService.class)); repository.registerConsumer(consumerModel); List allReferredServices = repository.getReferredServices(); @@ -83,15 +89,18 @@ class ModuleServiceRepositoryTest { Assertions.assertEquals(1, referredServices.size()); Assertions.assertEquals(referredServices.get(0), consumerModel); - ConsumerModel referredService = repository.lookupReferredServices(DemoService.class.getName()).get(0); + ConsumerModel referredService = + repository.lookupReferredServices(DemoService.class.getName()).get(0); Assertions.assertEquals(referredService, consumerModel); // 3.test providerModel - ProviderModel providerModel = new ProviderModel(DemoService.class.getName(), - new DemoServiceImpl(), - serviceDescriptor, - moduleModel, - serviceMetadata, ClassUtils.getClassLoader(DemoService.class)); + ProviderModel providerModel = new ProviderModel( + DemoService.class.getName(), + new DemoServiceImpl(), + serviceDescriptor, + moduleModel, + serviceMetadata, + ClassUtils.getClassLoader(DemoService.class)); repository.registerProvider(providerModel); List allExportedServices = repository.getExportedServices(); Assertions.assertEquals(1, allExportedServices.size()); @@ -100,7 +109,8 @@ class ModuleServiceRepositoryTest { ProviderModel exportedService = repository.lookupExportedService(DemoService.class.getName()); Assertions.assertEquals(exportedService, providerModel); - List providerModels = frameworkModel.getServiceRepository().allProviderModels(); + List providerModels = + frameworkModel.getServiceRepository().allProviderModels(); Assertions.assertEquals(1, providerModels.size()); Assertions.assertEquals(providerModels.get(0), providerModel); @@ -109,6 +119,7 @@ class ModuleServiceRepositoryTest { Assertions.assertTrue(repository.getAllServices().isEmpty()); Assertions.assertTrue(repository.getReferredServices().isEmpty()); Assertions.assertTrue(repository.getExportedServices().isEmpty()); - Assertions.assertTrue(frameworkModel.getServiceRepository().allProviderModels().isEmpty()); + Assertions.assertTrue( + frameworkModel.getServiceRepository().allProviderModels().isEmpty()); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/Person.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/Person.java index d09fcc0a24..a1af12566c 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/Person.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/Person.java @@ -74,22 +74,15 @@ public class Person { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; Person other = (Person) obj; - if (age != other.age) - return false; + if (age != other.age) return false; if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (!Arrays.equals(value, other.value)) - return false; + if (other.name != null) return false; + } else if (!name.equals(other.name)) return false; + if (!Arrays.equals(value, other.value)) return false; return true; } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ReflectionMethodDescriptorTest.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ReflectionMethodDescriptorTest.java index 93462ada31..352b1ac645 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ReflectionMethodDescriptorTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ReflectionMethodDescriptorTest.java @@ -14,26 +14,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.model; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.rpc.model.MethodDescriptor.RpcType; import org.apache.dubbo.rpc.support.DemoService; +import java.lang.reflect.Type; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.lang.reflect.Type; - class ReflectionMethodDescriptorTest { private final ReflectionMethodDescriptor method; { try { - method = new ReflectionMethodDescriptor( - DemoService.class.getDeclaredMethod("sayHello", String.class)); + method = new ReflectionMethodDescriptor(DemoService.class.getDeclaredMethod("sayHello", String.class)); } catch (NoSuchMethodException e) { throw new IllegalStateException(e); } @@ -51,13 +49,12 @@ class ReflectionMethodDescriptorTest { @Test void getCompatibleParamSignatures() { - Assertions.assertArrayEquals(new String[]{String.class.getName()}, - method.getCompatibleParamSignatures()); + Assertions.assertArrayEquals(new String[] {String.class.getName()}, method.getCompatibleParamSignatures()); } @Test void getParameterClasses() { - Assertions.assertArrayEquals(new Class[]{String.class}, method.getParameterClasses()); + Assertions.assertArrayEquals(new Class[] {String.class}, method.getParameterClasses()); } @Test @@ -72,8 +69,7 @@ class ReflectionMethodDescriptorTest { @Test void getReturnTypes() { - Assertions.assertArrayEquals(new Type[]{String.class, String.class}, - method.getReturnTypes()); + Assertions.assertArrayEquals(new Type[] {String.class, String.class}, method.getReturnTypes()); } @Test @@ -96,8 +92,8 @@ class ReflectionMethodDescriptorTest { @Test void testEquals() { try { - MethodDescriptor method2 = new ReflectionMethodDescriptor( - DemoService.class.getDeclaredMethod("sayHello", String.class)); + MethodDescriptor method2 = + new ReflectionMethodDescriptor(DemoService.class.getDeclaredMethod("sayHello", String.class)); method.addAttribute("attr", "attr"); method2.addAttribute("attr", "attr"); Assertions.assertEquals(method, method2); @@ -109,8 +105,8 @@ class ReflectionMethodDescriptorTest { @Test void testHashCode() { try { - MethodDescriptor method2 = new ReflectionMethodDescriptor( - DemoService.class.getDeclaredMethod("sayHello", String.class)); + MethodDescriptor method2 = + new ReflectionMethodDescriptor(DemoService.class.getDeclaredMethod("sayHello", String.class)); method.addAttribute("attr", "attr"); method2.addAttribute("attr", "attr"); Assertions.assertEquals(method.hashCode(), method2.hashCode()); @@ -118,4 +114,4 @@ class ReflectionMethodDescriptorTest { throw new IllegalStateException(e); } } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ReflectionServiceDescriptorTest.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ReflectionServiceDescriptorTest.java index b7011526be..11ddacfb42 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ReflectionServiceDescriptorTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ReflectionServiceDescriptorTest.java @@ -14,14 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.model; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder; import org.apache.dubbo.rpc.support.DemoService; - import org.apache.dubbo.rpc.support.DemoService1; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -30,13 +29,11 @@ import static org.mockito.Mockito.when; class ReflectionServiceDescriptorTest { - private final ReflectionServiceDescriptor service = new ReflectionServiceDescriptor( - DemoService.class); + private final ReflectionServiceDescriptor service = new ReflectionServiceDescriptor(DemoService.class); @Test void addMethod() { - ReflectionServiceDescriptor service2 = new ReflectionServiceDescriptor( - DemoService.class); + ReflectionServiceDescriptor service2 = new ReflectionServiceDescriptor(DemoService.class); MethodDescriptor method = Mockito.mock(MethodDescriptor.class); when(method.getMethodName()).thenReturn("sayHello2"); service2.addMethod(method); @@ -48,8 +45,7 @@ class ReflectionServiceDescriptorTest { try { new ReflectionServiceDescriptor(DemoService1.class); } catch (IllegalStateException e) { - Assertions.assertTrue(e.getMessage() - .contains("Stream method could not be overloaded.")); + Assertions.assertTrue(e.getMessage().contains("Stream method could not be overloaded.")); } } @@ -82,7 +78,7 @@ class ReflectionServiceDescriptorTest { @Test void testGetMethod() { - Assertions.assertNotNull(service.getMethod("sayHello", new Class[]{String.class})); + Assertions.assertNotNull(service.getMethod("sayHello", new Class[] {String.class})); } @Test @@ -92,19 +88,15 @@ class ReflectionServiceDescriptorTest { @Test void testEquals() { - ReflectionServiceDescriptor service2 = new ReflectionServiceDescriptor( - DemoService.class); - ReflectionServiceDescriptor service3 = new ReflectionServiceDescriptor( - DemoService.class); + ReflectionServiceDescriptor service2 = new ReflectionServiceDescriptor(DemoService.class); + ReflectionServiceDescriptor service3 = new ReflectionServiceDescriptor(DemoService.class); Assertions.assertEquals(service2, service3); } @Test void testHashCode() { - ReflectionServiceDescriptor service2 = new ReflectionServiceDescriptor( - DemoService.class); - ReflectionServiceDescriptor service3 = new ReflectionServiceDescriptor( - DemoService.class); + ReflectionServiceDescriptor service2 = new ReflectionServiceDescriptor(DemoService.class); + ReflectionServiceDescriptor service3 = new ReflectionServiceDescriptor(DemoService.class); Assertions.assertEquals(service2.hashCode(), service3.hashCode()); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ScopeModelAwareExtensionProcessorTest.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ScopeModelAwareExtensionProcessorTest.java index 87d0c11771..e1eb6b7a36 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ScopeModelAwareExtensionProcessorTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ScopeModelAwareExtensionProcessorTest.java @@ -68,7 +68,8 @@ class ScopeModelAwareExtensionProcessorTest { void testPostProcessAfterInitialization() throws Exception { ScopeModelAwareExtensionProcessor processor = new ScopeModelAwareExtensionProcessor(moduleModel); MockScopeModelAware mockScopeModelAware = new MockScopeModelAware(); - Object object = processor.postProcessAfterInitialization(mockScopeModelAware, mockScopeModelAware.getClass().getName()); + Object object = processor.postProcessAfterInitialization( + mockScopeModelAware, mockScopeModelAware.getClass().getName()); Assertions.assertEquals(object, mockScopeModelAware); Assertions.assertEquals(mockScopeModelAware.getScopeModel(), moduleModel); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ScopeModelTest.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ScopeModelTest.java index a7f56c4066..c72e3076bf 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ScopeModelTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ScopeModelTest.java @@ -18,14 +18,14 @@ package org.apache.dubbo.rpc.model; import org.apache.dubbo.common.utils.StringUtils; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.stream.Collectors; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class ScopeModelTest { @Test @@ -102,11 +102,15 @@ class ScopeModelTest { errorMsg = StringUtils.toString(throwable); errorMsg += "\n"; } - Assertions.assertEquals(0, errors.size(), "Error occurred while destroy FrameworkModel: "+ errorMsg); + Assertions.assertEquals(0, errors.size(), "Error occurred while destroy FrameworkModel: " + errorMsg); // destroy all FrameworkModel FrameworkModel.destroyAll(); - List remainFrameworks = FrameworkModel.getAllInstances().stream().map(m -> m.getDesc()).collect(Collectors.toList()); - Assertions.assertEquals(0, FrameworkModel.getAllInstances().size(), "FrameworkModel is not completely destroyed: " + remainFrameworks); + List remainFrameworks = + FrameworkModel.getAllInstances().stream().map(m -> m.getDesc()).collect(Collectors.toList()); + Assertions.assertEquals( + 0, + FrameworkModel.getAllInstances().size(), + "FrameworkModel is not completely destroyed: " + remainFrameworks); } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ScopeModelUtilTest.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ScopeModelUtilTest.java index 2e90314da1..b6e4384cb8 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ScopeModelUtilTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ScopeModelUtilTest.java @@ -20,13 +20,13 @@ import org.apache.dubbo.common.config.Environment; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; +import java.util.concurrent.locks.Lock; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.concurrent.locks.Lock; - /** * {@link ScopeModelUtil} */ @@ -54,48 +54,53 @@ class ScopeModelUtilTest { Assertions.assertEquals(ScopeModelUtil.getFrameworkModel(frameworkModel), frameworkModel); Assertions.assertEquals(ScopeModelUtil.getFrameworkModel(applicationModel), frameworkModel); Assertions.assertEquals(ScopeModelUtil.getFrameworkModel(moduleModel), frameworkModel); - Assertions.assertThrows(IllegalArgumentException.class, () -> ScopeModelUtil.getFrameworkModel(new MockScopeModel(null, null))); + Assertions.assertThrows( + IllegalArgumentException.class, () -> ScopeModelUtil.getFrameworkModel(new MockScopeModel(null, null))); Assertions.assertEquals(ScopeModelUtil.getApplicationModel(null), ApplicationModel.defaultModel()); Assertions.assertEquals(ScopeModelUtil.getApplicationModel(applicationModel), applicationModel); Assertions.assertEquals(ScopeModelUtil.getApplicationModel(moduleModel), applicationModel); - Assertions.assertThrows(IllegalArgumentException.class, () -> ScopeModelUtil.getApplicationModel(frameworkModel)); + Assertions.assertThrows( + IllegalArgumentException.class, () -> ScopeModelUtil.getApplicationModel(frameworkModel)); - Assertions.assertEquals(ScopeModelUtil.getModuleModel(null), ApplicationModel.defaultModel().getDefaultModule()); + Assertions.assertEquals( + ScopeModelUtil.getModuleModel(null), + ApplicationModel.defaultModel().getDefaultModule()); Assertions.assertEquals(ScopeModelUtil.getModuleModel(moduleModel), moduleModel); Assertions.assertThrows(IllegalArgumentException.class, () -> ScopeModelUtil.getModuleModel(frameworkModel)); Assertions.assertThrows(IllegalArgumentException.class, () -> ScopeModelUtil.getModuleModel(applicationModel)); Assertions.assertEquals(ScopeModelUtil.getOrDefault(null, SPIDemo1.class), FrameworkModel.defaultModel()); Assertions.assertEquals(ScopeModelUtil.getOrDefault(null, SPIDemo2.class), ApplicationModel.defaultModel()); - Assertions.assertEquals(ScopeModelUtil.getOrDefault(null, SPIDemo3.class), ApplicationModel.defaultModel().getDefaultModule()); - Assertions.assertThrows(IllegalArgumentException.class, () -> ScopeModelUtil.getOrDefault(null, SPIDemo4.class)); + Assertions.assertEquals( + ScopeModelUtil.getOrDefault(null, SPIDemo3.class), + ApplicationModel.defaultModel().getDefaultModule()); + Assertions.assertThrows( + IllegalArgumentException.class, () -> ScopeModelUtil.getOrDefault(null, SPIDemo4.class)); - Assertions.assertEquals(ScopeModelUtil.getExtensionLoader(SPIDemo1.class, null), FrameworkModel.defaultModel().getExtensionLoader(SPIDemo1.class)); - Assertions.assertEquals(ScopeModelUtil.getExtensionLoader(SPIDemo2.class, null), ApplicationModel.defaultModel().getExtensionLoader(SPIDemo2.class)); - Assertions.assertEquals(ScopeModelUtil.getExtensionLoader(SPIDemo3.class, null), ApplicationModel.defaultModel().getDefaultModule().getExtensionLoader(SPIDemo3.class)); - Assertions.assertThrows(IllegalArgumentException.class, () -> ScopeModelUtil.getExtensionLoader(SPIDemo4.class, null)); + Assertions.assertEquals( + ScopeModelUtil.getExtensionLoader(SPIDemo1.class, null), + FrameworkModel.defaultModel().getExtensionLoader(SPIDemo1.class)); + Assertions.assertEquals( + ScopeModelUtil.getExtensionLoader(SPIDemo2.class, null), + ApplicationModel.defaultModel().getExtensionLoader(SPIDemo2.class)); + Assertions.assertEquals( + ScopeModelUtil.getExtensionLoader(SPIDemo3.class, null), + ApplicationModel.defaultModel().getDefaultModule().getExtensionLoader(SPIDemo3.class)); + Assertions.assertThrows( + IllegalArgumentException.class, () -> ScopeModelUtil.getExtensionLoader(SPIDemo4.class, null)); } - @SPI(scope = ExtensionScope.FRAMEWORK) - interface SPIDemo1 { - - } + interface SPIDemo1 {} @SPI(scope = ExtensionScope.APPLICATION) - interface SPIDemo2 { - - } + interface SPIDemo2 {} @SPI(scope = ExtensionScope.MODULE) - interface SPIDemo3 { + interface SPIDemo3 {} - } - - interface SPIDemo4 { - - } + interface SPIDemo4 {} class MockScopeModel extends ScopeModel { public MockScopeModel(ScopeModel parent, ExtensionScope scope) { @@ -103,9 +108,7 @@ class ScopeModelUtilTest { } @Override - protected void onDestroy() { - - } + protected void onDestroy() {} @Override public Environment modelEnvironment() { @@ -117,5 +120,4 @@ class ScopeModelUtilTest { return null; } } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/SerializablePerson.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/SerializablePerson.java index 6fff76c133..dc9848ede9 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/SerializablePerson.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/SerializablePerson.java @@ -76,22 +76,15 @@ public class SerializablePerson implements Serializable { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; SerializablePerson other = (SerializablePerson) obj; - if (age != other.age) - return false; + if (age != other.age) return false; if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (!Arrays.equals(value, other.value)) - return false; + if (other.name != null) return false; + } else if (!name.equals(other.name)) return false; + if (!Arrays.equals(value, other.value)) return false; return true; } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ServiceRepositoryTest.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ServiceRepositoryTest.java index d7490c0333..6d29ea5be0 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ServiceRepositoryTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/ServiceRepositoryTest.java @@ -20,15 +20,15 @@ import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.rpc.support.DemoService; import org.apache.dubbo.rpc.support.DemoServiceImpl; +import java.util.Collection; +import java.util.List; +import java.util.Set; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Collection; -import java.util.List; -import java.util.Set; - /** * {@link ServiceRepository} */ @@ -52,28 +52,38 @@ class ServiceRepositoryTest { @Test void test() { // verify BuiltinService - Set builtinServices - = applicationModel.getExtensionLoader(BuiltinServiceDetector.class).getSupportedExtensionInstances(); - ModuleServiceRepository moduleServiceRepository = applicationModel.getInternalModule().getServiceRepository(); + Set builtinServices = applicationModel + .getExtensionLoader(BuiltinServiceDetector.class) + .getSupportedExtensionInstances(); + ModuleServiceRepository moduleServiceRepository = + applicationModel.getInternalModule().getServiceRepository(); List allServices = moduleServiceRepository.getAllServices(); Assertions.assertEquals(allServices.size(), builtinServices.size()); ModuleServiceRepository repository = moduleModel.getServiceRepository(); - ServiceMetadata serviceMetadata = new ServiceMetadata(DemoService.class.getName(), null, null, DemoService.class); + ServiceMetadata serviceMetadata = + new ServiceMetadata(DemoService.class.getName(), null, null, DemoService.class); ServiceDescriptor serviceDescriptor = repository.registerService(DemoService.class); // registerConsumer ConsumerModel consumerModel = new ConsumerModel( - serviceMetadata.getServiceKey(), new DemoServiceImpl(), serviceDescriptor, - moduleModel, serviceMetadata, null, ClassUtils.getClassLoader(DemoService.class)); + serviceMetadata.getServiceKey(), + new DemoServiceImpl(), + serviceDescriptor, + moduleModel, + serviceMetadata, + null, + ClassUtils.getClassLoader(DemoService.class)); repository.registerConsumer(consumerModel); // registerProvider - ProviderModel providerModel = new ProviderModel(DemoService.class.getName(), - new DemoServiceImpl(), - serviceDescriptor, - moduleModel, - serviceMetadata, ClassUtils.getClassLoader(DemoService.class)); + ProviderModel providerModel = new ProviderModel( + DemoService.class.getName(), + new DemoServiceImpl(), + serviceDescriptor, + moduleModel, + serviceMetadata, + ClassUtils.getClassLoader(DemoService.class)); repository.registerProvider(providerModel); // verify allProviderModels, allConsumerModels @@ -85,7 +95,5 @@ class ServiceRepositoryTest { Collection consumerModels = serviceRepository.allConsumerModels(); Assertions.assertEquals(consumerModels.size(), 1); Assertions.assertTrue(consumerModels.contains(consumerModel)); - } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/User.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/User.java index 68db5a727c..cf55802c9f 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/User.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/User.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.model; import java.util.Objects; diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/media/Image.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/media/Image.java index c9df833555..f9a885cf82 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/media/Image.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/media/Image.java @@ -16,17 +16,15 @@ */ package org.apache.dubbo.rpc.model.media; - public class Image implements java.io.Serializable { private static final long serialVersionUID = 1L; public String uri; - public String title; // Can be null + public String title; // Can be null public int width; public int height; public Size size; - public Image() { - } + public Image() {} public Image(String uri, String title, int width, int height, Size size) { this.height = height; @@ -115,6 +113,7 @@ public class Image implements java.io.Serializable { } public enum Size { - SMALL, LARGE + SMALL, + LARGE } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/media/Media.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/media/Media.java index 7987460a61..59f856f094 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/media/Media.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/media/Media.java @@ -21,22 +21,33 @@ import java.util.List; @SuppressWarnings("serial") public class Media implements java.io.Serializable { public String uri; - public String title; // Can be unset. + public String title; // Can be unset. public int width; public int height; public String format; public long duration; public long size; - public int bitrate; // Can be unset. + public int bitrate; // Can be unset. public boolean hasBitrate; public List persons; public Player player; - public String copyright; // Can be unset. + public String copyright; // Can be unset. - public Media() { - } + public Media() {} - public Media(String uri, String title, int width, int height, String format, long duration, long size, int bitrate, boolean hasBitrate, List persons, Player player, String copyright) { + public Media( + String uri, + String title, + int width, + int height, + String format, + long duration, + long size, + int bitrate, + boolean hasBitrate, + List persons, + Player player, + String copyright) { this.uri = uri; this.title = title; this.width = width; @@ -200,6 +211,7 @@ public class Media implements java.io.Serializable { } public enum Player { - JAVA, FLASH + JAVA, + FLASH } } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/person/BigPerson.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/person/BigPerson.java index 3c24fd9f95..b80e91ece3 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/person/BigPerson.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/person/BigPerson.java @@ -33,9 +33,7 @@ public class BigPerson implements Serializable { PersonInfo infoProfile; - public BigPerson() { - - } + public BigPerson() {} public BigPerson(String id) { this.personId = id; @@ -104,40 +102,26 @@ public class BigPerson implements Serializable { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; BigPerson other = (BigPerson) obj; if (email == null) { - if (other.email != null) - return false; - } else if (!email.equals(other.email)) - return false; + if (other.email != null) return false; + } else if (!email.equals(other.email)) return false; if (infoProfile == null) { - if (other.infoProfile != null) - return false; - } else if (!infoProfile.equals(other.infoProfile)) - return false; + if (other.infoProfile != null) return false; + } else if (!infoProfile.equals(other.infoProfile)) return false; if (loginName == null) { - if (other.loginName != null) - return false; - } else if (!loginName.equals(other.loginName)) - return false; + if (other.loginName != null) return false; + } else if (!loginName.equals(other.loginName)) return false; if (penName == null) { - if (other.penName != null) - return false; - } else if (!penName.equals(other.penName)) - return false; + if (other.penName != null) return false; + } else if (!penName.equals(other.penName)) return false; if (personId == null) { - if (other.personId != null) - return false; - } else if (!personId.equals(other.personId)) - return false; - if (status != other.status) - return false; + if (other.personId != null) return false; + } else if (!personId.equals(other.personId)) return false; + if (status != other.status) return false; return true; } @@ -147,5 +131,4 @@ public class BigPerson implements Serializable { + status + ", email=" + email + ", penName=" + penName + ", infoProfile=" + infoProfile + "]"; } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/person/FullAddress.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/person/FullAddress.java index dfbb56fa17..26288df28e 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/person/FullAddress.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/person/FullAddress.java @@ -36,11 +36,9 @@ public class FullAddress implements Serializable { private String zipCode; - public FullAddress() { - } + public FullAddress() {} - public FullAddress(String countryId, String provinceName, String cityId, String streetAddress, - String zipCode) { + public FullAddress(String countryId, String provinceName, String cityId, String streetAddress, String zipCode) { this.countryId = countryId; this.countryName = countryId; this.provinceName = provinceName; @@ -50,8 +48,14 @@ public class FullAddress implements Serializable { this.zipCode = zipCode; } - public FullAddress(String countryId, String countryName, String provinceName, String cityId, - String cityName, String streetAddress, String zipCode) { + public FullAddress( + String countryId, + String countryName, + String provinceName, + String cityId, + String cityName, + String streetAddress, + String zipCode) { this.countryId = countryId; this.countryName = countryName; this.provinceName = provinceName; @@ -133,48 +137,31 @@ public class FullAddress implements Serializable { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; FullAddress other = (FullAddress) obj; if (cityId == null) { - if (other.cityId != null) - return false; - } else if (!cityId.equals(other.cityId)) - return false; + if (other.cityId != null) return false; + } else if (!cityId.equals(other.cityId)) return false; if (cityName == null) { - if (other.cityName != null) - return false; - } else if (!cityName.equals(other.cityName)) - return false; + if (other.cityName != null) return false; + } else if (!cityName.equals(other.cityName)) return false; if (countryId == null) { - if (other.countryId != null) - return false; - } else if (!countryId.equals(other.countryId)) - return false; + if (other.countryId != null) return false; + } else if (!countryId.equals(other.countryId)) return false; if (countryName == null) { - if (other.countryName != null) - return false; - } else if (!countryName.equals(other.countryName)) - return false; + if (other.countryName != null) return false; + } else if (!countryName.equals(other.countryName)) return false; if (provinceName == null) { - if (other.provinceName != null) - return false; - } else if (!provinceName.equals(other.provinceName)) - return false; + if (other.provinceName != null) return false; + } else if (!provinceName.equals(other.provinceName)) return false; if (streetAddress == null) { - if (other.streetAddress != null) - return false; - } else if (!streetAddress.equals(other.streetAddress)) - return false; + if (other.streetAddress != null) return false; + } else if (!streetAddress.equals(other.streetAddress)) return false; if (zipCode == null) { - if (other.zipCode != null) - return false; - } else if (!zipCode.equals(other.zipCode)) - return false; + if (other.zipCode != null) return false; + } else if (!zipCode.equals(other.zipCode)) return false; return true; } @@ -198,5 +185,4 @@ public class FullAddress implements Serializable { } return sb.toString(); } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/person/PersonInfo.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/person/PersonInfo.java index 57f156b660..9b7aaf9d7b 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/person/PersonInfo.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/person/PersonInfo.java @@ -141,57 +141,36 @@ public class PersonInfo implements Serializable { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; PersonInfo other = (PersonInfo) obj; if (department == null) { - if (other.department != null) - return false; - } else if (!department.equals(other.department)) - return false; + if (other.department != null) return false; + } else if (!department.equals(other.department)) return false; if (fax == null) { - if (other.fax != null) - return false; - } else if (!fax.equals(other.fax)) - return false; - if (female != other.female) - return false; + if (other.fax != null) return false; + } else if (!fax.equals(other.fax)) return false; + if (female != other.female) return false; if (fullAddress == null) { - if (other.fullAddress != null) - return false; - } else if (!fullAddress.equals(other.fullAddress)) - return false; + if (other.fullAddress != null) return false; + } else if (!fullAddress.equals(other.fullAddress)) return false; if (homepageUrl == null) { - if (other.homepageUrl != null) - return false; - } else if (!homepageUrl.equals(other.homepageUrl)) - return false; + if (other.homepageUrl != null) return false; + } else if (!homepageUrl.equals(other.homepageUrl)) return false; if (jobTitle == null) { - if (other.jobTitle != null) - return false; - } else if (!jobTitle.equals(other.jobTitle)) - return false; - if (male != other.male) - return false; + if (other.jobTitle != null) return false; + } else if (!jobTitle.equals(other.jobTitle)) return false; + if (male != other.male) return false; if (mobileNo == null) { - if (other.mobileNo != null) - return false; - } else if (!mobileNo.equals(other.mobileNo)) - return false; + if (other.mobileNo != null) return false; + } else if (!mobileNo.equals(other.mobileNo)) return false; if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; + if (other.name != null) return false; + } else if (!name.equals(other.name)) return false; if (phones == null) { - if (other.phones != null) - return false; - } else if (!phones.equals(other.phones)) - return false; + if (other.phones != null) return false; + } else if (!phones.equals(other.phones)) return false; return true; } @@ -202,5 +181,4 @@ public class PersonInfo implements Serializable { + female + ", department=" + department + ", jobTitle=" + jobTitle + ", homepageUrl=" + homepageUrl + "]"; } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/person/Phone.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/person/Phone.java index ee18ade41d..523fac549c 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/person/Phone.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/model/person/Phone.java @@ -30,8 +30,7 @@ public class Phone implements Serializable { private String extensionNumber; - public Phone() { - } + public Phone() {} public Phone(String country, String area, String number, String extensionNumber) { this.country = country; @@ -85,33 +84,22 @@ public class Phone implements Serializable { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; Phone other = (Phone) obj; if (area == null) { - if (other.area != null) - return false; - } else if (!area.equals(other.area)) - return false; + if (other.area != null) return false; + } else if (!area.equals(other.area)) return false; if (country == null) { - if (other.country != null) - return false; - } else if (!country.equals(other.country)) - return false; + if (other.country != null) return false; + } else if (!country.equals(other.country)) return false; if (extensionNumber == null) { - if (other.extensionNumber != null) - return false; - } else if (!extensionNumber.equals(other.extensionNumber)) - return false; + if (other.extensionNumber != null) return false; + } else if (!extensionNumber.equals(other.extensionNumber)) return false; if (number == null) { - if (other.number != null) - return false; - } else if (!number.equals(other.number)) - return false; + if (other.number != null) return false; + } else if (!number.equals(other.number)) return false; return true; } @@ -135,5 +123,4 @@ public class Phone implements Serializable { } return sb.toString(); } - } diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/service/GenericExceptionTest.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/service/GenericExceptionTest.java index 19e24c5d71..ed7a8f2657 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/service/GenericExceptionTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/service/GenericExceptionTest.java @@ -14,16 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.service; import org.apache.dubbo.common.utils.JsonUtils; +import java.io.IOException; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.io.IOException; - class GenericExceptionTest { @Test diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/service/ServiceDescriptorInternalCacheTest.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/service/ServiceDescriptorInternalCacheTest.java index 025122368f..1bfbd97e21 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/service/ServiceDescriptorInternalCacheTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/service/ServiceDescriptorInternalCacheTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.service; import org.junit.jupiter.api.Assertions; @@ -25,14 +24,15 @@ class ServiceDescriptorInternalCacheTest { @Test void genericService() { Assertions.assertNotNull(ServiceDescriptorInternalCache.genericService()); - Assertions.assertEquals(GenericService.class, - ServiceDescriptorInternalCache.genericService().getServiceInterfaceClass()); + Assertions.assertEquals( + GenericService.class, + ServiceDescriptorInternalCache.genericService().getServiceInterfaceClass()); } @Test void echoService() { Assertions.assertNotNull(ServiceDescriptorInternalCache.echoService()); - Assertions.assertEquals(EchoService.class, - ServiceDescriptorInternalCache.echoService().getServiceInterfaceClass()); + Assertions.assertEquals( + EchoService.class, ServiceDescriptorInternalCache.echoService().getServiceInterfaceClass()); } -} \ No newline at end of file +} diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/support/DemoService1Impl.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/support/DemoService1Impl.java index 7b5ec906fb..b19852cbe0 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/support/DemoService1Impl.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/support/DemoService1Impl.java @@ -18,7 +18,7 @@ package org.apache.dubbo.rpc.support; import org.apache.dubbo.common.stream.StreamObserver; -public class DemoService1Impl implements DemoService1{ +public class DemoService1Impl implements DemoService1 { @Override public StreamObserver sayHello(StreamObserver request) { request.onNext("BI_STREAM"); diff --git a/dubbo-common/src/test/java/org/apache/dubbo/rpc/support/ProtocolUtilsTest.java b/dubbo-common/src/test/java/org/apache/dubbo/rpc/support/ProtocolUtilsTest.java index d0cc3ae95c..8ea272749f 100644 --- a/dubbo-common/src/test/java/org/apache/dubbo/rpc/support/ProtocolUtilsTest.java +++ b/dubbo-common/src/test/java/org/apache/dubbo/rpc/support/ProtocolUtilsTest.java @@ -49,8 +49,7 @@ class ProtocolUtilsTest { private void assertServiceKey(int port, String serviceName, String serviceVersion, String serviceGroup) { Assertions.assertEquals( serviceKeyOldImpl(port, serviceName, serviceVersion, serviceGroup), - ProtocolUtils.serviceKey(port, serviceName, serviceVersion, serviceGroup) - ); + ProtocolUtils.serviceKey(port, serviceName, serviceVersion, serviceGroup)); } /** @@ -71,5 +70,4 @@ class ProtocolUtilsTest { buf.append(port); return buf.toString(); } - -} \ No newline at end of file +} diff --git a/dubbo-compatible/pom.xml b/dubbo-compatible/pom.xml index 1cdcf0d304..aaf41f29de 100644 --- a/dubbo-compatible/pom.xml +++ b/dubbo-compatible/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - org.apache.dubbo - dubbo-parent - ${revision} - ../pom.xml - - dubbo-compatible - jar - ${project.artifactId} - The compatible module of dubbo project - - - org.apache.dubbo - dubbo-config-spring - ${project.parent.version} - - - org.springframework - spring-tx - test - - - org.apache.dubbo - dubbo-qos - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-zookeeper - ${project.parent.version} - - - org.apache.dubbo - dubbo-rpc-rest - ${project.parent.version} - - - org.apache.dubbo - dubbo-filter-cache - ${project.parent.version} - - - org.apache.dubbo - dubbo-filter-validation - ${project.parent.version} - - - org.slf4j - slf4j-log4j12 - true - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-registry-multicast - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-metadata-processor - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-plugin-generic-invoke - ${project.parent.version} - test - - - com.alibaba - fastjson - test - - - org.apache.dubbo - dubbo-test-check - ${project.parent.version} - test - - + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + + dubbo-compatible + jar + ${project.artifactId} + The compatible module of dubbo project + + + org.apache.dubbo + dubbo-config-spring + ${project.parent.version} + + + org.springframework + spring-tx + test + + + org.apache.dubbo + dubbo-qos + ${project.parent.version} + + + org.apache.dubbo + dubbo-remoting-zookeeper + ${project.parent.version} + + + org.apache.dubbo + dubbo-rpc-rest + ${project.parent.version} + + + org.apache.dubbo + dubbo-filter-cache + ${project.parent.version} + + + org.apache.dubbo + dubbo-filter-validation + ${project.parent.version} + + + org.slf4j + slf4j-log4j12 + true + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-registry-multicast + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-metadata-processor + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-plugin-generic-invoke + ${project.parent.version} + test + + + com.alibaba + fastjson + test + + + org.apache.dubbo + dubbo-test-check + ${project.parent.version} + test + + diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/cache/Cache.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/cache/Cache.java index 62539d233e..44a0a67b58 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/cache/Cache.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/cache/Cache.java @@ -14,9 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.cache; @Deprecated -public interface Cache extends org.apache.dubbo.cache.Cache { -} +public interface Cache extends org.apache.dubbo.cache.Cache {} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/cache/CacheFactory.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/cache/CacheFactory.java index 626eed2b4e..83092a2a22 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/cache/CacheFactory.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/cache/CacheFactory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.cache; import com.alibaba.dubbo.common.DelegateURL; @@ -26,7 +25,8 @@ public interface CacheFactory extends org.apache.dubbo.cache.CacheFactory { Cache getCache(URL url, Invocation invocation); - default org.apache.dubbo.cache.Cache getCache(org.apache.dubbo.common.URL url, org.apache.dubbo.rpc.Invocation invocation) { + default org.apache.dubbo.cache.Cache getCache( + org.apache.dubbo.common.URL url, org.apache.dubbo.rpc.Invocation invocation) { return this.getCache(new DelegateURL(url), new Invocation.CompatibleInvocation(invocation)); } } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/cache/support/AbstractCacheFactory.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/cache/support/AbstractCacheFactory.java index 6ca184c660..05a9c25d52 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/cache/support/AbstractCacheFactory.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/cache/support/AbstractCacheFactory.java @@ -14,18 +14,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.cache.support; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + import com.alibaba.dubbo.cache.Cache; import com.alibaba.dubbo.cache.CacheFactory; import com.alibaba.dubbo.common.DelegateURL; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.rpc.Invocation; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; @Deprecated @@ -48,7 +47,8 @@ public abstract class AbstractCacheFactory implements CacheFactory { protected abstract Cache createCache(URL url); @Override - public org.apache.dubbo.cache.Cache getCache(org.apache.dubbo.common.URL url, org.apache.dubbo.rpc.Invocation invocation) { + public org.apache.dubbo.cache.Cache getCache( + org.apache.dubbo.common.URL url, org.apache.dubbo.rpc.Invocation invocation) { return getCache(new DelegateURL(url), new Invocation.CompatibleInvocation(invocation)); } } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java index 4ed46e5e23..9579e26d67 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/Constants.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.common; import org.apache.dubbo.common.constants.CommonConstants; @@ -27,22 +26,23 @@ import java.util.concurrent.ExecutorService; import java.util.regex.Pattern; @Deprecated -public class Constants implements CommonConstants, - QosConstants, - FilterConstants, - RegistryConstants, - RemotingConstants, - org.apache.dubbo.config.Constants, - org.apache.dubbo.remoting.Constants, - org.apache.dubbo.rpc.cluster.Constants, - org.apache.dubbo.monitor.Constants, - org.apache.dubbo.rpc.Constants, - org.apache.dubbo.rpc.protocol.dubbo.Constants, - org.apache.dubbo.common.serialize.Constants, - org.apache.dubbo.common.config.configcenter.Constants, - org.apache.dubbo.metadata.report.support.Constants, - org.apache.dubbo.rpc.protocol.rest.Constants, - org.apache.dubbo.registry.Constants { +public class Constants + implements CommonConstants, + QosConstants, + FilterConstants, + RegistryConstants, + RemotingConstants, + org.apache.dubbo.config.Constants, + org.apache.dubbo.remoting.Constants, + org.apache.dubbo.rpc.cluster.Constants, + org.apache.dubbo.monitor.Constants, + org.apache.dubbo.rpc.Constants, + org.apache.dubbo.rpc.protocol.dubbo.Constants, + org.apache.dubbo.common.serialize.Constants, + org.apache.dubbo.common.config.configcenter.Constants, + org.apache.dubbo.metadata.report.support.Constants, + org.apache.dubbo.rpc.protocol.rest.Constants, + org.apache.dubbo.registry.Constants { public static final String PROVIDER = "provider"; public static final String CONSUMER = "consumer"; @@ -91,8 +91,7 @@ public class Constants implements CommonConstants, public static final String $ECHO = "$echo"; - public static final int DEFAULT_IO_THREADS = Runtime.getRuntime() - .availableProcessors() + 1; + public static final int DEFAULT_IO_THREADS = Runtime.getRuntime().availableProcessors() + 1; public static final String DEFAULT_PROXY = "javassist"; @@ -354,20 +353,17 @@ public class Constants implements CommonConstants, public static final String COMMA_SEPARATOR = ","; - public static final Pattern COMMA_SPLIT_PATTERN = Pattern - .compile("\\s*[,]+\\s*"); + public static final Pattern COMMA_SPLIT_PATTERN = Pattern.compile("\\s*[,]+\\s*"); - public final static String PATH_SEPARATOR = "/"; + public static final String PATH_SEPARATOR = "/"; public static final String REGISTRY_SEPARATOR = "|"; - public static final Pattern REGISTRY_SPLIT_PATTERN = Pattern - .compile("\\s*[|;]+\\s*"); + public static final Pattern REGISTRY_SPLIT_PATTERN = Pattern.compile("\\s*[|;]+\\s*"); public static final String SEMICOLON_SEPARATOR = ";"; - public static final Pattern SEMICOLON_SPLIT_PATTERN = Pattern - .compile("\\s*[;]+\\s*"); + public static final Pattern SEMICOLON_SPLIT_PATTERN = Pattern.compile("\\s*[;]+\\s*"); public static final String CONNECT_QUEUE_CAPACITY = "connect.queue.capacity"; diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/DelegateURL.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/DelegateURL.java index 2825e89cea..918b7d8a92 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/DelegateURL.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/DelegateURL.java @@ -778,7 +778,8 @@ public class DelegateURL extends com.alibaba.dubbo.common.URL { return apacheUrl.equals(obj); } - public static void putMethodParameter(String method, String key, String value, Map> methodParameters) { + public static void putMethodParameter( + String method, String key, String value, Map> methodParameters) { org.apache.dubbo.common.URL.putMethodParameter(method, key, value, methodParameters); } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/URL.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/URL.java index 3491c841d5..4809d5168d 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/URL.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/URL.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.common; import org.apache.dubbo.common.utils.CollectionUtils; @@ -32,7 +31,14 @@ public class URL extends org.apache.dubbo.common.URL { } public URL(org.apache.dubbo.common.URL url) { - super(url.getProtocol(), url.getUsername(), url.getPassword(), url.getHost(), url.getPort(), url.getPath(), url.getParameters()); + super( + url.getProtocol(), + url.getUsername(), + url.getPassword(), + url.getHost(), + url.getPort(), + url.getPath(), + url.getParameters()); } public URL(String protocol, String host, int port) { @@ -67,7 +73,14 @@ public class URL extends org.apache.dubbo.common.URL { super(protocol, username, password, host, port, path, CollectionUtils.toStringMap(pairs)); } - public URL(String protocol, String username, String password, String host, int port, String path, Map parameters) { + public URL( + String protocol, + String username, + String password, + String host, + int port, + String path, + Map parameters) { super(protocol, username, password, host, port, path, parameters); } @@ -91,7 +104,14 @@ public class URL extends org.apache.dubbo.common.URL { @Override public URL setProtocol(String protocol) { - return new URL(protocol, super.getUsername(), super.getPassword(), super.getHost(), super.getPort(), super.getPath(), super.getParameters()); + return new URL( + protocol, + super.getUsername(), + super.getPassword(), + super.getHost(), + super.getPort(), + super.getPath(), + super.getParameters()); } @Override @@ -101,7 +121,14 @@ public class URL extends org.apache.dubbo.common.URL { @Override public URL setUsername(String username) { - return new URL(super.getProtocol(), username, super.getPassword(), super.getHost(), super.getPort(), super.getPath(), super.getParameters()); + return new URL( + super.getProtocol(), + username, + super.getPassword(), + super.getHost(), + super.getPort(), + super.getPath(), + super.getParameters()); } @Override @@ -111,7 +138,14 @@ public class URL extends org.apache.dubbo.common.URL { @Override public URL setPassword(String password) { - return new URL(super.getProtocol(), super.getUsername(), password, super.getHost(), super.getPort(), super.getPath(), super.getParameters()); + return new URL( + super.getProtocol(), + super.getUsername(), + password, + super.getHost(), + super.getPort(), + super.getPath(), + super.getParameters()); } @Override @@ -127,7 +161,14 @@ public class URL extends org.apache.dubbo.common.URL { @Override public URL setHost(String host) { - return new URL(super.getProtocol(), super.getUsername(), super.getPassword(), host, super.getPort(), super.getPath(), super.getParameters()); + return new URL( + super.getProtocol(), + super.getUsername(), + super.getPassword(), + host, + super.getPort(), + super.getPath(), + super.getParameters()); } @Override @@ -142,7 +183,14 @@ public class URL extends org.apache.dubbo.common.URL { @Override public URL setPort(int port) { - return new URL(super.getProtocol(), super.getUsername(), super.getPassword(), super.getHost(), port, super.getPath(), super.getParameters()); + return new URL( + super.getProtocol(), + super.getUsername(), + super.getPassword(), + super.getHost(), + port, + super.getPath(), + super.getParameters()); } @Override @@ -171,10 +219,10 @@ public class URL extends org.apache.dubbo.common.URL { return super.getBackupAddress(defaultPort); } -// public List getBackupUrls() { -// List res = super.getBackupUrls(); -// return res.stream().map(url -> new URL(url)).collect(Collectors.toList()); -// } + // public List getBackupUrls() { + // List res = super.getBackupUrls(); + // return res.stream().map(url -> new URL(url)).collect(Collectors.toList()); + // } @Override public String getPath() { @@ -183,7 +231,14 @@ public class URL extends org.apache.dubbo.common.URL { @Override public URL setPath(String path) { - return new URL(super.getProtocol(), super.getUsername(), super.getPassword(), super.getHost(), super.getPort(), path, super.getParameters()); + return new URL( + super.getProtocol(), + super.getUsername(), + super.getPassword(), + super.getHost(), + super.getPort(), + path, + super.getParameters()); } @Override @@ -626,7 +681,13 @@ public class URL extends org.apache.dubbo.common.URL { } public org.apache.dubbo.common.URL getOriginalURL() { - return new org.apache.dubbo.common.URL(super.getProtocol(), super.getUsername(), super.getPassword(), - super.getHost(), super.getPort(), super.getPath(), super.getParameters()); + return new org.apache.dubbo.common.URL( + super.getProtocol(), + super.getUsername(), + super.getPassword(), + super.getHost(), + super.getPort(), + super.getPath(), + super.getParameters()); } } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/compiler/Compiler.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/compiler/Compiler.java index 548a6ab9a6..eaac5445e4 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/compiler/Compiler.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/compiler/Compiler.java @@ -14,9 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.common.compiler; @Deprecated -public interface Compiler extends org.apache.dubbo.common.compiler.Compiler { -} +public interface Compiler extends org.apache.dubbo.common.compiler.Compiler {} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/extension/Activate.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/extension/Activate.java index 875e25b602..4cf96d7227 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/extension/Activate.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/extension/Activate.java @@ -48,5 +48,4 @@ public @interface Activate { * @return className names to all match */ String[] onClass() default {}; - } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/extension/ExtensionFactory.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/extension/ExtensionFactory.java index bd98ea2e77..a5efb0e524 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/extension/ExtensionFactory.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/extension/ExtensionFactory.java @@ -21,5 +21,4 @@ import org.apache.dubbo.common.extension.SPI; @Deprecated @SPI(scope = ExtensionScope.FRAMEWORK) -public interface ExtensionFactory extends org.apache.dubbo.common.extension.ExtensionFactory { -} +public interface ExtensionFactory extends org.apache.dubbo.common.extension.ExtensionFactory {} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/logger/LoggerAdapter.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/logger/LoggerAdapter.java index ed26a62034..e8dff684c8 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/logger/LoggerAdapter.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/logger/LoggerAdapter.java @@ -14,9 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.common.logger; @Deprecated -public interface LoggerAdapter extends org.apache.dubbo.common.logger.LoggerAdapter { -} +public interface LoggerAdapter extends org.apache.dubbo.common.logger.LoggerAdapter {} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/serialize/ObjectInput.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/serialize/ObjectInput.java index a6caf8828e..c6167fd7dd 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/serialize/ObjectInput.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/serialize/ObjectInput.java @@ -14,9 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.common.serialize; @Deprecated -public interface ObjectInput extends org.apache.dubbo.common.serialize.ObjectInput { -} +public interface ObjectInput extends org.apache.dubbo.common.serialize.ObjectInput {} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/serialize/ObjectOutput.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/serialize/ObjectOutput.java index 5d57dc7762..39c81e807e 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/serialize/ObjectOutput.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/serialize/ObjectOutput.java @@ -14,9 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.common.serialize; @Deprecated -public interface ObjectOutput extends org.apache.dubbo.common.serialize.ObjectOutput { -} +public interface ObjectOutput extends org.apache.dubbo.common.serialize.ObjectOutput {} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/serialize/Serialization.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/serialize/Serialization.java index dc82b3195f..45b6bca868 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/serialize/Serialization.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/serialize/Serialization.java @@ -14,16 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.common.serialize; -import com.alibaba.dubbo.common.DelegateURL; -import com.alibaba.dubbo.common.URL; - import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import com.alibaba.dubbo.common.DelegateURL; +import com.alibaba.dubbo.common.URL; + @Deprecated public interface Serialization extends org.apache.dubbo.common.serialize.Serialization { @@ -32,12 +31,14 @@ public interface Serialization extends org.apache.dubbo.common.serialize.Seriali ObjectInput deserialize(URL url, InputStream input) throws IOException; @Override - default org.apache.dubbo.common.serialize.ObjectOutput serialize(org.apache.dubbo.common.URL url, OutputStream output) throws IOException { + default org.apache.dubbo.common.serialize.ObjectOutput serialize( + org.apache.dubbo.common.URL url, OutputStream output) throws IOException { return this.serialize(new DelegateURL(url), output); } @Override - default org.apache.dubbo.common.serialize.ObjectInput deserialize(org.apache.dubbo.common.URL url, InputStream input) throws IOException { + default org.apache.dubbo.common.serialize.ObjectInput deserialize( + org.apache.dubbo.common.URL url, InputStream input) throws IOException { return this.deserialize(new DelegateURL(url), input); } } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/status/Status.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/status/Status.java index 04600acf3c..f83369a2e4 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/status/Status.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/status/Status.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.common.status; @Deprecated diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/status/StatusChecker.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/status/StatusChecker.java index 3f74c133ff..5c4b4300e1 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/status/StatusChecker.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/status/StatusChecker.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.common.status; @Deprecated diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/store/DataStore.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/store/DataStore.java index 81a25a8c4f..c08b87fa40 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/store/DataStore.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/store/DataStore.java @@ -14,9 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.common.store; @Deprecated -public interface DataStore extends org.apache.dubbo.common.store.DataStore { -} +public interface DataStore extends org.apache.dubbo.common.store.DataStore {} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/threadpool/ThreadPool.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/threadpool/ThreadPool.java index da4adf80ba..6af6fefb20 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/threadpool/ThreadPool.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/threadpool/ThreadPool.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.common.threadpool; import org.apache.dubbo.common.URL; diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java index aec0f871b7..92bb1968c0 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/common/utils/UrlUtils.java @@ -16,14 +16,14 @@ */ package com.alibaba.dubbo.common.utils; -import com.alibaba.dubbo.common.DelegateURL; -import com.alibaba.dubbo.common.URL; - import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; +import com.alibaba.dubbo.common.DelegateURL; +import com.alibaba.dubbo.common.URL; + /** * 2019-04-17 */ @@ -35,7 +35,9 @@ public class UrlUtils { } public static List parseURLs(String address, Map defaults) { - return org.apache.dubbo.common.utils.UrlUtils.parseURLs(address, defaults).stream().map(e -> new DelegateURL(e)).collect(Collectors.toList()); + return org.apache.dubbo.common.utils.UrlUtils.parseURLs(address, defaults).stream() + .map(e -> new DelegateURL(e)) + .collect(Collectors.toList()); } public static Map> convertRegister(Map> register) { @@ -58,9 +60,10 @@ public class UrlUtils { return org.apache.dubbo.common.utils.UrlUtils.revertNotify(notify); } - //compatible for dubbo-2.0.0 + // compatible for dubbo-2.0.0 public static List revertForbid(List forbid, Set subscribed) { - Set urls = subscribed.stream().map(e -> e.getOriginalURL()).collect(Collectors.toSet()); + Set urls = + subscribed.stream().map(e -> e.getOriginalURL()).collect(Collectors.toSet()); return org.apache.dubbo.common.utils.UrlUtils.revertForbid(forbid, urls); } @@ -73,7 +76,8 @@ public class UrlUtils { } public static boolean isMatch(URL consumerUrl, URL providerUrl) { - return org.apache.dubbo.common.utils.UrlUtils.isMatch(consumerUrl.getOriginalURL(), providerUrl.getOriginalURL()); + return org.apache.dubbo.common.utils.UrlUtils.isMatch( + consumerUrl.getOriginalURL(), providerUrl.getOriginalURL()); } public static boolean isMatchGlobPattern(String pattern, String value, URL param) { @@ -85,10 +89,10 @@ public class UrlUtils { } public static boolean isServiceKeyMatch(URL pattern, URL value) { - return org.apache.dubbo.common.utils.UrlUtils.isServiceKeyMatch(pattern.getOriginalURL(), value.getOriginalURL()); + return org.apache.dubbo.common.utils.UrlUtils.isServiceKeyMatch( + pattern.getOriginalURL(), value.getOriginalURL()); } - public static boolean isConfigurator(URL url) { return org.apache.dubbo.common.utils.UrlUtils.isConfigurator(url.getOriginalURL()); } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ApplicationConfig.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ApplicationConfig.java index ab5f8c2fa8..ddb4a61d01 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ApplicationConfig.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ApplicationConfig.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.config; @Deprecated diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ArgumentConfig.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ArgumentConfig.java index 2ba33bbdf4..f65bb0c198 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ArgumentConfig.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ArgumentConfig.java @@ -14,9 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.config; @Deprecated -public class ArgumentConfig extends org.apache.dubbo.config.ArgumentConfig { -} +public class ArgumentConfig extends org.apache.dubbo.config.ArgumentConfig {} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ConsumerConfig.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ConsumerConfig.java index 3c24db1d2a..6ba119b77a 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ConsumerConfig.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ConsumerConfig.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.config; @Deprecated diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/MethodConfig.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/MethodConfig.java index ff368c7011..528846ef0f 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/MethodConfig.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/MethodConfig.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.config; @Deprecated diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ModuleConfig.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ModuleConfig.java index 3b122efc56..8472cdd360 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ModuleConfig.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ModuleConfig.java @@ -14,14 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.config; @Deprecated public class ModuleConfig extends org.apache.dubbo.config.ModuleConfig { - public ModuleConfig() { - } + public ModuleConfig() {} public ModuleConfig(String name) { super(name); diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/MonitorConfig.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/MonitorConfig.java index 0c5d17525b..fac470dd77 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/MonitorConfig.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/MonitorConfig.java @@ -14,13 +14,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.config; @Deprecated public class MonitorConfig extends org.apache.dubbo.config.MonitorConfig { - public MonitorConfig() { - } + public MonitorConfig() {} public MonitorConfig(String address) { super(address); diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java index 3f716c3480..4cdcb25c6b 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java @@ -14,14 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.config; @Deprecated public class ProtocolConfig extends org.apache.dubbo.config.ProtocolConfig { - public ProtocolConfig() { - } + public ProtocolConfig() {} public ProtocolConfig(String name) { super(name); @@ -34,6 +32,4 @@ public class ProtocolConfig extends org.apache.dubbo.config.ProtocolConfig { public void mergeProtocol(ProtocolConfig sourceConfig) { super.mergeProtocol(sourceConfig); } - - } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java index f7ff0c345c..d6a91e73f9 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.config; @Deprecated diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java index 1e40b6f4c9..35db9e9c68 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.config; import org.apache.dubbo.config.annotation.Reference; @@ -22,8 +21,7 @@ import org.apache.dubbo.config.annotation.Reference; @Deprecated public class ReferenceConfig extends org.apache.dubbo.config.ReferenceConfig { - public ReferenceConfig() { - } + public ReferenceConfig() {} public ReferenceConfig(Reference reference) { super(reference); diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/RegistryConfig.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/RegistryConfig.java index 501f918ba0..4da493f764 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/RegistryConfig.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/RegistryConfig.java @@ -14,14 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.config; @Deprecated public class RegistryConfig extends org.apache.dubbo.config.RegistryConfig { - public RegistryConfig() { - } + public RegistryConfig() {} public RegistryConfig(String address) { super(address); diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java index e874a59798..fbd752f358 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.config; import org.apache.dubbo.config.annotation.Service; @@ -25,8 +24,7 @@ import java.util.List; @Deprecated public class ServiceConfig extends org.apache.dubbo.config.ServiceConfig { - public ServiceConfig() { - } + public ServiceConfig() {} public ServiceConfig(Service service) { super(service); @@ -60,8 +58,8 @@ public class ServiceConfig extends org.apache.dubbo.config.ServiceConfig { if (monitorConfig instanceof com.alibaba.dubbo.config.MonitorConfig) { return (com.alibaba.dubbo.config.MonitorConfig) monitorConfig; } - throw new IllegalArgumentException("Monitor has not been set with type com.alibaba.dubbo.config.MonitorConfig. " + - "Found " + monitorConfig.getClass().getName() + " instead."); + throw new IllegalArgumentException("Monitor has not been set with type com.alibaba.dubbo.config.MonitorConfig. " + + "Found " + monitorConfig.getClass().getName() + " instead."); } public void setMonitor(com.alibaba.dubbo.config.MonitorConfig monitor) { diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/annotation/Reference.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/annotation/Reference.java index ae28c751a1..9cc65f7595 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/annotation/Reference.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/annotation/Reference.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.config.annotation; import org.apache.dubbo.config.annotation.DubboReference; @@ -127,6 +126,4 @@ public @interface Reference { String monitor() default ""; String[] registry() default {}; - } - diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/annotation/Service.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/annotation/Service.java index 5de941fa33..84da43fae7 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/annotation/Service.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/annotation/Service.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.config.annotation; import org.apache.dubbo.config.annotation.DubboService; @@ -129,5 +128,4 @@ public @interface Service { String monitor() default ""; String[] registry() default {}; - } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/spring/context/annotation/EnableDubbo.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/spring/context/annotation/EnableDubbo.java index bb13c8732b..e9d6380c7a 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/spring/context/annotation/EnableDubbo.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/config/spring/context/annotation/EnableDubbo.java @@ -14,15 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.config.spring.context.annotation; import org.apache.dubbo.config.AbstractConfig; import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan; import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig; -import org.springframework.core.annotation.AliasFor; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; @@ -30,6 +27,8 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.springframework.core.annotation.AliasFor; + @Deprecated @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @@ -62,7 +61,6 @@ public @interface EnableDubbo { @AliasFor(annotation = DubboComponentScan.class, attribute = "basePackageClasses") Class[] scanBasePackageClasses() default {}; - /** * It indicates whether {@link AbstractConfig} binding to multiple Spring Beans. * @@ -71,5 +69,4 @@ public @interface EnableDubbo { */ @AliasFor(annotation = EnableDubboConfig.class, attribute = "multiple") boolean multipleConfig() default false; - } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/Container.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/Container.java index 4f236dd93a..51c50fd36b 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/Container.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/Container.java @@ -14,9 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.container; @Deprecated -public interface Container extends org.apache.dubbo.container.Container { -} +public interface Container extends org.apache.dubbo.container.Container {} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/Menu.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/Menu.java index fad7b52534..8905faf5b4 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/Menu.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/Menu.java @@ -35,5 +35,4 @@ public @interface Menu { String desc() default ""; int order() default 0; - } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/MenuComparator.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/MenuComparator.java index 645f9408be..e16196dfa8 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/MenuComparator.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/MenuComparator.java @@ -37,8 +37,11 @@ public class MenuComparator implements Comparator, Serializable { if (o2 == null) { return 1; } - return o1.equals(o2) ? 0 : (o1.getClass().getAnnotation(Menu.class).order() - > o2.getClass().getAnnotation(Menu.class).order() ? 1 : -1); + return o1.equals(o2) + ? 0 + : (o1.getClass().getAnnotation(Menu.class).order() + > o2.getClass().getAnnotation(Menu.class).order() + ? 1 + : -1); } - } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/Page.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/Page.java index 5583912c12..24042939a8 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/Page.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/Page.java @@ -37,18 +37,19 @@ public class Page { this(navigation, (String) null, (String[]) null, (List>) null); } - public Page(String navigation, String title, - String column, String row) { - this(navigation, title, column == null ? null : Arrays.asList(new String[]{column}), row == null ? null : stringToList(row)); + public Page(String navigation, String title, String column, String row) { + this( + navigation, + title, + column == null ? null : Arrays.asList(new String[] {column}), + row == null ? null : stringToList(row)); } - public Page(String navigation, String title, - String[] columns, List> rows) { + public Page(String navigation, String title, String[] columns, List> rows) { this(navigation, title, columns == null ? null : Arrays.asList(columns), rows); } - public Page(String navigation, String title, - List columns, List> rows) { + public Page(String navigation, String title, List columns, List> rows) { this.navigation = navigation; this.title = title; this.columns = columns; @@ -78,5 +79,4 @@ public class Page { public List> getRows() { return rows; } - } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/PageHandler.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/PageHandler.java index ac8fee7c55..e052888897 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/PageHandler.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/PageHandler.java @@ -16,7 +16,6 @@ */ package com.alibaba.dubbo.container.page; - import org.apache.dubbo.common.extension.SPI; import com.alibaba.dubbo.common.URL; @@ -34,5 +33,4 @@ public interface PageHandler { * @return the page. */ Page handle(URL url); - } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/PageServlet.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/PageServlet.java index 040101d282..25486c07ed 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/PageServlet.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/PageServlet.java @@ -21,13 +21,11 @@ import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; @@ -39,6 +37,9 @@ import java.util.Map; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; + /** * PageServlet */ @@ -71,7 +72,8 @@ public class PageServlet extends HttpServlet { names = ExtensionLoader.getExtensionLoader(PageHandler.class).getSupportedExtensions(); } for (String name : names) { - PageHandler handler = ExtensionLoader.getExtensionLoader(PageHandler.class).getExtension(name); + PageHandler handler = + ExtensionLoader.getExtensionLoader(PageHandler.class).getExtension(name); pages.put(ExtensionLoader.getExtensionLoader(PageHandler.class).getExtensionName(handler), handler); Menu menu = handler.getClass().getAnnotation(Menu.class); if (menu != null) { @@ -114,15 +116,17 @@ public class PageServlet extends HttpServlet { PageHandler pageHandler = pageHandlerLoader.hasExtension(uri) ? pageHandlerLoader.getExtension(uri) : null; if (isHtml) { writer.println("Dubbo"); - writer.println(""); + writer.println( + ""); writer.println(""); } if (pageHandler != null) { Page page = null; try { String query = request.getQueryString(); - page = pageHandler.handle(URL.valueOf(request.getRequestURL().toString() - + (query == null || query.length() == 0 ? "" : "?" + query))); + page = pageHandler.handle( + URL.valueOf(request.getRequestURL().toString() + + (query == null || query.length() == 0 ? "" : "?" + query))); } catch (Throwable t) { logger.warn(t.getMessage(), t); String msg = t.getMessage(); @@ -139,7 +143,8 @@ public class PageServlet extends HttpServlet { writer.println(""); writer.println(" "); writer.println(" "); - writer.println(" " + msg.replace("<", "<").replace(">", "<").replace("\n", "
")); + writer.println(" " + + msg.replace("<", "<").replace(">", "<").replace("\n", "
")); writer.println(" "); writer.println(" "); writer.println(""); @@ -153,15 +158,15 @@ public class PageServlet extends HttpServlet { if (isHtml) { String nav = page.getNavigation(); if (nav == null || nav.length() == 0) { - nav = ExtensionLoader.getExtensionLoader(PageHandler.class).getExtensionName(pageHandler); + nav = ExtensionLoader.getExtensionLoader(PageHandler.class) + .getExtensionName(pageHandler); nav = nav.substring(0, 1).toUpperCase() + nav.substring(1); } if (!"index".equals(uri)) { nav = "Home > " + nav; } writeMenu(request, writer, nav); - writeTable(writer, page.getTitle(), page.getColumns(), - page.getRows()); + writeTable(writer, page.getTitle(), page.getColumns(), page.getRows()); } else { if (page.getRows().size() > 0 && page.getRows().get(0).size() > 0) { writer.println(page.getRows().get(0).get(0)); @@ -218,10 +223,10 @@ public class PageServlet extends HttpServlet { writer.println("
"); } - protected final void writeTable(PrintWriter writer, String title, List columns, - List> rows) { + protected final void writeTable(PrintWriter writer, String title, List columns, List> rows) { int n = random.nextInt(); - int c = (columns == null ? (rows == null || rows.size() == 0 ? 0 : rows.get(0).size()) + int c = (columns == null + ? (rows == null || rows.size() == 0 ? 0 : rows.get(0).size()) : columns.size()); int r = (rows == null ? 0 : rows.size()); writer.println(""); @@ -264,8 +269,8 @@ public class PageServlet extends HttpServlet { writer.println(" "); int j = 0; for (String col : row) { - writer.println(" "); + writer.println(" "); j++; } writer.println(" "); @@ -276,5 +281,4 @@ public class PageServlet extends HttpServlet { writer.println("
" + col + "" + col + + "
"); writer.println("
"); } - } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/ResourceFilter.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/ResourceFilter.java index 3ffd172869..62f3da3d8e 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/ResourceFilter.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/ResourceFilter.java @@ -16,8 +16,6 @@ */ package com.alibaba.dubbo.container.page; -import com.alibaba.dubbo.common.Constants; - import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; @@ -26,6 +24,7 @@ import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; @@ -36,6 +35,8 @@ import java.net.URL; import java.util.ArrayList; import java.util.List; +import com.alibaba.dubbo.common.Constants; + /** * ResourceServlet */ @@ -63,8 +64,7 @@ public class ResourceFilter implements Filter { } } - public void destroy() { - } + public void destroy() {} public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { @@ -138,7 +138,9 @@ public class ResourceFilter implements Filter { if (isFile(path)) { return new FileInputStream(path); } else if (path.startsWith(CLASSPATH_PREFIX)) { - return Thread.currentThread().getContextClassLoader().getResourceAsStream(path.substring(CLASSPATH_PREFIX.length())); + return Thread.currentThread() + .getContextClassLoader() + .getResourceAsStream(path.substring(CLASSPATH_PREFIX.length())); } else { return new URL(path).openStream(); } @@ -147,5 +149,4 @@ public class ResourceFilter implements Filter { } return null; } - } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/HomePageHandler.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/HomePageHandler.java index f243345895..306706c22c 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/HomePageHandler.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/HomePageHandler.java @@ -18,15 +18,15 @@ package com.alibaba.dubbo.container.page.pages; import org.apache.dubbo.common.extension.ExtensionLoader; +import java.util.ArrayList; +import java.util.List; + import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.container.page.Menu; import com.alibaba.dubbo.container.page.Page; import com.alibaba.dubbo.container.page.PageHandler; import com.alibaba.dubbo.container.page.PageServlet; -import java.util.ArrayList; -import java.util.List; - /** * HomePageHandler */ @@ -44,7 +44,6 @@ public class HomePageHandler implements PageHandler { row.add(menu.desc()); rows.add(row); } - return new Page("Home", "Menus", new String[]{"Menu Name", "Menu Desc"}, rows); + return new Page("Home", "Menus", new String[] {"Menu Name", "Menu Desc"}, rows); } - } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/LogPageHandler.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/LogPageHandler.java index 874bdb3dfd..ee9f3670d5 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/LogPageHandler.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/LogPageHandler.java @@ -16,15 +16,6 @@ */ package com.alibaba.dubbo.container.page.pages; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.container.page.Menu; -import com.alibaba.dubbo.container.page.Page; -import com.alibaba.dubbo.container.page.PageHandler; -import org.apache.log4j.Appender; -import org.apache.log4j.FileAppender; -import org.apache.log4j.Level; -import org.apache.log4j.LogManager; - import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -36,6 +27,15 @@ import java.util.Date; import java.util.Enumeration; import java.util.List; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.container.page.Menu; +import com.alibaba.dubbo.container.page.Page; +import com.alibaba.dubbo.container.page.PageHandler; +import org.apache.log4j.Appender; +import org.apache.log4j.FileAppender; +import org.apache.log4j.Level; +import org.apache.log4j.LogManager; + /** * LogPageHandler */ @@ -88,10 +88,11 @@ public class LogPageHandler implements PageHandler { channel.read(bb, pos); } bb.flip(); - content = new String(bb.array()).replace("<", "<") - .replace(">", ">").replace("\n", "

"); - modified = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") - .format(new Date(file.lastModified())); + content = new String(bb.array()) + .replace("<", "<") + .replace(">", ">") + .replace("\n", "

"); + modified = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(file.lastModified())); } catch (IOException e) { } } @@ -100,7 +101,11 @@ public class LogPageHandler implements PageHandler { List row = new ArrayList(); row.add(content); rows.add(row); - return new Page("Log", "Log", new String[]{(file == null ? "" : file.getName()) + ", " + size + " bytes, " + modified + ", " + level}, rows); + return new Page( + "Log", + "Log", + new String[] {(file == null ? "" : file.getName()) + ", " + size + " bytes, " + modified + ", " + level + }, + rows); } - } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/StatusPageHandler.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/StatusPageHandler.java index 50e5564c68..f0fdb34a2a 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/StatusPageHandler.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/StatusPageHandler.java @@ -20,18 +20,18 @@ import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.status.Status; import org.apache.dubbo.common.status.support.StatusUtils; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.status.StatusChecker; -import com.alibaba.dubbo.container.page.Menu; -import com.alibaba.dubbo.container.page.Page; -import com.alibaba.dubbo.container.page.PageHandler; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.status.StatusChecker; +import com.alibaba.dubbo.container.page.Menu; +import com.alibaba.dubbo.container.page.Page; +import com.alibaba.dubbo.container.page.PageHandler; + /** * StatusPageHandler */ @@ -41,10 +41,12 @@ public class StatusPageHandler implements PageHandler { @Override public Page handle(URL url) { List> rows = new ArrayList>(); - Set names = ExtensionLoader.getExtensionLoader(StatusChecker.class).getSupportedExtensions(); + Set names = + ExtensionLoader.getExtensionLoader(StatusChecker.class).getSupportedExtensions(); Map statuses = new HashMap(); for (String name : names) { - StatusChecker checker = ExtensionLoader.getExtensionLoader(StatusChecker.class).getExtension(name); + StatusChecker checker = + ExtensionLoader.getExtensionLoader(StatusChecker.class).getExtension(name); List row = new ArrayList(); row.add(name); Status status = checker.check(); @@ -64,7 +66,11 @@ public class StatusPageHandler implements PageHandler { row.add(getLevelHtml(status.getLevel())); row.add("summary"); rows.add(row); - return new Page("Status (summary)", "Status", new String[]{"Name", "Status", "Description"}, rows); + return new Page( + "Status (summary)", + "Status", + new String[] {"Name", "Status", "Description"}, + rows); } } @@ -82,5 +88,4 @@ public class StatusPageHandler implements PageHandler { } return "gray"; } - } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/SystemPageHandler.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/SystemPageHandler.java index c4c6308b76..0c8e3c26ec 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/SystemPageHandler.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/pages/SystemPageHandler.java @@ -19,11 +19,6 @@ package com.alibaba.dubbo.container.page.pages; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.container.page.Menu; -import com.alibaba.dubbo.container.page.Page; -import com.alibaba.dubbo.container.page.PageHandler; - import java.lang.management.ManagementFactory; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -31,6 +26,11 @@ import java.util.Date; import java.util.List; import java.util.Locale; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.container.page.Menu; +import com.alibaba.dubbo.container.page.Page; +import com.alibaba.dubbo.container.page.PageHandler; + /** * SystemPageHandler */ @@ -65,12 +65,15 @@ public class SystemPageHandler implements PageHandler { row = new ArrayList(); row.add("JVM"); - row.add(System.getProperty("java.runtime.name") + " " + System.getProperty("java.runtime.version") + ",
" + System.getProperty("java.vm.name") + " " + System.getProperty("java.vm.version") + " " + System.getProperty("java.vm.info", "")); + row.add(System.getProperty("java.runtime.name") + " " + System.getProperty("java.runtime.version") + ",
" + + System.getProperty("java.vm.name") + " " + System.getProperty("java.vm.version") + " " + + System.getProperty("java.vm.info", "")); rows.add(row); row = new ArrayList(); row.add("CPU"); - row.add(System.getProperty("os.arch", "") + ", " + String.valueOf(Runtime.getRuntime().availableProcessors()) + " cores"); + row.add(System.getProperty("os.arch", "") + ", " + + String.valueOf(Runtime.getRuntime().availableProcessors()) + " cores"); rows.add(row); row = new ArrayList(); @@ -88,8 +91,7 @@ public class SystemPageHandler implements PageHandler { row.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z").format(new Date())); rows.add(row); - return new Page("System", "System", new String[]{ - "Property", "Value"}, rows); + return new Page("System", "System", new String[] {"Property", "Value"}, rows); } private String formatUptime(long uptime) { diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/monitor/Monitor.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/monitor/Monitor.java index 6e1ed3767b..a4205e886f 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/monitor/Monitor.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/monitor/Monitor.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.monitor; import org.apache.dubbo.common.URL; @@ -39,6 +38,8 @@ public interface Monitor extends org.apache.dubbo.monitor.Monitor { @Override default List lookup(URL query) { - return this.lookup(new com.alibaba.dubbo.common.DelegateURL(query)).stream().map(url -> url.getOriginalURL()).collect(Collectors.toList()); + return this.lookup(new com.alibaba.dubbo.common.DelegateURL(query)).stream() + .map(url -> url.getOriginalURL()) + .collect(Collectors.toList()); } } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/monitor/MonitorFactory.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/monitor/MonitorFactory.java index 4f30d1f3c7..9a054c5327 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/monitor/MonitorFactory.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/monitor/MonitorFactory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.monitor; import org.apache.dubbo.common.URL; diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/qos/command/BaseCommand.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/qos/command/BaseCommand.java index e44d92311a..168b8fd230 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/qos/command/BaseCommand.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/qos/command/BaseCommand.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.qos.command; import org.apache.dubbo.qos.api.CommandContext; diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/qos/command/CommandContext.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/qos/command/CommandContext.java index 6428e1d5fb..9f474b30b0 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/qos/command/CommandContext.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/qos/command/CommandContext.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.qos.command; @Deprecated diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/NotifyListener.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/NotifyListener.java index ae262e1fa7..8c425dd29d 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/NotifyListener.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/NotifyListener.java @@ -14,15 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.registry; -import com.alibaba.dubbo.common.DelegateURL; -import com.alibaba.dubbo.common.URL; - import java.util.List; import java.util.stream.Collectors; +import com.alibaba.dubbo.common.DelegateURL; +import com.alibaba.dubbo.common.URL; + @Deprecated public interface NotifyListener { diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/Registry.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/Registry.java index 8256b368db..1394a1c0ee 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/Registry.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/Registry.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.registry; import org.apache.dubbo.common.URL; @@ -51,19 +50,22 @@ public interface Registry extends org.apache.dubbo.registry.Registry { @Override default void subscribe(URL url, NotifyListener listener) { - this.subscribe(new com.alibaba.dubbo.common.DelegateURL(url), + this.subscribe( + new com.alibaba.dubbo.common.DelegateURL(url), new com.alibaba.dubbo.registry.NotifyListener.CompatibleNotifyListener(listener)); } @Override default void unsubscribe(URL url, NotifyListener listener) { - this.unsubscribe(new com.alibaba.dubbo.common.DelegateURL(url), + this.unsubscribe( + new com.alibaba.dubbo.common.DelegateURL(url), new com.alibaba.dubbo.registry.NotifyListener.CompatibleNotifyListener(listener)); } @Override default List lookup(URL url) { - return this.lookup(new com.alibaba.dubbo.common.DelegateURL(url)).stream().map(u -> u.getOriginalURL()). - collect(Collectors.toList()); + return this.lookup(new com.alibaba.dubbo.common.DelegateURL(url)).stream() + .map(u -> u.getOriginalURL()) + .collect(Collectors.toList()); } } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/RegistryFactory.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/RegistryFactory.java index e0eaf5c52b..7cd7e8cbb3 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/RegistryFactory.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/RegistryFactory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.registry; import org.apache.dubbo.common.URL; diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistry.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistry.java index 48a8cafc18..26cc9de0b8 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistry.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistry.java @@ -47,39 +47,49 @@ public abstract class AbstractRegistry implements Registry { } public Set getRegistered() { - return abstractRegistry.getRegistered().stream().map(url -> new com.alibaba.dubbo.common.DelegateURL(url)).collect(Collectors.toSet()); + return abstractRegistry.getRegistered().stream() + .map(url -> new com.alibaba.dubbo.common.DelegateURL(url)) + .collect(Collectors.toSet()); } public Map> getSubscribed() { - return abstractRegistry.getSubscribed().entrySet() - .stream() - .collect(Collectors.toMap(entry -> new com.alibaba.dubbo.common.DelegateURL(entry.getKey()), + return abstractRegistry.getSubscribed().entrySet().stream() + .collect(Collectors.toMap( + entry -> new com.alibaba.dubbo.common.DelegateURL(entry.getKey()), entry -> convertToNotifyListeners(entry.getValue()))); } public Map>> getNotified() { return abstractRegistry.getNotified().entrySet().stream() - .collect(Collectors.toMap(entry -> new com.alibaba.dubbo.common.DelegateURL(entry.getKey()), - entry -> { - return entry.getValue().entrySet() - .stream() - .collect(Collectors.toMap(e -> e.getKey(), e -> { - return e.getValue().stream().map(url -> new com.alibaba.dubbo.common.DelegateURL(url)).collect(Collectors.toList()); - })); - })); + .collect(Collectors.toMap(entry -> new com.alibaba.dubbo.common.DelegateURL(entry.getKey()), entry -> { + return entry.getValue().entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> { + return e.getValue().stream() + .map(url -> new com.alibaba.dubbo.common.DelegateURL(url)) + .collect(Collectors.toList()); + })); + })); } - public List getCacheUrls(com.alibaba.dubbo.common.URL url) { - return abstractRegistry.lookup(url.getOriginalURL()).stream().map(tmpUrl -> new com.alibaba.dubbo.common.DelegateURL(tmpUrl)).collect(Collectors.toList()); + return abstractRegistry.lookup(url.getOriginalURL()).stream() + .map(tmpUrl -> new com.alibaba.dubbo.common.DelegateURL(tmpUrl)) + .collect(Collectors.toList()); } public List lookup(com.alibaba.dubbo.common.URL url) { - return abstractRegistry.lookup(url.getOriginalURL()).stream().map(tmpUrl -> new com.alibaba.dubbo.common.DelegateURL(tmpUrl)).collect(Collectors.toList()); + return abstractRegistry.lookup(url.getOriginalURL()).stream() + .map(tmpUrl -> new com.alibaba.dubbo.common.DelegateURL(tmpUrl)) + .collect(Collectors.toList()); } - protected void notify(com.alibaba.dubbo.common.URL url, com.alibaba.dubbo.registry.NotifyListener listener, List urls) { - abstractRegistry.notify(url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener), urls.stream().map(tmpUrl -> tmpUrl.getOriginalURL()).collect(Collectors.toList())); + protected void notify( + com.alibaba.dubbo.common.URL url, + com.alibaba.dubbo.registry.NotifyListener listener, + List urls) { + abstractRegistry.notify( + url.getOriginalURL(), + new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener), + urls.stream().map(tmpUrl -> tmpUrl.getOriginalURL()).collect(Collectors.toList())); } public void register(com.alibaba.dubbo.common.URL url) { @@ -91,14 +101,17 @@ public abstract class AbstractRegistry implements Registry { } public void subscribe(com.alibaba.dubbo.common.URL url, com.alibaba.dubbo.registry.NotifyListener listener) { - abstractRegistry.subscribe(url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener)); + abstractRegistry.subscribe( + url.getOriginalURL(), + new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener)); } public void unsubscribe(com.alibaba.dubbo.common.URL url, com.alibaba.dubbo.registry.NotifyListener listener) { - abstractRegistry.unsubscribe(url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener)); + abstractRegistry.unsubscribe( + url.getOriginalURL(), + new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener)); } - @Override public void register(URL url) { this.register(new com.alibaba.dubbo.common.DelegateURL(url)); @@ -111,19 +124,24 @@ public abstract class AbstractRegistry implements Registry { @Override public void subscribe(URL url, NotifyListener listener) { - this.subscribe(new com.alibaba.dubbo.common.DelegateURL(url), new com.alibaba.dubbo.registry.NotifyListener.CompatibleNotifyListener(listener)); + this.subscribe( + new com.alibaba.dubbo.common.DelegateURL(url), + new com.alibaba.dubbo.registry.NotifyListener.CompatibleNotifyListener(listener)); } @Override public void unsubscribe(URL url, NotifyListener listener) { - this.unsubscribe(new com.alibaba.dubbo.common.DelegateURL(url), new com.alibaba.dubbo.registry.NotifyListener.CompatibleNotifyListener(listener)); + this.unsubscribe( + new com.alibaba.dubbo.common.DelegateURL(url), + new com.alibaba.dubbo.registry.NotifyListener.CompatibleNotifyListener(listener)); } final Set convertToNotifyListeners(Set notifyListeners) { - return notifyListeners.stream().map(listener -> new com.alibaba.dubbo.registry.NotifyListener.CompatibleNotifyListener(listener)).collect(Collectors.toSet()); + return notifyListeners.stream() + .map(listener -> new com.alibaba.dubbo.registry.NotifyListener.CompatibleNotifyListener(listener)) + .collect(Collectors.toSet()); } - static class CompatibleAbstractRegistry extends org.apache.dubbo.registry.support.AbstractRegistry { public CompatibleAbstractRegistry(URL url) { super(url); diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistryFactory.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistryFactory.java index badd9f082e..4b9218f641 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistryFactory.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/AbstractRegistryFactory.java @@ -25,11 +25,12 @@ import com.alibaba.dubbo.registry.RegistryFactory; * 2019-04-16 */ @Deprecated -public abstract class AbstractRegistryFactory extends org.apache.dubbo.registry.support.AbstractRegistryFactory implements RegistryFactory { +public abstract class AbstractRegistryFactory extends org.apache.dubbo.registry.support.AbstractRegistryFactory + implements RegistryFactory { @Override public com.alibaba.dubbo.registry.Registry getRegistry(com.alibaba.dubbo.common.URL url) { - return (com.alibaba.dubbo.registry.Registry)super.getRegistry(url.getOriginalURL()); + return (com.alibaba.dubbo.registry.Registry) super.getRegistry(url.getOriginalURL()); } protected abstract com.alibaba.dubbo.registry.Registry createRegistry(com.alibaba.dubbo.common.URL url); diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/FailbackRegistry.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/FailbackRegistry.java index f50c2c1fb4..ccc1997cf4 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/FailbackRegistry.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/registry/support/FailbackRegistry.java @@ -16,14 +16,14 @@ */ package com.alibaba.dubbo.registry.support; +import java.util.List; +import java.util.stream.Collectors; + import com.alibaba.dubbo.common.DelegateURL; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.registry.NotifyListener; import com.alibaba.dubbo.registry.Registry; -import java.util.List; -import java.util.stream.Collectors; - /** * 2019-04-17 */ @@ -45,11 +45,13 @@ public abstract class FailbackRegistry implements org.apache.dubbo.registry.Regi } public void removeFailedSubscribedTask(URL url, NotifyListener listener) { - failbackRegistry.removeFailedSubscribedTask(url.getOriginalURL(), new NotifyListener.ReverseCompatibleNotifyListener(listener)); + failbackRegistry.removeFailedSubscribedTask( + url.getOriginalURL(), new NotifyListener.ReverseCompatibleNotifyListener(listener)); } public void removeFailedUnsubscribedTask(URL url, NotifyListener listener) { - failbackRegistry.removeFailedUnsubscribedTask(url.getOriginalURL(), new NotifyListener.ReverseCompatibleNotifyListener(listener)); + failbackRegistry.removeFailedUnsubscribedTask( + url.getOriginalURL(), new NotifyListener.ReverseCompatibleNotifyListener(listener)); } @Override @@ -64,22 +66,34 @@ public abstract class FailbackRegistry implements org.apache.dubbo.registry.Regi @Override public void subscribe(URL url, NotifyListener listener) { - failbackRegistry.subscribe(url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener)); + failbackRegistry.subscribe( + url.getOriginalURL(), + new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener)); } @Override public void unsubscribe(URL url, NotifyListener listener) { - failbackRegistry.unsubscribe(url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener)); + failbackRegistry.unsubscribe( + url.getOriginalURL(), + new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener)); } protected void notify(URL url, NotifyListener listener, List urls) { - List urlResult = urls.stream().map(URL::getOriginalURL).collect(Collectors.toList()); - failbackRegistry.notify(url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener), urlResult); + List urlResult = + urls.stream().map(URL::getOriginalURL).collect(Collectors.toList()); + failbackRegistry.notify( + url.getOriginalURL(), + new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener), + urlResult); } protected void doNotify(URL url, NotifyListener listener, List urls) { - List urlResult = urls.stream().map(URL::getOriginalURL).collect(Collectors.toList()); - failbackRegistry.doNotify(url.getOriginalURL(), new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener), urlResult); + List urlResult = + urls.stream().map(URL::getOriginalURL).collect(Collectors.toList()); + failbackRegistry.doNotify( + url.getOriginalURL(), + new com.alibaba.dubbo.registry.NotifyListener.ReverseCompatibleNotifyListener(listener), + urlResult); } protected void recover() throws Exception { @@ -88,7 +102,9 @@ public abstract class FailbackRegistry implements org.apache.dubbo.registry.Regi @Override public List lookup(URL url) { - return failbackRegistry.lookup(url.getOriginalURL()).stream().map(e -> new DelegateURL(e)).collect(Collectors.toList()); + return failbackRegistry.lookup(url.getOriginalURL()).stream() + .map(e -> new DelegateURL(e)) + .collect(Collectors.toList()); } @Override @@ -136,12 +152,12 @@ public abstract class FailbackRegistry implements org.apache.dubbo.registry.Regi return failbackRegistry.lookup(url); } - static class CompatibleFailbackRegistry extends org.apache.dubbo.registry.support.FailbackRegistry { private FailbackRegistry compatibleFailbackRegistry; - public CompatibleFailbackRegistry(org.apache.dubbo.common.URL url, FailbackRegistry compatibleFailbackRegistry) { + public CompatibleFailbackRegistry( + org.apache.dubbo.common.URL url, FailbackRegistry compatibleFailbackRegistry) { super(url); this.compatibleFailbackRegistry = compatibleFailbackRegistry; } @@ -158,21 +174,29 @@ public abstract class FailbackRegistry implements org.apache.dubbo.registry.Regi @Override public void doSubscribe(org.apache.dubbo.common.URL url, org.apache.dubbo.registry.NotifyListener listener) { - this.compatibleFailbackRegistry.doSubscribe(new DelegateURL(url), new NotifyListener.CompatibleNotifyListener(listener)); + this.compatibleFailbackRegistry.doSubscribe( + new DelegateURL(url), new NotifyListener.CompatibleNotifyListener(listener)); } @Override public void doUnsubscribe(org.apache.dubbo.common.URL url, org.apache.dubbo.registry.NotifyListener listener) { - this.compatibleFailbackRegistry.doUnsubscribe(new DelegateURL(url), new NotifyListener.CompatibleNotifyListener(listener)); + this.compatibleFailbackRegistry.doUnsubscribe( + new DelegateURL(url), new NotifyListener.CompatibleNotifyListener(listener)); } @Override - public void notify(org.apache.dubbo.common.URL url, org.apache.dubbo.registry.NotifyListener listener, List urls) { + public void notify( + org.apache.dubbo.common.URL url, + org.apache.dubbo.registry.NotifyListener listener, + List urls) { super.notify(url, listener, urls); } @Override - public void doNotify(org.apache.dubbo.common.URL url, org.apache.dubbo.registry.NotifyListener listener, List urls) { + public void doNotify( + org.apache.dubbo.common.URL url, + org.apache.dubbo.registry.NotifyListener listener, + List urls) { super.doNotify(url, listener, urls); } @@ -186,5 +210,4 @@ public abstract class FailbackRegistry implements org.apache.dubbo.registry.Regi super.recover(); } } - } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Channel.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Channel.java index a900047fb9..a3e1192e7f 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Channel.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Channel.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.remoting; @Deprecated diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/ChannelHandler.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/ChannelHandler.java index 4be71fe31a..a5fe7e16b5 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/ChannelHandler.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/ChannelHandler.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.remoting; import org.apache.dubbo.remoting.Channel; @@ -27,34 +26,27 @@ public interface ChannelHandler extends org.apache.dubbo.remoting.ChannelHandler void disconnected(com.alibaba.dubbo.remoting.Channel channel) throws com.alibaba.dubbo.remoting.RemotingException; - void sent(com.alibaba.dubbo.remoting.Channel channel, Object message) throws com.alibaba.dubbo.remoting.RemotingException; + void sent(com.alibaba.dubbo.remoting.Channel channel, Object message) + throws com.alibaba.dubbo.remoting.RemotingException; - void received(com.alibaba.dubbo.remoting.Channel channel, Object message) throws com.alibaba.dubbo.remoting.RemotingException; + void received(com.alibaba.dubbo.remoting.Channel channel, Object message) + throws com.alibaba.dubbo.remoting.RemotingException; - void caught(com.alibaba.dubbo.remoting.Channel channel, Throwable exception) throws com.alibaba.dubbo.remoting.RemotingException; + void caught(com.alibaba.dubbo.remoting.Channel channel, Throwable exception) + throws com.alibaba.dubbo.remoting.RemotingException; @Override - default void connected(Channel channel) throws RemotingException { - - } + default void connected(Channel channel) throws RemotingException {} @Override - default void disconnected(Channel channel) throws RemotingException { - - } + default void disconnected(Channel channel) throws RemotingException {} @Override - default void sent(Channel channel, Object message) throws RemotingException { - - } + default void sent(Channel channel, Object message) throws RemotingException {} @Override - default void received(Channel channel, Object message) throws RemotingException { - - } + default void received(Channel channel, Object message) throws RemotingException {} @Override - default void caught(Channel channel, Throwable exception) throws RemotingException { - - } + default void caught(Channel channel, Throwable exception) throws RemotingException {} } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Codec.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Codec.java index c398fe7110..a375973472 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Codec.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Codec.java @@ -14,9 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.remoting; @Deprecated -public interface Codec extends org.apache.dubbo.remoting.Codec { -} +public interface Codec extends org.apache.dubbo.remoting.Codec {} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Codec2.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Codec2.java index 5bb4bb25ff..12645da366 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Codec2.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Codec2.java @@ -14,9 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.remoting; @Deprecated -public interface Codec2 extends org.apache.dubbo.remoting.Codec2 { -} +public interface Codec2 extends org.apache.dubbo.remoting.Codec2 {} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java index 3ec02d45c2..0f146e3c83 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.remoting; import org.apache.dubbo.common.URL; @@ -23,8 +22,8 @@ import org.apache.dubbo.remoting.ChannelHandler; @Deprecated public interface Dispatcher extends org.apache.dubbo.remoting.Dispatcher { - com.alibaba.dubbo.remoting.ChannelHandler dispatch(com.alibaba.dubbo.remoting.ChannelHandler handler, - com.alibaba.dubbo.common.URL url); + com.alibaba.dubbo.remoting.ChannelHandler dispatch( + com.alibaba.dubbo.remoting.ChannelHandler handler, com.alibaba.dubbo.common.URL url); @Override default ChannelHandler dispatch(ChannelHandler handler, URL url) { diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/RemotingException.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/RemotingException.java index c863a51034..c86262ff04 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/RemotingException.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/RemotingException.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.remoting; import org.apache.dubbo.remoting.Channel; @@ -44,11 +43,12 @@ public class RemotingException extends org.apache.dubbo.remoting.RemotingExcepti super(channel, message, cause); } - public RemotingException(InetSocketAddress localAddress, InetSocketAddress remoteAddress, String message, Throwable cause) { + public RemotingException( + InetSocketAddress localAddress, InetSocketAddress remoteAddress, String message, Throwable cause) { super(localAddress, remoteAddress, message, cause); } - public RemotingException(Exception e){ + public RemotingException(Exception e) { super(null, e.getMessage()); } } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Server.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Server.java index 2ad23d6ad6..c89fb61a19 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Server.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Server.java @@ -19,5 +19,4 @@ package com.alibaba.dubbo.remoting; import org.apache.dubbo.remoting.RemotingServer; @Deprecated -public interface Server extends RemotingServer { -} +public interface Server extends RemotingServer {} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Transporter.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Transporter.java index b34aca3232..c984a701b7 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Transporter.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/Transporter.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.remoting; import org.apache.dubbo.common.extension.Adaptive; diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/exchange/Exchanger.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/exchange/Exchanger.java index b8f20f65b2..807b4afcc4 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/exchange/Exchanger.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/exchange/Exchanger.java @@ -14,9 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.remoting.exchange; @Deprecated -public interface Exchanger extends org.apache.dubbo.remoting.exchange.Exchanger { -} +public interface Exchanger extends org.apache.dubbo.remoting.exchange.Exchanger {} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseCallback.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseCallback.java index 30a71afdf1..614bfdc5df 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseCallback.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseCallback.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.remoting.exchange; /** @@ -35,5 +34,4 @@ public interface ResponseCallback { * @param exception */ void caught(Throwable exception); - } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseFuture.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseFuture.java index c7083a6058..461531e822 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseFuture.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/exchange/ResponseFuture.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.remoting.exchange; - import com.alibaba.dubbo.remoting.RemotingException; /** diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/http/HttpBinder.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/http/HttpBinder.java index 6deaab96f3..c0982a0845 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/http/HttpBinder.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/http/HttpBinder.java @@ -14,9 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.remoting.http; @Deprecated -public interface HttpBinder extends org.apache.dubbo.remoting.http.HttpBinder { -} +public interface HttpBinder extends org.apache.dubbo.remoting.http.HttpBinder {} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/telnet/TelnetHandler.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/telnet/TelnetHandler.java index 0cd3e5d127..81479debf7 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/telnet/TelnetHandler.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/telnet/TelnetHandler.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.remoting.telnet; import org.apache.dubbo.remoting.Channel; @@ -23,7 +22,8 @@ import org.apache.dubbo.remoting.RemotingException; @Deprecated public interface TelnetHandler extends org.apache.dubbo.remoting.telnet.TelnetHandler { - String telnet(com.alibaba.dubbo.remoting.Channel channel, String message) throws com.alibaba.dubbo.remoting.RemotingException; + String telnet(com.alibaba.dubbo.remoting.Channel channel, String message) + throws com.alibaba.dubbo.remoting.RemotingException; @Override default String telnet(Channel channel, String message) throws RemotingException { diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/zookeeper/ZookeeperTransporter.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/zookeeper/ZookeeperTransporter.java index 61252825e8..25cabd64ce 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/zookeeper/ZookeeperTransporter.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/remoting/zookeeper/ZookeeperTransporter.java @@ -14,9 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.remoting.zookeeper; @Deprecated -public interface ZookeeperTransporter extends org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter { -} +public interface ZookeeperTransporter extends org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter {} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Exporter.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Exporter.java index d89fe3aa5c..cca7cbd8f1 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Exporter.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Exporter.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc; @Deprecated diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Filter.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Filter.java index c196baa517..d21aca9a48 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Filter.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Filter.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc; import org.apache.dubbo.rpc.AsyncRpcResult; @@ -28,11 +27,11 @@ public interface Filter extends org.apache.dubbo.rpc.Filter { Result invoke(Invoker invoker, Invocation invocation) throws RpcException; @Override - default org.apache.dubbo.rpc.Result invoke(org.apache.dubbo.rpc.Invoker invoker, - org.apache.dubbo.rpc.Invocation invocation) - throws org.apache.dubbo.rpc.RpcException { - Result invokeResult = invoke(new Invoker.CompatibleInvoker<>(invoker), - new Invocation.CompatibleInvocation(invocation)); + default org.apache.dubbo.rpc.Result invoke( + org.apache.dubbo.rpc.Invoker invoker, org.apache.dubbo.rpc.Invocation invocation) + throws org.apache.dubbo.rpc.RpcException { + Result invokeResult = + invoke(new Invoker.CompatibleInvoker<>(invoker), new Invocation.CompatibleInvocation(invocation)); if (invokeResult instanceof Result.CompatibleResult) { return ((Result.CompatibleResult) invokeResult).getDelegate(); diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invocation.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invocation.java index 85e5cfcfe5..a2dfd10329 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invocation.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invocation.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc; import org.apache.dubbo.rpc.model.ServiceModel; @@ -47,13 +46,10 @@ public interface Invocation extends org.apache.dubbo.rpc.Invocation { } @Override - default void setObjectAttachmentIfAbsent(String key, Object value) { - } + default void setObjectAttachmentIfAbsent(String key, Object value) {} @Override - default void setObjectAttachment(String key, Object value) { - - } + default void setObjectAttachment(String key, Object value) {} @Override default void setAttachment(String key, Object value) { @@ -65,7 +61,6 @@ public interface Invocation extends org.apache.dubbo.rpc.Invocation { setObjectAttachmentIfAbsent(key, value); } - @Override default String getServiceName() { return null; @@ -82,9 +77,7 @@ public interface Invocation extends org.apache.dubbo.rpc.Invocation { } @Override - default void setServiceModel(ServiceModel serviceModel) { - - } + default void setServiceModel(ServiceModel serviceModel) {} @Override default ServiceModel getServiceModel() { diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invoker.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invoker.java index c8b86f98a2..fc4c053ddb 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invoker.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invoker.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc; import org.apache.dubbo.rpc.AsyncRpcResult; @@ -36,7 +35,8 @@ public interface Invoker extends org.apache.dubbo.rpc.Invoker { // This method will never be called for a legacy invoker. @Override - default org.apache.dubbo.rpc.Result invoke(org.apache.dubbo.rpc.Invocation invocation) throws org.apache.dubbo.rpc.RpcException { + default org.apache.dubbo.rpc.Result invoke(org.apache.dubbo.rpc.Invocation invocation) + throws org.apache.dubbo.rpc.RpcException { return null; } @@ -54,7 +54,8 @@ public interface Invoker extends org.apache.dubbo.rpc.Invoker { } @Override - public org.apache.dubbo.rpc.Result invoke(org.apache.dubbo.rpc.Invocation invocation) throws org.apache.dubbo.rpc.RpcException { + public org.apache.dubbo.rpc.Result invoke(org.apache.dubbo.rpc.Invocation invocation) + throws org.apache.dubbo.rpc.RpcException { return new Result.CompatibleResult(invoker.invoke(invocation)); } @@ -95,12 +96,12 @@ public interface Invoker extends org.apache.dubbo.rpc.Invoker { public org.apache.dubbo.rpc.Invoker getOriginal() { return invoker; } - + @Override public int hashCode() { return invoker.hashCode(); } - + @Override public boolean equals(Object o) { if (this == o) { diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/InvokerListener.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/InvokerListener.java index 6ba4a37b47..ffca181f1f 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/InvokerListener.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/InvokerListener.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc; import org.apache.dubbo.rpc.Invoker; diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Protocol.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Protocol.java index ba603d6b1b..690ee86fe4 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Protocol.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Protocol.java @@ -14,17 +14,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc; import org.apache.dubbo.rpc.ProtocolServer; -import com.alibaba.dubbo.common.DelegateURL; -import com.alibaba.dubbo.common.URL; - import java.util.Collections; import java.util.List; +import com.alibaba.dubbo.common.DelegateURL; +import com.alibaba.dubbo.common.URL; + @Deprecated public interface Protocol extends org.apache.dubbo.rpc.Protocol { @@ -38,7 +37,8 @@ public interface Protocol extends org.apache.dubbo.rpc.Protocol { } @Override - default org.apache.dubbo.rpc.Invoker refer(Class aClass, org.apache.dubbo.common.URL url) throws RpcException { + default org.apache.dubbo.rpc.Invoker refer(Class aClass, org.apache.dubbo.common.URL url) + throws RpcException { return this.refer(aClass, new DelegateURL(url)); } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/ProxyFactory.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/ProxyFactory.java index 35ff7f0da9..933541ef11 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/ProxyFactory.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/ProxyFactory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc; import org.apache.dubbo.common.URL; @@ -28,7 +27,8 @@ public interface ProxyFactory extends org.apache.dubbo.rpc.ProxyFactory { T getProxy(com.alibaba.dubbo.rpc.Invoker invoker, boolean generic) throws com.alibaba.dubbo.rpc.RpcException; - com.alibaba.dubbo.rpc.Invoker getInvoker(T proxy, Class type, com.alibaba.dubbo.common.URL url) throws com.alibaba.dubbo.rpc.RpcException; + com.alibaba.dubbo.rpc.Invoker getInvoker(T proxy, Class type, com.alibaba.dubbo.common.URL url) + throws com.alibaba.dubbo.rpc.RpcException; @Override default T getProxy(Invoker invoker) throws RpcException { diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Result.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Result.java index 040736647a..da5bc07608 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Result.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Result.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc; import java.util.Collections; @@ -30,14 +29,10 @@ import java.util.function.Function; public interface Result extends org.apache.dubbo.rpc.Result { @Override - default void setValue(Object value) { - - } + default void setValue(Object value) {} @Override - default void setException(Throwable t) { - - } + default void setException(Throwable t) {} @Override default Map getObjectAttachments() { @@ -45,14 +40,10 @@ public interface Result extends org.apache.dubbo.rpc.Result { } @Override - default void addObjectAttachments(Map map) { - - } + default void addObjectAttachments(Map map) {} @Override - default void setObjectAttachments(Map map) { - - } + default void setObjectAttachments(Map map) {} @Override default Object getObjectAttachment(String key) { @@ -64,7 +55,6 @@ public interface Result extends org.apache.dubbo.rpc.Result { return null; } - /** * @see com.alibaba.dubbo.rpc.Result#getValue() * @deprecated Replace to getValue() @@ -86,7 +76,8 @@ public interface Result extends org.apache.dubbo.rpc.Result { } @Override - public org.apache.dubbo.rpc.Result whenCompleteWithContext(BiConsumer fn) { + public org.apache.dubbo.rpc.Result whenCompleteWithContext( + BiConsumer fn) { return delegate.whenCompleteWithContext(fn); } @@ -171,7 +162,8 @@ public interface Result extends org.apache.dubbo.rpc.Result { } @Override - public org.apache.dubbo.rpc.Result get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + public org.apache.dubbo.rpc.Result get(long timeout, TimeUnit unit) + throws InterruptedException, ExecutionException, TimeoutException { return delegate.get(timeout, unit); } } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java index cfc5fb4b8b..6f1b383e62 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java @@ -14,17 +14,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.rpc.FutureContext; -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.DelegateURL; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.rpc.protocol.dubbo.FutureAdapter; - import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collections; @@ -39,6 +33,11 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.DelegateURL; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.rpc.protocol.dubbo.FutureAdapter; + @Deprecated public class RpcContext { @@ -49,6 +48,7 @@ public class RpcContext { public static RpcContext getServerContext() { return new RpcContext(org.apache.dubbo.rpc.RpcContext.getServerContext()); } + public static RpcContext getClientResponseContext() { return new RpcContext(org.apache.dubbo.rpc.RpcContext.getClientResponseContext()); } @@ -56,6 +56,7 @@ public class RpcContext { public static RpcContext getServerResponseContext() { return new RpcContext(org.apache.dubbo.rpc.RpcContext.getServerResponseContext()); } + public static void removeClientResponseContext() { org.apache.dubbo.rpc.RpcContext.removeClientResponseContext(); } @@ -67,6 +68,7 @@ public class RpcContext { public static void removeServerContext() { org.apache.dubbo.rpc.RpcContext.removeServerContext(); } + public static void removeContext() { org.apache.dubbo.rpc.RpcContext.removeContext(); } @@ -85,7 +87,6 @@ public class RpcContext { return newRpcContext.getRequest(clazz); } - public void setRequest(Object request) { newRpcContext.setRequest(request); } @@ -336,9 +337,7 @@ public class RpcContext { if (CollectionUtils.isEmpty(invokers)) { return Collections.emptyList(); } - return invokers.stream() - .map(Invoker.CompatibleInvoker::new) - .collect(Collectors.toList()); + return invokers.stream().map(Invoker.CompatibleInvoker::new).collect(Collectors.toList()); } /** * Async invocation. Timeout will be handled even if Future.get() is not called. @@ -352,7 +351,7 @@ public class RpcContext { try { setAttachment(Constants.ASYNC_KEY, Boolean.TRUE.toString()); final T o = callable.call(); - //local invoke will return directly + // local invoke will return directly if (o != null) { FutureTask f = new FutureTask(new Callable() { @Override @@ -394,8 +393,7 @@ public class RpcContext { @Override public T get(long timeout, TimeUnit unit) - throws InterruptedException, ExecutionException, - TimeoutException { + throws InterruptedException, ExecutionException, TimeoutException { return get(); } }; diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcException.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcException.java index 1e994019ac..b01ca571b5 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcException.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcException.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc; @Deprecated diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcInvocation.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcInvocation.java index 7206210ceb..d9bc2dd662 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcInvocation.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcInvocation.java @@ -14,12 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc; -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; - import java.beans.Transient; import java.io.Serializable; import java.lang.reflect.Method; @@ -28,6 +24,9 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; + @Deprecated public class RpcInvocation implements Invocation, Serializable { @@ -43,12 +42,14 @@ public class RpcInvocation implements Invocation, Serializable { private transient Invoker invoker; - public RpcInvocation() { - } + public RpcInvocation() {} public RpcInvocation(Invocation invocation, Invoker invoker) { - this(invocation.getMethodName(), invocation.getParameterTypes(), - invocation.getArguments(), new HashMap(invocation.getAttachments()), + this( + invocation.getMethodName(), + invocation.getParameterTypes(), + invocation.getArguments(), + new HashMap(invocation.getAttachments()), invocation.getInvoker()); if (invoker != null) { URL url = invoker.getUrl(); @@ -75,8 +76,12 @@ public class RpcInvocation implements Invocation, Serializable { } public RpcInvocation(Invocation invocation) { - this(invocation.getMethodName(), invocation.getParameterTypes(), - invocation.getArguments(), invocation.getAttachments(), invocation.getInvoker()); + this( + invocation.getMethodName(), + invocation.getParameterTypes(), + invocation.getArguments(), + invocation.getAttachments(), + invocation.getInvoker()); } public RpcInvocation(Method method, Object[] arguments) { @@ -91,11 +96,17 @@ public class RpcInvocation implements Invocation, Serializable { this(methodName, parameterTypes, arguments, null, null); } - public RpcInvocation(String methodName, Class[] parameterTypes, Object[] arguments, Map attachments) { + public RpcInvocation( + String methodName, Class[] parameterTypes, Object[] arguments, Map attachments) { this(methodName, parameterTypes, arguments, attachments, null); } - public RpcInvocation(String methodName, Class[] parameterTypes, Object[] arguments, Map attachments, Invoker invoker) { + public RpcInvocation( + String methodName, + Class[] parameterTypes, + Object[] arguments, + Map attachments, + Invoker invoker) { this.methodName = methodName; this.parameterTypes = parameterTypes == null ? new Class[0] : parameterTypes; this.arguments = arguments == null ? new Object[0] : arguments; @@ -218,5 +229,4 @@ public class RpcInvocation implements Invocation, Serializable { + Arrays.toString(parameterTypes) + ", arguments=" + Arrays.toString(arguments) + ", attachments=" + attachments + "]"; } - } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcResult.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcResult.java index d62eb09418..e383ff2476 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcResult.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcResult.java @@ -21,8 +21,7 @@ import org.apache.dubbo.rpc.AppResponse; @Deprecated public class RpcResult extends AppResponse implements com.alibaba.dubbo.rpc.Result { - public RpcResult() { - } + public RpcResult() {} public RpcResult(Object result) { super(result); @@ -31,5 +30,4 @@ public class RpcResult extends AppResponse implements com.alibaba.dubbo.rpc.Resu public RpcResult(Throwable exception) { super(exception); } - } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Cluster.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Cluster.java index 13c9629c36..e92ca0ef1e 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Cluster.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Cluster.java @@ -23,8 +23,8 @@ import org.apache.dubbo.rpc.cluster.Directory; @Deprecated public interface Cluster extends org.apache.dubbo.rpc.cluster.Cluster { - com.alibaba.dubbo.rpc.Invoker join(com.alibaba.dubbo.rpc.cluster.Directory directory) throws - com.alibaba.dubbo.rpc.RpcException; + com.alibaba.dubbo.rpc.Invoker join(com.alibaba.dubbo.rpc.cluster.Directory directory) + throws com.alibaba.dubbo.rpc.RpcException; @Override default Invoker join(Directory directory, boolean buildFilterChain) throws RpcException { diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Directory.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Directory.java index 69a2f4b7ad..750a88b6c7 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Directory.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Directory.java @@ -14,29 +14,30 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc.cluster; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; -import com.alibaba.dubbo.common.URL; - import java.util.List; import java.util.stream.Collectors; +import com.alibaba.dubbo.common.URL; + @Deprecated public interface Directory extends org.apache.dubbo.rpc.cluster.Directory { @Override URL getUrl(); - List> list(com.alibaba.dubbo.rpc.Invocation invocation) throws com.alibaba.dubbo.rpc.RpcException; + List> list(com.alibaba.dubbo.rpc.Invocation invocation) + throws com.alibaba.dubbo.rpc.RpcException; @Override default List> list(Invocation invocation) throws RpcException { - List> res = this.list(new com.alibaba.dubbo.rpc.Invocation.CompatibleInvocation(invocation)); + List> res = + this.list(new com.alibaba.dubbo.rpc.Invocation.CompatibleInvocation(invocation)); return res.stream().map(com.alibaba.dubbo.rpc.Invoker::getOriginal).collect(Collectors.toList()); } } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/LoadBalance.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/LoadBalance.java index d0f978afa6..cec780365f 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/LoadBalance.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/LoadBalance.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc.cluster; import org.apache.dubbo.common.URL; @@ -22,26 +21,28 @@ import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; -import com.alibaba.dubbo.common.DelegateURL; - import java.util.List; import java.util.stream.Collectors; +import com.alibaba.dubbo.common.DelegateURL; + @Deprecated public interface LoadBalance extends org.apache.dubbo.rpc.cluster.LoadBalance { - com.alibaba.dubbo.rpc.Invoker select(List> invokers, - com.alibaba.dubbo.common.URL url, - com.alibaba.dubbo.rpc.Invocation invocation) throws RpcException; + com.alibaba.dubbo.rpc.Invoker select( + List> invokers, + com.alibaba.dubbo.common.URL url, + com.alibaba.dubbo.rpc.Invocation invocation) + throws RpcException; @Override default Invoker select(List> invokers, URL url, Invocation invocation) throws RpcException { - List> invs = invokers.stream(). - map(invoker -> new com.alibaba.dubbo.rpc.Invoker.CompatibleInvoker(invoker)). - collect(Collectors.toList()); + List> invs = invokers.stream() + .map(invoker -> new com.alibaba.dubbo.rpc.Invoker.CompatibleInvoker(invoker)) + .collect(Collectors.toList()); - com.alibaba.dubbo.rpc.Invoker selected = select(invs, new DelegateURL(url), - new com.alibaba.dubbo.rpc.Invocation.CompatibleInvocation(invocation)); + com.alibaba.dubbo.rpc.Invoker selected = select( + invs, new DelegateURL(url), new com.alibaba.dubbo.rpc.Invocation.CompatibleInvocation(invocation)); return selected == null ? null : selected.getOriginal(); } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Merger.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Merger.java index b5f37fbcb2..093ed29eb3 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Merger.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Merger.java @@ -14,9 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc.cluster; @Deprecated -public interface Merger extends org.apache.dubbo.rpc.cluster.Merger { -} +public interface Merger extends org.apache.dubbo.rpc.cluster.Merger {} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Router.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Router.java index 2bc4aabd18..94bf7362fc 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Router.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/Router.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc.cluster; import org.apache.dubbo.common.URL; @@ -27,14 +26,15 @@ import java.util.Objects; import java.util.stream.Collectors; @Deprecated -public interface Router extends org.apache.dubbo.rpc.cluster.Router{ +public interface Router extends org.apache.dubbo.rpc.cluster.Router { @Override com.alibaba.dubbo.common.URL getUrl(); - List> route(List> invokers, - com.alibaba.dubbo.common.URL url, - com.alibaba.dubbo.rpc.Invocation invocation) + List> route( + List> invokers, + com.alibaba.dubbo.common.URL url, + com.alibaba.dubbo.rpc.Invocation invocation) throws com.alibaba.dubbo.rpc.RpcException; int compareTo(Router o); @@ -42,12 +42,19 @@ public interface Router extends org.apache.dubbo.rpc.cluster.Router{ // Add since 2.7.0 @Override default List> route(List> invokers, URL url, Invocation invocation) throws RpcException { - List> invs = invokers.stream().map(invoker -> new com.alibaba.dubbo.rpc.Invoker.CompatibleInvoker(invoker)). - collect(Collectors.toList()); + List> invs = invokers.stream() + .map(invoker -> new com.alibaba.dubbo.rpc.Invoker.CompatibleInvoker(invoker)) + .collect(Collectors.toList()); - List> res = this.route(invs, new com.alibaba.dubbo.common.DelegateURL(url), new com.alibaba.dubbo.rpc.Invocation.CompatibleInvocation(invocation)); + List> res = this.route( + invs, + new com.alibaba.dubbo.common.DelegateURL(url), + new com.alibaba.dubbo.rpc.Invocation.CompatibleInvocation(invocation)); - return res.stream().map(inv -> inv.getOriginal()).filter(Objects::nonNull).collect(Collectors.toList()); + return res.stream() + .map(inv -> inv.getOriginal()) + .filter(Objects::nonNull) + .collect(Collectors.toList()); } @Override @@ -66,11 +73,11 @@ public interface Router extends org.apache.dubbo.rpc.cluster.Router{ } @Override - default int compareTo (org.apache.dubbo.rpc.cluster.Router o) { + default int compareTo(org.apache.dubbo.rpc.cluster.Router o) { if (!(o instanceof Router)) { return 1; } - return this.compareTo((Router)o); + return this.compareTo((Router) o); } } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/RouterFactory.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/RouterFactory.java index f57a0023d5..34160fe846 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/RouterFactory.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/RouterFactory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc.cluster; import org.apache.dubbo.common.URL; diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/RuleConverter.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/RuleConverter.java index acf6c8797b..eb67cdb615 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/RuleConverter.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/RuleConverter.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc.cluster; import org.apache.dubbo.common.URL; @@ -29,7 +28,8 @@ public interface RuleConverter extends org.apache.dubbo.rpc.cluster.RuleConverte @Override default List convert(URL subscribeUrl, Object source) { - return this.convert(new com.alibaba.dubbo.common.DelegateURL(subscribeUrl), source). - stream().map(url -> url.getOriginalURL()).collect(Collectors.toList()); + return this.convert(new com.alibaba.dubbo.common.DelegateURL(subscribeUrl), source).stream() + .map(url -> url.getOriginalURL()) + .collect(Collectors.toList()); } } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java index 98f9aa78fd..d2a1a2aec3 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java @@ -14,35 +14,33 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc.cluster.loadbalance; import org.apache.dubbo.rpc.support.RpcUtils; +import java.util.List; + import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.rpc.Invocation; import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.cluster.LoadBalance; -import java.util.List; - @Deprecated public abstract class AbstractLoadBalance implements LoadBalance { @Override public Invoker select(List> invokers, URL url, Invocation invocation) { - if (invokers == null || invokers.size() == 0) - return null; - if (invokers.size() == 1) - return invokers.get(0); + if (invokers == null || invokers.size() == 0) return null; + if (invokers.size() == 1) return invokers.get(0); return doSelect(invokers, url, invocation); } protected abstract Invoker doSelect(List> invokers, URL url, Invocation invocation); protected int getWeight(Invoker invoker, Invocation invocation) { - int weight = invoker.getUrl().getMethodParameter(RpcUtils.getMethodName(invocation), Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT); + int weight = invoker.getUrl() + .getMethodParameter(RpcUtils.getMethodName(invocation), Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT); if (weight > 0) { long timestamp = invoker.getUrl().getParameter(Constants.TIMESTAMP_KEY, 0L); if (timestamp > 0L) { @@ -57,7 +55,7 @@ public abstract class AbstractLoadBalance implements LoadBalance { } static int calculateWarmupWeight(int uptime, int warmup, int weight) { - int ww = (int) ( (float) uptime / ( (float) warmup / (float) weight ) ); + int ww = (int) ((float) uptime / ((float) warmup / (float) weight)); return ww < 1 ? 1 : (ww > weight ? weight : ww); } } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureAdapter.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureAdapter.java index b2bba70b7f..448d26a4eb 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureAdapter.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/FutureAdapter.java @@ -14,17 +14,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc.protocol.dubbo; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Result; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.exchange.ResponseCallback; -import com.alibaba.dubbo.remoting.exchange.ResponseFuture; -import com.alibaba.dubbo.rpc.RpcException; - import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.ExecutionException; @@ -33,6 +27,11 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.BiConsumer; +import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exchange.ResponseCallback; +import com.alibaba.dubbo.remoting.exchange.ResponseFuture; +import com.alibaba.dubbo.rpc.RpcException; + /** * 2019-06-20 */ @@ -103,7 +102,7 @@ public class FutureAdapter implements Future { } callback.caught(t); } else { - AppResponse appResponse = (AppResponse)obj; + AppResponse appResponse = (AppResponse) obj; if (appResponse.hasException()) { callback.caught(appResponse.getException()); } else { @@ -135,7 +134,7 @@ public class FutureAdapter implements Future { public V get() throws InterruptedException, ExecutionException { try { return (V) (((Result) future.get()).recreate()); - } catch (InterruptedException | ExecutionException e) { + } catch (InterruptedException | ExecutionException e) { throw e; } catch (Throwable e) { throw new RpcException(e); @@ -147,7 +146,7 @@ public class FutureAdapter implements Future { public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { try { return (V) (((Result) future.get(timeout, unit)).recreate()); - } catch (InterruptedException | ExecutionException | TimeoutException e) { + } catch (InterruptedException | ExecutionException | TimeoutException e) { throw e; } catch (Throwable e) { throw new RpcException(e); diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/ContentType.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/ContentType.java index e47b1ca17f..ad2508fa6f 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/ContentType.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/ContentType.java @@ -14,9 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc.protocol.rest.support; @Deprecated -public class ContentType extends org.apache.dubbo.rpc.protocol.rest.support.ContentType { -} +public class ContentType extends org.apache.dubbo.rpc.protocol.rest.support.ContentType {} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/service/EchoService.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/service/EchoService.java index 470e952b40..e50733b17d 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/service/EchoService.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/service/EchoService.java @@ -14,9 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc.service; @Deprecated -public interface EchoService extends org.apache.dubbo.rpc.service.EchoService { -} +public interface EchoService extends org.apache.dubbo.rpc.service.EchoService {} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/service/GenericException.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/service/GenericException.java index 0d5ac6fed2..aa0275df4a 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/service/GenericException.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/service/GenericException.java @@ -14,17 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc.service; - @Deprecated public class GenericException extends org.apache.dubbo.rpc.service.GenericException { private static final long serialVersionUID = -1182299763306599962L; - public GenericException() { - } + public GenericException() {} public GenericException(String exceptionMessage) { super(exceptionMessage); diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/service/GenericService.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/service/GenericService.java index cc3282a7a0..113c973450 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/service/GenericService.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/service/GenericService.java @@ -14,13 +14,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc.service; @Deprecated public interface GenericService extends org.apache.dubbo.rpc.service.GenericService { @Override - Object $invoke(String method, String[] parameterTypes, Object[] args) - throws GenericException; + Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException; } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/support/RpcUtils.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/support/RpcUtils.java index 378f14adc2..45a333e9dc 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/support/RpcUtils.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/support/RpcUtils.java @@ -14,20 +14,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.rpc.support; +import java.lang.reflect.Type; + import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.rpc.Invocation; -import java.lang.reflect.Type; - /** * 2019-04-18 */ public class RpcUtils extends org.apache.dubbo.rpc.support.RpcUtils { - public static Class getReturnType(Invocation invocation) { return org.apache.dubbo.rpc.support.RpcUtils.getReturnType(invocation); } @@ -51,7 +49,6 @@ public class RpcUtils extends org.apache.dubbo.rpc.support.RpcUtils { org.apache.dubbo.rpc.support.RpcUtils.attachInvocationIdIfAsync(url.getOriginalURL(), inv); } - public static String getMethodName(Invocation invocation) { return org.apache.dubbo.rpc.support.RpcUtils.getMethodName(invocation); } diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/validation/Validation.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/validation/Validation.java index 4881f3395a..673bbefb1b 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/validation/Validation.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/validation/Validation.java @@ -14,9 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.validation; @Deprecated -public interface Validation extends org.apache.dubbo.validation.Validation { -} +public interface Validation extends org.apache.dubbo.validation.Validation {} diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/validation/Validator.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/validation/Validator.java index 97719c2c00..fbee29fb73 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/validation/Validator.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/validation/Validator.java @@ -14,9 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.alibaba.dubbo.validation; @Deprecated -public interface Validator extends org.apache.dubbo.validation.Validator { -} +public interface Validator extends org.apache.dubbo.validation.Validator {} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/cache/CacheTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/cache/CacheTest.java index b60f7bf163..47c6f4a9ae 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/cache/CacheTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/cache/CacheTest.java @@ -14,21 +14,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.cache; +import org.apache.dubbo.rpc.RpcInvocation; + import java.util.List; import java.util.Map; -import org.apache.dubbo.rpc.RpcInvocation; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import com.alibaba.dubbo.cache.Cache; import com.alibaba.dubbo.cache.CacheFactory; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.rpc.Invocation; import com.alibaba.dubbo.rpc.Invoker; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; class CacheTest { @@ -41,7 +40,8 @@ class CacheTest { cache.put("testKey", "testValue"); org.apache.dubbo.cache.CacheFactory factory = cacheFactory; - org.apache.dubbo.common.URL u = org.apache.dubbo.common.URL.valueOf("test://test:11/test?cache=jacache&.cache.write.expire=1"); + org.apache.dubbo.common.URL u = + org.apache.dubbo.common.URL.valueOf("test://test:11/test?cache=jacache&.cache.write.expire=1"); org.apache.dubbo.rpc.Invocation inv = new RpcInvocation(); org.apache.dubbo.cache.Cache c = factory.getCache(u, inv); String v = (String) c.get("testKey"); @@ -110,9 +110,7 @@ class CacheTest { } @Override - public void addInvokedInvoker(org.apache.dubbo.rpc.Invoker invoker) { - - } + public void addInvokedInvoker(org.apache.dubbo.rpc.Invoker invoker) {} @Override public List> getInvokedInvokers() { diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/cache/MyCache.java b/dubbo-compatible/src/test/java/org/apache/dubbo/cache/MyCache.java index c7a7528350..72941d7951 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/cache/MyCache.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/cache/MyCache.java @@ -14,21 +14,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.cache; -import com.alibaba.dubbo.cache.Cache; -import com.alibaba.dubbo.common.URL; - import java.util.HashMap; import java.util.Map; +import com.alibaba.dubbo.cache.Cache; +import com.alibaba.dubbo.common.URL; + public class MyCache implements Cache { private Map map = new HashMap(); - public MyCache(URL url) { - } + public MyCache(URL url) {} @Override public void put(Object key, Object value) { diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/cache/MyCacheFactory.java b/dubbo-compatible/src/test/java/org/apache/dubbo/cache/MyCacheFactory.java index aa22fbe4a7..25560a70de 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/cache/MyCacheFactory.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/cache/MyCacheFactory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.cache; import com.alibaba.dubbo.cache.Cache; diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/ExtensionTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/ExtensionTest.java index 187c28905a..0dca5da42b 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/ExtensionTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/ExtensionTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension; import org.apache.dubbo.common.URL; @@ -23,11 +22,11 @@ import org.apache.dubbo.common.extension.activate.impl.OldActivateExt1Impl2; import org.apache.dubbo.common.extension.activate.impl.OldActivateExt1Impl3; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.List; - import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.junit.jupiter.api.Assertions.fail; @@ -36,13 +35,15 @@ class ExtensionTest { @Test void testExtensionFactory() { try { - ExtensionInjector myfactory = ExtensionLoader.getExtensionLoader(ExtensionInjector.class).getExtension("myfactory"); + ExtensionInjector myfactory = + ExtensionLoader.getExtensionLoader(ExtensionInjector.class).getExtension("myfactory"); Assertions.assertTrue(myfactory instanceof ExtensionInjector); Assertions.assertTrue(myfactory instanceof ExtensionFactory); Assertions.assertTrue(myfactory instanceof com.alibaba.dubbo.common.extension.ExtensionFactory); Assertions.assertTrue(myfactory instanceof MyExtensionFactory); - ExtensionInjector spring = ExtensionLoader.getExtensionLoader(ExtensionInjector.class).getExtension("spring"); + ExtensionInjector spring = + ExtensionLoader.getExtensionLoader(ExtensionInjector.class).getExtension("spring"); Assertions.assertTrue(spring instanceof ExtensionInjector); Assertions.assertFalse(spring instanceof ExtensionFactory); Assertions.assertFalse(spring instanceof com.alibaba.dubbo.common.extension.ExtensionFactory); @@ -58,13 +59,11 @@ class ExtensionTest { @Test void testLoadActivateExtension() { // test default - URL url = URL.valueOf("test://localhost/test") - .addParameter(GROUP_KEY, "old_group"); - List list = getExtensionLoader(ActivateExt1.class) - .getActivateExtension(url, new String[]{}, "old_group"); + URL url = URL.valueOf("test://localhost/test").addParameter(GROUP_KEY, "old_group"); + List list = + getExtensionLoader(ActivateExt1.class).getActivateExtension(url, new String[] {}, "old_group"); Assertions.assertEquals(2, list.size()); Assertions.assertTrue(list.get(0).getClass() == OldActivateExt1Impl2.class - || list.get(0).getClass() == OldActivateExt1Impl3.class); - + || list.get(0).getClass() == OldActivateExt1Impl3.class); } } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/MockDispatcher.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/MockDispatcher.java index 732f333c08..5b5e77c897 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/MockDispatcher.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/MockDispatcher.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension; import org.apache.dubbo.common.URL; diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/MyExtensionFactory.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/MyExtensionFactory.java index d2187b9d74..548b5f0b8a 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/MyExtensionFactory.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/MyExtensionFactory.java @@ -29,7 +29,7 @@ public class MyExtensionFactory implements ExtensionFactory { } public static class InjectObject { - + private final String name; public InjectObject(final String name) { diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/activate/ActivateExt1.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/activate/ActivateExt1.java index c00a988577..e828f7775d 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/activate/ActivateExt1.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/activate/ActivateExt1.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension.activate; import org.apache.dubbo.common.extension.SPI; diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateExt1Impl1.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateExt1Impl1.java index fe3e082d49..8c62c2462f 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateExt1Impl1.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/activate/impl/ActivateExt1Impl1.java @@ -14,13 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension.activate.impl; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.extension.activate.ActivateExt1; -@Activate(order = 1, group = {"default_group"}) +@Activate( + order = 1, + group = {"default_group"}) public class ActivateExt1Impl1 implements ActivateExt1 { public String echo(String msg) { return msg; diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/ActivateComparatorTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/ActivateComparatorTest.java index 1c1cf7dc80..9ddcd7d19d 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/ActivateComparatorTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/ActivateComparatorTest.java @@ -18,25 +18,26 @@ package org.apache.dubbo.common.extension.support; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.Collections; import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + class ActivateComparatorTest { private ActivateComparator activateComparator; @BeforeEach public void setup() { - activateComparator = new ActivateComparator(ApplicationModel.defaultModel().getExtensionDirector()); + activateComparator = + new ActivateComparator(ApplicationModel.defaultModel().getExtensionDirector()); } @Test - void testActivateComparator(){ + void testActivateComparator() { Filter1 f1 = new Filter1(); Filter2 f2 = new Filter2(); Filter3 f3 = new Filter3(); diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter0.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter0.java index 612440894d..1a08826412 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter0.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter0.java @@ -19,5 +19,4 @@ package org.apache.dubbo.common.extension.support; import org.apache.dubbo.common.extension.SPI; @SPI -public interface Filter0 { -} +public interface Filter0 {} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter1.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter1.java index 5f30dd650e..b1408919bf 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter1.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter1.java @@ -19,5 +19,4 @@ package org.apache.dubbo.common.extension.support; import org.apache.dubbo.common.extension.Activate; @Activate -public class Filter1 implements Filter0{ -} +public class Filter1 implements Filter0 {} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter2.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter2.java index df93fa6eaf..3b9b9e27c8 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter2.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter2.java @@ -19,5 +19,4 @@ package org.apache.dubbo.common.extension.support; import org.apache.dubbo.common.extension.Activate; @Activate(before = "_1") -public class Filter2 implements Filter0{ -} +public class Filter2 implements Filter0 {} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter3.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter3.java index c02aaa13c2..38f787a306 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter3.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter3.java @@ -19,5 +19,4 @@ package org.apache.dubbo.common.extension.support; import org.apache.dubbo.common.extension.Activate; @Activate(after = "_4") -public class Filter3 implements Filter0{ -} +public class Filter3 implements Filter0 {} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter4.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter4.java index 353874bc9a..fdca0bcff5 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter4.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Filter4.java @@ -19,5 +19,4 @@ package org.apache.dubbo.common.extension.support; import org.apache.dubbo.common.extension.Activate; @Activate(before = "_2") -public class Filter4 implements Filter0{ -} +public class Filter4 implements Filter0 {} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/OldFilter0.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/OldFilter0.java index c01e4c93b2..ba1be8a1aa 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/OldFilter0.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/OldFilter0.java @@ -16,5 +16,4 @@ */ package org.apache.dubbo.common.extension.support; -public interface OldFilter0 extends Filter0 { -} +public interface OldFilter0 extends Filter0 {} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/OldFilter5.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/OldFilter5.java index 58feca1692..2f1c73170b 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/OldFilter5.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/OldFilter5.java @@ -16,9 +16,7 @@ */ package org.apache.dubbo.common.extension.support; - import com.alibaba.dubbo.common.extension.Activate; @Activate(after = "_4") -public class OldFilter5 implements OldFilter0 { -} +public class OldFilter5 implements OldFilter0 {} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter0.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter0.java index 634e92f12f..c900d47480 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter0.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter0.java @@ -14,11 +14,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension.support; import org.apache.dubbo.common.extension.SPI; @SPI -public interface Order0Filter0 { -} +public interface Order0Filter0 {} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter1.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter1.java index cf23ffee94..a58500f413 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter1.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter1.java @@ -14,11 +14,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension.support; import org.apache.dubbo.common.extension.Activate; @Activate -public class Order0Filter1 implements Order0Filter0 { -} +public class Order0Filter1 implements Order0Filter0 {} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter2.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter2.java index b09ed993a9..99b08f9ebb 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter2.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/support/Order0Filter2.java @@ -14,11 +14,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.extension.support; import org.apache.dubbo.common.extension.Activate; @Activate -public class Order0Filter2 implements Order0Filter0 { -} +public class Order0Filter2 implements Order0Filter0 {} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/common/utils/AnnotationUtilsTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/common/utils/AnnotationUtilsTest.java index 26b1960f35..da9d879335 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/common/utils/AnnotationUtilsTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/common/utils/AnnotationUtilsTest.java @@ -20,8 +20,6 @@ import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.config.annotation.Service; -import org.junit.jupiter.api.Test; - import java.lang.annotation.Annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; @@ -34,6 +32,8 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Test; + import static java.util.Arrays.asList; import static org.apache.dubbo.common.utils.AnnotationUtils.excludedType; import static org.apache.dubbo.common.utils.AnnotationUtils.filterDefaultValues; @@ -160,11 +160,11 @@ class AnnotationUtilsTest { annotations = getAllDeclaredAnnotations(findMethod(A.class, "execute")); MyAdaptive myAdaptive = (MyAdaptive) annotations.get(0); - assertArrayEquals(new String[]{"e"}, myAdaptive.value()); + assertArrayEquals(new String[] {"e"}, myAdaptive.value()); annotations = getAllDeclaredAnnotations(findMethod(B.class, "execute")); Adaptive adaptive = (Adaptive) annotations.get(0); - assertArrayEquals(new String[]{"f"}, adaptive.value()); + assertArrayEquals(new String[] {"f"}, adaptive.value()); } @Test @@ -210,23 +210,26 @@ class AnnotationUtilsTest { assertEquals(set3, set4); } - @Test void testIsAnnotationPresent() { assertTrue(isAnnotationPresent(A.class, true, Service.class)); - assertTrue(isAnnotationPresent(A.class, true, Service.class, com.alibaba.dubbo.config.annotation.Service.class)); + assertTrue( + isAnnotationPresent(A.class, true, Service.class, com.alibaba.dubbo.config.annotation.Service.class)); assertTrue(isAnnotationPresent(A.class, Service.class)); assertTrue(isAnnotationPresent(A.class, "org.apache.dubbo.config.annotation.Service")); - assertTrue(AnnotationUtils.isAllAnnotationPresent(A.class, Service.class, Service.class, com.alibaba.dubbo.config.annotation.Service.class)); + assertTrue(AnnotationUtils.isAllAnnotationPresent( + A.class, Service.class, Service.class, com.alibaba.dubbo.config.annotation.Service.class)); assertTrue(isAnnotationPresent(A.class, Deprecated.class)); } @Test void testIsAnyAnnotationPresent() { - assertTrue(isAnyAnnotationPresent(A.class, Service.class, com.alibaba.dubbo.config.annotation.Service.class, Deprecated.class)); + assertTrue(isAnyAnnotationPresent( + A.class, Service.class, com.alibaba.dubbo.config.annotation.Service.class, Deprecated.class)); assertTrue(isAnyAnnotationPresent(A.class, Service.class, com.alibaba.dubbo.config.annotation.Service.class)); assertTrue(isAnyAnnotationPresent(A.class, Service.class, Deprecated.class)); - assertTrue(isAnyAnnotationPresent(A.class, com.alibaba.dubbo.config.annotation.Service.class, Deprecated.class)); + assertTrue( + isAnyAnnotationPresent(A.class, com.alibaba.dubbo.config.annotation.Service.class, Deprecated.class)); assertTrue(isAnyAnnotationPresent(A.class, Service.class)); assertTrue(isAnyAnnotationPresent(A.class, com.alibaba.dubbo.config.annotation.Service.class)); assertTrue(isAnyAnnotationPresent(A.class, Deprecated.class)); @@ -282,16 +285,14 @@ class AnnotationUtilsTest { } @Service(interfaceName = "java.lang.CharSequence", interfaceClass = CharSequence.class) - @com.alibaba.dubbo.config.annotation.Service(interfaceName = "java.lang.CharSequence", interfaceClass = CharSequence.class) + @com.alibaba.dubbo.config.annotation.Service( + interfaceName = "java.lang.CharSequence", + interfaceClass = CharSequence.class) @Adaptive(value = {"a", "b", "c"}) static class A { @MyAdaptive("e") - public void execute() { - - } - - + public void execute() {} } @Documented @@ -299,40 +300,28 @@ class AnnotationUtilsTest { @Target({ElementType.TYPE}) @Inherited @DubboService(interfaceClass = Cloneable.class) - @interface Service2 { - - - } + @interface Service2 {} @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Inherited @Service2 - @interface Service3 { - - - } + @interface Service3 {} @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Inherited @Service3 - @interface Service4 { - - - } + @interface Service4 {} @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Inherited @Service4 - @interface Service5 { - - - } + @interface Service5 {} @Documented @Retention(RetentionPolicy.RUNTIME) @@ -342,7 +331,6 @@ class AnnotationUtilsTest { @interface MyAdaptive { String[] value() default {}; - } @Service5 @@ -350,17 +338,11 @@ class AnnotationUtilsTest { @Adaptive("f") @Override - public void execute() { - - } - - + public void execute() {} } @MyAdaptive - static class C extends B { - - } + static class C extends B {} private void assertADeclaredAnnotations(List annotations, int offset) { int size = 3 + offset; @@ -369,21 +351,25 @@ class AnnotationUtilsTest { boolean alibabaServiceFound = false; boolean adaptiveFound = false; - for (Annotation annotation: annotations) { + for (Annotation annotation : annotations) { if (!apacheServiceFound && (annotation instanceof Service)) { - assertEquals("java.lang.CharSequence", ((Service)annotation).interfaceName()); - assertEquals(CharSequence.class, ((Service)annotation).interfaceClass()); + assertEquals("java.lang.CharSequence", ((Service) annotation).interfaceName()); + assertEquals(CharSequence.class, ((Service) annotation).interfaceClass()); apacheServiceFound = true; continue; } if (!alibabaServiceFound && (annotation instanceof com.alibaba.dubbo.config.annotation.Service)) { - assertEquals("java.lang.CharSequence", ((com.alibaba.dubbo.config.annotation.Service)annotation).interfaceName()); - assertEquals(CharSequence.class, ((com.alibaba.dubbo.config.annotation.Service)annotation).interfaceClass()); + assertEquals( + "java.lang.CharSequence", + ((com.alibaba.dubbo.config.annotation.Service) annotation).interfaceName()); + assertEquals( + CharSequence.class, + ((com.alibaba.dubbo.config.annotation.Service) annotation).interfaceClass()); alibabaServiceFound = true; continue; } if (!adaptiveFound && (annotation instanceof Adaptive)) { - assertArrayEquals(new String[]{"a", "b", "c"}, ((Adaptive)annotation).value()); + assertArrayEquals(new String[] {"a", "b", "c"}, ((Adaptive) annotation).value()); adaptiveFound = true; continue; } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java index 3d35af9984..fb2b13d6eb 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java @@ -14,19 +14,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + import com.alibaba.dubbo.config.ApplicationConfig; import com.alibaba.dubbo.config.MonitorConfig; import com.alibaba.dubbo.config.RegistryConfig; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY; import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP; diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/ArgumentConfigTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/ArgumentConfigTest.java index ba1ba93a63..2ffa853a0c 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/ArgumentConfigTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/ArgumentConfigTest.java @@ -14,15 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; -import com.alibaba.dubbo.config.ArgumentConfig; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.Map; +import com.alibaba.dubbo.config.ArgumentConfig; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/ConfigTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/ConfigTest.java index 2470a2da24..2a4f4af975 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/ConfigTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/ConfigTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; import org.apache.dubbo.config.bootstrap.DubboBootstrap; @@ -29,8 +28,10 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class ConfigTest { - private com.alibaba.dubbo.config.ApplicationConfig applicationConfig = new com.alibaba.dubbo.config.ApplicationConfig("first-dubbo-test"); - private com.alibaba.dubbo.config.RegistryConfig registryConfig = new com.alibaba.dubbo.config.RegistryConfig("multicast://224.5.6.7:1234"); + private com.alibaba.dubbo.config.ApplicationConfig applicationConfig = + new com.alibaba.dubbo.config.ApplicationConfig("first-dubbo-test"); + private com.alibaba.dubbo.config.RegistryConfig registryConfig = + new com.alibaba.dubbo.config.RegistryConfig("multicast://224.5.6.7:1234"); @AfterEach public void tearDown() { diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/ConsumerConfigTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/ConsumerConfigTest.java index 5dda5ae966..1e4a51fb1d 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/ConsumerConfigTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/ConsumerConfigTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; import com.alibaba.dubbo.config.ConsumerConfig; diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/MethodConfigTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/MethodConfigTest.java index f53106d793..9e4b975adf 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/MethodConfigTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/MethodConfigTest.java @@ -14,21 +14,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; import org.apache.dubbo.rpc.model.AsyncMethodInfo; import org.apache.dubbo.service.Person; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + import com.alibaba.dubbo.config.ArgumentConfig; import com.alibaba.dubbo.config.MethodConfig; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - import static org.apache.dubbo.config.Constants.ON_INVOKE_INSTANCE_ATTRIBUTE_KEY; import static org.apache.dubbo.config.Constants.ON_INVOKE_METHOD_ATTRIBUTE_KEY; import static org.apache.dubbo.config.Constants.ON_RETURN_INSTANCE_ATTRIBUTE_KEY; @@ -124,7 +123,7 @@ class MethodConfigTest { assertEquals(methodInfo.getOnreturnMethod(), Person.class.getMethod(methodName, String.class)); } - //@Test + // @Test void testOnreturn() { MethodConfig method = new MethodConfig(); method.setOnreturn("on-return-object"); @@ -150,7 +149,7 @@ class MethodConfigTest { assertThat(parameters.size(), is(0)); } - //@Test + // @Test void testOnthrow() { MethodConfig method = new MethodConfig(); method.setOnthrow("on-throw-object"); @@ -176,7 +175,7 @@ class MethodConfigTest { assertThat(parameters.size(), is(0)); } - //@Test + // @Test void testOninvoke() { MethodConfig method = new MethodConfig(); method.setOninvoke("on-invoke-object"); diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/ModuleConfigTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/ModuleConfigTest.java index 45c60bbb20..ff52b0aeb1 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/ModuleConfigTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/ModuleConfigTest.java @@ -14,19 +14,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + import com.alibaba.dubbo.config.ModuleConfig; import com.alibaba.dubbo.config.MonitorConfig; import com.alibaba.dubbo.config.RegistryConfig; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/ProtocolConfigTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/ProtocolConfigTest.java index 983d2bb43f..cb31ea9b4b 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/ProtocolConfigTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/ProtocolConfigTest.java @@ -14,16 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; -import com.alibaba.dubbo.config.ProtocolConfig; -import org.junit.jupiter.api.Test; - import java.util.Collections; import java.util.HashMap; import java.util.Map; +import com.alibaba.dubbo.config.ProtocolConfig; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/ProviderConfigTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/ProviderConfigTest.java index ccbffaebd3..d88abf52a6 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/ProviderConfigTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/ProviderConfigTest.java @@ -14,15 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; -import com.alibaba.dubbo.config.ProviderConfig; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.Map; +import com.alibaba.dubbo.config.ProviderConfig; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; @@ -89,7 +88,6 @@ class ProviderConfigTest { assertThat(parameters, not(hasKey("/context-path"))); } - @Test void testThreads() throws Exception { ProviderConfig provider = new ProviderConfig(); diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java index 7eacd6acce..a4bdd495f2 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; import org.apache.dubbo.config.bootstrap.DubboBootstrap; diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java index dd42978cfb..fca18eb1f2 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java @@ -14,16 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; -import com.alibaba.dubbo.config.RegistryConfig; -import org.junit.jupiter.api.Test; - import java.util.Collections; import java.util.HashMap; import java.util.Map; +import com.alibaba.dubbo.config.RegistryConfig; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/SignatureTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/SignatureTest.java index ac1d1647dc..ffb7d479d5 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/SignatureTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/SignatureTest.java @@ -19,47 +19,50 @@ package org.apache.dubbo.config; import org.apache.dubbo.common.utils.IOUtils; import org.apache.dubbo.common.utils.StringUtils; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsCollectionWithSize.hasSize; public class SignatureTest { @ParameterizedTest - @ValueSource(classes = { - com.alibaba.dubbo.config.ApplicationConfig.class, - com.alibaba.dubbo.config.ArgumentConfig.class, - com.alibaba.dubbo.config.ConsumerConfig.class, - com.alibaba.dubbo.config.MethodConfig.class, - com.alibaba.dubbo.config.ModuleConfig.class, - com.alibaba.dubbo.config.MonitorConfig.class, - com.alibaba.dubbo.config.ProtocolConfig.class, - com.alibaba.dubbo.config.ProviderConfig.class, - com.alibaba.dubbo.config.ReferenceConfig.class, - com.alibaba.dubbo.config.RegistryConfig.class, - com.alibaba.dubbo.config.ServiceConfig.class}) + @ValueSource( + classes = { + com.alibaba.dubbo.config.ApplicationConfig.class, + com.alibaba.dubbo.config.ArgumentConfig.class, + com.alibaba.dubbo.config.ConsumerConfig.class, + com.alibaba.dubbo.config.MethodConfig.class, + com.alibaba.dubbo.config.ModuleConfig.class, + com.alibaba.dubbo.config.MonitorConfig.class, + com.alibaba.dubbo.config.ProtocolConfig.class, + com.alibaba.dubbo.config.ProviderConfig.class, + com.alibaba.dubbo.config.ReferenceConfig.class, + com.alibaba.dubbo.config.RegistryConfig.class, + com.alibaba.dubbo.config.ServiceConfig.class + }) void test(Class targetClass) throws IOException { String[] lines = IOUtils.readLines( - this.getClass().getClassLoader().getResourceAsStream("definition/" + targetClass.getName())); + this.getClass().getClassLoader().getResourceAsStream("definition/" + targetClass.getName())); // only compare setter now. // getter cannot make it compatible with the old version. Set setters = Arrays.stream(lines) - .filter(StringUtils::isNotEmpty) - .filter(s -> !s.startsWith("//")) - .filter(s -> s.contains("set")) - .collect(Collectors.toSet()); + .filter(StringUtils::isNotEmpty) + .filter(s -> !s.startsWith("//")) + .filter(s -> s.contains("set")) + .collect(Collectors.toSet()); for (Method method : targetClass.getMethods()) { - setters.remove(method.toString().replace(method.getDeclaringClass().getName() + ".", targetClass.getName() + ".")); + setters.remove( + method.toString().replace(method.getDeclaringClass().getName() + ".", targetClass.getName() + ".")); } assertThat(setters.toString(), setters, hasSize(0)); diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/Box.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/Box.java index ed168fc37a..9fc3119aa4 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/Box.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/Box.java @@ -19,5 +19,4 @@ package org.apache.dubbo.config.spring.api; public interface Box { String getName(); - } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/DemoService.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/DemoService.java index 84fd939716..a0314e6f58 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/DemoService.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/DemoService.java @@ -24,5 +24,4 @@ public interface DemoService { String sayName(String name); Box getBox(); - } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/HelloService.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/HelloService.java index 3cc5416096..d6e9fbcf64 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/HelloService.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/api/HelloService.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config.spring.api; public interface HelloService { diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationTestConfiguration.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationTestConfiguration.java index 59f1385a13..358bda2dc6 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationTestConfiguration.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationTestConfiguration.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config.spring.beans.factory.annotation; - import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.RegistryConfig; @@ -76,7 +75,7 @@ public class ServiceAnnotationTestConfiguration { * * @return {@link ProtocolConfig} Bean */ - @Bean//("dubbo") + @Bean // ("dubbo") public ProtocolConfig protocolConfig() { ProtocolConfig protocolConfig = new ProtocolConfig(); protocolConfig.setName("dubbo"); @@ -95,15 +94,10 @@ public class ServiceAnnotationTestConfiguration { } @Override - public void commit(TransactionStatus status) throws TransactionException { - - } + public void commit(TransactionStatus status) throws TransactionException {} @Override - public void rollback(TransactionStatus status) throws TransactionException { - - } + public void rollback(TransactionStatus status) throws TransactionException {} }; } - } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrarTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrarTest.java index 6ad42e80c7..5f5d4ac3aa 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrarTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrarTest.java @@ -45,8 +45,7 @@ class DubboComponentScanRegistrarTest { } @AfterEach - public void tearDown() { - } + public void tearDown() {} @Test void test() { @@ -71,7 +70,6 @@ class DubboComponentScanRegistrarTest { // Test @Transactional is present or not Assertions.assertNotNull(findAnnotation(beanClass, Transactional.class)); - // consumer app AnnotationConfigApplicationContext consumerContext = new AnnotationConfigApplicationContext(); @@ -121,9 +119,5 @@ class DubboComponentScanRegistrarTest { providerContext.close(); consumerContext.close(); - - } - - } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationTest.java index f4b705315e..69acec2129 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationTest.java @@ -22,6 +22,8 @@ import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; +import java.io.IOException; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -29,8 +31,6 @@ import org.junit.jupiter.api.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.core.io.support.ResourcePropertySource; -import java.io.IOException; - /** * {@link DubboConfigConfiguration} Test * @@ -47,7 +47,6 @@ class DubboConfigConfigurationTest { context = new AnnotationConfigApplicationContext(); ResourcePropertySource propertySource = new ResourcePropertySource("META-INF/config.properties"); context.getEnvironment().getPropertySources().addFirst(propertySource); - } @AfterEach @@ -90,5 +89,4 @@ class DubboConfigConfigurationTest { RegistryConfig registry2 = context.getBean("registry2", RegistryConfig.class); Assertions.assertEquals(2182, registry2.getPort()); } - -} \ No newline at end of file +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfigTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfigTest.java index 803241d535..ba5392a02d 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfigTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfigTest.java @@ -27,18 +27,17 @@ import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.Collection; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.PropertySource; -import java.util.Collection; - import static com.alibaba.spring.util.BeanRegistrar.hasAlias; import static org.junit.jupiter.api.Assertions.assertFalse; - /** * {@link EnableDubboConfig} Test * @@ -56,7 +55,7 @@ class EnableDubboConfigTest { DubboBootstrap.reset(); } - //@Test + // @Test public void testSingle() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @@ -88,7 +87,6 @@ class EnableDubboConfigTest { ProviderConfig providerConfig = context.getBean(ProviderConfig.class); Assertions.assertEquals("127.0.0.1", providerConfig.getHost()); - // consumer ConsumerConfig consumerConfig = context.getBean(ConsumerConfig.class); Assertions.assertEquals("netty", consumerConfig.getClient()); @@ -98,7 +96,7 @@ class EnableDubboConfigTest { assertFalse(hasAlias(context, "org.apache.dubbo.config.MonitorConfig#0", "zookeeper")); } - //@Test + // @Test public void testMultiple() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @@ -119,22 +117,17 @@ class EnableDubboConfigTest { configManager.getProtocol("rest").get(); configManager.getProtocol("thrift").get(); - // asserts aliases -// assertTrue(hasAlias(context, "applicationBean2", "dubbo-demo-application2")); -// assertTrue(hasAlias(context, "applicationBean3", "dubbo-demo-application3")); + // assertTrue(hasAlias(context, "applicationBean2", "dubbo-demo-application2")); + // assertTrue(hasAlias(context, "applicationBean3", "dubbo-demo-application3")); } @EnableDubboConfig @PropertySource("META-INF/config.properties") - private static class TestMultipleConfig { - - } + private static class TestMultipleConfig {} @EnableDubboConfig(multiple = false) @PropertySource("META-INF/config.properties") - private static class TestConfig { - - } -} \ No newline at end of file + private static class TestConfig {} +} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboTest.java index 729d5ec5f0..ebaa0dcded 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboTest.java @@ -37,6 +37,7 @@ import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionException; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.annotation.EnableTransactionManagement; + /** * {@link EnableDubbo} Test * @@ -113,7 +114,6 @@ class EnableDubboTest { // Test multiple binding Assertions.assertEquals("N/A", registryConfig.getAddress()); - } @EnableDubbo(scanBasePackages = "org.apache.dubbo.config.spring.context.annotation.provider") @@ -134,17 +134,11 @@ class EnableDubboTest { } @Override - public void commit(TransactionStatus status) throws TransactionException { - - } + public void commit(TransactionStatus status) throws TransactionException {} @Override - public void rollback(TransactionStatus status) throws TransactionException { - - } + public void rollback(TransactionStatus status) throws TransactionException {} }; } } - - } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/ConsumerConfiguration.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/ConsumerConfiguration.java index 9fd7b2e1b7..5f3aabb3f9 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/ConsumerConfiguration.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/ConsumerConfiguration.java @@ -28,9 +28,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @Configuration("consumerConfiguration") -@DubboComponentScan( - basePackageClasses = ConsumerConfiguration.class -) +@DubboComponentScan(basePackageClasses = ConsumerConfiguration.class) @PropertySource("META-INF/default.properties") public class ConsumerConfiguration { @@ -80,13 +78,12 @@ public class ConsumerConfiguration { this.demoService = demoService; } - @Bean public Child c() { return new Child(); } - public static abstract class Ancestor { + public abstract static class Ancestor { @Reference(version = "2.5.7", url = remoteURL) private DemoService demoServiceFromAncestor; @@ -100,7 +97,7 @@ public class ConsumerConfiguration { } } - public static abstract class Parent extends Ancestor { + public abstract static class Parent extends Ancestor { private DemoService demoServiceFromParent; @@ -112,7 +109,6 @@ public class ConsumerConfiguration { public void setDemoServiceFromParent(DemoService demoServiceFromParent) { this.demoServiceFromParent = demoServiceFromParent; } - } public static class Child extends Parent { @@ -123,7 +119,6 @@ public class ConsumerConfiguration { @Reference(version = "2.5.7", url = remoteURL) private DemoService demoServiceFromChild; - public DemoService getDemoService() { return demoService; } @@ -136,5 +131,4 @@ public class ConsumerConfiguration { this.demoServiceFromChild = demoServiceFromChild; } } - } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/test/TestConsumerConfiguration.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/test/TestConsumerConfiguration.java index 5869d95e89..87a44c7b42 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/test/TestConsumerConfiguration.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/test/TestConsumerConfiguration.java @@ -39,7 +39,8 @@ public class TestConsumerConfiguration { private static final String remoteURL = "dubbo://127.0.0.1:12345?version=2.5.7"; - @Reference(id = "demoService", + @Reference( + id = "demoService", version = "2.5.7", url = remoteURL, application = "dubbo-demo-application", @@ -70,15 +71,14 @@ public class TestConsumerConfiguration { this.demoService = demoService; } - @Bean public Child c() { return new Child(); } - public static abstract class Ancestor { + public abstract static class Ancestor { - @DubboReference(version = "2.5.7", url = remoteURL,filter = "mymock", application = "dubbo-demo-application") + @DubboReference(version = "2.5.7", url = remoteURL, filter = "mymock", application = "dubbo-demo-application") private DemoService demoServiceFromAncestor; public DemoService getDemoServiceFromAncestor() { @@ -90,7 +90,7 @@ public class TestConsumerConfiguration { } } - public static abstract class Parent extends Ancestor { + public abstract static class Parent extends Ancestor { private DemoService demoServiceFromParent; @@ -98,11 +98,14 @@ public class TestConsumerConfiguration { return demoServiceFromParent; } - @com.alibaba.dubbo.config.annotation.Reference(version = "2.5.7", url = remoteURL, filter = "mymock", application = "dubbo-demo-application") + @com.alibaba.dubbo.config.annotation.Reference( + version = "2.5.7", + url = remoteURL, + filter = "mymock", + application = "dubbo-demo-application") public void setDemoServiceFromParent(DemoService demoServiceFromParent) { this.demoServiceFromParent = demoServiceFromParent; } - } public static class Child extends Parent { diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DefaultHelloService.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DefaultHelloService.java index c4df6f4340..8b50e8780b 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DefaultHelloService.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DefaultHelloService.java @@ -34,5 +34,4 @@ public class DefaultHelloService implements HelloService { public String sayHello(String name) { return "Greeting, " + name; } - } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DemoServiceImpl.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DemoServiceImpl.java index 8ee2a8a09f..62f7e24b74 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DemoServiceImpl.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DemoServiceImpl.java @@ -23,7 +23,6 @@ import org.apache.dubbo.config.spring.api.DemoService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; - /** * {@link DemoService} Service implementation * @@ -34,8 +33,7 @@ import org.springframework.transaction.annotation.Transactional; application = "${demo.service.application}", protocol = "${demo.service.protocol}", registry = "${demo.service.registry}", - methods = @Method(timeout = 100,name = "sayName") -) + methods = @Method(timeout = 100, name = "sayName")) @Service @Transactional public class DemoServiceImpl implements DemoService { diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/ProviderConfiguration.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/ProviderConfiguration.java index 59e0cb3d77..d4e103aad7 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/ProviderConfiguration.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/ProviderConfiguration.java @@ -21,6 +21,8 @@ import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan; +import java.util.UUID; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; @@ -33,8 +35,6 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.support.AbstractPlatformTransactionManager; import org.springframework.transaction.support.DefaultTransactionStatus; -import java.util.UUID; - @DubboComponentScan(basePackages = "org.apache.dubbo.config.spring.context.annotation.provider") @PropertySource("classpath:/META-INF/default.properties") @EnableTransactionManagement @@ -115,6 +115,4 @@ public class ProviderConfiguration { } }; } - } - diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockDao.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockDao.java index 9006995903..c43c9bd1b8 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockDao.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockDao.java @@ -19,6 +19,4 @@ package org.apache.dubbo.config.spring.filter; /** * MockDao */ -public interface MockDao { - -} +public interface MockDao {} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockDaoImpl.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockDaoImpl.java index d8f6f9cd75..470e50db88 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockDaoImpl.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockDaoImpl.java @@ -19,6 +19,4 @@ package org.apache.dubbo.config.spring.filter; /** * MockDaoImpl */ -public class MockDaoImpl implements MockDao { - -} +public class MockDaoImpl implements MockDao {} diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockFilter.java b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockFilter.java index e41d734c60..daedbb3990 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockFilter.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/config/spring/filter/MockFilter.java @@ -62,5 +62,4 @@ public class MockFilter implements Filter { public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { return invoker.invoke(invocation); } - } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/echo/EchoServiceTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/echo/EchoServiceTest.java index 74ad8d6cc6..cdd615874f 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/echo/EchoServiceTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/echo/EchoServiceTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.echo; import org.apache.dubbo.common.URL; @@ -35,7 +34,8 @@ class EchoServiceTest { @Test void testEcho() { DemoService server = new DemoServiceImpl(); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + ProxyFactory proxyFactory = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); URL url = URL.valueOf("dubbo://127.0.0.1:5342/" + DemoService.class.getName() + "?version=1.0.0"); Exporter exporter = protocol.export(proxyFactory.getInvoker(server, DemoService.class, url)); @@ -44,7 +44,8 @@ class EchoServiceTest { Object result = client.$echo("haha"); Assertions.assertEquals("haha", result); - org.apache.dubbo.rpc.service.EchoService newClient = (org.apache.dubbo.rpc.service.EchoService) proxyFactory.getProxy(invoker); + org.apache.dubbo.rpc.service.EchoService newClient = + (org.apache.dubbo.rpc.service.EchoService) proxyFactory.getProxy(invoker); Object res = newClient.$echo("hehe"); Assertions.assertEquals("hehe", res); invoker.destroy(); diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/filter/FilterTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/filter/FilterTest.java index 24996c2c32..a66ac4cda8 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/filter/FilterTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/filter/FilterTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.filter; import org.apache.dubbo.rpc.RpcException; @@ -48,7 +47,8 @@ class FilterTest { @Test void testDefault() throws Throwable { Invoker invoker = new LegacyInvoker(null); - org.apache.dubbo.rpc.Invocation invocation = new RpcInvocation(null, "echo", "DemoService", "DemoService", new Class[]{String.class}, new Object[]{"bbb"}); + org.apache.dubbo.rpc.Invocation invocation = new RpcInvocation( + null, "echo", "DemoService", "DemoService", new Class[] {String.class}, new Object[] {"bbb"}); org.apache.dubbo.rpc.Result res = myFilter.invoke(invoker, invocation); Assertions.assertEquals("alibaba", res.recreate()); } @@ -56,7 +56,8 @@ class FilterTest { @Test void testRecreate() throws Throwable { Invoker invoker = new LegacyInvoker(null); - org.apache.dubbo.rpc.Invocation invocation = new RpcInvocation(null, "echo", "DemoService", "DemoService", new Class[]{String.class}, new Object[]{"cc"}); + org.apache.dubbo.rpc.Invocation invocation = new RpcInvocation( + null, "echo", "DemoService", "DemoService", new Class[] {String.class}, new Object[] {"cc"}); org.apache.dubbo.rpc.Result res = myFilter.invoke(invoker, invocation); Assertions.assertEquals("123test", res.recreate()); } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java b/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java index 8495a944e9..cddcb9956b 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvocation.java @@ -56,11 +56,11 @@ public class LegacyInvocation implements Invocation { } public Class[] getParameterTypes() { - return new Class[]{String.class}; + return new Class[] {String.class}; } public Object[] getArguments() { - return new Object[]{arg0}; + return new Object[] {arg0}; } public Map getAttachments() { @@ -102,9 +102,7 @@ public class LegacyInvocation implements Invocation { } @Override - public void addInvokedInvoker(org.apache.dubbo.rpc.Invoker invoker) { - - } + public void addInvokedInvoker(org.apache.dubbo.rpc.Invoker invoker) {} @Override public List> getInvokedInvokers() { diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvoker.java b/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvoker.java index 328b842321..8b72325053 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvoker.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/filter/LegacyInvoker.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.filter; - import org.apache.dubbo.service.DemoService; import com.alibaba.dubbo.common.URL; @@ -68,7 +67,5 @@ public class LegacyInvoker implements Invoker { } @Override - public void destroy() { - } - + public void destroy() {} } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/filter/MyFilter.java b/dubbo-compatible/src/test/java/org/apache/dubbo/filter/MyFilter.java index 68c5c8786b..6f9dac3996 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/filter/MyFilter.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/filter/MyFilter.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.filter; import com.alibaba.dubbo.rpc.Filter; @@ -24,7 +23,6 @@ import com.alibaba.dubbo.rpc.Result; import com.alibaba.dubbo.rpc.RpcException; import com.alibaba.dubbo.rpc.RpcResult; - public class MyFilter implements Filter { public static int count = 0; diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/generic/GenericServiceTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/generic/GenericServiceTest.java index 3ec36e00f4..26f99a6f2d 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/generic/GenericServiceTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/generic/GenericServiceTest.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.generic; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.compact.Dubbo2CompactUtils; import org.apache.dubbo.common.extension.ExtensionLoader; @@ -36,17 +34,17 @@ import org.apache.dubbo.service.ComplexObject; import org.apache.dubbo.service.DemoService; import org.apache.dubbo.service.DemoServiceImpl; -import com.alibaba.dubbo.config.ReferenceConfig; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; +import com.alibaba.dubbo.config.ReferenceConfig; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + class GenericServiceTest { @BeforeEach @@ -57,18 +55,20 @@ class GenericServiceTest { @Test void testGeneric() { DemoService server = new DemoServiceImpl(); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + ProxyFactory proxyFactory = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); URL url = URL.valueOf("dubbo://127.0.0.1:5342/" + DemoService.class.getName() + "?version=1.0.0"); Exporter exporter = protocol.export(proxyFactory.getInvoker(server, DemoService.class, url)); Invoker invoker = protocol.refer(DemoService.class, url); GenericService client = (GenericService) proxyFactory.getProxy(invoker, true); - Object result = client.$invoke("sayHello", new String[]{"java.lang.String"}, new Object[]{"haha"}); + Object result = client.$invoke("sayHello", new String[] {"java.lang.String"}, new Object[] {"haha"}); Assertions.assertEquals("hello haha", result); - org.apache.dubbo.rpc.service.GenericService newClient = (org.apache.dubbo.rpc.service.GenericService) proxyFactory.getProxy(invoker, true); - Object res = newClient.$invoke("sayHello", new String[]{"java.lang.String"}, new Object[]{"hehe"}); + org.apache.dubbo.rpc.service.GenericService newClient = + (org.apache.dubbo.rpc.service.GenericService) proxyFactory.getProxy(invoker, true); + Object res = newClient.$invoke("sayHello", new String[] {"java.lang.String"}, new Object[] {"hehe"}); Assertions.assertEquals("hello hehe", res); invoker.destroy(); exporter.unexport(); @@ -77,20 +77,22 @@ class GenericServiceTest { @Test void testGeneric2() { DemoService server = new DemoServiceImpl(); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + ProxyFactory proxyFactory = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - URL url = URL.valueOf("dubbo://127.0.0.1:5342/" + DemoService.class.getName() + "?version=1.0.0&generic=true$timeout=3000"); + URL url = URL.valueOf( + "dubbo://127.0.0.1:5342/" + DemoService.class.getName() + "?version=1.0.0&generic=true$timeout=3000"); Exporter exporter = protocol.export(proxyFactory.getInvoker(server, DemoService.class, url)); Invoker invoker = protocol.refer(GenericService.class, url); GenericService client = proxyFactory.getProxy(invoker, true); - Object result = client.$invoke("sayHello", new String[]{"java.lang.String"}, new Object[]{"haha"}); + Object result = client.$invoke("sayHello", new String[] {"java.lang.String"}, new Object[] {"haha"}); Assertions.assertEquals("hello haha", result); Invoker invoker2 = protocol.refer(DemoService.class, url); GenericService client2 = (GenericService) proxyFactory.getProxy(invoker2, true); - Object result2 = client2.$invoke("sayHello", new String[]{"java.lang.String"}, new Object[]{"haha"}); + Object result2 = client2.$invoke("sayHello", new String[] {"java.lang.String"}, new Object[] {"haha"}); Assertions.assertEquals("hello haha", result2); invoker.destroy(); @@ -99,14 +101,14 @@ class GenericServiceTest { @Test void testGenericCompatible() { - DubboBootstrap.getInstance() - .application("test-app") - .initialize(); + DubboBootstrap.getInstance().application("test-app").initialize(); DemoService server = new DemoServiceImpl(); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + ProxyFactory proxyFactory = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - URL url = URL.valueOf("dubbo://127.0.0.1:5342/" + DemoService.class.getName() + "?version=1.0.0&generic=true$timeout=3000"); + URL url = URL.valueOf( + "dubbo://127.0.0.1:5342/" + DemoService.class.getName() + "?version=1.0.0&generic=true$timeout=3000"); Exporter exporter = protocol.export(proxyFactory.getInvoker(server, DemoService.class, url)); // simulate normal invoke @@ -118,7 +120,7 @@ class GenericServiceTest { GenericService client = (GenericService) proxyFactory.getProxy(invoker, true); Assertions.assertInstanceOf(Dubbo2CompactUtils.getGenericServiceClass(), client); - Object result = client.$invoke("sayHello", new String[]{"java.lang.String"}, new Object[]{"haha"}); + Object result = client.$invoke("sayHello", new String[] {"java.lang.String"}, new Object[] {"haha"}); Assertions.assertEquals("hello haha", result); invoker.destroy(); @@ -128,12 +130,13 @@ class GenericServiceTest { @Test void testGenericComplexCompute4FullServiceMetadata() { DemoService server = new DemoServiceImpl(); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + ProxyFactory proxyFactory = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - URL url = URL.valueOf("dubbo://127.0.0.1:5342/" + DemoService.class.getName() + "?version=1.0.0&generic=true$timeout=3000"); + URL url = URL.valueOf( + "dubbo://127.0.0.1:5342/" + DemoService.class.getName() + "?version=1.0.0&generic=true$timeout=3000"); Exporter exporter = protocol.export(proxyFactory.getInvoker(server, DemoService.class, url)); - String var1 = "v1"; int var2 = 234; long l = 555; @@ -148,15 +151,15 @@ class GenericServiceTest { Invoker invoker = protocol.refer(GenericService.class, url); - GenericService client = proxyFactory.getProxy(invoker, true); - Object result = client.$invoke(methodDefinition.getName(), methodDefinition.getParameterTypes(), new Object[]{"haha", mapObject}); + Object result = client.$invoke( + methodDefinition.getName(), methodDefinition.getParameterTypes(), new Object[] {"haha", mapObject}); Assertions.assertEquals("haha###" + complexObject.toString(), result); - Invoker invoker2 = protocol.refer(DemoService.class, url); GenericService client2 = (GenericService) proxyFactory.getProxy(invoker2, true); - Object result2 = client2.$invoke("complexCompute", methodDefinition.getParameterTypes(), new Object[]{"haha2", mapObject}); + Object result2 = client2.$invoke( + "complexCompute", methodDefinition.getParameterTypes(), new Object[] {"haha2", mapObject}); Assertions.assertEquals("haha2###" + complexObject.toString(), result2); invoker.destroy(); @@ -166,25 +169,35 @@ class GenericServiceTest { @Test void testGenericFindComplexObject4FullServiceMetadata() { DemoService server = new DemoServiceImpl(); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + ProxyFactory proxyFactory = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - URL url = URL.valueOf("dubbo://127.0.0.1:5342/" + DemoService.class.getName() + "?version=1.0.0&generic=true$timeout=3000"); + URL url = URL.valueOf( + "dubbo://127.0.0.1:5342/" + DemoService.class.getName() + "?version=1.0.0&generic=true$timeout=3000"); Exporter exporter = protocol.export(proxyFactory.getInvoker(server, DemoService.class, url)); - String var1 = "v1"; int var2 = 234; long l = 555; String[] var3 = {"var31", "var32"}; List var4 = Arrays.asList(2, 4, 8); ComplexObject.TestEnum testEnum = ComplexObject.TestEnum.VALUE2; - //ComplexObject complexObject = createComplexObject(var1, var2, l, var3, var4, testEnum); + // ComplexObject complexObject = createComplexObject(var1, var2, l, var3, var4, testEnum); Invoker invoker = protocol.refer(GenericService.class, url); GenericService client = proxyFactory.getProxy(invoker, true); - Object result = client.$invoke("findComplexObject", new String[]{"java.lang.String", "int", "long", "java.lang.String[]", "java.util.List", "org.apache.dubbo.service.ComplexObject$TestEnum"}, - new Object[]{var1, var2, l, var3, var4, testEnum}); + Object result = client.$invoke( + "findComplexObject", + new String[] { + "java.lang.String", + "int", + "long", + "java.lang.String[]", + "java.util.List", + "org.apache.dubbo.service.ComplexObject$TestEnum" + }, + new Object[] {var1, var2, l, var3, var4, testEnum}); Assertions.assertNotNull(result); ComplexObject r = map2bean((Map) result); Assertions.assertEquals(r, createComplexObject(var1, var2, l, var3, var4, testEnum)); @@ -202,7 +215,14 @@ class GenericServiceTest { return null; } - Map createComplexObject(FullServiceDefinition fullServiceDefinition, String var1, int var2, long l, String[] var3, List var4, ComplexObject.TestEnum testEnum) { + Map createComplexObject( + FullServiceDefinition fullServiceDefinition, + String var1, + int var2, + long l, + String[] var3, + List var4, + ComplexObject.TestEnum testEnum) { List typeDefinitions = fullServiceDefinition.getTypes(); TypeDefinition topTypeDefinition = null; TypeDefinition innerTypeDefinition = null; @@ -220,21 +240,37 @@ class GenericServiceTest { } } Assertions.assertEquals("long", topTypeDefinition.getProperties().get("v")); - Assertions.assertEquals("java.util.Map", topTypeDefinition.getProperties().get("maps")); - Assertions.assertEquals("org.apache.dubbo.service.ComplexObject.InnerObject", topTypeDefinition.getProperties().get("innerObject")); - Assertions.assertEquals("java.util.List", topTypeDefinition.getProperties().get("intList")); - Assertions.assertEquals("java.lang.String[]", topTypeDefinition.getProperties().get("strArrays")); - Assertions.assertEquals("org.apache.dubbo.service.ComplexObject.InnerObject3[]", topTypeDefinition.getProperties().get("innerObject3")); - Assertions.assertEquals("org.apache.dubbo.service.ComplexObject.TestEnum", topTypeDefinition.getProperties().get("testEnum")); - Assertions.assertEquals("java.util.List", topTypeDefinition.getProperties().get("innerObject2")); + Assertions.assertEquals( + "java.util.Map", + topTypeDefinition.getProperties().get("maps")); + Assertions.assertEquals( + "org.apache.dubbo.service.ComplexObject.InnerObject", + topTypeDefinition.getProperties().get("innerObject")); + Assertions.assertEquals( + "java.util.List", + topTypeDefinition.getProperties().get("intList")); + Assertions.assertEquals( + "java.lang.String[]", topTypeDefinition.getProperties().get("strArrays")); + Assertions.assertEquals( + "org.apache.dubbo.service.ComplexObject.InnerObject3[]", + topTypeDefinition.getProperties().get("innerObject3")); + Assertions.assertEquals( + "org.apache.dubbo.service.ComplexObject.TestEnum", + topTypeDefinition.getProperties().get("testEnum")); + Assertions.assertEquals( + "java.util.List", + topTypeDefinition.getProperties().get("innerObject2")); - Assertions.assertSame("java.lang.String", innerTypeDefinition.getProperties().get("innerA")); + Assertions.assertSame( + "java.lang.String", innerTypeDefinition.getProperties().get("innerA")); Assertions.assertSame("int", innerTypeDefinition.getProperties().get("innerB")); - Assertions.assertSame("java.lang.String", inner2TypeDefinition.getProperties().get("innerA2")); + Assertions.assertSame( + "java.lang.String", inner2TypeDefinition.getProperties().get("innerA2")); Assertions.assertSame("int", inner2TypeDefinition.getProperties().get("innerB2")); - Assertions.assertSame("java.lang.String", inner3TypeDefinition.getProperties().get("innerA3")); + Assertions.assertSame( + "java.lang.String", inner3TypeDefinition.getProperties().get("innerA3")); Map result = new HashMap<>(); result.put("v", l); @@ -268,7 +304,7 @@ class GenericServiceTest { innerObject3Tmp2.put("innerA3", var1 + "_32"); Map innerObject3Tmp3 = new HashMap<>(4); innerObject3Tmp3.put("innerA3", var1 + "_32"); - result.put("innerObject3", new Map[]{innerObject3Tmp1, innerObject3Tmp2, innerObject3Tmp3}); + result.put("innerObject3", new Map[] {innerObject3Tmp1, innerObject3Tmp2, innerObject3Tmp3}); return result; } @@ -281,8 +317,8 @@ class GenericServiceTest { return JsonUtils.toJavaObject(JsonUtils.toJson(map), ComplexObject.class); } - ComplexObject createComplexObject(String var1, int var2, long l, String[] var3, List var4, ComplexObject.TestEnum testEnum) { + ComplexObject createComplexObject( + String var1, int var2, long l, String[] var3, List var4, ComplexObject.TestEnum testEnum) { return new ComplexObject(var1, var2, l, var3, var4, testEnum); } - } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/AbstractAnnotationProcessingTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/AbstractAnnotationProcessingTest.java index abe91275d4..cbb0a5da77 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/AbstractAnnotationProcessingTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/AbstractAnnotationProcessingTest.java @@ -18,17 +18,18 @@ package org.apache.dubbo.metadata.annotation.processing; import org.apache.dubbo.metadata.annotation.processing.util.TypeUtils; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.extension.ExtendWith; - import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; + import java.lang.annotation.Annotation; import java.util.Set; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; + /** * Abstract {@link Annotation} Processing Test case * diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/AnnotationProcessingTestProcessor.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/AnnotationProcessingTestProcessor.java index a02432711b..4b21c6437f 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/AnnotationProcessingTestProcessor.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/AnnotationProcessingTestProcessor.java @@ -16,18 +16,19 @@ */ package org.apache.dubbo.metadata.annotation.processing; -import org.junit.jupiter.api.extension.ExtensionContext; -import org.junit.jupiter.api.extension.InvocationInterceptor; -import org.junit.jupiter.api.extension.ReflectiveInvocationContext; - import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.SourceVersion; import javax.lang.model.element.TypeElement; + import java.lang.reflect.Method; import java.util.Set; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.InvocationInterceptor; +import org.junit.jupiter.api.extension.ReflectiveInvocationContext; + import static javax.lang.model.SourceVersion.latestSupported; @SupportedAnnotationTypes("*") @@ -40,9 +41,11 @@ public class AnnotationProcessingTestProcessor extends AbstractProcessor { private final ExtensionContext extensionContext; - public AnnotationProcessingTestProcessor(AbstractAnnotationProcessingTest abstractAnnotationProcessingTest, InvocationInterceptor.Invocation invocation, - ReflectiveInvocationContext invocationContext, - ExtensionContext extensionContext) { + public AnnotationProcessingTestProcessor( + AbstractAnnotationProcessingTest abstractAnnotationProcessingTest, + InvocationInterceptor.Invocation invocation, + ReflectiveInvocationContext invocationContext, + ExtensionContext extensionContext) { this.abstractAnnotationProcessingTest = abstractAnnotationProcessingTest; this.invocation = invocation; this.invocationContext = invocationContext; diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/CompilerInvocationInterceptor.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/CompilerInvocationInterceptor.java index fe97b4b4b8..44689fe64e 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/CompilerInvocationInterceptor.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/CompilerInvocationInterceptor.java @@ -18,28 +18,31 @@ package org.apache.dubbo.metadata.annotation.processing; import org.apache.dubbo.metadata.tools.Compiler; -import org.junit.jupiter.api.extension.ExtensionContext; -import org.junit.jupiter.api.extension.InvocationInterceptor; -import org.junit.jupiter.api.extension.ReflectiveInvocationContext; - import java.lang.reflect.Method; import java.util.LinkedHashSet; import java.util.Set; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.InvocationInterceptor; +import org.junit.jupiter.api.extension.ReflectiveInvocationContext; + import static org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest.testInstanceHolder; public class CompilerInvocationInterceptor implements InvocationInterceptor { @Override - public void interceptTestMethod(Invocation invocation, - ReflectiveInvocationContext invocationContext, - ExtensionContext extensionContext) throws Throwable { + public void interceptTestMethod( + Invocation invocation, + ReflectiveInvocationContext invocationContext, + ExtensionContext extensionContext) + throws Throwable { Set> classesToBeCompiled = new LinkedHashSet<>(); AbstractAnnotationProcessingTest abstractAnnotationProcessingTest = testInstanceHolder.get(); classesToBeCompiled.add(getClass()); abstractAnnotationProcessingTest.addCompiledClasses(classesToBeCompiled); Compiler compiler = new Compiler(); - compiler.processors(new AnnotationProcessingTestProcessor(abstractAnnotationProcessingTest, invocation, invocationContext, extensionContext)); + compiler.processors(new AnnotationProcessingTestProcessor( + abstractAnnotationProcessingTest, invocation, invocationContext, extensionContext)); compiler.compile(classesToBeCompiled.toArray(new Class[0])); } } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilderTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilderTest.java index cd84396e6d..779cbd08b8 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilderTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilderTest.java @@ -20,18 +20,19 @@ import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcess import org.apache.dubbo.metadata.annotation.processing.model.ArrayTypeModel; import org.apache.dubbo.metadata.definition.model.TypeDefinition; -import org.junit.jupiter.api.Test; - import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.ElementKind; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; + import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; import java.util.stream.Stream; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -89,37 +90,51 @@ class ArrayTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { buildAndAssertTypeDefinition(processingEnv, stringsField, "java.lang.String[]", "java.lang.String", builder); - buildAndAssertTypeDefinition(processingEnv, primitiveTypeModelsField, + buildAndAssertTypeDefinition( + processingEnv, + primitiveTypeModelsField, "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel[]", - "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel", builder); + "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel", + builder); - buildAndAssertTypeDefinition(processingEnv, modelsField, + buildAndAssertTypeDefinition( + processingEnv, + modelsField, "org.apache.dubbo.metadata.annotation.processing.model.Model[]", - "org.apache.dubbo.metadata.annotation.processing.model.Model", builder, (def, subDef) -> { + "org.apache.dubbo.metadata.annotation.processing.model.Model", + builder, + (def, subDef) -> { TypeElement subType = elements.getTypeElement(subDef.getType()); assertEquals(ElementKind.CLASS, subType.getKind()); }); - buildAndAssertTypeDefinition(processingEnv, colorsField, + buildAndAssertTypeDefinition( + processingEnv, + colorsField, "org.apache.dubbo.metadata.annotation.processing.model.Color[]", - "org.apache.dubbo.metadata.annotation.processing.model.Color", builder, (def, subDef) -> { + "org.apache.dubbo.metadata.annotation.processing.model.Color", + builder, + (def, subDef) -> { TypeElement subType = elements.getTypeElement(subDef.getType()); assertEquals(ElementKind.ENUM, subType.getKind()); }); - } - static void buildAndAssertTypeDefinition(ProcessingEnvironment processingEnv, VariableElement field, - String expectedType, String compositeType, TypeBuilder builder, - BiConsumer... assertions) { + static void buildAndAssertTypeDefinition( + ProcessingEnvironment processingEnv, + VariableElement field, + String expectedType, + String compositeType, + TypeBuilder builder, + BiConsumer... assertions) { Map typeCache = new HashMap<>(); TypeDefinition typeDefinition = TypeDefinitionBuilder.build(processingEnv, field, typeCache); String subTypeName = typeDefinition.getItems().get(0); TypeDefinition subTypeDefinition = typeCache.get(subTypeName); assertEquals(expectedType, typeDefinition.getType()); -// assertEquals(field.getSimpleName().toString(), typeDefinition.get$ref()); + // assertEquals(field.getSimpleName().toString(), typeDefinition.get$ref()); assertEquals(compositeType, subTypeDefinition.getType()); -// assertEquals(builder.getClass().getName(), typeDefinition.getTypeBuilderName()); + // assertEquals(builder.getClass().getName(), typeDefinition.getTypeBuilderName()); Stream.of(assertions).forEach(assertion -> assertion.accept(typeDefinition, subTypeDefinition)); } } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilderTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilderTest.java index e99d417784..865613a496 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilderTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilderTest.java @@ -19,12 +19,13 @@ package org.apache.dubbo.metadata.annotation.processing.builder; import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; import org.apache.dubbo.metadata.annotation.processing.model.CollectionTypeModel; -import org.junit.jupiter.api.Test; - import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; + import java.util.Set; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.metadata.annotation.processing.builder.ArrayTypeDefinitionBuilderTest.buildAndAssertTypeDefinition; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -58,15 +59,16 @@ class CollectionTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTe protected void beforeEach() { builder = new CollectionTypeDefinitionBuilder(); TypeElement testType = getType(CollectionTypeModel.class); - stringsField = findField( testType, "strings"); - colorsField = findField( testType, "colors"); - primitiveTypeModelsField = findField( testType, "primitiveTypeModels"); - modelsField = findField( testType, "models"); - modelArraysField = findField( testType, "modelArrays"); + stringsField = findField(testType, "strings"); + colorsField = findField(testType, "colors"); + primitiveTypeModelsField = findField(testType, "primitiveTypeModels"); + modelsField = findField(testType, "models"); + modelArraysField = findField(testType, "modelArrays"); assertEquals("strings", stringsField.getSimpleName().toString()); assertEquals("colors", colorsField.getSimpleName().toString()); - assertEquals("primitiveTypeModels", primitiveTypeModelsField.getSimpleName().toString()); + assertEquals( + "primitiveTypeModels", primitiveTypeModelsField.getSimpleName().toString()); assertEquals("models", modelsField.getSimpleName().toString()); assertEquals("modelArrays", modelArraysField.getSimpleName().toString()); } @@ -83,23 +85,35 @@ class CollectionTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTe @Test void testBuild() { - buildAndAssertTypeDefinition(processingEnv, stringsField, "java.util.Collection", "java.lang.String", builder); + buildAndAssertTypeDefinition( + processingEnv, stringsField, "java.util.Collection", "java.lang.String", builder); - buildAndAssertTypeDefinition(processingEnv, colorsField, "java.util.List", - "org.apache.dubbo.metadata.annotation.processing.model.Color", builder); + buildAndAssertTypeDefinition( + processingEnv, + colorsField, + "java.util.List", + "org.apache.dubbo.metadata.annotation.processing.model.Color", + builder); - buildAndAssertTypeDefinition(processingEnv, primitiveTypeModelsField, + buildAndAssertTypeDefinition( + processingEnv, + primitiveTypeModelsField, "java.util.Queue", - "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel", builder); + "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel", + builder); - buildAndAssertTypeDefinition(processingEnv, modelsField, + buildAndAssertTypeDefinition( + processingEnv, + modelsField, "java.util.Deque", - "org.apache.dubbo.metadata.annotation.processing.model.Model", builder); + "org.apache.dubbo.metadata.annotation.processing.model.Model", + builder); - buildAndAssertTypeDefinition(processingEnv, modelArraysField, + buildAndAssertTypeDefinition( + processingEnv, + modelArraysField, "java.util.Set", - "org.apache.dubbo.metadata.annotation.processing.model.Model[]", builder); - - + "org.apache.dubbo.metadata.annotation.processing.model.Model[]", + builder); } } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilderTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilderTest.java index 49572e708e..d3a7261f57 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilderTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilderTest.java @@ -20,13 +20,14 @@ import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcess import org.apache.dubbo.metadata.annotation.processing.model.Color; import org.apache.dubbo.metadata.definition.model.TypeDefinition; -import org.junit.jupiter.api.Test; - import javax.lang.model.element.TypeElement; + import java.util.HashMap; import java.util.Map; import java.util.Set; +import org.junit.jupiter.api.Test; + import static java.util.Arrays.asList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -63,7 +64,6 @@ class EnumTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { TypeDefinition typeDefinition = TypeDefinitionBuilder.build(processingEnv, typeElement, typeCache); assertEquals(Color.class.getName(), typeDefinition.getType()); assertEquals(asList("RED", "YELLOW", "BLUE"), typeDefinition.getEnums()); -// assertEquals(typeDefinition.getTypeBuilderName(), builder.getClass().getName()); + // assertEquals(typeDefinition.getTypeBuilderName(), builder.getClass().getName()); } - } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilderTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilderTest.java index 8ca703aa32..7a930e5924 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilderTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilderTest.java @@ -24,10 +24,10 @@ import org.apache.dubbo.metadata.annotation.processing.model.Model; import org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel; import org.apache.dubbo.metadata.annotation.processing.model.SimpleTypeModel; -import org.junit.jupiter.api.Test; - import java.util.Set; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -53,15 +53,15 @@ class GeneralTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest @Test void testAccept() { assertTrue(builder.accept(processingEnv, getType(Model.class).asType())); - assertTrue(builder.accept(processingEnv, getType(PrimitiveTypeModel.class).asType())); + assertTrue( + builder.accept(processingEnv, getType(PrimitiveTypeModel.class).asType())); assertTrue(builder.accept(processingEnv, getType(SimpleTypeModel.class).asType())); assertTrue(builder.accept(processingEnv, getType(ArrayTypeModel.class).asType())); - assertTrue(builder.accept(processingEnv, getType(CollectionTypeModel.class).asType())); + assertTrue( + builder.accept(processingEnv, getType(CollectionTypeModel.class).asType())); assertFalse(builder.accept(processingEnv, getType(Color.class).asType())); } @Test - void testBuild() { - - } + void testBuild() {} } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilderTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilderTest.java index 4f48684606..dd7944c66e 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilderTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilderTest.java @@ -20,17 +20,18 @@ import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcess import org.apache.dubbo.metadata.annotation.processing.model.MapTypeModel; import org.apache.dubbo.metadata.definition.model.TypeDefinition; -import org.junit.jupiter.api.Test; - import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; + import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; import java.util.stream.Stream; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -71,7 +72,8 @@ class MapTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { assertEquals("strings", stringsField.getSimpleName().toString()); assertEquals("colors", colorsField.getSimpleName().toString()); - assertEquals("primitiveTypeModels", primitiveTypeModelsField.getSimpleName().toString()); + assertEquals( + "primitiveTypeModels", primitiveTypeModelsField.getSimpleName().toString()); assertEquals("models", modelsField.getSimpleName().toString()); assertEquals("modelArrays", modelArraysField.getSimpleName().toString()); } @@ -88,41 +90,55 @@ class MapTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { @Test void testBuild() { - buildAndAssertTypeDefinition(processingEnv, stringsField, + buildAndAssertTypeDefinition( + processingEnv, + stringsField, "java.util.Map", "java.lang.String", "java.lang.String", builder); - buildAndAssertTypeDefinition(processingEnv, colorsField, + buildAndAssertTypeDefinition( + processingEnv, + colorsField, "java.util.SortedMap", "java.lang.String", "org.apache.dubbo.metadata.annotation.processing.model.Color", builder); - buildAndAssertTypeDefinition(processingEnv, primitiveTypeModelsField, + buildAndAssertTypeDefinition( + processingEnv, + primitiveTypeModelsField, "java.util.NavigableMap", "org.apache.dubbo.metadata.annotation.processing.model.Color", "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel", builder); - buildAndAssertTypeDefinition(processingEnv, modelsField, + buildAndAssertTypeDefinition( + processingEnv, + modelsField, "java.util.HashMap", "java.lang.String", "org.apache.dubbo.metadata.annotation.processing.model.Model", builder); - buildAndAssertTypeDefinition(processingEnv, modelArraysField, + buildAndAssertTypeDefinition( + processingEnv, + modelArraysField, "java.util.TreeMap", "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel", "org.apache.dubbo.metadata.annotation.processing.model.Model[]", builder); } - static void buildAndAssertTypeDefinition(ProcessingEnvironment processingEnv, VariableElement field, - String expectedType, String keyType, String valueType, - TypeBuilder builder, - BiConsumer... assertions) { + static void buildAndAssertTypeDefinition( + ProcessingEnvironment processingEnv, + VariableElement field, + String expectedType, + String keyType, + String valueType, + TypeBuilder builder, + BiConsumer... assertions) { Map typeCache = new HashMap<>(); TypeDefinition typeDefinition = TypeDefinitionBuilder.build(processingEnv, field, typeCache); String keyTypeName = typeDefinition.getItems().get(0); @@ -130,10 +146,10 @@ class MapTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { String valueTypeName = typeDefinition.getItems().get(1); TypeDefinition valueTypeDefinition = typeCache.get(valueTypeName); assertEquals(expectedType, typeDefinition.getType()); -// assertEquals(field.getSimpleName().toString(), typeDefinition.get$ref()); + // assertEquals(field.getSimpleName().toString(), typeDefinition.get$ref()); assertEquals(keyType, keyTypeDefinition.getType()); assertEquals(valueType, valueTypeDefinition.getType()); -// assertEquals(builder.getClass().getName(), typeDefinition.getTypeBuilderName()); + // assertEquals(builder.getClass().getName(), typeDefinition.getTypeBuilderName()); Stream.of(assertions).forEach(assertion -> assertion.accept(typeDefinition, keyTypeDefinition)); } } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilderTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilderTest.java index 3c9774cf6c..db714bde3f 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilderTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilderTest.java @@ -20,15 +20,16 @@ import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcess import org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel; import org.apache.dubbo.metadata.definition.model.TypeDefinition; -import org.junit.jupiter.api.Test; - import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; + import java.util.HashMap; import java.util.Map; import java.util.Set; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -70,14 +71,14 @@ class PrimitiveTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTes TypeElement testType = getType(PrimitiveTypeModel.class); - zField = findField( testType, "z"); - bField = findField( testType, "b"); - cField = findField( testType, "c"); - sField = findField( testType, "s"); - iField = findField( testType, "i"); - lField = findField( testType, "l"); - fField = findField( testType, "f"); - dField = findField( testType, "d"); + zField = findField(testType, "z"); + bField = findField(testType, "b"); + cField = findField(testType, "c"); + sField = findField(testType, "s"); + iField = findField(testType, "i"); + lField = findField(testType, "l"); + fField = findField(testType, "f"); + dField = findField(testType, "d"); assertEquals("boolean", zField.asType().toString()); assertEquals("byte", bField.asType().toString()); @@ -114,16 +115,17 @@ class PrimitiveTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTes buildAndAssertTypeDefinition(processingEnv, dField, builder); } - static void buildAndAssertTypeDefinition(ProcessingEnvironment processingEnv, VariableElement field, TypeBuilder builder) { + static void buildAndAssertTypeDefinition( + ProcessingEnvironment processingEnv, VariableElement field, TypeBuilder builder) { Map typeCache = new HashMap<>(); TypeDefinition typeDefinition = TypeDefinitionBuilder.build(processingEnv, field, typeCache); assertBasicTypeDefinition(typeDefinition, field.asType().toString(), builder); -// assertEquals(field.getSimpleName().toString(), typeDefinition.get$ref()); + // assertEquals(field.getSimpleName().toString(), typeDefinition.get$ref()); } static void assertBasicTypeDefinition(TypeDefinition typeDefinition, String type, TypeBuilder builder) { assertEquals(type, typeDefinition.getType()); -// assertEquals(builder.getClass().getName(), typeDefinition.getTypeBuilderName()); + // assertEquals(builder.getClass().getName(), typeDefinition.getTypeBuilderName()); assertTrue(typeDefinition.getProperties().isEmpty()); assertTrue(typeDefinition.getItems().isEmpty()); assertTrue(typeDefinition.getEnums().isEmpty()); diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilderTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilderTest.java index 9906f12975..0f57ba3778 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilderTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilderTest.java @@ -21,12 +21,12 @@ import org.apache.dubbo.metadata.definition.model.ServiceDefinition; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import org.apache.dubbo.metadata.tools.TestServiceImpl; -import org.junit.jupiter.api.Test; - import java.util.Arrays; import java.util.List; import java.util.Set; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.metadata.annotation.processing.builder.ServiceDefinitionBuilder.build; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -37,15 +37,13 @@ import static org.junit.jupiter.api.Assertions.assertEquals; */ class ServiceDefinitionBuilderTest extends AbstractAnnotationProcessingTest { - @Override protected void addCompiledClasses(Set> classesToBeCompiled) { classesToBeCompiled.add(TestServiceImpl.class); } @Override - protected void beforeEach() { - } + protected void beforeEach() {} @Test void testBuild() { @@ -61,8 +59,7 @@ class ServiceDefinitionBuilderTest extends AbstractAnnotationProcessingTest { "org.apache.dubbo.metadata.tools.TestService", "java.lang.AutoCloseable", "java.io.Serializable", - "java.util.EventListener" - ); + "java.util.EventListener"); for (String typeName : typeNames) { String gotTypeName = getTypeName(typeName, serviceDefinition.getTypes()); assertEquals(typeName, gotTypeName); diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilderTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilderTest.java index 08f008d394..10118ee8bd 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilderTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilderTest.java @@ -19,12 +19,13 @@ package org.apache.dubbo.metadata.annotation.processing.builder; import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; import org.apache.dubbo.metadata.annotation.processing.model.SimpleTypeModel; -import org.junit.jupiter.api.Test; - import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; + import java.util.Set; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.metadata.annotation.processing.builder.PrimitiveTypeDefinitionBuilderTest.buildAndAssertTypeDefinition; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -68,7 +69,6 @@ class SimpleTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { private VariableElement invalidField; - @Override protected void addCompiledClasses(Set> classesToBeCompiled) { classesToBeCompiled.add(SimpleTypeModel.class); diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/ArrayTypeModel.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/ArrayTypeModel.java index 28bf4f3111..8c8a63a8f5 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/ArrayTypeModel.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/ArrayTypeModel.java @@ -23,14 +23,13 @@ package org.apache.dubbo.metadata.annotation.processing.model; */ public class ArrayTypeModel { - private int[] integers; // Primitive type array + private int[] integers; // Primitive type array - private String[] strings; // Simple type array + private String[] strings; // Simple type array private PrimitiveTypeModel[] primitiveTypeModels; // Complex type array - private Model[] models; // Hierarchical Complex type array - - private Color[] colors; // Enum type array + private Model[] models; // Hierarchical Complex type array + private Color[] colors; // Enum type array } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/CollectionTypeModel.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/CollectionTypeModel.java index e90f1c8926..f370432203 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/CollectionTypeModel.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/CollectionTypeModel.java @@ -31,12 +31,11 @@ public class CollectionTypeModel { private Collection strings; // The composite element is simple type - private List colors; // The composite element is Enum type + private List colors; // The composite element is Enum type - private Queue primitiveTypeModels; // The composite element is POJO type + private Queue primitiveTypeModels; // The composite element is POJO type - private Deque models; // The composite element is hierarchical POJO type + private Deque models; // The composite element is hierarchical POJO type private Set modelArrays; // The composite element is hierarchical POJO type - } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Color.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Color.java index 9fab9df62d..e1fc517bee 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Color.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Color.java @@ -22,7 +22,6 @@ package org.apache.dubbo.metadata.annotation.processing.model; * @since 2.7.6 */ public enum Color { - RED(1), YELLOW(2), BLUE(3); @@ -35,9 +34,7 @@ public enum Color { @Override public String toString() { - return "Color{" + - "value=" + value + - "} " + super.toString(); + return "Color{" + "value=" + value + "} " + super.toString(); } public int getValue() { diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/MapTypeModel.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/MapTypeModel.java index 087aa932ed..fb58296034 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/MapTypeModel.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/MapTypeModel.java @@ -31,11 +31,11 @@ public class MapTypeModel { private Map strings; // The composite element is simple type - private SortedMap colors; // The composite element is Enum type + private SortedMap colors; // The composite element is Enum type - private NavigableMap primitiveTypeModels; // The composite element is POJO type + private NavigableMap primitiveTypeModels; // The composite element is POJO type - private HashMap models; // The composite element is hierarchical POJO type + private HashMap models; // The composite element is hierarchical POJO type private TreeMap modelArrays; // The composite element is hierarchical POJO type } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtilsTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtilsTest.java index 186b06bb4f..18814dc273 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtilsTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtilsTest.java @@ -22,9 +22,6 @@ import org.apache.dubbo.metadata.rest.SpringRestService; import org.apache.dubbo.metadata.tools.TestService; import org.apache.dubbo.metadata.tools.TestServiceImpl; -import org.junit.jupiter.api.Test; -import org.springframework.web.bind.annotation.GetMapping; - import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; @@ -32,10 +29,14 @@ import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; import javax.ws.rs.Path; + import java.util.Iterator; import java.util.List; import java.util.Set; +import org.junit.jupiter.api.Test; +import org.springframework.web.bind.annotation.GetMapping; + import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.findAnnotation; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.findMetaAnnotation; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getAllAnnotations; @@ -61,8 +62,7 @@ class AnnotationUtilsTest extends AbstractAnnotationProcessingTest { private TypeElement testType; @Override - protected void addCompiledClasses(Set> classesToBeCompiled) { - } + protected void addCompiledClasses(Set> classesToBeCompiled) {} @Override protected void beforeEach() { @@ -95,23 +95,33 @@ class AnnotationUtilsTest extends AbstractAnnotationProcessingTest { Iterator iterator = annotations.iterator(); assertEquals(2, annotations.size()); - assertEquals("com.alibaba.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); - assertEquals("org.apache.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); + assertEquals( + "com.alibaba.dubbo.config.annotation.Service", + iterator.next().getAnnotationType().toString()); + assertEquals( + "org.apache.dubbo.config.annotation.Service", + iterator.next().getAnnotationType().toString()); annotations = getAnnotations(testType, Service.class); iterator = annotations.iterator(); assertEquals(1, annotations.size()); - assertEquals("org.apache.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); + assertEquals( + "org.apache.dubbo.config.annotation.Service", + iterator.next().getAnnotationType().toString()); annotations = getAnnotations(testType.asType(), Service.class); iterator = annotations.iterator(); assertEquals(1, annotations.size()); - assertEquals("org.apache.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); + assertEquals( + "org.apache.dubbo.config.annotation.Service", + iterator.next().getAnnotationType().toString()); annotations = getAnnotations(testType.asType(), Service.class.getTypeName()); iterator = annotations.iterator(); assertEquals(1, annotations.size()); - assertEquals("org.apache.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); + assertEquals( + "org.apache.dubbo.config.annotation.Service", + iterator.next().getAnnotationType().toString()); annotations = getAnnotations(testType, Override.class); assertEquals(0, annotations.size()); @@ -152,14 +162,14 @@ class AnnotationUtilsTest extends AbstractAnnotationProcessingTest { assertTrue(getAllAnnotations((Element) null, (Class) null).isEmpty()); assertTrue(getAllAnnotations((TypeMirror) null, (String) null).isEmpty()); assertTrue(getAllAnnotations((ProcessingEnvironment) null, (Class) null).isEmpty()); - assertTrue(getAllAnnotations((ProcessingEnvironment) null, (String) null).isEmpty()); + assertTrue( + getAllAnnotations((ProcessingEnvironment) null, (String) null).isEmpty()); assertTrue(getAllAnnotations((Element) null).isEmpty()); assertTrue(getAllAnnotations((TypeMirror) null).isEmpty()); assertTrue(getAllAnnotations(processingEnv, (Class) null).isEmpty()); assertTrue(getAllAnnotations(processingEnv, (String) null).isEmpty()); - assertTrue(getAllAnnotations(testType, (Class) null).isEmpty()); assertTrue(getAllAnnotations(testType.asType(), (Class) null).isEmpty()); @@ -167,18 +177,34 @@ class AnnotationUtilsTest extends AbstractAnnotationProcessingTest { assertTrue(getAllAnnotations(testType.asType(), (String) null).isEmpty()); assertTrue(getAllAnnotations((Element) null, Service.class).isEmpty()); - assertTrue(getAllAnnotations((TypeMirror) null, Service.class.getTypeName()).isEmpty()); + assertTrue(getAllAnnotations((TypeMirror) null, Service.class.getTypeName()) + .isEmpty()); } - @Test void testFindAnnotation() { - assertEquals("org.apache.dubbo.config.annotation.Service", findAnnotation(testType, Service.class).getAnnotationType().toString()); - assertEquals("com.alibaba.dubbo.config.annotation.Service", findAnnotation(testType, com.alibaba.dubbo.config.annotation.Service.class).getAnnotationType().toString()); - assertEquals("javax.ws.rs.Path", findAnnotation(testType, Path.class).getAnnotationType().toString()); - assertEquals("javax.ws.rs.Path", findAnnotation(testType.asType(), Path.class).getAnnotationType().toString()); - assertEquals("javax.ws.rs.Path", findAnnotation(testType.asType(), Path.class.getTypeName()).getAnnotationType().toString()); + assertEquals( + "org.apache.dubbo.config.annotation.Service", + findAnnotation(testType, Service.class).getAnnotationType().toString()); + assertEquals( + "com.alibaba.dubbo.config.annotation.Service", + findAnnotation(testType, com.alibaba.dubbo.config.annotation.Service.class) + .getAnnotationType() + .toString()); + assertEquals( + "javax.ws.rs.Path", + findAnnotation(testType, Path.class).getAnnotationType().toString()); + assertEquals( + "javax.ws.rs.Path", + findAnnotation(testType.asType(), Path.class) + .getAnnotationType() + .toString()); + assertEquals( + "javax.ws.rs.Path", + findAnnotation(testType.asType(), Path.class.getTypeName()) + .getAnnotationType() + .toString()); assertNull(findAnnotation(testType, Override.class)); assertNull(findAnnotation((Element) null, (Class) null)); @@ -195,14 +221,22 @@ class AnnotationUtilsTest extends AbstractAnnotationProcessingTest { @Test void testFindMetaAnnotation() { getAllDeclaredMethods(getType(TestService.class)).forEach(method -> { - assertEquals("javax.ws.rs.HttpMethod", findMetaAnnotation(method, "javax.ws.rs.HttpMethod").getAnnotationType().toString()); + assertEquals( + "javax.ws.rs.HttpMethod", + findMetaAnnotation(method, "javax.ws.rs.HttpMethod") + .getAnnotationType() + .toString()); }); } @Test void testGetAttribute() { - assertEquals("org.apache.dubbo.metadata.tools.TestService", getAttribute(findAnnotation(testType, Service.class), "interfaceName")); - assertEquals("org.apache.dubbo.metadata.tools.TestService", getAttribute(findAnnotation(testType, Service.class).getElementValues(), "interfaceName")); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", + getAttribute(findAnnotation(testType, Service.class), "interfaceName")); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", + getAttribute(findAnnotation(testType, Service.class).getElementValues(), "interfaceName")); assertEquals("/echo", getAttribute(findAnnotation(testType, Path.class), "value")); assertNull(getAttribute(findAnnotation(testType, Path.class), null)); @@ -212,7 +246,7 @@ class AnnotationUtilsTest extends AbstractAnnotationProcessingTest { AnnotationMirror annotation = findAnnotation(method, GetMapping.class); - assertArrayEquals(new String[]{"/param"}, (String[]) getAttribute(annotation, "value")); + assertArrayEquals(new String[] {"/param"}, (String[]) getAttribute(annotation, "value")); assertNull(getAttribute(annotation, "path")); } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtilsTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtilsTest.java index 74b69cc72d..d2e5f72e2a 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtilsTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtilsTest.java @@ -21,12 +21,11 @@ import org.apache.dubbo.metadata.annotation.processing.model.Color; import org.apache.dubbo.metadata.annotation.processing.model.Model; import org.apache.dubbo.metadata.tools.TestServiceImpl; -import org.junit.jupiter.api.Test; - import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; + import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger; @@ -34,6 +33,8 @@ import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; + import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; @@ -62,8 +63,7 @@ class FieldUtilsTest extends AbstractAnnotationProcessingTest { private TypeElement testType; @Override - protected void addCompiledClasses(Set> classesToBeCompiled) { - } + protected void addCompiledClasses(Set> classesToBeCompiled) {} @Override protected void beforeEach() { @@ -185,7 +185,6 @@ class FieldUtilsTest extends AbstractAnnotationProcessingTest { type = getType(Color.class); assertTrue(isField(findField(type, "BLUE"), PUBLIC, STATIC, FINAL)); - assertFalse(isField(null)); assertFalse(isField(null, PUBLIC, STATIC, FINAL)); } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtilsTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtilsTest.java index 59a1b4545a..7b43a1210e 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtilsTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtilsTest.java @@ -20,15 +20,16 @@ import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcess import org.apache.dubbo.metadata.annotation.processing.model.Model; import org.apache.dubbo.metadata.tools.TestServiceImpl; -import org.junit.jupiter.api.Test; - import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; + import java.util.List; import java.util.Set; +import org.junit.jupiter.api.Test; + import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.util.ElementFilter.fieldsIn; import static javax.lang.model.util.ElementFilter.methodsIn; @@ -52,8 +53,7 @@ class MemberUtilsTest extends AbstractAnnotationProcessingTest { private TypeElement testType; @Override - protected void addCompiledClasses(Set> classesToBeCompiled) { - } + protected void addCompiledClasses(Set> classesToBeCompiled) {} @Override protected void beforeEach() { diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtilsTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtilsTest.java index dca4090df5..ee3ecc4eac 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtilsTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtilsTest.java @@ -21,14 +21,15 @@ import org.apache.dubbo.metadata.annotation.processing.model.Model; import org.apache.dubbo.metadata.tools.TestService; import org.apache.dubbo.metadata.tools.TestServiceImpl; -import org.junit.jupiter.api.Test; - import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; + import java.util.List; import java.util.Set; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.findMethod; import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getAllDeclaredMethods; import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getDeclaredMethods; @@ -52,8 +53,7 @@ class MethodUtilsTest extends AbstractAnnotationProcessingTest { private TypeElement testType; @Override - protected void addCompiledClasses(Set> classesToBeCompiled) { - } + protected void addCompiledClasses(Set> classesToBeCompiled) {} @Override protected void beforeEach() { @@ -102,7 +102,8 @@ class MethodUtilsTest extends AbstractAnnotationProcessingTest { @Test void testIsPublicNonStaticMethod() { List methods = getPublicNonStaticMethods(testType, Object.class); - assertEquals(14, methods.stream().map(MethodUtils::isPublicNonStaticMethod).count()); + assertEquals( + 14, methods.stream().map(MethodUtils::isPublicNonStaticMethod).count()); } @Test @@ -190,7 +191,7 @@ class MethodUtilsTest extends AbstractAnnotationProcessingTest { @Test void testMatchParameterTypes() { ExecutableElement method = findMethod(testType, "echo", "java.lang.String"); - assertArrayEquals(new String[]{"java.lang.String"}, getMethodParameterTypes(method)); + assertArrayEquals(new String[] {"java.lang.String"}, getMethodParameterTypes(method)); assertTrue(getMethodParameterTypes(null).length == 0); } } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtilsTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtilsTest.java index 1bca2bc027..d7dc3d6771 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtilsTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtilsTest.java @@ -22,12 +22,13 @@ import org.apache.dubbo.metadata.tools.GenericTestService; import org.apache.dubbo.metadata.tools.TestService; import org.apache.dubbo.metadata.tools.TestServiceImpl; -import org.junit.jupiter.api.Test; - import javax.lang.model.element.TypeElement; + import java.util.LinkedHashSet; import java.util.Set; +import org.junit.jupiter.api.Test; + import static java.util.Arrays.asList; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.DUBBO_SERVICE_ANNOTATION_TYPE; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.GROUP_ATTRIBUTE_NAME; @@ -55,14 +56,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue; class ServiceAnnotationUtilsTest extends AbstractAnnotationProcessingTest { @Override - protected void addCompiledClasses(Set> classesToBeCompiled) { - - } + protected void addCompiledClasses(Set> classesToBeCompiled) {} @Override - protected void beforeEach() { - - } + protected void beforeEach() {} @Test void testConstants() { @@ -73,7 +70,12 @@ class ServiceAnnotationUtilsTest extends AbstractAnnotationProcessingTest { assertEquals("interfaceName", INTERFACE_NAME_ATTRIBUTE_NAME); assertEquals("group", GROUP_ATTRIBUTE_NAME); assertEquals("version", VERSION_ATTRIBUTE_NAME); - assertEquals(new LinkedHashSet<>(asList("org.apache.dubbo.config.annotation.DubboService", "org.apache.dubbo.config.annotation.Service", "com.alibaba.dubbo.config.annotation.Service")), SUPPORTED_ANNOTATION_TYPES); + assertEquals( + new LinkedHashSet<>(asList( + "org.apache.dubbo.config.annotation.DubboService", + "org.apache.dubbo.config.annotation.Service", + "com.alibaba.dubbo.config.annotation.Service")), + SUPPORTED_ANNOTATION_TYPES); } @Test @@ -89,13 +91,19 @@ class ServiceAnnotationUtilsTest extends AbstractAnnotationProcessingTest { @Test void testGetAnnotation() { TypeElement type = getType(TestServiceImpl.class); - assertEquals("org.apache.dubbo.config.annotation.Service", getAnnotation(type).getAnnotationType().toString()); + assertEquals( + "org.apache.dubbo.config.annotation.Service", + getAnnotation(type).getAnnotationType().toString()); type = getType(GenericTestService.class); - assertEquals("com.alibaba.dubbo.config.annotation.Service", getAnnotation(type).getAnnotationType().toString()); + assertEquals( + "com.alibaba.dubbo.config.annotation.Service", + getAnnotation(type).getAnnotationType().toString()); type = getType(DefaultTestService.class); - assertEquals("org.apache.dubbo.config.annotation.Service", getAnnotation(type).getAnnotationType().toString()); + assertEquals( + "org.apache.dubbo.config.annotation.Service", + getAnnotation(type).getAnnotationType().toString()); assertThrows(IllegalArgumentException.class, () -> getAnnotation(getType(TestService.class))); } @@ -103,13 +111,16 @@ class ServiceAnnotationUtilsTest extends AbstractAnnotationProcessingTest { @Test void testResolveServiceInterfaceName() { TypeElement type = getType(TestServiceImpl.class); - assertEquals("org.apache.dubbo.metadata.tools.TestService", resolveServiceInterfaceName(type, getAnnotation(type))); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", resolveServiceInterfaceName(type, getAnnotation(type))); type = getType(GenericTestService.class); - assertEquals("org.apache.dubbo.metadata.tools.TestService", resolveServiceInterfaceName(type, getAnnotation(type))); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", resolveServiceInterfaceName(type, getAnnotation(type))); type = getType(DefaultTestService.class); - assertEquals("org.apache.dubbo.metadata.tools.TestService", resolveServiceInterfaceName(type, getAnnotation(type))); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", resolveServiceInterfaceName(type, getAnnotation(type))); } @Test diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtilsTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtilsTest.java index 04e86e77ff..282c5c470c 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtilsTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtilsTest.java @@ -25,15 +25,13 @@ import org.apache.dubbo.metadata.tools.DefaultTestService; import org.apache.dubbo.metadata.tools.GenericTestService; import org.apache.dubbo.metadata.tools.TestServiceImpl; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; + import java.io.File; import java.lang.reflect.Type; import java.math.BigDecimal; @@ -45,6 +43,9 @@ import java.util.Iterator; import java.util.List; import java.util.Set; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + import static java.util.Arrays.asList; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getDeclaredFields; @@ -172,8 +173,7 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { @Test void testIsPrimitiveType() { TypeElement type = getType(PrimitiveTypeModel.class); - getDeclaredFields(type.asType()) - .stream() + getDeclaredFields(type.asType()).stream() .map(VariableElement::asType) .forEach(t -> assertTrue(isPrimitiveType(t))); @@ -217,11 +217,18 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { Set hierarchicalTypes = getHierarchicalTypes(testType.asType(), true, true, true); Iterator iterator = hierarchicalTypes.iterator(); assertEquals(8, hierarchicalTypes.size()); - assertEquals("org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.GenericTestService", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.DefaultTestService", iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestServiceImpl", + iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.GenericTestService", + iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.DefaultTestService", + iterator.next().toString()); assertEquals("java.lang.Object", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); assertEquals("java.lang.AutoCloseable", iterator.next().toString()); assertEquals("java.io.Serializable", iterator.next().toString()); assertEquals("java.util.EventListener", iterator.next().toString()); @@ -229,11 +236,18 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { hierarchicalTypes = getHierarchicalTypes(testType); iterator = hierarchicalTypes.iterator(); assertEquals(8, hierarchicalTypes.size()); - assertEquals("org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.GenericTestService", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.DefaultTestService", iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestServiceImpl", + iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.GenericTestService", + iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.DefaultTestService", + iterator.next().toString()); assertEquals("java.lang.Object", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); assertEquals("java.lang.AutoCloseable", iterator.next().toString()); assertEquals("java.io.Serializable", iterator.next().toString()); assertEquals("java.util.EventListener", iterator.next().toString()); @@ -241,10 +255,17 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { hierarchicalTypes = getHierarchicalTypes(testType.asType(), Object.class); iterator = hierarchicalTypes.iterator(); assertEquals(7, hierarchicalTypes.size()); - assertEquals("org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.GenericTestService", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.DefaultTestService", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestServiceImpl", + iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.GenericTestService", + iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.DefaultTestService", + iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); assertEquals("java.lang.AutoCloseable", iterator.next().toString()); assertEquals("java.io.Serializable", iterator.next().toString()); assertEquals("java.util.EventListener", iterator.next().toString()); @@ -252,16 +273,25 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { hierarchicalTypes = getHierarchicalTypes(testType.asType(), true, true, false); iterator = hierarchicalTypes.iterator(); assertEquals(4, hierarchicalTypes.size()); - assertEquals("org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.GenericTestService", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.DefaultTestService", iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestServiceImpl", + iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.GenericTestService", + iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.DefaultTestService", + iterator.next().toString()); assertEquals("java.lang.Object", iterator.next().toString()); hierarchicalTypes = getHierarchicalTypes(testType.asType(), true, false, true); iterator = hierarchicalTypes.iterator(); assertEquals(5, hierarchicalTypes.size()); - assertEquals("org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestServiceImpl", + iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); assertEquals("java.lang.AutoCloseable", iterator.next().toString()); assertEquals("java.io.Serializable", iterator.next().toString()); assertEquals("java.util.EventListener", iterator.next().toString()); @@ -269,7 +299,8 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { hierarchicalTypes = getHierarchicalTypes(testType.asType(), false, false, true); iterator = hierarchicalTypes.iterator(); assertEquals(4, hierarchicalTypes.size()); - assertEquals("org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); assertEquals("java.lang.AutoCloseable", iterator.next().toString()); assertEquals("java.io.Serializable", iterator.next().toString()); assertEquals("java.util.EventListener", iterator.next().toString()); @@ -277,7 +308,9 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { hierarchicalTypes = getHierarchicalTypes(testType.asType(), true, false, false); iterator = hierarchicalTypes.iterator(); assertEquals(1, hierarchicalTypes.size()); - assertEquals("org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestServiceImpl", + iterator.next().toString()); hierarchicalTypes = getHierarchicalTypes(testType.asType(), false, false, false); assertEquals(0, hierarchicalTypes.size()); @@ -286,7 +319,6 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { assertTrue(getHierarchicalTypes((TypeMirror) null).isEmpty()); } - @Test void testGetInterfaces() { TypeElement type = getType(Model.class); @@ -296,7 +328,8 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { interfaces = getInterfaces(testType.asType()); assertEquals(3, interfaces.size()); - assertEquals("org.apache.dubbo.metadata.tools.TestService", interfaces.get(0).toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", interfaces.get(0).toString()); assertEquals("java.lang.AutoCloseable", interfaces.get(1).toString()); assertEquals("java.io.Serializable", interfaces.get(2).toString()); @@ -309,7 +342,8 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { Set interfaces = getAllInterfaces(testType.asType()); assertEquals(4, interfaces.size()); Iterator iterator = interfaces.iterator(); - assertEquals("org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); assertEquals("java.lang.AutoCloseable", iterator.next().toString()); assertEquals("java.io.Serializable", iterator.next().toString()); assertEquals("java.util.EventListener", iterator.next().toString()); @@ -318,7 +352,9 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { assertEquals(4, interfaces.size()); Iterator allIterator = allInterfaces.iterator(); - assertEquals("org.apache.dubbo.metadata.tools.TestService", allIterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", + allIterator.next().toString()); assertEquals("java.lang.AutoCloseable", allIterator.next().toString()); assertEquals("java.io.Serializable", allIterator.next().toString()); assertEquals("java.util.EventListener", allIterator.next().toString()); @@ -416,7 +452,8 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { @Test void testOfDeclaredTypes() { - Set declaredTypes = ofDeclaredTypes(asList(getType(String.class), getType(TestServiceImpl.class), getType(Color.class))); + Set declaredTypes = + ofDeclaredTypes(asList(getType(String.class), getType(TestServiceImpl.class), getType(Color.class))); assertTrue(declaredTypes.contains(getType(String.class).asType())); assertTrue(declaredTypes.contains(getType(TestServiceImpl.class).asType())); assertTrue(declaredTypes.contains(getType(Color.class).asType())); @@ -430,7 +467,7 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { assertEquals(1, types.size()); assertEquals(ofDeclaredType(testType), types.get(0)); - types = listDeclaredTypes(asList(new Element[]{null})); + types = listDeclaredTypes(asList(new Element[] {null})); assertTrue(types.isEmpty()); } @@ -440,10 +477,11 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { assertEquals(1, typeElements.size()); assertEquals(testType, typeElements.get(0)); - typeElements = listTypeElements(asList(types.getPrimitiveType(TypeKind.BYTE), types.getNullType(), types.getNoType(TypeKind.NONE))); + typeElements = listTypeElements( + asList(types.getPrimitiveType(TypeKind.BYTE), types.getNullType(), types.getNoType(TypeKind.NONE))); assertTrue(typeElements.isEmpty()); - typeElements = listTypeElements(asList(new TypeMirror[]{null})); + typeElements = listTypeElements(asList(new TypeMirror[] {null})); assertTrue(typeElements.isEmpty()); typeElements = listTypeElements(null); diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/RestService.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/RestService.java index 65d67ab475..7b6883780d 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/RestService.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/RestService.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.rest; - import java.util.Map; /** diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java index c2daf9b104..b475bd53da 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java @@ -18,6 +18,9 @@ package org.apache.dubbo.metadata.rest; import org.apache.dubbo.config.annotation.DubboService; +import java.util.HashMap; +import java.util.Map; + import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -27,9 +30,6 @@ import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import java.util.HashMap; -import java.util.Map; - /** * Spring MVC {@link RestService} * @@ -47,22 +47,24 @@ public class SpringRestService implements RestService { @Override @PostMapping("/params") - public String params(@RequestParam(defaultValue = "value-a") int a, @RequestParam(defaultValue = "value-b") String b) { + public String params( + @RequestParam(defaultValue = "value-a") int a, @RequestParam(defaultValue = "value-b") String b) { return null; } @Override @GetMapping("/headers") - public String headers(@RequestHeader(name = "h", defaultValue = "value-h") String header, - @RequestHeader(name = "h2", defaultValue = "value-h2") String header2, - @RequestParam(value = "v", defaultValue = "1") Integer param) { + public String headers( + @RequestHeader(name = "h", defaultValue = "value-h") String header, + @RequestHeader(name = "h2", defaultValue = "value-h2") String header2, + @RequestParam(value = "v", defaultValue = "1") Integer param) { return null; } @Override @GetMapping("/path-variables/{p1}/{p2}") - public String pathVariables(@PathVariable("p1") String path1, - @PathVariable("p2") String path2, @RequestParam("v") String param) { + public String pathVariables( + @PathVariable("p1") String path1, @PathVariable("p2") String path2, @RequestParam("v") String param) { return null; } @@ -74,8 +76,7 @@ public class SpringRestService implements RestService { @Override @PostMapping(value = "/request/body/map", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - public User requestBodyMap(@RequestBody Map data, - @RequestParam("param") String param) { + public User requestBodyMap(@RequestBody Map data, @RequestParam("param") String param) { User user = new User(); user.setId(((Integer) data.get("id")).longValue()); user.setName((String) data.get("name")); diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java index 684d76fd3b..2f7d57e557 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java @@ -27,14 +27,17 @@ import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; + import java.util.HashMap; import java.util.Map; - /** * JAX-RS {@link RestService} */ -@DubboService(version = "3.0.0", protocol = {"dubbo", "rest"}, group = "standard") +@DubboService( + version = "3.0.0", + protocol = {"dubbo", "rest"}, + group = "standard") @Path("/") public class StandardRestService implements RestService { @@ -55,8 +58,8 @@ public class StandardRestService implements RestService { @Override @Path("headers") @GET - public String headers(@HeaderParam("h") String header, - @HeaderParam("h2") String header2, @QueryParam("v") Integer param) { + public String headers( + @HeaderParam("h") String header, @HeaderParam("h2") String header2, @QueryParam("v") Integer param) { String result = header + " , " + header2 + " , " + param; return result; } @@ -64,8 +67,8 @@ public class StandardRestService implements RestService { @Override @Path("path-variables/{p1}/{p2}") @GET - public String pathVariables(@PathParam("p1") String path1, - @PathParam("p2") String path2, @QueryParam("v") String param) { + public String pathVariables( + @PathParam("p1") String path1, @PathParam("p2") String path2, @QueryParam("v") String param) { String result = path1 + " , " + path2 + " , " + param; return result; } @@ -84,8 +87,7 @@ public class StandardRestService implements RestService { @Path("request/body/map") @POST @Produces("application/json;charset=UTF-8") - public User requestBodyMap(Map data, - @QueryParam("param") String param) { + public User requestBodyMap(Map data, @QueryParam("param") String param) { User user = new User(); user.setId(((Integer) data.get("id")).longValue()); user.setName((String) data.get("name")); diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/Compiler.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/Compiler.java index e2f27dd306..5874ad0562 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/Compiler.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/Compiler.java @@ -22,6 +22,7 @@ import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.StandardLocation; import javax.tools.ToolProvider; + import java.io.File; import java.io.IOException; import java.net.URL; @@ -104,10 +105,14 @@ public class Compiler { } public boolean compile(Class... sourceClasses) { - JavaCompiler.CompilationTask task = javaCompiler.getTask(null, this.javaFileManager, null, + JavaCompiler.CompilationTask task = javaCompiler.getTask( + null, + this.javaFileManager, + null, asList("-parameters", "-Xlint:unchecked", "-nowarn", "-Xlint:deprecation"), -// null, - null, getJavaFileObjects(sourceClasses)); + // null, + null, + getJavaFileObjects(sourceClasses)); if (!processors.isEmpty()) { task.setProcessors(processors); } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/CompilerTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/CompilerTest.java index 071e1b26c8..762e297d36 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/CompilerTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/CompilerTest.java @@ -16,10 +16,10 @@ */ package org.apache.dubbo.metadata.tools; -import org.junit.jupiter.api.Test; - import java.io.IOException; +import org.junit.jupiter.api.Test; + /** * The Compiler test case */ @@ -28,10 +28,6 @@ class CompilerTest { @Test void testCompile() throws IOException { Compiler compiler = new Compiler(); - compiler.compile( - TestServiceImpl.class, - DefaultTestService.class, - GenericTestService.class); + compiler.compile(TestServiceImpl.class, DefaultTestService.class, GenericTestService.class); } } - diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/DefaultRestServiceTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/DefaultRestServiceTest.java index d7b73c4abc..9b020d2ca4 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/DefaultRestServiceTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/DefaultRestServiceTest.java @@ -22,10 +22,10 @@ import org.apache.dubbo.metadata.rest.SpringRestService; import org.apache.dubbo.metadata.rest.StandardRestService; import org.apache.dubbo.metadata.rest.User; -import org.junit.jupiter.api.Test; - import java.io.IOException; +import org.junit.jupiter.api.Test; + /** * The test case for {@link DefaultRestService} * @@ -36,7 +36,8 @@ class DefaultRestServiceTest { @Test void test() throws IOException { Compiler compiler = new Compiler(); - compiler.compile(User.class, + compiler.compile( + User.class, RestService.class, DefaultRestService.class, SpringRestService.class, diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/DefaultTestService.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/DefaultTestService.java index 85bce6924d..bb2bc21b63 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/DefaultTestService.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/DefaultTestService.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.tools; - import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.metadata.annotation.processing.model.Model; @@ -27,11 +26,7 @@ import java.util.concurrent.TimeUnit; * * @since 2.7.6 */ -@Service( - interfaceName = "org.apache.dubbo.metadata.tools.TestService", - version = "1.0.0", - group = "default" -) +@Service(interfaceName = "org.apache.dubbo.metadata.tools.TestService", version = "1.0.0", group = "default") public class DefaultTestService implements TestService { private String name; diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/GenericTestService.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/GenericTestService.java index 83cf19ff2c..637e4d1077 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/GenericTestService.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/GenericTestService.java @@ -16,20 +16,16 @@ */ package org.apache.dubbo.metadata.tools; +import java.util.EventListener; import com.alibaba.dubbo.config.annotation.Service; -import java.util.EventListener; - /** * {@link TestService} Implementation * * @since 2.7.6 */ -@Service( - version = "2.0.0", - group = "generic" -) +@Service(version = "2.0.0", group = "generic") public class GenericTestService extends DefaultTestService implements TestService, EventListener { @Override public String echo(String message) { diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/RestServiceTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/RestServiceTest.java index 5f0ed6e093..b8ea68c957 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/RestServiceTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/RestServiceTest.java @@ -21,10 +21,10 @@ import org.apache.dubbo.metadata.rest.SpringRestService; import org.apache.dubbo.metadata.rest.StandardRestService; import org.apache.dubbo.metadata.rest.User; -import org.junit.jupiter.api.Test; - import java.io.IOException; +import org.junit.jupiter.api.Test; + /** * {@link RestService} Test * @@ -35,8 +35,6 @@ class RestServiceTest { @Test void test() throws IOException { Compiler compiler = new Compiler(); - compiler.compile(User.class, RestService.class, - StandardRestService.class, - SpringRestService.class); + compiler.compile(User.class, RestService.class, StandardRestService.class, SpringRestService.class); } } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/SpringRestServiceTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/SpringRestServiceTest.java index ce17abd592..5871c21fef 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/SpringRestServiceTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/SpringRestServiceTest.java @@ -20,10 +20,10 @@ import org.apache.dubbo.metadata.rest.RestService; import org.apache.dubbo.metadata.rest.SpringRestService; import org.apache.dubbo.metadata.rest.User; -import org.junit.jupiter.api.Test; - import java.io.IOException; +import org.junit.jupiter.api.Test; + /** * {@link SpringRestService} Test * diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/StandardRestServiceTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/StandardRestServiceTest.java index e55fdf3da4..84c8199dc7 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/StandardRestServiceTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/StandardRestServiceTest.java @@ -20,10 +20,10 @@ import org.apache.dubbo.metadata.rest.RestService; import org.apache.dubbo.metadata.rest.StandardRestService; import org.apache.dubbo.metadata.rest.User; -import org.junit.jupiter.api.Test; - import java.io.IOException; +import org.junit.jupiter.api.Test; + /** * The test case for {@link StandardRestService} * diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestProcessor.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestProcessor.java index cb8ae82354..42cdaa1811 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestProcessor.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestProcessor.java @@ -23,6 +23,7 @@ import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.SourceVersion; import javax.lang.model.element.TypeElement; + import java.util.Set; import static javax.lang.model.SourceVersion.latestSupported; @@ -44,7 +45,7 @@ public class TestProcessor extends AbstractProcessor { return super.processingEnv; } - public SourceVersion getSupportedSourceVersion(){ + public SourceVersion getSupportedSourceVersion() { return latestSupported(); } } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestService.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestService.java index 83c0ef6aff..83fdf165e8 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestService.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestService.java @@ -24,6 +24,7 @@ import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; + import java.util.concurrent.TimeUnit; /** diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestServiceImpl.java b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestServiceImpl.java index 713e8e701b..fe5f42c496 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestServiceImpl.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/metadata/tools/TestServiceImpl.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.tools; - import org.apache.dubbo.config.annotation.Service; import java.io.Serializable; @@ -30,14 +29,12 @@ import java.io.Serializable; interfaceName = "org.apache.dubbo.metadata.tools.TestService", interfaceClass = TestService.class, version = "3.0.0", - group = "test" -) + group = "test") @Service( interfaceName = "org.apache.dubbo.metadata.tools.TestService", interfaceClass = TestService.class, version = "3.0.0", - group = "test" -) + group = "test") public class TestServiceImpl extends GenericTestService implements TestService, AutoCloseable, Serializable { @Override @@ -46,6 +43,5 @@ public class TestServiceImpl extends GenericTestService implements TestService, } @Override - public void close() throws Exception { - } + public void close() throws Exception {} } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/RpcContextTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/RpcContextTest.java index 20c311104e..27b35778cd 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/RpcContextTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/RpcContextTest.java @@ -14,15 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc; -import com.alibaba.dubbo.rpc.RpcContext; -import org.junit.jupiter.api.Test; - import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; +import com.alibaba.dubbo.rpc.RpcContext; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; class RpcContextTest { diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/cluster/CompatibleRouter.java b/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/cluster/CompatibleRouter.java index 2351b21440..af437dc882 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/cluster/CompatibleRouter.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/cluster/CompatibleRouter.java @@ -16,14 +16,14 @@ */ package org.apache.dubbo.rpc.cluster; +import java.util.List; + import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.rpc.Invocation; import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.RpcException; import com.alibaba.dubbo.rpc.cluster.Router; -import java.util.List; - /** * */ diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/cluster/CompatibleRouter2.java b/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/cluster/CompatibleRouter2.java index 13350d4572..47ec05c090 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/cluster/CompatibleRouter2.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/cluster/CompatibleRouter2.java @@ -16,14 +16,14 @@ */ package org.apache.dubbo.rpc.cluster; +import java.util.List; + import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.rpc.Invocation; import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.RpcException; import com.alibaba.dubbo.rpc.cluster.Router; -import java.util.List; - /** * */ diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/cluster/RouterTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/cluster/RouterTest.java index 056bd106fd..dcd8311e5d 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/cluster/RouterTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/cluster/RouterTest.java @@ -16,14 +16,14 @@ */ package org.apache.dubbo.rpc.cluster; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.Collections; import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + /** * */ @@ -32,7 +32,7 @@ class RouterTest { private static List routers = new ArrayList<>(); @BeforeAll - public static void setUp () { + public static void setUp() { CompatibleRouter compatibleRouter = new CompatibleRouter(); routers.add(compatibleRouter); CompatibleRouter2 compatibleRouter2 = new CompatibleRouter2(); @@ -42,7 +42,7 @@ class RouterTest { } @Test - void testCompareTo () { + void testCompareTo() { try { Collections.sort(routers); Assertions.assertTrue(true); diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java index 874950ce80..a2dd7d196a 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java @@ -37,20 +37,27 @@ import static org.mockito.Mockito.when; class GenericImplFilterTest { - private GenericImplFilter genericImplFilter = new GenericImplFilter(ApplicationModel.defaultModel().getDefaultModule()); + private GenericImplFilter genericImplFilter = + new GenericImplFilter(ApplicationModel.defaultModel().getDefaultModule()); @Test void testInvokeWithException() throws Exception { - RpcInvocation invocation = new RpcInvocation("getPerson", "org.apache.dubbo.rpc.support.DemoService", - "org.apache.dubbo.rpc.support.DemoService:dubbo", new Class[]{Person.class}, new Object[]{new Person("dubbo", 10)}); + RpcInvocation invocation = new RpcInvocation( + "getPerson", + "org.apache.dubbo.rpc.support.DemoService", + "org.apache.dubbo.rpc.support.DemoService:dubbo", + new Class[] {Person.class}, + new Object[] {new Person("dubbo", 10)}); - URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + - "accesslog=true&group=dubbo&version=1.1&generic=true"); + URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + + "accesslog=true&group=dubbo&version=1.1&generic=true"); Invoker invoker = Mockito.mock(Invoker.class); - AppResponse mockRpcResult = new AppResponse(Dubbo2GenericExceptionUtils.newGenericException(new RuntimeException("failed"))); - when(invoker.invoke(any(Invocation.class))).thenReturn(AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation)); + AppResponse mockRpcResult = + new AppResponse(Dubbo2GenericExceptionUtils.newGenericException(new RuntimeException("failed"))); + when(invoker.invoke(any(Invocation.class))) + .thenReturn(AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation)); when(invoker.getUrl()).thenReturn(url); when(invoker.getInterface()).thenReturn(DemoService.class); @@ -58,7 +65,5 @@ class GenericImplFilterTest { Result result = asyncResult.get(); genericImplFilter.onResponse(result, invoker, invocation); Assertions.assertEquals(RuntimeException.class, result.getException().getClass()); - } - } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/support/DemoService.java b/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/support/DemoService.java index ed595724f8..325f1e4fde 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/support/DemoService.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/support/DemoService.java @@ -39,9 +39,9 @@ public interface DemoService { Type enumlength(Type... types); -// Type enumlength(Type type); + // Type enumlength(Type type); -// String get(CustomArgument arg1); + // String get(CustomArgument arg1); byte getbyte(byte arg); @@ -60,5 +60,4 @@ public interface DemoService { CompletableFuture> testReturnType5(String str); void $invoke(String s1, String s2); - } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/support/Type.java b/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/support/Type.java index 22ded46777..b5368d2b38 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/support/Type.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/rpc/support/Type.java @@ -17,5 +17,7 @@ package org.apache.dubbo.rpc.support; public enum Type { - High, Normal, Lower + High, + Normal, + Lower } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/serialization/MyObjectInput.java b/dubbo-compatible/src/test/java/org/apache/dubbo/serialization/MyObjectInput.java index 0e1d96c9e3..925d20b4e8 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/serialization/MyObjectInput.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/serialization/MyObjectInput.java @@ -14,17 +14,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.serialization; -import com.alibaba.dubbo.common.serialize.ObjectInput; - import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Type; +import com.alibaba.dubbo.common.serialize.ObjectInput; + public class MyObjectInput implements ObjectInput { private final BufferedReader reader; diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/serialization/MyObjectOutput.java b/dubbo-compatible/src/test/java/org/apache/dubbo/serialization/MyObjectOutput.java index 7147515a66..3f0cbed6a3 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/serialization/MyObjectOutput.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/serialization/MyObjectOutput.java @@ -14,16 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.serialization; -import com.alibaba.dubbo.common.serialize.ObjectOutput; - import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; +import com.alibaba.dubbo.common.serialize.ObjectOutput; + public class MyObjectOutput implements ObjectOutput { private final BufferedWriter writer; @@ -33,44 +32,28 @@ public class MyObjectOutput implements ObjectOutput { } @Override - public void writeObject(Object obj) throws IOException { - - } + public void writeObject(Object obj) throws IOException {} @Override - public void writeBool(boolean v) throws IOException { - - } + public void writeBool(boolean v) throws IOException {} @Override - public void writeByte(byte v) throws IOException { - - } + public void writeByte(byte v) throws IOException {} @Override - public void writeShort(short v) throws IOException { - - } + public void writeShort(short v) throws IOException {} @Override - public void writeInt(int v) throws IOException { - - } + public void writeInt(int v) throws IOException {} @Override - public void writeLong(long v) throws IOException { - - } + public void writeLong(long v) throws IOException {} @Override - public void writeFloat(float v) throws IOException { - - } + public void writeFloat(float v) throws IOException {} @Override - public void writeDouble(double v) throws IOException { - - } + public void writeDouble(double v) throws IOException {} @Override public void writeUTF(String v) throws IOException { @@ -79,14 +62,10 @@ public class MyObjectOutput implements ObjectOutput { } @Override - public void writeBytes(byte[] v) throws IOException { - - } + public void writeBytes(byte[] v) throws IOException {} @Override - public void writeBytes(byte[] v, int off, int len) throws IOException { - - } + public void writeBytes(byte[] v, int off, int len) throws IOException {} @Override public void flushBuffer() throws IOException { diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/serialization/MySerialization.java b/dubbo-compatible/src/test/java/org/apache/dubbo/serialization/MySerialization.java index 94db7059f9..cc6ee02de1 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/serialization/MySerialization.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/serialization/MySerialization.java @@ -14,18 +14,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.serialization; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.serialize.ObjectInput; import com.alibaba.dubbo.common.serialize.ObjectOutput; import com.alibaba.dubbo.common.serialize.Serialization; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - public class MySerialization implements Serialization { @Override diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/serialization/SerializationTest.java b/dubbo-compatible/src/test/java/org/apache/dubbo/serialization/SerializationTest.java index 9dcfa9114c..28a8cb7fff 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/serialization/SerializationTest.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/serialization/SerializationTest.java @@ -14,23 +14,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.serialization; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; -import org.hamcrest.CoreMatchers; -import org.hamcrest.Matchers; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import org.hamcrest.CoreMatchers; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.mock; diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/service/ComplexObject.java b/dubbo-compatible/src/test/java/org/apache/dubbo/service/ComplexObject.java index 7941af88ff..b2dcda7fc9 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/service/ComplexObject.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/service/ComplexObject.java @@ -28,10 +28,10 @@ import java.util.Objects; */ public class ComplexObject { - public ComplexObject() { - } + public ComplexObject() {} - public ComplexObject(String var1, int var2, long l, String[] var3, List var4, ComplexObject.TestEnum testEnum) { + public ComplexObject( + String var1, int var2, long l, String[] var3, List var4, ComplexObject.TestEnum testEnum) { this.setInnerObject(new ComplexObject.InnerObject()); this.getInnerObject().setInnerA(var1); this.getInnerObject().setInnerB(var2); @@ -53,7 +53,7 @@ public class ComplexObject { io32.setInnerA3(var1 + "_32"); InnerObject3 io33 = new InnerObject3(); io33.setInnerA3(var1 + "_33"); - this.setInnerObject3(new InnerObject3[]{io31, io32, io33}); + this.setInnerObject3(new InnerObject3[] {io31, io32, io33}); this.maps = new HashMap<>(4); this.maps.put(var1 + "_k1", var1 + "_v1"); this.maps.put(var1 + "_k2", var1 + "_v2"); @@ -134,16 +134,15 @@ public class ComplexObject { @Override public String toString() { - return "ComplexObject{" + - "innerObject=" + innerObject + - ", innerObject2=" + innerObject2 + - ", innerObject3=" + Arrays.toString(innerObject3) + - ", strArrays=" + Arrays.toString(strArrays) + - ", intList=" + intList + - ", v=" + v + - ", testEnum=" + testEnum + - ", maps=" + maps + - '}'; + return "ComplexObject{" + "innerObject=" + + innerObject + ", innerObject2=" + + innerObject2 + ", innerObject3=" + + Arrays.toString(innerObject3) + ", strArrays=" + + Arrays.toString(strArrays) + ", intList=" + + intList + ", v=" + + v + ", testEnum=" + + testEnum + ", maps=" + + maps + '}'; } @Override @@ -151,14 +150,14 @@ public class ComplexObject { if (this == o) return true; if (!(o instanceof ComplexObject)) return false; ComplexObject that = (ComplexObject) o; - return getV() == that.getV() && - Objects.equals(getInnerObject(), that.getInnerObject()) && - Objects.equals(getInnerObject2(), that.getInnerObject2()) && - Arrays.equals(getInnerObject3(), that.getInnerObject3()) && - Arrays.equals(getStrArrays(), that.getStrArrays()) && - Objects.equals(getIntList(), that.getIntList()) && - getTestEnum() == that.getTestEnum() && - Objects.equals(getMaps(), that.getMaps()); + return getV() == that.getV() + && Objects.equals(getInnerObject(), that.getInnerObject()) + && Objects.equals(getInnerObject2(), that.getInnerObject2()) + && Arrays.equals(getInnerObject3(), that.getInnerObject3()) + && Arrays.equals(getStrArrays(), that.getStrArrays()) + && Objects.equals(getIntList(), that.getIntList()) + && getTestEnum() == that.getTestEnum() + && Objects.equals(getMaps(), that.getMaps()); } @Override @@ -170,10 +169,11 @@ public class ComplexObject { } public enum TestEnum { - VALUE1, VALUE2 + VALUE1, + VALUE2 } - static public class InnerObject { + public static class InnerObject { String innerA; int innerB; @@ -195,10 +195,7 @@ public class ComplexObject { @Override public String toString() { - return "InnerObject{" + - "innerA='" + innerA + '\'' + - ", innerB=" + innerB + - '}'; + return "InnerObject{" + "innerA='" + innerA + '\'' + ", innerB=" + innerB + '}'; } @Override @@ -206,8 +203,7 @@ public class ComplexObject { if (this == o) return true; if (!(o instanceof InnerObject)) return false; InnerObject that = (InnerObject) o; - return getInnerB() == that.getInnerB() && - Objects.equals(getInnerA(), that.getInnerA()); + return getInnerB() == that.getInnerB() && Objects.equals(getInnerA(), that.getInnerA()); } @Override @@ -216,7 +212,7 @@ public class ComplexObject { } } - static public class InnerObject2 { + public static class InnerObject2 { String innerA2; int innerB2; @@ -238,10 +234,7 @@ public class ComplexObject { @Override public String toString() { - return "InnerObject{" + - "innerA='" + innerA2 + '\'' + - ", innerB=" + innerB2 + - '}'; + return "InnerObject{" + "innerA='" + innerA2 + '\'' + ", innerB=" + innerB2 + '}'; } @Override @@ -249,8 +242,7 @@ public class ComplexObject { if (this == o) return true; if (!(o instanceof InnerObject2)) return false; InnerObject2 that = (InnerObject2) o; - return getInnerB2() == that.getInnerB2() && - Objects.equals(getInnerA2(), that.getInnerA2()); + return getInnerB2() == that.getInnerB2() && Objects.equals(getInnerA2(), that.getInnerA2()); } @Override @@ -259,7 +251,7 @@ public class ComplexObject { } } - static public class InnerObject3 { + public static class InnerObject3 { String innerA3; public String getInnerA3() { @@ -272,9 +264,7 @@ public class ComplexObject { @Override public String toString() { - return "InnerObject3{" + - "innerA3='" + innerA3 + '\'' + - '}'; + return "InnerObject3{" + "innerA3='" + innerA3 + '\'' + '}'; } @Override @@ -291,5 +281,3 @@ public class ComplexObject { } } } - - diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/service/CustomArgument.java b/dubbo-compatible/src/test/java/org/apache/dubbo/service/CustomArgument.java index 220b3f178f..25696349d7 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/service/CustomArgument.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/service/CustomArgument.java @@ -24,8 +24,8 @@ public class CustomArgument implements Serializable { Type type; String name; - public CustomArgument() { - } + public CustomArgument() {} + public CustomArgument(Type type, String name) { super(); this.type = type; diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/service/DemoService.java b/dubbo-compatible/src/test/java/org/apache/dubbo/service/DemoService.java index cdd0d278d5..3379be2175 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/service/DemoService.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/service/DemoService.java @@ -35,7 +35,7 @@ public interface DemoService { Type enumlength(Type... types); -// Type enumlength(Type type); + // Type enumlength(Type type); String get(CustomArgument arg1); @@ -43,6 +43,6 @@ public interface DemoService { String complexCompute(String input, ComplexObject co); - ComplexObject findComplexObject(String var1, int var2, long l, String[] var3, List var4, ComplexObject.TestEnum testEnum); - + ComplexObject findComplexObject( + String var1, int var2, long l, String[] var3, List var4, ComplexObject.TestEnum testEnum); } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/service/DemoServiceImpl.java b/dubbo-compatible/src/test/java/org/apache/dubbo/service/DemoServiceImpl.java index ea2ac17b3e..c74dc3ce48 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/service/DemoServiceImpl.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/service/DemoServiceImpl.java @@ -23,7 +23,6 @@ import java.util.List; /** * DemoServiceImpl */ - public class DemoServiceImpl implements DemoService { public DemoServiceImpl() { super(); @@ -42,25 +41,23 @@ public class DemoServiceImpl implements DemoService { } public int getSize(String[] strs) { - if (strs == null) - return -1; + if (strs == null) return -1; return strs.length; } public int getSize(Object[] os) { - if (os == null) - return -1; + if (os == null) return -1; return os.length; } public Object invoke(String service, String method) throws Exception { - System.out.println("RpcContext.getServerAttachment().getRemoteHost()=" + RpcContext.getServiceContext().getRemoteHost()); + System.out.println("RpcContext.getServerAttachment().getRemoteHost()=" + + RpcContext.getServiceContext().getRemoteHost()); return service + ":" + method; } public Type enumlength(Type... types) { - if (types.length == 0) - return Type.Lower; + if (types.length == 0) return Type.Lower; return types[0]; } @@ -86,7 +83,8 @@ public class DemoServiceImpl implements DemoService { } @Override - public ComplexObject findComplexObject(String var1, int var2, long l, String[] var3, List var4, ComplexObject.TestEnum testEnum) { + public ComplexObject findComplexObject( + String var1, int var2, long l, String[] var3, List var4, ComplexObject.TestEnum testEnum) { return new ComplexObject(var1, var2, l, var3, var4, testEnum); } diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java b/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java index d29e339c1f..80af895443 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/service/MockInvocation.java @@ -16,16 +16,16 @@ */ package org.apache.dubbo.service; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; - import org.apache.dubbo.rpc.AttachmentsAdapter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.model.ServiceModel; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; + import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; @@ -74,11 +74,11 @@ public class MockInvocation implements Invocation { } public Class[] getParameterTypes() { - return new Class[]{String.class}; + return new Class[] {String.class}; } public Object[] getArguments() { - return new Object[]{arg0}; + return new Object[] {arg0}; } public Map getAttachments() { @@ -145,9 +145,7 @@ public class MockInvocation implements Invocation { } @Override - public void setServiceModel(ServiceModel serviceModel) { - - } + public void setServiceModel(ServiceModel serviceModel) {} @Override public ServiceModel getServiceModel() { @@ -182,9 +180,7 @@ public class MockInvocation implements Invocation { } @Override - public void addInvokedInvoker(Invoker invoker) { - - } + public void addInvokedInvoker(Invoker invoker) {} @Override public List> getInvokedInvokers() { diff --git a/dubbo-compatible/src/test/java/org/apache/dubbo/service/Type.java b/dubbo-compatible/src/test/java/org/apache/dubbo/service/Type.java index 8bdb392b76..3700bccad5 100644 --- a/dubbo-compatible/src/test/java/org/apache/dubbo/service/Type.java +++ b/dubbo-compatible/src/test/java/org/apache/dubbo/service/Type.java @@ -17,5 +17,7 @@ package org.apache.dubbo.service; public enum Type { - High, Normal, Lower + High, + Normal, + Lower } diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml index 6dc26ed9fc..0d67610524 100644 --- a/dubbo-config/dubbo-config-api/pom.xml +++ b/dubbo-config/dubbo-config-api/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - org.apache.dubbo - dubbo-config - ${revision} - - dubbo-config-api - jar - ${project.artifactId} - The config api module of dubbo project - - false - - - - org.apache.dubbo - dubbo-registry-api - ${project.parent.version} - + + 4.0.0 + + org.apache.dubbo + dubbo-config + ${revision} + + dubbo-config-api + jar + ${project.artifactId} + The config api module of dubbo project + + false + + + + org.apache.dubbo + dubbo-registry-api + ${project.parent.version} + - - org.apache.dubbo - dubbo-metadata-api - ${project.parent.version} - + + org.apache.dubbo + dubbo-metadata-api + ${project.parent.version} + - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - + + org.apache.dubbo + dubbo-metrics-api + ${project.parent.version} + - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - + + org.apache.dubbo + dubbo-metrics-default + ${project.parent.version} + - - org.apache.dubbo - dubbo-metrics-registry - ${project.parent.version} - + + org.apache.dubbo + dubbo-metrics-registry + ${project.parent.version} + - - org.apache.dubbo - dubbo-metrics-metadata - ${project.parent.version} - + + org.apache.dubbo + dubbo-metrics-metadata + ${project.parent.version} + - - org.apache.dubbo - dubbo-metrics-config-center - ${project.parent.version} - + + org.apache.dubbo + dubbo-metrics-config-center + ${project.parent.version} + - - org.apache.dubbo - dubbo-tracing - ${project.parent.version} - + + org.apache.dubbo + dubbo-tracing + ${project.parent.version} + - - org.apache.dubbo - dubbo-monitor-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-rpc-injvm - ${project.parent.version} - + + org.apache.dubbo + dubbo-monitor-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-remoting-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-rpc-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-rpc-injvm + ${project.parent.version} + - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-rpc-triple - ${project.parent.version} - test - + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-rpc-triple + ${project.parent.version} + test + - - org.apache.dubbo - dubbo-rpc-rest - ${project.parent.version} - test - + + org.apache.dubbo + dubbo-rpc-rest + ${project.parent.version} + test + - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.parent.version} - test - + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.parent.version} + test + - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.parent.version} - test - + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.parent.version} + test + - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.parent.version} - test - + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.parent.version} + test + - - org.apache.dubbo - dubbo-registry-multicast - ${project.parent.version} - test - + + org.apache.dubbo + dubbo-registry-multicast + ${project.parent.version} + test + - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.parent.version} - test - + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.parent.version} + test + - - org.apache.curator - curator-framework - test - - - org.apache.curator - curator-recipes - test - - - org.apache.zookeeper - zookeeper - test - - - org.slf4j - slf4j-log4j12 - test - + + org.apache.curator + curator-framework + test + + + org.apache.curator + curator-recipes + test + + + org.apache.zookeeper + zookeeper + test + + + org.slf4j + slf4j-log4j12 + test + - - org.apache.dubbo - dubbo-registry-nacos - ${project.parent.version} - test - + + org.apache.dubbo + dubbo-registry-nacos + ${project.parent.version} + test + - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.parent.version} - test - - - com.google.guava - guava - - - + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${project.parent.version} + test + + + com.google.guava + guava + + + - - org.apache.dubbo - dubbo-metadata-report-redis - ${project.parent.version} - test - + + org.apache.dubbo + dubbo-metadata-report-redis + ${project.parent.version} + test + - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.parent.version} - test - + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.parent.version} + test + - - org.apache.dubbo - dubbo-configcenter-nacos - ${project.parent.version} - test - - - com.google.guava - guava - - - + + org.apache.dubbo + dubbo-configcenter-nacos + ${project.parent.version} + test + + + com.google.guava + guava + + + - - org.apache.dubbo - dubbo-filter-cache - ${project.parent.version} - test - + + org.apache.dubbo + dubbo-filter-cache + ${project.parent.version} + test + - - org.apache.dubbo - dubbo-filter-validation - ${project.parent.version} - test - + + org.apache.dubbo + dubbo-filter-validation + ${project.parent.version} + test + - - org.apache.dubbo - dubbo-plugin-router-condition - ${project.parent.version} - test - + + org.apache.dubbo + dubbo-plugin-router-condition + ${project.parent.version} + test + - - org.apache.dubbo - dubbo-plugin-router-tag - ${project.parent.version} - test - + + org.apache.dubbo + dubbo-plugin-router-tag + ${project.parent.version} + test + - - org.testcontainers - testcontainers - 1.19.1 - test - + + org.testcontainers + testcontainers + 1.19.1 + test + - - org.jboss.resteasy - resteasy-jackson-provider - test - - + + org.jboss.resteasy + resteasy-jackson-provider + test + + diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigInitializer.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigInitializer.java index 8f12d79c76..52fe883d4c 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigInitializer.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigInitializer.java @@ -22,16 +22,10 @@ import org.apache.dubbo.common.extension.SPI; /** * Dynamically add some parameters / check config */ - @SPI(scope = ExtensionScope.MODULE) public interface ConfigInitializer { - default void initReferConfig(ReferenceConfig referenceConfig) { - - } - - default void initServiceConfig(ServiceConfig serviceConfig) { - - } + default void initReferConfig(ReferenceConfig referenceConfig) {} + default void initServiceConfig(ServiceConfig serviceConfig) {} } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigPostProcessor.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigPostProcessor.java index 7e59582ff9..57daef48df 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigPostProcessor.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigPostProcessor.java @@ -27,11 +27,7 @@ import org.apache.dubbo.common.extension.SPI; @SPI(scope = ExtensionScope.MODULE) public interface ConfigPostProcessor extends CommonConfigPostProcessor { - default void postProcessReferConfig(ReferenceConfig referenceConfig) { + default void postProcessReferConfig(ReferenceConfig referenceConfig) {} - } - - default void postProcessServiceConfig(ServiceConfig serviceConfig) { - - } + default void postProcessServiceConfig(ServiceConfig serviceConfig) {} } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigScopeModelInitializer.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigScopeModelInitializer.java index 955da26d23..56fcb2caf0 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigScopeModelInitializer.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigScopeModelInitializer.java @@ -42,7 +42,6 @@ public class ConfigScopeModelInitializer implements ScopeModelInitializer { // applicationDeployer ApplicationDeployer applicationDeployer = beanFactory.registerBean(DefaultApplicationDeployer.class); applicationModel.setDeployer(applicationDeployer); - } @Override diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/DubboShutdownHook.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/DubboShutdownHook.java index a8dc78d606..6dc9a0f54a 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/DubboShutdownHook.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/DubboShutdownHook.java @@ -63,9 +63,11 @@ public class DubboShutdownHook extends Thread { super("DubboShutdownHook"); this.applicationModel = applicationModel; Assert.notNull(this.applicationModel, "ApplicationModel is null"); - ignoreListenShutdownHook = Boolean.parseBoolean(ConfigurationUtils.getProperty(applicationModel, CommonConstants.IGNORE_LISTEN_SHUTDOWN_HOOK)); + ignoreListenShutdownHook = Boolean.parseBoolean( + ConfigurationUtils.getProperty(applicationModel, CommonConstants.IGNORE_LISTEN_SHUTDOWN_HOOK)); if (ignoreListenShutdownHook) { - logger.info(CommonConstants.IGNORE_LISTEN_SHUTDOWN_HOOK + " configured, will ignore add shutdown hook to jvm."); + logger.info( + CommonConstants.IGNORE_LISTEN_SHUTDOWN_HOOK + " configured, will ignore add shutdown hook to jvm."); } } @@ -86,7 +88,8 @@ public class DubboShutdownHook extends Thread { ConfigurationUtils.setExpectedShutdownTime(System.currentTimeMillis() + timeout); // send readonly for shutdown hook - List gracefulShutdowns = GracefulShutdown.getGracefulShutdowns(applicationModel.getFrameworkModel()); + List gracefulShutdowns = + GracefulShutdown.getGracefulShutdowns(applicationModel.getFrameworkModel()); for (GracefulShutdown gracefulShutdown : gracefulShutdowns) { gracefulShutdown.readonly(); } @@ -103,12 +106,14 @@ public class DubboShutdownHook extends Thread { if (timeout > 0) { long start = System.currentTimeMillis(); /* - To avoid shutdown conflicts between Dubbo and Spring, - wait for the modules bound to Spring to be handled by Spring until timeout. - */ - logger.info("Waiting for modules(" + applicationModel.getDesc() + ") managed by Spring to be shutdown."); - while (!applicationModel.isDestroyed() && hasModuleBindSpring - && (System.currentTimeMillis() - start) < timeout) { + To avoid shutdown conflicts between Dubbo and Spring, + wait for the modules bound to Spring to be handled by Spring until timeout. + */ + logger.info( + "Waiting for modules(" + applicationModel.getDesc() + ") managed by Spring to be shutdown."); + while (!applicationModel.isDestroyed() + && hasModuleBindSpring + && (System.currentTimeMillis() - start) < timeout) { try { TimeUnit.MILLISECONDS.sleep(10); hasModuleBindSpring = false; @@ -127,8 +132,8 @@ public class DubboShutdownHook extends Thread { } if (!applicationModel.isDestroyed()) { long usage = System.currentTimeMillis() - start; - logger.info("Dubbo wait for application(" + applicationModel.getDesc() + ") managed by Spring to be shutdown failed, " + - "time usage: " + usage + "ms"); + logger.info("Dubbo wait for application(" + applicationModel.getDesc() + + ") managed by Spring to be shutdown failed, " + "time usage: " + usage + "ms"); } } } @@ -165,9 +170,11 @@ public class DubboShutdownHook extends Thread { try { Runtime.getRuntime().removeShutdownHook(this); } catch (IllegalStateException e) { - logger.warn(CONFIG_FAILED_SHUTDOWN_HOOK, "", "", "unregister shutdown hook failed: " + e.getMessage(), e); + logger.warn( + CONFIG_FAILED_SHUTDOWN_HOOK, "", "", "unregister shutdown hook failed: " + e.getMessage(), e); } catch (Exception e) { - logger.warn(CONFIG_FAILED_SHUTDOWN_HOOK, "", "", "unregister shutdown hook failed: " + e.getMessage(), e); + logger.warn( + CONFIG_FAILED_SHUTDOWN_HOOK, "", "", "unregister shutdown hook failed: " + e.getMessage(), e); } } } @@ -175,5 +182,4 @@ public class DubboShutdownHook extends Thread { public boolean getRegistered() { return registered.get(); } - } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java index 343f8d0ac1..23bd4eaaa5 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java @@ -263,7 +263,12 @@ public class ReferenceConfig extends ReferenceConfigBase { invoker.destroy(); } } catch (Throwable destroy) { - logger.warn(CONFIG_FAILED_DESTROY_INVOKER, "", "", "Unexpected error occurred when destroy invoker of ReferenceConfig(" + url + ").", t); + logger.warn( + CONFIG_FAILED_DESTROY_INVOKER, + "", + "", + "Unexpected error occurred when destroy invoker of ReferenceConfig(" + url + ").", + t); } if (consumerModel != null) { ModuleServiceRepository repository = getScopeModel().getServiceRepository(); @@ -277,8 +282,8 @@ public class ReferenceConfig extends ReferenceConfigBase { serviceMetadata.getAttributeMap().remove(PROXY_CLASS_REF); // Thrown by checkInvokerAvailable(). - if (t.getClass() == IllegalStateException.class && - t.getMessage().contains("No provider available for the service")) { + if (t.getClass() == IllegalStateException.class + && t.getMessage().contains("No provider available for the service")) { // 2-2 - No provider available. logger.error(CLUSTER_NO_VALID_PROVIDER, "server crashed", "", "No provider available.", t); @@ -297,7 +302,12 @@ public class ReferenceConfig extends ReferenceConfigBase { invoker.destroy(); } } catch (Throwable t) { - logger.warn(CONFIG_FAILED_DESTROY_INVOKER, "", "", "Unexpected error occurred when destroy invoker of ReferenceConfig(" + url + ").", t); + logger.warn( + CONFIG_FAILED_DESTROY_INVOKER, + "", + "", + "Unexpected error occurred when destroy invoker of ReferenceConfig(" + url + ").", + t); } invoker = null; ref = null; @@ -319,10 +329,9 @@ public class ReferenceConfig extends ReferenceConfigBase { if (!this.isRefreshed()) { this.refresh(); } - //auto detect proxy type + // auto detect proxy type String proxyType = getProxy(); - if (StringUtils.isBlank(proxyType) - && DubboStub.class.isAssignableFrom(interfaceClass)) { + if (StringUtils.isBlank(proxyType) && DubboStub.class.isAssignableFrom(interfaceClass)) { setProxy(CommonConstants.NATIVE_STUB); } @@ -343,10 +352,17 @@ public class ReferenceConfig extends ReferenceConfigBase { } else { serviceDescriptor = repository.registerService(interfaceClass); } - consumerModel = new ConsumerModel(serviceMetadata.getServiceKey(), proxy, serviceDescriptor, - getScopeModel(), serviceMetadata, createAsyncMethodInfo(), interfaceClassLoader); + consumerModel = new ConsumerModel( + serviceMetadata.getServiceKey(), + proxy, + serviceDescriptor, + getScopeModel(), + serviceMetadata, + createAsyncMethodInfo(), + interfaceClassLoader); - // Compatible with dependencies on ServiceModel#getReferenceConfig() , and will be removed in a future version. + // Compatible with dependencies on ServiceModel#getReferenceConfig() , and will be removed in a future + // version. consumerModel.setConfig(this); repository.registerConsumer(consumerModel); @@ -414,7 +430,11 @@ public class ReferenceConfig extends ReferenceConfigBase { String[] methods = methods(interfaceClass); if (methods.length == 0) { - logger.warn(CONFIG_NO_METHOD_FOUND, "", "", "No method found in service interface: " + interfaceClass.getName()); + logger.warn( + CONFIG_NO_METHOD_FOUND, + "", + "", + "No method found in service interface: " + interfaceClass.getName()); map.put(METHODS_KEY, ANY_VALUE); } else { map.put(METHODS_KEY, StringUtils.join(new TreeSet<>(Arrays.asList(methods)), COMMA_SEPARATOR)); @@ -431,8 +451,8 @@ public class ReferenceConfig extends ReferenceConfigBase { if (StringUtils.isEmpty(hostToRegistry)) { hostToRegistry = NetUtils.getLocalHost(); } else if (isInvalidLocalHost(hostToRegistry)) { - throw new IllegalArgumentException( - "Specified invalid registry ip from property:" + DUBBO_IP_TO_REGISTRY + ", value:" + hostToRegistry); + throw new IllegalArgumentException("Specified invalid registry ip from property:" + DUBBO_IP_TO_REGISTRY + + ", value:" + hostToRegistry); } map.put(REGISTER_IP_KEY, hostToRegistry); @@ -469,13 +489,18 @@ public class ReferenceConfig extends ReferenceConfigBase { createInvoker(); if (logger.isInfoEnabled()) { - logger.info("Referred dubbo service: [" + referenceParameters.get(INTERFACE_KEY) + "]." + - (ProtocolUtils.isGeneric(referenceParameters.get(GENERIC_KEY)) ? - " it's GenericService reference" : " it's not GenericService reference")); + logger.info("Referred dubbo service: [" + referenceParameters.get(INTERFACE_KEY) + "]." + + (ProtocolUtils.isGeneric(referenceParameters.get(GENERIC_KEY)) + ? " it's GenericService reference" + : " it's not GenericService reference")); } - URL consumerUrl = new ServiceConfigURL(CONSUMER_PROTOCOL, referenceParameters.get(REGISTER_IP_KEY), 0, - referenceParameters.get(INTERFACE_KEY), referenceParameters); + URL consumerUrl = new ServiceConfigURL( + CONSUMER_PROTOCOL, + referenceParameters.get(REGISTER_IP_KEY), + 0, + referenceParameters.get(INTERFACE_KEY), + referenceParameters); consumerUrl = consumerUrl.setScopeModel(getScopeModel()); consumerUrl = consumerUrl.setServiceModel(consumerModel); MetadataUtils.publishServiceDefinition(consumerUrl, consumerModel.getServiceModel(), getApplicationModel()); @@ -508,8 +533,12 @@ public class ReferenceConfig extends ReferenceConfigBase { if (StringUtils.isEmpty(podNamespace)) { if (StringUtils.isEmpty(System.getenv(POD_NAMESPACE))) { if (logger.isWarnEnabled()) { - logger.warn(CONFIG_FAILED_LOAD_ENV_VARIABLE, "", "", "Can not get env variable: POD_NAMESPACE, it may not be running in the K8S environment , " + - "finally use 'default' replace."); + logger.warn( + CONFIG_FAILED_LOAD_ENV_VARIABLE, + "", + "", + "Can not get env variable: POD_NAMESPACE, it may not be running in the K8S environment , " + + "finally use 'default' replace."); } podNamespace = "default"; } else { @@ -520,8 +549,10 @@ public class ReferenceConfig extends ReferenceConfigBase { // In mesh mode, providedBy equals K8S Service name. String providedBy = referenceParameters.get(PROVIDED_BY); // cluster_domain default is 'cluster.local',generally unchanged. - String clusterDomain = Optional.ofNullable(System.getenv(CLUSTER_DOMAIN)).orElse(DEFAULT_CLUSTER_DOMAIN); - // By VirtualService and DestinationRule, envoy will generate a new route rule,such as 'demo.default.svc.cluster.local:80',the default port is 80. + String clusterDomain = + Optional.ofNullable(System.getenv(CLUSTER_DOMAIN)).orElse(DEFAULT_CLUSTER_DOMAIN); + // By VirtualService and DestinationRule, envoy will generate a new route rule,such as + // 'demo.default.svc.cluster.local:80',the default port is 80. Integer meshPort = Optional.ofNullable(getProviderPort()).orElse(DEFAULT_MESH_PORT); // DubboReference default is -1, process it. meshPort = meshPort > -1 ? meshPort : DEFAULT_MESH_PORT; @@ -542,7 +573,9 @@ public class ReferenceConfig extends ReferenceConfigBase { return false; } - getScopeModel().getConfigManager().getProtocol(TRIPLE) + getScopeModel() + .getConfigManager() + .getProtocol(TRIPLE) .orElseThrow(() -> new IllegalStateException("In mesh mode, a triple protocol must be specified")); String providedBy = referenceParameters.get(PROVIDED_BY); @@ -553,7 +586,6 @@ public class ReferenceConfig extends ReferenceConfigBase { return true; } - /** * Parse the directly configured url. */ @@ -570,7 +602,11 @@ public class ReferenceConfig extends ReferenceConfigBase { if (UrlUtils.isRegistry(url)) { urls.add(url.putAttribute(REFER_KEY, referenceParameters)); } else { - URL peerUrl = getScopeModel().getApplicationModel().getBeanFactory().getBean(ClusterUtils.class).mergeUrl(url, referenceParameters); + URL peerUrl = getScopeModel() + .getApplicationModel() + .getBeanFactory() + .getBean(ClusterUtils.class) + .mergeUrl(url, referenceParameters); peerUrl = peerUrl.putAttribute(PEER_KEY, true); urls.add(peerUrl); } @@ -599,20 +635,20 @@ public class ReferenceConfig extends ReferenceConfigBase { } } if (urls.isEmpty() && shouldJvmRefer(referenceParameters)) { - URL injvmUrl = new URL(LOCAL_PROTOCOL,LOCALHOST_VALUE,0,interfaceClass.getName()).addParameters(referenceParameters); + URL injvmUrl = new URL(LOCAL_PROTOCOL, LOCALHOST_VALUE, 0, interfaceClass.getName()) + .addParameters(referenceParameters); injvmUrl = injvmUrl.setScopeModel(getScopeModel()); injvmUrl = injvmUrl.setServiceModel(consumerModel); urls.add(injvmUrl.putAttribute(REFER_KEY, referenceParameters)); } if (urls.isEmpty()) { - throw new IllegalStateException( - "No such any registry to reference " + interfaceName + " on the consumer " + NetUtils.getLocalHost() + - " use dubbo version " + Version.getVersion() + - ", please config to your spring config."); + throw new IllegalStateException("No such any registry to reference " + interfaceName + " on the consumer " + + NetUtils.getLocalHost() + " use dubbo version " + + Version.getVersion() + + ", please config to your spring config."); } } - /** * \create a reference invoker */ @@ -622,11 +658,11 @@ public class ReferenceConfig extends ReferenceConfigBase { URL curUrl = urls.get(0); invoker = protocolSPI.refer(interfaceClass, curUrl); // registry url, mesh-enable and unloadClusterRelated is true, not need Cluster. - if (!UrlUtils.isRegistry(curUrl) && - !curUrl.getParameter(UNLOAD_CLUSTER_RELATED, false)) { + if (!UrlUtils.isRegistry(curUrl) && !curUrl.getParameter(UNLOAD_CLUSTER_RELATED, false)) { List> invokers = new ArrayList<>(); invokers.add(invoker); - invoker = Cluster.getCluster(getScopeModel(), Cluster.DEFAULT).join(new StaticDirectory(curUrl, invokers), true); + invoker = Cluster.getCluster(getScopeModel(), Cluster.DEFAULT) + .join(new StaticDirectory(curUrl, invokers), true); } } else { List> invokers = new ArrayList<>(); @@ -646,9 +682,11 @@ public class ReferenceConfig extends ReferenceConfigBase { // registry url is available // for multi-subscription scenario, use 'zone-aware' policy by default String cluster = registryUrl.getParameter(CLUSTER_KEY, ZoneAwareCluster.NAME); - // The invoker wrap sequence would be: ZoneAwareClusterInvoker(StaticDirectory) -> FailoverClusterInvoker + // The invoker wrap sequence would be: ZoneAwareClusterInvoker(StaticDirectory) -> + // FailoverClusterInvoker // (RegistryDirectory, routing happens here) -> Invoker - invoker = Cluster.getCluster(registryUrl.getScopeModel(), cluster, false).join(new StaticDirectory(registryUrl, invokers), false); + invoker = Cluster.getCluster(registryUrl.getScopeModel(), cluster, false) + .join(new StaticDirectory(registryUrl, invokers), false); } else { // not a registry url, must be direct invoke. if (CollectionUtils.isEmpty(invokers)) { @@ -656,7 +694,8 @@ public class ReferenceConfig extends ReferenceConfigBase { } URL curUrl = invokers.get(0).getUrl(); String cluster = curUrl.getParameter(CLUSTER_KEY, Cluster.DEFAULT); - invoker = Cluster.getCluster(getScopeModel(), cluster).join(new StaticDirectory(curUrl, invokers), true); + invoker = + Cluster.getCluster(getScopeModel(), cluster).join(new StaticDirectory(curUrl, invokers), true); } } } @@ -681,25 +720,34 @@ public class ReferenceConfig extends ReferenceConfigBase { } available = invoker.isAvailable(); } while (!available && checkDeadline > System.currentTimeMillis()); - logger.warn(LoggerCodeConstants.REGISTRY_EMPTY_ADDRESS, "", "", - "Check reference of [" + getUniqueServiceName() + "] failed very beginning. " + - "After " + (System.currentTimeMillis() - startTime) + "ms reties, finally " + - (available ? "succeed" : "failed") + "."); + logger.warn( + LoggerCodeConstants.REGISTRY_EMPTY_ADDRESS, + "", + "", + "Check reference of [" + getUniqueServiceName() + "] failed very beginning. " + "After " + + (System.currentTimeMillis() - startTime) + "ms reties, finally " + + (available ? "succeed" : "failed") + + "."); if (!available) { // 2-2 - No provider available. - IllegalStateException illegalStateException = new IllegalStateException("Failed to check the status of the service " - + interfaceName - + ". No provider available for the service " - + (group == null ? "" : group + "/") - + interfaceName + - (version == null ? "" : ":" + version) - + " from the url " - + invoker.getUrl() - + " to the consumer " - + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion()); + IllegalStateException illegalStateException = + new IllegalStateException("Failed to check the status of the service " + + interfaceName + + ". No provider available for the service " + + (group == null ? "" : group + "/") + + interfaceName + (version == null ? "" : ":" + version) + + " from the url " + + invoker.getUrl() + + " to the consumer " + + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion()); - logger.error(CLUSTER_NO_VALID_PROVIDER, "provider not started", "", "No provider available.", illegalStateException); + logger.error( + CLUSTER_NO_VALID_PROVIDER, + "provider not started", + "", + "No provider available.", + illegalStateException); throw illegalStateException; } @@ -727,19 +775,29 @@ public class ReferenceConfig extends ReferenceConfigBase { } if (ProtocolUtils.isGeneric(generic)) { if (interfaceClass != null && !interfaceClass.equals(GenericService.class)) { - logger.warn(CONFIG_PROPERTY_CONFLICT, "", "", String.format("Found conflicting attributes for interface type: [interfaceClass=%s] and [generic=%s], " + - "because the 'generic' attribute has higher priority than 'interfaceClass', so change 'interfaceClass' to '%s'. " + - "Note: it will make this reference bean as a candidate bean of type '%s' instead of '%s' when resolving dependency in Spring.", - interfaceClass.getName(), generic, GenericService.class.getName(), GenericService.class.getName(), interfaceClass.getName())); + logger.warn( + CONFIG_PROPERTY_CONFLICT, + "", + "", + String.format( + "Found conflicting attributes for interface type: [interfaceClass=%s] and [generic=%s], " + + "because the 'generic' attribute has higher priority than 'interfaceClass', so change 'interfaceClass' to '%s'. " + + "Note: it will make this reference bean as a candidate bean of type '%s' instead of '%s' when resolving dependency in Spring.", + interfaceClass.getName(), + generic, + GenericService.class.getName(), + GenericService.class.getName(), + interfaceClass.getName())); } interfaceClass = GenericService.class; } else { try { - if (getInterfaceClassLoader() != null && (interfaceClass == null || interfaceClass.getClassLoader() != getInterfaceClassLoader())) { + if (getInterfaceClassLoader() != null + && (interfaceClass == null || interfaceClass.getClassLoader() != getInterfaceClassLoader())) { interfaceClass = Class.forName(interfaceName, true, getInterfaceClassLoader()); } else if (interfaceClass == null) { - interfaceClass = Class.forName(interfaceName, true, Thread.currentThread() - .getContextClassLoader()); + interfaceClass = Class.forName( + interfaceName, true, Thread.currentThread().getContextClassLoader()); } } catch (ClassNotFoundException e) { throw new IllegalStateException(e.getMessage(), e); @@ -800,8 +858,9 @@ public class ReferenceConfig extends ReferenceConfigBase { private void postProcessConfig() { List configPostProcessors = this.getExtensionLoader(ConfigPostProcessor.class) .getActivateExtension(URL.valueOf("configPostProcessor://"), (String[]) null); - List commonConfigPostProcessors = this.getExtensionLoader(CommonConfigPostProcessor.class) - .getActivateExtension(URL.valueOf("configPostProcessor://"), (String[]) null); + List commonConfigPostProcessors = this.getExtensionLoader( + CommonConfigPostProcessor.class) + .getActivateExtension(URL.valueOf("configPostProcessor://"), (String[]) null); HashSet allConfigPostProcessor = new HashSet<>(); diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java index f7290aa9fc..f2e4869e7d 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java @@ -162,8 +162,7 @@ public class ServiceConfig extends ServiceConfigBase { private final List serviceListeners = new ArrayList<>(); - public ServiceConfig() { - } + public ServiceConfig() {} public ServiceConfig(ModuleModel moduleModel) { super(moduleModel); @@ -190,7 +189,6 @@ public class ServiceConfig extends ServiceConfigBase { return exported; } - @Override @Parameter(excluded = true, attribute = false) public boolean isUnexported() { @@ -211,7 +209,12 @@ public class ServiceConfig extends ServiceConfigBase { try { exporter.unregister(); } catch (Throwable t) { - logger.warn(CONFIG_UNEXPORT_ERROR, "", "", "Unexpected error occurred when unexport " + exporter, t); + logger.warn( + CONFIG_UNEXPORT_ERROR, + "", + "", + "Unexpected error occurred when unexport " + exporter, + t); } } } @@ -221,7 +224,12 @@ public class ServiceConfig extends ServiceConfigBase { try { exporter.unexport(); } catch (Throwable t) { - logger.warn(CONFIG_UNEXPORT_ERROR, "", "", "Unexpected error occurred when unexport " + exporter, t); + logger.warn( + CONFIG_UNEXPORT_ERROR, + "", + "", + "Unexpected error occurred when unexport " + exporter, + t); } } } @@ -243,10 +251,12 @@ public class ServiceConfig extends ServiceConfigBase { return; } - // 2. if service has idle for more than 6.7s(2/3 of shutdown time), wait for the rest time, then un-export directly + // 2. if service has idle for more than 6.7s(2/3 of shutdown time), wait for the rest time, then un-export + // directly int tick = timeout / 3; if (timeout - idleTime < tick) { - logger.info("Service " + getUniqueServiceName() + " has idle for " + idleTime + " ms, wait for " + (timeout - idleTime) + " ms to un-export"); + logger.info("Service " + getUniqueServiceName() + " has idle for " + idleTime + " ms, wait for " + + (timeout - idleTime) + " ms to un-export"); try { Thread.sleep(timeout - idleTime); } catch (InterruptedException e) { @@ -256,8 +266,10 @@ public class ServiceConfig extends ServiceConfigBase { return; } - // 3. Wait for 3.33s(1/3 of shutdown time), if service has idle for 3.33s(1/3 of shutdown time), un-export directly, - // otherwise wait for the rest time until idle for 3.33s(1/3 of shutdown time). The max wait time is 10s(shutdown time). + // 3. Wait for 3.33s(1/3 of shutdown time), if service has idle for 3.33s(1/3 of shutdown time), un-export + // directly, + // otherwise wait for the rest time until idle for 3.33s(1/3 of shutdown time). The max wait time is + // 10s(shutdown time). idleTime = 0; long startTime = System.currentTimeMillis(); while (idleTime < tick) { @@ -268,7 +280,8 @@ public class ServiceConfig extends ServiceConfigBase { } // idle rest time or timeout rest time long waitTime = Math.min(tick - idleTime, timeout + startTime - System.currentTimeMillis()); - logger.info("Service " + getUniqueServiceName() + " has idle for " + idleTime + " ms, wait for " + waitTime + " ms to un-export"); + logger.info("Service " + getUniqueServiceName() + " has idle for " + idleTime + " ms, wait for " + waitTime + + " ms to un-export"); try { Thread.sleep(waitTime); } catch (InterruptedException e) { @@ -321,9 +334,9 @@ public class ServiceConfig extends ServiceConfigBase { if (shouldDelay()) { // should register if delay export doDelayExport(); - } else if (Integer.valueOf(-1).equals(getDelay()) && - Boolean.parseBoolean(ConfigurationUtils.getProperty( - getScopeModel(), CommonConstants.DUBBO_MANUAL_REGISTER_KEY, "false"))) { + } else if (Integer.valueOf(-1).equals(getDelay()) + && Boolean.parseBoolean(ConfigurationUtils.getProperty( + getScopeModel(), CommonConstants.DUBBO_MANUAL_REGISTER_KEY, "false"))) { // should not register by default doExport(RegisterTypeEnum.MANUAL_REGISTER); } else { @@ -344,12 +357,14 @@ public class ServiceConfig extends ServiceConfigBase { return; } - for (Exporter exporter : exporters.getOrDefault(RegisterTypeEnum.AUTO_REGISTER, Collections.emptyList())) { + for (Exporter exporter : + exporters.getOrDefault(RegisterTypeEnum.AUTO_REGISTER, Collections.emptyList())) { exporter.register(); } if (byDeployer) { - for (Exporter exporter : exporters.getOrDefault(RegisterTypeEnum.AUTO_REGISTER_BY_DEPLOYER, Collections.emptyList())) { + for (Exporter exporter : + exporters.getOrDefault(RegisterTypeEnum.AUTO_REGISTER_BY_DEPLOYER, Collections.emptyList())) { exporter.register(); } } @@ -357,14 +372,23 @@ public class ServiceConfig extends ServiceConfigBase { } protected void doDelayExport() { - ExecutorRepository.getInstance(getScopeModel().getApplicationModel()).getServiceExportExecutor() - .schedule(() -> { - try { - doExport(RegisterTypeEnum.AUTO_REGISTER); - } catch (Exception e) { - logger.error(CONFIG_FAILED_EXPORT_SERVICE, "configuration server disconnected", "", "Failed to (async)export service config: " + interfaceName, e); - } - }, getDelay(), TimeUnit.MILLISECONDS); + ExecutorRepository.getInstance(getScopeModel().getApplicationModel()) + .getServiceExportExecutor() + .schedule( + () -> { + try { + doExport(RegisterTypeEnum.AUTO_REGISTER); + } catch (Exception e) { + logger.error( + CONFIG_FAILED_EXPORT_SERVICE, + "configuration server disconnected", + "", + "Failed to (async)export service config: " + interfaceName, + e); + } + }, + getDelay(), + TimeUnit.MILLISECONDS); } protected void exported() { @@ -373,8 +397,10 @@ public class ServiceConfig extends ServiceConfigBase { exportedURLs.forEach(url -> { if (url.getParameters().containsKey(SERVICE_NAME_MAPPING_KEY)) { ServiceNameMapping serviceNameMapping = ServiceNameMapping.getDefaultExtension(getScopeModel()); - ScheduledExecutorService scheduledExecutor = getScopeModel().getBeanFactory() - .getBean(FrameworkExecutorRepository.class).getSharedScheduledExecutor(); + ScheduledExecutorService scheduledExecutor = getScopeModel() + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class) + .getSharedScheduledExecutor(); mapServiceName(url, serviceNameMapping, scheduledExecutor); } }); @@ -388,10 +414,14 @@ public class ServiceConfig extends ServiceConfigBase { public boolean hasRegistrySpecified() { return CollectionUtils.isNotEmpty(this.getRegistries()) - || CollectionUtils.isNotEmpty(getScopeModel().getApplicationModel().getApplicationConfigManager().getRegistries()); + || CollectionUtils.isNotEmpty(getScopeModel() + .getApplicationModel() + .getApplicationConfigManager() + .getRegistries()); } - protected void mapServiceName(URL url, ServiceNameMapping serviceNameMapping, ScheduledExecutorService scheduledExecutor) { + protected void mapServiceName( + URL url, ServiceNameMapping serviceNameMapping, ScheduledExecutorService scheduledExecutor) { if (!exported) { return; } @@ -402,20 +432,32 @@ public class ServiceConfig extends ServiceConfigBase { if (succeeded) { logger.info("Successfully registered interface application mapping for service " + url.getServiceKey()); } else { - logger.error(CONFIG_SERVER_DISCONNECTED, "configuration server disconnected", "", "Failed register interface application mapping for service " + url.getServiceKey()); + logger.error( + CONFIG_SERVER_DISCONNECTED, + "configuration server disconnected", + "", + "Failed register interface application mapping for service " + url.getServiceKey()); } } catch (Exception e) { - logger.error(CONFIG_SERVER_DISCONNECTED, "configuration server disconnected", "", "Failed register interface application mapping for service " + url.getServiceKey(), e); + logger.error( + CONFIG_SERVER_DISCONNECTED, + "configuration server disconnected", + "", + "Failed register interface application mapping for service " + url.getServiceKey(), + e); } if (!succeeded && serviceNameMapping.hasValidMetadataCenter()) { scheduleToMapping(scheduledExecutor, serviceNameMapping, url); } } - private void scheduleToMapping(ScheduledExecutorService scheduledExecutor, ServiceNameMapping serviceNameMapping, URL url) { + private void scheduleToMapping( + ScheduledExecutorService scheduledExecutor, ServiceNameMapping serviceNameMapping, URL url) { Integer mappingRetryInterval = getApplication().getMappingRetryInterval(); - scheduledExecutor.schedule(() -> mapServiceName(url, serviceNameMapping, scheduledExecutor), - mappingRetryInterval == null ? 5000 : mappingRetryInterval, TimeUnit.MILLISECONDS); + scheduledExecutor.schedule( + () -> mapServiceName(url, serviceNameMapping, scheduledExecutor), + mappingRetryInterval == null ? 5000 : mappingRetryInterval, + TimeUnit.MILLISECONDS); } private void checkAndUpdateSubConfigs() { @@ -427,7 +469,7 @@ public class ServiceConfig extends ServiceConfigBase { // init some null configuration. List configInitializers = this.getExtensionLoader(ConfigInitializer.class) - .getActivateExtension(URL.valueOf("configInitializer://", getScopeModel()), (String[]) null); + .getActivateExtension(URL.valueOf("configInitializer://", getScopeModel()), (String[]) null); configInitializers.forEach(e -> e.initServiceConfig(this)); // if protocol is not injvm checkRegistry @@ -449,7 +491,8 @@ public class ServiceConfig extends ServiceConfigBase { if (getInterfaceClassLoader() != null) { interfaceClass = Class.forName(interfaceName, true, getInterfaceClassLoader()); } else { - interfaceClass = Class.forName(interfaceName, true, Thread.currentThread().getContextClassLoader()); + interfaceClass = Class.forName( + interfaceName, true, Thread.currentThread().getContextClassLoader()); } } catch (ClassNotFoundException e) { throw new IllegalStateException(e.getMessage(), e); @@ -468,7 +511,8 @@ public class ServiceConfig extends ServiceConfigBase { throw new IllegalStateException(e.getMessage(), e); } if (!interfaceClass.isAssignableFrom(localClass)) { - throw new IllegalStateException("The local implementation class " + localClass.getName() + " not implement interface " + interfaceName); + throw new IllegalStateException("The local implementation class " + localClass.getName() + + " not implement interface " + interfaceName); } } if (stub != null) { @@ -482,7 +526,8 @@ public class ServiceConfig extends ServiceConfigBase { throw new IllegalStateException(e.getMessage(), e); } if (!interfaceClass.isAssignableFrom(stubClass)) { - throw new IllegalStateException("The stub implementation class " + stubClass.getName() + " not implement interface " + interfaceName); + throw new IllegalStateException("The stub implementation class " + stubClass.getName() + + " not implement interface " + interfaceName); } } checkStubAndLocal(interfaceClass); @@ -522,11 +567,13 @@ public class ServiceConfig extends ServiceConfigBase { } else { serviceDescriptor = repository.registerService(getInterfaceClass()); } - providerModel = new ProviderModel(serviceMetadata.getServiceKey(), - ref, - serviceDescriptor, - getScopeModel(), - serviceMetadata, interfaceClassLoader); + providerModel = new ProviderModel( + serviceMetadata.getServiceKey(), + ref, + serviceDescriptor, + getScopeModel(), + serviceMetadata, + interfaceClassLoader); // Compatible with dependencies on ServiceModel#getServiceConfig(), and will be removed in a future version providerModel.setConfig(this); @@ -534,13 +581,13 @@ public class ServiceConfig extends ServiceConfigBase { providerModel.setDestroyRunner(getDestroyRunner()); repository.registerProvider(providerModel); - List registryURLs = !Boolean.FALSE.equals(isRegister()) ? - ConfigValidationUtils.loadRegistries(this, true) : Collections.emptyList(); + List registryURLs = !Boolean.FALSE.equals(isRegister()) + ? ConfigValidationUtils.loadRegistries(this, true) + : Collections.emptyList(); for (ProtocolConfig protocolConfig : protocols) { - String pathKey = URL.buildKey(getContextPath(protocolConfig) - .map(p -> p + "/" + path) - .orElse(path), group, version); + String pathKey = URL.buildKey( + getContextPath(protocolConfig).map(p -> p + "/" + path).orElse(path), group, version); // stub service will use generated service name if (!serverService) { // In case user specified path, register service one more time to map it to path. @@ -552,7 +599,8 @@ public class ServiceConfig extends ServiceConfigBase { providerModel.setServiceUrls(urls); } - private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List registryURLs, RegisterTypeEnum registerType) { + private void doExportUrlsFor1Protocol( + ProtocolConfig protocolConfig, List registryURLs, RegisterTypeEnum registerType) { Map map = buildAttributes(protocolConfig); // remove null key and null value @@ -573,11 +621,25 @@ public class ServiceConfig extends ServiceConfigBase { } private void initServiceMethodMetrics(URL url) { - String[] methods = Optional.ofNullable(url.getParameter(METHODS_KEY)).map(i -> i.split(",")).orElse(new String[]{}); + String[] methods = Optional.ofNullable(url.getParameter(METHODS_KEY)) + .map(i -> i.split(",")) + .orElse(new String[] {}); boolean serviceLevel = MethodMetric.isServiceLevel(application.getApplicationModel()); Arrays.stream(methods).forEach(method -> { - RpcInvocation invocation = new RpcInvocation(url.getServiceKey(), url.getServiceModel(), method, interfaceName, url.getProtocolServiceKey(), null, null, null, null, null, null); - MetricsEventBus.publish(MetricsInitEvent.toMetricsInitEvent(application.getApplicationModel(), invocation, serviceLevel)); + RpcInvocation invocation = new RpcInvocation( + url.getServiceKey(), + url.getServiceModel(), + method, + interfaceName, + url.getProtocolServiceKey(), + null, + null, + null, + null, + null, + null); + MetricsEventBus.publish( + MetricsInitEvent.toMetricsInitEvent(application.getApplicationModel(), invocation, serviceLevel)); }); } @@ -585,8 +647,13 @@ public class ServiceConfig extends ServiceConfigBase { if (getExecutor() != null) { String mode = application.getExecutorManagementMode(); if (!EXECUTOR_MANAGEMENT_MODE_ISOLATION.equals(mode)) { - logger.warn(COMMON_ISOLATED_EXECUTOR_CONFIGURATION_ERROR, "", "", "The current executor management mode is " + mode + - ", the configured service executor cannot take effect unless the mode is configured as " + EXECUTOR_MANAGEMENT_MODE_ISOLATION); + logger.warn( + COMMON_ISOLATED_EXECUTOR_CONFIGURATION_ERROR, + "", + "", + "The current executor management mode is " + mode + + ", the configured service executor cannot take effect unless the mode is configured as " + + EXECUTOR_MANAGEMENT_MODE_ISOLATION); return; } /** @@ -630,7 +697,11 @@ public class ServiceConfig extends ServiceConfigBase { String[] methods = methods(interfaceClass); if (methods.length == 0) { - logger.warn(CONFIG_NO_METHOD_FOUND, "", "", "No method found in service interface: " + interfaceClass.getName()); + logger.warn( + CONFIG_NO_METHOD_FOUND, + "", + "", + "No method found in service interface: " + interfaceClass.getName()); map.put(METHODS_KEY, ANY_VALUE); } else { map.put(METHODS_KEY, StringUtils.join(new TreeSet<>(Arrays.asList(methods)), COMMA_SEPARATOR)); @@ -695,7 +766,8 @@ public class ServiceConfig extends ServiceConfigBase { } else if (hasIndex(argument)) { AbstractConfig.appendParameters(params, argument, method.getName() + "." + argument.getIndex()); } else { - throw new IllegalArgumentException("Argument config must set index or type attribute.eg: or "); + throw new IllegalArgumentException( + "Argument config must set index or type attribute.eg: or "); } } @@ -704,7 +776,10 @@ public class ServiceConfig extends ServiceConfigBase { } private boolean isTypeMatched(String type, Integer index, Class[] argtypes) { - return index != null && index >= 0 && index < argtypes.length && argtypes[index].getName().equals(type); + return index != null + && index >= 0 + && index < argtypes.length + && argtypes[index].getName().equals(type); } private Integer findArgumentIndexIndexWithGivenType(ArgumentConfig argument, Method method) { @@ -716,7 +791,9 @@ public class ServiceConfig extends ServiceConfigBase { if (isTypeMatched(type, index, argTypes)) { return index; } else { - throw new IllegalArgumentException("Argument config error : the index attribute and type attribute not match :index :" + argument.getIndex() + ", type:" + argument.getType()); + throw new IllegalArgumentException( + "Argument config error : the index attribute and type attribute not match :index :" + + argument.getIndex() + ", type:" + argument.getType()); } } else { // multiple callbacks in the method @@ -725,7 +802,8 @@ public class ServiceConfig extends ServiceConfigBase { return j; } } - throw new IllegalArgumentException("Argument config error : no argument matched with the type:" + argument.getType()); + throw new IllegalArgumentException( + "Argument config error : no argument matched with the type:" + argument.getType()); } } @@ -746,14 +824,23 @@ public class ServiceConfig extends ServiceConfigBase { params.put(CommonConstants.IPV6_KEY, ipv6Host); } - Integer port = findConfiguredPort(protocolConfig, provider, this.getExtensionLoader(Protocol.class), name, params); - URL url = new ServiceConfigURL(name, null, null, host, port, getContextPath(protocolConfig).map(p -> p + "/" + path).orElse(path), params); + Integer port = + findConfiguredPort(protocolConfig, provider, this.getExtensionLoader(Protocol.class), name, params); + URL url = new ServiceConfigURL( + name, + null, + null, + host, + port, + getContextPath(protocolConfig).map(p -> p + "/" + path).orElse(path), + params); // You can customize Configurator to append extra parameters - if (this.getExtensionLoader(ConfiguratorFactory.class) - .hasExtension(url.getProtocol())) { + if (this.getExtensionLoader(ConfiguratorFactory.class).hasExtension(url.getProtocol())) { url = this.getExtensionLoader(ConfiguratorFactory.class) - .getExtension(url.getProtocol()).getConfigurator(url).configure(url); + .getExtension(url.getProtocol()) + .getConfigurator(url) + .configure(url); } url = url.setScopeModel(getScopeModel()); url = url.setServiceModel(providerModel); @@ -778,9 +865,9 @@ public class ServiceConfig extends ServiceConfigBase { if (StringUtils.isNotBlank(extProtocol)) { // export original url - url = URLBuilder.from(url). - addParameter(IS_PU_SERVER_KEY, Boolean.TRUE.toString()). - build(); + url = URLBuilder.from(url) + .addParameter(IS_PU_SERVER_KEY, Boolean.TRUE.toString()) + .build(); } url = exportRemote(url, registryURLs, registerType); @@ -795,14 +882,15 @@ public class ServiceConfig extends ServiceConfigBase { // export extra protocols for (String protocol : protocols) { if (StringUtils.isNotBlank(protocol)) { - URL localUrl = URLBuilder.from(url). - setProtocol(protocol). - addParameter(IS_EXTRA, Boolean.TRUE.toString()). - removeParameter(EXT_PROTOCOL). - build(); + URL localUrl = URLBuilder.from(url) + .setProtocol(protocol) + .addParameter(IS_EXTRA, Boolean.TRUE.toString()) + .removeParameter(EXT_PROTOCOL) + .build(); localUrl = exportRemote(localUrl, registryURLs, registerType); if (!isGeneric(generic) && !getScopeModel().isInternal()) { - MetadataUtils.publishServiceDefinition(localUrl, providerModel.getServiceModel(), getApplicationModel()); + MetadataUtils.publishServiceDefinition( + localUrl, providerModel.getServiceModel(), getApplicationModel()); } this.urls.add(localUrl); } @@ -819,7 +907,7 @@ public class ServiceConfig extends ServiceConfigBase { url = url.addParameterIfAbsent(SERVICE_NAME_MAPPING_KEY, "true"); } - //if protocol is only injvm ,not register + // if protocol is only injvm ,not register if (LOCAL_PROTOCOL.equalsIgnoreCase(url.getProtocol())) { continue; } @@ -838,7 +926,8 @@ public class ServiceConfig extends ServiceConfigBase { if (logger.isInfoEnabled()) { if (url.getParameter(REGISTER_KEY, true)) { - logger.info("Register dubbo service " + interfaceClass.getName() + " url " + url + " to registry " + registryURL.getAddress()); + logger.info("Register dubbo service " + interfaceClass.getName() + " url " + url + + " to registry " + registryURL.getAddress()); } else { logger.info("Export dubbo service " + interfaceClass.getName() + " to url " + url); } @@ -856,7 +945,6 @@ public class ServiceConfig extends ServiceConfigBase { doExportUrl(url, true, registerType); } - return url; } @@ -865,9 +953,9 @@ public class ServiceConfig extends ServiceConfigBase { if (!url.getParameter(REGISTER_KEY, true)) { registerType = RegisterTypeEnum.MANUAL_REGISTER; } - if (registerType == RegisterTypeEnum.NEVER_REGISTER || - registerType == RegisterTypeEnum.MANUAL_REGISTER || - registerType == RegisterTypeEnum.AUTO_REGISTER_BY_DEPLOYER) { + if (registerType == RegisterTypeEnum.NEVER_REGISTER + || registerType == RegisterTypeEnum.MANUAL_REGISTER + || registerType == RegisterTypeEnum.AUTO_REGISTER_BY_DEPLOYER) { url = url.addParameter(REGISTER_KEY, false); } @@ -876,21 +964,21 @@ public class ServiceConfig extends ServiceConfigBase { invoker = new DelegateProviderMetaDataInvoker(invoker, this); } Exporter exporter = protocolSPI.export(invoker); - exporters.computeIfAbsent(registerType, k -> new CopyOnWriteArrayList<>()).add(exporter); + exporters + .computeIfAbsent(registerType, k -> new CopyOnWriteArrayList<>()) + .add(exporter); } - /** * always export injvm */ private void exportLocal(URL url) { URL local = URLBuilder.from(url) - .setProtocol(LOCAL_PROTOCOL) - .setHost(LOCALHOST_VALUE) - .setPort(0) - .build(); - local = local.setScopeModel(getScopeModel()) - .setServiceModel(providerModel); + .setProtocol(LOCAL_PROTOCOL) + .setHost(LOCALHOST_VALUE) + .setPort(0) + .build(); + local = local.setScopeModel(getScopeModel()).setServiceModel(providerModel); local = local.addParameter(EXPORTER_LISTENER_KEY, LOCAL_PROTOCOL); doExportUrl(local, false, RegisterTypeEnum.AUTO_REGISTER); logger.info("Export dubbo service " + interfaceClass.getName() + " to local registry url : " + local); @@ -903,14 +991,15 @@ public class ServiceConfig extends ServiceConfigBase { */ private boolean isOnlyInJvm() { return getProtocols().size() == 1 - && LOCAL_PROTOCOL.equalsIgnoreCase(getProtocols().get(0).getName()); + && LOCAL_PROTOCOL.equalsIgnoreCase(getProtocols().get(0).getName()); } private void postProcessConfig() { List configPostProcessors = this.getExtensionLoader(ConfigPostProcessor.class) - .getActivateExtension(URL.valueOf("configPostProcessor://", getScopeModel()), (String[]) null); - List commonConfigPostProcessors = this.getExtensionLoader(CommonConfigPostProcessor.class) - .getActivateExtension(URL.valueOf("configPostProcessor://"), (String[]) null); + .getActivateExtension(URL.valueOf("configPostProcessor://", getScopeModel()), (String[]) null); + List commonConfigPostProcessors = this.getExtensionLoader( + CommonConfigPostProcessor.class) + .getActivateExtension(URL.valueOf("configPostProcessor://"), (String[]) null); HashSet allConfigPostProcessor = new HashSet<>(); @@ -946,14 +1035,14 @@ public class ServiceConfig extends ServiceConfigBase { * @param map * @return */ - private static String findConfiguredHosts(ProtocolConfig protocolConfig, - ProviderConfig provider, - Map map) { + private static String findConfiguredHosts( + ProtocolConfig protocolConfig, ProviderConfig provider, Map map) { boolean anyhost = false; String hostToBind = getValueFromConfig(protocolConfig, DUBBO_IP_TO_BIND); if (StringUtils.isNotEmpty(hostToBind) && isInvalidLocalHost(hostToBind)) { - throw new IllegalArgumentException("Specified invalid bind ip from property:" + DUBBO_IP_TO_BIND + ", value:" + hostToBind); + throw new IllegalArgumentException( + "Specified invalid bind ip from property:" + DUBBO_IP_TO_BIND + ", value:" + hostToBind); } // if bind ip is not found in environment, keep looking up @@ -976,7 +1065,8 @@ public class ServiceConfig extends ServiceConfigBase { // bind ip is not used for registry ip by default String hostToRegistry = getValueFromConfig(protocolConfig, DUBBO_IP_TO_REGISTRY); if (StringUtils.isNotEmpty(hostToRegistry) && isInvalidLocalHost(hostToRegistry)) { - throw new IllegalArgumentException("Specified invalid registry ip from property:" + DUBBO_IP_TO_REGISTRY + ", value:" + hostToRegistry); + throw new IllegalArgumentException("Specified invalid registry ip from property:" + DUBBO_IP_TO_REGISTRY + + ", value:" + hostToRegistry); } else if (StringUtils.isEmpty(hostToRegistry)) { // bind ip is used as registry ip by default hostToRegistry = hostToBind; @@ -987,7 +1077,6 @@ public class ServiceConfig extends ServiceConfigBase { return hostToRegistry; } - /** * Register port and bind port for the provider, can be configured separately * Configuration priority: environment variable -> java system properties -> port property in protocol config file @@ -997,10 +1086,12 @@ public class ServiceConfig extends ServiceConfigBase { * @param name * @return */ - private static synchronized Integer findConfiguredPort(ProtocolConfig protocolConfig, - ProviderConfig provider, - ExtensionLoader extensionLoader, - String name, Map map) { + private static synchronized Integer findConfiguredPort( + ProtocolConfig protocolConfig, + ProviderConfig provider, + ExtensionLoader extensionLoader, + String name, + Map map) { Integer portToBind; // parse bind port from environment @@ -1073,7 +1164,8 @@ public class ServiceConfig extends ServiceConfigBase { protocol = protocol.toLowerCase(); if (!RANDOM_PORT_MAP.containsKey(protocol)) { RANDOM_PORT_MAP.put(protocol, port); - logger.warn(CONFIG_USE_RANDOM_PORT, "", "", "Use random available port(" + port + ") for protocol " + protocol); + logger.warn( + CONFIG_USE_RANDOM_PORT, "", "", "Use random available port(" + port + ") for protocol " + protocol); } } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/BootstrapTakeoverMode.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/BootstrapTakeoverMode.java index f2f3319108..a207606e83 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/BootstrapTakeoverMode.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/BootstrapTakeoverMode.java @@ -26,5 +26,8 @@ import org.apache.dubbo.config.ServiceConfig; * SERVLET: will be controlled by java servlet container */ public enum BootstrapTakeoverMode { - SPRING, MANUAL, AUTO, SERVLET + SPRING, + MANUAL, + AUTO, + SERVLET } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/DubboBootstrap.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/DubboBootstrap.java index bfb2278fb6..abb9327eac 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/DubboBootstrap.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/DubboBootstrap.java @@ -118,7 +118,8 @@ public final class DubboBootstrap { } public static DubboBootstrap getInstance(ApplicationModel applicationModel) { - return ConcurrentHashMapUtils.computeIfAbsent(instanceMap, applicationModel, _k -> new DubboBootstrap(applicationModel)); + return ConcurrentHashMapUtils.computeIfAbsent( + instanceMap, applicationModel, _k -> new DubboBootstrap(applicationModel)); } public static DubboBootstrap newInstance() { @@ -188,12 +189,14 @@ public final class DubboBootstrap { } private void notifyStarted(ApplicationModel applicationModel) { - ExtensionLoader exts = applicationModel.getExtensionLoader(DubboBootstrapStartStopListener.class); + ExtensionLoader exts = + applicationModel.getExtensionLoader(DubboBootstrapStartStopListener.class); exts.getSupportedExtensionInstances().forEach(ext -> ext.onStart(DubboBootstrap.this)); } private void notifyStopped(ApplicationModel applicationModel) { - ExtensionLoader exts = applicationModel.getExtensionLoader(DubboBootstrapStartStopListener.class); + ExtensionLoader exts = + applicationModel.getExtensionLoader(DubboBootstrapStartStopListener.class); exts.getSupportedExtensionInstances().forEach(ext -> ext.onStop(DubboBootstrap.this)); executeMutually(() -> { awaited.set(true); @@ -351,7 +354,7 @@ public final class DubboBootstrap { } public void setTakeoverMode(BootstrapTakeoverMode takeoverMode) { - //TODO this.started.set(false); + // TODO this.started.set(false); this.takeoverMode = takeoverMode; } @@ -367,7 +370,6 @@ public final class DubboBootstrap { return configManager; } - // MetadataReportConfig correlative methods public DubboBootstrap metadataReport(Consumer consumerBuilder) { @@ -433,7 +435,6 @@ public final class DubboBootstrap { return this; } - // {@link RegistryConfig} correlative methods /** @@ -485,7 +486,6 @@ public final class DubboBootstrap { return this; } - // {@link ProtocolConfig} correlative methods public DubboBootstrap protocol(Consumer consumerBuilder) { return protocol(null, consumerBuilder); @@ -704,7 +704,7 @@ public final class DubboBootstrap { return this; } - public DubboBootstrap tracing(TracingConfig tracing){ + public DubboBootstrap tracing(TracingConfig tracing) { tracing.setScopeModel(applicationModel); configManager.setTracing(tracing); return this; @@ -770,7 +770,6 @@ public final class DubboBootstrap { return this; } - public class Module { private ModuleModel moduleModel; private DubboBootstrap bootstrap; @@ -889,5 +888,4 @@ public final class DubboBootstrap { return this; } } - } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/DubboBootstrapStartStopListener.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/DubboBootstrapStartStopListener.java index 0befe7dad7..5d326c9469 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/DubboBootstrapStartStopListener.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/DubboBootstrapStartStopListener.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config.bootstrap; import org.apache.dubbo.common.extension.SPI; diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/AbstractBuilder.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/AbstractBuilder.java index 300bdc4cf4..d2a8dd0e57 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/AbstractBuilder.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/AbstractBuilder.java @@ -50,7 +50,8 @@ public abstract class AbstractBuilder appendParameters(Map parameters, Map appendParameters) { + protected static Map appendParameters( + Map parameters, Map appendParameters) { if (parameters == null) { parameters = new HashMap<>(); } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/AbstractInterfaceBuilder.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/AbstractInterfaceBuilder.java index 7010096fec..1d43765bfd 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/AbstractInterfaceBuilder.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/AbstractInterfaceBuilder.java @@ -34,7 +34,8 @@ import java.util.List; * * @since 2.7 */ -public abstract class AbstractInterfaceBuilder> +public abstract class AbstractInterfaceBuilder< + T extends AbstractInterfaceConfig, B extends AbstractInterfaceBuilder> extends AbstractMethodBuilder { /** * Local impl class name for the service interface @@ -112,6 +113,7 @@ public abstract class AbstractInterfaceBuilder> +public abstract class AbstractReferenceBuilder< + T extends AbstractReferenceConfig, B extends AbstractReferenceBuilder> extends AbstractInterfaceBuilder { /** diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/AbstractServiceBuilder.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/AbstractServiceBuilder.java index f1f4e4fd66..219cf1c081 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/AbstractServiceBuilder.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/AbstractServiceBuilder.java @@ -30,7 +30,7 @@ import java.util.concurrent.Executor; * @since 2.7 */ public abstract class AbstractServiceBuilder> - extends AbstractInterfaceBuilder { + extends AbstractInterfaceBuilder { /** * The service version @@ -88,6 +88,7 @@ public abstract class AbstractServiceBuilder protocols; + protected String protocolIds; // max allowed execute times diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/InternalServiceConfigBuilder.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/InternalServiceConfigBuilder.java index c6a1557137..9320382d44 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/InternalServiceConfigBuilder.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/InternalServiceConfigBuilder.java @@ -51,15 +51,16 @@ import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY; public class InternalServiceConfigBuilder { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); - private static final Set ACCEPTABLE_PROTOCOL = Stream.of("dubbo", "tri", "injvm").collect(Collectors.toSet()); + private static final Set ACCEPTABLE_PROTOCOL = + Stream.of("dubbo", "tri", "injvm").collect(Collectors.toSet()); private final ApplicationModel applicationModel; - private String protocol; + private String protocol; private Integer port; private String registryId; private Class interfaceClass; private Executor executor; - private T ref; + private T ref; private InternalServiceConfigBuilder(ApplicationModel applicationModel) { this.applicationModel = applicationModel; @@ -69,8 +70,6 @@ public class InternalServiceConfigBuilder { return new InternalServiceConfigBuilder<>(applicationModel); } - - public InternalServiceConfigBuilder interfaceClass(Class interfaceClass) { this.interfaceClass = interfaceClass; return getThis(); @@ -104,7 +103,6 @@ public class InternalServiceConfigBuilder { return getThis(); } - /** * Get other configured protocol from environment in priority order. If get nothing, use default dubbo. * @@ -114,41 +112,45 @@ public class InternalServiceConfigBuilder { String protocol = ""; // if (StringUtils.isEmpty(protocol)) { - Collection protocols = applicationModel.getApplicationConfigManager().getProtocols(); + Collection protocols = + applicationModel.getApplicationConfigManager().getProtocols(); if (CollectionUtils.isNotEmpty(protocols)) { protocol = protocols.stream() - .map(ProtocolConfig::getName) - .filter(StringUtils::isNotEmpty) - .filter(p -> ACCEPTABLE_PROTOCOL.contains(p)) - .findFirst() - .orElse(""); + .map(ProtocolConfig::getName) + .filter(StringUtils::isNotEmpty) + .filter(p -> ACCEPTABLE_PROTOCOL.contains(p)) + .findFirst() + .orElse(""); } } // List moduleModels = applicationModel.getPubModuleModels(); if (StringUtils.isEmpty(protocol)) { Stream providerConfigStream = moduleModels.stream() - .map(ModuleModel::getConfigManager) - .map(ModuleConfigManager::getProviders) - .filter(CollectionUtils::isNotEmpty) - .flatMap(Collection::stream); + .map(ModuleModel::getConfigManager) + .map(ModuleConfigManager::getProviders) + .filter(CollectionUtils::isNotEmpty) + .flatMap(Collection::stream); protocol = providerConfigStream - .filter((providerConfig) -> providerConfig.getProtocol() != null || CollectionUtils.isNotEmpty(providerConfig.getProtocols())) - .map(providerConfig -> { - if (providerConfig.getProtocol() != null && StringUtils.isNotEmpty(providerConfig.getProtocol().getName())) { - return providerConfig.getProtocol().getName(); - } else { - return providerConfig.getProtocols().stream() - .map(ProtocolConfig::getName) - .filter(StringUtils::isNotEmpty) - .findFirst() - .orElse(""); - } - }) - .filter(StringUtils::isNotEmpty) - .filter(p -> ACCEPTABLE_PROTOCOL.contains(p)) - .findFirst() - .orElse(""); + .filter((providerConfig) -> providerConfig.getProtocol() != null + || CollectionUtils.isNotEmpty(providerConfig.getProtocols())) + .map(providerConfig -> { + if (providerConfig.getProtocol() != null + && StringUtils.isNotEmpty( + providerConfig.getProtocol().getName())) { + return providerConfig.getProtocol().getName(); + } else { + return providerConfig.getProtocols().stream() + .map(ProtocolConfig::getName) + .filter(StringUtils::isNotEmpty) + .findFirst() + .orElse(""); + } + }) + .filter(StringUtils::isNotEmpty) + .filter(p -> ACCEPTABLE_PROTOCOL.contains(p)) + .findFirst() + .orElse(""); } // if (StringUtils.isEmpty(protocol)) { @@ -162,15 +164,15 @@ public class InternalServiceConfigBuilder { } // protocol = moduleModels.stream() - .map(ModuleModel::getConfigManager) - .map(ModuleConfigManager::getConsumers) - .filter(CollectionUtils::isNotEmpty) - .flatMap(Collection::stream) - .map(ConsumerConfig::getProtocol) - .filter(StringUtils::isNotEmpty) - .filter(p -> ACCEPTABLE_PROTOCOL.contains(p)) - .findFirst() - .orElse(""); + .map(ModuleModel::getConfigManager) + .map(ModuleConfigManager::getConsumers) + .filter(CollectionUtils::isNotEmpty) + .flatMap(Collection::stream) + .map(ConsumerConfig::getProtocol) + .filter(StringUtils::isNotEmpty) + .filter(p -> ACCEPTABLE_PROTOCOL.contains(p)) + .findFirst() + .orElse(""); return StringUtils.isNotEmpty(protocol) && ACCEPTABLE_PROTOCOL.contains(protocol) ? protocol : DUBBO_PROTOCOL; } @@ -180,13 +182,12 @@ public class InternalServiceConfigBuilder { } public InternalServiceConfigBuilder port(Integer specPort) { - return port(specPort,null); + return port(specPort, null); } - public InternalServiceConfigBuilder port(Integer specPort, String key) { - Assert.notEmptyString(this.protocol,"export protocol is null"); - Assert.notNull(this.interfaceClass,"export interfaceClass is null"); + Assert.notEmptyString(this.protocol, "export protocol is null"); + Assert.notNull(this.interfaceClass, "export interfaceClass is null"); if (specPort != null) { this.port = specPort; @@ -203,10 +204,12 @@ public class InternalServiceConfigBuilder { if (specPort == null || specPort < -1) { try { if (logger.isInfoEnabled()) { - logger.info(interfaceClass.getName()+"Service Port hasn't been set will use default protocol defined in protocols."); + logger.info(interfaceClass.getName() + + "Service Port hasn't been set will use default protocol defined in protocols."); } - Protocol protocol = applicationModel.getExtensionLoader(Protocol.class).getExtension(this.protocol); + Protocol protocol = + applicationModel.getExtensionLoader(Protocol.class).getExtension(this.protocol); if (protocol != null && protocol.getServers() != null) { Iterator it = protocol.getServers().iterator(); // export service may export before normal service export, it.hasNext() will return false. @@ -230,8 +233,12 @@ public class InternalServiceConfigBuilder { } } } catch (Exception e) { - logger.error(INTERNAL_ERROR, "invalid specified " + port + " port, error "+e.getMessage(), - "", "Failed to find any valid protocol, will use random port to export service.",e); + logger.error( + INTERNAL_ERROR, + "invalid specified " + port + " port, error " + e.getMessage(), + "", + "Failed to find any valid protocol, will use random port to export service.", + e); } } if (this.port == null) { @@ -241,24 +248,30 @@ public class InternalServiceConfigBuilder { } private ProtocolConfig getProtocolConfig() { - return applicationModel.getApplicationConfigManager().getProtocol(protocol).orElse(null); + return applicationModel + .getApplicationConfigManager() + .getProtocol(protocol) + .orElse(null); } - public ServiceConfig build(Consumer> configConsumer){ + public ServiceConfig build(Consumer> configConsumer) { ProtocolConfig protocolConfig = new ProtocolConfig(); protocolConfig.setName(this.protocol); protocolConfig.setPort(this.port); this.nullAssert(); - logger.info("Using " + this.protocol + " protocol to export "+interfaceClass.getName()+" service on port " + protocolConfig.getPort()); + logger.info("Using " + this.protocol + " protocol to export " + interfaceClass.getName() + " service on port " + + protocolConfig.getPort()); - applicationModel.getApplicationConfigManager().getProtocol(this.protocol) - .ifPresent(p -> { - protocolConfig.mergeProtocol(p); - // clear extra protocols possibly merged from global ProtocolConfig - protocolConfig.setExtProtocol(null); - }); + applicationModel + .getApplicationConfigManager() + .getProtocol(this.protocol) + .ifPresent(p -> { + protocolConfig.mergeProtocol(p); + // clear extra protocols possibly merged from global ProtocolConfig + protocolConfig.setExtProtocol(null); + }); ApplicationConfig applicationConfig = getApplicationConfig(); @@ -293,15 +306,16 @@ public class InternalServiceConfigBuilder { return serviceConfig; } - public ServiceConfig build(){ + public ServiceConfig build() { return build(null); } + private void nullAssert() { Assert.notNull(port, "export service port is null"); Assert.notNull(protocol, "export service protocol is null"); Assert.notNull(interfaceClass, "export service interfaceClass is null"); - Assert.notNull(ref,"export service ref is null"); - Assert.notNull(registryId,"export service registryId is null"); + Assert.notNull(ref, "export service ref is null"); + Assert.notNull(registryId, "export service registryId is null"); } protected InternalServiceConfigBuilder getThis() { @@ -311,5 +325,4 @@ public class InternalServiceConfigBuilder { private ApplicationConfig getApplicationConfig() { return applicationModel.getApplicationConfigManager().getApplicationOrElseThrow(); } - } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/MethodBuilder.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/MethodBuilder.java index 7b5724dfcf..cef437808a 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/MethodBuilder.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/MethodBuilder.java @@ -107,6 +107,7 @@ public class MethodBuilder extends AbstractMethodBuilder extends AbstractServiceBuilder, return getThis(); } -// @Override -// public ServiceBuilder mock(String mock) { -// throw new IllegalArgumentException("mock doesn't support on provider side"); -// } + // @Override + // public ServiceBuilder mock(String mock) { + // throw new IllegalArgumentException("mock doesn't support on provider side"); + // } -// @Override -// public ServiceBuilder mock(Boolean mock) { -// throw new IllegalArgumentException("mock doesn't support on provider side"); -// } + // @Override + // public ServiceBuilder mock(Boolean mock) { + // throw new IllegalArgumentException("mock doesn't support on provider side"); + // } public ServiceConfig build() { ServiceConfig serviceConfig = new ServiceConfig<>(); diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java index 4d81c1497b..925034a878 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java @@ -114,7 +114,8 @@ import static org.apache.dubbo.remoting.Constants.CLIENT_KEY; */ public class DefaultApplicationDeployer extends AbstractDeployer implements ApplicationDeployer { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DefaultApplicationDeployer.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(DefaultApplicationDeployer.class); private final ApplicationModel applicationModel; @@ -148,12 +149,14 @@ public class DefaultApplicationDeployer extends AbstractDeployer deployListeners = applicationModel.getExtensionLoader(ApplicationDeployListener.class) + Set deployListeners = applicationModel + .getExtensionLoader(ApplicationDeployListener.class) .getSupportedExtensionInstances(); for (ApplicationDeployListener listener : deployListeners) { this.addDeployListener(listener); @@ -223,7 +226,6 @@ public class DefaultApplicationDeployer extends AbstractDeployer metadataReportConfigs = configManager.getMetadataConfigs(); if (CollectionUtils.isEmpty(metadataReportConfigs)) { if (REMOTE_METADATA_STORAGE_TYPE.equals(metadataType)) { - throw new IllegalStateException("No MetadataConfig found, Metadata Center address is required when 'metadata=remote' is enabled."); + throw new IllegalStateException( + "No MetadataConfig found, Metadata Center address is required when 'metadata=remote' is enabled."); } return; } - MetadataReportInstance metadataReportInstance = applicationModel.getBeanFactory().getBean(MetadataReportInstance.class); + MetadataReportInstance metadataReportInstance = + applicationModel.getBeanFactory().getBean(MetadataReportInstance.class); List validMetadataReportConfigs = new ArrayList<>(metadataReportConfigs.size()); for (MetadataReportConfig metadataReportConfig : metadataReportConfigs) { if (ConfigValidationUtils.isValidMetadataConfig(metadataReportConfig)) { @@ -332,7 +336,8 @@ public class DefaultApplicationDeployer extends AbstractDeployer defaultRegistries = configManager.getDefaultRegistries(); if (defaultRegistries.size() > 0) { - defaultRegistries - .stream() + defaultRegistries.stream() .filter(this::isUsedRegistryAsConfigCenter) .map(this::registryAsConfigCenter) .forEach(configCenter -> { @@ -366,13 +370,13 @@ public class DefaultApplicationDeployer extends AbstractDeployer configOptional = configManager.getMetrics(); - //If no specific metrics type is configured and there is no Prometheus dependency in the dependencies. + // If no specific metrics type is configured and there is no Prometheus dependency in the dependencies. MetricsConfig metricsConfig = configOptional.orElse(new MetricsConfig(applicationModel)); if (StringUtils.isBlank(metricsConfig.getProtocol())) { - metricsConfig.setProtocol(MetricsSupportUtil.isSupportPrometheus() ? PROTOCOL_PROMETHEUS : PROTOCOL_DEFAULT); + metricsConfig.setProtocol( + MetricsSupportUtil.isSupportPrometheus() ? PROTOCOL_PROMETHEUS : PROTOCOL_DEFAULT); } collector.setCollectEnabled(true); collector.collectApplication(); - collector.setThreadpoolCollectEnabled(Optional.ofNullable(metricsConfig.getEnableThreadpool()).orElse(true)); - collector.setMetricsInitEnabled(Optional.ofNullable(metricsConfig.getEnableMetricsInit()).orElse(true)); - MetricsReporterFactory metricsReporterFactory = getExtensionLoader(MetricsReporterFactory.class).getAdaptiveExtension(); + collector.setThreadpoolCollectEnabled( + Optional.ofNullable(metricsConfig.getEnableThreadpool()).orElse(true)); + collector.setMetricsInitEnabled( + Optional.ofNullable(metricsConfig.getEnableMetricsInit()).orElse(true)); + MetricsReporterFactory metricsReporterFactory = + getExtensionLoader(MetricsReporterFactory.class).getAdaptiveExtension(); MetricsReporter metricsReporter = null; try { metricsReporter = metricsReporterFactory.createMetricsReporter(metricsConfig.toUrl()); @@ -406,10 +413,12 @@ public class DefaultApplicationDeployer extends AbstractDeployer 1.10.0"); + logger.debug( + "Not found micrometer-observation or plz check the version of micrometer-observation version if already introduced, need > 1.10.0"); } return; } @@ -436,14 +446,14 @@ public class DefaultApplicationDeployer extends AbstractDeployer metadataConfigsToOverride = originMetadataConfigs - .stream() + Collection metadataConfigsToOverride = originMetadataConfigs.stream() .filter(m -> Objects.isNull(m.getAddress())) .collect(Collectors.toList()); @@ -493,12 +502,12 @@ public class DefaultApplicationDeployer extends AbstractDeployer defaultRegistries = configManager.getDefaultRegistries(); if (!defaultRegistries.isEmpty()) { - defaultRegistries - .stream() + defaultRegistries.stream() .filter(this::isUsedRegistryAsMetadataCenter) .map(registryConfig -> registryAsMetadataCenter(registryConfig, metadataConfigToOverride)) .forEach(metadataReportConfig -> { @@ -507,12 +516,14 @@ public class DefaultApplicationDeployer extends AbstractDeployer metadataReportConfigs = configManager.getMetadataConfigs(); if (CollectionUtils.isNotEmpty(metadataReportConfigs)) { for (MetadataReportConfig existedConfig : metadataReportConfigs) { - if (existedConfig.getId() == null && existedConfig.getAddress().equals(metadataReportConfig.getAddress())) { + if (existedConfig.getId() == null + && existedConfig.getAddress().equals(metadataReportConfig.getAddress())) { return; } } @@ -520,7 +531,8 @@ public class DefaultApplicationDeployer extends AbstractDeployer configOptional = configManager.getConfig(MetadataReportConfig.class, metadataReportConfig.getId()); + Optional configOptional = + configManager.getConfig(MetadataReportConfig.class, metadataReportConfig.getId()); if (configOptional.isPresent()) { return; } @@ -531,8 +543,8 @@ public class DefaultApplicationDeployer extends AbstractDeployer usedRegistryAsCenter, - String centerType, - Class extensionClass) { + private boolean isUsedRegistryAsCenter( + RegistryConfig registryConfig, + Supplier usedRegistryAsCenter, + String centerType, + Class extensionClass) { final boolean supported; Boolean configuredValue = usedRegistryAsCenter.get(); if (configuredValue != null) { // If configured, take its value. supported = configuredValue.booleanValue(); - } else { // Or check the extension existence + } else { // Or check the extension existence String protocol = registryConfig.getProtocol(); supported = supportsExtension(extensionClass, protocol); if (logger.isInfoEnabled()) { - logger.info(format("No value is configured in the registry, the %s extension[name : %s] %s as the %s center" - , extensionClass.getSimpleName(), protocol, supported ? "supports" : "does not support", centerType)); + logger.info(format( + "No value is configured in the registry, the %s extension[name : %s] %s as the %s center", + extensionClass.getSimpleName(), + protocol, + supported ? "supports" : "does not support", + centerType)); } } if (logger.isInfoEnabled()) { - logger.info(format("The registry[%s] will be %s as the %s center", registryConfig, - supported ? "used" : "not used", centerType)); + logger.info(format( + "The registry[%s] will be %s as the %s center", + registryConfig, supported ? "used" : "not used", centerType)); } return supported; } @@ -585,9 +604,11 @@ public class DefaultApplicationDeployer extends AbstractDeployer()); } if (CollectionUtils.isNotEmptyMap(registryConfig.getParameters())) { - for (Map.Entry entry : registryConfig.getParameters().entrySet()) { - metadataReportConfig.getParameters().putIfAbsent(entry.getKey(), entry.getValue()); // copy the parameters + for (Map.Entry entry : + registryConfig.getParameters().entrySet()) { + metadataReportConfig + .getParameters() + .putIfAbsent(entry.getKey(), entry.getValue()); // copy the parameters } } metadataReportConfig.getParameters().put(CLIENT_KEY, registryConfig.getClient()); @@ -708,30 +732,30 @@ public class DefaultApplicationDeployer extends AbstractDeployer { -// try { -// while (isStarting()) { -// // notify when any module state changed -// synchronized (stateLock) { -// try { -// stateLock.wait(500); -// } catch (InterruptedException e) { -// // ignore -// } -// } -// -// // if has new module, do start again -// if (hasPendingModule()) { -// startModules(); -// } -// } -// } catch (Throwable e) { -// onFailed(getIdentifier() + " check start occurred an exception", e); -// } -// }); + // executorRepository.getSharedExecutor().submit(() -> { + // try { + // while (isStarting()) { + // // notify when any module state changed + // synchronized (stateLock) { + // try { + // stateLock.wait(500); + // } catch (InterruptedException e) { + // // ignore + // } + // } + // + // // if has new module, do start again + // if (hasPendingModule()) { + // startModules(); + // } + // } + // } catch (Throwable e) { + // onFailed(getIdentifier() + " check start occurred an exception", e); + // } + // }); } private void startModules() { @@ -778,7 +802,8 @@ public class DefaultApplicationDeployer extends AbstractDeployer { + asyncMetadataFuture = frameworkExecutorRepository + .getSharedScheduledExecutor() + .scheduleWithFixedDelay( + () -> { - // ignore refresh metadata on stopping - if (applicationModel.isDestroyed()) { - return; - } + // ignore refresh metadata on stopping + if (applicationModel.isDestroyed()) { + return; + } - // refresh for 30 times (default for 30s) when deployer is not started, prevent submit too many revision - if (instanceRefreshScheduleTimes.incrementAndGet() % 30 != 0 && !isStarted()) { - return; - } + // refresh for 30 times (default for 30s) when deployer is not started, prevent submit + // too many revision + if (instanceRefreshScheduleTimes.incrementAndGet() % 30 != 0 && !isStarted()) { + return; + } - // refresh for 5 times (default for 5s) when services are being updated by other threads, prevent submit too many revision - // note: should not always wait here - if (serviceRefreshState.get() != 0 && instanceRefreshScheduleTimes.get() % 5 != 0) { - return; - } + // refresh for 5 times (default for 5s) when services are being updated by other + // threads, prevent submit too many revision + // note: should not always wait here + if (serviceRefreshState.get() != 0 && instanceRefreshScheduleTimes.get() % 5 != 0) { + return; + } - try { - if (!applicationModel.isDestroyed() && registered) { - ServiceInstanceMetadataUtils.refreshMetadataAndInstance(applicationModel); - } - } catch (Exception e) { - if (!applicationModel.isDestroyed()) { - logger.error(CONFIG_REFRESH_INSTANCE_ERROR, "", "", "Refresh instance and metadata error.", e); - } - } - }, 0, ConfigurationUtils.get(applicationModel, METADATA_PUBLISH_DELAY_KEY, DEFAULT_METADATA_PUBLISH_DELAY), TimeUnit.MILLISECONDS); + try { + if (!applicationModel.isDestroyed() && registered) { + ServiceInstanceMetadataUtils.refreshMetadataAndInstance(applicationModel); + } + } catch (Exception e) { + if (!applicationModel.isDestroyed()) { + logger.error( + CONFIG_REFRESH_INSTANCE_ERROR, + "", + "", + "Refresh instance and metadata error.", + e); + } + } + }, + 0, + ConfigurationUtils.get( + applicationModel, METADATA_PUBLISH_DELAY_KEY, DEFAULT_METADATA_PUBLISH_DELAY), + TimeUnit.MILLISECONDS); } } @@ -1011,7 +1090,6 @@ public class DefaultApplicationDeployer extends AbstractDeployer metadataReportFactories = getExtensionLoader(MetadataReportFactory.class).getLoadedExtensionInstances(); + List metadataReportFactories = + getExtensionLoader(MetadataReportFactory.class).getLoadedExtensionInstances(); for (MetadataReportFactory metadataReportFactory : metadataReportFactories) { metadataReportFactory.destroy(); } @@ -1334,5 +1430,4 @@ public class DefaultApplicationDeployer extends AbstractDeployer getApplication() { return configManager.getApplication(); } - } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultMetricsServiceExporter.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultMetricsServiceExporter.java index c770e5350a..a350110244 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultMetricsServiceExporter.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultMetricsServiceExporter.java @@ -41,8 +41,8 @@ public class DefaultMetricsServiceExporter implements MetricsServiceExporter, Sc private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); - private ApplicationModel applicationModel; - private MetricsService metricsService; + private ApplicationModel applicationModel; + private MetricsService metricsService; private volatile ServiceConfig serviceConfig; @Override @@ -51,15 +51,22 @@ public class DefaultMetricsServiceExporter implements MetricsServiceExporter, Sc } private void initialize() { - MetricsConfig metricsConfig = applicationModel.getApplicationConfigManager().getMetrics().orElse(null); + MetricsConfig metricsConfig = + applicationModel.getApplicationConfigManager().getMetrics().orElse(null); // TODO compatible with old usage of metrics, remove protocol check after new metrics is ready for use. - if (metricsConfig != null && metricsService == null) { + if (metricsConfig != null && metricsService == null) { String protocol = Optional.ofNullable(metricsConfig.getProtocol()).orElse(PROTOCOL_PROMETHEUS); - if (PROTOCOL_PROMETHEUS.equals(protocol) ) { - this.metricsService = applicationModel.getExtensionLoader(MetricsService.class).getDefaultExtension(); + if (PROTOCOL_PROMETHEUS.equals(protocol)) { + this.metricsService = applicationModel + .getExtensionLoader(MetricsService.class) + .getDefaultExtension(); } else { - logger.warn(COMMON_METRICS_COLLECTOR_EXCEPTION, "", "", "Protocol " + protocol + " not support for new metrics mechanism. " + - "Using old metrics mechanism instead."); + logger.warn( + COMMON_METRICS_COLLECTOR_EXCEPTION, + "", + "", + "Protocol " + protocol + " not support for new metrics mechanism. " + + "Using old metrics mechanism instead."); } } } @@ -73,16 +80,20 @@ public class DefaultMetricsServiceExporter implements MetricsServiceExporter, Sc public MetricsServiceExporter export() { if (metricsService != null) { if (!isExported()) { - ExecutorService internalServiceExecutor = applicationModel.getFrameworkModel().getBeanFactory() - .getBean(FrameworkExecutorRepository.class).getInternalServiceExecutor(); - ServiceConfig serviceConfig = InternalServiceConfigBuilder.newBuilder(applicationModel) - .interfaceClass(MetricsService.class) - .protocol(getMetricsConfig().getExportServiceProtocol()) - .port(getMetricsConfig().getExportServicePort()) - .executor(internalServiceExecutor) - .ref(metricsService) - .registryId("internal-metrics-registry") - .build(); + ExecutorService internalServiceExecutor = applicationModel + .getFrameworkModel() + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class) + .getInternalServiceExecutor(); + ServiceConfig serviceConfig = InternalServiceConfigBuilder.newBuilder( + applicationModel) + .interfaceClass(MetricsService.class) + .protocol(getMetricsConfig().getExportServiceProtocol()) + .port(getMetricsConfig().getExportServicePort()) + .executor(internalServiceExecutor) + .ref(metricsService) + .registryId("internal-metrics-registry") + .build(); // export serviceConfig.export(); @@ -93,7 +104,11 @@ public class DefaultMetricsServiceExporter implements MetricsServiceExporter, Sc this.serviceConfig = serviceConfig; } else { if (logger.isWarnEnabled()) { - logger.warn(LoggerCodeConstants.INTERNAL_ERROR, "", "", "The MetricsService has been exported : " + serviceConfig.getExportedUrls()); + logger.warn( + LoggerCodeConstants.INTERNAL_ERROR, + "", + "", + "The MetricsService has been exported : " + serviceConfig.getExportedUrls()); } } } else { @@ -114,7 +129,8 @@ public class DefaultMetricsServiceExporter implements MetricsServiceExporter, Sc } private MetricsConfig getMetricsConfig() { - Optional metricsConfig = applicationModel.getApplicationConfigManager().getMetrics(); + Optional metricsConfig = + applicationModel.getApplicationConfigManager().getMetrics(); if (metricsConfig.isPresent()) { return metricsConfig.get(); } else { @@ -125,5 +141,4 @@ public class DefaultMetricsServiceExporter implements MetricsServiceExporter, Sc private boolean isExported() { return serviceConfig != null && serviceConfig.isExported() && !serviceConfig.isUnexported(); } - } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultModuleDeployer.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultModuleDeployer.java index 281415d7d5..0722ff2c7e 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultModuleDeployer.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultModuleDeployer.java @@ -65,7 +65,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNABL */ public class DefaultModuleDeployer extends AbstractDeployer implements ModuleDeployer { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DefaultModuleDeployer.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(DefaultModuleDeployer.class); private final List> asyncExportingFutures = new ArrayList<>(); @@ -93,18 +94,22 @@ public class DefaultModuleDeployer extends AbstractDeployer impleme private CompletableFuture exportFuture; private CompletableFuture referFuture; - public DefaultModuleDeployer(ModuleModel moduleModel) { super(moduleModel); this.moduleModel = moduleModel; configManager = moduleModel.getConfigManager(); - frameworkExecutorRepository = moduleModel.getApplicationModel().getFrameworkModel().getBeanFactory().getBean(FrameworkExecutorRepository.class); + frameworkExecutorRepository = moduleModel + .getApplicationModel() + .getFrameworkModel() + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class); executorRepository = ExecutorRepository.getInstance(moduleModel.getApplicationModel()); referenceCache = SimpleReferenceCache.newCache(); applicationDeployer = DefaultApplicationDeployer.get(moduleModel); - //load spi listener - Set listeners = moduleModel.getExtensionLoader(ModuleDeployListener.class).getSupportedExtensionInstances(); + // load spi listener + Set listeners = + moduleModel.getExtensionLoader(ModuleDeployListener.class).getSupportedExtensionInstances(); for (ModuleDeployListener listener : listeners) { this.addDeployListener(listener); } @@ -125,7 +130,10 @@ public class DefaultModuleDeployer extends AbstractDeployer impleme loadConfigs(); // read ModuleConfig - ModuleConfig moduleConfig = moduleModel.getConfigManager().getModule().orElseThrow(() -> new IllegalStateException("Default module config is not initialized")); + ModuleConfig moduleConfig = moduleModel + .getConfigManager() + .getModule() + .orElseThrow(() -> new IllegalStateException("Default module config is not initialized")); exportAsync = Boolean.TRUE.equals(moduleConfig.getExportAsync()); referAsync = Boolean.TRUE.equals(moduleConfig.getReferAsync()); @@ -163,7 +171,6 @@ public class DefaultModuleDeployer extends AbstractDeployer impleme onModuleStarting(); - initialize(); // export services @@ -208,7 +215,12 @@ public class DefaultModuleDeployer extends AbstractDeployer impleme // check reference config checkReferences(); } catch (Throwable e) { - logger.warn(CONFIG_FAILED_WAIT_EXPORT_REFER, "", "", "wait for export/refer services occurred an exception", e); + logger.warn( + CONFIG_FAILED_WAIT_EXPORT_REFER, + "", + "", + "wait for export/refer services occurred an exception", + e); onModuleFailed(getIdentifier() + " start failed: " + e, e); } finally { // complete module start future after application state changed @@ -262,13 +274,17 @@ public class DefaultModuleDeployer extends AbstractDeployer impleme } } } catch (Throwable t) { - logger.error(LoggerCodeConstants.INTERNAL_ERROR, "", "", "Exceptions occurred when unregister services.", t); + logger.error( + LoggerCodeConstants.INTERNAL_ERROR, "", "", "Exceptions occurred when unregister services.", t); } } private void doOffline(ProviderModel.RegisterStatedURL statedURL) { - RegistryFactory registryFactory = - statedURL.getRegistryUrl().getOrDefaultApplicationModel().getExtensionLoader(RegistryFactory.class).getAdaptiveExtension(); + RegistryFactory registryFactory = statedURL + .getRegistryUrl() + .getOrDefaultApplicationModel() + .getExtensionLoader(RegistryFactory.class) + .getAdaptiveExtension(); Registry registry = registryFactory.getRegistry(statedURL.getRegistryUrl()); registry.unregister(statedURL.getProviderUrl()); statedURL.setRegistered(false); @@ -292,7 +308,12 @@ public class DefaultModuleDeployer extends AbstractDeployer impleme consumerModel.getDestroyRunner().run(); } } catch (Throwable t) { - logger.error(CONFIG_UNABLE_DESTROY_MODEL, "there are problems with the custom implementation.", "", "Unable to destroy model: consumerModel.", t); + logger.error( + CONFIG_UNABLE_DESTROY_MODEL, + "there are problems with the custom implementation.", + "", + "Unable to destroy model: consumerModel.", + t); } } @@ -303,7 +324,12 @@ public class DefaultModuleDeployer extends AbstractDeployer impleme providerModel.getDestroyRunner().run(); } } catch (Throwable t) { - logger.error(CONFIG_UNABLE_DESTROY_MODEL, "there are problems with the custom implementation.", "", "Unable to destroy model: providerModel.", t); + logger.error( + CONFIG_UNABLE_DESTROY_MODEL, + "there are problems with the custom implementation.", + "", + "Unable to destroy model: providerModel.", + t); } } serviceRepository.destroy(); @@ -316,7 +342,12 @@ public class DefaultModuleDeployer extends AbstractDeployer impleme try { listener.onInitialize(moduleModel); } catch (Throwable e) { - logger.error(CONFIG_FAILED_START_MODEL, "", "", getIdentifier() + " an exception occurred when handle initialize event", e); + logger.error( + CONFIG_FAILED_START_MODEL, + "", + "", + getIdentifier() + " an exception occurred when handle initialize event", + e); } } } @@ -329,11 +360,11 @@ public class DefaultModuleDeployer extends AbstractDeployer impleme } private void onModuleStarted() { - if (isStarting()) { - setStarted(); - logger.info(getIdentifier() + " has started."); - applicationDeployer.notifyModuleChanged(moduleModel, DeployState.STARTED); - } + if (isStarting()) { + setStarted(); + logger.info(getIdentifier() + " has started."); + applicationDeployer.notifyModuleChanged(moduleModel, DeployState.STARTED); + } } private void onModuleFailed(String msg, Throwable ex) { @@ -424,16 +455,24 @@ public class DefaultModuleDeployer extends AbstractDeployer impleme } if (exportAsync || sc.shouldExportAsync()) { ExecutorService executor = executorRepository.getServiceExportExecutor(); - CompletableFuture future = CompletableFuture.runAsync(() -> { - try { - if (!sc.isExported()) { - sc.export(); - exportedServices.add(sc); - } - } catch (Throwable t) { - logger.error(CONFIG_FAILED_EXPORT_SERVICE, "", "", "Failed to async export service config: " + getIdentifier() + " , catch error : " + t.getMessage(), t); - } - }, executor); + CompletableFuture future = CompletableFuture.runAsync( + () -> { + try { + if (!sc.isExported()) { + sc.export(); + exportedServices.add(sc); + } + } catch (Throwable t) { + logger.error( + CONFIG_FAILED_EXPORT_SERVICE, + "", + "", + "Failed to async export service config: " + getIdentifier() + " , catch error : " + + t.getMessage(), + t); + } + }, + executor); asyncExportingFutures.add(future); } else { @@ -489,13 +528,21 @@ public class DefaultModuleDeployer extends AbstractDeployer impleme if (rc.shouldInit()) { if (referAsync || rc.shouldReferAsync()) { ExecutorService executor = executorRepository.getServiceReferExecutor(); - CompletableFuture future = CompletableFuture.runAsync(() -> { - try { - referenceCache.get(rc, false); - } catch (Throwable t) { - logger.error(CONFIG_FAILED_EXPORT_SERVICE, "", "", "Failed to async export service config: " + getIdentifier() + " , catch error : " + t.getMessage(), t); - } - }, executor); + CompletableFuture future = CompletableFuture.runAsync( + () -> { + try { + referenceCache.get(rc, false); + } catch (Throwable t) { + logger.error( + CONFIG_FAILED_EXPORT_SERVICE, + "", + "", + "Failed to async export service config: " + getIdentifier() + + " , catch error : " + t.getMessage(), + t); + } + }, + executor); asyncReferringFutures.add(future); } else { @@ -503,7 +550,12 @@ public class DefaultModuleDeployer extends AbstractDeployer impleme } } } catch (Throwable t) { - logger.error(CONFIG_FAILED_REFERENCE_MODEL, "", "", "Model reference failed: " + getIdentifier() + " , catch error : " + t.getMessage(), t); + logger.error( + CONFIG_FAILED_REFERENCE_MODEL, + "", + "", + "Model reference failed: " + getIdentifier() + " , catch error : " + t.getMessage(), + t); referenceCache.destroy(rc); throw t; } @@ -532,7 +584,11 @@ public class DefaultModuleDeployer extends AbstractDeployer impleme exportFuture = CompletableFuture.allOf(asyncExportingFutures.toArray(new CompletableFuture[0])); exportFuture.get(); } catch (Throwable e) { - logger.warn(CONFIG_FAILED_EXPORT_SERVICE, "", "", getIdentifier() + " export services occurred an exception: " + e.toString()); + logger.warn( + CONFIG_FAILED_EXPORT_SERVICE, + "", + "", + getIdentifier() + " export services occurred an exception: " + e.toString()); } finally { logger.info(getIdentifier() + " export services finished."); asyncExportingFutures.clear(); @@ -545,7 +601,11 @@ public class DefaultModuleDeployer extends AbstractDeployer impleme referFuture = CompletableFuture.allOf(asyncReferringFutures.toArray(new CompletableFuture[0])); referFuture.get(); } catch (Throwable e) { - logger.warn(CONFIG_FAILED_REFER_SERVICE, "", "", getIdentifier() + " refer services occurred an exception: " + e.toString()); + logger.warn( + CONFIG_FAILED_REFER_SERVICE, + "", + "", + getIdentifier() + " refer services occurred an exception: " + e.toString()); } finally { logger.info(getIdentifier() + " refer services finished."); asyncReferringFutures.clear(); @@ -558,17 +618,15 @@ public class DefaultModuleDeployer extends AbstractDeployer impleme } private boolean isExportBackground() { - return moduleModel.getConfigManager().getProviders() - .stream() - .map(ProviderConfig::getExportBackground) - .anyMatch(k -> k != null && k); + return moduleModel.getConfigManager().getProviders().stream() + .map(ProviderConfig::getExportBackground) + .anyMatch(k -> k != null && k); } private boolean isReferBackground() { - return moduleModel.getConfigManager().getConsumers() - .stream() - .map(ConsumerConfig::getReferBackground) - .anyMatch(k -> k != null && k); + return moduleModel.getConfigManager().getConsumers().stream() + .map(ConsumerConfig::getReferBackground) + .anyMatch(k -> k != null && k); } @Override diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/FrameworkModelCleaner.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/FrameworkModelCleaner.java index 258181d2f2..2405e6fda0 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/FrameworkModelCleaner.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/FrameworkModelCleaner.java @@ -32,7 +32,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNDEF */ public class FrameworkModelCleaner implements ScopeModelDestroyListener { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FrameworkModelCleaner.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(FrameworkModelCleaner.class); private final AtomicBoolean protocolDestroyed = new AtomicBoolean(false); @@ -72,5 +73,4 @@ public class FrameworkModelCleaner implements ScopeModelDestroyListener serviceConfig; private final ApplicationModel applicationModel; - public ConfigurableMetadataServiceExporter(ApplicationModel applicationModel, MetadataServiceDelegation metadataService) { + public ConfigurableMetadataServiceExporter( + ApplicationModel applicationModel, MetadataServiceDelegation metadataService) { this.applicationModel = applicationModel; this.metadataService = metadataService; } public synchronized ConfigurableMetadataServiceExporter export() { if (serviceConfig == null || !isExported()) { - ExecutorService internalServiceExecutor = applicationModel.getFrameworkModel().getBeanFactory() - .getBean(FrameworkExecutorRepository.class).getInternalServiceExecutor(); + ExecutorService internalServiceExecutor = applicationModel + .getFrameworkModel() + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class) + .getInternalServiceExecutor(); this.serviceConfig = InternalServiceConfigBuilder.newBuilder(applicationModel) - .interfaceClass(MetadataService.class) - .protocol(getApplicationConfig().getMetadataServiceProtocol(), METADATA_SERVICE_PROTOCOL_KEY) - .port(getApplicationConfig().getMetadataServicePort(), METADATA_SERVICE_PORT_KEY) - .registryId("internal-metadata-registry") - .executor(internalServiceExecutor) - .ref(metadataService) - .build(configConsumer -> configConsumer.setMethods(generateMethodConfig())); + .interfaceClass(MetadataService.class) + .protocol(getApplicationConfig().getMetadataServiceProtocol(), METADATA_SERVICE_PROTOCOL_KEY) + .port(getApplicationConfig().getMetadataServicePort(), METADATA_SERVICE_PORT_KEY) + .registryId("internal-metadata-registry") + .executor(internalServiceExecutor) + .ref(metadataService) + .build(configConsumer -> configConsumer.setMethods(generateMethodConfig())); // export serviceConfig.export(); @@ -77,7 +81,11 @@ public class ConfigurableMetadataServiceExporter { } } else { if (logger.isWarnEnabled()) { - logger.warn(CONFIG_METADATA_SERVICE_EXPORTED, "", "", "The MetadataService has been exported : " + serviceConfig.getExportedUrls()); + logger.warn( + CONFIG_METADATA_SERVICE_EXPORTED, + "", + "", + "The MetadataService has been exported : " + serviceConfig.getExportedUrls()); } } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ExporterDeployListener.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ExporterDeployListener.java index f3e34bb4c9..b5819892bd 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ExporterDeployListener.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ExporterDeployListener.java @@ -31,27 +31,22 @@ public class ExporterDeployListener implements ApplicationDeployListener, Priori protected volatile ConfigurableMetadataServiceExporter metadataServiceExporter; @Override - public void onInitialize(ApplicationModel scopeModel) { - - } + public void onInitialize(ApplicationModel scopeModel) {} @Override - public void onStarting(ApplicationModel scopeModel) { - - } + public void onStarting(ApplicationModel scopeModel) {} @Override - public synchronized void onStarted(ApplicationModel applicationModel) { - - } + public synchronized void onStarted(ApplicationModel applicationModel) {} @Override - public synchronized void onStopping(ApplicationModel scopeModel) { - - } + public synchronized void onStopping(ApplicationModel scopeModel) {} private String getMetadataType(ApplicationModel applicationModel) { - String type = applicationModel.getApplicationConfigManager().getApplicationOrElseThrow().getMetadataType(); + String type = applicationModel + .getApplicationConfigManager() + .getApplicationOrElseThrow() + .getMetadataType(); if (StringUtils.isEmpty(type)) { type = DEFAULT_METADATA_STORAGE_TYPE; } @@ -59,7 +54,10 @@ public class ExporterDeployListener implements ApplicationDeployListener, Priori } private String getRegisterMode(ApplicationModel applicationModel) { - String type = applicationModel.getApplicationConfigManager().getApplicationOrElseThrow().getRegisterMode(); + String type = applicationModel + .getApplicationConfigManager() + .getApplicationOrElseThrow() + .getRegisterMode(); if (StringUtils.isEmpty(type)) { type = DEFAULT_REGISTER_MODE; } @@ -77,17 +75,18 @@ public class ExporterDeployListener implements ApplicationDeployListener, Priori @Override public synchronized void onModuleStarted(ApplicationModel applicationModel) { // start metadata service exporter - MetadataServiceDelegation metadataService = applicationModel.getBeanFactory().getOrRegisterBean(MetadataServiceDelegation.class); + MetadataServiceDelegation metadataService = + applicationModel.getBeanFactory().getOrRegisterBean(MetadataServiceDelegation.class); if (metadataServiceExporter == null) { metadataServiceExporter = new ConfigurableMetadataServiceExporter(applicationModel, metadataService); // fixme, let's disable local metadata service export at this moment - if (!REMOTE_METADATA_STORAGE_TYPE.equals(getMetadataType(applicationModel)) && !INTERFACE_REGISTER_MODE.equals(getRegisterMode(applicationModel))) { + if (!REMOTE_METADATA_STORAGE_TYPE.equals(getMetadataType(applicationModel)) + && !INTERFACE_REGISTER_MODE.equals(getRegisterMode(applicationModel))) { metadataServiceExporter.export(); } } } - @Override public synchronized void onStopped(ApplicationModel scopeModel) { if (metadataServiceExporter != null && metadataServiceExporter.isExported()) { @@ -100,9 +99,7 @@ public class ExporterDeployListener implements ApplicationDeployListener, Priori } @Override - public void onFailure(ApplicationModel scopeModel, Throwable cause) { - - } + public void onFailure(ApplicationModel scopeModel, Throwable cause) {} @Override public int getPriority() { diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/MetadataServiceURLParamsMetadataCustomizer.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/MetadataServiceURLParamsMetadataCustomizer.java index 6e1f677b3c..6bd1f7d5e4 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/MetadataServiceURLParamsMetadataCustomizer.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/MetadataServiceURLParamsMetadataCustomizer.java @@ -57,8 +57,10 @@ public class MetadataServiceURLParamsMetadataCustomizer implements ServiceInstan } private String resolveMetadataPropertyValue(ApplicationModel applicationModel) { - ModuleServiceRepository serviceRepository = applicationModel.getInternalModule().getServiceRepository(); - String key = BaseServiceMetadata.buildServiceKey(MetadataService.class.getName(), applicationModel.getApplicationName(), MetadataService.VERSION); + ModuleServiceRepository serviceRepository = + applicationModel.getInternalModule().getServiceRepository(); + String key = BaseServiceMetadata.buildServiceKey( + MetadataService.class.getName(), applicationModel.getApplicationName(), MetadataService.VERSION); ProviderModel providerModel = serviceRepository.lookupExportedService(key); String metadataValue = ""; if (providerModel != null) { diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/CompositeReferenceCache.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/CompositeReferenceCache.java index 5ae8f010a6..508ce9ad67 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/CompositeReferenceCache.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/CompositeReferenceCache.java @@ -34,7 +34,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_API_W */ public class CompositeReferenceCache implements ReferenceCache { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CompositeReferenceCache.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(CompositeReferenceCache.class); private final ApplicationModel applicationModel; @@ -46,15 +47,20 @@ public class CompositeReferenceCache implements ReferenceCache { public T get(ReferenceConfigBase referenceConfig, boolean check) { Class type = referenceConfig.getInterfaceClass(); - String key = BaseServiceMetadata.buildServiceKey(type.getName(), referenceConfig.getGroup(), referenceConfig.getVersion()); + String key = BaseServiceMetadata.buildServiceKey( + type.getName(), referenceConfig.getGroup(), referenceConfig.getVersion()); boolean singleton = referenceConfig.getSingleton() == null || referenceConfig.getSingleton(); T proxy = null; if (singleton) { proxy = get(key, (Class) type); } else { - logger.warn(CONFIG_API_WRONG_USE, "the api method is being used incorrectly", "", "Using non-singleton ReferenceConfig and ReferenceCache at the same time may cause memory leak. " + - "Call ReferenceConfig#get() directly for non-singleton ReferenceConfig instead of using ReferenceCache#get(ReferenceConfig)"); + logger.warn( + CONFIG_API_WRONG_USE, + "the api method is being used incorrectly", + "", + "Using non-singleton ReferenceConfig and ReferenceCache at the same time may cause memory leak. " + + "Call ReferenceConfig#get() directly for non-singleton ReferenceConfig instead of using ReferenceCache#get(ReferenceConfig)"); } if (proxy == null) { proxy = referenceConfig.get(check); diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/ConfigValidationUtils.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/ConfigValidationUtils.java index 3d8a84047d..6c12adc097 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/ConfigValidationUtils.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/ConfigValidationUtils.java @@ -108,9 +108,9 @@ import static org.apache.dubbo.common.constants.RegistryConstants.DUBBO_REGISTER import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_MODE_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; +import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL_TYPE; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL_TYPE; import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; import static org.apache.dubbo.common.utils.StringUtils.isEmpty; import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty; @@ -220,10 +220,10 @@ public class ConfigValidationUtils { for (URL url : urls) { url = URLBuilder.from(url) - .addParameter(REGISTRY_KEY, url.getProtocol()) - .setProtocol(extractRegistryType(url)) - .setScopeModel(interfaceConfig.getScopeModel()) - .build(); + .addParameter(REGISTRY_KEY, url.getProtocol()) + .setProtocol(extractRegistryType(url)) + .setScopeModel(interfaceConfig.getScopeModel()) + .build(); // provider delay register state will be checked in RegistryProtocol#export if (provider && url.getParameter(REGISTER_KEY, true)) { registryList.add(url); @@ -245,39 +245,49 @@ public class ConfigValidationUtils { // for registries enabled service discovery, automatically register interface compatible addresses. String registerMode; if (SERVICE_REGISTRY_PROTOCOL.equals(registryURL.getProtocol())) { - registerMode = registryURL.getParameter(REGISTER_MODE_KEY, ConfigurationUtils.getCachedDynamicProperty(scopeModel, DUBBO_REGISTER_MODE_DEFAULT_KEY, DEFAULT_REGISTER_MODE_INSTANCE)); + registerMode = registryURL.getParameter( + REGISTER_MODE_KEY, + ConfigurationUtils.getCachedDynamicProperty( + scopeModel, DUBBO_REGISTER_MODE_DEFAULT_KEY, DEFAULT_REGISTER_MODE_INSTANCE)); if (!isValidRegisterMode(registerMode)) { registerMode = DEFAULT_REGISTER_MODE_INSTANCE; } result.add(registryURL); if (DEFAULT_REGISTER_MODE_ALL.equalsIgnoreCase(registerMode) - && registryNotExists(registryURL, registryList, REGISTRY_PROTOCOL)) { + && registryNotExists(registryURL, registryList, REGISTRY_PROTOCOL)) { URL interfaceCompatibleRegistryURL = URLBuilder.from(registryURL) - .setProtocol(REGISTRY_PROTOCOL) - .removeParameter(REGISTRY_TYPE_KEY) - .build(); + .setProtocol(REGISTRY_PROTOCOL) + .removeParameter(REGISTRY_TYPE_KEY) + .build(); result.add(interfaceCompatibleRegistryURL); } } else { - registerMode = registryURL.getParameter(REGISTER_MODE_KEY, ConfigurationUtils.getCachedDynamicProperty(scopeModel, DUBBO_REGISTER_MODE_DEFAULT_KEY, DEFAULT_REGISTER_MODE_ALL)); + registerMode = registryURL.getParameter( + REGISTER_MODE_KEY, + ConfigurationUtils.getCachedDynamicProperty( + scopeModel, DUBBO_REGISTER_MODE_DEFAULT_KEY, DEFAULT_REGISTER_MODE_ALL)); if (!isValidRegisterMode(registerMode)) { registerMode = DEFAULT_REGISTER_MODE_INTERFACE; } - if ((DEFAULT_REGISTER_MODE_INSTANCE.equalsIgnoreCase(registerMode) || DEFAULT_REGISTER_MODE_ALL.equalsIgnoreCase(registerMode)) - && registryNotExists(registryURL, registryList, SERVICE_REGISTRY_PROTOCOL)) { + if ((DEFAULT_REGISTER_MODE_INSTANCE.equalsIgnoreCase(registerMode) + || DEFAULT_REGISTER_MODE_ALL.equalsIgnoreCase(registerMode)) + && registryNotExists(registryURL, registryList, SERVICE_REGISTRY_PROTOCOL)) { URL serviceDiscoveryRegistryURL = URLBuilder.from(registryURL) - .setProtocol(SERVICE_REGISTRY_PROTOCOL) - .removeParameter(REGISTRY_TYPE_KEY) - .build(); + .setProtocol(SERVICE_REGISTRY_PROTOCOL) + .removeParameter(REGISTRY_TYPE_KEY) + .build(); result.add(serviceDiscoveryRegistryURL); } - if (DEFAULT_REGISTER_MODE_INTERFACE.equalsIgnoreCase(registerMode) || DEFAULT_REGISTER_MODE_ALL.equalsIgnoreCase(registerMode)) { + if (DEFAULT_REGISTER_MODE_INTERFACE.equalsIgnoreCase(registerMode) + || DEFAULT_REGISTER_MODE_ALL.equalsIgnoreCase(registerMode)) { result.add(registryURL); } } - FrameworkStatusReportService reportService = ScopeModelUtil.getApplicationModel(scopeModel).getBeanFactory().getBean(FrameworkStatusReportService.class); + FrameworkStatusReportService reportService = ScopeModelUtil.getApplicationModel(scopeModel) + .getBeanFactory() + .getBean(FrameworkStatusReportService.class); reportService.reportRegistrationStatus(reportService.createRegistrationReport(registerMode)); } else { result.add(registryURL); @@ -289,29 +299,28 @@ public class ConfigValidationUtils { private static boolean isValidRegisterMode(String mode) { return isNotEmpty(mode) - && (DEFAULT_REGISTER_MODE_INTERFACE.equalsIgnoreCase(mode) - || DEFAULT_REGISTER_MODE_INSTANCE.equalsIgnoreCase(mode) - || DEFAULT_REGISTER_MODE_ALL.equalsIgnoreCase(mode) - ); + && (DEFAULT_REGISTER_MODE_INTERFACE.equalsIgnoreCase(mode) + || DEFAULT_REGISTER_MODE_INSTANCE.equalsIgnoreCase(mode) + || DEFAULT_REGISTER_MODE_ALL.equalsIgnoreCase(mode)); } private static boolean registryNotExists(URL registryURL, List registryList, String registryType) { - return registryList.stream().noneMatch( - url -> registryType.equals(url.getProtocol()) && registryURL.getBackupAddress().equals(url.getBackupAddress()) - ); + return registryList.stream() + .noneMatch(url -> registryType.equals(url.getProtocol()) + && registryURL.getBackupAddress().equals(url.getBackupAddress())); } public static URL loadMonitor(AbstractInterfaceConfig interfaceConfig, URL registryURL) { Map map = new HashMap(); map.put(INTERFACE_KEY, MonitorService.class.getName()); AbstractInterfaceConfig.appendRuntimeParameters(map); - //set ip + // set ip String hostToRegistry = ConfigUtils.getSystemProperty(DUBBO_IP_TO_REGISTRY); if (StringUtils.isEmpty(hostToRegistry)) { hostToRegistry = NetUtils.getLocalHost(); } else if (NetUtils.isInvalidLocalHost(hostToRegistry)) { - throw new IllegalArgumentException("Specified invalid registry ip from property:" + - DUBBO_IP_TO_REGISTRY + ", value:" + hostToRegistry); + throw new IllegalArgumentException("Specified invalid registry ip from property:" + DUBBO_IP_TO_REGISTRY + + ", value:" + hostToRegistry); } map.put(REGISTER_IP_KEY, hostToRegistry); @@ -327,17 +336,20 @@ public class ConfigValidationUtils { address = monitor.getAddress(); } String protocol = monitor == null ? null : monitor.getProtocol(); - if (monitor != null && - (REGISTRY_PROTOCOL.equals(protocol) || SERVICE_REGISTRY_PROTOCOL.equals(protocol)) - && registryURL != null) { + if (monitor != null + && (REGISTRY_PROTOCOL.equals(protocol) || SERVICE_REGISTRY_PROTOCOL.equals(protocol)) + && registryURL != null) { return URLBuilder.from(registryURL) - .setProtocol(DUBBO_PROTOCOL) - .addParameter(PROTOCOL_KEY, protocol) - .putAttribute(REFER_KEY, map) - .build(); + .setProtocol(DUBBO_PROTOCOL) + .addParameter(PROTOCOL_KEY, protocol) + .putAttribute(REFER_KEY, map) + .build(); } else if (ConfigUtils.isNotEmpty(address) || ConfigUtils.isNotEmpty(protocol)) { if (!map.containsKey(PROTOCOL_KEY)) { - if (interfaceConfig.getScopeModel().getExtensionLoader(MonitorFactory.class).hasExtension(LOGSTAT_PROTOCOL)) { + if (interfaceConfig + .getScopeModel() + .getExtensionLoader(MonitorFactory.class) + .hasExtension(LOGSTAT_PROTOCOL)) { map.put(PROTOCOL_KEY, LOGSTAT_PROTOCOL); } else if (ConfigUtils.isNotEmpty(protocol)) { map.put(PROTOCOL_KEY, protocol); @@ -353,7 +365,6 @@ public class ConfigValidationUtils { return null; } - public static void validateAbstractInterfaceConfig(AbstractInterfaceConfig config) { checkName(LOCAL_KEY, config.getLocal()); checkName("stub", config.getStub()); @@ -361,7 +372,11 @@ public class ConfigValidationUtils { checkExtension(config.getScopeModel(), ProxyFactory.class, PROXY_KEY, config.getProxy()); checkExtension(config.getScopeModel(), Cluster.class, CLUSTER_KEY, config.getCluster()); - checkMultiExtension(config.getScopeModel(), Arrays.asList(Filter.class, ClusterFilter.class), FILTER_KEY, config.getFilter()); + checkMultiExtension( + config.getScopeModel(), + Arrays.asList(Filter.class, ClusterFilter.class), + FILTER_KEY, + config.getFilter()); checkNameHasSymbol(LAYER_KEY, config.getLayer()); List methods = config.getMethods(); @@ -433,8 +448,8 @@ public class ConfigValidationUtils { } if (!config.isValid()) { - throw new IllegalStateException("No application config found or it's not a valid config! " + - "Please add to your spring config."); + throw new IllegalStateException("No application config found or it's not a valid config! " + + "Please add to your spring config."); } // backward compatibility @@ -464,7 +479,8 @@ public class ConfigValidationUtils { try { ClassUtils.forName("org.apache.dubbo.qos.protocol.QosProtocolWrapper"); } catch (ClassNotFoundException e) { - logger.info("QosProtocolWrapper not found, qos will not be enabled, please check if 'dubbo-qos' dependency was imported correctly."); + logger.info( + "QosProtocolWrapper not found, qos will not be enabled, please check if 'dubbo-qos' dependency was imported correctly."); } } } @@ -482,8 +498,8 @@ public class ConfigValidationUtils { return false; } - if (Boolean.FALSE.equals(metadataReportConfig.getReportMetadata()) && - Boolean.FALSE.equals(metadataReportConfig.getReportDefinition())) { + if (Boolean.FALSE.equals(metadataReportConfig.getReportMetadata()) + && Boolean.FALSE.equals(metadataReportConfig.getReportDefinition())) { return false; } @@ -499,7 +515,8 @@ public class ConfigValidationUtils { String protocol = metadataReportConfig.getProtocol(); if ((isEmpty(address) || !address.contains("://")) && isEmpty(protocol)) { - throw new IllegalArgumentException("Please specify valid protocol or address for metadata report " + address); + throw new IllegalArgumentException( + "Please specify valid protocol or address for metadata report " + address); } } @@ -524,8 +541,8 @@ public class ConfigValidationUtils { public static void validateMonitorConfig(MonitorConfig config) { if (config != null) { if (!config.isValid()) { - logger.info("There's no valid monitor config found, if you want to open monitor statistics for Dubbo, " + - "please make sure your monitor is configured properly."); + logger.info("There's no valid monitor config found, if you want to open monitor statistics for Dubbo, " + + "please make sure your monitor is configured properly."); } checkParameterName(config.getParameters()); @@ -539,10 +556,10 @@ public class ConfigValidationUtils { checkHost(HOST_KEY, config.getHost()); checkPathName("contextpath", config.getContextpath()); - if (DUBBO_PROTOCOL.equals(name)) { checkMultiExtension(config.getScopeModel(), Codec2.class, CODEC_KEY, config.getCodec()); - checkMultiExtension(config.getScopeModel(), Serialization.class, SERIALIZATION_KEY, config.getSerialization()); + checkMultiExtension( + config.getScopeModel(), Serialization.class, SERIALIZATION_KEY, config.getSerialization()); checkMultiExtension(config.getScopeModel(), Transporter.class, SERVER_KEY, config.getServer()); checkMultiExtension(config.getScopeModel(), Transporter.class, CLIENT_KEY, config.getClient()); } @@ -601,7 +618,9 @@ public class ConfigValidationUtils { } private static String extractRegistryType(URL url) { - return UrlUtils.hasServiceDiscoveryRegistryTypeKey(url) ? SERVICE_REGISTRY_PROTOCOL : getRegistryProtocolType(url); + return UrlUtils.hasServiceDiscoveryRegistryTypeKey(url) + ? SERVICE_REGISTRY_PROTOCOL + : getRegistryProtocolType(url); } private static String getRegistryProtocolType(URL url) { @@ -611,8 +630,7 @@ public class ConfigValidationUtils { public static void checkExtension(ScopeModel scopeModel, Class type, String property, String value) { checkName(property, value); - if (isNotEmpty(value) - && !scopeModel.getExtensionLoader(type).hasExtension(value)) { + if (isNotEmpty(value) && !scopeModel.getExtensionLoader(type).hasExtension(value)) { throw new IllegalStateException("No such extension " + value + " for " + property + "/" + type.getName()); } } @@ -648,8 +666,8 @@ public class ConfigValidationUtils { } } if (!match) { - throw new IllegalStateException("No such extension " + v + " for " + property + "/" + - types.stream().map(Class::getName).collect(Collectors.joining(","))); + throw new IllegalStateException("No such extension " + v + " for " + property + "/" + + types.stream().map(Class::getName).collect(Collectors.joining(","))); } } } @@ -725,17 +743,24 @@ public class ConfigValidationUtils { return; } if (value.length() > maxlength) { - logger.error(CONFIG_PARAMETER_FORMAT_ERROR, "the value content is too long", "", "Parameter value format error. Invalid " + - property + "=\"" + value + "\" is longer than " + maxlength); + logger.error( + CONFIG_PARAMETER_FORMAT_ERROR, + "the value content is too long", + "", + "Parameter value format error. Invalid " + property + "=\"" + value + "\" is longer than " + + maxlength); } if (pattern != null) { Matcher matcher = pattern.matcher(value); if (!matcher.matches()) { - logger.error(CONFIG_PARAMETER_FORMAT_ERROR, "the value content is illegal character", "", "Parameter value format error. Invalid " + - property + "=\"" + value + "\" contains illegal " + - "character, only digit, letter, '-', '_' or '.' is legal."); + logger.error( + CONFIG_PARAMETER_FORMAT_ERROR, + "the value content is illegal character", + "", + "Parameter value format error. Invalid " + property + + "=\"" + value + "\" contains illegal " + + "character, only digit, letter, '-', '_' or '.' is legal."); } } } - } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/DefaultConfigValidator.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/DefaultConfigValidator.java index 396f6afc49..6bf010c3fc 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/DefaultConfigValidator.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/DefaultConfigValidator.java @@ -58,5 +58,4 @@ public class DefaultConfigValidator implements ConfigValidator { ConfigValidationUtils.validateSslConfig((SslConfig) config); } } - } diff --git a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/SimpleReferenceCache.java b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/SimpleReferenceCache.java index 7e798004fc..7b1b26b7f1 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/SimpleReferenceCache.java +++ b/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/SimpleReferenceCache.java @@ -45,7 +45,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_API_W * You can implement and use your own {@link ReferenceConfigBase} cache if you need use complicate strategy. */ public class SimpleReferenceCache implements ReferenceCache { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SimpleReferenceCache.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(SimpleReferenceCache.class); public static final String DEFAULT_NAME = "_DEFAULT_"; /** * Create the key with the Group, Interface and version attribute of {@link ReferenceConfigBase}. @@ -105,7 +106,8 @@ public class SimpleReferenceCache implements ReferenceCache { * Create cache if not existed yet. */ public static SimpleReferenceCache getCache(String name, KeyGenerator keyGenerator) { - return ConcurrentHashMapUtils.computeIfAbsent(CACHE_HOLDER, name, k -> new SimpleReferenceCache(k, keyGenerator)); + return ConcurrentHashMapUtils.computeIfAbsent( + CACHE_HOLDER, name, k -> new SimpleReferenceCache(k, keyGenerator)); } @Override @@ -120,14 +122,20 @@ public class SimpleReferenceCache implements ReferenceCache { if (singleton) { proxy = get(key, (Class) type); } else { - logger.warn(CONFIG_API_WRONG_USE, "", "", "Using non-singleton ReferenceConfig and ReferenceCache at the same time may cause memory leak. " + - "Call ReferenceConfig#get() directly for non-singleton ReferenceConfig instead of using ReferenceCache#get(ReferenceConfig)"); + logger.warn( + CONFIG_API_WRONG_USE, + "", + "", + "Using non-singleton ReferenceConfig and ReferenceCache at the same time may cause memory leak. " + + "Call ReferenceConfig#get() directly for non-singleton ReferenceConfig instead of using ReferenceCache#get(ReferenceConfig)"); } if (proxy == null) { - List> referencesOfType = ConcurrentHashMapUtils.computeIfAbsent(referenceTypeMap, type, _t -> Collections.synchronizedList(new ArrayList<>())); + List> referencesOfType = ConcurrentHashMapUtils.computeIfAbsent( + referenceTypeMap, type, _t -> Collections.synchronizedList(new ArrayList<>())); referencesOfType.add(rc); - List> referenceConfigList = ConcurrentHashMapUtils.computeIfAbsent(referenceKeyMap, key, _k -> Collections.synchronizedList(new ArrayList<>())); + List> referenceConfigList = ConcurrentHashMapUtils.computeIfAbsent( + referenceKeyMap, key, _k -> Collections.synchronizedList(new ArrayList<>())); referenceConfigList.add(rc); proxy = rc.get(check); } @@ -216,7 +224,6 @@ public class SimpleReferenceCache implements ReferenceCache { for (ReferenceConfigBase rc : referencesOfKey) { rc.checkOrDestroy(timeout); } - } @Override @@ -240,7 +247,6 @@ public class SimpleReferenceCache implements ReferenceCache { referencesOfType.remove(rc); destroyReference(rc); } - } @Override diff --git a/dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderServiceImpl.java b/dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderServiceImpl.java index b315aa2e4e..b546238ef3 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderServiceImpl.java +++ b/dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderServiceImpl.java @@ -22,7 +22,9 @@ public class MultiClassLoaderServiceImpl implements MultiClassLoaderService { private AtomicReference innerRequestReference; private AtomicReference innerResultReference; - public MultiClassLoaderServiceImpl(AtomicReference innerRequestReference, AtomicReference innerResultReference) { + public MultiClassLoaderServiceImpl( + AtomicReference innerRequestReference, + AtomicReference innerResultReference) { this.innerRequestReference = innerRequestReference; this.innerResultReference = innerResultReference; } diff --git a/dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderServiceRequest.java b/dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderServiceRequest.java index 9dd67ca5a5..0d07661d13 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderServiceRequest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderServiceRequest.java @@ -18,5 +18,4 @@ package demo; import java.io.Serializable; -public class MultiClassLoaderServiceRequest implements Serializable { -} +public class MultiClassLoaderServiceRequest implements Serializable {} diff --git a/dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderServiceResult.java b/dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderServiceResult.java index c4ed2aa702..f4d2b96a45 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderServiceResult.java +++ b/dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderServiceResult.java @@ -18,5 +18,4 @@ package demo; import java.io.Serializable; -public class MultiClassLoaderServiceResult implements Serializable { -} +public class MultiClassLoaderServiceResult implements Serializable {} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractConfigTest.java index 359ca39222..edaa1955b4 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractConfigTest.java @@ -27,12 +27,6 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ScopeModel; -import org.hamcrest.Matchers; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -44,6 +38,12 @@ import java.util.List; import java.util.Map; import java.util.Properties; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -111,7 +111,7 @@ class AbstractConfigTest { @Test void testAppendAttributes1() { - ParameterConfig config = new ParameterConfig(1, "hello/world", 30, "password","BEIJING"); + ParameterConfig config = new ParameterConfig(1, "hello/world", 30, "password", "BEIJING"); Map parameters = new HashMap<>(); AbstractConfig.appendParameters(parameters, config); @@ -126,39 +126,49 @@ class AbstractConfigTest { Assertions.assertEquals(String.valueOf(config.getNumber()), attributes.get("number")); Assertions.assertEquals(String.valueOf(config.getAge()), attributes.get("age")); Assertions.assertEquals(StringUtils.encodeParameters(config.getParameters()), attributes.get("parameters")); - Assertions.assertTrue(parameters.containsKey("detail.address"));// detailAddress -> detail.address - Assertions.assertTrue(attributes.containsKey("detail-address"));// detailAddress -> detail-address + Assertions.assertTrue(parameters.containsKey("detail.address")); // detailAddress -> detail.address + Assertions.assertTrue(attributes.containsKey("detail-address")); // detailAddress -> detail-address } @Test void checkExtension() { - Assertions.assertThrows(IllegalStateException.class, () -> ConfigValidationUtils.checkExtension(ApplicationModel.defaultModel(), Greeting.class, "hello", "world")); + Assertions.assertThrows( + IllegalStateException.class, + () -> ConfigValidationUtils.checkExtension( + ApplicationModel.defaultModel(), Greeting.class, "hello", "world")); } @Test void checkMultiExtension1() { - Assertions.assertThrows(IllegalStateException.class, - () -> ConfigValidationUtils.checkMultiExtension(ApplicationModel.defaultModel(), Greeting.class, "hello", "default,world")); + Assertions.assertThrows( + IllegalStateException.class, + () -> ConfigValidationUtils.checkMultiExtension( + ApplicationModel.defaultModel(), Greeting.class, "hello", "default,world")); } @Test void checkMultiExtension2() { try { - ConfigValidationUtils.checkMultiExtension(ApplicationModel.defaultModel(), Greeting.class, "hello", "default,-world"); + ConfigValidationUtils.checkMultiExtension( + ApplicationModel.defaultModel(), Greeting.class, "hello", "default,-world"); } catch (Throwable t) { Assertions.fail(t); } } + @Test void checkMultiExtension3() { - Assertions.assertThrows(IllegalStateException.class, - () -> ConfigValidationUtils.checkMultiExtension(ApplicationModel.defaultModel(), Greeting.class, "hello", "default , world")); + Assertions.assertThrows( + IllegalStateException.class, + () -> ConfigValidationUtils.checkMultiExtension( + ApplicationModel.defaultModel(), Greeting.class, "hello", "default , world")); } @Test void checkMultiExtension4() { try { - ConfigValidationUtils.checkMultiExtension(ApplicationModel.defaultModel(), Greeting.class, "hello", "default , -world "); + ConfigValidationUtils.checkMultiExtension( + ApplicationModel.defaultModel(), Greeting.class, "hello", "default , -world "); } catch (Throwable t) { Assertions.fail(t); } @@ -255,7 +265,10 @@ class AbstractConfigTest { } @Test - @Config(interfaceClass = Greeting.class, filter = {"f1, f2"}, listener = {"l1, l2"}, + @Config( + interfaceClass = Greeting.class, + filter = {"f1, f2"}, + listener = {"l1, l2"}, parameters = {"k1", "v1", "k2", "v2"}) public void appendAnnotation() throws Exception { Config config = getClass().getMethod("appendAnnotation").getAnnotation(Config.class); @@ -345,7 +358,10 @@ class AbstractConfigTest { Properties properties = new Properties(); properties.load(this.getClass().getResourceAsStream("/dubbo.properties")); - ApplicationModel.defaultModel().modelEnvironment().getPropertiesConfiguration().setProperties(properties); + ApplicationModel.defaultModel() + .modelEnvironment() + .getPropertiesConfiguration() + .setProperties(properties); overrideConfig.refresh(); @@ -353,7 +369,7 @@ class AbstractConfigTest { Assertions.assertEquals("override-config", overrideConfig.getProtocol()); Assertions.assertEquals("override-config://", overrideConfig.getEscape()); Assertions.assertEquals("properties", overrideConfig.getKey2()); - //Assertions.assertEquals("properties", overrideConfig.getUseKeyAsProperty()); + // Assertions.assertEquals("properties", overrideConfig.getUseKeyAsProperty()); } finally { ApplicationModel.defaultModel().modelEnvironment().destroy(); } @@ -435,7 +451,6 @@ class AbstractConfigTest { OverrideConfig overrideConfig = new OverrideConfig(); overrideConfig.setParameters(parameters); - Map external = new HashMap<>(); external.put("dubbo.override.parameters", "[{key3:value3},{key4:value4},{key2:value5}]"); ApplicationModel.defaultModel().modelEnvironment().initialize(); @@ -495,9 +510,9 @@ class AbstractConfigTest { overrideConfig.refresh(); Assertions.assertEquals(overrideConfig.getAddress(), "system://127.0.0.1:2181"); Assertions.assertEquals(overrideConfig.getProtocol(), "system"); - Assertions.assertEquals(overrideConfig.getParameters(), - StringUtils.parseParameters("[{key1:systemValue1},{key2:systemValue2},{key3:value3}]")); - + Assertions.assertEquals( + overrideConfig.getParameters(), + StringUtils.parseParameters("[{key1:systemValue1},{key2:systemValue2},{key3:value3}]")); } // test OVERRIDE_IF_ABSENT configMode { @@ -516,13 +531,15 @@ class AbstractConfigTest { parameters.put("key3", "value3"); overrideConfig.setParameters(parameters); - // overrideConfig's config is overridden/set by system config only when the overrideConfig's config is absent/empty + // overrideConfig's config is overridden/set by system config only when the overrideConfig's config is + // absent/empty overrideConfig.refresh(); Assertions.assertEquals(overrideConfig.getAddress(), "override-config://127.0.0.1:2181"); Assertions.assertEquals(overrideConfig.getProtocol(), "override-config"); Assertions.assertEquals(overrideConfig.getKey(), "systemKey"); - Assertions.assertEquals(overrideConfig.getParameters(), - StringUtils.parseParameters("[{key1:value1},{key2:systemValue2},{key3:value3}]")); + Assertions.assertEquals( + overrideConfig.getParameters(), + StringUtils.parseParameters("[{key1:value1},{key2:systemValue2},{key3:value3}]")); } } finally { @@ -548,7 +565,6 @@ class AbstractConfigTest { Assertions.assertEquals("value-from-external", overrideConfig.getNotConflictKey2()); } finally { ApplicationModel.defaultModel().modelEnvironment().destroy(); - } } @@ -570,7 +586,8 @@ class AbstractConfigTest { Assertions.assertNull(metaData.get("key2")); // with prefix - Map prefixMetadata = overrideConfig.getMetaData(OverrideConfig.getTypePrefix(OverrideConfig.class)); + Map prefixMetadata = + overrideConfig.getMetaData(OverrideConfig.getTypePrefix(OverrideConfig.class)); Assertions.assertEquals("override-config://127.0.0.1:2181", prefixMetadata.get("dubbo.override.address")); Assertions.assertEquals("override-config", prefixMetadata.get("dubbo.override.protocol")); Assertions.assertEquals("override-config://", prefixMetadata.get("dubbo.override.escape")); @@ -650,8 +667,7 @@ class AbstractConfigTest { public String notConflictKey2; protected Map parameters; - public OverrideConfig() { - } + public OverrideConfig() {} public OverrideConfig(ScopeModel scopeModel) { super(scopeModel); @@ -741,14 +757,13 @@ class AbstractConfigTest { private String secret; private String detailAddress; - ParameterConfig() { - } + ParameterConfig() {} ParameterConfig(int number, String name, int age, String secret) { this(number, name, age, secret, ""); } - ParameterConfig(int number, String name, int age, String secret,String detailAddress) { + ParameterConfig(int number, String name, int age, String secret, String detailAddress) { this.number = number; this.name = name; this.age = age; @@ -861,15 +876,30 @@ class AbstractConfigTest { // Expect empty metadata for new instance // Check and set default value of field in checkDefault() method - List> configClasses = Arrays.asList(ApplicationConfig.class, - ConsumerConfig.class, ProviderConfig.class, ReferenceConfig.class, ServiceConfig.class, - ProtocolConfig.class, RegistryConfig.class, ConfigCenterConfig.class, MetadataReportConfig.class, - ModuleConfig.class, SslConfig.class, MetricsConfig.class, MonitorConfig.class, MethodConfig.class); + List> configClasses = Arrays.asList( + ApplicationConfig.class, + ConsumerConfig.class, + ProviderConfig.class, + ReferenceConfig.class, + ServiceConfig.class, + ProtocolConfig.class, + RegistryConfig.class, + ConfigCenterConfig.class, + MetadataReportConfig.class, + ModuleConfig.class, + SslConfig.class, + MetricsConfig.class, + MonitorConfig.class, + MethodConfig.class); for (Class configClass : configClasses) { AbstractConfig config = configClass.getDeclaredConstructor().newInstance(); Map metaData = config.getMetaData(); - Assertions.assertEquals(0, metaData.size(), "Expect empty metadata for new instance but found: "+metaData +" of "+configClass.getSimpleName()); + Assertions.assertEquals( + 0, + metaData.size(), + "Expect empty metadata for new instance but found: " + metaData + " of " + + configClass.getSimpleName()); System.out.println(configClass.getSimpleName() + " metadata is checked."); } } @@ -950,8 +980,7 @@ class AbstractConfigTest { @Nested private InnerConfig b; - OuterConfig() { - } + OuterConfig() {} OuterConfig(String id) { this.setId(id); diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractMethodConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractMethodConfigTest.java index 4973e1d3d9..8842e1a203 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractMethodConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractMethodConfigTest.java @@ -18,12 +18,12 @@ package org.apache.dubbo.config; import org.apache.dubbo.config.bootstrap.DubboBootstrap; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; @@ -129,7 +129,5 @@ class AbstractMethodConfigTest { assertThat(methodConfig.getParameters(), sameInstance(parameters)); } - private static class MethodConfig extends AbstractMethodConfig { - - } + private static class MethodConfig extends AbstractMethodConfig {} } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java index bc3ffe739a..c3e1330145 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; import org.apache.dubbo.common.URL; @@ -26,14 +25,14 @@ import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory; import org.apache.dubbo.rpc.cluster.router.tag.TagStateRouterFactory; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; import static org.apache.dubbo.common.constants.CommonConstants.INVOKER_LISTENER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REFERENCE_FILTER_KEY; @@ -109,13 +108,20 @@ class AbstractReferenceConfigTest { assertThat(parameters, hasValue("tag,condition")); URL url = mock(URL.class); when(url.getParameter(ROUTER_KEY)).thenReturn("condition"); - List routerFactories = ExtensionLoader.getExtensionLoader(StateRouterFactory.class).getActivateExtension(url, ROUTER_KEY); - assertThat(routerFactories.stream().anyMatch(routerFactory -> routerFactory.getClass().equals(ConditionStateRouterFactory.class)), is(true)); + List routerFactories = + ExtensionLoader.getExtensionLoader(StateRouterFactory.class).getActivateExtension(url, ROUTER_KEY); + assertThat( + routerFactories.stream() + .anyMatch(routerFactory -> routerFactory.getClass().equals(ConditionStateRouterFactory.class)), + is(true)); when(url.getParameter(ROUTER_KEY)).thenReturn("-tag,-app"); - routerFactories = ExtensionLoader.getExtensionLoader(StateRouterFactory.class).getActivateExtension(url, ROUTER_KEY); - assertThat(routerFactories.stream() - .allMatch(routerFactory -> !routerFactory.getClass().equals(TagStateRouterFactory.class) - && !routerFactory.getClass().equals(AppStateRouterFactory.class)), is(true)); + routerFactories = + ExtensionLoader.getExtensionLoader(StateRouterFactory.class).getActivateExtension(url, ROUTER_KEY); + assertThat( + routerFactories.stream() + .allMatch(routerFactory -> !routerFactory.getClass().equals(TagStateRouterFactory.class) + && !routerFactory.getClass().equals(AppStateRouterFactory.class)), + is(true)); } @Test @@ -214,7 +220,5 @@ class AbstractReferenceConfigTest { Assertions.assertNull(referenceConfig2.getGeneric()); } - private static class ReferenceConfig extends AbstractReferenceConfig { - - } + private static class ReferenceConfig extends AbstractReferenceConfig {} } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractServiceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractServiceConfigTest.java index f25a5ed327..3dc4bd90dd 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractServiceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractServiceConfigTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,17 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; - -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.EXPORTER_LISTENER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SERVICE_FILTER_KEY; import static org.hamcrest.MatcherAssert.assertThat; @@ -217,8 +215,5 @@ class AbstractServiceConfigTest { assertThat(serviceConfig.getPreferSerialization(), equalTo("x-serialization")); } - - private static class ServiceConfig extends AbstractServiceConfig { - - } + private static class ServiceConfig extends AbstractServiceConfig {} } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java index a6ec4dac6e..54dacb1a77 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,19 +14,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; import org.apache.dubbo.config.bootstrap.DubboBootstrap; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO; import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY; @@ -233,7 +233,7 @@ class ApplicationConfigTest { void testMetaData() { ApplicationConfig config = new ApplicationConfig(); Map metaData = config.getMetaData(); - Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: "+metaData); + Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData); } @Test @@ -245,9 +245,7 @@ class ApplicationConfigTest { ApplicationConfig applicationConfig = new ApplicationConfig(); - DubboBootstrap.getInstance() - .application(applicationConfig) - .initialize(); + DubboBootstrap.getInstance().application(applicationConfig).initialize(); Assertions.assertEquals(owner, applicationConfig.getOwner()); Assertions.assertEquals("1.2.3", applicationConfig.getVersion()); @@ -265,9 +263,7 @@ class ApplicationConfigTest { ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setId("demo-app"); - DubboBootstrap.getInstance() - .application(applicationConfig) - .initialize(); + DubboBootstrap.getInstance().application(applicationConfig).initialize(); Assertions.assertEquals("demo-app", applicationConfig.getId()); Assertions.assertEquals("demo-app", applicationConfig.getName()); @@ -286,9 +282,7 @@ class ApplicationConfigTest { ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("demo-app"); - DubboBootstrap.getInstance() - .application(applicationConfig) - .initialize(); + DubboBootstrap.getInstance().application(applicationConfig).initialize(); Assertions.assertEquals(owner, applicationConfig.getOwner()); Assertions.assertEquals("1.2.3", applicationConfig.getVersion()); @@ -302,8 +296,7 @@ class ApplicationConfigTest { SysProps.setProperty("dubbo.applications.demo-app.owner", owner); SysProps.setProperty("dubbo.applications.demo-app.version", "1.2.3"); - DubboBootstrap.getInstance() - .initialize(); + DubboBootstrap.getInstance().initialize(); ApplicationConfig applicationConfig = DubboBootstrap.getInstance().getApplication(); @@ -322,8 +315,7 @@ class ApplicationConfigTest { SysProps.setProperty("dubbo.application.qos_host", "127.0.0.1"); SysProps.setProperty("dubbo.application.qosPort", "2345"); - DubboBootstrap.getInstance() - .initialize(); + DubboBootstrap.getInstance().initialize(); ApplicationConfig applicationConfig = DubboBootstrap.getInstance().getApplication(); @@ -339,8 +331,7 @@ class ApplicationConfigTest { void testDefaultValue() { SysProps.setProperty("dubbo.application.NAME", "demo-app"); - DubboBootstrap.getInstance() - .initialize(); + DubboBootstrap.getInstance().initialize(); ApplicationConfig applicationConfig = DubboBootstrap.getInstance().getApplication(); diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ArgumentConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ArgumentConfigTest.java index a3007f4503..9ec261f135 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ArgumentConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ArgumentConfigTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,14 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ConfigCenterConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ConfigCenterConfigTest.java index 0af13133ca..1c95936ca3 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ConfigCenterConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ConfigCenterConfigTest.java @@ -14,25 +14,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; - import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.remoting.Constants.CLIENT_KEY; class ConfigCenterConfigTest { @@ -53,8 +51,8 @@ class ConfigCenterConfigTest { Assertions.assertEquals(Arrays.asList("dubbo.config-center"), config.getPrefixes()); config.setId("configcenterA"); - Assertions.assertEquals(Arrays.asList("dubbo.config-centers.configcenterA", "dubbo.config-center"), - config.getPrefixes()); + Assertions.assertEquals( + Arrays.asList("dubbo.config-centers.configcenterA", "dubbo.config-center"), config.getPrefixes()); } @Test @@ -66,11 +64,11 @@ class ConfigCenterConfigTest { config.setHighestPriority(null); config.refresh(); - Assertions.assertEquals(ZookeeperRegistryCenterConfig.getConnectionAddress() + - "/" + ConfigCenterConfig.class.getName() + - "?check=true&config-file=dubbo.properties&group=group&namespace=namespace&timeout=30000", - config.toUrl().toFullString() - ); + Assertions.assertEquals( + ZookeeperRegistryCenterConfig.getConnectionAddress() + "/" + + ConfigCenterConfig.class.getName() + + "?check=true&config-file=dubbo.properties&group=group&namespace=namespace&timeout=30000", + config.toUrl().toFullString()); } @Test @@ -81,7 +79,7 @@ class ConfigCenterConfigTest { SysProps.setProperty("dubbo.config-center.check", "false"); SysProps.setProperty("dubbo.config-center.address", zkAddr); - //No id and no address + // No id and no address ConfigCenterConfig configCenter = new ConfigCenterConfig(); configCenter.setAddress("N/A"); @@ -95,7 +93,8 @@ class ConfigCenterConfigTest { e.printStackTrace(); } - Collection configCenters = ApplicationModel.defaultModel().getApplicationConfigManager().getConfigCenters(); + Collection configCenters = + ApplicationModel.defaultModel().getApplicationConfigManager().getConfigCenters(); Assertions.assertEquals(1, configCenters.size()); Assertions.assertEquals(configCenter, configCenters.iterator().next()); Assertions.assertEquals(zkAddr, configCenter.getAddress()); @@ -112,7 +111,7 @@ class ConfigCenterConfigTest { SysProps.setProperty("dubbo.config-center.check", "false"); SysProps.setProperty("dubbo.config-center.address", zkAddr); - //No id but has address + // No id but has address ConfigCenterConfig configCenter = new ConfigCenterConfig(); configCenter.setAddress(ZookeeperRegistryCenterConfig.getConnectionAddress()); @@ -121,7 +120,8 @@ class ConfigCenterConfigTest { .configCenter(configCenter) .start(); - Collection configCenters = ApplicationModel.defaultModel().getApplicationConfigManager().getConfigCenters(); + Collection configCenters = + ApplicationModel.defaultModel().getApplicationConfigManager().getConfigCenters(); Assertions.assertEquals(1, configCenters.size()); Assertions.assertEquals(configCenter, configCenters.iterator().next()); Assertions.assertEquals(zkAddr, configCenter.getAddress()); @@ -133,7 +133,7 @@ class ConfigCenterConfigTest { @Test void testOverrideConfigBySystemProps() { - //Config instance has Id, but sysprops without id + // Config instance has Id, but sysprops without id SysProps.setProperty("dubbo.config-center.check", "false"); SysProps.setProperty("dubbo.config-center.timeout", "1234"); @@ -146,7 +146,8 @@ class ConfigCenterConfigTest { .configCenter(configCenter) .initialize(); - Collection configCenters = ApplicationModel.defaultModel().getApplicationConfigManager().getConfigCenters(); + Collection configCenters = + ApplicationModel.defaultModel().getApplicationConfigManager().getConfigCenters(); Assertions.assertEquals(1, configCenters.size()); Assertions.assertEquals(configCenter, configCenters.iterator().next()); Assertions.assertEquals(1234, configCenter.getTimeout()); @@ -160,8 +161,14 @@ class ConfigCenterConfigTest { ApplicationModel.defaultModel().getDefaultModule(); // Config instance has id, dubbo props has no id - ApplicationModel.defaultModel().modelEnvironment().getPropertiesConfiguration().setProperty("dubbo.config-center.check", "false"); - ApplicationModel.defaultModel().modelEnvironment().getPropertiesConfiguration().setProperty("dubbo.config-center.timeout", "1234"); + ApplicationModel.defaultModel() + .modelEnvironment() + .getPropertiesConfiguration() + .setProperty("dubbo.config-center.check", "false"); + ApplicationModel.defaultModel() + .modelEnvironment() + .getPropertiesConfiguration() + .setProperty("dubbo.config-center.timeout", "1234"); try { // Config instance has id @@ -173,13 +180,18 @@ class ConfigCenterConfigTest { .configCenter(configCenter) .initialize(); - Collection configCenters = ApplicationModel.defaultModel().getApplicationConfigManager().getConfigCenters(); + Collection configCenters = ApplicationModel.defaultModel() + .getApplicationConfigManager() + .getConfigCenters(); Assertions.assertEquals(1, configCenters.size()); Assertions.assertEquals(configCenter, configCenters.iterator().next()); Assertions.assertEquals(3000L, configCenter.getTimeout()); Assertions.assertEquals(false, configCenter.isCheck()); } finally { - ApplicationModel.defaultModel().modelEnvironment().getPropertiesConfiguration().refresh(); + ApplicationModel.defaultModel() + .modelEnvironment() + .getPropertiesConfiguration() + .refresh(); DubboBootstrap.getInstance().stop(); } } @@ -201,7 +213,8 @@ class ConfigCenterConfigTest { .configCenter(configCenter) .start(); - Collection configCenters = ApplicationModel.defaultModel().getApplicationConfigManager().getConfigCenters(); + Collection configCenters = + ApplicationModel.defaultModel().getApplicationConfigManager().getConfigCenters(); Assertions.assertEquals(1, configCenters.size()); Assertions.assertEquals(configCenter, configCenters.iterator().next()); Assertions.assertEquals(1234, configCenter.getTimeout()); @@ -215,8 +228,14 @@ class ConfigCenterConfigTest { ApplicationModel.defaultModel().getDefaultModule(); // Config instance has id, dubbo props has id - ApplicationModel.defaultModel().modelEnvironment().getPropertiesConfiguration().setProperty("dubbo.config-centers.configcenterA.check", "false"); - ApplicationModel.defaultModel().modelEnvironment().getPropertiesConfiguration().setProperty("dubbo.config-centers.configcenterA.timeout", "1234"); + ApplicationModel.defaultModel() + .modelEnvironment() + .getPropertiesConfiguration() + .setProperty("dubbo.config-centers.configcenterA.check", "false"); + ApplicationModel.defaultModel() + .modelEnvironment() + .getPropertiesConfiguration() + .setProperty("dubbo.config-centers.configcenterA.timeout", "1234"); try { // Config instance has id @@ -229,13 +248,18 @@ class ConfigCenterConfigTest { .configCenter(configCenter) .start(); - Collection configCenters = ApplicationModel.defaultModel().getApplicationConfigManager().getConfigCenters(); + Collection configCenters = ApplicationModel.defaultModel() + .getApplicationConfigManager() + .getConfigCenters(); Assertions.assertEquals(1, configCenters.size()); Assertions.assertEquals(configCenter, configCenters.iterator().next()); Assertions.assertEquals(3000L, configCenter.getTimeout()); Assertions.assertEquals(false, configCenter.isCheck()); } finally { - ApplicationModel.defaultModel().modelEnvironment().getPropertiesConfiguration().refresh(); + ApplicationModel.defaultModel() + .modelEnvironment() + .getPropertiesConfiguration() + .refresh(); DubboBootstrap.getInstance().stop(); } } @@ -244,7 +268,7 @@ class ConfigCenterConfigTest { void testMetaData() { ConfigCenterConfig configCenter = new ConfigCenterConfig(); Map metaData = configCenter.getMetaData(); - Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: "+metaData); + Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData); } @Test @@ -261,7 +285,8 @@ class ConfigCenterConfigTest { String encodedParametersStr = attributes.get("parameters"); Assertions.assertEquals("[]", encodedParametersStr); - Assertions.assertEquals(0, StringUtils.parseParameters(encodedParametersStr).size()); + Assertions.assertEquals( + 0, StringUtils.parseParameters(encodedParametersStr).size()); } @Test @@ -273,10 +298,9 @@ class ConfigCenterConfigTest { Assertions.assertEquals(cc.getAddress(), attributes.get("address")); Assertions.assertEquals(cc.getProtocol(), attributes.get("protocol")); - Assertions.assertEquals(""+cc.getPort(), attributes.get("port")); + Assertions.assertEquals("" + cc.getPort(), attributes.get("port")); Assertions.assertEquals(null, attributes.get("valid")); Assertions.assertEquals(null, attributes.get("refreshed")); - } @Test @@ -292,6 +316,5 @@ class ConfigCenterConfigTest { Assertions.assertEquals(2181, cc.getPort()); Assertions.assertEquals("user123", cc.getUsername()); Assertions.assertEquals("pass123", cc.getPassword()); - } } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ConfigScopeModelInitializerTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ConfigScopeModelInitializerTest.java index 4946e0b2b2..d1abfb2e4f 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ConfigScopeModelInitializerTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ConfigScopeModelInitializerTest.java @@ -43,7 +43,7 @@ class ConfigScopeModelInitializerTest { } @Test - void test(){ + void test() { Assertions.assertNotNull(applicationModel.getDeployer()); Assertions.assertNotNull(moduleModel.getDeployer()); } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ConsumerConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ConsumerConfigTest.java index 1a303ced7b..f3a161c01c 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ConsumerConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ConsumerConfigTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; import org.apache.dubbo.common.utils.JsonUtils; @@ -22,15 +21,15 @@ import org.apache.dubbo.config.api.DemoService; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; @@ -114,7 +113,10 @@ class ConsumerConfigTest { .consumer(consumerConfig) .initialize(); - Collection consumers = ApplicationModel.defaultModel().getDefaultModule().getConfigManager().getConsumers(); + Collection consumers = ApplicationModel.defaultModel() + .getDefaultModule() + .getConfigManager() + .getConsumers(); Assertions.assertEquals(1, consumers.size()); Assertions.assertEquals(consumerConfig, consumers.iterator().next()); Assertions.assertEquals(false, consumerConfig.isCheck()); @@ -122,12 +124,11 @@ class ConsumerConfigTest { Assertions.assertEquals(10, consumerConfig.getThreads()); DubboBootstrap.getInstance().destroy(); - } @Test void testOverrideConfigByPluralityId() { - SysProps.setProperty("dubbo.consumer.group", "demoA"); //ignore + SysProps.setProperty("dubbo.consumer.group", "demoA"); // ignore SysProps.setProperty("dubbo.consumers.consumerA.check", "false"); SysProps.setProperty("dubbo.consumers.consumerA.group", "demoB"); SysProps.setProperty("dubbo.consumers.consumerA.threads", "10"); @@ -143,7 +144,10 @@ class ConsumerConfigTest { .consumer(consumerConfig) .initialize(); - Collection consumers = ApplicationModel.defaultModel().getDefaultModule().getConfigManager().getConsumers(); + Collection consumers = ApplicationModel.defaultModel() + .getDefaultModule() + .getConfigManager() + .getConsumers(); Assertions.assertEquals(1, consumers.size()); Assertions.assertEquals(consumerConfig, consumers.iterator().next()); Assertions.assertEquals(false, consumerConfig.isCheck()); @@ -174,7 +178,10 @@ class ConsumerConfigTest { .consumer(consumerConfig) .initialize(); - Collection consumers = ApplicationModel.defaultModel().getDefaultModule().getConfigManager().getConsumers(); + Collection consumers = ApplicationModel.defaultModel() + .getDefaultModule() + .getConfigManager() + .getConsumers(); Assertions.assertEquals(1, consumers.size()); Assertions.assertEquals(consumerConfig, consumers.iterator().next()); Assertions.assertEquals(true, consumerConfig.isCheck()); @@ -187,9 +194,18 @@ class ConsumerConfigTest { @Test void testOverrideConfigByDubboProps() { ApplicationModel.defaultModel().getDefaultModule(); - ApplicationModel.defaultModel().modelEnvironment().getPropertiesConfiguration().setProperty("dubbo.consumers.consumerA.check", "false"); - ApplicationModel.defaultModel().modelEnvironment().getPropertiesConfiguration().setProperty("dubbo.consumers.consumerA.group", "demo"); - ApplicationModel.defaultModel().modelEnvironment().getPropertiesConfiguration().setProperty("dubbo.consumers.consumerA.threads", "10"); + ApplicationModel.defaultModel() + .modelEnvironment() + .getPropertiesConfiguration() + .setProperty("dubbo.consumers.consumerA.check", "false"); + ApplicationModel.defaultModel() + .modelEnvironment() + .getPropertiesConfiguration() + .setProperty("dubbo.consumers.consumerA.group", "demo"); + ApplicationModel.defaultModel() + .modelEnvironment() + .getPropertiesConfiguration() + .setProperty("dubbo.consumers.consumerA.threads", "10"); try { ConsumerConfig consumerConfig = new ConsumerConfig(); @@ -201,14 +217,20 @@ class ConsumerConfigTest { .consumer(consumerConfig) .initialize(); - Collection consumers = ApplicationModel.defaultModel().getDefaultModule().getConfigManager().getConsumers(); + Collection consumers = ApplicationModel.defaultModel() + .getDefaultModule() + .getConfigManager() + .getConsumers(); Assertions.assertEquals(1, consumers.size()); Assertions.assertEquals(consumerConfig, consumers.iterator().next()); Assertions.assertEquals(false, consumerConfig.isCheck()); Assertions.assertEquals("groupA", consumerConfig.getGroup()); Assertions.assertEquals(10, consumerConfig.getThreads()); } finally { - ApplicationModel.defaultModel().modelEnvironment().getPropertiesConfiguration().refresh(); + ApplicationModel.defaultModel() + .modelEnvironment() + .getPropertiesConfiguration() + .refresh(); DubboBootstrap.getInstance().destroy(); } } @@ -226,9 +248,9 @@ class ConsumerConfigTest { referenceConfig.setInterface(DemoService.class); DubboBootstrap.getInstance() - .application("demo-app") - .reference(referenceConfig) - .initialize(); + .application("demo-app") + .reference(referenceConfig) + .initialize(); Assertions.assertEquals("demo", referenceConfig.getGroup()); Assertions.assertEquals(1234, referenceConfig.getTimeout()); @@ -236,14 +258,13 @@ class ConsumerConfigTest { Assertions.assertEquals(false, referenceConfig.isCheck()); DubboBootstrap.getInstance().destroy(); - } @Test void testMetaData() { ConsumerConfig consumerConfig = new ConsumerConfig(); Map metaData = consumerConfig.getMetaData(); - Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: "+metaData); + Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData); } @Test diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/DubboShutdownHookTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/DubboShutdownHookTest.java index fd34d7ac88..56cb1196a6 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/DubboShutdownHookTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/DubboShutdownHookTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; import org.apache.dubbo.common.constants.CommonConstants; @@ -22,13 +21,13 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; +import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.concurrent.TimeUnit; - import static java.util.Arrays.asList; public class DubboShutdownHookTest { @@ -74,8 +73,9 @@ public class DubboShutdownHookTest { public void testDestoryWithModuleManagedExternally() throws InterruptedException { applicationModel.getModuleModels().get(0).setLifeCycleManagedExternally(true); new Thread(() -> { - applicationModel.getModuleModels().get(0).destroy(); - }).start(); + applicationModel.getModuleModels().get(0).destroy(); + }) + .start(); TimeUnit.MILLISECONDS.sleep(10); dubboShutdownHook.run(); Assertions.assertTrue(applicationModel.isDestroyed()); diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MetadataReportConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MetadataReportConfigTest.java index 62fb8723f8..73708d73da 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MetadataReportConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MetadataReportConfigTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; import org.apache.dubbo.common.URL; @@ -34,7 +33,5 @@ class MetadataReportConfigTest { metadataReportConfig.setAddress("file://dir-to-file"); URL url = metadataReportConfig.toUrl(); assertThat(url.getParameter("file"), equalTo("file")); - } - -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MethodConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MethodConfigTest.java index d8580388cf..fe9e5d865d 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MethodConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MethodConfigTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; import org.apache.dubbo.config.annotation.Argument; @@ -26,12 +25,6 @@ import org.apache.dubbo.config.common.Person; import org.apache.dubbo.config.provider.impl.DemoServiceImpl; import org.apache.dubbo.rpc.model.AsyncMethodInfo; -import org.hamcrest.Matchers; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.Arrays; import java.util.Collections; import java.util.HashMap; @@ -39,6 +32,12 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.config.Constants.ON_INVOKE_INSTANCE_ATTRIBUTE_KEY; import static org.apache.dubbo.config.Constants.ON_INVOKE_METHOD_ATTRIBUTE_KEY; import static org.apache.dubbo.config.Constants.ON_RETURN_INSTANCE_ATTRIBUTE_KEY; @@ -76,10 +75,27 @@ class MethodConfigTest { private static final boolean ARGUMENTS_CALLBACK = true; private static final String ARGUMENTS_TYPE = "sss"; - @Reference(methods = {@Method(name = METHOD_NAME, timeout = TIMEOUT, retries = RETRIES, loadbalance = LOADBALANCE, async = ASYNC, - actives = ACTIVES, executes = EXECUTES, deprecated = DEPERECATED, sticky = STICKY, oninvoke = ONINVOKE+"."+ONINVOKE_METHOD, - onthrow = ONTHROW+"."+ONTHROW_METHOD, onreturn = ONRETURN+"."+ONRETURN_METHOD, cache = CACHE, validation = VALIDATION, - arguments = {@Argument(index = ARGUMENTS_INDEX, callback = ARGUMENTS_CALLBACK, type = ARGUMENTS_TYPE)})}) + @Reference( + methods = { + @Method( + name = METHOD_NAME, + timeout = TIMEOUT, + retries = RETRIES, + loadbalance = LOADBALANCE, + async = ASYNC, + actives = ACTIVES, + executes = EXECUTES, + deprecated = DEPERECATED, + sticky = STICKY, + oninvoke = ONINVOKE + "." + ONINVOKE_METHOD, + onthrow = ONTHROW + "." + ONTHROW_METHOD, + onreturn = ONRETURN + "." + ONRETURN_METHOD, + cache = CACHE, + validation = VALIDATION, + arguments = { + @Argument(index = ARGUMENTS_INDEX, callback = ARGUMENTS_CALLBACK, type = ARGUMENTS_TYPE) + }) + }) private String testField; @BeforeEach @@ -92,10 +108,13 @@ class MethodConfigTest { SysProps.clear(); } - //TODO remove this test + // TODO remove this test @Test void testStaticConstructor() throws NoSuchFieldException { - Method[] methods = this.getClass().getDeclaredField("testField").getAnnotation(Reference.class).methods(); + Method[] methods = this.getClass() + .getDeclaredField("testField") + .getAnnotation(Reference.class) + .methods(); List methodConfigs = MethodConfig.constructMethodConfig(methods); MethodConfig methodConfig = methodConfigs.get(0); @@ -117,7 +136,8 @@ class MethodConfigTest { assertThat(CACHE, equalTo(methodConfig.getCache())); assertThat(VALIDATION, equalTo(methodConfig.getValidation())); assertThat(ARGUMENTS_INDEX, equalTo(methodConfig.getArguments().get(0).getIndex())); - assertThat(ARGUMENTS_CALLBACK, equalTo(methodConfig.getArguments().get(0).isCallback())); + assertThat( + ARGUMENTS_CALLBACK, equalTo(methodConfig.getArguments().get(0).isCallback())); assertThat(ARGUMENTS_TYPE, equalTo(methodConfig.getArguments().get(0).getType())); } @@ -200,7 +220,7 @@ class MethodConfigTest { assertEquals(methodInfo.getOnreturnMethod(), Person.class.getMethod(methodName, String.class)); } - //@Test + // @Test void testOnReturn() { MethodConfig method = new MethodConfig(); method.setOnreturn("on-return-object"); @@ -226,7 +246,7 @@ class MethodConfigTest { assertThat(parameters.size(), is(0)); } - //@Test + // @Test void testOnThrow() { MethodConfig method = new MethodConfig(); method.setOnthrow("on-throw-object"); @@ -252,7 +272,7 @@ class MethodConfigTest { assertThat(parameters.size(), is(0)); } - //@Test + // @Test void testOnInvoke() { MethodConfig method = new MethodConfig(); method.setOninvoke("on-invoke-object"); @@ -289,10 +309,10 @@ class MethodConfigTest { void testOverrideMethodConfigOfReference() { String interfaceName = DemoService.class.getName(); - SysProps.setProperty("dubbo.reference."+ interfaceName +".sayName.timeout", "1234"); - SysProps.setProperty("dubbo.reference."+ interfaceName +".sayName.sticky", "true"); - SysProps.setProperty("dubbo.reference."+ interfaceName +".sayName.parameters", "[{a:1},{b:2}]"); - SysProps.setProperty("dubbo.reference."+ interfaceName +".init", "false"); + SysProps.setProperty("dubbo.reference." + interfaceName + ".sayName.timeout", "1234"); + SysProps.setProperty("dubbo.reference." + interfaceName + ".sayName.sticky", "true"); + SysProps.setProperty("dubbo.reference." + interfaceName + ".sayName.parameters", "[{a:1},{b:2}]"); + SysProps.setProperty("dubbo.reference." + interfaceName + ".init", "false"); ReferenceConfig referenceConfig = new ReferenceConfig<>(); referenceConfig.setInterface(interfaceName); @@ -302,9 +322,9 @@ class MethodConfigTest { referenceConfig.setMethods(Arrays.asList(methodConfig)); DubboBootstrap.getInstance() - .application("demo-app") - .reference(referenceConfig) - .initialize(); + .application("demo-app") + .reference(referenceConfig) + .initialize(); Map params = new LinkedHashMap<>(); params.put("a", "1"); @@ -314,25 +334,24 @@ class MethodConfigTest { Assertions.assertEquals(true, methodConfig.getSticky()); Assertions.assertEquals(params, methodConfig.getParameters()); Assertions.assertEquals(false, referenceConfig.isInit()); - } @Test void testAddMethodConfigOfReference() { String interfaceName = DemoService.class.getName(); - SysProps.setProperty("dubbo.reference."+ interfaceName +".sayName.timeout", "1234"); - SysProps.setProperty("dubbo.reference."+ interfaceName +".sayName.sticky", "true"); - SysProps.setProperty("dubbo.reference."+ interfaceName +".sayName.parameters", "[{a:1},{b:2}]"); - SysProps.setProperty("dubbo.reference."+ interfaceName +".init", "false"); + SysProps.setProperty("dubbo.reference." + interfaceName + ".sayName.timeout", "1234"); + SysProps.setProperty("dubbo.reference." + interfaceName + ".sayName.sticky", "true"); + SysProps.setProperty("dubbo.reference." + interfaceName + ".sayName.parameters", "[{a:1},{b:2}]"); + SysProps.setProperty("dubbo.reference." + interfaceName + ".init", "false"); ReferenceConfig referenceConfig = new ReferenceConfig<>(); referenceConfig.setInterface(interfaceName); DubboBootstrap.getInstance() - .application("demo-app") - .reference(referenceConfig) - .initialize(); + .application("demo-app") + .reference(referenceConfig) + .initialize(); List methodConfigs = referenceConfig.getMethods(); Assertions.assertEquals(1, methodConfigs.size()); @@ -348,17 +367,16 @@ class MethodConfigTest { Assertions.assertEquals(false, referenceConfig.isInit()); DubboBootstrap.getInstance().destroy(); - } @Test void testOverrideMethodConfigOfService() { String interfaceName = DemoService.class.getName(); - SysProps.setProperty("dubbo.service."+ interfaceName +".sayName.timeout", "1234"); - SysProps.setProperty("dubbo.service."+ interfaceName +".sayName.sticky", "true"); - SysProps.setProperty("dubbo.service."+ interfaceName +".sayName.parameters", "[{a:1},{b:2}]"); - SysProps.setProperty("dubbo.service."+ interfaceName +".group", "demo"); + SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.timeout", "1234"); + SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.sticky", "true"); + SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.parameters", "[{a:1},{b:2}]"); + SysProps.setProperty("dubbo.service." + interfaceName + ".group", "demo"); SysProps.setProperty("dubbo.registry.address", "N/A"); ServiceConfig serviceConfig = new ServiceConfig<>(); @@ -370,9 +388,9 @@ class MethodConfigTest { serviceConfig.setMethods(Collections.singletonList(methodConfig)); DubboBootstrap.getInstance() - .application("demo-app") - .service(serviceConfig) - .initialize(); + .application("demo-app") + .service(serviceConfig) + .initialize(); Map params = new LinkedHashMap<>(); params.put("a", "1"); @@ -384,19 +402,18 @@ class MethodConfigTest { Assertions.assertEquals("demo", serviceConfig.getGroup()); DubboBootstrap.getInstance().destroy(); - } @Test void testAddMethodConfigOfService() { String interfaceName = DemoService.class.getName(); - SysProps.setProperty("dubbo.service."+ interfaceName +".sayName.timeout", "1234"); - SysProps.setProperty("dubbo.service."+ interfaceName +".sayName.sticky", "true"); - SysProps.setProperty("dubbo.service."+ interfaceName +".sayName.parameters", "[{a:1},{b:2}]"); - SysProps.setProperty("dubbo.service."+ interfaceName +".sayName.0.callback", "true"); - SysProps.setProperty("dubbo.service."+ interfaceName +".group", "demo"); - SysProps.setProperty("dubbo.service."+ interfaceName +".echo", "non-method-config"); + SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.timeout", "1234"); + SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.sticky", "true"); + SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.parameters", "[{a:1},{b:2}]"); + SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.0.callback", "true"); + SysProps.setProperty("dubbo.service." + interfaceName + ".group", "demo"); + SysProps.setProperty("dubbo.service." + interfaceName + ".echo", "non-method-config"); SysProps.setProperty("dubbo.registry.address", "N/A"); ServiceConfig serviceConfig = new ServiceConfig<>(); @@ -406,9 +423,9 @@ class MethodConfigTest { Assertions.assertNull(serviceConfig.getMethods()); DubboBootstrap.getInstance() - .application("demo-app") - .service(serviceConfig) - .initialize(); + .application("demo-app") + .service(serviceConfig) + .initialize(); List methodConfigs = serviceConfig.getMethods(); Assertions.assertEquals(1, methodConfigs.size()); @@ -435,8 +452,8 @@ class MethodConfigTest { void testVerifyMethodConfigOfService() { String interfaceName = DemoService.class.getName(); - SysProps.setProperty("dubbo.service."+ interfaceName +".sayHello.timeout", "1234"); - SysProps.setProperty("dubbo.service."+ interfaceName +".group", "demo"); + SysProps.setProperty("dubbo.service." + interfaceName + ".sayHello.timeout", "1234"); + SysProps.setProperty("dubbo.service." + interfaceName + ".group", "demo"); SysProps.setProperty("dubbo.registry.address", "N/A"); ServiceConfig serviceConfig = new ServiceConfig<>(); @@ -449,16 +466,16 @@ class MethodConfigTest { try { DubboBootstrap.getInstance() - .application("demo-app") - .service(serviceConfig) - .initialize(); + .application("demo-app") + .service(serviceConfig) + .initialize(); Assertions.fail("Method config verification should failed"); } catch (Exception e) { // ignore Throwable cause = e.getCause(); Assertions.assertEquals(IllegalStateException.class, cause.getClass()); Assertions.assertTrue(cause.getMessage().contains("not found method"), cause.toString()); - }finally { + } finally { DubboBootstrap.getInstance().destroy(); } } @@ -467,8 +484,8 @@ class MethodConfigTest { void testIgnoreInvalidMethodConfigOfService() { String interfaceName = DemoService.class.getName(); - SysProps.setProperty("dubbo.service."+ interfaceName +".sayHello.timeout", "1234"); - SysProps.setProperty("dubbo.service."+ interfaceName +".sayName.timeout", "1234"); + SysProps.setProperty("dubbo.service." + interfaceName + ".sayHello.timeout", "1234"); + SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.timeout", "1234"); SysProps.setProperty("dubbo.registry.address", "N/A"); SysProps.setProperty(ConfigKeys.DUBBO_CONFIG_IGNORE_INVALID_METHOD_CONFIG, "true"); @@ -481,9 +498,9 @@ class MethodConfigTest { serviceConfig.setMethods(Collections.singletonList(methodConfig)); DubboBootstrap.getInstance() - .application("demo-app") - .service(serviceConfig) - .initialize(); + .application("demo-app") + .service(serviceConfig) + .initialize(); // expect sayHello method config will be ignored, and sayName method config will be created. Assertions.assertEquals(1, serviceConfig.getMethods().size()); @@ -495,6 +512,6 @@ class MethodConfigTest { void testMetaData() { MethodConfig methodConfig = new MethodConfig(); Map metaData = methodConfig.getMetaData(); - Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: "+metaData); + Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData); } } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MetricsConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MetricsConfigTest.java index 578a632160..432d4390f4 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MetricsConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MetricsConfigTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -18,8 +18,9 @@ package org.apache.dubbo.config; import org.apache.dubbo.common.URL; import org.apache.dubbo.config.nested.AggregationConfig; -import org.apache.dubbo.config.nested.PrometheusConfig; import org.apache.dubbo.config.nested.HistogramConfig; +import org.apache.dubbo.config.nested.PrometheusConfig; + import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ModuleConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ModuleConfigTest.java index 6aeba1bc98..cb8bb4ebf9 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ModuleConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ModuleConfigTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,17 +14,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; -import org.hamcrest.Matchers; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.Collections; import java.util.HashMap; import java.util.Map; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; @@ -107,6 +106,6 @@ class ModuleConfigTest { void testMetaData() { MonitorConfig config = new MonitorConfig(); Map metaData = config.getMetaData(); - Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: "+metaData); + Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MonitorConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MonitorConfigTest.java index 0edf1c9b87..d5001a8b30 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MonitorConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MonitorConfigTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,16 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.Collections; import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; @@ -110,6 +109,6 @@ class MonitorConfigTest { void testMetaData() { MonitorConfig config = new MonitorConfig(); Map metaData = config.getMetaData(); - Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: "+metaData); + Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ProtocolConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ProtocolConfigTest.java index d15052b4ad..686794ffa6 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ProtocolConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ProtocolConfigTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,24 +14,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.context.ConfigManager; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - import static org.apache.dubbo.common.constants.ProviderConstants.DEFAULT_PREFER_SERIALIZATION; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -234,14 +233,14 @@ class ProtocolConfigTest { void testMetaData() { ProtocolConfig config = new ProtocolConfig(); Map metaData = config.getMetaData(); - Assertions.assertEquals(0, metaData.size(), "actual: "+metaData); + Assertions.assertEquals(0, metaData.size(), "actual: " + metaData); } @Test void testOverrideEmptyConfig() { int port = NetUtils.getAvailablePort(); - //dubbo.protocol.name=rest - //dubbo.protocol.port=port + // dubbo.protocol.name=rest + // dubbo.protocol.port=port SysProps.setProperty("dubbo.protocol.name", "rest"); SysProps.setProperty("dubbo.protocol.port", String.valueOf(port)); @@ -285,7 +284,7 @@ class ProtocolConfigTest { void testOverrideConfigById() { int port = NetUtils.getAvailablePort(); SysProps.setProperty("dubbo.protocols.rest1.name", "rest"); - SysProps.setProperty("dubbo.protocols.rest1.port", String.valueOf(port)); + SysProps.setProperty("dubbo.protocols.rest1.port", String.valueOf(port)); try { ProtocolConfig protocolConfig = new ProtocolConfig(); @@ -316,8 +315,7 @@ class ProtocolConfigTest { try { DubboBootstrap bootstrap = DubboBootstrap.getInstance(); - bootstrap.application("test-app") - .initialize(); + bootstrap.application("test-app").initialize(); ConfigManager configManager = bootstrap.getConfigManager(); Collection protocols = configManager.getProtocols(); @@ -343,8 +341,7 @@ class ProtocolConfigTest { try { DubboBootstrap bootstrap = DubboBootstrap.getInstance(); - bootstrap.application("test-app") - .initialize(); + bootstrap.application("test-app").initialize(); ConfigManager configManager = bootstrap.getConfigManager(); Collection protocols = configManager.getProtocols(); @@ -370,8 +367,7 @@ class ProtocolConfigTest { try { DubboBootstrap bootstrap = DubboBootstrap.getInstance(); - bootstrap.application("test-app") - .initialize(); + bootstrap.application("test-app").initialize(); ConfigManager configManager = bootstrap.getConfigManager(); Collection protocols = configManager.getProtocols(); @@ -387,7 +383,6 @@ class ProtocolConfigTest { } } - @Test void testPreferSerializationDefault1() throws Exception { ProtocolConfig protocolConfig = new ProtocolConfig(); @@ -419,6 +414,4 @@ class ProtocolConfigTest { protocolConfig.refresh(); assertThat(protocolConfig.getPreferSerialization(), equalTo("x-serialization")); } - - } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ProviderConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ProviderConfigTest.java index dd534342db..07c3e16693 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ProviderConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ProviderConfigTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,15 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; @@ -223,6 +222,6 @@ class ProviderConfigTest { void testMetaData() { ProviderConfig config = new ProviderConfig(); Map metaData = config.getMetaData(); - Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: "+metaData); + Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java index db3478e1a2..675e3ee502 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java @@ -48,23 +48,6 @@ import org.apache.dubbo.rpc.protocol.injvm.InjvmInvoker; import org.apache.dubbo.rpc.protocol.injvm.InjvmProtocol; import org.apache.dubbo.rpc.service.GenericService; -import demo.MultiClassLoaderService; -import demo.MultiClassLoaderServiceImpl; -import demo.MultiClassLoaderServiceRequest; -import demo.MultiClassLoaderServiceResult; -import javassist.CannotCompileException; -import javassist.CtClass; -import javassist.NotFoundException; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.condition.DisabledForJreRange; -import org.junit.jupiter.api.condition.JRE; -import org.mockito.Mockito; - import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -83,6 +66,23 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; +import javassist.CannotCompileException; +import javassist.CtClass; +import javassist.NotFoundException; + +import demo.MultiClassLoaderService; +import demo.MultiClassLoaderServiceImpl; +import demo.MultiClassLoaderServiceRequest; +import demo.MultiClassLoaderServiceResult; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledForJreRange; +import org.junit.jupiter.api.condition.JRE; +import org.mockito.Mockito; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_VERSION_KEY; @@ -244,11 +244,12 @@ class ReferenceConfigTest { referenceConfig.setRegistry(registry); DubboBootstrap dubboBootstrap = DubboBootstrap.newInstance(FrameworkModel.defaultModel()); - dubboBootstrap.application(applicationConfig) - .reference(referenceConfig) - .registry(registry) - .module(moduleConfig) - .initialize(); + dubboBootstrap + .application(applicationConfig) + .reference(referenceConfig) + .registry(registry) + .module(moduleConfig) + .initialize(); referenceConfig.init(); @@ -258,135 +259,200 @@ class ReferenceConfigTest { Assertions.assertEquals(CONSUMER_SIDE, serviceMetadata.getAttachments().get(SIDE_KEY)); // verify additional interface parameter - Assertions.assertEquals(DemoService.class.getName(), serviceMetadata.getAttachments().get(INTERFACE_KEY)); + Assertions.assertEquals( + DemoService.class.getName(), serviceMetadata.getAttachments().get(INTERFACE_KEY)); // verify additional metadata-type parameter - Assertions.assertEquals(DEFAULT_METADATA_STORAGE_TYPE, serviceMetadata.getAttachments().get(METADATA_KEY)); + Assertions.assertEquals( + DEFAULT_METADATA_STORAGE_TYPE, serviceMetadata.getAttachments().get(METADATA_KEY)); // verify additional register.ip parameter - Assertions.assertEquals(NetUtils.getLocalHost(), serviceMetadata.getAttachments().get(REGISTER_IP_KEY)); + Assertions.assertEquals( + NetUtils.getLocalHost(), serviceMetadata.getAttachments().get(REGISTER_IP_KEY)); // verify additional runtime parameters - Assertions.assertEquals(Version.getProtocolVersion(), serviceMetadata.getAttachments().get(DUBBO_VERSION_KEY)); - Assertions.assertEquals(Version.getVersion(), serviceMetadata.getAttachments().get(RELEASE_KEY)); + Assertions.assertEquals( + Version.getProtocolVersion(), serviceMetadata.getAttachments().get(DUBBO_VERSION_KEY)); + Assertions.assertEquals( + Version.getVersion(), serviceMetadata.getAttachments().get(RELEASE_KEY)); Assertions.assertTrue(serviceMetadata.getAttachments().containsKey(TIMESTAMP_KEY)); - Assertions.assertEquals(String.valueOf(ConfigUtils.getPid()), serviceMetadata.getAttachments().get(PID_KEY)); + Assertions.assertEquals( + String.valueOf(ConfigUtils.getPid()), + serviceMetadata.getAttachments().get(PID_KEY)); // verify additional application config - Assertions.assertEquals(applicationConfig.getName(), serviceMetadata.getAttachments().get(APPLICATION_KEY)); - Assertions.assertEquals(applicationConfig.getOwner(), serviceMetadata.getAttachments().get("owner")); - Assertions.assertEquals(applicationConfig.getVersion(), - serviceMetadata.getAttachments().get(APPLICATION_VERSION_KEY)); - Assertions.assertEquals(applicationConfig.getOrganization(), - serviceMetadata.getAttachments().get("organization")); - Assertions.assertEquals(applicationConfig.getArchitecture(), - serviceMetadata.getAttachments().get("architecture")); - Assertions.assertEquals(applicationConfig.getEnvironment(), - serviceMetadata.getAttachments().get("environment")); - Assertions.assertEquals(applicationConfig.getCompiler(), serviceMetadata.getAttachments().get("compiler")); - Assertions.assertEquals(applicationConfig.getLogger(), serviceMetadata.getAttachments().get("logger")); + Assertions.assertEquals( + applicationConfig.getName(), serviceMetadata.getAttachments().get(APPLICATION_KEY)); + Assertions.assertEquals( + applicationConfig.getOwner(), serviceMetadata.getAttachments().get("owner")); + Assertions.assertEquals( + applicationConfig.getVersion(), serviceMetadata.getAttachments().get(APPLICATION_VERSION_KEY)); + Assertions.assertEquals( + applicationConfig.getOrganization(), + serviceMetadata.getAttachments().get("organization")); + Assertions.assertEquals( + applicationConfig.getArchitecture(), + serviceMetadata.getAttachments().get("architecture")); + Assertions.assertEquals( + applicationConfig.getEnvironment(), + serviceMetadata.getAttachments().get("environment")); + Assertions.assertEquals( + applicationConfig.getCompiler(), + serviceMetadata.getAttachments().get("compiler")); + Assertions.assertEquals( + applicationConfig.getLogger(), serviceMetadata.getAttachments().get("logger")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("registries")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("registry.ids")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("monitor")); - Assertions.assertEquals(applicationConfig.getDumpDirectory(), - serviceMetadata.getAttachments().get(DUMP_DIRECTORY)); - Assertions.assertEquals(applicationConfig.getQosEnable().toString(), - serviceMetadata.getAttachments().get(QOS_ENABLE)); - Assertions.assertEquals(applicationConfig.getQosHost(), - serviceMetadata.getAttachments().get(QOS_HOST)); - Assertions.assertEquals(applicationConfig.getQosPort().toString(), - serviceMetadata.getAttachments().get(QOS_PORT)); - Assertions.assertEquals(applicationConfig.getQosAcceptForeignIp().toString(), - serviceMetadata.getAttachments().get(ACCEPT_FOREIGN_IP)); - Assertions.assertEquals(applicationConfig.getParameters().get("key1"), - serviceMetadata.getAttachments().get("key1")); - Assertions.assertEquals(applicationConfig.getParameters().get("key2"), - serviceMetadata.getAttachments().get("key2")); - Assertions.assertEquals(applicationConfig.getShutwait(), - serviceMetadata.getAttachments().get("shutwait")); - Assertions.assertEquals(applicationConfig.getMetadataType(), - serviceMetadata.getAttachments().get(METADATA_KEY)); - Assertions.assertEquals(applicationConfig.getRegisterConsumer().toString(), - serviceMetadata.getAttachments().get("register.consumer")); - Assertions.assertEquals(applicationConfig.getRepository(), - serviceMetadata.getAttachments().get("repository")); - Assertions.assertEquals(applicationConfig.getEnableFileCache().toString(), - serviceMetadata.getAttachments().get(REGISTRY_LOCAL_FILE_CACHE_ENABLED)); - Assertions.assertEquals(applicationConfig.getMetadataServicePort().toString(), - serviceMetadata.getAttachments().get(METADATA_SERVICE_PORT_KEY)); - Assertions.assertEquals(applicationConfig.getMetadataServiceProtocol().toString(), - serviceMetadata.getAttachments().get(METADATA_SERVICE_PROTOCOL_KEY)); - Assertions.assertEquals(applicationConfig.getLivenessProbe(), - serviceMetadata.getAttachments().get(LIVENESS_PROBE_KEY)); - Assertions.assertEquals(applicationConfig.getReadinessProbe(), - serviceMetadata.getAttachments().get(READINESS_PROBE_KEY)); - Assertions.assertEquals(applicationConfig.getStartupProbe(), - serviceMetadata.getAttachments().get(STARTUP_PROBE)); + Assertions.assertEquals( + applicationConfig.getDumpDirectory(), + serviceMetadata.getAttachments().get(DUMP_DIRECTORY)); + Assertions.assertEquals( + applicationConfig.getQosEnable().toString(), + serviceMetadata.getAttachments().get(QOS_ENABLE)); + Assertions.assertEquals( + applicationConfig.getQosHost(), serviceMetadata.getAttachments().get(QOS_HOST)); + Assertions.assertEquals( + applicationConfig.getQosPort().toString(), + serviceMetadata.getAttachments().get(QOS_PORT)); + Assertions.assertEquals( + applicationConfig.getQosAcceptForeignIp().toString(), + serviceMetadata.getAttachments().get(ACCEPT_FOREIGN_IP)); + Assertions.assertEquals( + applicationConfig.getParameters().get("key1"), + serviceMetadata.getAttachments().get("key1")); + Assertions.assertEquals( + applicationConfig.getParameters().get("key2"), + serviceMetadata.getAttachments().get("key2")); + Assertions.assertEquals( + applicationConfig.getShutwait(), + serviceMetadata.getAttachments().get("shutwait")); + Assertions.assertEquals( + applicationConfig.getMetadataType(), + serviceMetadata.getAttachments().get(METADATA_KEY)); + Assertions.assertEquals( + applicationConfig.getRegisterConsumer().toString(), + serviceMetadata.getAttachments().get("register.consumer")); + Assertions.assertEquals( + applicationConfig.getRepository(), + serviceMetadata.getAttachments().get("repository")); + Assertions.assertEquals( + applicationConfig.getEnableFileCache().toString(), + serviceMetadata.getAttachments().get(REGISTRY_LOCAL_FILE_CACHE_ENABLED)); + Assertions.assertEquals( + applicationConfig.getMetadataServicePort().toString(), + serviceMetadata.getAttachments().get(METADATA_SERVICE_PORT_KEY)); + Assertions.assertEquals( + applicationConfig.getMetadataServiceProtocol().toString(), + serviceMetadata.getAttachments().get(METADATA_SERVICE_PROTOCOL_KEY)); + Assertions.assertEquals( + applicationConfig.getLivenessProbe(), + serviceMetadata.getAttachments().get(LIVENESS_PROBE_KEY)); + Assertions.assertEquals( + applicationConfig.getReadinessProbe(), + serviceMetadata.getAttachments().get(READINESS_PROBE_KEY)); + Assertions.assertEquals( + applicationConfig.getStartupProbe(), + serviceMetadata.getAttachments().get(STARTUP_PROBE)); // verify additional module config - Assertions.assertEquals(moduleConfig.getName(), serviceMetadata.getAttachments().get("module")); + Assertions.assertEquals( + moduleConfig.getName(), serviceMetadata.getAttachments().get("module")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("monitor")); - Assertions.assertEquals(moduleConfig.getOrganization(), - serviceMetadata.getAttachments().get("module.organization")); - Assertions.assertEquals(moduleConfig.getOwner(), serviceMetadata.getAttachments().get("module.owner")); + Assertions.assertEquals( + moduleConfig.getOrganization(), serviceMetadata.getAttachments().get("module.organization")); + Assertions.assertEquals( + moduleConfig.getOwner(), serviceMetadata.getAttachments().get("module.owner")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("registries")); - Assertions.assertEquals(moduleConfig.getVersion(), serviceMetadata.getAttachments().get("module.version")); + Assertions.assertEquals( + moduleConfig.getVersion(), serviceMetadata.getAttachments().get("module.version")); // verify additional consumer config - Assertions.assertEquals(consumerConfig.getClient(), serviceMetadata.getAttachments().get("client")); - Assertions.assertEquals(consumerConfig.getThreadpool(), serviceMetadata.getAttachments().get("threadpool")); - Assertions.assertEquals(consumerConfig.getCorethreads().toString(), - serviceMetadata.getAttachments().get("corethreads")); - Assertions.assertEquals(consumerConfig.getQueues().toString(), - serviceMetadata.getAttachments().get("queues")); - Assertions.assertEquals(consumerConfig.getThreads().toString(), - serviceMetadata.getAttachments().get("threads")); - Assertions.assertEquals(consumerConfig.getShareconnections().toString(), - serviceMetadata.getAttachments().get("shareconnections")); - Assertions.assertEquals(consumerConfig.getUrlMergeProcessor(), - serviceMetadata.getAttachments().get(URL_MERGE_PROCESSOR_KEY)); + Assertions.assertEquals( + consumerConfig.getClient(), serviceMetadata.getAttachments().get("client")); + Assertions.assertEquals( + consumerConfig.getThreadpool(), serviceMetadata.getAttachments().get("threadpool")); + Assertions.assertEquals( + consumerConfig.getCorethreads().toString(), + serviceMetadata.getAttachments().get("corethreads")); + Assertions.assertEquals( + consumerConfig.getQueues().toString(), + serviceMetadata.getAttachments().get("queues")); + Assertions.assertEquals( + consumerConfig.getThreads().toString(), + serviceMetadata.getAttachments().get("threads")); + Assertions.assertEquals( + consumerConfig.getShareconnections().toString(), + serviceMetadata.getAttachments().get("shareconnections")); + Assertions.assertEquals( + consumerConfig.getUrlMergeProcessor(), + serviceMetadata.getAttachments().get(URL_MERGE_PROCESSOR_KEY)); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey(REFER_THREAD_NUM_KEY)); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey(REFER_BACKGROUND_KEY)); // verify additional reference config - Assertions.assertEquals(referenceConfig.getClient(), serviceMetadata.getAttachments().get("client")); - Assertions.assertEquals(referenceConfig.getGeneric(), serviceMetadata.getAttachments().get("generic")); - Assertions.assertEquals(referenceConfig.getProtocol(), serviceMetadata.getAttachments().get("protocol")); - Assertions.assertEquals(referenceConfig.isInit().toString(), serviceMetadata.getAttachments().get("init")); - Assertions.assertEquals(referenceConfig.getLazy().toString(), serviceMetadata.getAttachments().get("lazy")); - Assertions.assertEquals(referenceConfig.isInjvm().toString(), serviceMetadata.getAttachments().get("injvm")); - Assertions.assertEquals(referenceConfig.getReconnect(), serviceMetadata.getAttachments().get("reconnect")); - Assertions.assertEquals(referenceConfig.getSticky().toString(), serviceMetadata.getAttachments().get("sticky")); - Assertions.assertEquals(referenceConfig.getStub(), serviceMetadata.getAttachments().get("stub")); - Assertions.assertEquals(referenceConfig.getProvidedBy(), serviceMetadata.getAttachments().get("provided-by")); - Assertions.assertEquals(referenceConfig.getRouter(), serviceMetadata.getAttachments().get("router")); - Assertions.assertEquals(referenceConfig.getReferAsync().toString(), - serviceMetadata.getAttachments().get(REFER_ASYNC_KEY)); + Assertions.assertEquals( + referenceConfig.getClient(), serviceMetadata.getAttachments().get("client")); + Assertions.assertEquals( + referenceConfig.getGeneric(), serviceMetadata.getAttachments().get("generic")); + Assertions.assertEquals( + referenceConfig.getProtocol(), serviceMetadata.getAttachments().get("protocol")); + Assertions.assertEquals( + referenceConfig.isInit().toString(), + serviceMetadata.getAttachments().get("init")); + Assertions.assertEquals( + referenceConfig.getLazy().toString(), + serviceMetadata.getAttachments().get("lazy")); + Assertions.assertEquals( + referenceConfig.isInjvm().toString(), + serviceMetadata.getAttachments().get("injvm")); + Assertions.assertEquals( + referenceConfig.getReconnect(), serviceMetadata.getAttachments().get("reconnect")); + Assertions.assertEquals( + referenceConfig.getSticky().toString(), + serviceMetadata.getAttachments().get("sticky")); + Assertions.assertEquals( + referenceConfig.getStub(), serviceMetadata.getAttachments().get("stub")); + Assertions.assertEquals( + referenceConfig.getProvidedBy(), + serviceMetadata.getAttachments().get("provided-by")); + Assertions.assertEquals( + referenceConfig.getRouter(), serviceMetadata.getAttachments().get("router")); + Assertions.assertEquals( + referenceConfig.getReferAsync().toString(), + serviceMetadata.getAttachments().get(REFER_ASYNC_KEY)); // verify additional method config Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("name")); - Assertions.assertEquals(methodConfig.getStat().toString(), - serviceMetadata.getAttachments().get("sayName.stat")); - Assertions.assertEquals(methodConfig.getRetries().toString(), - serviceMetadata.getAttachments().get("sayName.retries")); + Assertions.assertEquals( + methodConfig.getStat().toString(), + serviceMetadata.getAttachments().get("sayName.stat")); + Assertions.assertEquals( + methodConfig.getRetries().toString(), + serviceMetadata.getAttachments().get("sayName.retries")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.reliable")); - Assertions.assertEquals(methodConfig.getExecutes().toString(), - serviceMetadata.getAttachments().get("sayName.executes")); - Assertions.assertEquals(methodConfig.getDeprecated().toString(), - serviceMetadata.getAttachments().get("sayName.deprecated")); + Assertions.assertEquals( + methodConfig.getExecutes().toString(), + serviceMetadata.getAttachments().get("sayName.executes")); + Assertions.assertEquals( + methodConfig.getDeprecated().toString(), + serviceMetadata.getAttachments().get("sayName.deprecated")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.stick")); - Assertions.assertEquals(methodConfig.isReturn().toString(), - serviceMetadata.getAttachments().get("sayName.return")); + Assertions.assertEquals( + methodConfig.isReturn().toString(), + serviceMetadata.getAttachments().get("sayName.return")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.service")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.service.id")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.parent.prefix")); // verify additional revision and methods parameter - Assertions.assertEquals(Version.getVersion(referenceConfig.getInterfaceClass(), referenceConfig.getVersion()), - serviceMetadata.getAttachments().get(REVISION_KEY)); + Assertions.assertEquals( + Version.getVersion(referenceConfig.getInterfaceClass(), referenceConfig.getVersion()), + serviceMetadata.getAttachments().get(REVISION_KEY)); Assertions.assertTrue(serviceMetadata.getAttachments().containsKey(METHODS_KEY)); - Assertions.assertEquals(DemoService.class.getMethods().length, - StringUtils.split((String) serviceMetadata.getAttachments().get(METHODS_KEY), ',').length); + Assertions.assertEquals( + DemoService.class.getMethods().length, + StringUtils.split((String) serviceMetadata.getAttachments().get(METHODS_KEY), ',').length); dubboBootstrap.stop(); } @@ -409,28 +475,31 @@ class ReferenceConfigTest { referenceConfig.setCheck(false); DubboBootstrap dubboBootstrap = DubboBootstrap.newInstance(FrameworkModel.defaultModel()); - dubboBootstrap.application(applicationConfig) - .reference(referenceConfig) - .initialize(); + dubboBootstrap.application(applicationConfig).reference(referenceConfig).initialize(); referenceConfig.init(); Assertions.assertTrue(referenceConfig.getInvoker() instanceof ScopeClusterInvoker); ScopeClusterInvoker scopeClusterInvoker = (ScopeClusterInvoker) referenceConfig.getInvoker(); Invoker mockInvoker = scopeClusterInvoker.getInvoker(); -// Assertions.assertTrue(mockInvoker instanceof MockClusterInvoker); -// Invoker withCount = ((MockClusterInvoker) mockInvoker).getDirectory().getAllInvokers().get(0); - Invoker withCount = scopeClusterInvoker.getDirectory().getAllInvokers().get(0); + // Assertions.assertTrue(mockInvoker instanceof MockClusterInvoker); + // Invoker withCount = ((MockClusterInvoker) mockInvoker).getDirectory().getAllInvokers().get(0); + Invoker withCount = + scopeClusterInvoker.getDirectory().getAllInvokers().get(0); Assertions.assertTrue(withCount instanceof ReferenceCountInvokerWrapper); Invoker withFilter = ((ReferenceCountInvokerWrapper) withCount).getInvoker(); Assertions.assertTrue(withFilter instanceof ListenerInvokerWrapper - || withFilter instanceof FilterChainBuilder.CallbackRegistrationInvoker); + || withFilter instanceof FilterChainBuilder.CallbackRegistrationInvoker); if (withFilter instanceof ListenerInvokerWrapper) { - Assertions.assertTrue(((ListenerInvokerWrapper) (((ReferenceCountInvokerWrapper) withCount).getInvoker())).getInvoker() instanceof InjvmInvoker); + Assertions.assertTrue( + ((ListenerInvokerWrapper) (((ReferenceCountInvokerWrapper) withCount).getInvoker())) + .getInvoker() + instanceof InjvmInvoker); } if (withFilter instanceof FilterChainBuilder.CallbackRegistrationInvoker) { Invoker filterInvoker = ((FilterChainBuilder.CallbackRegistrationInvoker) withFilter).getFilterInvoker(); - FilterChainBuilder.CopyOfFilterChainNode filterInvoker1 = (FilterChainBuilder.CopyOfFilterChainNode) filterInvoker; + FilterChainBuilder.CopyOfFilterChainNode filterInvoker1 = + (FilterChainBuilder.CopyOfFilterChainNode) filterInvoker; ListenerInvokerWrapper originalInvoker = (ListenerInvokerWrapper) filterInvoker1.getOriginalInvoker(); Invoker invoker = originalInvoker.getInvoker(); Assertions.assertTrue(invoker instanceof InjvmInvoker); @@ -476,10 +545,7 @@ class ReferenceConfigTest { referenceConfig.setRegistry(registry); - dubboBootstrap - .application(applicationConfig) - .reference(referenceConfig) - .initialize(); + dubboBootstrap.application(applicationConfig).reference(referenceConfig).initialize(); referenceConfig.init(); Assertions.assertTrue(referenceConfig.getInvoker() instanceof MigrationInvoker); @@ -487,7 +553,6 @@ class ReferenceConfigTest { dubboBootstrap.destroy(); } - /** * Verify that the remote url is directly configured for remote reference */ @@ -517,18 +582,20 @@ class ReferenceConfigTest { referenceConfig.setUrl("dubbo://127.0.0.1:20880"); - dubboBootstrap - .application(applicationConfig) - .reference(referenceConfig) - .initialize(); + dubboBootstrap.application(applicationConfig).reference(referenceConfig).initialize(); referenceConfig.init(); Assertions.assertTrue(referenceConfig.getInvoker() instanceof ScopeClusterInvoker); Invoker scopeClusterInvoker = referenceConfig.getInvoker(); -// Assertions.assertTrue(((ScopeClusterInvoker) scopeClusterInvoker).getInvoker() instanceof MockClusterInvoker); - Assertions.assertEquals(Boolean.TRUE, ((ScopeClusterInvoker) scopeClusterInvoker).getInvoker().getUrl().getAttribute(PEER_KEY)); + // Assertions.assertTrue(((ScopeClusterInvoker) scopeClusterInvoker).getInvoker() instanceof + // MockClusterInvoker); + Assertions.assertEquals( + Boolean.TRUE, + ((ScopeClusterInvoker) scopeClusterInvoker) + .getInvoker() + .getUrl() + .getAttribute(PEER_KEY)); dubboBootstrap.destroy(); - } /** @@ -560,15 +627,11 @@ class ReferenceConfigTest { referenceConfig.setUrl(registryUrl1); - dubboBootstrap - .application(applicationConfig) - .reference(referenceConfig) - .initialize(); + dubboBootstrap.application(applicationConfig).reference(referenceConfig).initialize(); referenceConfig.init(); Assertions.assertTrue(referenceConfig.getInvoker() instanceof MigrationInvoker); dubboBootstrap.destroy(); - } /** @@ -612,10 +675,7 @@ class ReferenceConfigTest { referenceConfig.setRegistries(registryConfigs); - dubboBootstrap - .application(applicationConfig) - .reference(referenceConfig) - .initialize(); + dubboBootstrap.application(applicationConfig).reference(referenceConfig).initialize(); referenceConfig.init(); Assertions.assertTrue(referenceConfig.getInvoker() instanceof ZoneAwareClusterInvoker); @@ -653,8 +713,8 @@ class ReferenceConfigTest { System.setProperty("java.net.preferIPv4Stack", "true"); demoService.export(); rc.get(); - Assertions.assertFalse(LOCAL_PROTOCOL.equalsIgnoreCase( - rc.getInvoker().getUrl().getProtocol())); + Assertions.assertFalse( + LOCAL_PROTOCOL.equalsIgnoreCase(rc.getInvoker().getUrl().getProtocol())); } finally { System.clearProperty("java.net.preferIPv4Stack"); rc.destroy(); @@ -695,12 +755,16 @@ class ReferenceConfigTest { try { System.setProperty("java.net.preferIPv4Stack", "true"); - ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + ProxyFactory proxy = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); DemoService service = new DemoServiceImpl(); URL url = URL.valueOf("injvm://127.0.0.1/DemoService") - .addParameter(INTERFACE_KEY, DemoService.class.getName()).setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); + .addParameter(INTERFACE_KEY, DemoService.class.getName()) + .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); url = url.addParameter(EXPORTER_LISTENER_KEY, LOCAL_PROTOCOL); - Protocol protocolSPI = ApplicationModel.defaultModel().getExtensionLoader(Protocol.class).getAdaptiveExtension(); + Protocol protocolSPI = ApplicationModel.defaultModel() + .getExtensionLoader(Protocol.class) + .getAdaptiveExtension(); protocolSPI.export(proxy.getInvoker(service, DemoService.class, url)); demoService = rc.get(); success = true; @@ -710,11 +774,9 @@ class ReferenceConfigTest { rc.destroy(); InjvmProtocol.getInjvmProtocol(FrameworkModel.defaultModel()).destroy(); System.clearProperty("java.net.preferIPv4Stack"); - } Assertions.assertTrue(success); Assertions.assertNotNull(demoService); - } @Test @@ -761,11 +823,9 @@ class ReferenceConfigTest { rc.destroy(); sc.unexport(); System.clearProperty("java.net.preferIPv4Stack"); - } Assertions.assertTrue(success); Assertions.assertNotNull(demoService); - } @Test @@ -779,13 +839,12 @@ class ReferenceConfigTest { consumerConfig.setAsync(true); consumerConfig.setActives(10); config.setConsumer(consumerConfig); - config.setAsync(false);// override + config.setAsync(false); // override metaData = config.getMetaData(); Assertions.assertEquals(2, metaData.size()); Assertions.assertEquals(String.valueOf(consumerConfig.getActives()), metaData.get("actives")); Assertions.assertEquals(String.valueOf(config.isAsync()), metaData.get("async")); - } @Test @@ -803,7 +862,6 @@ class ReferenceConfigTest { } long end = System.currentTimeMillis(); System.out.println("ReferenceConfig get prefixes cost: " + (end - start)); - } @Test @@ -814,18 +872,20 @@ class ReferenceConfigTest { referenceConfig.setGeneric("true"); DubboBootstrap.getInstance() - .application("demo app") - .reference(referenceConfig) - .initialize(); + .application("demo app") + .reference(referenceConfig) + .initialize(); Assertions.assertEquals(GenericService.class, referenceConfig.getInterfaceClass()); } - @Test void testLargeReferences() throws InterruptedException { int amount = 10000; - ModuleConfigManager configManager = DubboBootstrap.getInstance().getApplicationModel().getDefaultModule().getConfigManager(); + ModuleConfigManager configManager = DubboBootstrap.getInstance() + .getApplicationModel() + .getDefaultModule() + .getConfigManager(); ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("test-app"); @@ -850,7 +910,8 @@ class ReferenceConfigTest { end = amount; } int finalEnd = end; - System.out.println(String.format("start thread %s: range: %s - %s, count: %s", i, start, end, (end - start))); + System.out.println( + String.format("start thread %s: range: %s - %s, count: %s", i, start, end, (end - start))); executorService.submit(() -> { testInitReferences(start, finalEnd, applicationConfig, metadataReportConfig, configCenterConfig); }); @@ -864,16 +925,20 @@ class ReferenceConfigTest { Assertions.assertEquals(amount, configManager.getReferences().size()); Assertions.assertTrue(cost < 1000, "Init large references too slowly: " + cost); - //test equals + // test equals testSearchReferences(); - } private void testSearchReferences() { long t1 = System.currentTimeMillis(); - Collection> references = DubboBootstrap.getInstance().getApplicationModel().getDefaultModule().getConfigManager().getReferences(); - List> results = references.stream().filter(rc -> rc.equals(references.iterator().next())) - .collect(Collectors.toList()); + Collection> references = DubboBootstrap.getInstance() + .getApplicationModel() + .getDefaultModule() + .getConfigManager() + .getReferences(); + List> results = references.stream() + .filter(rc -> rc.equals(references.iterator().next())) + .collect(Collectors.toList()); long t2 = System.currentTimeMillis(); long cost = t2 - t1; System.out.println("Search large references cost: " + cost + "ms"); @@ -881,7 +946,12 @@ class ReferenceConfigTest { Assertions.assertTrue(cost < 1000, "Search large references too slowly: " + cost); } - private long testInitReferences(int start, int end, ApplicationConfig applicationConfig, MetadataReportConfig metadataReportConfig, ConfigCenterConfig configCenterConfig) { + private long testInitReferences( + int start, + int end, + ApplicationConfig applicationConfig, + MetadataReportConfig metadataReportConfig, + ConfigCenterConfig configCenterConfig) { // test add large number of references long t1 = System.currentTimeMillis(); try { @@ -893,7 +963,7 @@ class ReferenceConfigTest { referenceConfig.setConfigCenter(configCenterConfig); DubboBootstrap.getInstance().reference(referenceConfig); - //ApplicationModel.defaultModel().getConfigManager().getConfigCenters(); + // ApplicationModel.defaultModel().getConfigManager().getConfigCenters(); } } catch (Throwable e) { e.printStackTrace(); @@ -935,7 +1005,11 @@ class ReferenceConfigTest { serviceConfig.setRef(demoService); serviceConfig.export(); - String basePath = DemoService.class.getProtectionDomain().getCodeSource().getLocation().getFile(); + String basePath = DemoService.class + .getProtectionDomain() + .getCodeSource() + .getLocation() + .getFile(); basePath = URLDecoder.decode(basePath, "UTF-8"); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); TestClassLoader classLoader1 = new TestClassLoader(classLoader, basePath); @@ -956,7 +1030,8 @@ class ReferenceConfigTest { for (Class anInterface : demoService1.getClass().getInterfaces()) { Assertions.assertNotEquals(DemoService.class, anInterface); } - Assertions.assertTrue(Arrays.stream(demoService1.getClass().getInterfaces()).anyMatch((clazz) -> clazz.getClassLoader().equals(classLoader1))); + Assertions.assertTrue(Arrays.stream(demoService1.getClass().getInterfaces()) + .anyMatch((clazz) -> clazz.getClassLoader().equals(classLoader1))); java.lang.reflect.Method callBean1 = demoService1.getClass().getDeclaredMethod("callInnerClass"); callBean1.setAccessible(true); @@ -975,7 +1050,8 @@ class ReferenceConfigTest { for (Class anInterface : demoService2.getClass().getInterfaces()) { Assertions.assertNotEquals(DemoService.class, anInterface); } - Assertions.assertTrue(Arrays.stream(demoService2.getClass().getInterfaces()).anyMatch((clazz) -> clazz.getClassLoader().equals(classLoader2))); + Assertions.assertTrue(Arrays.stream(demoService2.getClass().getInterfaces()) + .anyMatch((clazz) -> clazz.getClassLoader().equals(classLoader2))); java.lang.reflect.Method callBean2 = demoService2.getClass().getDeclaredMethod("callInnerClass"); callBean2.setAccessible(true); @@ -996,7 +1072,11 @@ class ReferenceConfigTest { @DisabledForJreRange(min = JRE.JAVA_16) public void testDifferentClassLoaderRequest() throws Exception { FrameworkModel frameworkModel = FrameworkModel.defaultModel(); - String basePath = DemoService.class.getProtectionDomain().getCodeSource().getLocation().getFile(); + String basePath = DemoService.class + .getProtectionDomain() + .getCodeSource() + .getLocation() + .getFile(); basePath = java.net.URLDecoder.decode(basePath, "UTF-8"); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); TestClassLoader1 classLoader1 = new TestClassLoader1(basePath); @@ -1017,7 +1097,8 @@ class ReferenceConfigTest { AtomicReference innerRequestReference = new AtomicReference(); AtomicReference innerResultReference = new AtomicReference(); innerResultReference.set(resultClazzCustom1.getDeclaredConstructor().newInstance()); - Constructor declaredConstructor = clazz1impl.getDeclaredConstructor(AtomicReference.class, AtomicReference.class); + Constructor declaredConstructor = + clazz1impl.getDeclaredConstructor(AtomicReference.class, AtomicReference.class); ServiceConfig serviceConfig = new ServiceConfig<>(); serviceConfig.setInterfaceClassLoader(classLoader1); @@ -1045,11 +1126,13 @@ class ReferenceConfigTest { java.lang.reflect.Method callBean1 = object1.getClass().getDeclaredMethod("call", requestClazzOrigin); callBean1.setAccessible(true); - Object result1 = callBean1.invoke(object1, requestClazzCustom2.getDeclaredConstructor().newInstance()); + Object result1 = callBean1.invoke( + object1, requestClazzCustom2.getDeclaredConstructor().newInstance()); Assertions.assertEquals(resultClazzCustom3, result1.getClass()); Assertions.assertNotEquals(classLoader2, result1.getClass().getClassLoader()); - Assertions.assertEquals(classLoader1, innerRequestReference.get().getClass().getClassLoader()); + Assertions.assertEquals( + classLoader1, innerRequestReference.get().getClass().getClassLoader()); Thread.currentThread().setContextClassLoader(classLoader1); callBean1.invoke(object1, requestClazzCustom2.getDeclaredConstructor().newInstance()); @@ -1068,8 +1151,7 @@ class ReferenceConfigTest { applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("Test")); ClassLoader originClassLoader = Thread.currentThread().getContextClassLoader(); - ClassLoader classLoader = new ClassLoader(originClassLoader) { - }; + ClassLoader classLoader = new ClassLoader(originClassLoader) {}; Thread.currentThread().setContextClassLoader(classLoader); ServiceConfig serviceConfig = new ServiceConfig<>(applicationModel.newModule()); @@ -1112,14 +1194,28 @@ class ReferenceConfigTest { return cls.toClass(classLoader, JavassistCompiler.class.getProtectionDomain()); } - @Reference(methods = {@Method(name = "sayHello", timeout = 1300, retries = 4, loadbalance = "random", async = true, - actives = 3, executes = 5, deprecated = true, sticky = true, oninvoke = "instance.i", onthrow = "instance.t", onreturn = "instance.r", cache = "c", validation = "v", - arguments = {@Argument(index = 24, callback = true, type = "sss")})}) + @Reference( + methods = { + @Method( + name = "sayHello", + timeout = 1300, + retries = 4, + loadbalance = "random", + async = true, + actives = 3, + executes = 5, + deprecated = true, + sticky = true, + oninvoke = "instance.i", + onthrow = "instance.t", + onreturn = "instance.r", + cache = "c", + validation = "v", + arguments = {@Argument(index = 24, callback = true, type = "sss")}) + }) private InnerTest innerTest; - private class InnerTest { - - } + private class InnerTest {} private static class TestClassLoader extends ClassLoader { private String basePath; @@ -1146,7 +1242,8 @@ class ReferenceConfigTest { return loadedClass; } else { try { - if (name.equals("org.apache.dubbo.config.api.DemoService") || name.equals("org.apache.dubbo.config.api.DemoService$InnerClass")) { + if (name.equals("org.apache.dubbo.config.api.DemoService") + || name.equals("org.apache.dubbo.config.api.DemoService$InnerClass")) { Class aClass = this.findClass(name); if (resolve) { this.resolveClass(aClass); @@ -1161,7 +1258,6 @@ class ReferenceConfigTest { } } - public byte[] loadClassData(String className) throws IOException { className = className.replaceAll("\\.", "/"); String path = basePath + File.separator + className + ".class"; @@ -1217,7 +1313,6 @@ class ReferenceConfigTest { } } - public byte[] loadClassData(String className) throws IOException { className = className.replaceAll("\\.", "/"); String path = basePath + File.separator + className + ".class"; @@ -1270,7 +1365,6 @@ class ReferenceConfigTest { } } - public byte[] loadClassData(String className) throws IOException { className = className.replaceAll("\\.", "/"); String path = basePath + File.separator + className + ".class"; @@ -1284,5 +1378,4 @@ class ReferenceConfigTest { return classBytes; } } - } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java index 572665eac4..f184d81752 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; import org.apache.dubbo.common.URL; @@ -23,16 +22,16 @@ import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.PREFERRED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.config.Constants.SHUTDOWN_TIMEOUT_KEY; @@ -66,7 +65,9 @@ class RegistryConfigTest { void testAddress() throws Exception { RegistryConfig registry = new RegistryConfig(); registry.setAddress("zookeeper://mrh:123@localhost:9103/registry?backup=localhost:9104&k1=v1"); - assertThat(registry.getAddress(), equalTo("zookeeper://mrh:123@localhost:9103/registry?backup=localhost:9104&k1=v1")); + assertThat( + registry.getAddress(), + equalTo("zookeeper://mrh:123@localhost:9103/registry?backup=localhost:9104&k1=v1")); assertThat(registry.getProtocol(), equalTo("zookeeper")); assertThat(registry.getUsername(), equalTo("mrh")); assertThat(registry.getPassword(), equalTo("123")); @@ -228,15 +229,12 @@ class RegistryConfigTest { SysProps.setProperty("zookeeper.address", "localhost"); SysProps.setProperty("zookeeper.port", "2188"); - - DubboBootstrap.getInstance() - .application("demo-app") - .initialize(); - Collection registries = ApplicationModel.defaultModel().getApplicationConfigManager().getRegistries(); + DubboBootstrap.getInstance().application("demo-app").initialize(); + Collection registries = + ApplicationModel.defaultModel().getApplicationConfigManager().getRegistries(); Assertions.assertEquals(1, registries.size()); RegistryConfig registryConfig = registries.iterator().next(); Assertions.assertEquals("zookeeper://localhost:2188", registryConfig.getAddress()); - } public void testPreferredWithTrueValue() { @@ -261,5 +259,4 @@ class RegistryConfigTest { URL url = UrlUtils.parseURL(ZookeeperRegistryCenterConfig.getConnectionAddress1(), map); Assertions.assertFalse(url.getParameter(PREFERRED_KEY, false)); } - -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java index 467fd63d5e..79a648d77b 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config; import org.apache.dubbo.common.URL; @@ -37,13 +36,6 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.service.GenericService; -import com.google.common.collect.Lists; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - import java.util.Collections; import java.util.Map; import java.util.Set; @@ -52,6 +44,13 @@ import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicInteger; +import com.google.common.collect.Lists; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_BEAN; @@ -164,8 +163,7 @@ class ServiceConfigTest { } @AfterEach - public void tearDown() { - } + public void tearDown() {} @Test void testExport() throws Exception { @@ -193,7 +191,7 @@ class ServiceConfigTest { @Test void testVersionAndGroupConfigFromProvider() { - //Service no configuration version , the Provider configured. + // Service no configuration version , the Provider configured. service.getProvider().setVersion("1.0.0"); service.getProvider().setGroup("groupA"); service.export(); @@ -217,7 +215,6 @@ class ServiceConfigTest { TestProxyFactory.count = 0; } - @Test void testDelayExport() throws Exception { CountDownLatch latch = new CountDownLatch(1); @@ -230,9 +227,7 @@ class ServiceConfigTest { } @Override - public void unexported(ServiceConfig sc) { - - } + public void unexported(ServiceConfig sc) {} }); delayService.export(); assertTrue(delayService.getExportedUrls().isEmpty()); @@ -245,7 +240,7 @@ class ServiceConfigTest { try { service.export(); service.unexport(); -// Thread.sleep(1000); + // Thread.sleep(1000); Mockito.verify(exporter, Mockito.atLeastOnce()).unexport(); } finally { System.clearProperty(SHUTDOWN_TIMEOUT_KEY); @@ -324,7 +319,7 @@ class ServiceConfigTest { providerConfig.setAsync(true); providerConfig.setActives(10); config.setProvider(providerConfig); - config.setAsync(false);// override + config.setAsync(false); // override metaData = config.getMetaData(); Assertions.assertEquals(2, metaData.size()); @@ -332,7 +327,6 @@ class ServiceConfigTest { Assertions.assertEquals("" + config.isAsync(), metaData.get("async")); } - @Test void testExportWithoutRegistryConfig() { serviceWithoutRegistryConfig.export(); @@ -352,7 +346,8 @@ class ServiceConfigTest { assertThat(url.getParameters(), hasKey(METHODS_KEY)); assertThat(url.getParameters().get(METHODS_KEY), containsString("echo")); assertThat(url.getParameters(), hasEntry(SIDE_KEY, PROVIDER)); - // export DemoService in "mockprotocol2" protocol (MetadataService will be not exported if no registry specified) + // export DemoService in "mockprotocol2" protocol (MetadataService will be not exported if no registry + // specified) Mockito.verify(protocolDelegate, times(1)).export(Mockito.any(Invoker.class)); } @@ -371,7 +366,6 @@ class ServiceConfigTest { assertSame(service, serviceConfig); } - @Test void testMethodConfigWithInvalidArgumentConfig() { Assertions.assertThrows(IllegalArgumentException.class, () -> { @@ -379,16 +373,20 @@ class ServiceConfigTest { service.setInterface(DemoService.class); service.setRef(new DemoServiceImpl()); - service.setProtocol(new ProtocolConfig() {{ - setName("dubbo"); - }}); + service.setProtocol(new ProtocolConfig() { + { + setName("dubbo"); + } + }); MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("sayName"); // invalid argument index. - methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() {{ - // unset config. - }})); + methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() { + { + // unset config. + } + })); service.setMethods(Lists.newArrayList(methodConfig)); service.export(); @@ -401,18 +399,22 @@ class ServiceConfigTest { service.setInterface(DemoService.class); service.setRef(new DemoServiceImpl()); - service.setProtocol(new ProtocolConfig() {{ - setName("dubbo"); - }}); + service.setProtocol(new ProtocolConfig() { + { + setName("dubbo"); + } + }); MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("sayName"); // invalid argument index. - methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() {{ - setType(String.class.getName()); - setIndex(0); - setCallback(false); - }})); + methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() { + { + setType(String.class.getName()); + setIndex(0); + setCallback(false); + } + })); service.setMethods(Lists.newArrayList(methodConfig)); service.export(); @@ -427,17 +429,21 @@ class ServiceConfigTest { service.setInterface(DemoService.class); service.setRef(new DemoServiceImpl()); - service.setProtocol(new ProtocolConfig() {{ - setName("dubbo"); - }}); + service.setProtocol(new ProtocolConfig() { + { + setName("dubbo"); + } + }); MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("sayName"); // invalid argument index. - methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() {{ - setIndex(0); - setCallback(false); - }})); + methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() { + { + setIndex(0); + setCallback(false); + } + })); service.setMethods(Lists.newArrayList(methodConfig)); service.export(); @@ -452,17 +458,21 @@ class ServiceConfigTest { service.setInterface(DemoService.class); service.setRef(new DemoServiceImpl()); - service.setProtocol(new ProtocolConfig() {{ - setName("dubbo"); - }}); + service.setProtocol(new ProtocolConfig() { + { + setName("dubbo"); + } + }); MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("sayName"); // invalid argument index. - methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() {{ - setType(String.class.getName()); - setCallback(false); - }})); + methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() { + { + setType(String.class.getName()); + setCallback(false); + } + })); service.setMethods(Lists.newArrayList(methodConfig)); service.export(); @@ -478,17 +488,21 @@ class ServiceConfigTest { service.setInterface(DemoService.class); service.setRef(new DemoServiceImpl()); - service.setProtocol(new ProtocolConfig() {{ - setName("dubbo"); - }}); + service.setProtocol(new ProtocolConfig() { + { + setName("dubbo"); + } + }); MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("sayName"); // invalid argument index. - methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() {{ - setType(Integer.class.getName()); - setCallback(false); - }})); + methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() { + { + setType(Integer.class.getName()); + setCallback(false); + } + })); service.setMethods(Lists.newArrayList(methodConfig)); service.export(); @@ -502,17 +516,21 @@ class ServiceConfigTest { service.setInterface(DemoService.class); service.setRef(new DemoServiceImpl()); - service.setProtocol(new ProtocolConfig() {{ - setName("dubbo"); - }}); + service.setProtocol(new ProtocolConfig() { + { + setName("dubbo"); + } + }); MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("sayName"); // invalid argument index. - methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() {{ - setType(Integer.class.getName()); - setIndex(0); - }})); + methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() { + { + setType(Integer.class.getName()); + setIndex(0); + } + })); service.setMethods(Lists.newArrayList(methodConfig)); service.export(); @@ -526,17 +544,21 @@ class ServiceConfigTest { service.setInterface(DemoService.class); service.setRef(new DemoServiceImpl()); - service.setProtocol(new ProtocolConfig() {{ - setName("dubbo"); - }}); + service.setProtocol(new ProtocolConfig() { + { + setName("dubbo"); + } + }); MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("sayName"); // invalid argument index. - methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() {{ - setType(String.class.getName()); - setIndex(1); - }})); + methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() { + { + setType(String.class.getName()); + setIndex(1); + } + })); service.setMethods(Lists.newArrayList(methodConfig)); service.export(); @@ -593,9 +615,7 @@ class ServiceConfigTest { } @Override - public void putCachedMapping(String serviceKey, Set apps) { - - } + public void putCachedMapping(String serviceKey, Set apps) {} @Override public Set getRemoteMapping(URL consumerURL) { @@ -608,9 +628,7 @@ class ServiceConfigTest { } @Override - public void $destroy() { - - } + public void $destroy() {} }; ApplicationConfig applicationConfig = new ApplicationConfig("app"); applicationConfig.setMappingRetryInterval(10); @@ -651,9 +669,7 @@ class ServiceConfigTest { } @Override - public void putCachedMapping(String serviceKey, Set apps) { - - } + public void putCachedMapping(String serviceKey, Set apps) {} @Override public Set getMapping(URL consumerURL) { @@ -671,9 +687,7 @@ class ServiceConfigTest { } @Override - public void $destroy() { - - } + public void $destroy() {} }; ApplicationConfig applicationConfig = new ApplicationConfig("app"); applicationConfig.setMappingRetryInterval(10); diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/SysProps.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/SysProps.java index 6c3fe4eaaa..8a09132bea 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/SysProps.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/SysProps.java @@ -41,5 +41,4 @@ public class SysProps { } reset(); } - } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/Box.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/Box.java index e9c87d4f5d..7937c28d4a 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/Box.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/Box.java @@ -19,5 +19,4 @@ package org.apache.dubbo.config.api; public interface Box { String getName(); - } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/DemoException.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/DemoException.java index 2f32c3f64d..5324f43a5e 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/DemoException.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/DemoException.java @@ -38,5 +38,4 @@ public class DemoException extends Exception { public DemoException(Throwable cause) { super(cause); } - } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/DemoService.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/DemoService.java index 96ff3bb3c3..7fb348dda5 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/DemoService.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/DemoService.java @@ -19,7 +19,6 @@ package org.apache.dubbo.config.api; import java.io.Serializable; import java.util.List; - /** * DemoService */ @@ -39,6 +38,5 @@ public interface DemoService { return new InnerClass(); } - class InnerClass implements Serializable { - } + class InnerClass implements Serializable {} } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/Greeting.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/Greeting.java index c2afa98875..acdb009e3d 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/Greeting.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/Greeting.java @@ -6,7 +6,7 @@ * (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 + * 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, diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/User.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/User.java index 5e55cbbf54..5f66f79cde 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/User.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/User.java @@ -27,8 +27,7 @@ public class User implements Serializable { private String name; - public User() { - } + public User() {} public User(String name) { this.name = name; @@ -61,5 +60,4 @@ public class User implements Serializable { } return false; } - } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ConsulDubboServiceConsumerBootstrap.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ConsulDubboServiceConsumerBootstrap.java index 824de82dae..c72c843676 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ConsulDubboServiceConsumerBootstrap.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ConsulDubboServiceConsumerBootstrap.java @@ -31,11 +31,14 @@ public class ConsulDubboServiceConsumerBootstrap { DubboBootstrap bootstrap = DubboBootstrap.getInstance() .application("consul-dubbo-consumer", app -> app.metadata(DEFAULT_METADATA_STORAGE_TYPE)) - .registry("zookeeper", builder -> builder.address("consul://127.0.0.1:8500?registry-type=service&subscribed-services=consul-dubbo-provider") + .registry("zookeeper", builder -> builder.address( + "consul://127.0.0.1:8500?registry-type=service&subscribed-services=consul-dubbo-provider") .useAsConfigCenter(true) .useAsMetadataCenter(true)) - .reference("echo", builder -> builder.interfaceClass(EchoService.class).protocol("dubbo")) - .reference("user", builder -> builder.interfaceClass(UserService.class).protocol("rest")) + .reference("echo", builder -> builder.interfaceClass(EchoService.class) + .protocol("dubbo")) + .reference("user", builder -> builder.interfaceClass(UserService.class) + .protocol("rest")) .start(); EchoService echoService = bootstrap.getCache().get(EchoService.class); diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ConsulDubboServiceProviderBootstrap.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ConsulDubboServiceProviderBootstrap.java index ef3894422e..a08d876eb0 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ConsulDubboServiceProviderBootstrap.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ConsulDubboServiceProviderBootstrap.java @@ -34,8 +34,12 @@ public class ConsulDubboServiceProviderBootstrap { .useAsMetadataCenter(true)) .protocol("dubbo", builder -> builder.port(-1).name("dubbo")) .protocol("rest", builder -> builder.port(8081).name("rest")) - .service("echo", builder -> builder.interfaceClass(EchoService.class).ref(new EchoServiceImpl()).protocolIds("dubbo")) - .service("user", builder -> builder.interfaceClass(UserService.class).ref(new UserServiceImpl()).protocolIds("rest")) + .service("echo", builder -> builder.interfaceClass(EchoService.class) + .ref(new EchoServiceImpl()) + .protocolIds("dubbo")) + .service("user", builder -> builder.interfaceClass(UserService.class) + .ref(new UserServiceImpl()) + .protocolIds("rest")) .start() .await(); } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboBootstrapTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboBootstrapTest.java index 2852bf55d4..fe791af7c0 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboBootstrapTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboBootstrapTest.java @@ -44,13 +44,6 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; @@ -61,6 +54,13 @@ import java.util.List; import java.util.Map; import java.util.Properties; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_MONITOR_ADDRESS; import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE; import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; @@ -115,13 +115,19 @@ class DubboBootstrapTest { System.clearProperty(SHUTDOWN_WAIT_SECONDS_KEY); writeDubboProperties(SHUTDOWN_WAIT_KEY, "100"); - ApplicationModel.defaultModel().modelEnvironment().getPropertiesConfiguration().refresh(); + ApplicationModel.defaultModel() + .modelEnvironment() + .getPropertiesConfiguration() + .refresh(); ConfigValidationUtils.validateApplicationConfig(new ApplicationConfig("demo")); Assertions.assertEquals("100", System.getProperty(SHUTDOWN_WAIT_KEY)); System.clearProperty(SHUTDOWN_WAIT_KEY); writeDubboProperties(SHUTDOWN_WAIT_SECONDS_KEY, "1000"); - ApplicationModel.defaultModel().modelEnvironment().getPropertiesConfiguration().refresh(); + ApplicationModel.defaultModel() + .modelEnvironment() + .getPropertiesConfiguration() + .refresh(); ConfigValidationUtils.validateApplicationConfig(new ApplicationConfig("demo")); Assertions.assertEquals("1000", System.getProperty(SHUTDOWN_WAIT_SECONDS_KEY)); } finally { @@ -141,12 +147,12 @@ class DubboBootstrapTest { serviceConfig.setApplication(new ApplicationConfig("testLoadRegistries")); // load configs from props - DubboBootstrap.getInstance() - .initialize(); + DubboBootstrap.getInstance().initialize(); serviceConfig.refresh(); - //ApplicationModel.defaultModel().getEnvironment().setDynamicConfiguration(new CompositeDynamicConfiguration()); + // ApplicationModel.defaultModel().getEnvironment().setDynamicConfiguration(new + // CompositeDynamicConfiguration()); List urls = ConfigValidationUtils.loadRegistries(serviceConfig, true); Assertions.assertEquals(2, urls.size()); for (URL url : urls) { @@ -164,7 +170,8 @@ class DubboBootstrapTest { void testLoadUserMonitor_address_only() { // -Ddubbo.monitor.address=monitor-addr:12080 SysProps.setProperty(DUBBO_MONITOR_ADDRESS, "monitor-addr:12080"); - URL url = ConfigValidationUtils.loadMonitor(getTestInterfaceConfig(new MonitorConfig()), new ServiceConfigURL("dubbo", "addr1", 9090)); + URL url = ConfigValidationUtils.loadMonitor( + getTestInterfaceConfig(new MonitorConfig()), new ServiceConfigURL("dubbo", "addr1", 9090)); Assertions.assertEquals("monitor-addr:12080", url.getAddress()); Assertions.assertEquals(MonitorService.class.getName(), url.getParameter("interface")); Assertions.assertNotNull(url.getParameter("dubbo")); @@ -178,7 +185,9 @@ class DubboBootstrapTest { MonitorConfig monitorConfig = new MonitorConfig(); monitorConfig.setProtocol("registry"); - URL url = ConfigValidationUtils.loadMonitor(getTestInterfaceConfig(monitorConfig), URL.valueOf(ZookeeperRegistryCenterConfig.getConnectionAddress())); + URL url = ConfigValidationUtils.loadMonitor( + getTestInterfaceConfig(monitorConfig), + URL.valueOf(ZookeeperRegistryCenterConfig.getConnectionAddress())); Assertions.assertEquals("dubbo", url.getProtocol()); Assertions.assertEquals("registry", url.getParameter("protocol")); } @@ -189,14 +198,17 @@ class DubboBootstrapTest { MonitorConfig monitorConfig = new MonitorConfig(); monitorConfig.setProtocol("service-discovery-registry"); - URL url = ConfigValidationUtils.loadMonitor(getTestInterfaceConfig(monitorConfig), URL.valueOf(ZookeeperRegistryCenterConfig.getConnectionAddress())); + URL url = ConfigValidationUtils.loadMonitor( + getTestInterfaceConfig(monitorConfig), + URL.valueOf(ZookeeperRegistryCenterConfig.getConnectionAddress())); Assertions.assertEquals("dubbo", url.getProtocol()); Assertions.assertEquals("service-discovery-registry", url.getParameter("protocol")); } @Test void testLoadUserMonitor_no_monitor() { - URL url = ConfigValidationUtils.loadMonitor(getTestInterfaceConfig(null), URL.valueOf(ZookeeperRegistryCenterConfig.getConnectionAddress())); + URL url = ConfigValidationUtils.loadMonitor( + getTestInterfaceConfig(null), URL.valueOf(ZookeeperRegistryCenterConfig.getConnectionAddress())); Assertions.assertNull(url); } @@ -206,7 +218,9 @@ class DubboBootstrapTest { MonitorConfig monitorConfig = new MonitorConfig(); monitorConfig.setProtocol("user"); - URL url = ConfigValidationUtils.loadMonitor(getTestInterfaceConfig(monitorConfig), URL.valueOf(ZookeeperRegistryCenterConfig.getConnectionAddress())); + URL url = ConfigValidationUtils.loadMonitor( + getTestInterfaceConfig(monitorConfig), + URL.valueOf(ZookeeperRegistryCenterConfig.getConnectionAddress())); Assertions.assertEquals("user", url.getProtocol()); } @@ -215,7 +229,9 @@ class DubboBootstrapTest { // dubbo.monitor.address=user://1.2.3.4:5678?k=v MonitorConfig monitorConfig = new MonitorConfig(); monitorConfig.setAddress("user://1.2.3.4:5678?param1=value1"); - URL url = ConfigValidationUtils.loadMonitor(getTestInterfaceConfig(monitorConfig), URL.valueOf(ZookeeperRegistryCenterConfig.getConnectionAddress())); + URL url = ConfigValidationUtils.loadMonitor( + getTestInterfaceConfig(monitorConfig), + URL.valueOf(ZookeeperRegistryCenterConfig.getConnectionAddress())); Assertions.assertEquals("user", url.getProtocol()); Assertions.assertEquals("1.2.3.4:5678", url.getAddress()); Assertions.assertEquals("value1", url.getParameter("param1")); @@ -224,7 +240,7 @@ class DubboBootstrapTest { private InterfaceConfig getTestInterfaceConfig(MonitorConfig monitorConfig) { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setApplication(new ApplicationConfig("testLoadMonitor")); - if(monitorConfig!=null) { + if (monitorConfig != null) { interfaceConfig.setMonitor(monitorConfig); } return interfaceConfig; @@ -237,11 +253,12 @@ class DubboBootstrapTest { service.setRef(new DemoServiceImpl()); DubboBootstrap bootstrap = DubboBootstrap.getInstance(); - bootstrap.application(new ApplicationConfig("bootstrap-test")) - .registry(new RegistryConfig(zkServerAddress)) - .protocol(new ProtocolConfig(CommonConstants.DUBBO_PROTOCOL, -1)) - .service(service) - .start(); + bootstrap + .application(new ApplicationConfig("bootstrap-test")) + .registry(new RegistryConfig(zkServerAddress)) + .protocol(new ProtocolConfig(CommonConstants.DUBBO_PROTOCOL, -1)) + .service(service) + .start(); Assertions.assertTrue(bootstrap.isInitialized()); Assertions.assertTrue(bootstrap.isStarted()); @@ -250,7 +267,12 @@ class DubboBootstrapTest { ApplicationModel applicationModel = bootstrap.getApplicationModel(); DefaultApplicationDeployer applicationDeployer = getApplicationDeployer(applicationModel); Assertions.assertNotNull(ReflectUtils.getFieldValue(applicationDeployer, "asyncMetadataFuture")); - Assertions.assertTrue(applicationModel.getDefaultModule().getServiceRepository().getExportedServices().size() > 0); + Assertions.assertTrue(applicationModel + .getDefaultModule() + .getServiceRepository() + .getExportedServices() + .size() + > 0); } private DefaultApplicationDeployer getApplicationDeployer(ApplicationModel applicationModel) { @@ -268,11 +290,12 @@ class DubboBootstrapTest { ApplicationConfig applicationConfig = new ApplicationConfig("bootstrap-test"); applicationConfig.setMetadataServicePort(availablePort); DubboBootstrap bootstrap = DubboBootstrap.getInstance(); - bootstrap.application(applicationConfig) - .registry(new RegistryConfig(zkServerAddress)) - .protocol(new ProtocolConfig(CommonConstants.DUBBO_PROTOCOL, -1)) - .service(service) - .start(); + bootstrap + .application(applicationConfig) + .registry(new RegistryConfig(zkServerAddress)) + .protocol(new ProtocolConfig(CommonConstants.DUBBO_PROTOCOL, -1)) + .service(service) + .start(); assertMetadataService(bootstrap, availablePort, true); } @@ -296,11 +319,11 @@ class DubboBootstrapTest { Exception exception = null; try { DubboBootstrap.getInstance() - .application(applicationConfig) - .registry(registryConfig) - .protocol(new ProtocolConfig(CommonConstants.DUBBO_PROTOCOL, -1)) - .service(service) - .start(); + .application(applicationConfig) + .registry(registryConfig) + .protocol(new ProtocolConfig(CommonConstants.DUBBO_PROTOCOL, -1)) + .service(service) + .start(); } catch (Exception e) { exception = e; DubboBootstrap.reset(); @@ -309,19 +332,19 @@ class DubboBootstrapTest { Assertions.assertNotNull(exception); DubboBootstrap.getInstance() - .application(applicationConfig) - .registry(registryConfig) - .protocol(new ProtocolConfig(CommonConstants.DUBBO_PROTOCOL, -1)) - .service(service) - .metadataReport(new MetadataReportConfig(zkServerAddress)) - .start(); + .application(applicationConfig) + .registry(registryConfig) + .protocol(new ProtocolConfig(CommonConstants.DUBBO_PROTOCOL, -1)) + .service(service) + .metadataReport(new MetadataReportConfig(zkServerAddress)) + .start(); assertMetadataService(DubboBootstrap.getInstance(), availablePort, false); - } private ExporterDeployListener getListener(ApplicationModel model) { - return (ExporterDeployListener)model.getExtensionLoader(ApplicationDeployListener.class).getExtension("exporter"); + return (ExporterDeployListener) + model.getExtensionLoader(ApplicationDeployListener.class).getExtension("exporter"); } private void assertMetadataService(DubboBootstrap bootstrap, int availablePort, boolean metadataExported) { @@ -336,7 +359,8 @@ class DubboBootstrapTest { ServiceConfig serviceConfig = new ServiceConfig<>(); serviceConfig.setRegistry(new RegistryConfig("N/A")); serviceConfig.setInterface(MetadataService.class); - serviceConfig.setGroup(ApplicationModel.defaultModel().getCurrentConfig().getName()); + serviceConfig.setGroup( + ApplicationModel.defaultModel().getCurrentConfig().getName()); serviceConfig.setVersion(MetadataService.VERSION); assertThat(exporters, hasEntry(is(serviceConfig.getUniqueServiceName() + ":" + availablePort), anything())); } else { @@ -344,7 +368,6 @@ class DubboBootstrapTest { } } - private void writeDubboProperties(String key, String value) { OutputStream os = null; try { @@ -364,9 +387,5 @@ class DubboBootstrapTest { } } - - public static class InterfaceConfig extends AbstractInterfaceConfig { - - } - + public static class InterfaceConfig extends AbstractInterfaceConfig {} } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceConsumerBootstrap.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceConsumerBootstrap.java index ca84218b1e..28971f1689 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceConsumerBootstrap.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceConsumerBootstrap.java @@ -33,19 +33,27 @@ public class DubboServiceConsumerBootstrap { .application("dubbo-consumer-demo") .protocol(builder -> builder.port(20887).name("dubbo")) // Eureka -// .registry(builder -> builder.address("eureka://127.0.0.1:8761?registry-type=service&subscribed-services=dubbo-provider-demo")) + // .registry(builder -> + // builder.address("eureka://127.0.0.1:8761?registry-type=service&subscribed-services=dubbo-provider-demo")) // Zookeeper - .registry("zookeeper", builder -> builder.address(ZookeeperRegistryCenterConfig.getConnectionAddress()+"?registry-type=service&subscribed-services=dubbo-provider-demo")) + .registry( + "zookeeper", + builder -> builder.address(ZookeeperRegistryCenterConfig.getConnectionAddress() + + "?registry-type=service&subscribed-services=dubbo-provider-demo")) .metadataReport(new MetadataReportConfig(ZookeeperRegistryCenterConfig.getConnectionAddress())) // Nacos - // .registry("nacos", builder -> builder.address("nacos://127.0.0.1:8848?registry.type=service&subscribed.services=dubbo-provider-demo")) + // .registry("nacos", builder -> + // builder.address("nacos://127.0.0.1:8848?registry.type=service&subscribed.services=dubbo-provider-demo")) // Consul - // .registry("consul", builder -> builder.address("consul://127.0.0.1:8500?registry.type=service&subscribed.services=dubbo-provider-demo").group("namespace1")) - .reference("echo", builder -> builder.interfaceClass(EchoService.class).protocol("dubbo")) - .reference("user", builder -> builder.interfaceClass(UserService.class).protocol("rest")) + // .registry("consul", builder -> + // builder.address("consul://127.0.0.1:8500?registry.type=service&subscribed.services=dubbo-provider-demo").group("namespace1")) + .reference("echo", builder -> builder.interfaceClass(EchoService.class) + .protocol("dubbo")) + .reference("user", builder -> builder.interfaceClass(UserService.class) + .protocol("rest")) .start(); EchoService echoService = bootstrap.getCache().get(EchoService.class); @@ -54,6 +62,5 @@ public class DubboServiceConsumerBootstrap { Thread.sleep(2000L); System.out.println(echoService.echo("Hello,World")); } - } } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceProviderBootstrap.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceProviderBootstrap.java index 6ed451124f..945d3ba79a 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceProviderBootstrap.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceProviderBootstrap.java @@ -50,29 +50,32 @@ public class DubboServiceProviderBootstrap { RegistryConfig serviceRegistry = new RegistryConfig(); serviceRegistry.setId("serviceRegistry"); - serviceRegistry.setAddress(ZookeeperRegistryCenterConfig.getConnectionAddress()+"?registry-type=service"); + serviceRegistry.setAddress(ZookeeperRegistryCenterConfig.getConnectionAddress() + "?registry-type=service"); ServiceConfig echoService = new ServiceConfig<>(); echoService.setInterface(EchoService.class.getName()); echoService.setRef(new EchoServiceImpl()); -// echoService.setRegistries(Arrays.asList(interfaceRegistry, serviceRegistry)); + // echoService.setRegistries(Arrays.asList(interfaceRegistry, serviceRegistry)); ServiceConfig userService = new ServiceConfig<>(); userService.setInterface(UserService.class.getName()); userService.setRef(new UserServiceImpl()); userService.setProtocol(restProtocol); -// userService.setRegistries(Arrays.asList(interfaceRegistry, serviceRegistry)); + // userService.setRegistries(Arrays.asList(interfaceRegistry, serviceRegistry)); ApplicationConfig applicationConfig = new ApplicationConfig("dubbo-provider-demo"); applicationConfig.setMetadataType("remote"); DubboBootstrap.getInstance() .application(applicationConfig) // Zookeeper in service registry type -// .registry("zookeeper", builder -> builder.address("zookeeper://127.0.0.1:2181?registry.type=service")) + // .registry("zookeeper", builder -> + // builder.address("zookeeper://127.0.0.1:2181?registry.type=service")) // Nacos -// .registry("zookeeper", builder -> builder.address("nacos://127.0.0.1:8848?registry.type=service")) + // .registry("zookeeper", builder -> + // builder.address("nacos://127.0.0.1:8848?registry.type=service")) .registries(Arrays.asList(interfaceRegistry, serviceRegistry)) -// .registry(RegistryBuilder.newBuilder().address("consul://127.0.0.1:8500?registry.type=service").build()) + // + // .registry(RegistryBuilder.newBuilder().address("consul://127.0.0.1:8500?registry.type=service").build()) .protocol(builder -> builder.port(-1).name("dubbo")) .metadataReport(new MetadataReportConfig(ZookeeperRegistryCenterConfig.getConnectionAddress())) .service(echoService) @@ -81,16 +84,9 @@ public class DubboServiceProviderBootstrap { .await(); } - private static void testSCCallDubbo() { + private static void testSCCallDubbo() {} - } - - private static void testDubboCallSC() { - - } - - private static void testDubboTansormation() { - - } + private static void testDubboCallSC() {} + private static void testDubboTansormation() {} } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceProviderMinimumBootstrap.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceProviderMinimumBootstrap.java index 2d705ac09c..f22154b683 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceProviderMinimumBootstrap.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceProviderMinimumBootstrap.java @@ -28,11 +28,14 @@ public class DubboServiceProviderMinimumBootstrap { public static void main(String[] args) { DubboBootstrap.getInstance() .application("dubbo-provider-demo") - .registry(builder -> builder.address(ZookeeperRegistryCenterConfig.getConnectionAddress()+"?registry-type=service")) -// .registry(builder -> builder.address("eureka://127.0.0.1:8761?registry-type=service")) + .registry(builder -> builder.address( + ZookeeperRegistryCenterConfig.getConnectionAddress() + "?registry-type=service")) + // .registry(builder -> builder.address("eureka://127.0.0.1:8761?registry-type=service")) .protocol(builder -> builder.port(-1).name("dubbo")) - .service("echo", builder -> builder.interfaceClass(EchoService.class).ref(new EchoServiceImpl())) - .service("user", builder -> builder.interfaceClass(UserService.class).ref(new UserServiceImpl())) + .service("echo", builder -> builder.interfaceClass(EchoService.class) + .ref(new EchoServiceImpl())) + .service("user", builder -> builder.interfaceClass(UserService.class) + .ref(new UserServiceImpl())) .start() .await(); } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/EtcdDubboServiceConsumerBootstrap.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/EtcdDubboServiceConsumerBootstrap.java index 8d6152443f..729211830a 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/EtcdDubboServiceConsumerBootstrap.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/EtcdDubboServiceConsumerBootstrap.java @@ -32,12 +32,18 @@ public class EtcdDubboServiceConsumerBootstrap { .application("dubbo-consumer-demo") // Zookeeper .protocol(builder -> builder.port(20887).name("dubbo")) - .registry("etcd3", builder -> builder.address("etcd3://127.0.0.1:2379?registry-type=service&subscribed-services=dubbo-provider-demo")) + .registry( + "etcd3", + builder -> builder.address( + "etcd3://127.0.0.1:2379?registry-type=service&subscribed-services=dubbo-provider-demo")) .metadataReport(new MetadataReportConfig("etcd://127.0.0.1:2379")) // Nacos -// .registry("consul", builder -> builder.address("consul://127.0.0.1:8500?registry.type=service&subscribed.services=dubbo-provider-demo").group("namespace1")) - .reference("echo", builder -> builder.interfaceClass(EchoService.class).protocol("dubbo")) - .reference("user", builder -> builder.interfaceClass(UserService.class).protocol("rest")) + // .registry("consul", builder -> + // builder.address("consul://127.0.0.1:8500?registry.type=service&subscribed.services=dubbo-provider-demo").group("namespace1")) + .reference("echo", builder -> builder.interfaceClass(EchoService.class) + .protocol("dubbo")) + .reference("user", builder -> builder.interfaceClass(UserService.class) + .protocol("rest")) .start(); EchoService echoService = bootstrap.getCache().get(EchoService.class); @@ -46,6 +52,5 @@ public class EtcdDubboServiceConsumerBootstrap { Thread.sleep(2000L); System.out.println(echoService.echo("Hello,World")); } - } } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/EtcdDubboServiceProviderBootstrap.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/EtcdDubboServiceProviderBootstrap.java index cbe7b01112..7647448fa3 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/EtcdDubboServiceProviderBootstrap.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/EtcdDubboServiceProviderBootstrap.java @@ -53,42 +53,38 @@ public class EtcdDubboServiceProviderBootstrap { ServiceConfig echoService = new ServiceConfig<>(); echoService.setInterface(EchoService.class.getName()); echoService.setRef(new EchoServiceImpl()); -// echoService.setRegistries(Arrays.asList(interfaceRegistry, serviceRegistry)); + // echoService.setRegistries(Arrays.asList(interfaceRegistry, serviceRegistry)); ServiceConfig userService = new ServiceConfig<>(); userService.setInterface(UserService.class.getName()); userService.setRef(new UserServiceImpl()); userService.setProtocol(restProtocol); -// userService.setRegistries(Arrays.asList(interfaceRegistry, serviceRegistry)); + // userService.setRegistries(Arrays.asList(interfaceRegistry, serviceRegistry)); ApplicationConfig applicationConfig = new ApplicationConfig("dubbo-provider-demo"); -// applicationConfig.setMetadataType("remote"); + // applicationConfig.setMetadataType("remote"); DubboBootstrap.getInstance() .application(applicationConfig) // Zookeeper in service registry type -// .registry("zookeeper", builder -> builder.address("zookeeper://127.0.0.1:2181?registry.type=service")) + // .registry("zookeeper", builder -> + // builder.address("zookeeper://127.0.0.1:2181?registry.type=service")) // Nacos -// .registry("zookeeper", builder -> builder.address("nacos://127.0.0.1:8848?registry.type=service")) + // .registry("zookeeper", builder -> + // builder.address("nacos://127.0.0.1:8848?registry.type=service")) .registries(Arrays.asList(interfaceRegistry, serviceRegistry)) -// .registry(RegistryBuilder.newBuilder().address("consul://127.0.0.1:8500?registry.type=service").build()) + // + // .registry(RegistryBuilder.newBuilder().address("consul://127.0.0.1:8500?registry.type=service").build()) .protocol(builder -> builder.port(-1).name("dubbo")) -// .metadataReport(new MetadataReportConfig("etcd://127.0.0.1:2379")) + // .metadataReport(new MetadataReportConfig("etcd://127.0.0.1:2379")) .service(echoService) .service(userService) .start() .await(); } - private static void testSCCallDubbo() { + private static void testSCCallDubbo() {} - } - - private static void testDubboCallSC() { - - } - - private static void testDubboTansormation() { - - } + private static void testDubboCallSC() {} + private static void testDubboTansormation() {} } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/MultiInstanceTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/MultiInstanceTest.java index 5987b8acf9..1aa652dca6 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/MultiInstanceTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/MultiInstanceTest.java @@ -44,12 +44,6 @@ import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.test.check.DubboTestChecker; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; @@ -58,6 +52,12 @@ import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_BOSS_POOL_NAME; @Disabled @@ -76,7 +76,7 @@ class MultiInstanceTest { registryConfig = new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress1()); // pre-check threads - //precheckUnclosedThreads(); + // precheckUnclosedThreads(); } @AfterEach @@ -84,7 +84,7 @@ class MultiInstanceTest { FrameworkModel.destroyAll(); // check threads - //checkUnclosedThreads(); + // checkUnclosedThreads(); } private static Map precheckUnclosedThreads() throws IOException { @@ -220,7 +220,7 @@ class MultiInstanceTest { @Test void testMultiModuleApplication() throws InterruptedException { - //SysProps.setProperty(METADATA_PUBLISH_DELAY_KEY, "100"); + // SysProps.setProperty(METADATA_PUBLISH_DELAY_KEY, "100"); String version1 = "1.0"; String version2 = "2.0"; String version3 = "3.0"; @@ -248,16 +248,16 @@ class MultiInstanceTest { serviceConfig3.setVersion(version3); providerBootstrap - .application("provider-app") - .registry(registryConfig) - .protocol(new ProtocolConfig("dubbo", -1)) - .service(serviceConfig1) - .newModule() - .service(serviceConfig2) - .endModule() - .newModule() - .service(serviceConfig3) - .endModule(); + .application("provider-app") + .registry(registryConfig) + .protocol(new ProtocolConfig("dubbo", -1)) + .service(serviceConfig1) + .newModule() + .service(serviceConfig2) + .endModule() + .newModule() + .service(serviceConfig3) + .endModule(); ApplicationModel applicationModel = providerBootstrap.getApplicationModel(); List moduleModels = applicationModel.getModuleModels(); @@ -271,22 +271,21 @@ class MultiInstanceTest { providerBootstrap.start(); - //Thread.sleep(200); + // Thread.sleep(200); // consumer app consumerBootstrap = DubboBootstrap.newInstance(); - consumerBootstrap.application("consumer-app") - .registry(registryConfig) - .reference(builder -> builder - .interfaceClass(DemoService.class) - .version(version1) - .injvm(false)) - .newModule() - .reference(builder -> builder - .interfaceClass(DemoService.class) - .version(version2) - .injvm(false)) - .endModule(); + consumerBootstrap + .application("consumer-app") + .registry(registryConfig) + .reference(builder -> builder.interfaceClass(DemoService.class) + .version(version1) + .injvm(false)) + .newModule() + .reference(builder -> builder.interfaceClass(DemoService.class) + .version(version2) + .injvm(false)) + .endModule(); consumerBootstrap.start(); DemoService referProxy1 = consumerBootstrap.getCache().get(DemoService.class.getName() + ":" + version1); @@ -330,11 +329,12 @@ class MultiInstanceTest { ProtocolConfig protocolConfig1 = new ProtocolConfig("dubbo", NetUtils.getAvailablePort()); providerBootstrap1 = DubboBootstrap.getInstance(); - providerBootstrap1.application("provider1") - .registry(new RegistryConfig(registryConfig.getAddress())) - .service(serviceConfig1) - .protocol(protocolConfig1) - .start(); + providerBootstrap1 + .application("provider1") + .registry(new RegistryConfig(registryConfig.getAddress())) + .service(serviceConfig1) + .protocol(protocolConfig1) + .start(); // save threads of provider app 1 Map lastAllThreadStackTraces = Thread.getAllStackTraces(); @@ -353,11 +353,12 @@ class MultiInstanceTest { ProtocolConfig protocolConfig2 = new ProtocolConfig("dubbo", NetUtils.getAvailablePort()); providerBootstrap2 = DubboBootstrap.newInstance(); - providerBootstrap2.application("provider2") - .registry(registryConfig2) - .service(serviceConfig2) - .protocol(protocolConfig2) - .start(); + providerBootstrap2 + .application("provider2") + .registry(registryConfig2) + .service(serviceConfig2) + .protocol(protocolConfig2) + .start(); // save threads of provider app 2 Map stackTraces2 = findNewThreads(Thread.getAllStackTraces(), stackTraces0); @@ -366,11 +367,14 @@ class MultiInstanceTest { // stop provider app 1 and check threads providerBootstrap1.stop(); - // TODO Remove ignore thread prefix of NettyServerBoss if supporting close protocol server only used by one application + // TODO Remove ignore thread prefix of NettyServerBoss if supporting close protocol server only used by one + // application // see org.apache.dubbo.config.deploy.DefaultApplicationDeployer.postDestroy - // NettyServer will close when all applications are shutdown, but not close if any application of the framework is alive, just ignore it currently - checkUnclosedThreadsOfApp(stackTraces1, "Found unclosed threads of app 1: ", new String[]{EVENT_LOOP_BOSS_POOL_NAME, "Dubbo-global-shared-handler", "Dubbo-framework"}); - + // NettyServer will close when all applications are shutdown, but not close if any application of the + // framework is alive, just ignore it currently + checkUnclosedThreadsOfApp(stackTraces1, "Found unclosed threads of app 1: ", new String[] { + EVENT_LOOP_BOSS_POOL_NAME, "Dubbo-global-shared-handler", "Dubbo-framework" + }); // stop provider app 2 and check threads providerBootstrap2.stop(); @@ -387,15 +391,20 @@ class MultiInstanceTest { } } - private Map findNewThreads(Map newAllThreadMap, Map prevThreadMap) { + private Map findNewThreads( + Map newAllThreadMap, Map prevThreadMap) { Map deltaThreadMap = new HashMap<>(newAllThreadMap); deltaThreadMap.keySet().removeAll(prevThreadMap.keySet()); // expect deltaThreadMap not contains any elements of prevThreadMap - Assertions.assertFalse(deltaThreadMap.keySet().stream().filter(thread -> prevThreadMap.containsKey(thread)).findAny().isPresent()); + Assertions.assertFalse(deltaThreadMap.keySet().stream() + .filter(thread -> prevThreadMap.containsKey(thread)) + .findAny() + .isPresent()); return deltaThreadMap; } - private void checkUnclosedThreadsOfApp(Map stackTraces1, String msg, String[] ignoredThreadPrefixes) { + private void checkUnclosedThreadsOfApp( + Map stackTraces1, String msg, String[] ignoredThreadPrefixes) { int waitTimeMs = 5000; System.out.println("Wait " + waitTimeMs + "ms to check threads of app ..."); try { @@ -447,17 +456,15 @@ class MultiInstanceTest { serviceConfig1.setRef(new DemoServiceImpl()); serviceConfig1.setVersion(version1); - //provider module 1 + // provider module 1 providerBootstrap - .application("provider-app") - .registry(registryConfig) - .protocol(new ProtocolConfig("dubbo", -1)) - .service(builder -> builder - .interfaceClass(Greeting.class) - .ref(new GreetingLocal2())) - .newModule() - .service(serviceConfig1) - .endModule(); + .application("provider-app") + .registry(registryConfig) + .protocol(new ProtocolConfig("dubbo", -1)) + .service(builder -> builder.interfaceClass(Greeting.class).ref(new GreetingLocal2())) + .newModule() + .service(serviceConfig1) + .endModule(); ApplicationModel applicationModel = providerBootstrap.getApplicationModel(); List moduleModels = applicationModel.getModuleModels(); @@ -469,22 +476,24 @@ class MultiInstanceTest { ModuleDeployer moduleDeployer1 = serviceConfig1.getScopeModel().getDeployer(); moduleDeployer1.start().get(); Assertions.assertTrue(moduleDeployer1.isStarted()); - ModuleDeployer internalModuleDeployer = applicationModel.getInternalModule().getDeployer(); + ModuleDeployer internalModuleDeployer = + applicationModel.getInternalModule().getDeployer(); Assertions.assertTrue(internalModuleDeployer.isStarted()); - FrameworkServiceRepository frameworkServiceRepository = applicationModel.getFrameworkModel().getServiceRepository(); + FrameworkServiceRepository frameworkServiceRepository = + applicationModel.getFrameworkModel().getServiceRepository(); Assertions.assertNotNull(frameworkServiceRepository.lookupExportedServiceWithoutGroup(serviceKey1)); Assertions.assertNull(frameworkServiceRepository.lookupExportedServiceWithoutGroup(serviceKey2)); Assertions.assertNull(frameworkServiceRepository.lookupExportedServiceWithoutGroup(serviceKey3)); // consumer module 1 consumerBootstrap = DubboBootstrap.newInstance(); - consumerBootstrap.application("consumer-app") - .registry(registryConfig) - .reference(builder -> builder - .interfaceClass(DemoService.class) - .version(version1) - .injvm(false)); + consumerBootstrap + .application("consumer-app") + .registry(registryConfig) + .reference(builder -> builder.interfaceClass(DemoService.class) + .version(version1) + .injvm(false)); consumerBootstrap.start(); DemoService referProxy1 = consumerBootstrap.getCache().get(serviceKey1); @@ -500,9 +509,7 @@ class MultiInstanceTest { serviceConfig2.setRef(new DemoServiceImpl()); serviceConfig2.setVersion(version2); - providerBootstrap.newModule() - .service(serviceConfig2) - .endModule(); + providerBootstrap.newModule().service(serviceConfig2).endModule(); // start provider module 2 and wait serviceConfig2.getScopeModel().getDeployer().start().get(); @@ -511,12 +518,12 @@ class MultiInstanceTest { Assertions.assertNull(frameworkServiceRepository.lookupExportedServiceWithoutGroup(serviceKey3)); // consumer module2 - ModuleModel consumerModule2 = consumerBootstrap.newModule() - .reference(builder -> builder - .interfaceClass(DemoService.class) - .version(version2) - .injvm(false)) - .getModuleModel(); + ModuleModel consumerModule2 = consumerBootstrap + .newModule() + .reference(builder -> builder.interfaceClass(DemoService.class) + .version(version2) + .injvm(false)) + .getModuleModel(); ModuleDeployer moduleDeployer2 = consumerModule2.getDeployer(); moduleDeployer2.start().get(); @@ -534,9 +541,7 @@ class MultiInstanceTest { serviceConfig3.setRef(new DemoServiceImpl()); serviceConfig3.setVersion(version3); - providerBootstrap.newModule() - .service(serviceConfig3) - .endModule(); + providerBootstrap.newModule().service(serviceConfig3).endModule(); serviceConfig3.getScopeModel().getDeployer().start().get(); Assertions.assertNull(frameworkServiceRepository.lookupExportedServiceWithoutGroup(serviceKey1)); @@ -544,16 +549,17 @@ class MultiInstanceTest { Assertions.assertNotNull(frameworkServiceRepository.lookupExportedServiceWithoutGroup(serviceKey3)); // consumer module3 - ModuleModel consumerModule3 = consumerBootstrap.newModule() - .reference(builder -> builder - .interfaceClass(DemoService.class) - .version(version3) - .injvm(false)) - .getModuleModel(); + ModuleModel consumerModule3 = consumerBootstrap + .newModule() + .reference(builder -> builder.interfaceClass(DemoService.class) + .version(version3) + .injvm(false)) + .getModuleModel(); consumerBootstrap.start(); - DemoService referProxy3 = consumerModule3.getDeployer().getReferenceCache().get(serviceKey3); + DemoService referProxy3 = + consumerModule3.getDeployer().getReferenceCache().get(serviceKey3); String result3 = referProxy3.sayName("dubbo3"); Assertions.assertEquals("say:dubbo3", result3); @@ -587,17 +593,15 @@ class MultiInstanceTest { serviceConfig1.setRef(new DemoServiceImpl()); serviceConfig1.setVersion(version1); - //provider module 1 + // provider module 1 providerBootstrap - .application("provider-app") - .registry(registryConfig) - .protocol(new ProtocolConfig("dubbo", -1)) - .service(builder -> builder - .interfaceClass(Greeting.class) - .ref(new GreetingLocal2())) - .newModule() - .service(serviceConfig1) - .endModule(); + .application("provider-app") + .registry(registryConfig) + .protocol(new ProtocolConfig("dubbo", -1)) + .service(builder -> builder.interfaceClass(Greeting.class).ref(new GreetingLocal2())) + .newModule() + .service(serviceConfig1) + .endModule(); // 1. start module1 and wait ModuleDeployer moduleDeployer1 = serviceConfig1.getScopeModel().getDeployer(); @@ -608,36 +612,38 @@ class MultiInstanceTest { ApplicationDeployer applicationDeployer = applicationModel.getDeployer(); Assertions.assertEquals(DeployState.STARTING, applicationDeployer.getState()); ModuleModel defaultModule = applicationModel.getDefaultModule(); - Assertions.assertEquals(DeployState.PENDING, defaultModule.getDeployer().getState()); + Assertions.assertEquals( + DeployState.PENDING, defaultModule.getDeployer().getState()); // 2. start application after module1 is started providerBootstrap.start(); Assertions.assertEquals(DeployState.STARTED, applicationDeployer.getState()); - Assertions.assertEquals(DeployState.STARTED, defaultModule.getDeployer().getState()); + Assertions.assertEquals( + DeployState.STARTED, defaultModule.getDeployer().getState()); // 3. add module2 and re-start application ServiceConfig serviceConfig2 = new ServiceConfig(); serviceConfig2.setInterface(DemoService.class); serviceConfig2.setRef(new DemoServiceImpl()); serviceConfig2.setVersion(version2); - ModuleModel moduleModel2 = providerBootstrap.newModule() - .service(serviceConfig2) - .getModuleModel(); + ModuleModel moduleModel2 = + providerBootstrap.newModule().service(serviceConfig2).getModuleModel(); providerBootstrap.start(); Assertions.assertEquals(DeployState.STARTED, applicationDeployer.getState()); - Assertions.assertEquals(DeployState.STARTED, moduleModel2.getDeployer().getState()); + Assertions.assertEquals( + DeployState.STARTED, moduleModel2.getDeployer().getState()); // 4. add module3 and start module3 ServiceConfig serviceConfig3 = new ServiceConfig(); serviceConfig3.setInterface(DemoService.class); serviceConfig3.setRef(new DemoServiceImpl()); serviceConfig3.setVersion(version3); - ModuleModel moduleModel3 = providerBootstrap.newModule() - .service(serviceConfig3) - .getModuleModel(); + ModuleModel moduleModel3 = + providerBootstrap.newModule().service(serviceConfig3).getModuleModel(); moduleModel3.getDeployer().start().get(); Assertions.assertEquals(DeployState.STARTED, applicationDeployer.getState()); - Assertions.assertEquals(DeployState.STARTED, moduleModel3.getDeployer().getState()); + Assertions.assertEquals( + DeployState.STARTED, moduleModel3.getDeployer().getState()); } finally { if (providerBootstrap != null) { @@ -646,7 +652,6 @@ class MultiInstanceTest { } } - @Test void testBothStartModuleAndApplicationNoWait() throws Exception { String version1 = "1.0"; @@ -667,17 +672,15 @@ class MultiInstanceTest { serviceConfig1.setRef(new DemoServiceImpl()); serviceConfig1.setVersion(version1); - //provider module 1 + // provider module 1 providerBootstrap - .application("provider-app") - .registry(registryConfig) - .protocol(new ProtocolConfig("dubbo", -1)) - .service(builder -> builder - .interfaceClass(Greeting.class) - .ref(new GreetingLocal2())) - .newModule() - .service(serviceConfig1) - .endModule(); + .application("provider-app") + .registry(registryConfig) + .protocol(new ProtocolConfig("dubbo", -1)) + .service(builder -> builder.interfaceClass(Greeting.class).ref(new GreetingLocal2())) + .newModule() + .service(serviceConfig1) + .endModule(); ApplicationModel applicationModel = providerBootstrap.getApplicationModel(); @@ -689,13 +692,15 @@ class MultiInstanceTest { ApplicationDeployer applicationDeployer = applicationModel.getDeployer(); Assertions.assertEquals(DeployState.STARTING, applicationDeployer.getState()); ModuleModel defaultModule = applicationModel.getDefaultModule(); - Assertions.assertEquals(DeployState.PENDING, defaultModule.getDeployer().getState()); + Assertions.assertEquals( + DeployState.PENDING, defaultModule.getDeployer().getState()); // 2. start application after module1 is starting providerBootstrap.start(); Assertions.assertEquals(DeployState.STARTED, applicationDeployer.getState()); Assertions.assertEquals(DeployState.STARTED, moduleDeployer1.getState()); - Assertions.assertEquals(DeployState.STARTED, defaultModule.getDeployer().getState()); + Assertions.assertEquals( + DeployState.STARTED, defaultModule.getDeployer().getState()); } finally { if (providerBootstrap != null) { @@ -717,7 +722,7 @@ class MultiInstanceTest { serviceConfig.setApplication(new ApplicationConfig("provider-app")); serviceConfig.setRegistry(new RegistryConfig(registryConfig.getAddress())); // add service - //serviceConfig.getScopeModel().getConfigManager().addService(serviceConfig); + // serviceConfig.getScopeModel().getConfigManager().addService(serviceConfig); // detect deploy events DeployEventHandler serviceDeployEventHandler = new DeployEventHandler(serviceConfig.getScopeModel()); @@ -730,14 +735,14 @@ class MultiInstanceTest { // export service and start module serviceConfig.export(); // expect internal module is started - Assertions.assertTrue(providerApplicationModel.getInternalModule().getDeployer().isStarted()); + Assertions.assertTrue( + providerApplicationModel.getInternalModule().getDeployer().isStarted()); // expect service module is starting Assertions.assertTrue(serviceDeployEventMap.containsKey(DeployState.STARTING)); // wait for service module started serviceConfig.getScopeModel().getDeployer().getStartFuture().get(); Assertions.assertTrue(serviceDeployEventMap.containsKey(DeployState.STARTED)); - // consumer app ApplicationModel consumerApplicationModel = ApplicationModel.defaultModel(); ReferenceConfig referenceConfig = new ReferenceConfig<>(); @@ -759,7 +764,8 @@ class MultiInstanceTest { // get ref proxy and start module DemoService demoService = referenceConfig.get(); // expect internal module is started - Assertions.assertTrue(consumerApplicationModel.getInternalModule().getDeployer().isStarted()); + Assertions.assertTrue( + consumerApplicationModel.getInternalModule().getDeployer().isStarted()); Assertions.assertTrue(deployEventMap.containsKey(DeployState.STARTING)); // wait for reference module started referenceConfig.getScopeModel().getDeployer().getStartFuture().get(); @@ -799,30 +805,33 @@ class MultiInstanceTest { // provider app Future providerFuture = providerBootstrap - .application("provider-app") - .registry(registryConfig) - .protocol(new ProtocolConfig("dubbo", -1)) - .service(serviceConfig) - .asyncStart(); + .application("provider-app") + .registry(registryConfig) + .protocol(new ProtocolConfig("dubbo", -1)) + .service(serviceConfig) + .asyncStart(); logger.info("provider app has start async"); // it might be started if running on fast machine. - // Assertions.assertFalse(serviceConfig.getScopeModel().getDeployer().isStarted(), "Async export seems something wrong"); + // Assertions.assertFalse(serviceConfig.getScopeModel().getDeployer().isStarted(), "Async export seems + // something wrong"); // consumer app Future consumerFuture = consumerBootstrap - .application("consumer-app") - .registry(registryConfig) - .reference(referenceConfig) - .asyncStart(); + .application("consumer-app") + .registry(registryConfig) + .reference(referenceConfig) + .asyncStart(); logger.info("consumer app has start async"); // it might be started if running on fast machine. - // Assertions.assertFalse(referenceConfig.getScopeModel().getDeployer().isStarted(), "Async refer seems something wrong"); + // Assertions.assertFalse(referenceConfig.getScopeModel().getDeployer().isStarted(), "Async refer seems + // something wrong"); // wait for provider app startup providerFuture.get(); logger.info("provider app is startup"); Assertions.assertEquals(true, serviceConfig.isExported()); - ServiceDescriptor serviceDescriptor = serviceConfig.getScopeModel().getServiceRepository().lookupService(Greeting.class.getName()); + ServiceDescriptor serviceDescriptor = + serviceConfig.getScopeModel().getServiceRepository().lookupService(Greeting.class.getName()); Assertions.assertNotNull(serviceDescriptor); // wait for consumer app startup @@ -834,7 +843,7 @@ class MultiInstanceTest { MigrationInvoker migrationInvoker = (MigrationInvoker) referenceConfig.getInvoker(); for (int i = 0; i < 10; i++) { if (((List) migrationInvoker.getDirectory().getAllInvokers()) - .stream().anyMatch(invoker -> invoker.getInterface() == Greeting.class)) { + .stream().anyMatch(invoker -> invoker.getInterface() == Greeting.class)) { break; } Thread.sleep(100); @@ -856,8 +865,7 @@ class MultiInstanceTest { if (!dubboBootstrap.getConfigManager().getApplication().isPresent()) { dubboBootstrap.application("consumer-app"); } - dubboBootstrap.registry(registryConfig) - .reference(referenceConfig); + dubboBootstrap.registry(registryConfig).reference(referenceConfig); return dubboBootstrap; } @@ -880,9 +888,7 @@ class MultiInstanceTest { if (!dubboBootstrap.getConfigManager().getApplication().isPresent()) { dubboBootstrap.application("provider-app"); } - dubboBootstrap.registry(registryConfig) - .protocol(protocol1) - .service(serviceConfig); + dubboBootstrap.registry(registryConfig).protocol(protocol1).service(serviceConfig); return dubboBootstrap; } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/NacosDubboServiceConsumerBootstrap.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/NacosDubboServiceConsumerBootstrap.java index 37262e23c2..98603b8d47 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/NacosDubboServiceConsumerBootstrap.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/NacosDubboServiceConsumerBootstrap.java @@ -39,9 +39,11 @@ public class NacosDubboServiceConsumerBootstrap { .useAsConfigCenter(true) .useAsMetadataCenter(true)) // Nacos in traditional registry type -// .registry("nacos-traditional", builder -> builder.address("nacos://127.0.0.1:8848")) - .reference("echo", builder -> builder.interfaceClass(EchoService.class).protocol("dubbo")) - .reference("user", builder -> builder.interfaceClass(UserService.class).protocol("rest")) + // .registry("nacos-traditional", builder -> builder.address("nacos://127.0.0.1:8848")) + .reference("echo", builder -> builder.interfaceClass(EchoService.class) + .protocol("dubbo")) + .reference("user", builder -> builder.interfaceClass(UserService.class) + .protocol("rest")) .start(); EchoService echoService = bootstrap.getCache().get(EchoService.class); diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/NacosDubboServiceProviderBootstrap.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/NacosDubboServiceProviderBootstrap.java index 72c597ae2f..ad5911c182 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/NacosDubboServiceProviderBootstrap.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/NacosDubboServiceProviderBootstrap.java @@ -40,11 +40,17 @@ public class NacosDubboServiceProviderBootstrap { .registry("nacos", builder -> builder.address("nacos://127.0.0.1:8848?username=nacos&password=nacos") .parameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE)) // Nacos in traditional registry type -// .registry("nacos-traditional", builder -> builder.address("nacos://127.0.0.1:8848")) + // .registry("nacos-traditional", builder -> builder.address("nacos://127.0.0.1:8848")) .protocol("dubbo", builder -> builder.port(20885).name("dubbo")) .protocol("rest", builder -> builder.port(9090).name("rest")) - .service(builder -> builder.id("echo").interfaceClass(EchoService.class).ref(new EchoServiceImpl()).protocolIds("dubbo")) - .service(builder -> builder.id("user").interfaceClass(UserService.class).ref(new UserServiceImpl()).protocolIds("rest")) + .service(builder -> builder.id("echo") + .interfaceClass(EchoService.class) + .ref(new EchoServiceImpl()) + .protocolIds("dubbo")) + .service(builder -> builder.id("user") + .interfaceClass(UserService.class) + .ref(new UserServiceImpl()) + .protocolIds("rest")) .start() .await(); } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ZookeeperDubboServiceConsumerBootstrap.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ZookeeperDubboServiceConsumerBootstrap.java index 25093206f5..657120a211 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ZookeeperDubboServiceConsumerBootstrap.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ZookeeperDubboServiceConsumerBootstrap.java @@ -38,8 +38,11 @@ public class ZookeeperDubboServiceConsumerBootstrap { .parameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE) .useAsConfigCenter(true) .useAsMetadataCenter(true)) - .reference("echo", builder -> builder.interfaceClass(EchoService.class).protocol("dubbo").services("zookeeper-dubbo-provider")) - .reference("user", builder -> builder.interfaceClass(UserService.class).protocol("rest")) + .reference("echo", builder -> builder.interfaceClass(EchoService.class) + .protocol("dubbo") + .services("zookeeper-dubbo-provider")) + .reference("user", builder -> builder.interfaceClass(UserService.class) + .protocol("rest")) .start(); EchoService echoService = bootstrap.getCache().get(EchoService.class); diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ZookeeperDubboServiceProviderBootstrap.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ZookeeperDubboServiceProviderBootstrap.java index 889aae2598..927716f813 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ZookeeperDubboServiceProviderBootstrap.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ZookeeperDubboServiceProviderBootstrap.java @@ -31,12 +31,17 @@ public class ZookeeperDubboServiceProviderBootstrap { public static void main(String[] args) { DubboBootstrap.getInstance() .application("zookeeper-dubbo-provider", app -> app.metadata(COMPOSITE_METADATA_STORAGE_TYPE)) - .registry(builder -> builder.address("127.0.0.1:2181").protocol("zookeeper") + .registry(builder -> builder.address("127.0.0.1:2181") + .protocol("zookeeper") .parameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE)) .protocol("dubbo", builder -> builder.port(-1).name("dubbo")) .protocol("rest", builder -> builder.port(8081).name("rest")) - .service("echo", builder -> builder.interfaceClass(EchoService.class).ref(new EchoServiceImpl()).protocolIds("dubbo")) - .service("user", builder -> builder.interfaceClass(UserService.class).ref(new UserServiceImpl()).protocolIds("rest")) + .service("echo", builder -> builder.interfaceClass(EchoService.class) + .ref(new EchoServiceImpl()) + .protocolIds("dubbo")) + .service("user", builder -> builder.interfaceClass(UserService.class) + .ref(new UserServiceImpl()) + .protocolIds("rest")) .start() .await(); } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractBuilderTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractBuilderTest.java index 428a93306f..c382ecf9fc 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractBuilderTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractBuilderTest.java @@ -18,12 +18,12 @@ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.AbstractConfig; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class AbstractBuilderTest { @Test @@ -112,6 +112,5 @@ class AbstractBuilderTest { } } - private static class Config extends AbstractConfig { - } -} \ No newline at end of file + private static class Config extends AbstractConfig {} +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractInterfaceBuilderTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractInterfaceBuilderTest.java index e865ea46bb..871e951c56 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractInterfaceBuilderTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractInterfaceBuilderTest.java @@ -25,12 +25,12 @@ import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; +import java.util.Collections; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Collections; - class AbstractInterfaceBuilderTest { @BeforeEach @@ -261,14 +261,27 @@ class AbstractInterfaceBuilderTest { ConfigCenterConfig configCenterConfig = new ConfigCenterConfig(); InterfaceBuilder builder = new InterfaceBuilder(); - builder.id("id").local(true).stub(false).monitor("123").proxy("mockproxyfactory").cluster("mockcluster") - .filter("mockfilter").listener("mockinvokerlistener").owner("owner").connections(1) - .layer("layer").application(applicationConfig).module(moduleConfig) - .addRegistry(registryConfig).registryIds("registryIds") - .onconnect("onconnet").ondisconnect("ondisconnect") + builder.id("id") + .local(true) + .stub(false) + .monitor("123") + .proxy("mockproxyfactory") + .cluster("mockcluster") + .filter("mockfilter") + .listener("mockinvokerlistener") + .owner("owner") + .connections(1) + .layer("layer") + .application(applicationConfig) + .module(moduleConfig) + .addRegistry(registryConfig) + .registryIds("registryIds") + .onconnect("onconnet") + .ondisconnect("ondisconnect") .metadataReportConfig(metadataReportConfig) .configCenter(configCenterConfig) - .callbacks(2).scope("scope"); + .callbacks(2) + .scope("scope"); InterfaceConfig config = builder.build(); InterfaceConfig config2 = builder.build(); @@ -313,6 +326,5 @@ class AbstractInterfaceBuilderTest { } } - private static class InterfaceConfig extends AbstractInterfaceConfig { - } -} \ No newline at end of file + private static class InterfaceConfig extends AbstractInterfaceConfig {} +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractMethodBuilderTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractMethodBuilderTest.java index fb2beb61cb..02cc967984 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractMethodBuilderTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractMethodBuilderTest.java @@ -18,12 +18,12 @@ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.AbstractMethodConfig; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class AbstractMethodBuilderTest { @Test @@ -150,8 +150,17 @@ class AbstractMethodBuilderTest { @Test void build() { MethodBuilder builder = new MethodBuilder(); - builder.id("id").timeout(1).retries(2).actives(3).loadbalance("mockloadbalance").async(true) - .sent(false).mock("mock").merger("merger").cache("cache").validation("validation") + builder.id("id") + .timeout(1) + .retries(2) + .actives(3) + .loadbalance("mockloadbalance") + .async(true) + .sent(false) + .mock("mock") + .merger("merger") + .cache("cache") + .validation("validation") .appendParameter("default.num", "one"); MethodConfig config = builder.build(); @@ -172,7 +181,6 @@ class AbstractMethodBuilderTest { Assertions.assertEquals("one", config.getParameters().get("default.num")); Assertions.assertNotSame(config, config2); - } private static class MethodBuilder extends AbstractMethodBuilder { @@ -190,6 +198,5 @@ class AbstractMethodBuilderTest { } } - private static class MethodConfig extends AbstractMethodConfig { - } -} \ No newline at end of file + private static class MethodConfig extends AbstractMethodConfig {} +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractReferenceBuilderTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractReferenceBuilderTest.java index c066a16a31..d8be34dd4c 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractReferenceBuilderTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractReferenceBuilderTest.java @@ -110,8 +110,16 @@ class AbstractReferenceBuilderTest { @Test void build() { ReferenceBuilder builder = new ReferenceBuilder(); - builder.check(true).init(false).generic(true).injvm(false).lazy(true).reconnect("reconnect").sticky(false) - .version("version").group("group").id("id"); + builder.check(true) + .init(false) + .generic(true) + .injvm(false) + .lazy(true) + .reconnect("reconnect") + .sticky(false) + .version("version") + .group("group") + .id("id"); ReferenceConfig config = builder.build(); ReferenceConfig config2 = builder.build(); @@ -145,6 +153,5 @@ class AbstractReferenceBuilderTest { } } - private static class ReferenceConfig extends AbstractReferenceConfig { - } -} \ No newline at end of file + private static class ReferenceConfig extends AbstractReferenceConfig {} +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractServiceBuilderTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractServiceBuilderTest.java index ef8a9daa48..dbd3608dfe 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractServiceBuilderTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractServiceBuilderTest.java @@ -19,11 +19,11 @@ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.AbstractServiceConfig; import org.apache.dubbo.config.ProtocolConfig; +import java.util.Collections; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.Collections; - class AbstractServiceBuilderTest { @Test @@ -194,10 +194,24 @@ class AbstractServiceBuilderTest { ProtocolConfig protocol = new ProtocolConfig(); ServiceBuilder builder = new ServiceBuilder(); - builder.version("version").group("group").deprecated(true).delay(1000).export(false).weight(1) - .document("document").dynamic(true).token("token").accesslog("accesslog") - .addProtocol(protocol).protocolIds("protocolIds").tag("tag").executes(100).register(false) - .warmup(200).serialization("serialization").id("id"); + builder.version("version") + .group("group") + .deprecated(true) + .delay(1000) + .export(false) + .weight(1) + .document("document") + .dynamic(true) + .token("token") + .accesslog("accesslog") + .addProtocol(protocol) + .protocolIds("protocolIds") + .tag("tag") + .executes(100) + .register(false) + .warmup(200) + .serialization("serialization") + .id("id"); ServiceConfig config = builder.build(); ServiceConfig config2 = builder.build(); @@ -238,7 +252,5 @@ class AbstractServiceBuilderTest { } } - private static class ServiceConfig extends AbstractServiceConfig { - - } -} \ No newline at end of file + private static class ServiceConfig extends AbstractServiceConfig {} +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ApplicationBuilderTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ApplicationBuilderTest.java index f3b5517bd5..c41be48084 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ApplicationBuilderTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ApplicationBuilderTest.java @@ -20,13 +20,13 @@ import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.RegistryConfig; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.Collections; import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class ApplicationBuilderTest { @Test @@ -247,12 +247,29 @@ class ApplicationBuilderTest { RegistryConfig registry = new RegistryConfig(); ApplicationBuilder builder = new ApplicationBuilder(); - builder.id("id").name("name").version("version").owner("owner").organization("organization").architecture("architecture") - .environment("develop").compiler("compiler").logger("log4j").monitor(monitor).isDefault(false) - .dumpDirectory("dumpDirectory").qosEnable(true).qosPort(8080).qosAcceptForeignIp(false) - .shutwait("shutwait").registryIds("registryIds").addRegistry(registry) - .appendParameter("default.num", "one").metadataServicePort(12345) - .livenessProbe("liveness").readinessProbe("readiness").startupProbe("startup"); + builder.id("id") + .name("name") + .version("version") + .owner("owner") + .organization("organization") + .architecture("architecture") + .environment("develop") + .compiler("compiler") + .logger("log4j") + .monitor(monitor) + .isDefault(false) + .dumpDirectory("dumpDirectory") + .qosEnable(true) + .qosPort(8080) + .qosAcceptForeignIp(false) + .shutwait("shutwait") + .registryIds("registryIds") + .addRegistry(registry) + .appendParameter("default.num", "one") + .metadataServicePort(12345) + .livenessProbe("liveness") + .readinessProbe("readiness") + .startupProbe("startup"); ApplicationConfig config = builder.build(); ApplicationConfig config2 = builder.build(); @@ -284,4 +301,4 @@ class ApplicationBuilderTest { Assertions.assertNotSame(config, config2); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ArgumentBuilderTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ArgumentBuilderTest.java index 1b6638dd76..3fe6d31c5e 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ArgumentBuilderTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ArgumentBuilderTest.java @@ -60,4 +60,4 @@ class ArgumentBuilderTest { Assertions.assertNotSame(argument1, argument2); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ConfigCenterBuilderTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ConfigCenterBuilderTest.java index e07db36fbc..802e3d64bc 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ConfigCenterBuilderTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ConfigCenterBuilderTest.java @@ -18,12 +18,12 @@ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.ConfigCenterConfig; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class ConfigCenterBuilderTest { @Test @@ -139,10 +139,20 @@ class ConfigCenterBuilderTest { @Test void build() { ConfigCenterBuilder builder = new ConfigCenterBuilder(); - builder.check(true).protocol("protocol").address("address").appConfigFile("appConfigFile") - .cluster("cluster").configFile("configFile").group("group").highestPriority(false) - .namespace("namespace").password("password").timeout(1000L).username("usernama") - .appendParameter("default.num", "one").id("id"); + builder.check(true) + .protocol("protocol") + .address("address") + .appConfigFile("appConfigFile") + .cluster("cluster") + .configFile("configFile") + .group("group") + .highestPriority(false) + .namespace("namespace") + .password("password") + .timeout(1000L) + .username("usernama") + .appendParameter("default.num", "one") + .id("id"); ConfigCenterConfig config = builder.build(); ConfigCenterConfig config2 = builder.build(); @@ -165,4 +175,4 @@ class ConfigCenterBuilderTest { Assertions.assertNotSame(config, config2); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ConsumerBuilderTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ConsumerBuilderTest.java index 607388c7b2..7aa88fcd8e 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ConsumerBuilderTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ConsumerBuilderTest.java @@ -75,8 +75,14 @@ class ConsumerBuilderTest { @Test void build() { ConsumerBuilder builder = new ConsumerBuilder(); - builder.isDefault(true).client("client").threadPool("threadPool").coreThreads(10).threads(100).queues(200) - .shareConnections(300).id("id"); + builder.isDefault(true) + .client("client") + .threadPool("threadPool") + .coreThreads(10) + .threads(100) + .queues(200) + .shareConnections(300) + .id("id"); ConsumerConfig config = builder.build(); ConsumerConfig config2 = builder.build(); @@ -91,4 +97,4 @@ class ConsumerBuilderTest { Assertions.assertEquals(300, config.getShareconnections()); Assertions.assertNotSame(config, config2); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/MetadataReportBuilderTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/MetadataReportBuilderTest.java index 9e3e718c6a..11692fc5a9 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/MetadataReportBuilderTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/MetadataReportBuilderTest.java @@ -18,12 +18,12 @@ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.MetadataReportConfig; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class MetadataReportBuilderTest { @Test @@ -126,9 +126,17 @@ class MetadataReportBuilderTest { @Test void build() { MetadataReportBuilder builder = new MetadataReportBuilder(); - builder.address("address").username("username").password("password").timeout(1000).group("group") - .retryTimes(1).retryPeriod(2).cycleReport(true).syncReport(false) - .appendParameter("default.num", "one").id("id"); + builder.address("address") + .username("username") + .password("password") + .timeout(1000) + .group("group") + .retryTimes(1) + .retryPeriod(2) + .cycleReport(true) + .syncReport(false) + .appendParameter("default.num", "one") + .id("id"); MetadataReportConfig config = builder.build(); MetadataReportConfig config2 = builder.build(); @@ -147,4 +155,4 @@ class MetadataReportBuilderTest { Assertions.assertEquals("id", config.getId()); Assertions.assertNotSame(config, config2); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/MethodBuilderTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/MethodBuilderTest.java index 9196c48210..2c0855ac40 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/MethodBuilderTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/MethodBuilderTest.java @@ -19,11 +19,11 @@ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.ArgumentConfig; import org.apache.dubbo.config.MethodConfig; +import java.util.Collections; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.Collections; - class MethodBuilderTest { @Test @@ -160,10 +160,23 @@ class MethodBuilderTest { void build() { ArgumentConfig argument = new ArgumentConfig(); MethodBuilder builder = new MethodBuilder(); - builder.name("name").stat(1).retry(true).reliable(false).executes(2).deprecated(true).sticky(false) - .isReturn(true).oninvoke("on-invoke-object").oninvokeMethod("on-invoke-method").service("service") - .onreturn("on-return-object").onreturnMethod("on-return-method").serviceId("serviceId") - .onthrow("on-throw-object").onthrowMethod("on-throw-method").addArgument(argument); + builder.name("name") + .stat(1) + .retry(true) + .reliable(false) + .executes(2) + .deprecated(true) + .sticky(false) + .isReturn(true) + .oninvoke("on-invoke-object") + .oninvokeMethod("on-invoke-method") + .service("service") + .onreturn("on-return-object") + .onreturnMethod("on-return-method") + .serviceId("serviceId") + .onthrow("on-throw-object") + .onthrowMethod("on-throw-method") + .addArgument(argument); MethodConfig config = builder.build(); MethodConfig config2 = builder.build(); @@ -186,4 +199,4 @@ class MethodBuilderTest { Assertions.assertEquals("serviceId", config.getServiceId()); Assertions.assertNotSame(config, config2); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ModuleBuilderTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ModuleBuilderTest.java index bbf7d2eb93..03f48a06d2 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ModuleBuilderTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ModuleBuilderTest.java @@ -20,11 +20,11 @@ import org.apache.dubbo.config.ModuleConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.RegistryConfig; +import java.util.Collections; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.Collections; - class ModuleBuilderTest { @Test @@ -94,8 +94,13 @@ class ModuleBuilderTest { MonitorConfig monitor = new MonitorConfig(); ModuleBuilder builder = new ModuleBuilder(); - builder.name("name").version("version").owner("owner").organization("organization").addRegistry(registry) - .monitor(monitor).isDefault(false); + builder.name("name") + .version("version") + .owner("owner") + .organization("organization") + .addRegistry(registry) + .monitor(monitor) + .isDefault(false); ModuleConfig config = builder.build(); ModuleConfig config2 = builder.build(); @@ -109,4 +114,4 @@ class ModuleBuilderTest { Assertions.assertFalse(config.isDefault()); Assertions.assertNotSame(config, config2); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/MonitorBuilderTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/MonitorBuilderTest.java index f63fd39d42..aedbb08700 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/MonitorBuilderTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/MonitorBuilderTest.java @@ -18,12 +18,12 @@ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.MonitorConfig; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class MonitorBuilderTest { @Test @@ -111,9 +111,16 @@ class MonitorBuilderTest { @Test void build() { MonitorBuilder builder = new MonitorBuilder(); - builder.protocol("protocol").address("address").group("group").interval("interval").isDefault(true) - .password("password").username("username").version("version") - .appendParameter("default.num", "one").id("id"); + builder.protocol("protocol") + .address("address") + .group("group") + .interval("interval") + .isDefault(true) + .password("password") + .username("username") + .version("version") + .appendParameter("default.num", "one") + .id("id"); MonitorConfig config = builder.build(); MonitorConfig config2 = builder.build(); @@ -131,4 +138,4 @@ class MonitorBuilderTest { Assertions.assertEquals("id", config.getId()); Assertions.assertNotSame(config, config2); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ProtocolBuilderTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ProtocolBuilderTest.java index 331d228f72..b5867f19c7 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ProtocolBuilderTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ProtocolBuilderTest.java @@ -18,12 +18,12 @@ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.ProtocolConfig; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class ProtocolBuilderTest { @Test @@ -286,14 +286,39 @@ class ProtocolBuilderTest { @Test void build() { ProtocolBuilder builder = new ProtocolBuilder(); - builder.name("name").host("host").port(8080).contextpath("contextpath").threadpool("mockthreadpool") - .corethreads(1).threads(2).iothreads(3).queues(4).accepts(5).codec("mockcodec") - .serialization("serialization").charset("utf-8").payload(6).buffer(1024).heartbeat(1000) - .accesslog("accesslog").transporter("mocktransporter").exchanger("mockexchanger") - .dispatcher("mockdispatcher").networker("networker").server("server").client("client") - .telnet("mocktelnethandler").prompt("prompt").status("mockstatuschecker").register(true).keepAlive(false) - .optimizer("optimizer").extension("extension").isDefault(true) - .appendParameter("default.num", "one").id("id"); + builder.name("name") + .host("host") + .port(8080) + .contextpath("contextpath") + .threadpool("mockthreadpool") + .corethreads(1) + .threads(2) + .iothreads(3) + .queues(4) + .accepts(5) + .codec("mockcodec") + .serialization("serialization") + .charset("utf-8") + .payload(6) + .buffer(1024) + .heartbeat(1000) + .accesslog("accesslog") + .transporter("mocktransporter") + .exchanger("mockexchanger") + .dispatcher("mockdispatcher") + .networker("networker") + .server("server") + .client("client") + .telnet("mocktelnethandler") + .prompt("prompt") + .status("mockstatuschecker") + .register(true) + .keepAlive(false) + .optimizer("optimizer") + .extension("extension") + .isDefault(true) + .appendParameter("default.num", "one") + .id("id"); ProtocolConfig config = builder.build(); ProtocolConfig config2 = builder.build(); @@ -334,4 +359,4 @@ class ProtocolBuilderTest { Assertions.assertEquals("id", config.getId()); Assertions.assertNotSame(config, config2); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ProviderBuilderTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ProviderBuilderTest.java index f3cc1a6b22..06a8f68b51 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ProviderBuilderTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ProviderBuilderTest.java @@ -187,12 +187,30 @@ class ProviderBuilderTest { @Test void build() { ProviderBuilder builder = new ProviderBuilder(); - builder.host("host").port(8080).contextPath("contextpath").threadPool("mockthreadpool") - .threads(2).ioThreads(3).queues(4).accepts(5).codec("mockcodec") - .charset("utf-8").payload(6).buffer(1024).transporter("mocktransporter").exchanger("mockexchanger") - .dispatcher("mockdispatcher").networker("networker").server("server").client("client") - .telnet("mocktelnethandler").prompt("prompt").status("mockstatuschecker").wait(Integer.valueOf(1000)) - .isDefault(true).id("id"); + builder.host("host") + .port(8080) + .contextPath("contextpath") + .threadPool("mockthreadpool") + .threads(2) + .ioThreads(3) + .queues(4) + .accepts(5) + .codec("mockcodec") + .charset("utf-8") + .payload(6) + .buffer(1024) + .transporter("mocktransporter") + .exchanger("mockexchanger") + .dispatcher("mockdispatcher") + .networker("networker") + .server("server") + .client("client") + .telnet("mocktelnethandler") + .prompt("prompt") + .status("mockstatuschecker") + .wait(Integer.valueOf(1000)) + .isDefault(true) + .id("id"); ProviderConfig config = builder.build(); ProviderConfig config2 = builder.build(); @@ -223,4 +241,4 @@ class ProviderBuilderTest { Assertions.assertEquals("id", config.getId()); Assertions.assertNotSame(config, config2); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ReferenceBuilderTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ReferenceBuilderTest.java index 4d11ef4314..5deba4d4ee 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ReferenceBuilderTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ReferenceBuilderTest.java @@ -21,11 +21,11 @@ import org.apache.dubbo.config.MethodConfig; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.api.DemoService; +import java.util.Collections; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.Collections; - import static org.apache.dubbo.common.utils.CollectionUtils.ofSet; class ReferenceBuilderTest { @@ -34,7 +34,8 @@ class ReferenceBuilderTest { void interfaceName() { ReferenceBuilder builder = new ReferenceBuilder(); builder.interfaceName(DemoService.class.getName()); - Assertions.assertEquals("org.apache.dubbo.config.api.DemoService", builder.build().getInterface()); + Assertions.assertEquals( + "org.apache.dubbo.config.api.DemoService", builder.build().getInterface()); } @Test @@ -122,4 +123,4 @@ class ReferenceBuilderTest { Assertions.assertEquals(1, config.getMethods().size()); Assertions.assertNotSame(config, config2); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/RegistryBuilderTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/RegistryBuilderTest.java index eab629d0a5..05aa52fc8f 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/RegistryBuilderTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/RegistryBuilderTest.java @@ -18,12 +18,12 @@ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.RegistryConfig; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class RegistryBuilderTest { @Test @@ -216,11 +216,30 @@ class RegistryBuilderTest { @Test void build() { RegistryBuilder builder = new RegistryBuilder(); - builder.address("address").username("username").password("password").port(8080).protocol("protocol") - .transporter("transporter").server("server").client("client").cluster("cluster").group("group") - .version("version").timeout(1000).session(2000).file("file").wait(Integer.valueOf(10)).isCheck(true) - .isDynamic(false).register(true).subscribe(false).isDefault(true).simplified(false).extraKeys("A") - .parameter("default.num", "one").id("id"); + builder.address("address") + .username("username") + .password("password") + .port(8080) + .protocol("protocol") + .transporter("transporter") + .server("server") + .client("client") + .cluster("cluster") + .group("group") + .version("version") + .timeout(1000) + .session(2000) + .file("file") + .wait(Integer.valueOf(10)) + .isCheck(true) + .isDynamic(false) + .register(true) + .subscribe(false) + .isDefault(true) + .simplified(false) + .extraKeys("A") + .parameter("default.num", "one") + .id("id"); RegistryConfig config = builder.build(); RegistryConfig config2 = builder.build(); @@ -252,4 +271,4 @@ class RegistryBuilderTest { Assertions.assertEquals("id", config.getId()); Assertions.assertNotSame(config, config2); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ServiceBuilderTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ServiceBuilderTest.java index cb22a45cdf..db2ed60a58 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ServiceBuilderTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ServiceBuilderTest.java @@ -20,11 +20,11 @@ import org.apache.dubbo.config.MethodConfig; import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.ServiceConfig; +import java.util.Collections; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.Collections; - import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_BEAN; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_DEFAULT; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; @@ -91,22 +91,22 @@ class ServiceBuilderTest { builder.generic("illegal").build(); }); } -// -// @Test -// public void Mock() throws Exception { -// Assertions.assertThrows(IllegalArgumentException.class, () -> { -// ServiceBuilder builder = new ServiceBuilder(); -// builder.mock("true"); -// }); -// } -// -// @Test -// public void Mock1() throws Exception { -// Assertions.assertThrows(IllegalArgumentException.class, () -> { -// ServiceBuilder builder = new ServiceBuilder(); -// builder.mock(true); -// }); -// } + // + // @Test + // public void Mock() throws Exception { + // Assertions.assertThrows(IllegalArgumentException.class, () -> { + // ServiceBuilder builder = new ServiceBuilder(); + // builder.mock("true"); + // }); + // } + // + // @Test + // public void Mock1() throws Exception { + // Assertions.assertThrows(IllegalArgumentException.class, () -> { + // ServiceBuilder builder = new ServiceBuilder(); + // builder.mock(true); + // }); + // } @Test void build() { @@ -114,7 +114,10 @@ class ServiceBuilderTest { ProviderConfig provider = new ProviderConfig(); ServiceBuilder builder = new ServiceBuilder(); - builder.path("path").addMethod(method).provider(provider).providerIds("providerIds") + builder.path("path") + .addMethod(method) + .provider(provider) + .providerIds("providerIds") .generic(GENERIC_SERIALIZATION_DEFAULT); ServiceConfig config = builder.build(); @@ -128,4 +131,4 @@ class ServiceBuilderTest { Assertions.assertEquals(1, config.getMethods().size()); Assertions.assertNotSame(config, config2); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/compatible/DubboInterfaceConsumerBootstrap.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/compatible/DubboInterfaceConsumerBootstrap.java index d9c9c57287..6e559fbea0 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/compatible/DubboInterfaceConsumerBootstrap.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/compatible/DubboInterfaceConsumerBootstrap.java @@ -39,9 +39,12 @@ public class DubboInterfaceConsumerBootstrap { // Zookeeper .registry(interfaceRegistry) // Nacos -// .registry("consul", builder -> builder.address("consul://127.0.0.1:8500?registry.type=service&subscribed.services=dubbo-provider-demo")) - .reference("echo", builder -> builder.interfaceClass(EchoService.class).protocol("dubbo")) - .reference("user", builder -> builder.interfaceClass(UserService.class).protocol("rest")) + // .registry("consul", builder -> + // builder.address("consul://127.0.0.1:8500?registry.type=service&subscribed.services=dubbo-provider-demo")) + .reference("echo", builder -> builder.interfaceClass(EchoService.class) + .protocol("dubbo")) + .reference("user", builder -> builder.interfaceClass(UserService.class) + .protocol("rest")) .start() .await(); @@ -53,6 +56,5 @@ public class DubboInterfaceConsumerBootstrap { System.out.println(echoService.echo("Hello,World")); System.out.println(userService.getUser(1L)); } - } } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/User.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/User.java index cfd52e2457..a1586f9955 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/User.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/User.java @@ -1,25 +1,21 @@ /* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. + * 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 org.apache.dubbo.config.bootstrap.rest; -import org.codehaus.jackson.annotate.JsonProperty; - import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @@ -27,8 +23,11 @@ import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; + import java.io.Serializable; +import org.codehaus.jackson.annotate.JsonProperty; + @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class User implements Serializable { @@ -43,8 +42,7 @@ public class User implements Serializable { @Size(min = 6, max = 50) private String name; - public User() { - } + public User() {} public User(Long id, String name) { this.id = id; @@ -69,9 +67,6 @@ public class User implements Serializable { @Override public String toString() { - return "User (" + - "id=" + id + - ", name='" + name + '\'' + - ')'; + return "User (" + "id=" + id + ", name='" + name + '\'' + ')'; } } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/UserService.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/UserService.java index fa5b7ae38d..53400f292e 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/UserService.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/UserService.java @@ -1,30 +1,23 @@ /* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. + * 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 org.apache.dubbo.config.bootstrap.rest; - import org.apache.dubbo.rpc.protocol.rest.support.ContentType; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; - import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; @@ -32,6 +25,10 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; + @Path("users") @Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) @Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8}) diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/UserServiceImpl.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/UserServiceImpl.java index 8cb0bd0d33..6d24d6206d 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/UserServiceImpl.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/UserServiceImpl.java @@ -1,20 +1,18 @@ /* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. + * 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 org.apache.dubbo.config.bootstrap.rest; @@ -28,5 +26,4 @@ public class UserServiceImpl implements UserService { public User getUser(Long id) { return new User(id, "username" + id); } - } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/cache/CacheService.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/cache/CacheService.java index 7696b24e70..abf553d4f8 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/cache/CacheService.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/cache/CacheService.java @@ -22,5 +22,4 @@ package org.apache.dubbo.config.cache; public interface CacheService { String findCache(String id); - } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/cache/CacheServiceImpl.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/cache/CacheServiceImpl.java index 14e9ee7d8a..254917ecd5 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/cache/CacheServiceImpl.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/cache/CacheServiceImpl.java @@ -28,5 +28,4 @@ public class CacheServiceImpl implements CacheService { public String findCache(String id) { return "request: " + id + ", response: " + i.getAndIncrement(); } - } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/cache/CacheTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/cache/CacheTest.java index 839b8d3c15..c264fe1a83 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/cache/CacheTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/cache/CacheTest.java @@ -32,14 +32,14 @@ import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.RpcInvocation; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.Arrays; import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -55,7 +55,7 @@ class CacheTest { @AfterEach public void tearDown() { -// ApplicationModel.defaultModel().getConfigManager().clear(); + // ApplicationModel.defaultModel().getConfigManager().clear(); } private void testCache(String type) throws Exception { @@ -129,16 +129,25 @@ class CacheTest { @Test void testCacheProvider() { - CacheFactory cacheFactory = ExtensionLoader.getExtensionLoader(CacheFactory.class).getAdaptiveExtension(); + CacheFactory cacheFactory = + ExtensionLoader.getExtensionLoader(CacheFactory.class).getAdaptiveExtension(); Map parameters = new HashMap(); parameters.put("findCache.cache", "threadlocal"); - URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 29582, "org.apache.dubbo.config.cache.CacheService", parameters); + URL url = new ServiceConfigURL( + "dubbo", "127.0.0.1", 29582, "org.apache.dubbo.config.cache.CacheService", parameters); - Invocation invocation = new RpcInvocation("findCache", CacheService.class.getName(), "", new Class[]{String.class}, new String[]{"0"}, null, null, null); + Invocation invocation = new RpcInvocation( + "findCache", + CacheService.class.getName(), + "", + new Class[] {String.class}, + new String[] {"0"}, + null, + null, + null); Cache cache = cacheFactory.getCache(url, invocation); assertTrue(cache instanceof ThreadLocalCache); } - } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployerTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployerTest.java index 99f94ebe49..a4ac9c59d8 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployerTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployerTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config.deploy; import org.apache.dubbo.common.utils.Assert; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/AbstractRegistryCenterExporterListener.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/AbstractRegistryCenterExporterListener.java index b62c15f4b6..e37f92da0c 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/AbstractRegistryCenterExporterListener.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/AbstractRegistryCenterExporterListener.java @@ -63,9 +63,9 @@ public abstract class AbstractRegistryCenterExporterListener implements Exporter exportedExporters.add(exporter); return; } - FilterChainBuilder.CallbackRegistrationInvoker callbackRegistrationInvoker = (FilterChainBuilder.CallbackRegistrationInvoker) invoker; - if (callbackRegistrationInvoker == null || - callbackRegistrationInvoker.getInterface() != getInterface()) { + FilterChainBuilder.CallbackRegistrationInvoker callbackRegistrationInvoker = + (FilterChainBuilder.CallbackRegistrationInvoker) invoker; + if (callbackRegistrationInvoker == null || callbackRegistrationInvoker.getInterface() != getInterface()) { return; } exportedExporters.add(exporter); @@ -104,7 +104,8 @@ public abstract class AbstractRegistryCenterExporterListener implements Exporter /** * Use reflection to obtain {@link Filter} */ - private FilterChainBuilder.CopyOfFilterChainNode getFilterChainNode(FilterChainBuilder.CallbackRegistrationInvoker callbackRegistrationInvoker) { + private FilterChainBuilder.CopyOfFilterChainNode getFilterChainNode( + FilterChainBuilder.CallbackRegistrationInvoker callbackRegistrationInvoker) { if (callbackRegistrationInvoker != null) { Field field = null; try { @@ -138,7 +139,8 @@ public abstract class AbstractRegistryCenterExporterListener implements Exporter /** * Use reflection to obtain {@link FilterChainBuilder.CopyOfFilterChainNode} */ - private FilterChainBuilder.CopyOfFilterChainNode getNextNode(FilterChainBuilder.CopyOfFilterChainNode filterChainNode) { + private FilterChainBuilder.CopyOfFilterChainNode getNextNode( + FilterChainBuilder.CopyOfFilterChainNode filterChainNode) { if (filterChainNode != null) { Field field = null; try { diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/AbstractRegistryCenterServiceListener.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/AbstractRegistryCenterServiceListener.java index c898c91860..337d68d24c 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/AbstractRegistryCenterServiceListener.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/AbstractRegistryCenterServiceListener.java @@ -39,7 +39,7 @@ public abstract class AbstractRegistryCenterServiceListener implements ServiceLi */ @Override public void exported(ServiceConfig sc) { - //All exported services will be added + // All exported services will be added if (sc.getInterfaceClass() == getInterface()) { exportedServices.add(sc); } @@ -50,7 +50,7 @@ public abstract class AbstractRegistryCenterServiceListener implements ServiceLi */ @Override public void unexported(ServiceConfig sc) { - //remove the exported services. + // remove the exported services. exportedServices.remove(sc); } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/IntegrationTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/IntegrationTest.java index 2e3067affa..a185231fb8 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/IntegrationTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/IntegrationTest.java @@ -25,4 +25,4 @@ public interface IntegrationTest { * Run the integration testcases. */ void integrate(); -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/AbstractStorage.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/AbstractStorage.java index f113cde98f..a12f4cfb32 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/AbstractStorage.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/AbstractStorage.java @@ -28,7 +28,6 @@ public abstract class AbstractStorage implements Storage { private Map storage = new ConcurrentHashMap<>(); - /** * Generate the key for storage * diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/Storage.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/Storage.java index cf2d870a06..6a864e030f 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/Storage.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/Storage.java @@ -20,7 +20,7 @@ package org.apache.dubbo.config.integration.multiple; * This interface to store the given type instance in multiple registry center. * @param The type to store */ -public interface Storage { +public interface Storage { /** * Gets the stored instance with the given host and port. diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportmetadata/MultipleRegistryCenterExportMetadataIntegrationTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportmetadata/MultipleRegistryCenterExportMetadataIntegrationTest.java index 8f25f3c195..0cc1e25b6d 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportmetadata/MultipleRegistryCenterExportMetadataIntegrationTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportmetadata/MultipleRegistryCenterExportMetadataIntegrationTest.java @@ -30,6 +30,9 @@ import org.apache.dubbo.rpc.ExporterListener; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; +import java.io.IOException; +import java.util.List; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -37,9 +40,6 @@ import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.util.List; - import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; /** @@ -47,7 +47,8 @@ import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; */ class MultipleRegistryCenterExportMetadataIntegrationTest implements IntegrationTest { - private static final Logger logger = LoggerFactory.getLogger(MultipleRegistryCenterExportMetadataIntegrationTest.class); + private static final Logger logger = + LoggerFactory.getLogger(MultipleRegistryCenterExportMetadataIntegrationTest.class); /** * Define the provider application name. @@ -78,7 +79,6 @@ class MultipleRegistryCenterExportMetadataIntegrationTest implements Integration */ private MultipleRegistryCenterExportMetadataExporterListener exporterListener; - @BeforeEach public void setUp() throws Exception { logger.info(getClass().getSimpleName() + " testcase is beginning..."); @@ -92,11 +92,11 @@ class MultipleRegistryCenterExportMetadataIntegrationTest implements Integration // initailize bootstrap DubboBootstrap.getInstance() - .application(new ApplicationConfig(PROVIDER_APPLICATION_NAME)) - .protocol(new ProtocolConfig(PROTOCOL_NAME)) - .service(serviceConfig) - .registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress1())) - .registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress2())); + .application(new ApplicationConfig(PROVIDER_APPLICATION_NAME)) + .protocol(new ProtocolConfig(PROTOCOL_NAME)) + .service(serviceConfig) + .registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress1())) + .registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress2())); } /** @@ -111,8 +111,10 @@ class MultipleRegistryCenterExportMetadataIntegrationTest implements Integration */ private void beforeExport() { // ---------------initialize--------------- // - serviceListener = (MultipleRegistryCenterExportMetadataServiceListener) ExtensionLoader.getExtensionLoader(ServiceListener.class).getExtension(SPI_NAME); - exporterListener = (MultipleRegistryCenterExportMetadataExporterListener) ExtensionLoader.getExtensionLoader(ExporterListener.class).getExtension(SPI_NAME); + serviceListener = (MultipleRegistryCenterExportMetadataServiceListener) + ExtensionLoader.getExtensionLoader(ServiceListener.class).getExtension(SPI_NAME); + exporterListener = (MultipleRegistryCenterExportMetadataExporterListener) + ExtensionLoader.getExtensionLoader(ExporterListener.class).getExtension(SPI_NAME); // ---------------checkpoints--------------- // // There is nothing in ServiceListener @@ -147,8 +149,8 @@ class MultipleRegistryCenterExportMetadataIntegrationTest implements Integration // The metadata service is only one Assertions.assertEquals(serviceListener.getExportedServices().size(), 1); // The exported service is MetadataService - Assertions.assertEquals(serviceListener.getExportedServices().get(0).getInterfaceClass(), - MetadataService.class); + Assertions.assertEquals( + serviceListener.getExportedServices().get(0).getInterfaceClass(), MetadataService.class); // The MetadataService is exported Assertions.assertTrue(serviceListener.getExportedServices().get(0).isExported()); // FIXME there may be something wrong with the whole process of diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderFilter.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderFilter.java index daf839bc3b..b00bae913f 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderFilter.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderFilter.java @@ -25,7 +25,7 @@ import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; @Activate(group = CommonConstants.PROVIDER, order = 10001) -public class MultipleRegistryCenterExportProviderFilter implements Filter,Filter.Listener { +public class MultipleRegistryCenterExportProviderFilter implements Filter, Filter.Listener { /** * The filter is called or not diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderIntegrationTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderIntegrationTest.java index d2f9b7ee2d..10395824f5 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderIntegrationTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderIntegrationTest.java @@ -35,6 +35,8 @@ import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; +import java.io.IOException; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -42,14 +44,13 @@ import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; - /** * The testcases are only for checking the core process of exporting provider. */ class MultipleRegistryCenterExportProviderIntegrationTest implements IntegrationTest { - private static final Logger logger = LoggerFactory.getLogger(MultipleRegistryCenterExportProviderIntegrationTest.class); + private static final Logger logger = + LoggerFactory.getLogger(MultipleRegistryCenterExportProviderIntegrationTest.class); /** * Define the provider application name. @@ -107,11 +108,11 @@ class MultipleRegistryCenterExportProviderIntegrationTest implements Integration // initailize bootstrap DubboBootstrap.getInstance() - .application(new ApplicationConfig(PROVIDER_APPLICATION_NAME)) - .protocol(new ProtocolConfig(PROTOCOL_NAME, PROTOCOL_PORT)) - .service(serviceConfig) - .registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress1())) - .registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress2())); + .application(new ApplicationConfig(PROVIDER_APPLICATION_NAME)) + .protocol(new ProtocolConfig(PROTOCOL_NAME, PROTOCOL_PORT)) + .service(serviceConfig) + .registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress1())) + .registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress2())); } /** @@ -124,18 +125,15 @@ class MultipleRegistryCenterExportProviderIntegrationTest implements Integration * */ private void beforeExport() { - registryProtocolListener = (MultipleRegistryCenterExportProviderRegistryProtocolListener) ExtensionLoader - .getExtensionLoader(RegistryProtocolListener.class) - .getExtension(SPI_NAME); - exporterListener = (MultipleRegistryCenterExportProviderExporterListener) ExtensionLoader - .getExtensionLoader(ExporterListener.class) - .getExtension(SPI_NAME); - filter = (MultipleRegistryCenterExportProviderFilter) ExtensionLoader - .getExtensionLoader(Filter.class) - .getExtension(SPI_NAME); - serviceListener = (MultipleRegistryCenterExportProviderServiceListener) ExtensionLoader - .getExtensionLoader(ServiceListener.class) - .getExtension(SPI_NAME); + registryProtocolListener = (MultipleRegistryCenterExportProviderRegistryProtocolListener) + ExtensionLoader.getExtensionLoader(RegistryProtocolListener.class) + .getExtension(SPI_NAME); + exporterListener = (MultipleRegistryCenterExportProviderExporterListener) + ExtensionLoader.getExtensionLoader(ExporterListener.class).getExtension(SPI_NAME); + filter = (MultipleRegistryCenterExportProviderFilter) + ExtensionLoader.getExtensionLoader(Filter.class).getExtension(SPI_NAME); + serviceListener = (MultipleRegistryCenterExportProviderServiceListener) + ExtensionLoader.getExtensionLoader(ServiceListener.class).getExtension(SPI_NAME); // ---------------checkpoints--------------- // // ServiceConfig isn't exported Assertions.assertFalse(serviceConfig.isExported()); @@ -180,8 +178,9 @@ class MultipleRegistryCenterExportProviderIntegrationTest implements Integration // The exported service is only one Assertions.assertEquals(serviceListener.getExportedServices().size(), 1); // The exported service is MultipleRegistryCenterExportProviderService - Assertions.assertEquals(serviceListener.getExportedServices().get(0).getInterfaceClass(), - MultipleRegistryCenterExportProviderService.class); + Assertions.assertEquals( + serviceListener.getExportedServices().get(0).getInterfaceClass(), + MultipleRegistryCenterExportProviderService.class); // The MultipleRegistryCenterExportProviderService is exported Assertions.assertTrue(serviceListener.getExportedServices().get(0).isExported()); // The exported exporter are three @@ -197,7 +196,8 @@ class MultipleRegistryCenterExportProviderIntegrationTest implements Integration // The best way to verify this issue is to check if the exported service (or provider) // has been registered in the path of /dubbo/mapping/**** // FixME We should check if the exported service (or provider) has been registered in multiple registry centers. - // However, the registered exporter are override in RegistryProtocol#export, so there is only the first registry center + // However, the registered exporter are override in RegistryProtocol#export, so there is only the first + // registry center // that can register the mapping relationship. This is really a problem that needs to be fix. // Now, we are discussing the solution for this issue. // For this testcase, we still check the only exported service (or provider). @@ -206,13 +206,15 @@ class MultipleRegistryCenterExportProviderIntegrationTest implements Integration // registryKey: the registryKey is the default cluster, CommonConstants.DEFAULT_KEY // key: The exported interface's name // group: the group is "mapping", ServiceNameMapping.DEFAULT_MAPPING_GROUP - ConfigItem configItem = ApplicationModel.defaultModel().getBeanFactory().getBean(MetadataReportInstance.class).getMetadataReport(CommonConstants.DEFAULT_KEY) - .getConfigItem(serviceConfig.getInterface() - , ServiceNameMapping.DEFAULT_MAPPING_GROUP); + ConfigItem configItem = ApplicationModel.defaultModel() + .getBeanFactory() + .getBean(MetadataReportInstance.class) + .getMetadataReport(CommonConstants.DEFAULT_KEY) + .getConfigItem(serviceConfig.getInterface(), ServiceNameMapping.DEFAULT_MAPPING_GROUP); // Check if the exported service (provider) is registered Assertions.assertNotNull(configItem); // Check if registered service (provider)'s name is right - Assertions.assertEquals(PROVIDER_APPLICATION_NAME,configItem.getContent()); + Assertions.assertEquals(PROVIDER_APPLICATION_NAME, configItem.getContent()); // Check if registered service (provider)'s version exists Assertions.assertNotNull(configItem.getTicket()); } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderRegistryProtocolListener.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderRegistryProtocolListener.java index 8b6c87f985..ef632ffa34 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderRegistryProtocolListener.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderRegistryProtocolListener.java @@ -38,9 +38,9 @@ public class MultipleRegistryCenterExportProviderRegistryProtocolListener implem @Override public void onExport(RegistryProtocol registryProtocol, Exporter exporter) { if (registryProtocol instanceof InterfaceCompatibleRegistryProtocol - && exporter != null - && exporter.getInvoker() != null - && exporter.getInvoker().getInterface().equals(MultipleRegistryCenterExportProviderService.class)) { + && exporter != null + && exporter.getInvoker() != null + && exporter.getInvoker().getInterface().equals(MultipleRegistryCenterExportProviderService.class)) { this.exported = true; } } @@ -49,16 +49,13 @@ public class MultipleRegistryCenterExportProviderRegistryProtocolListener implem * {@inheritDoc} */ @Override - public void onRefer(RegistryProtocol registryProtocol, ClusterInvoker invoker, URL url, URL registryURL) { - - } + public void onRefer(RegistryProtocol registryProtocol, ClusterInvoker invoker, URL url, URL registryURL) {} /** * {@inheritDoc} */ @Override - public void onDestroy() { - } + public void onDestroy() {} /** * Returns if this exporter is exported. diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmFilter.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmFilter.java index cd2e87dfe5..77ef3f1ada 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmFilter.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmFilter.java @@ -25,7 +25,7 @@ import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; @Activate(group = CommonConstants.PROVIDER, order = 10200) -public class MultipleRegistryCenterInjvmFilter implements Filter,Filter.Listener{ +public class MultipleRegistryCenterInjvmFilter implements Filter, Filter.Listener { /** * The filter is called or not diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmIntegrationTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmIntegrationTest.java index 227eaf2718..3d7315a456 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmIntegrationTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmIntegrationTest.java @@ -29,6 +29,8 @@ import org.apache.dubbo.rpc.ExporterListener; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; +import java.io.IOException; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -36,8 +38,6 @@ import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; - import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; /** @@ -89,11 +89,11 @@ class MultipleRegistryCenterInjvmIntegrationTest implements IntegrationTest { serviceConfig.setScope(SCOPE_LOCAL); DubboBootstrap.getInstance() - .application(new ApplicationConfig(PROVIDER_APPLICATION_NAME)) - .protocol(new ProtocolConfig("injvm")) - .service(serviceConfig) - .registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress1())) - .registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress2())); + .application(new ApplicationConfig(PROVIDER_APPLICATION_NAME)) + .protocol(new ProtocolConfig("injvm")) + .service(serviceConfig) + .registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress1())) + .registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress2())); } /** @@ -108,9 +108,12 @@ class MultipleRegistryCenterInjvmIntegrationTest implements IntegrationTest { */ private void beforeExport() { // ---------------initialize--------------- // - serviceListener = (MultipleRegistryCenterInjvmServiceListener) ExtensionLoader.getExtensionLoader(ServiceListener.class).getExtension(SPI_NAME); - exporterListener = (MultipleRegistryCenterInjvmExporterListener) ExtensionLoader.getExtensionLoader(ExporterListener.class).getExtension(SPI_NAME); - filter = (MultipleRegistryCenterInjvmFilter) ExtensionLoader.getExtensionLoader(Filter.class).getExtension(SPI_NAME); + serviceListener = (MultipleRegistryCenterInjvmServiceListener) + ExtensionLoader.getExtensionLoader(ServiceListener.class).getExtension(SPI_NAME); + exporterListener = (MultipleRegistryCenterInjvmExporterListener) + ExtensionLoader.getExtensionLoader(ExporterListener.class).getExtension(SPI_NAME); + filter = (MultipleRegistryCenterInjvmFilter) + ExtensionLoader.getExtensionLoader(Filter.class).getExtension(SPI_NAME); // ---------------checkpoints--------------- // // There is nothing in ServiceListener @@ -151,8 +154,9 @@ class MultipleRegistryCenterInjvmIntegrationTest implements IntegrationTest { // The exported service is only one Assertions.assertEquals(serviceListener.getExportedServices().size(), 1); // The exported service is MultipleRegistryCenterInjvmService - Assertions.assertEquals(serviceListener.getExportedServices().get(0).getInterfaceClass(), - MultipleRegistryCenterInjvmService.class); + Assertions.assertEquals( + serviceListener.getExportedServices().get(0).getInterfaceClass(), + MultipleRegistryCenterInjvmService.class); // The MultipleRegistryCenterInjvmService is exported Assertions.assertTrue(serviceListener.getExportedServices().get(0).isExported()); // The exported exporter is only one @@ -175,8 +179,7 @@ class MultipleRegistryCenterInjvmIntegrationTest implements IntegrationTest { // The MultipleRegistryCenterInjvmFilter doesn't exist error Assertions.assertFalse(filter.hasError()); // Check the MultipleRegistryCenterInjvmFilter's response - Assertions.assertEquals("Hello Dubbo in multiple registry center", - filter.getResponse()); + Assertions.assertEquals("Hello Dubbo in multiple registry center", filter.getResponse()); } @AfterEach diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest.java index d0047fe4ce..1f89b88cc3 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest.java @@ -30,6 +30,12 @@ import org.apache.dubbo.registry.client.metadata.MetadataServiceDelegation; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperConfig; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; +import java.io.IOException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -37,12 +43,6 @@ import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - import static org.apache.dubbo.config.integration.Constants.MULTIPLE_CONFIG_CENTER_SERVICE_DISCOVERY_REGISTRY; /** @@ -50,12 +50,14 @@ import static org.apache.dubbo.config.integration.Constants.MULTIPLE_CONFIG_CENT */ class MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest implements IntegrationTest { - private static final Logger logger = LoggerFactory.getLogger(MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest.class); + private static final Logger logger = + LoggerFactory.getLogger(MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest.class); /** * Define the provider application name. */ - public static String PROVIDER_APPLICATION_NAME = "multiple-registry-center-provider-for-service-discovery-registry-protocol"; + public static String PROVIDER_APPLICATION_NAME = + "multiple-registry-center-provider-for-service-discovery-registry-protocol"; /** * Define the protocol's name. @@ -111,16 +113,16 @@ class MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest implements I ports.add(ZookeeperConfig.DEFAULT_CLIENT_PORT_2); DubboBootstrap.getInstance() - .application(new ApplicationConfig(PROVIDER_APPLICATION_NAME)) - .protocol(new ProtocolConfig(PROTOCOL_NAME, PROTOCOL_PORT)) - .service(serviceConfig); + .application(new ApplicationConfig(PROVIDER_APPLICATION_NAME)) + .protocol(new ProtocolConfig(PROTOCOL_NAME, PROTOCOL_PORT)) + .service(serviceConfig); // ---------------initialize--------------- // - registryServiceListener = (MultipleRegistryCenterServiceDiscoveryRegistryRegistryServiceListener) ExtensionLoader - .getExtensionLoader(RegistryServiceListener.class).getExtension(MULTIPLE_CONFIG_CENTER_SERVICE_DISCOVERY_REGISTRY); + registryServiceListener = (MultipleRegistryCenterServiceDiscoveryRegistryRegistryServiceListener) + ExtensionLoader.getExtensionLoader(RegistryServiceListener.class) + .getExtension(MULTIPLE_CONFIG_CENTER_SERVICE_DISCOVERY_REGISTRY); // RegistryServiceListener is not null Assertions.assertNotNull(registryServiceListener); registryServiceListener.getStorage().clear(); - } /** @@ -149,7 +151,8 @@ class MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest implements I beforeExport(); DubboBootstrap.getInstance().start(); afterExport(); - ReferenceConfig referenceConfig = new ReferenceConfig<>(); + ReferenceConfig referenceConfig = + new ReferenceConfig<>(); referenceConfig.setInterface(MultipleRegistryCenterServiceDiscoveryRegistryService.class); referenceConfig.get().hello("Dubbo in multiple registry center"); afterInvoke(); @@ -168,18 +171,23 @@ class MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest implements I // All register center has been registered and subscribed for (int port : ports) { Assertions.assertTrue(registryServiceListener.getStorage().contains(HOST, port)); - ServiceDiscoveryRegistryInfoWrapper serviceDiscoveryRegistryInfoWrapper = registryServiceListener.getStorage().get(HOST, port); + ServiceDiscoveryRegistryInfoWrapper serviceDiscoveryRegistryInfoWrapper = + registryServiceListener.getStorage().get(HOST, port); // check if it's registered Assertions.assertTrue(serviceDiscoveryRegistryInfoWrapper.isRegistered()); // check if it's subscribed Assertions.assertFalse(serviceDiscoveryRegistryInfoWrapper.isSubscribed()); - MetadataServiceDelegation metadataService = DubboBootstrap.getInstance().getApplicationModel().getBeanFactory().getBean(MetadataServiceDelegation.class); + MetadataServiceDelegation metadataService = DubboBootstrap.getInstance() + .getApplicationModel() + .getBeanFactory() + .getBean(MetadataServiceDelegation.class); // check if the count of exported urls is right or not Assertions.assertEquals(metadataService.getExportedURLs().size(), 1); // check the exported url is right or not. - Assertions.assertTrue(metadataService.getExportedURLs() - .first() - .contains(MultipleRegistryCenterServiceDiscoveryRegistryService.class.getName())); + Assertions.assertTrue(metadataService + .getExportedURLs() + .first() + .contains(MultipleRegistryCenterServiceDiscoveryRegistryService.class.getName())); // check the count of metadatainfo is right or not. Assertions.assertEquals(2, metadataService.getMetadataInfos().size()); } @@ -188,9 +196,7 @@ class MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest implements I /** * There are some checkpoints need to check after invoked as follow: */ - private void afterInvoke() { - - } + private void afterInvoke() {} @AfterEach public void tearDown() throws IOException { @@ -213,4 +219,4 @@ class MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest implements I registryServiceListener = null; logger.info(getClass().getSimpleName() + " testcase is ending..."); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/MultipleRegistryCenterServiceDiscoveryRegistryRegistryServiceListener.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/MultipleRegistryCenterServiceDiscoveryRegistryRegistryServiceListener.java index f84a9b8765..2cd8e64b61 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/MultipleRegistryCenterServiceDiscoveryRegistryRegistryServiceListener.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/MultipleRegistryCenterServiceDiscoveryRegistryRegistryServiceListener.java @@ -24,7 +24,6 @@ import org.apache.dubbo.registry.client.ServiceDiscoveryRegistry; import static org.apache.dubbo.config.integration.Constants.MULTIPLE_CONFIG_CENTER_SERVICE_DISCOVERY_REGISTRY; - @Activate(value = MULTIPLE_CONFIG_CENTER_SERVICE_DISCOVERY_REGISTRY) public class MultipleRegistryCenterServiceDiscoveryRegistryRegistryServiceListener implements RegistryServiceListener { @@ -33,11 +32,13 @@ public class MultipleRegistryCenterServiceDiscoveryRegistryRegistryServiceListen /** * Create an {@link ServiceDiscoveryRegistryInfoWrapper} instance. */ - private ServiceDiscoveryRegistryInfoWrapper createServiceDiscoveryRegistryInfoWrapper(ServiceDiscoveryRegistry serviceDiscoveryRegistry){ + private ServiceDiscoveryRegistryInfoWrapper createServiceDiscoveryRegistryInfoWrapper( + ServiceDiscoveryRegistry serviceDiscoveryRegistry) { URL url = serviceDiscoveryRegistry.getUrl(); String host = url.getHost(); int port = url.getPort(); - ServiceDiscoveryRegistryInfoWrapper serviceDiscoveryRegistryInfoWrapper = new ServiceDiscoveryRegistryInfoWrapper(); + ServiceDiscoveryRegistryInfoWrapper serviceDiscoveryRegistryInfoWrapper = + new ServiceDiscoveryRegistryInfoWrapper(); serviceDiscoveryRegistryInfoWrapper.setHost(host); serviceDiscoveryRegistryInfoWrapper.setPort(port); serviceDiscoveryRegistryInfoWrapper.setServiceDiscoveryRegistry(serviceDiscoveryRegistry); @@ -48,10 +49,10 @@ public class MultipleRegistryCenterServiceDiscoveryRegistryRegistryServiceListen /** * Checks if the registry is checked application */ - private boolean isCheckedApplication(Registry registry){ - return registry.getUrl().getApplication() - .equals(MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest - .PROVIDER_APPLICATION_NAME); + private boolean isCheckedApplication(Registry registry) { + return registry.getUrl() + .getApplication() + .equals(MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest.PROVIDER_APPLICATION_NAME); } public void onRegister(URL url, Registry registry) { diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/MultipleRegistryCenterServiceDiscoveryRegistryServiceImpl.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/MultipleRegistryCenterServiceDiscoveryRegistryServiceImpl.java index 09469df5a7..3ddaad57cd 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/MultipleRegistryCenterServiceDiscoveryRegistryServiceImpl.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/MultipleRegistryCenterServiceDiscoveryRegistryServiceImpl.java @@ -18,7 +18,8 @@ package org.apache.dubbo.config.integration.multiple.servicediscoveryregistry; /** * The simple implementation for {@link MultipleRegistryCenterServiceDiscoveryRegistryService} */ -public class MultipleRegistryCenterServiceDiscoveryRegistryServiceImpl implements MultipleRegistryCenterServiceDiscoveryRegistryService { +public class MultipleRegistryCenterServiceDiscoveryRegistryServiceImpl + implements MultipleRegistryCenterServiceDiscoveryRegistryService { /** * {@inheritDoc} */ diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/ServiceDiscoveryRegistryStorage.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/ServiceDiscoveryRegistryStorage.java index 3a615f6709..8bb4736e76 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/ServiceDiscoveryRegistryStorage.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/ServiceDiscoveryRegistryStorage.java @@ -21,6 +21,4 @@ import org.apache.dubbo.config.integration.multiple.AbstractStorage; /** * The storage to store {@link ServiceDiscoveryRegistryInfoWrapper} instances in multiple registry center. */ -public class ServiceDiscoveryRegistryStorage extends AbstractStorage { - -} +public class ServiceDiscoveryRegistryStorage extends AbstractStorage {} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/SingleRegistryCenterDubboProtocolIntegrationTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/SingleRegistryCenterDubboProtocolIntegrationTest.java index b10835de23..5f668f48a2 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/SingleRegistryCenterDubboProtocolIntegrationTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/SingleRegistryCenterDubboProtocolIntegrationTest.java @@ -41,6 +41,10 @@ import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; +import java.io.IOException; +import java.util.Collection; +import java.util.Set; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -50,21 +54,17 @@ import org.junit.jupiter.api.condition.JRE; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.util.Collection; -import java.util.Set; - import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY; import static org.apache.dubbo.rpc.Constants.SCOPE_REMOTE; - /** * This abstraction class will implement some methods as base for single registry center. */ @DisabledForJreRange(min = JRE.JAVA_16) class SingleRegistryCenterDubboProtocolIntegrationTest implements IntegrationTest { - private static final Logger logger = LoggerFactory.getLogger(SingleRegistryCenterDubboProtocolIntegrationTest.class); + private static final Logger logger = + LoggerFactory.getLogger(SingleRegistryCenterDubboProtocolIntegrationTest.class); /** * Define the provider application name. */ @@ -114,9 +114,9 @@ class SingleRegistryCenterDubboProtocolIntegrationTest implements IntegrationTes serviceConfig.setAsync(false); DubboBootstrap.getInstance() - .application(new ApplicationConfig(PROVIDER_APPLICATION_NAME)) - .protocol(new ProtocolConfig(PROTOCOL_NAME, PROTOCOL_PORT)) - .service(serviceConfig); + .application(new ApplicationConfig(PROVIDER_APPLICATION_NAME)) + .protocol(new ProtocolConfig(PROTOCOL_NAME, PROTOCOL_PORT)) + .service(serviceConfig); registryConfig = new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress()); DubboBootstrap.getInstance().registry(registryConfig); } @@ -217,7 +217,8 @@ class SingleRegistryCenterDubboProtocolIntegrationTest implements IntegrationTes // ServiceDiscoveryRegistry's protocol is right or not Assertions.assertTrue(serviceDiscoveryRegistry.getServiceDiscovery() instanceof ZookeeperServiceDiscovery); // Convert to ZookeeperServiceDiscovery instance - ZookeeperServiceDiscovery zookeeperServiceDiscovery = (ZookeeperServiceDiscovery) serviceDiscoveryRegistry.getServiceDiscovery(); + ZookeeperServiceDiscovery zookeeperServiceDiscovery = + (ZookeeperServiceDiscovery) serviceDiscoveryRegistry.getServiceDiscovery(); // Gets registered service by ZookeeperServiceDiscovery Set services = zookeeperServiceDiscovery.getServices(); // check service exists @@ -226,18 +227,35 @@ class SingleRegistryCenterDubboProtocolIntegrationTest implements IntegrationTes Assertions.assertTrue(services.contains(PROVIDER_APPLICATION_NAME)); // obtain InMemoryWritableMetadataService instance - MetadataServiceDelegation inMemoryWritableMetadataService = (MetadataServiceDelegation) serviceConfig.getScopeModel().getBeanFactory().getBean(MetadataService.class); + MetadataServiceDelegation inMemoryWritableMetadataService = (MetadataServiceDelegation) + serviceConfig.getScopeModel().getBeanFactory().getBean(MetadataService.class); // Exported url is right or not in InMemoryWritableMetadataService - Assertions.assertEquals(inMemoryWritableMetadataService.getExportedURLs().size(), 1); + Assertions.assertEquals( + inMemoryWritableMetadataService.getExportedURLs().size(), 1); // MetadataInfo exists or not in InMemoryWritableMetadataService - Assertions.assertFalse(inMemoryWritableMetadataService.getMetadataInfos().isEmpty()); + Assertions.assertFalse( + inMemoryWritableMetadataService.getMetadataInfos().isEmpty()); // MetadataInfo has reported or not has service or not - Assertions.assertFalse(inMemoryWritableMetadataService.getMetadataInfos().get(0).getServices().isEmpty()); + Assertions.assertFalse(inMemoryWritableMetadataService + .getMetadataInfos() + .get(0) + .getServices() + .isEmpty()); // MetadataInfo has reported or not has service or not - Assertions.assertEquals(inMemoryWritableMetadataService.getMetadataInfos().get(0).getServices().size(), 1); + Assertions.assertEquals( + inMemoryWritableMetadataService + .getMetadataInfos() + .get(0) + .getServices() + .size(), + 1); // obtain the service's key String key = SingleRegistryCenterIntegrationService.class.getName() + ":" + PROTOCOL_NAME; - MetadataInfo.ServiceInfo serviceInfo = inMemoryWritableMetadataService.getMetadataInfos().get(0).getServices().get(key); + MetadataInfo.ServiceInfo serviceInfo = inMemoryWritableMetadataService + .getMetadataInfos() + .get(0) + .getServices() + .get(key); // MetadataInfo's service exists or not Assertions.assertNotNull(serviceInfo); // The name of MetadataInfo's service is right or not @@ -256,12 +274,23 @@ class SingleRegistryCenterDubboProtocolIntegrationTest implements IntegrationTes // 1. The exported service must contain SingleRegistryCenterIntegrationService // 2. The exported service's interface must be SingleRegistryCenterIntegrationService.class // 3. All exported services must be exported - singleRegistryCenterExportedServiceListener = (SingleRegistryCenterExportedServiceListener) ExtensionLoader.getExtensionLoader(ServiceListener.class).getExtension("exported"); + singleRegistryCenterExportedServiceListener = (SingleRegistryCenterExportedServiceListener) + ExtensionLoader.getExtensionLoader(ServiceListener.class).getExtension("exported"); Assertions.assertNotNull(singleRegistryCenterExportedServiceListener); - Assertions.assertEquals(singleRegistryCenterExportedServiceListener.getExportedServices().size(), 1); - Assertions.assertEquals(SingleRegistryCenterIntegrationService.class, - singleRegistryCenterExportedServiceListener.getExportedServices().get(0).getInterfaceClass()); - ServiceConfig singleRegistryCenterServiceConfig = singleRegistryCenterExportedServiceListener.getExportedServices().get(0); + Assertions.assertEquals( + singleRegistryCenterExportedServiceListener + .getExportedServices() + .size(), + 1); + Assertions.assertEquals( + SingleRegistryCenterIntegrationService.class, + singleRegistryCenterExportedServiceListener + .getExportedServices() + .get(0) + .getInterfaceClass()); + ServiceConfig singleRegistryCenterServiceConfig = singleRegistryCenterExportedServiceListener + .getExportedServices() + .get(0); Assertions.assertNotNull(singleRegistryCenterServiceConfig); Assertions.assertTrue(singleRegistryCenterServiceConfig.isExported()); } @@ -272,9 +301,10 @@ class SingleRegistryCenterDubboProtocolIntegrationTest implements IntegrationTes * FIXME It's not a good way to obtain {@link ServiceDiscoveryRegistry} using Reflection. */ private ServiceDiscoveryRegistry getServiceDiscoveryRegistry() { - Collection registries = RegistryManager.getInstance(ApplicationModel.defaultModel()).getRegistries(); + Collection registries = + RegistryManager.getInstance(ApplicationModel.defaultModel()).getRegistries(); for (Registry registry : registries) { - if(registry instanceof ServiceDiscoveryRegistry) { + if (registry instanceof ServiceDiscoveryRegistry) { return (ServiceDiscoveryRegistry) registry; } } @@ -302,7 +332,9 @@ class SingleRegistryCenterDubboProtocolIntegrationTest implements IntegrationTes */ private void beforeRefer() { // ReferenceConfig has integrated into DubboBootstrap or not - Assertions.assertEquals(referenceConfig.getScopeModel(), DubboBootstrap.getInstance().getApplicationModel().getDefaultModule()); + Assertions.assertEquals( + referenceConfig.getScopeModel(), + DubboBootstrap.getInstance().getApplicationModel().getDefaultModule()); } /** @@ -329,8 +361,7 @@ class SingleRegistryCenterDubboProtocolIntegrationTest implements IntegrationTes Assertions.assertNotNull(referenceConfig.getInvoker()); Assertions.assertTrue(referenceConfig.getInvoker() instanceof MigrationInvoker); // RPC works well or not - Assertions.assertEquals("Hello Reference", - singleRegistryCenterIntegrationService.hello("Reference")); + Assertions.assertEquals("Hello Reference", singleRegistryCenterIntegrationService.hello("Reference")); // get ServiceDiscoveryRegistryDirectory instance Directory directory = ((MigrationInvoker) referenceConfig.getInvoker()).getDirectory(); // Directory is null or not @@ -345,16 +376,20 @@ class SingleRegistryCenterDubboProtocolIntegrationTest implements IntegrationTes Assertions.assertFalse(directory.isDestroyed()); // Directory has received notification or not Assertions.assertTrue(directory.isNotificationReceived()); - ServiceDiscoveryRegistryDirectory serviceDiscoveryRegistryDirectory = (ServiceDiscoveryRegistryDirectory) directory; + ServiceDiscoveryRegistryDirectory serviceDiscoveryRegistryDirectory = + (ServiceDiscoveryRegistryDirectory) directory; // ServiceDiscoveryRegistryDirectory should register or not Assertions.assertTrue(serviceDiscoveryRegistryDirectory.isShouldRegister()); // ServiceDiscoveryRegistryDirectory's registered consumer url is right or not - Assertions.assertEquals(serviceDiscoveryRegistryDirectory.getRegisteredConsumerUrl().getCategory(), CONSUMERS_CATEGORY); + Assertions.assertEquals( + serviceDiscoveryRegistryDirectory.getRegisteredConsumerUrl().getCategory(), CONSUMERS_CATEGORY); // ServiceDiscoveryRegistryDirectory's registry is right or not Assertions.assertTrue(serviceDiscoveryRegistryDirectory.getRegistry() instanceof ListenerRegistryWrapper); // Directory's invokers are right or not - Assertions.assertEquals(serviceDiscoveryRegistryDirectory.getAllInvokers().size(), 1); - Assertions.assertEquals(serviceDiscoveryRegistryDirectory.getInvokers(), serviceDiscoveryRegistryDirectory.getAllInvokers()); + Assertions.assertEquals( + serviceDiscoveryRegistryDirectory.getAllInvokers().size(), 1); + Assertions.assertEquals( + serviceDiscoveryRegistryDirectory.getInvokers(), serviceDiscoveryRegistryDirectory.getAllInvokers()); } @AfterEach @@ -366,8 +401,10 @@ class SingleRegistryCenterDubboProtocolIntegrationTest implements IntegrationTes serviceConfig = null; referenceConfig = null; // The exported service has been unexported - Assertions.assertTrue(singleRegistryCenterExportedServiceListener.getExportedServices().isEmpty()); + Assertions.assertTrue(singleRegistryCenterExportedServiceListener + .getExportedServices() + .isEmpty()); singleRegistryCenterExportedServiceListener = null; logger.info(getClass().getSimpleName() + " testcase is ending..."); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportmetadata/SingleRegistryCenterExportMetadataIntegrationTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportmetadata/SingleRegistryCenterExportMetadataIntegrationTest.java index e64a671f52..96536d0a62 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportmetadata/SingleRegistryCenterExportMetadataIntegrationTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportmetadata/SingleRegistryCenterExportMetadataIntegrationTest.java @@ -30,6 +30,9 @@ import org.apache.dubbo.rpc.ExporterListener; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; +import java.io.IOException; +import java.util.List; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -37,9 +40,6 @@ import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.util.List; - import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; /** @@ -47,7 +47,8 @@ import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; */ class SingleRegistryCenterExportMetadataIntegrationTest implements IntegrationTest { - private static final Logger logger = LoggerFactory.getLogger(SingleRegistryCenterExportMetadataIntegrationTest.class); + private static final Logger logger = + LoggerFactory.getLogger(SingleRegistryCenterExportMetadataIntegrationTest.class); /** * Define the provider application name. @@ -91,9 +92,9 @@ class SingleRegistryCenterExportMetadataIntegrationTest implements IntegrationTe // initailize bootstrap DubboBootstrap.getInstance() - .application(new ApplicationConfig(PROVIDER_APPLICATION_NAME)) - .protocol(new ProtocolConfig(PROTOCOL_NAME)) - .service(serviceConfig); + .application(new ApplicationConfig(PROVIDER_APPLICATION_NAME)) + .protocol(new ProtocolConfig(PROTOCOL_NAME)) + .service(serviceConfig); RegistryConfig registryConfig = new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress()); DubboBootstrap.getInstance().registry(registryConfig); } @@ -110,8 +111,10 @@ class SingleRegistryCenterExportMetadataIntegrationTest implements IntegrationTe */ private void beforeExport() { // ---------------initialize--------------- // - serviceListener = (SingleRegistryCenterExportMetadataServiceListener) ExtensionLoader.getExtensionLoader(ServiceListener.class).getExtension(SPI_NAME); - exporterListener = (SingleRegistryCenterExportMetadataExporterListener) ExtensionLoader.getExtensionLoader(ExporterListener.class).getExtension(SPI_NAME); + serviceListener = (SingleRegistryCenterExportMetadataServiceListener) + ExtensionLoader.getExtensionLoader(ServiceListener.class).getExtension(SPI_NAME); + exporterListener = (SingleRegistryCenterExportMetadataExporterListener) + ExtensionLoader.getExtensionLoader(ExporterListener.class).getExtension(SPI_NAME); // ---------------checkpoints--------------- // // There is nothing in ServiceListener @@ -146,8 +149,8 @@ class SingleRegistryCenterExportMetadataIntegrationTest implements IntegrationTe // The metadata service is only one Assertions.assertEquals(serviceListener.getExportedServices().size(), 1); // The exported service is MetadataService - Assertions.assertEquals(serviceListener.getExportedServices().get(0).getInterfaceClass(), - MetadataService.class); + Assertions.assertEquals( + serviceListener.getExportedServices().get(0).getInterfaceClass(), MetadataService.class); // The MetadataService is exported Assertions.assertTrue(serviceListener.getExportedServices().get(0).isExported()); // There are two exported exporters diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderFilter.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderFilter.java index caf9963de6..299e9c7338 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderFilter.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderFilter.java @@ -25,7 +25,7 @@ import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; @Activate(group = CommonConstants.PROVIDER, order = 10000) -public class SingleRegistryCenterExportProviderFilter implements Filter,Filter.Listener { +public class SingleRegistryCenterExportProviderFilter implements Filter, Filter.Listener { /** * The filter is called or not diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderIntegrationTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderIntegrationTest.java index 41de19efcb..d866f40d6e 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderIntegrationTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderIntegrationTest.java @@ -35,6 +35,10 @@ import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -42,10 +46,6 @@ import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_PROTOCOL_LISTENER_KEY; import static org.apache.dubbo.config.integration.Constants.SINGLE_CONFIG_CENTER_EXPORT_PROVIDER; import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; @@ -55,7 +55,8 @@ import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; */ class SingleRegistryCenterExportProviderIntegrationTest implements IntegrationTest { - private static final Logger logger = LoggerFactory.getLogger(SingleRegistryCenterExportProviderIntegrationTest.class); + private static final Logger logger = + LoggerFactory.getLogger(SingleRegistryCenterExportProviderIntegrationTest.class); /** * Define the provider application name. @@ -108,9 +109,9 @@ class SingleRegistryCenterExportProviderIntegrationTest implements IntegrationTe // initialize bootstrap DubboBootstrap.getInstance() - .application(new ApplicationConfig(PROVIDER_APPLICATION_NAME)) - .protocol(new ProtocolConfig(PROTOCOL_NAME, PROTOCOL_PORT)) - .service(serviceConfig); + .application(new ApplicationConfig(PROVIDER_APPLICATION_NAME)) + .protocol(new ProtocolConfig(PROTOCOL_NAME, PROTOCOL_PORT)) + .service(serviceConfig); RegistryConfig registryConfig = new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress()); Map parameters = new HashMap<>(); @@ -129,18 +130,17 @@ class SingleRegistryCenterExportProviderIntegrationTest implements IntegrationTe * */ private void beforeExport() { - registryProtocolListener = (SingleRegistryCenterExportProviderRegistryProtocolListener) ExtensionLoader - .getExtensionLoader(RegistryProtocolListener.class) - .getExtension(SINGLE_CONFIG_CENTER_EXPORT_PROVIDER); - exporterListener = (SingleRegistryCenterExportProviderExporterListener) ExtensionLoader - .getExtensionLoader(ExporterListener.class) - .getExtension(SINGLE_CONFIG_CENTER_EXPORT_PROVIDER); - filter = (SingleRegistryCenterExportProviderFilter) ExtensionLoader - .getExtensionLoader(Filter.class) - .getExtension(SINGLE_CONFIG_CENTER_EXPORT_PROVIDER); - serviceListener = (SingleRegistryCenterExportProviderServiceListener) ExtensionLoader - .getExtensionLoader(ServiceListener.class) - .getExtension(SINGLE_CONFIG_CENTER_EXPORT_PROVIDER); + registryProtocolListener = (SingleRegistryCenterExportProviderRegistryProtocolListener) + ExtensionLoader.getExtensionLoader(RegistryProtocolListener.class) + .getExtension(SINGLE_CONFIG_CENTER_EXPORT_PROVIDER); + exporterListener = (SingleRegistryCenterExportProviderExporterListener) + ExtensionLoader.getExtensionLoader(ExporterListener.class) + .getExtension(SINGLE_CONFIG_CENTER_EXPORT_PROVIDER); + filter = (SingleRegistryCenterExportProviderFilter) + ExtensionLoader.getExtensionLoader(Filter.class).getExtension(SINGLE_CONFIG_CENTER_EXPORT_PROVIDER); + serviceListener = (SingleRegistryCenterExportProviderServiceListener) + ExtensionLoader.getExtensionLoader(ServiceListener.class) + .getExtension(SINGLE_CONFIG_CENTER_EXPORT_PROVIDER); // ---------------checkpoints--------------- // // ServiceConfig isn't exported Assertions.assertFalse(serviceConfig.isExported()); @@ -187,8 +187,9 @@ class SingleRegistryCenterExportProviderIntegrationTest implements IntegrationTe // The exported service is only one Assertions.assertEquals(serviceListener.getExportedServices().size(), 1); // The exported service is SingleRegistryCenterExportProviderService - Assertions.assertEquals(serviceListener.getExportedServices().get(0).getInterfaceClass(), - SingleRegistryCenterExportProviderService.class); + Assertions.assertEquals( + serviceListener.getExportedServices().get(0).getInterfaceClass(), + SingleRegistryCenterExportProviderService.class); // The SingleRegistryCenterExportProviderService is exported Assertions.assertTrue(serviceListener.getExportedServices().get(0).isExported()); // The exported exporter are three @@ -206,13 +207,15 @@ class SingleRegistryCenterExportProviderIntegrationTest implements IntegrationTe // registryKey: the registryKey is the default cluster, CommonConstants.DEFAULT_KEY // key: The exported interface's name // group: the group is "mapping", ServiceNameMapping.DEFAULT_MAPPING_GROUP - ConfigItem configItem = ApplicationModel.defaultModel().getBeanFactory().getBean(MetadataReportInstance.class).getMetadataReport(CommonConstants.DEFAULT_KEY) - .getConfigItem(serviceConfig.getInterface() - , ServiceNameMapping.DEFAULT_MAPPING_GROUP); + ConfigItem configItem = ApplicationModel.defaultModel() + .getBeanFactory() + .getBean(MetadataReportInstance.class) + .getMetadataReport(CommonConstants.DEFAULT_KEY) + .getConfigItem(serviceConfig.getInterface(), ServiceNameMapping.DEFAULT_MAPPING_GROUP); // Check if the exported service (provider) is registered Assertions.assertNotNull(configItem); // Check if registered service (provider)'s name is right - Assertions.assertEquals(PROVIDER_APPLICATION_NAME,configItem.getContent()); + Assertions.assertEquals(PROVIDER_APPLICATION_NAME, configItem.getContent()); // Check if registered service (provider)'s version exists Assertions.assertNotNull(configItem.getTicket()); } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderRegistryProtocolListener.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderRegistryProtocolListener.java index c7de521d5b..c67e098137 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderRegistryProtocolListener.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderRegistryProtocolListener.java @@ -40,9 +40,9 @@ public class SingleRegistryCenterExportProviderRegistryProtocolListener implemen @Override public void onExport(RegistryProtocol registryProtocol, Exporter exporter) { if (registryProtocol instanceof InterfaceCompatibleRegistryProtocol - && exporter != null - && exporter.getInvoker() != null - && exporter.getInvoker().getInterface().equals(SingleRegistryCenterExportProviderService.class)) { + && exporter != null + && exporter.getInvoker() != null + && exporter.getInvoker().getInterface().equals(SingleRegistryCenterExportProviderService.class)) { this.exported = true; } } @@ -51,16 +51,13 @@ public class SingleRegistryCenterExportProviderRegistryProtocolListener implemen * {@inheritDoc} */ @Override - public void onRefer(RegistryProtocol registryProtocol, ClusterInvoker invoker, URL url, URL registryURL) { - - } + public void onRefer(RegistryProtocol registryProtocol, ClusterInvoker invoker, URL url, URL registryURL) {} /** * {@inheritDoc} */ @Override - public void onDestroy() { - } + public void onDestroy() {} /** * Returns if this exporter is exported. diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/injvm/SingleRegistryCenterInjvmFilter.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/injvm/SingleRegistryCenterInjvmFilter.java index 48b56df8b8..06bbdb0f63 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/injvm/SingleRegistryCenterInjvmFilter.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/injvm/SingleRegistryCenterInjvmFilter.java @@ -25,7 +25,7 @@ import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; @Activate(group = CommonConstants.PROVIDER, order = 10000) -public class SingleRegistryCenterInjvmFilter implements Filter,Filter.Listener { +public class SingleRegistryCenterInjvmFilter implements Filter, Filter.Listener { /** * The filter is called or not diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/injvm/SingleRegistryCenterInjvmIntegrationTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/injvm/SingleRegistryCenterInjvmIntegrationTest.java index b313d4461a..95090fd8ff 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/injvm/SingleRegistryCenterInjvmIntegrationTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/injvm/SingleRegistryCenterInjvmIntegrationTest.java @@ -29,6 +29,8 @@ import org.apache.dubbo.rpc.ExporterListener; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; +import java.io.IOException; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -36,8 +38,6 @@ import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; - import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; /** @@ -89,9 +89,9 @@ class SingleRegistryCenterInjvmIntegrationTest implements IntegrationTest { // initailize bootstrap DubboBootstrap.getInstance() - .application(new ApplicationConfig(PROVIDER_APPLICATION_NAME)) - .protocol(new ProtocolConfig("injvm")) - .service(serviceConfig); + .application(new ApplicationConfig(PROVIDER_APPLICATION_NAME)) + .protocol(new ProtocolConfig("injvm")) + .service(serviceConfig); RegistryConfig registryConfig = new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress()); DubboBootstrap.getInstance().registry(registryConfig); } @@ -108,9 +108,12 @@ class SingleRegistryCenterInjvmIntegrationTest implements IntegrationTest { */ private void beforeExport() { // ---------------initialize--------------- // - serviceListener = (SingleRegistryCenterInjvmServiceListener) ExtensionLoader.getExtensionLoader(ServiceListener.class).getExtension(SPI_NAME); - exporterListener = (SingleRegistryCenterInjvmExporterListener) ExtensionLoader.getExtensionLoader(ExporterListener.class).getExtension(SPI_NAME); - filter = (SingleRegistryCenterInjvmFilter) ExtensionLoader.getExtensionLoader(Filter.class).getExtension(SPI_NAME); + serviceListener = (SingleRegistryCenterInjvmServiceListener) + ExtensionLoader.getExtensionLoader(ServiceListener.class).getExtension(SPI_NAME); + exporterListener = (SingleRegistryCenterInjvmExporterListener) + ExtensionLoader.getExtensionLoader(ExporterListener.class).getExtension(SPI_NAME); + filter = (SingleRegistryCenterInjvmFilter) + ExtensionLoader.getExtensionLoader(Filter.class).getExtension(SPI_NAME); // ---------------checkpoints--------------- // // There is nothing in ServiceListener @@ -151,8 +154,9 @@ class SingleRegistryCenterInjvmIntegrationTest implements IntegrationTest { // The exported service is only one Assertions.assertEquals(serviceListener.getExportedServices().size(), 1); // The exported service is SingleRegistryCenterInjvmService - Assertions.assertEquals(serviceListener.getExportedServices().get(0).getInterfaceClass(), - SingleRegistryCenterInjvmService.class); + Assertions.assertEquals( + serviceListener.getExportedServices().get(0).getInterfaceClass(), + SingleRegistryCenterInjvmService.class); // The SingleRegistryCenterInjvmService is exported Assertions.assertTrue(serviceListener.getExportedServices().get(0).isExported()); // The exported exporter is only one diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/invoker/DelegateProviderMetaDataInvokerTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/invoker/DelegateProviderMetaDataInvokerTest.java index de42881568..1abbb66019 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/invoker/DelegateProviderMetaDataInvokerTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/invoker/DelegateProviderMetaDataInvokerTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config.invoker; import org.apache.dubbo.config.ServiceConfig; @@ -56,5 +55,4 @@ class DelegateProviderMetaDataInvokerTest { Mockito.verify(invoker).destroy(); assertThat(delegate.getMetadata(), sameInstance(service)); } - } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metadata/MetadataServiceURLParamsMetadataCustomizerTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metadata/MetadataServiceURLParamsMetadataCustomizerTest.java index a6c6622aa1..d638adacbf 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metadata/MetadataServiceURLParamsMetadataCustomizerTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metadata/MetadataServiceURLParamsMetadataCustomizerTest.java @@ -28,15 +28,15 @@ import org.apache.dubbo.config.provider.impl.DemoServiceImpl; import org.apache.dubbo.registry.client.DefaultServiceInstance; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.io.IOException; +import java.util.Map; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.io.IOException; -import java.util.Map; - import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; @@ -49,10 +49,10 @@ import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataU class MetadataServiceURLParamsMetadataCustomizerTest { public DefaultServiceInstance instance; - private URL metadataServiceURL = URL.valueOf("dubbo://10.225.12.124:2002/org.apache.dubbo.metadata.MetadataService" + - "?application=MetadataServiceURLParamsMetadataCustomizerTest&group=MetadataServiceURLParamsMetadataCustomizerTest" + - "&interface=org.apache.dubbo.metadata.MetadataService&side=provider×tamp=1637573430740&version=1.0.0"); - + private URL metadataServiceURL = URL.valueOf( + "dubbo://10.225.12.124:2002/org.apache.dubbo.metadata.MetadataService" + + "?application=MetadataServiceURLParamsMetadataCustomizerTest&group=MetadataServiceURLParamsMetadataCustomizerTest" + + "&interface=org.apache.dubbo.metadata.MetadataService&side=provider×tamp=1637573430740&version=1.0.0"); public static DefaultServiceInstance createInstance() { return new DefaultServiceInstance("A", "127.0.0.1", 20880, ApplicationModel.defaultModel()); @@ -80,10 +80,10 @@ class MetadataServiceURLParamsMetadataCustomizerTest { applicationConfig.setMetadataType(DEFAULT_METADATA_STORAGE_TYPE); providerBootstrap - .application(applicationConfig) - .registry(new RegistryConfig("N/A")) - .protocol(new ProtocolConfig("dubbo", 2002)) - .service(serviceConfig); + .application(applicationConfig) + .registry(new RegistryConfig("N/A")) + .protocol(new ProtocolConfig("dubbo", 2002)) + .service(serviceConfig); // will start exporter.export() providerBootstrap.start(); @@ -91,7 +91,7 @@ class MetadataServiceURLParamsMetadataCustomizerTest { ApplicationModel applicationModel = providerBootstrap.getApplicationModel(); MetadataServiceURLParamsMetadataCustomizer customizer = new MetadataServiceURLParamsMetadataCustomizer(); - Thread.sleep(5000);// wait for service delay export + Thread.sleep(5000); // wait for service delay export customizer.customize(instance, applicationModel); String val = instance.getMetadata().get(METADATA_SERVICE_URL_PARAMS_PROPERTY_NAME); diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/GreetingLocal1.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/GreetingLocal1.java index f3d5ee572b..6b688bf0fa 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/GreetingLocal1.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/GreetingLocal1.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -16,6 +16,4 @@ */ package org.apache.dubbo.config.mock; -public class GreetingLocal1 { - -} +public class GreetingLocal1 {} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/GreetingLocal2.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/GreetingLocal2.java index 8cae40684f..d60a212417 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/GreetingLocal2.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/GreetingLocal2.java @@ -6,7 +6,7 @@ * (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 + * 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, diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/GreetingLocal3.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/GreetingLocal3.java index 9b14ac6e9e..ba68d28e25 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/GreetingLocal3.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/GreetingLocal3.java @@ -6,7 +6,7 @@ * (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 + * 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, diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockCluster.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockCluster.java index 3b5b2cce00..d188a96580 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockCluster.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockCluster.java @@ -6,7 +6,7 @@ * (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 + * 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, diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockCodec.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockCodec.java index c1aac425e5..5de3b54501 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockCodec.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockCodec.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config.mock; import org.apache.dubbo.remoting.Channel; @@ -26,9 +25,7 @@ import java.io.OutputStream; public class MockCodec implements Codec { @Override - public void encode(Channel channel, OutputStream output, Object message) throws IOException { - - } + public void encode(Channel channel, OutputStream output, Object message) throws IOException {} @Override public Object decode(Channel channel, InputStream input) throws IOException { diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockDispatcher.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockDispatcher.java index 32fffca968..60dadb7765 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockDispatcher.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockDispatcher.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config.mock; import org.apache.dubbo.common.URL; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockExchanger.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockExchanger.java index fccfd2387f..729282aeed 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockExchanger.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockExchanger.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config.mock; import org.apache.dubbo.common.URL; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockExporterListener.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockExporterListener.java index b93f44cb62..f106811a62 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockExporterListener.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockExporterListener.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config.mock; import org.apache.dubbo.rpc.Exporter; @@ -23,12 +22,8 @@ import org.apache.dubbo.rpc.RpcException; public class MockExporterListener implements ExporterListener { @Override - public void exported(Exporter exporter) throws RpcException { - - } + public void exported(Exporter exporter) throws RpcException {} @Override - public void unexported(Exporter exporter) { - - } + public void unexported(Exporter exporter) {} } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockFilter.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockFilter.java index d51f12318f..46b570b0f3 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockFilter.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockFilter.java @@ -6,7 +6,7 @@ * (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 + * 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, diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockInvokerListener.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockInvokerListener.java index c929e5443f..7137edb2d9 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockInvokerListener.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockInvokerListener.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -22,12 +22,8 @@ import org.apache.dubbo.rpc.RpcException; public class MockInvokerListener implements InvokerListener { @Override - public void referred(Invoker invoker) throws RpcException { - - } + public void referred(Invoker invoker) throws RpcException {} @Override - public void destroyed(Invoker invoker) { - - } + public void destroyed(Invoker invoker) {} } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockLoadBalance.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockLoadBalance.java index 377f328a3d..a2f58129e2 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockLoadBalance.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockLoadBalance.java @@ -6,7 +6,7 @@ * (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 + * 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, diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockProtocol.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockProtocol.java index d09faf8336..cdea6a2d4d 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockProtocol.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockProtocol.java @@ -74,9 +74,7 @@ public class MockProtocol implements Protocol { } @Override - public void destroy() { - - } + public void destroy() {} }; } @@ -84,8 +82,5 @@ public class MockProtocol implements Protocol { * @see org.apache.dubbo.rpc.Protocol#destroy() */ @Override - public void destroy() { - - } - + public void destroy() {} } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockProtocol2.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockProtocol2.java index 91653d4dfb..2f1a31990c 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockProtocol2.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockProtocol2.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config.mock; import org.apache.dubbo.common.URL; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockProxyFactory.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockProxyFactory.java index 49f05d841e..215639d90b 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockProxyFactory.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockProxyFactory.java @@ -6,7 +6,7 @@ * (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 + * 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, diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockRegistry.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockRegistry.java index 735c942785..f1a461f429 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockRegistry.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockRegistry.java @@ -57,25 +57,19 @@ public class MockRegistry implements Registry { * @see org.apache.dubbo.common.Node#destroy() */ @Override - public void destroy() { - - } + public void destroy() {} /* * @see org.apache.dubbo.registry.RegistryService#register(org.apache.dubbo.common.URL) */ @Override - public void register(URL url) { - - } + public void register(URL url) {} /* * @see org.apache.dubbo.registry.RegistryService#unregister(org.apache.dubbo.common.URL) */ @Override - public void unregister(URL url) { - - } + public void unregister(URL url) {} /* * @see org.apache.dubbo.registry.RegistryService#subscribe(org.apache.dubbo.common.URL, org.apache.dubbo.registry.NotifyListener) @@ -85,9 +79,7 @@ public class MockRegistry implements Registry { this.subscribedUrl = url; List urls = new ArrayList(); - urls.add(url.setProtocol("mockprotocol") - .removeParameter(CATEGORY_KEY) - .addParameter(METHODS_KEY, "sayHello")); + urls.add(url.setProtocol("mockprotocol").removeParameter(CATEGORY_KEY).addParameter(METHODS_KEY, "sayHello")); listener.notify(urls); } @@ -96,9 +88,7 @@ public class MockRegistry implements Registry { * @see org.apache.dubbo.registry.RegistryService#unsubscribe(org.apache.dubbo.common.URL, org.apache.dubbo.registry.NotifyListener) */ @Override - public void unsubscribe(URL url, NotifyListener listener) { - - } + public void unsubscribe(URL url, NotifyListener listener) {} /* * @see org.apache.dubbo.registry.RegistryService#lookup(org.apache.dubbo.common.URL) @@ -107,5 +97,4 @@ public class MockRegistry implements Registry { public List lookup(URL url) { return null; } - } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockRegistryFactory.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockRegistryFactory.java index 1e0e6e7b79..9005378f4f 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockRegistryFactory.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockRegistryFactory.java @@ -33,5 +33,4 @@ public class MockRegistryFactory implements RegistryFactory { return new MockRegistry(); } - } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockRegistryFactory2.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockRegistryFactory2.java index 2ab3da8faa..4217a836d8 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockRegistryFactory2.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockRegistryFactory2.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config.mock; import org.apache.dubbo.common.URL; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockServiceDiscovery.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockServiceDiscovery.java index 694342a7ac..8dc9e8d611 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockServiceDiscovery.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockServiceDiscovery.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -16,16 +16,16 @@ */ package org.apache.dubbo.config.mock; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.client.AbstractServiceDiscovery; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + public class MockServiceDiscovery extends AbstractServiceDiscovery { private URL registryURL; @@ -38,9 +38,7 @@ public class MockServiceDiscovery extends AbstractServiceDiscovery { } @Override - public void doDestroy() throws Exception { - - } + public void doDestroy() throws Exception {} @Override public void doRegister(ServiceInstance serviceInstance) throws RuntimeException { @@ -48,7 +46,8 @@ public class MockServiceDiscovery extends AbstractServiceDiscovery { } @Override - protected void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance) throws RuntimeException { + protected void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance) + throws RuntimeException { this.serviceInstance = newServiceInstance; } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockServiceListener.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockServiceListener.java index 75e05a8462..a7e8e0cb89 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockServiceListener.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockServiceListener.java @@ -37,8 +37,7 @@ public class MockServiceListener implements ServiceListener { } @Override - public void unexported(ServiceConfig sc) { - } + public void unexported(ServiceConfig sc) {} public Map getExportedServices() { return exportedServices; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockStatusChecker.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockStatusChecker.java index e144c7bc2c..8683513278 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockStatusChecker.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockStatusChecker.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config.mock; import org.apache.dubbo.common.status.Status; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockTelnetHandler.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockTelnetHandler.java index a08160fa79..5738e5276d 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockTelnetHandler.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockTelnetHandler.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config.mock; import org.apache.dubbo.remoting.Channel; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockThreadPool.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockThreadPool.java index fe966899d8..80b327b6eb 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockThreadPool.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockThreadPool.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config.mock; import org.apache.dubbo.common.URL; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockTransporter.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockTransporter.java index 28bce33e44..4a1dc835c5 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockTransporter.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockTransporter.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config.mock; import org.apache.dubbo.common.URL; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/TestProxyFactory.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/TestProxyFactory.java index fe22bd13ff..f18ecb0200 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/TestProxyFactory.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/TestProxyFactory.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config.mock; import org.apache.dubbo.common.URL; diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/nested/AggregationConfigTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/nested/AggregationConfigTest.java index 76c9d504a8..13efc6a5ed 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/nested/AggregationConfigTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/nested/AggregationConfigTest.java @@ -43,4 +43,4 @@ class AggregationConfigTest { aggregationConfig.setTimeWindowSeconds(120); assertThat(aggregationConfig.getTimeWindowSeconds(), equalTo(120)); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/provider/impl/DemoServiceImpl.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/provider/impl/DemoServiceImpl.java index 50d0f0a6fc..8ba85b6de1 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/provider/impl/DemoServiceImpl.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/provider/impl/DemoServiceImpl.java @@ -47,5 +47,4 @@ public class DemoServiceImpl implements DemoService { public int echo(int i) { return i; } - } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/ExporterSideConfigUrlTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/ExporterSideConfigUrlTest.java index c07201b78e..4a7f225ff5 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/ExporterSideConfigUrlTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/ExporterSideConfigUrlTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -16,30 +16,27 @@ */ package org.apache.dubbo.config.url; - import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.config.bootstrap.DubboBootstrap; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; - class ExporterSideConfigUrlTest extends UrlTestBase { private static final Logger log = LoggerFactory.getLogger(ExporterSideConfigUrlTest.class); // ====================================================== // tests start - // ====================================================== + // ====================================================== @BeforeAll - public static void start() { - } - + public static void start() {} @BeforeEach public void setUp() { @@ -71,10 +68,9 @@ class ExporterSideConfigUrlTest extends UrlTestBase { @Test void exporterRegistryConfigUrlTest() { - //verifyExporterUrlGeneration(regConfForService, regConfForServiceTable); + // verifyExporterUrlGeneration(regConfForService, regConfForServiceTable); } - protected void verifyExporterUrlGeneration(T config, Object[][] dataTable) { // 1. fill corresponding config with data @@ -91,12 +87,11 @@ class ExporterSideConfigUrlTest extends UrlTestBase { // impossible } - - assertUrlStringWithLocalTable(paramStringFromDb, dataTable, config.getClass().getName(), TESTVALUE1); - + assertUrlStringWithLocalTable( + paramStringFromDb, dataTable, config.getClass().getName(), TESTVALUE1); // 4. unexport service //////////////////////////////////////////////////////////// servConf.unexport(); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/InvokerSideConfigUrlTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/InvokerSideConfigUrlTest.java index 5994f7e535..90d3657bb6 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/InvokerSideConfigUrlTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/InvokerSideConfigUrlTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -25,14 +25,14 @@ import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.api.DemoService; import org.apache.dubbo.config.mock.MockRegistry; +import java.util.Arrays; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import java.util.Arrays; - import static org.apache.dubbo.rpc.Constants.SCOPE_REMOTE; @Disabled @@ -49,77 +49,84 @@ class InvokerSideConfigUrlTest extends UrlTestBase { private ReferenceConfig refConf; private Object appConfForConsumerTable[][] = { - {"", "", "", "", "", "", "", "", "", ""}, + {"", "", "", "", "", "", "", "", "", ""}, }; private Object appConfForReferenceTable[][] = { - {"", "", "", "", "", "", "", "", "", ""}, + {"", "", "", "", "", "", "", "", "", ""}, }; private Object regConfForConsumerTable[][] = { -// {"timeout", "registry.timeout", "int", 5000, 9000, "", "", "", "", ""}, -// {"file", "registry.file", "string", "", "regConfForServiceTable.log", "", "", "", "", ""}, -// {"wait", "registry.wait", "int", 0, 9000, "", "", "", "", ""}, -// {"transport", "registry.transporter", "string", "netty", "mina", "", "", "", "", ""}, - {"subscribe", "subscribe", "boolean", true, false, "", "", "", "", ""}, - {"dynamic", "dynamic", "boolean", true, false, "", "", "", "", ""}, + // {"timeout", "registry.timeout", "int", 5000, 9000, "", "", "", "", ""}, + // {"file", "registry.file", "string", "", "regConfForServiceTable.log", "", "", "", "", ""}, + // {"wait", "registry.wait", "int", 0, 9000, "", "", "", "", ""}, + // {"transport", "registry.transporter", "string", "netty", "mina", "", "", "", "", ""}, + {"subscribe", "subscribe", "boolean", true, false, "", "", "", "", ""}, + {"dynamic", "dynamic", "boolean", true, false, "", "", "", "", ""}, }; private Object regConfForReferenceTable[][] = { - {"timeout", "registry.timeout", "int", 5000, 9000, "", "", "", "", ""}, - {"file", "registry.file", "string", "", "regConfForServiceTable.log", "", "", "", "", ""}, - {"wait", "registry.wait", "int", 0, 9000, "", "", "", "", ""}, - {"transport", "registry.transporter", "string", "netty", "mina", "", "", "", "", ""}, - {"subscribe", "subscribe", "boolean", true, false, "", "", "", "", ""}, - {"dynamic", "dynamic", "boolean", true, false, "", "", "", "", ""}, + {"timeout", "registry.timeout", "int", 5000, 9000, "", "", "", "", ""}, + {"file", "registry.file", "string", "", "regConfForServiceTable.log", "", "", "", "", ""}, + {"wait", "registry.wait", "int", 0, 9000, "", "", "", "", ""}, + {"transport", "registry.transporter", "string", "netty", "mina", "", "", "", "", ""}, + {"subscribe", "subscribe", "boolean", true, false, "", "", "", "", ""}, + {"dynamic", "dynamic", "boolean", true, false, "", "", "", "", ""}, }; private Object methodConfForReferenceTable[][] = { - {"actives", "eatTiger.actives", "int", 0, 90, "", "", "", "", ""}, - {"executes", "eatTiger.executes", "int", 0, 90, "", "", "", "", ""}, - {"deprecated", "eatTiger.deprecated", "boolean", false, true, "", "", "", "", ""}, - {"async", "eatTiger.async", "boolean", false, true, "", "", "", "", ""}, - {"timeout", "eatTiger.timeout", "int", 0, 90, "", "", "", "", ""}, + {"actives", "eatTiger.actives", "int", 0, 90, "", "", "", "", ""}, + {"executes", "eatTiger.executes", "int", 0, 90, "", "", "", "", ""}, + {"deprecated", "eatTiger.deprecated", "boolean", false, true, "", "", "", "", ""}, + {"async", "eatTiger.async", "boolean", false, true, "", "", "", "", ""}, + {"timeout", "eatTiger.timeout", "int", 0, 90, "", "", "", "", ""}, }; private Object refConfTable[][] = { -// {"version", "version", "string", "0.0.0", "1.2.3", "", "", "", "", ""}, -// {"group", "group", "string", "", "HaominTest", "", "", "", "", ""}, + // {"version", "version", "string", "0.0.0", "1.2.3", "", "", "", "", ""}, + // {"group", "group", "string", "", "HaominTest", "", "", "", "", ""}, -// {"delay", "delay", "int", 0, 5, "", "", "", "", ""}, // not boolean - {"timeout", "timeout", "int", 5000, 3000, "", "", "", "", ""}, - {"retries", "retries", "int", 2, 5, "", "", "", "", ""}, - {"connections", "connections", "boolean", 100, 20, "", "", "", "", ""}, - {"loadbalance", "loadbalance", "string", "random", "roundrobin", "leastactive", "", "", ""}, - {"async", "async", "boolean", false, true, "", "", "", "", ""}, - //excluded = true -// {"generic", "generic", "boolean", false, true, "", "", "", "", ""}, - {"check", "check", "boolean", false, true, "", "", "", "", ""}, - //{"local", "local", "string", "false", "HelloServiceLocal", "true", "", "", "", ""}, - //{"local", "local", "string", "false", "true", "", "", "", "", ""}, - //{"mock", "mock", "string", "false", "dubbo.test.HelloServiceMock", "true", "", "", "", ""}, - {"mock", "mock", "string", "false", "false", "", "", "", "", ""}, - {"proxy", "proxy", "boolean", "javassist", "jdk", "", "", "", "", ""}, - {"client", "client", "string", "netty", "mina", "", "", "", "", ""}, - {"client", "client", "string", "netty", "mina", "", "", "", "", ""}, - {"owner", "owner", "string", "", "haomin,ludvik", "", "", "", "", ""}, - {"actives", "actives", "int", 0, 30, "", "", "", "", ""}, - {"cluster", "cluster", "string", "failover", "failfast", "failsafe", "failback", "forking", "", ""}, - //excluded = true -// {"filter", "service.filter", "string", "default", "-generic", "", "", "", "", ""}, - //excluded = true -// {"listener", "exporter.listener", "string", "default", "-deprecated", "", "", "", "", ""}, - //{"", "", "", "", "", "", "", "", "", ""}, + // {"delay", "delay", "int", 0, 5, "", "", "", "", ""}, // not boolean + {"timeout", "timeout", "int", 5000, 3000, "", "", "", "", ""}, + {"retries", "retries", "int", 2, 5, "", "", "", "", ""}, + {"connections", "connections", "boolean", 100, 20, "", "", "", "", ""}, + {"loadbalance", "loadbalance", "string", "random", "roundrobin", "leastactive", "", "", ""}, + {"async", "async", "boolean", false, true, "", "", "", "", ""}, + // excluded = true + // {"generic", "generic", "boolean", false, true, "", "", "", "", ""}, + {"check", "check", "boolean", false, true, "", "", "", "", ""}, + // {"local", "local", "string", "false", "HelloServiceLocal", "true", "", "", "", ""}, + // {"local", "local", "string", "false", "true", "", "", "", "", ""}, + // {"mock", "mock", "string", "false", "dubbo.test.HelloServiceMock", "true", "", "", "", ""}, + {"mock", "mock", "string", "false", "false", "", "", "", "", ""}, + {"proxy", "proxy", "boolean", "javassist", "jdk", "", "", "", "", ""}, + {"client", "client", "string", "netty", "mina", "", "", "", "", ""}, + {"client", "client", "string", "netty", "mina", "", "", "", "", ""}, + {"owner", "owner", "string", "", "haomin,ludvik", "", "", "", "", ""}, + {"actives", "actives", "int", 0, 30, "", "", "", "", ""}, + {"cluster", "cluster", "string", "failover", "failfast", "failsafe", "failback", "forking", "", ""}, + // excluded = true + // {"filter", "service.filter", "string", "default", "-generic", "", "", "", "", ""}, + // excluded = true + // {"listener", "exporter.listener", "string", "default", "-deprecated", "", "", "", "", ""}, + // {"", "", "", "", "", "", "", "", "", ""}, }; - private Object consumerConfTable[][] = {{"timeout", "timeout", "int", 5000, 8000, "", "", "", "", ""}, {"retries", "retries", "int", 2, 5, "", "", "", "", ""}, {"loadbalance", "loadbalance", "string", "random", "leastactive", "", "", "", "", ""}, {"async", "async", "boolean", false, true, "", "", "", "", ""}, {"connections", "connections", "int", 100, 5, "", "", "", "", ""}, -// {"generic", "generic", "boolean", false, false, "", "", "", "", ""}, - {"check", "check", "boolean", true, false, "", "", "", "", ""}, - {"proxy", "proxy", "string", "javassist", "jdk", "javassist", "", "", "", ""}, - {"owner", "owner", "string", "", "haomin", "", "", "", "", ""}, {"actives", "actives", "int", 0, 5, "", "", "", "", ""}, {"cluster", "cluster", "string", "failover", "forking", "", "", "", "", ""}, - {"filter", "", "string", "", "", "", "", "", "", ""}, - {"listener", "", "string", "", "", "", "", "", "", ""}, -// {"", "", "", "", "", "", "", "", "", ""}, + private Object consumerConfTable[][] = { + {"timeout", "timeout", "int", 5000, 8000, "", "", "", "", ""}, + {"retries", "retries", "int", 2, 5, "", "", "", "", ""}, + {"loadbalance", "loadbalance", "string", "random", "leastactive", "", "", "", "", ""}, + {"async", "async", "boolean", false, true, "", "", "", "", ""}, + {"connections", "connections", "int", 100, 5, "", "", "", "", ""}, + // {"generic", "generic", "boolean", false, false, "", "", "", "", ""}, + {"check", "check", "boolean", true, false, "", "", "", "", ""}, + {"proxy", "proxy", "string", "javassist", "jdk", "javassist", "", "", "", ""}, + {"owner", "owner", "string", "", "haomin", "", "", "", "", ""}, + {"actives", "actives", "int", 0, 5, "", "", "", "", ""}, + {"cluster", "cluster", "string", "failover", "forking", "", "", "", "", ""}, + {"filter", "", "string", "", "", "", "", "", "", ""}, + {"listener", "", "string", "", "", "", "", "", "", ""}, + // {"", "", "", "", "", "", "", "", "", ""}, }; // ====================================================== @@ -128,24 +135,22 @@ class InvokerSideConfigUrlTest extends UrlTestBase { @BeforeAll public static void start() { - //RegistryController.startRegistryIfAbsence(1); + // RegistryController.startRegistryIfAbsence(1); } - @BeforeEach public void setUp() { initServConf(); initRefConf(); -// ApplicationModel.defaultModel().getConfigManager().clear(); + // ApplicationModel.defaultModel().getConfigManager().clear(); } @AfterEach() public void teardown() { - //RegistryServer.reloadCache(); -// ApplicationModel.defaultModel().getConfigManager().clear(); + // RegistryServer.reloadCache(); + // ApplicationModel.defaultModel().getConfigManager().clear(); } - @Test void consumerConfUrlTest() { verifyInvokerUrlGeneration(consumerConf, consumerConfTable); @@ -156,7 +161,8 @@ class InvokerSideConfigUrlTest extends UrlTestBase { verifyInvokerUrlGeneration(refConf, refConfTable); } - @Disabled("parameter on register center will not be merged any longer with query parameter request from the consumer") + @Disabled( + "parameter on register center will not be merged any longer with query parameter request from the consumer") @Test void regConfForConsumerUrlTest() { verifyInvokerUrlGeneration(regConfForConsumer, regConfForConsumerTable); @@ -179,14 +185,14 @@ class InvokerSideConfigUrlTest extends UrlTestBase { refConf.setInterface("org.apache.dubbo.config.api.DemoService"); refConf.setApplication(application); -// consumerConf.setApplication(appConfForConsumer); + // consumerConf.setApplication(appConfForConsumer); refConf.setRegistry(regConfForReference); consumerConf.setRegistry(regConfForConsumer); refConf.setConsumer(consumerConf); - refConf.setMethods(Arrays.asList(new MethodConfig[]{methodConfForReference})); + refConf.setMethods(Arrays.asList(new MethodConfig[] {methodConfForReference})); refConf.setScope(SCOPE_REMOTE); } @@ -214,4 +220,4 @@ class InvokerSideConfigUrlTest extends UrlTestBase { private String getSubscribedUrlString() { return MockRegistry.getSubscribedUrl().toString(); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/RpcConfigGetSetProxy.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/RpcConfigGetSetProxy.java index a41988ade0..15dcc0fa61 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/RpcConfigGetSetProxy.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/RpcConfigGetSetProxy.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -23,13 +23,11 @@ import org.apache.dubbo.config.AbstractConfig; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; - public class RpcConfigGetSetProxy { private static final String RPC_CONFIG_BASECLASS = AbstractConfig.class.getName(); private static final Logger log = LoggerFactory.getLogger(RpcConfigGetSetProxy.class); - private Object proxiee = null; private Class proxieeClass = null; private Boolean isOk = false; @@ -45,10 +43,9 @@ public class RpcConfigGetSetProxy { } proxiee = p; - //proxieeClass = c; + // proxieeClass = c; proxieeClass = p.getClass(); isOk = true; - } public static boolean isKindOf(Class c, String type) { @@ -162,5 +159,4 @@ public class RpcConfigGetSetProxy { return getMethod(methodName, value, clazz); } - } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/UrlTestBase.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/UrlTestBase.java index 5328bff6b2..868081c094 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/UrlTestBase.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/UrlTestBase.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config.url; - import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.config.ApplicationConfig; @@ -66,11 +65,22 @@ public class UrlTestBase { {"deprecated", "deprecated", "boolean", false, true, "", "", "", "", ""}, {"dynamic", "dynamic", "boolean", true, false, "", "", "", "", ""}, {"accesslog", "accesslog", "string", "", "haominTest", "", "", "", "", ""}, - {"document", "document", "string", "", "http://dubbo.apache.org/zh-cn/docs/user/quick-start.html?testquery=你好你好", "", "", "", "", ""}, + { + "document", + "document", + "string", + "", + "http://dubbo.apache.org/zh-cn/docs/user/quick-start.html?testquery=你好你好", + "", + "", + "", + "", + "" + }, {"weight", "weight", "int", 0, 90, "", "", "", "", ""}, - //{"filter", "service.filter", "string", "", "", "", "", "", "", ""}, - //{"listener", "listener", "string", "", "", "", "", "", "", ""}, + // {"filter", "service.filter", "string", "", "", "", "", "", "", ""}, + // {"listener", "listener", "string", "", "", "", "", "", "", ""}, }; protected Object regConfForServiceTable[][] = { @@ -81,10 +91,16 @@ public class UrlTestBase { // {"subscribe", "subscribe", "boolean", true, false, "", "", "", "", ""}, {"dynamic", "dynamic", "boolean", true, false, "", "", "", "", ""}, }; - protected Object provConfTable[][] = {{"cluster", "cluster", "string", "string", "failover", "failfast", "failsafe", "", "", ""}, {"async", "async", "boolean", false, true, "", "", "", "", ""}, {"loadbalance", "loadbalance", "string", "random", "leastactive", "", "", "", "", ""}, {"connections", "connections", "int", 0, 60, "", "", "", "", ""}, {"retries", "retries", "int", 2, 60, "", "", "", "", ""}, {"timeout", "timeout", "int", 5000, 60, "", "", "", "", ""}, - //change by fengting listener 没有缺省值 - //{"listener", "exporter.listener", "string", "", "", "", "", "", "", ""}, - //{"filter", "service.filter", "string", "", "", "", "", "", "", ""}, + protected Object provConfTable[][] = { + {"cluster", "cluster", "string", "string", "failover", "failfast", "failsafe", "", "", ""}, + {"async", "async", "boolean", false, true, "", "", "", "", ""}, + {"loadbalance", "loadbalance", "string", "random", "leastactive", "", "", "", "", ""}, + {"connections", "connections", "int", 0, 60, "", "", "", "", ""}, + {"retries", "retries", "int", 2, 60, "", "", "", "", ""}, + {"timeout", "timeout", "int", 5000, 60, "", "", "", "", ""}, + // change by fengting listener 没有缺省值 + // {"listener", "exporter.listener", "string", "", "", "", "", "", "", ""}, + // {"filter", "service.filter", "string", "", "", "", "", "", "", ""}, }; protected Object methodConfForServiceTable[][] = { @@ -130,7 +146,6 @@ public class UrlTestBase { RpcConfigGetSetProxy proxy = new RpcConfigGetSetProxy(conf); proxy.setValue((String) row[KEY], row[column]); - } @SuppressWarnings("deprecation") @@ -143,7 +158,7 @@ public class UrlTestBase { methodConfForService = new MethodConfig(); servConf = new ServiceConfig(); -// provConf.setApplication(appConfForProvider); + // provConf.setApplication(appConfForProvider); application = new ApplicationConfig(); application.setMetadataServicePort(20881); servConf.setApplication(application); @@ -154,7 +169,7 @@ public class UrlTestBase { provConf.setProtocols(new ArrayList<>(Arrays.asList(protoConfForProvider))); servConf.setProtocols(new ArrayList<>(Arrays.asList(protoConfForService))); - servConf.setMethods(Arrays.asList(new MethodConfig[]{methodConfForService})); + servConf.setMethods(Arrays.asList(new MethodConfig[] {methodConfForService})); servConf.setProvider(provConf); servConf.setRef(demoService); @@ -176,8 +191,8 @@ public class UrlTestBase { * @param configName * @param column */ - protected void assertUrlStringWithLocalTable(String paramStringFromDb, - Object[][] dataTable, String configName, int column) { + protected void assertUrlStringWithLocalTable( + String paramStringFromDb, Object[][] dataTable, String configName, int column) { final String FAILLOG_HEADER = "The following config items are not found in URLONE: "; log.warn("Verifying service url for " + configName + "... "); @@ -200,5 +215,4 @@ public class UrlTestBase { fail(failLog); } } - } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/ConfigValidationUtilsTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/ConfigValidationUtilsTest.java index 0570638276..d19df85eec 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/ConfigValidationUtilsTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/ConfigValidationUtilsTest.java @@ -21,22 +21,21 @@ import org.apache.dubbo.config.AbstractInterfaceConfig; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MetadataReportConfig; +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.Map; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; -import java.lang.reflect.Field; -import java.util.HashMap; -import java.util.Map; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; - class ConfigValidationUtilsTest { @Test @@ -66,8 +65,10 @@ class ConfigValidationUtilsTest { @Test void testValidateApplicationConfig() throws Exception { - try (MockedStatic mockedStatic = Mockito.mockStatic(ConfigValidationUtils.class);) { - mockedStatic.when(() -> ConfigValidationUtils.validateApplicationConfig(any())).thenCallRealMethod(); + try (MockedStatic mockedStatic = Mockito.mockStatic(ConfigValidationUtils.class); ) { + mockedStatic + .when(() -> ConfigValidationUtils.validateApplicationConfig(any())) + .thenCallRealMethod(); ApplicationConfig config = new ApplicationConfig(); Assertions.assertThrows(IllegalStateException.class, () -> { ConfigValidationUtils.validateApplicationConfig(config); @@ -83,15 +84,21 @@ class ConfigValidationUtilsTest { map.put("k2", "v2"); config.setParameters(map); ConfigValidationUtils.validateApplicationConfig(config); - mockedStatic.verify(() -> { - ConfigValidationUtils.checkName(any(), any()); - }, times(4)); - mockedStatic.verify(() -> { - ConfigValidationUtils.checkMultiName(any(), any()); - }, times(1)); - mockedStatic.verify(() -> { - ConfigValidationUtils.checkParameterName(any()); - }, times(1)); + mockedStatic.verify( + () -> { + ConfigValidationUtils.checkName(any(), any()); + }, + times(4)); + mockedStatic.verify( + () -> { + ConfigValidationUtils.checkMultiName(any(), any()); + }, + times(1)); + mockedStatic.verify( + () -> { + ConfigValidationUtils.checkParameterName(any()); + }, + times(1)); } } @@ -116,8 +123,5 @@ class ConfigValidationUtilsTest { field.set(null, newValue); } - public static class InterfaceConfig extends AbstractInterfaceConfig { - - } - + public static class InterfaceConfig extends AbstractInterfaceConfig {} } diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/ReferenceCacheTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/ReferenceCacheTest.java index 22ad45a7ac..c231d892bc 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/ReferenceCacheTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/ReferenceCacheTest.java @@ -41,13 +41,15 @@ class ReferenceCacheTest { @Test void testGetCacheSameReference() throws Exception { ReferenceCache cache = SimpleReferenceCache.getCache(); - MockReferenceConfig config = buildMockReferenceConfig("org.apache.dubbo.config.utils.service.FooService", "group1", "1.0.0"); + MockReferenceConfig config = + buildMockReferenceConfig("org.apache.dubbo.config.utils.service.FooService", "group1", "1.0.0"); assertEquals(0L, config.getCounter()); Object proxy = cache.get(config); assertTrue(config.isGetMethodRun()); // singleton reference config by default - MockReferenceConfig configCopy = buildMockReferenceConfig("org.apache.dubbo.config.utils.service.FooService", "group1", "1.0.0"); + MockReferenceConfig configCopy = + buildMockReferenceConfig("org.apache.dubbo.config.utils.service.FooService", "group1", "1.0.0"); assertEquals(1L, configCopy.getCounter()); Object proxyOfCopyConfig = cache.get(configCopy); assertFalse(configCopy.isGetMethodRun()); @@ -60,7 +62,8 @@ class ReferenceCacheTest { @Test void testGetCacheDiffReference() throws Exception { ReferenceCache cache = SimpleReferenceCache.getCache(); - MockReferenceConfig config = buildMockReferenceConfig("org.apache.dubbo.config.utils.service.FooService", "group1", "1.0.0"); + MockReferenceConfig config = + buildMockReferenceConfig("org.apache.dubbo.config.utils.service.FooService", "group1", "1.0.0"); assertEquals(0L, config.getCounter()); cache.get(config); assertEquals(1L, config.getCounter()); @@ -68,7 +71,8 @@ class ReferenceCacheTest { cache.get(config); assertEquals(1L, config.getCounter()); - XxxMockReferenceConfig configCopy = buildXxxMockReferenceConfig("org.apache.dubbo.config.utils.service.XxxService", "group1", "1.0.0"); + XxxMockReferenceConfig configCopy = + buildXxxMockReferenceConfig("org.apache.dubbo.config.utils.service.XxxService", "group1", "1.0.0"); assertEquals(0L, configCopy.getCounter()); cache.get(configCopy); assertTrue(configCopy.isGetMethodRun()); @@ -78,15 +82,18 @@ class ReferenceCacheTest { @Test void testGetCacheWithKey() throws Exception { ReferenceCache cache = SimpleReferenceCache.getCache(); - MockReferenceConfig config = buildMockReferenceConfig("org.apache.dubbo.config.utils.service.FooService", "group1", "1.0.0"); + MockReferenceConfig config = + buildMockReferenceConfig("org.apache.dubbo.config.utils.service.FooService", "group1", "1.0.0"); FooService value = cache.get(config); - assertEquals(value, cache.get("group1/org.apache.dubbo.config.utils.service.FooService:1.0.0", FooService.class)); + assertEquals( + value, cache.get("group1/org.apache.dubbo.config.utils.service.FooService:1.0.0", FooService.class)); } @Test void testGetCacheDiffName() throws Exception { SimpleReferenceCache cache = SimpleReferenceCache.getCache(); - MockReferenceConfig config = buildMockReferenceConfig("org.apache.dubbo.config.utils.service.FooService", "group1", "1.0.0"); + MockReferenceConfig config = + buildMockReferenceConfig("org.apache.dubbo.config.utils.service.FooService", "group1", "1.0.0"); assertEquals(0L, config.getCounter()); cache.get(config); assertTrue(config.isGetMethodRun()); @@ -104,9 +111,11 @@ class ReferenceCacheTest { @Test void testDestroy() throws Exception { SimpleReferenceCache cache = SimpleReferenceCache.getCache(); - MockReferenceConfig config = buildMockReferenceConfig("org.apache.dubbo.config.utils.service.FooService", "group1", "1.0.0"); + MockReferenceConfig config = + buildMockReferenceConfig("org.apache.dubbo.config.utils.service.FooService", "group1", "1.0.0"); cache.get(config); - XxxMockReferenceConfig configCopy = buildXxxMockReferenceConfig("org.apache.dubbo.config.utils.service.XxxService", "group1", "1.0.0"); + XxxMockReferenceConfig configCopy = + buildXxxMockReferenceConfig("org.apache.dubbo.config.utils.service.XxxService", "group1", "1.0.0"); cache.get(configCopy); assertEquals(2, cache.getReferenceMap().size()); cache.destroy(config); @@ -120,9 +129,11 @@ class ReferenceCacheTest { @Test void testDestroyAll() throws Exception { SimpleReferenceCache cache = SimpleReferenceCache.getCache(); - MockReferenceConfig config = buildMockReferenceConfig("org.apache.dubbo.config.utils.service.FooService", "group1", "1.0.0"); + MockReferenceConfig config = + buildMockReferenceConfig("org.apache.dubbo.config.utils.service.FooService", "group1", "1.0.0"); cache.get(config); - XxxMockReferenceConfig configCopy = buildXxxMockReferenceConfig("org.apache.dubbo.config.utils.service.XxxService", "group1", "1.0.0"); + XxxMockReferenceConfig configCopy = + buildXxxMockReferenceConfig("org.apache.dubbo.config.utils.service.XxxService", "group1", "1.0.0"); cache.get(configCopy); assertEquals(2, cache.getReferenceMap().size()); cache.destroyAll(); @@ -152,5 +163,4 @@ class ReferenceCacheTest { config.setVersion(version); return config; } - -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/FooService.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/FooService.java index 9526ec1b53..836b1cbf75 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/FooService.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/FooService.java @@ -19,5 +19,4 @@ package org.apache.dubbo.config.utils.service; /** * */ -public interface FooService { -} +public interface FooService {} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/FooServiceImpl.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/FooServiceImpl.java index 24bef7689c..50f3652a6e 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/FooServiceImpl.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/FooServiceImpl.java @@ -19,5 +19,4 @@ package org.apache.dubbo.config.utils.service; /** * */ -public class FooServiceImpl implements FooService { -} +public class FooServiceImpl implements FooService {} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/XxxService.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/XxxService.java index 47641ed235..e112b48d0c 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/XxxService.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/XxxService.java @@ -19,5 +19,4 @@ package org.apache.dubbo.config.utils.service; /** * */ -public interface XxxService { -} +public interface XxxService {} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/XxxServiceImpl.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/XxxServiceImpl.java index fc8a87b2e9..7db91167ba 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/XxxServiceImpl.java +++ b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/XxxServiceImpl.java @@ -19,5 +19,4 @@ package org.apache.dubbo.config.utils.service; /** * */ -public class XxxServiceImpl implements XxxService { -} +public class XxxServiceImpl implements XxxService {} diff --git a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/metadata/MetadataServiceExporterTest.java b/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/metadata/MetadataServiceExporterTest.java deleted file mode 100644 index 93869ad63d..0000000000 --- a/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/metadata/MetadataServiceExporterTest.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.dubbo.metadata; -// -//import org.apache.dubbo.common.URL; -//import org.apache.dubbo.common.deploy.ApplicationDeployListener; -//import org.apache.dubbo.common.utils.NetUtils; -//import org.apache.dubbo.config.ApplicationConfig; -//import org.apache.dubbo.config.ProtocolConfig; -//import org.apache.dubbo.config.RegistryConfig; -//import org.apache.dubbo.config.ServiceConfig; -//import org.apache.dubbo.config.api.DemoService; -//import org.apache.dubbo.config.bootstrap.DubboBootstrap; -//import org.apache.dubbo.config.metadata.ConfigurableMetadataServiceExporter; -//import org.apache.dubbo.config.metadata.ExporterDeployListener; -//import org.apache.dubbo.registry.client.metadata.MetadataServiceDelegation; -//import org.apache.dubbo.config.provider.impl.DemoServiceImpl; -//import org.apache.dubbo.rpc.model.ApplicationModel; -//import org.apache.dubbo.rpc.model.FrameworkModel; -//import org.apache.dubbo.test.check.registrycenter.RegistryCenter; -// -//import org.junit.jupiter.api.BeforeAll; -//import org.junit.jupiter.api.BeforeEach; -//import org.junit.jupiter.api.Test; -//import org.mockito.Mockito; -// -//import java.util.List; -// -//import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE; -//import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; -//import static org.junit.jupiter.api.Assertions.assertEquals; -//import static org.junit.jupiter.api.Assertions.assertFalse; -//import static org.junit.jupiter.api.Assertions.assertNotEquals; -//import static org.junit.jupiter.api.Assertions.assertNotNull; -//import static org.junit.jupiter.api.Assertions.assertTrue; -// -//public class MetadataServiceExporterTest { -// -// @BeforeEach -// public void init() { -// DubboBootstrap.reset(); -// -// ApplicationConfig applicationConfig = new ApplicationConfig("Test"); -// applicationConfig.setRegisterConsumer(true); -// ApplicationModel.defaultModel().getApplicationConfigManager().setApplication(applicationConfig); -// ApplicationModel.defaultModel().getApplicationConfigManager().addRegistry(new RegistryConfig("multicast://224.5.6.7:1234")); -// ApplicationModel.defaultModel().getApplicationConfigManager().addProtocol(new ProtocolConfig("injvm")); -// } -// -// @Test -// public void test() { -// MetadataServiceDelegation metadataService = Mockito.mock(MetadataServiceDelegation.class); -// ConfigurableMetadataServiceExporter exporter = new ConfigurableMetadataServiceExporter(ApplicationModel.defaultModel(), metadataService); -// exporter.setMetadataService(metadataService); -// -// exporter.export(); -// assertTrue(exporter.isExported()); -// exporter.unexport(); -// -// } -// -// @Test -// public void test2() throws Exception { -// -// ApplicationModel applicationModel = ApplicationModel.defaultModel(); -// -// applicationModel.getDeployer().start().get(); -// ExporterDeployListener listener = getListener(applicationModel); -// ConfigurableMetadataServiceExporter exporter = listener.getMetadataServiceExporter(); -// -// assertTrue(exporter.isExported()); -// -// applicationModel.getDeployer().stop(); -// assertFalse(exporter.isExported()); -// } -// -// /** -// * test reuse of port started by normal service -// */ -// @Test -// public void testPortReuse() throws Exception { -// DubboBootstrap providerBootstrap = DubboBootstrap.newInstance(); -// ServiceConfig serviceConfig = new ServiceConfig<>(); -// serviceConfig.setInterface(DemoService.class); -// serviceConfig.setRef(new DemoServiceImpl()); -// -// ApplicationConfig applicationConfig = new ApplicationConfig("exporter-test"); -// applicationConfig.setMetadataType(DEFAULT_METADATA_STORAGE_TYPE); -// -// providerBootstrap -// .application(applicationConfig) -// .registry(registryConfig) -// .protocol(new ProtocolConfig("dubbo", 2002)) -// .service(serviceConfig); -// -// // will start exporter -// providerBootstrap.start(); -// ExporterDeployListener listener = getListener(providerBootstrap.getApplicationModel()); -// ConfigurableMetadataServiceExporter exporter = listener.getMetadataServiceExporter(); -// -// try { -// assertTrue(exporter.isExported()); -// List urls = exporter.getExportedURLs(); -// assertNotNull(urls); -// assertEquals(2002, urls.get(0).getPort()); -// assertEquals(DUBBO_PROTOCOL, urls.get(0).getProtocol()); -// } finally { -// providerBootstrap.stop(); -// } -// assertFalse(exporter.isExported()); -// } -// -// /** -// * test user specified port and protocol -// * @throws Exception -// */ -// @Test -// public void testSpecifiedPortAndProtocol() throws Exception { -// DubboBootstrap providerBootstrap = DubboBootstrap.newInstance(); -// ServiceConfig serviceConfig = new ServiceConfig<>(); -// serviceConfig.setInterface(DemoService.class); -// serviceConfig.setRef(new DemoServiceImpl()); -// -// ApplicationConfig applicationConfig = new ApplicationConfig("exporter-test"); -// applicationConfig.setMetadataType(DEFAULT_METADATA_STORAGE_TYPE); -// applicationConfig.setMetadataServiceProtocol("tri"); -// applicationConfig.setMetadataServicePort(8089); -// -// providerBootstrap -// .application(applicationConfig) -// .registry(registryConfig) -// .protocol(new ProtocolConfig("dubbo", 2002)) -// .service(serviceConfig); -// -// // will start exporter.export() -// providerBootstrap.start(); -// ExporterDeployListener listener = getListener(providerBootstrap.getApplicationModel()); -// ConfigurableMetadataServiceExporter exporter = listener.getMetadataServiceExporter(); -// -// try { -// assertTrue(exporter.isExported()); -// List urls = exporter.getExportedURLs(); -// assertNotNull(urls); -// assertEquals(8089, urls.get(0).getPort()); -// assertEquals("tri", urls.get(0).getProtocol()); -// } finally { -// providerBootstrap.stop(); -// } -// assertFalse(exporter.isExported()); -// } -// -// @Test -// public void testMetadataStartsBeforeNormalService() throws Exception { -// DubboBootstrap providerBootstrap = DubboBootstrap.newInstance(); -// ServiceConfig serviceConfig = new ServiceConfig<>(); -// serviceConfig.setInterface(DemoService.class); -// serviceConfig.setRef(new DemoServiceImpl()); -// serviceConfig.setDelay(1000); -// -// ApplicationConfig applicationConfig = new ApplicationConfig("exporter-test"); -// applicationConfig.setMetadataType(DEFAULT_METADATA_STORAGE_TYPE); -//// applicationConfig.setMetadataServiceProtocol("triple"); -//// applicationConfig.setMetadataServicePort(8089); -// -// providerBootstrap -// .application(applicationConfig) -// .registry(registryConfig) -// .protocol(new ProtocolConfig("dubbo", 2002)) -// .service(serviceConfig); -// -// // will start exporter.export() -// providerBootstrap.start(); -// ExporterDeployListener listener = getListener(providerBootstrap.getApplicationModel()); -// ConfigurableMetadataServiceExporter exporter = listener.getMetadataServiceExporter(); -// try { -// assertTrue(exporter.isExported()); -// List urls = exporter.getExportedURLs(); -// assertNotNull(urls); -// assertNotEquals(2002, urls.get(0).getPort()); -// assertEquals("dubbo", urls.get(0).getProtocol()); -// } finally { -// providerBootstrap.stop(); -// } -// assertFalse(exporter.isExported()); -// } -//// -//// /** -//// * test multiple protocols -//// * @throws Exception -//// */ -//// @Test -//// public void testMultiProtocols() throws Exception { -//// DubboBootstrap providerBootstrap = DubboBootstrap.newInstance(); -//// ServiceConfig serviceConfig = new ServiceConfig<>(); -//// serviceConfig.setInterface(DemoService.class); -//// serviceConfig.setRef(new DemoServiceImpl()); -//// -//// providerBootstrap -//// .application("provider-app") -//// .registry(registryConfig) -//// .protocol(new ProtocolConfig("dubbo", 2002)) -//// .service(serviceConfig); -//// -//// ConfigurableMetadataServiceExporter exporter = (ConfigurableMetadataServiceExporter) applicationModel.getExtensionLoader(MetadataServiceExporter.class).getDefaultExtension(); -//// MetadataService metadataService = Mockito.mock(MetadataService.class); -//// exporter.setMetadataService(metadataService); -//// -//// try { -//// providerBootstrap.start(); -//// assertTrue(exporter.isExported()); -//// assertTrue(exporter.supports(DEFAULT_METADATA_STORAGE_TYPE)); -//// assertTrue(exporter.supports(REMOTE_METADATA_STORAGE_TYPE)); -//// assertTrue(exporter.supports(COMPOSITE_METADATA_STORAGE_TYPE)); -//// } finally { -//// providerBootstrap.stop(); -//// } -//// assertFalse(exporter.isExported()); -//// } -// -// private static ZookeeperSingleRegistryCenter registryCenter; -// private static RegistryConfig registryConfig; -// -// @BeforeAll -// public static void beforeAll() { -// FrameworkModel.destroyAll(); -// registryCenter = new ZookeeperSingleRegistryCenter(NetUtils.getAvailablePort()); -// registryCenter.startup(); -// RegistryCenter.Instance instance = registryCenter.getRegistryCenterInstance().get(0); -// registryConfig = new RegistryConfig(String.format("%s://%s:%s", -// instance.getType(), -// instance.getHostname(), -// instance.getPort())); -// -// // pre-check threads -// //precheckUnclosedThreads(); -// } -// -// private ExporterDeployListener getListener(ApplicationModel model) { -// return (ExporterDeployListener)model.getExtensionLoader(ApplicationDeployListener.class).getExtension("exporter"); -// } -// -//} \ No newline at end of file diff --git a/dubbo-config/dubbo-config-spring/pom.xml b/dubbo-config/dubbo-config-spring/pom.xml index 1a86c15c26..80b0d8781f 100644 --- a/dubbo-config/dubbo-config-spring/pom.xml +++ b/dubbo-config/dubbo-config-spring/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-config - ${revision} - - dubbo-config-spring - jar - ${project.artifactId} - The spring config module of dubbo project - - false - 2.7.17 - - - + 4.0.0 + + org.apache.dubbo + dubbo-config + ${revision} + + dubbo-config-spring + jar + ${project.artifactId} + The spring config module of dubbo project + + false + 2.7.17 + + + - - - org.apache.dubbo - dubbo-config-api - ${project.parent.version} - + + + org.apache.dubbo + dubbo-config-api + ${project.parent.version} + - - org.apache.dubbo - dubbo-metrics-prometheus - ${project.parent.version} - test - + + org.apache.dubbo + dubbo-metrics-prometheus + ${project.parent.version} + test + - - org.springframework - spring-beans - - - org.springframework - spring-web - - - org.springframework - spring-context - - - javax.servlet - javax.servlet-api - provided - + + org.springframework + spring-beans + + + org.springframework + spring-web + + + org.springframework + spring-context + + + javax.servlet + javax.servlet-api + provided + - - com.alibaba.spring - spring-context-support - + + com.alibaba.spring + spring-context-support + - - - org.aspectj - aspectjweaver - 1.9.20.1 - test - - - org.apache.dubbo - dubbo-monitor-default - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-rpc-triple - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-rpc-injvm - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-rpc-rest - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-plugin-context - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-plugin-generic-invoke - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-plugin-classloader-filter - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-plugin-access-log - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-monitor-common - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-plugin-qos-trace - ${project.parent.version} - test - - - javax.validation - validation-api - test - - - org.hibernate - hibernate-validator - test - - - org.glassfish - javax.el - test - - - org.springframework - spring-tx - test - - - org.springframework - spring-test - test - - - org.apache.tomcat.embed - tomcat-embed-core - test - - - org.springframework.boot - spring-boot-starter-test - ${spring-boot.version} - test - - - logback-classic - ch.qos.logback - - - log4j-to-slf4j - org.apache.logging.log4j - - - + + + org.aspectj + aspectjweaver + 1.9.20.1 + test + + + org.apache.dubbo + dubbo-monitor-default + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-rpc-triple + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-rpc-injvm + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-rpc-rest + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-plugin-context + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-plugin-generic-invoke + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-plugin-classloader-filter + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-plugin-access-log + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-monitor-common + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-plugin-qos-trace + ${project.parent.version} + test + + + javax.validation + validation-api + test + + + org.hibernate + hibernate-validator + test + + + org.glassfish + javax.el + test + + + org.springframework + spring-tx + test + + + org.springframework + spring-test + test + + + org.apache.tomcat.embed + tomcat-embed-core + test + + + org.springframework.boot + spring-boot-starter-test + ${spring-boot.version} + test + + + ch.qos.logback + logback-classic + + + org.apache.logging.log4j + log4j-to-slf4j + + + - - org.slf4j - slf4j-log4j12 - test - + + org.slf4j + slf4j-log4j12 + test + - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.parent.version} - test - + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.parent.version} + test + - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.parent.version} - test - - - com.google.guava - guava - - - - - org.apache.dubbo - dubbo-remoting-zookeeper-curator5 - ${project.parent.version} - test - - - org.apache.curator - curator-recipes - test - - - org.apache.curator - curator-x-discovery - test - - - org.apache.zookeeper - zookeeper - test - + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${project.parent.version} + test + + + com.google.guava + guava + + + + + org.apache.dubbo + dubbo-remoting-zookeeper-curator5 + ${project.parent.version} + test + + + org.apache.curator + curator-recipes + test + + + org.apache.curator + curator-x-discovery + test + + + org.apache.zookeeper + zookeeper + test + - - - org.apache.dubbo - dubbo-registry-nacos - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-configcenter-nacos - ${project.parent.version} - test - - - com.alibaba.nacos - nacos-client - test - - + + + org.apache.dubbo + dubbo-registry-nacos + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-configcenter-nacos + ${project.parent.version} + test + + + com.alibaba.nacos + nacos-client + test + + - - - - src/test/resources - - - src/test/java - - **/*.xml - **/*.yml - **/*.properties - - - + + + + src/test/resources + + + src/test/java + + **/*.xml + **/*.yml + **/*.properties + + + - - - maven-surefire-plugin - org.apache.maven.plugins - - 1 - - - - - + + + org.apache.maven.plugins + maven-surefire-plugin + + 1 + + + + + diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ConfigCenterBean.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ConfigCenterBean.java index 3126a88a07..888d89c47d 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ConfigCenterBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ConfigCenterBean.java @@ -21,6 +21,9 @@ import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.ConfigCenterConfig; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.HashMap; +import java.util.Map; + import org.springframework.beans.factory.DisposableBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; @@ -29,9 +32,6 @@ import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.core.env.PropertySource; -import java.util.HashMap; -import java.util.Map; - /** * Starting from 2.7.0+, export and refer will only be executed when Spring is fully initialized. *

@@ -40,14 +40,14 @@ import java.util.Map; * So it's ok for this bean not to be the first Dubbo Config bean being initialized. *

*/ -public class ConfigCenterBean extends ConfigCenterConfig implements ApplicationContextAware, DisposableBean, EnvironmentAware { +public class ConfigCenterBean extends ConfigCenterConfig + implements ApplicationContextAware, DisposableBean, EnvironmentAware { private transient ApplicationContext applicationContext; private Boolean includeSpringEnv = false; - public ConfigCenterBean() { - } + public ConfigCenterBean() {} public ConfigCenterBean(ApplicationModel applicationModel) { super(applicationModel); @@ -59,9 +59,7 @@ public class ConfigCenterBean extends ConfigCenterConfig implements ApplicationC } @Override - public void destroy() throws Exception { - - } + public void destroy() throws Exception {} @Override public void setEnvironment(Environment environment) { @@ -69,7 +67,11 @@ public class ConfigCenterBean extends ConfigCenterConfig implements ApplicationC // Get PropertySource mapped to 'dubbo.properties' in Spring Environment. setExternalConfig(getConfigurations(getConfigFile(), environment)); // Get PropertySource mapped to 'application.dubbo.properties' in Spring Environment. - setAppExternalConfig(getConfigurations(StringUtils.isNotEmpty(getAppConfigFile()) ? getAppConfigFile() : ("application." + getConfigFile()), environment)); + setAppExternalConfig(getConfigurations( + StringUtils.isNotEmpty(getAppConfigFile()) + ? getAppConfigFile() + : ("application." + getConfigFile()), + environment)); } } @@ -85,7 +87,8 @@ public class ConfigCenterBean extends ConfigCenterConfig implements ApplicationC if (environment instanceof ConfigurableEnvironment && externalProperties.isEmpty()) { ConfigurableEnvironment configurableEnvironment = (ConfigurableEnvironment) environment; - PropertySource propertySource = configurableEnvironment.getPropertySources().get(key); + PropertySource propertySource = + configurableEnvironment.getPropertySources().get(key); if (propertySource != null) { Object source = propertySource.getSource(); if (source instanceof Map) { @@ -112,5 +115,4 @@ public class ConfigCenterBean extends ConfigCenterConfig implements ApplicationC public void setIncludeSpringEnv(Boolean includeSpringEnv) { this.includeSpringEnv = includeSpringEnv; } - } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/Constants.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/Constants.java index eec610059a..3846b001a2 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/Constants.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/Constants.java @@ -41,5 +41,4 @@ public interface Constants { * From FactoryBean.OBJECT_TYPE_ATTRIBUTE of Spring 5.2. */ String OBJECT_TYPE_ATTRIBUTE = "factoryBeanObjectType"; - } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ReferenceBean.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ReferenceBean.java index 28d0ef0973..e7c50bd7d9 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ReferenceBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ReferenceBean.java @@ -37,6 +37,12 @@ import org.apache.dubbo.config.spring.util.LockUtils; import org.apache.dubbo.config.support.Parameter; import org.apache.dubbo.rpc.proxy.AbstractProxyFactory; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.BeanNameAware; @@ -49,16 +55,9 @@ import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_INITIALIZER; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED; - /** *

* Spring FactoryBean for {@link ReferenceConfig}. @@ -106,8 +105,13 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED * @see org.apache.dubbo.config.annotation.DubboReference * @see org.apache.dubbo.config.spring.reference.ReferenceBeanBuilder */ -public class ReferenceBean implements FactoryBean, - ApplicationContextAware, BeanClassLoaderAware, BeanNameAware, InitializingBean, DisposableBean { +public class ReferenceBean + implements FactoryBean, + ApplicationContextAware, + BeanClassLoaderAware, + BeanNameAware, + InitializingBean, + DisposableBean { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); private transient ApplicationContext applicationContext; @@ -130,19 +134,20 @@ public class ReferenceBean implements FactoryBean, /* * remote service interface class name */ - // 'interfaceName' field for compatible with seata-1.4.0: io.seata.rm.tcc.remoting.parser.DubboRemotingParser#getServiceDesc() + // 'interfaceName' field for compatible with seata-1.4.0: + // io.seata.rm.tcc.remoting.parser.DubboRemotingParser#getServiceDesc() private String interfaceName; // proxy style private String proxy; - //from annotation attributes + // from annotation attributes private Map referenceProps; - //from xml bean definition + // from xml bean definition private MutablePropertyValues propertyValues; - //actual reference config + // actual reference config private ReferenceConfig referenceConfig; // ReferenceBeanManager @@ -227,7 +232,8 @@ public class ReferenceBean implements FactoryBean, Assert.notEmptyString(getId(), "The id of ReferenceBean cannot be empty"); BeanDefinition beanDefinition = beanFactory.getBeanDefinition(getId()); if (AotWithSpringDetector.useGeneratedArtifacts()) { - this.interfaceClass = (Class) beanDefinition.getPropertyValues().get(ReferenceAttributes.INTERFACE_CLASS); + this.interfaceClass = + (Class) beanDefinition.getPropertyValues().get(ReferenceAttributes.INTERFACE_CLASS); this.interfaceName = (String) beanDefinition.getPropertyValues().get(ReferenceAttributes.INTERFACE_NAME); } else { @@ -282,7 +288,6 @@ public class ReferenceBean implements FactoryBean, this.id = id; } - /** * The interface of this ReferenceBean, for injection purpose * @@ -342,14 +347,14 @@ public class ReferenceBean implements FactoryBean, */ private void createLazyProxy() { - //set proxy interfaces - //see also: org.apache.dubbo.rpc.proxy.AbstractProxyFactory.getProxy(org.apache.dubbo.rpc.Invoker, boolean) + // set proxy interfaces + // see also: org.apache.dubbo.rpc.proxy.AbstractProxyFactory.getProxy(org.apache.dubbo.rpc.Invoker, boolean) List> interfaces = new ArrayList<>(); interfaces.add(interfaceClass); Class[] internalInterfaces = AbstractProxyFactory.getInternalInterfaces(); Collections.addAll(interfaces, internalInterfaces); if (!StringUtils.isEquals(interfaceClass.getName(), interfaceName)) { - //add service interface + // add service interface try { Class serviceInterface = ClassUtils.forName(interfaceName, beanClassLoader); interfaces.add(serviceInterface); @@ -369,18 +374,37 @@ public class ReferenceBean implements FactoryBean, private void generateFromJavassistFirst(List> interfaces) { try { - this.lazyProxy = Proxy.getProxy(interfaces.toArray(new Class[0])).newInstance(new LazyTargetInvocationHandler(new DubboReferenceLazyInitTargetSource())); + this.lazyProxy = Proxy.getProxy(interfaces.toArray(new Class[0])) + .newInstance(new LazyTargetInvocationHandler(new DubboReferenceLazyInitTargetSource())); } catch (Throwable fromJavassist) { // try fall back to JDK proxy factory try { - this.lazyProxy = java.lang.reflect.Proxy.newProxyInstance(beanClassLoader, interfaces.toArray(new Class[0]), new LazyTargetInvocationHandler(new DubboReferenceLazyInitTargetSource())); - logger.error(PROXY_FAILED, "", "", "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy success. " + - "Interfaces: " + interfaces, fromJavassist); + this.lazyProxy = java.lang.reflect.Proxy.newProxyInstance( + beanClassLoader, + interfaces.toArray(new Class[0]), + new LazyTargetInvocationHandler(new DubboReferenceLazyInitTargetSource())); + logger.error( + PROXY_FAILED, + "", + "", + "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy success. " + + "Interfaces: " + interfaces, + fromJavassist); } catch (Throwable fromJdk) { - logger.error(PROXY_FAILED, "", "", "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. " + - "Interfaces: " + interfaces + " Javassist Error.", fromJavassist); - logger.error(PROXY_FAILED, "", "", "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. " + - "Interfaces: " + interfaces + " JDK Error.", fromJdk); + logger.error( + PROXY_FAILED, + "", + "", + "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. " + + "Interfaces: " + interfaces + " Javassist Error.", + fromJavassist); + logger.error( + PROXY_FAILED, + "", + "", + "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. " + + "Interfaces: " + interfaces + " JDK Error.", + fromJdk); throw fromJavassist; } } @@ -388,10 +412,18 @@ public class ReferenceBean implements FactoryBean, private void generateFromJdk(List> interfaces) { try { - this.lazyProxy = java.lang.reflect.Proxy.newProxyInstance(beanClassLoader, interfaces.toArray(new Class[0]), new LazyTargetInvocationHandler(new DubboReferenceLazyInitTargetSource())); + this.lazyProxy = java.lang.reflect.Proxy.newProxyInstance( + beanClassLoader, + interfaces.toArray(new Class[0]), + new LazyTargetInvocationHandler(new DubboReferenceLazyInitTargetSource())); } catch (Throwable fromJdk) { - logger.error(PROXY_FAILED, "", "", "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. " + - "Interfaces: " + interfaces + " JDK Error.", fromJdk); + logger.error( + PROXY_FAILED, + "", + "", + "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. " + + "Interfaces: " + interfaces + " JDK Error.", + fromJdk); throw fromJdk; } } @@ -399,13 +431,21 @@ public class ReferenceBean implements FactoryBean, private Object getCallProxy() throws Exception { if (referenceConfig == null) { referenceBeanManager.initReferenceBean(this); - applicationContext.getBean(DubboConfigApplicationListener.class.getName(), DubboConfigApplicationListener.class).init(); - logger.warn(CONFIG_DUBBO_BEAN_INITIALIZER, "", "", "ReferenceBean is not ready yet, please make sure to call reference interface method after dubbo is started."); + applicationContext + .getBean(DubboConfigApplicationListener.class.getName(), DubboConfigApplicationListener.class) + .init(); + logger.warn( + CONFIG_DUBBO_BEAN_INITIALIZER, + "", + "", + "ReferenceBean is not ready yet, please make sure to call reference interface method after dubbo is started."); } - //get reference proxy - //Subclasses should synchronize on the given Object if they perform any sort of extended singleton creation phase. - // In particular, subclasses should not have their own mutexes involved in singleton creation, to avoid the potential for deadlocks in lazy-init situations. - //The redundant type cast is to be compatible with earlier than spring-4.2 + // get reference proxy + // Subclasses should synchronize on the given Object if they perform any sort of extended singleton creation + // phase. + // In particular, subclasses should not have their own mutexes involved in singleton creation, to avoid the + // potential for deadlocks in lazy-init situations. + // The redundant type cast is to be compatible with earlier than spring-4.2 if (referenceConfig.configInitialized()) { return referenceConfig.get(); } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ServiceBean.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ServiceBean.java index 4a1d7279cc..c0d37d0352 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ServiceBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ServiceBean.java @@ -39,9 +39,12 @@ import org.springframework.context.ApplicationEventPublisherAware; * * @export */ -public class ServiceBean extends ServiceConfig implements InitializingBean, DisposableBean, - ApplicationContextAware, BeanNameAware, ApplicationEventPublisherAware { - +public class ServiceBean extends ServiceConfig + implements InitializingBean, + DisposableBean, + ApplicationContextAware, + BeanNameAware, + ApplicationEventPublisherAware { private static final long serialVersionUID = 213195494150089726L; @@ -111,7 +114,7 @@ public class ServiceBean extends ServiceConfig implements InitializingBean setPath(getInterface()); } } - //register service bean + // register service bean ModuleModel moduleModel = DubboBeanUtils.getModuleModel(applicationContext); moduleModel.getConfigManager().addService(this); moduleModel.getDeployer().setPending(); diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/SpringScopeModelInitializer.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/SpringScopeModelInitializer.java index a0750ee19b..136aed980e 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/SpringScopeModelInitializer.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/SpringScopeModelInitializer.java @@ -27,17 +27,11 @@ import org.apache.dubbo.rpc.model.ScopeModelInitializer; public class SpringScopeModelInitializer implements ScopeModelInitializer { @Override - public void initializeFrameworkModel(FrameworkModel frameworkModel) { - - } + public void initializeFrameworkModel(FrameworkModel frameworkModel) {} @Override - public void initializeApplicationModel(ApplicationModel applicationModel) { - - } + public void initializeApplicationModel(ApplicationModel applicationModel) {} @Override - public void initializeModuleModel(ModuleModel moduleModel) { - - } + public void initializeModuleModel(ModuleModel moduleModel) {} } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/aot/AotWithSpringDetector.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/aot/AotWithSpringDetector.java index 97111ed870..3bda2719d0 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/aot/AotWithSpringDetector.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/aot/AotWithSpringDetector.java @@ -17,6 +17,7 @@ package org.apache.dubbo.config.spring.aot; import org.apache.dubbo.common.aot.NativeDetector; + import org.springframework.core.SpringProperties; public abstract class AotWithSpringDetector { @@ -39,5 +40,4 @@ public abstract class AotWithSpringDetector { public static boolean useGeneratedArtifacts() { return (NativeDetector.inNativeImage() || SpringProperties.getFlag(AOT_ENABLED)); } - } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AbstractAnnotationBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AbstractAnnotationBeanPostProcessor.java index d77f838c44..37594fffe2 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AbstractAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AbstractAnnotationBeanPostProcessor.java @@ -20,6 +20,19 @@ import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.config.spring.util.AnnotationUtils; +import java.beans.PropertyDescriptor; +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + import org.springframework.beans.BeanUtils; import org.springframework.beans.BeansException; import org.springframework.beans.PropertyValues; @@ -42,19 +55,6 @@ import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; -import java.beans.PropertyDescriptor; -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; -import java.lang.reflect.Member; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_INITIALIZER; import static org.springframework.core.BridgeMethodResolver.findBridgedMethod; import static org.springframework.core.BridgeMethodResolver.isVisibilityBridgeMethodPair; @@ -63,18 +63,23 @@ import static org.springframework.core.BridgeMethodResolver.isVisibilityBridgeMe * Abstract common {@link BeanPostProcessor} implementation for customized annotation that annotated injected-object. */ @SuppressWarnings("unchecked") -public abstract class AbstractAnnotationBeanPostProcessor implements - InstantiationAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, - BeanFactoryAware, BeanClassLoaderAware, EnvironmentAware, DisposableBean { +public abstract class AbstractAnnotationBeanPostProcessor + implements InstantiationAwareBeanPostProcessor, + MergedBeanDefinitionPostProcessor, + BeanFactoryAware, + BeanClassLoaderAware, + EnvironmentAware, + DisposableBean { - private final static int CACHE_SIZE = Integer.getInteger("", 32); + private static final int CACHE_SIZE = Integer.getInteger("", 32); private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); private final Class[] annotationTypes; - private final ConcurrentMap injectionMetadataCache = - new ConcurrentHashMap(CACHE_SIZE); + private final ConcurrentMap + injectionMetadataCache = new ConcurrentHashMap< + String, AbstractAnnotationBeanPostProcessor.AnnotatedInjectionMetadata>(CACHE_SIZE); private ConfigurableListableBeanFactory beanFactory; @@ -117,8 +122,10 @@ public abstract class AbstractAnnotationBeanPostProcessor implements @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - Assert.isInstanceOf(ConfigurableListableBeanFactory.class, beanFactory, - "AnnotationInjectedBeanPostProcessor requires a ConfigurableListableBeanFactory"); + Assert.isInstanceOf( + ConfigurableListableBeanFactory.class, + beanFactory, + "AnnotationInjectedBeanPostProcessor requires a ConfigurableListableBeanFactory"); this.beanFactory = (ConfigurableListableBeanFactory) beanFactory; } @@ -128,21 +135,26 @@ public abstract class AbstractAnnotationBeanPostProcessor implements * @param beanClass The {@link Class} of Bean * @return non-null {@link List} */ - private List findFieldAnnotationMetadata(final Class beanClass) { + private List findFieldAnnotationMetadata( + final Class beanClass) { final List elements = new LinkedList<>(); ReflectionUtils.doWithFields(beanClass, field -> { - for (Class annotationType : getAnnotationTypes()) { - AnnotationAttributes attributes = AnnotationUtils.getAnnotationAttributes(field, annotationType, getEnvironment(), true, true); + AnnotationAttributes attributes = + AnnotationUtils.getAnnotationAttributes(field, annotationType, getEnvironment(), true, true); if (attributes != null) { if (Modifier.isStatic(field.getModifiers())) { if (logger.isWarnEnabled()) { - logger.warn(CONFIG_DUBBO_BEAN_INITIALIZER, "", "", "@" + annotationType.getName() + " is not supported on static fields: " + field); + logger.warn( + CONFIG_DUBBO_BEAN_INITIALIZER, + "", + "", + "@" + annotationType.getName() + " is not supported on static fields: " + field); } return; } @@ -153,7 +165,6 @@ public abstract class AbstractAnnotationBeanPostProcessor implements }); return elements; - } /** @@ -162,12 +173,12 @@ public abstract class AbstractAnnotationBeanPostProcessor implements * @param beanClass The {@link Class} of Bean * @return non-null {@link List} */ - private List findAnnotatedMethodMetadata(final Class beanClass) { + private List findAnnotatedMethodMetadata( + final Class beanClass) { final List elements = new LinkedList<>(); ReflectionUtils.doWithMethods(beanClass, method -> { - Method bridgedMethod = findBridgedMethod(method); if (!isVisibilityBridgeMethodPair(method, bridgedMethod)) { @@ -181,14 +192,17 @@ public abstract class AbstractAnnotationBeanPostProcessor implements for (Class annotationType : getAnnotationTypes()) { - AnnotationAttributes attributes = AnnotationUtils.getAnnotationAttributes(bridgedMethod, annotationType, getEnvironment(), true, true); + AnnotationAttributes attributes = AnnotationUtils.getAnnotationAttributes( + bridgedMethod, annotationType, getEnvironment(), true, true); if (attributes != null && method.equals(ClassUtils.getMostSpecificMethod(method, beanClass))) { if (Modifier.isStatic(method.getModifiers())) { - throw new IllegalStateException("When using @" + annotationType.getName() + " to inject interface proxy, it is not supported on static methods: " + method); + throw new IllegalStateException("When using @" + annotationType.getName() + + " to inject interface proxy, it is not supported on static methods: " + method); } if (method.getParameterTypes().length != 1) { - throw new IllegalStateException("When using @" + annotationType.getName() + " to inject interface proxy, the method must have only one parameter: " + method); + throw new IllegalStateException("When using @" + annotationType.getName() + + " to inject interface proxy, the method must have only one parameter: " + method); } PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, beanClass); elements.add(new AnnotatedMethodElement(method, pd, attributes)); @@ -199,9 +213,12 @@ public abstract class AbstractAnnotationBeanPostProcessor implements return elements; } - private AbstractAnnotationBeanPostProcessor.AnnotatedInjectionMetadata buildAnnotatedMetadata(final Class beanClass) { - Collection fieldElements = findFieldAnnotationMetadata(beanClass); - Collection methodElements = findAnnotatedMethodMetadata(beanClass); + private AbstractAnnotationBeanPostProcessor.AnnotatedInjectionMetadata buildAnnotatedMetadata( + final Class beanClass) { + Collection fieldElements = + findFieldAnnotationMetadata(beanClass); + Collection methodElements = + findAnnotatedMethodMetadata(beanClass); return new AnnotatedInjectionMetadata(beanClass, fieldElements, methodElements); } @@ -209,7 +226,8 @@ public abstract class AbstractAnnotationBeanPostProcessor implements // Fall back to class name as cache key, for backwards compatibility with custom callers. String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName()); // Quick check on the concurrent map first, with minimal locking. - AbstractAnnotationBeanPostProcessor.AnnotatedInjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey); + AbstractAnnotationBeanPostProcessor.AnnotatedInjectionMetadata metadata = + this.injectionMetadataCache.get(cacheKey); if (needsRefreshInjectionMetadata(metadata, clazz)) { synchronized (this.injectionMetadataCache) { metadata = this.injectionMetadataCache.get(cacheKey); @@ -222,8 +240,10 @@ public abstract class AbstractAnnotationBeanPostProcessor implements metadata = buildAnnotatedMetadata(clazz); this.injectionMetadataCache.put(cacheKey, metadata); } catch (NoClassDefFoundError err) { - throw new IllegalStateException("Failed to introspect object class [" + clazz.getName() + - "] for annotation metadata: could not find class that it depends on", err); + throw new IllegalStateException( + "Failed to introspect object class [" + clazz.getName() + + "] for annotation metadata: could not find class that it depends on", + err); } } } @@ -244,7 +264,6 @@ public abstract class AbstractAnnotationBeanPostProcessor implements if (logger.isInfoEnabled()) { logger.info(getClass() + " was destroying!"); } - } @Override @@ -280,8 +299,13 @@ public abstract class AbstractAnnotationBeanPostProcessor implements * @return An injected object * @throws Exception If getting is failed */ - protected Object getInjectedObject(AnnotationAttributes attributes, Object bean, String beanName, Class injectedType, - AnnotatedInjectElement injectedElement) throws Exception { + protected Object getInjectedObject( + AnnotationAttributes attributes, + Object bean, + String beanName, + Class injectedType, + AnnotatedInjectElement injectedElement) + throws Exception { return doGetInjectedBean(attributes, bean, beanName, injectedType, injectedElement); } @@ -291,8 +315,7 @@ public abstract class AbstractAnnotationBeanPostProcessor implements * @param metadata * @throws Exception */ - protected void prepareInjection(AnnotatedInjectionMetadata metadata) throws Exception { - } + protected void prepareInjection(AnnotatedInjectionMetadata metadata) throws Exception {} /** * Subclass must implement this method to get injected-object. The context objects could help this method if @@ -311,8 +334,13 @@ public abstract class AbstractAnnotationBeanPostProcessor implements * @return The injected object * @throws Exception If resolving an injected object is failed. */ - protected abstract Object doGetInjectedBean(AnnotationAttributes attributes, Object bean, String beanName, Class injectedType, - AnnotatedInjectElement injectedElement) throws Exception; + protected abstract Object doGetInjectedBean( + AnnotationAttributes attributes, + Object bean, + String beanName, + Class injectedType, + AnnotatedInjectElement injectedElement) + throws Exception; @Override public Object postProcessBeforeInstantiation(Class beanClass, String beanName) throws BeansException { @@ -344,8 +372,10 @@ public abstract class AbstractAnnotationBeanPostProcessor implements private final Collection methodElements; - public AnnotatedInjectionMetadata(Class targetClass, Collection fieldElements, - Collection methodElements) { + public AnnotatedInjectionMetadata( + Class targetClass, + Collection fieldElements, + Collection methodElements) { super(targetClass, combine(fieldElements, methodElements)); this.targetClass = targetClass; this.fieldElements = fieldElements; @@ -360,12 +390,12 @@ public abstract class AbstractAnnotationBeanPostProcessor implements return methodElements; } - //@Override // since Spring 5.2.4 + // @Override // since Spring 5.2.4 protected boolean needsRefresh(Class clazz) { if (this.targetClass == clazz) { return false; } - //IGNORE Spring CGLIB enhanced class + // IGNORE Spring CGLIB enhanced class if (targetClass.isAssignableFrom(clazz) && clazz.getName().contains("$$EnhancerBySpringCGLIB$$")) { return false; } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationPropertyValuesAdapter.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationPropertyValuesAdapter.java index c0c2e96eb2..fd871607d4 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationPropertyValuesAdapter.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationPropertyValuesAdapter.java @@ -18,14 +18,14 @@ package org.apache.dubbo.config.spring.beans.factory.annotation; import org.apache.dubbo.config.spring.util.AnnotationUtils; +import java.lang.annotation.Annotation; +import java.util.Map; + import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.PropertyValue; import org.springframework.beans.PropertyValues; import org.springframework.core.env.PropertyResolver; -import java.lang.annotation.Annotation; -import java.util.Map; - /** * {@link Annotation} {@link PropertyValues} Adapter * @@ -43,17 +43,23 @@ public class AnnotationPropertyValuesAdapter implements PropertyValues { * @param ignoreAttributeNames * @since 2.7.3 */ - public AnnotationPropertyValuesAdapter(Map attributes, PropertyResolver propertyResolver, - String... ignoreAttributeNames) { - this.delegate = new MutablePropertyValues(AnnotationUtils.getAttributes(attributes, propertyResolver, ignoreAttributeNames)); + public AnnotationPropertyValuesAdapter( + Map attributes, PropertyResolver propertyResolver, String... ignoreAttributeNames) { + this.delegate = new MutablePropertyValues( + AnnotationUtils.getAttributes(attributes, propertyResolver, ignoreAttributeNames)); } - public AnnotationPropertyValuesAdapter(Annotation annotation, PropertyResolver propertyResolver, - boolean ignoreDefaultValue, String... ignoreAttributeNames) { - this.delegate = new MutablePropertyValues(AnnotationUtils.getAttributes(annotation, propertyResolver, ignoreDefaultValue, ignoreAttributeNames)); + public AnnotationPropertyValuesAdapter( + Annotation annotation, + PropertyResolver propertyResolver, + boolean ignoreDefaultValue, + String... ignoreAttributeNames) { + this.delegate = new MutablePropertyValues( + AnnotationUtils.getAttributes(annotation, propertyResolver, ignoreDefaultValue, ignoreAttributeNames)); } - public AnnotationPropertyValuesAdapter(Annotation annotation, PropertyResolver propertyResolver, String... ignoreAttributeNames) { + public AnnotationPropertyValuesAdapter( + Annotation annotation, PropertyResolver propertyResolver, String... ignoreAttributeNames) { this(annotation, propertyResolver, true, ignoreAttributeNames); } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/DubboConfigAliasPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/DubboConfigAliasPostProcessor.java index 84a1eb03a2..d8dc09388b 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/DubboConfigAliasPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/DubboConfigAliasPostProcessor.java @@ -39,7 +39,7 @@ public class DubboConfigAliasPostProcessor implements BeanDefinitionRegistryPost /** * The bean name of {@link DubboConfigConfigurationRegistrar} */ - public final static String BEAN_NAME = "dubboConfigAliasPostProcessor"; + public static final String BEAN_NAME = "dubboConfigAliasPostProcessor"; private BeanDefinitionRegistry registry; @@ -63,9 +63,9 @@ public class DubboConfigAliasPostProcessor implements BeanDefinitionRegistryPost public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof AbstractConfig) { String id = ((AbstractConfig) bean).getId(); - if (hasText(id) // id MUST be present in AbstractConfig - && !nullSafeEquals(id, beanName) // id MUST NOT be equal to bean name - && !BeanRegistrar.hasAlias(registry, beanName, id)) { // id MUST NOT be present in AliasRegistry + if (hasText(id) // id MUST be present in AbstractConfig + && !nullSafeEquals(id, beanName) // id MUST NOT be equal to bean name + && !BeanRegistrar.hasAlias(registry, beanName, id)) { // id MUST NOT be present in AliasRegistry registry.registerAlias(beanName, id); } } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java index aa359963d5..9cabb595d9 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config.spring.beans.factory.annotation; - import org.apache.dubbo.common.compact.Dubbo2CompactUtils; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -36,6 +35,18 @@ import org.apache.dubbo.config.spring.util.AnnotationUtils; import org.apache.dubbo.config.spring.util.SpringCompatUtils; import org.apache.dubbo.rpc.service.GenericService; +import java.beans.PropertyDescriptor; +import java.lang.annotation.Annotation; +import java.lang.reflect.Member; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + import org.springframework.beans.BeansException; import org.springframework.beans.PropertyValue; import org.springframework.beans.PropertyValues; @@ -56,18 +67,6 @@ import org.springframework.context.ApplicationContextAware; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.type.MethodMetadata; -import java.beans.PropertyDescriptor; -import java.lang.annotation.Annotation; -import java.lang.reflect.Member; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_INITIALIZER; import static org.apache.dubbo.common.utils.AnnotationUtils.filterDefaultValues; import static org.springframework.util.StringUtils.hasText; @@ -91,7 +90,7 @@ import static org.springframework.util.StringUtils.hasText; * @since 2.5.7 */ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBeanPostProcessor - implements ApplicationContextAware, BeanFactoryPostProcessor { + implements ApplicationContextAware, BeanFactoryPostProcessor { /** * The bean name of {@link ReferenceAnnotationBeanPostProcessor} @@ -106,10 +105,10 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); private final ConcurrentMap injectedFieldReferenceBeanCache = - new ConcurrentHashMap<>(CACHE_SIZE); + new ConcurrentHashMap<>(CACHE_SIZE); private final ConcurrentMap injectedMethodReferenceBeanCache = - new ConcurrentHashMap<>(CACHE_SIZE); + new ConcurrentHashMap<>(CACHE_SIZE); protected ApplicationContext applicationContext; @@ -128,9 +127,10 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean @SuppressWarnings("unchecked") private static Class[] loadAnnotationTypes() { if (Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isReferenceClassLoaded()) { - return (Class[])new Class[]{DubboReference.class, Reference.class, Dubbo2CompactUtils.getReferenceClass()}; + return (Class[]) + new Class[] {DubboReference.class, Reference.class, Dubbo2CompactUtils.getReferenceClass()}; } else { - return (Class[])new Class[]{DubboReference.class, Reference.class}; + return (Class[]) new Class[] {DubboReference.class, Reference.class}; } } @@ -172,8 +172,10 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean List beanPostProcessors = ((AbstractBeanFactory) beanFactory).getBeanPostProcessors(); for (BeanPostProcessor beanPostProcessor : beanPostProcessors) { if (beanPostProcessor == this) { - // This bean has been registered as BeanPostProcessor at org.apache.dubbo.config.spring.context.DubboInfraBeanRegisterPostProcessor.postProcessBeanFactory() - // so destroy this bean here, prevent register it as BeanPostProcessor again, avoid cause BeanPostProcessorChecker detection error + // This bean has been registered as BeanPostProcessor at + // org.apache.dubbo.config.spring.context.DubboInfraBeanRegisterPostProcessor.postProcessBeanFactory() + // so destroy this bean here, prevent register it as BeanPostProcessor again, avoid cause + // BeanPostProcessorChecker detection error beanDefinitionRegistry.removeBeanDefinition(BEAN_NAME); break; } @@ -181,11 +183,16 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean } try { - // this is an early event, it will be notified at org.springframework.context.support.AbstractApplicationContext.registerListeners() + // this is an early event, it will be notified at + // org.springframework.context.support.AbstractApplicationContext.registerListeners() applicationContext.publishEvent(new DubboConfigInitEvent(applicationContext)); } catch (Exception e) { // if spring version is less than 4.2, it does not support early application event - logger.warn(CONFIG_DUBBO_BEAN_INITIALIZER, "", "", "publish early application event failed, please upgrade spring version to 4.2.x or later: " + e); + logger.warn( + CONFIG_DUBBO_BEAN_INITIALIZER, + "", + "", + "publish early application event failed, please upgrade spring version to 4.2.x or later: " + e); } } @@ -226,7 +233,8 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean MethodMetadata factoryMethodMetadata = SpringCompatUtils.getFactoryMethodMetadata(beanDefinition); // Extract beanClass from generic return type of java-config bean method: ReferenceBean - // see org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryBeanFromMethod + // see + // org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryBeanFromMethod Class beanClass = getBeanFactory().getType(beanName); if (beanClass == Object.class) { beanClass = SpringCompatUtils.getGenericTypeOfReturnType(factoryMethodMetadata); @@ -237,10 +245,13 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean } if (beanClass == null) { - String beanMethodSignature = factoryMethodMetadata.getDeclaringClassName() + "#" + factoryMethodMetadata.getMethodName() + "()"; - throw new BeanCreationException("The ReferenceBean is missing necessary generic type, which returned by the @Bean method of Java-config class. " + - "The generic type of the returned ReferenceBean must be specified as the referenced interface type, " + - "such as ReferenceBean. Please check bean method: " + beanMethodSignature); + String beanMethodSignature = + factoryMethodMetadata.getDeclaringClassName() + "#" + factoryMethodMetadata.getMethodName() + "()"; + throw new BeanCreationException( + "The ReferenceBean is missing necessary generic type, which returned by the @Bean method of Java-config class. " + + "The generic type of the returned ReferenceBean must be specified as the referenced interface type, " + + "such as ReferenceBean. Please check bean method: " + + beanMethodSignature); } // get dubbo reference annotation attributes @@ -270,12 +281,16 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean // check beanClass and reference interface class if (!StringUtils.isEquals(interfaceName, beanClass.getName()) && beanClass != GenericService.class) { - String beanMethodSignature = factoryMethodMetadata.getDeclaringClassName() + "#" + factoryMethodMetadata.getMethodName() + "()"; - throw new BeanCreationException("The 'interfaceClass' or 'interfaceName' attribute value of @DubboReference annotation " + - "is inconsistent with the generic type of the ReferenceBean returned by the bean method. " + - "The interface class of @DubboReference is: " + interfaceName + ", but return ReferenceBean<" + beanClass.getName() + ">. " + - "Please remove the 'interfaceClass' and 'interfaceName' attributes from @DubboReference annotation. " + - "Please check bean method: " + beanMethodSignature); + String beanMethodSignature = factoryMethodMetadata.getDeclaringClassName() + "#" + + factoryMethodMetadata.getMethodName() + "()"; + throw new BeanCreationException( + "The 'interfaceClass' or 'interfaceName' attribute value of @DubboReference annotation " + + "is inconsistent with the generic type of the ReferenceBean returned by the bean method. " + + "The interface class of @DubboReference is: " + + interfaceName + ", but return ReferenceBean<" + beanClass.getName() + ">. " + + "Please remove the 'interfaceClass' and 'interfaceName' attributes from @DubboReference annotation. " + + "Please check bean method: " + + beanMethodSignature); } Class interfaceClass = beanClass; @@ -301,14 +316,15 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class beanType, String beanName) { if (beanType != null) { if (isReferenceBean(beanDefinition)) { - //mark property value as optional - List propertyValues = beanDefinition.getPropertyValues().getPropertyValueList(); + // mark property value as optional + List propertyValues = + beanDefinition.getPropertyValues().getPropertyValueList(); for (PropertyValue propertyValue : propertyValues) { propertyValue.setOptional(true); } } else if (isAnnotatedReferenceBean(beanDefinition)) { // extract beanClass from java-config bean method generic return type: ReferenceBean - //Class beanClass = getBeanFactory().getType(beanName); + // Class beanClass = getBeanFactory().getType(beanName); } else { AnnotatedInjectionMetadata metadata = findInjectionMetadata(beanName, beanType, null); metadata.checkConfigMembers(beanDefinition); @@ -329,7 +345,7 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean * @see #postProcessProperties */ public PropertyValues postProcessPropertyValues( - PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException { + PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException { return postProcessProperties(pvs, bean, beanName); } @@ -340,7 +356,7 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean */ @Override public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) - throws BeansException { + throws BeansException { try { AnnotatedInjectionMetadata metadata = findInjectionMetadata(beanName, bean.getClass(), pvs); prepareInjection(metadata); @@ -348,8 +364,8 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean } catch (BeansException ex) { throw ex; } catch (Throwable ex) { - throw new BeanCreationException(beanName, "Injection of @" + getAnnotationType().getSimpleName() - + " dependencies is failed", ex); + throw new BeanCreationException( + beanName, "Injection of @" + getAnnotationType().getSimpleName() + " dependencies is failed", ex); } return pvs; } @@ -360,19 +376,19 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean protected void prepareInjection(AnnotatedInjectionMetadata metadata) throws BeansException { try { - //find and register bean definition for @DubboReference/@Reference + // find and register bean definition for @DubboReference/@Reference for (AnnotatedFieldElement fieldElement : metadata.getFieldElements()) { if (fieldElement.injectedObject != null) { continue; } Class injectedType = fieldElement.field.getType(); AnnotationAttributes attributes = fieldElement.attributes; - String referenceBeanName = registerReferenceBean(fieldElement.getPropertyName(), injectedType, attributes, fieldElement.field); + String referenceBeanName = registerReferenceBean( + fieldElement.getPropertyName(), injectedType, attributes, fieldElement.field); - //associate fieldElement and reference bean + // associate fieldElement and reference bean fieldElement.injectedObject = referenceBeanName; injectedFieldReferenceBeanCache.put(fieldElement, referenceBeanName); - } for (AnnotatedMethodElement methodElement : metadata.getMethodElements()) { @@ -381,9 +397,10 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean } Class injectedType = methodElement.getInjectedType(); AnnotationAttributes attributes = methodElement.attributes; - String referenceBeanName = registerReferenceBean(methodElement.getPropertyName(), injectedType, attributes, methodElement.method); + String referenceBeanName = registerReferenceBean( + methodElement.getPropertyName(), injectedType, attributes, methodElement.method); - //associate methodElement and reference bean + // associate methodElement and reference bean methodElement.injectedObject = referenceBeanName; injectedMethodReferenceBeanCache.put(methodElement, referenceBeanName); } @@ -392,7 +409,9 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean } } - public String registerReferenceBean(String propertyName, Class injectedType, Map attributes, Member member) throws BeansException { + public String registerReferenceBean( + String propertyName, Class injectedType, Map attributes, Member member) + throws BeansException { boolean renameable = true; // referenceBeanName @@ -411,7 +430,9 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean // get interface String interfaceName = (String) attributes.get(ReferenceAttributes.INTERFACE); if (StringUtils.isBlank(interfaceName)) { - throw new BeanCreationException("Need to specify the 'interfaceName' or 'interfaceClass' attribute of '@DubboReference' if enable generic. " + checkLocation); + throw new BeanCreationException( + "Need to specify the 'interfaceName' or 'interfaceClass' attribute of '@DubboReference' if enable generic. " + + checkLocation); } // check reference key @@ -426,9 +447,10 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean } } - //check bean definition + // check bean definition boolean isContains; - if ((isContains = beanDefinitionRegistry.containsBeanDefinition(referenceBeanName)) || beanDefinitionRegistry.isAlias(referenceBeanName)) { + if ((isContains = beanDefinitionRegistry.containsBeanDefinition(referenceBeanName)) + || beanDefinitionRegistry.isAlias(referenceBeanName)) { String preReferenceBeanName = referenceBeanName; if (!isContains) { // Look in the alias for the origin bean name @@ -448,30 +470,34 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean String newBeanDesc = referenceBeanName + "[" + referenceKey + "]"; if (isReferenceBean(prevBeanDefinition)) { - //check reference key - String prevReferenceKey = ReferenceBeanSupport.generateReferenceKey(prevBeanDefinition, applicationContext); + // check reference key + String prevReferenceKey = + ReferenceBeanSupport.generateReferenceKey(prevBeanDefinition, applicationContext); if (StringUtils.isEquals(prevReferenceKey, referenceKey)) { - //found matched dubbo reference bean, ignore register + // found matched dubbo reference bean, ignore register return referenceBeanName; } - //get interfaceName from attribute + // get interfaceName from attribute Assert.notNull(prevBeanDefinition, "The interface class of ReferenceBean is not initialized"); prevBeanDesc = referenceBeanName + "[" + prevReferenceKey + "]"; } // bean name from attribute 'id' or java-config bean, cannot be renamed if (!renameable) { - throw new BeanCreationException("Already exists another bean definition with the same bean name [" + referenceBeanName + "], " + - "but cannot rename the reference bean name (specify the id attribute or java-config bean), " + - "please modify the name of one of the beans: " + - "prev: " + prevBeanDesc + ", new: " + newBeanDesc + ". " + checkLocation); + throw new BeanCreationException( + "Already exists another bean definition with the same bean name [" + referenceBeanName + "], " + + "but cannot rename the reference bean name (specify the id attribute or java-config bean), " + + "please modify the name of one of the beans: " + + "prev: " + + prevBeanDesc + ", new: " + newBeanDesc + ". " + checkLocation); } // the prev bean type is different, rename the new reference bean int index = 2; String newReferenceBeanName = null; - while (newReferenceBeanName == null || beanDefinitionRegistry.containsBeanDefinition(newReferenceBeanName) - || beanDefinitionRegistry.isAlias(newReferenceBeanName)) { + while (newReferenceBeanName == null + || beanDefinitionRegistry.containsBeanDefinition(newReferenceBeanName) + || beanDefinitionRegistry.isAlias(newReferenceBeanName)) { newReferenceBeanName = referenceBeanName + "#" + index; index++; // double check found same name and reference key @@ -481,10 +507,16 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean } newBeanDesc = newReferenceBeanName + "[" + referenceKey + "]"; - logger.warn(CONFIG_DUBBO_BEAN_INITIALIZER, "", "", "Already exists another bean definition with the same bean name [" + referenceBeanName + "], " + - "rename dubbo reference bean to [" + newReferenceBeanName + "]. " + - "It is recommended to modify the name of one of the beans to avoid injection problems. " + - "prev: " + prevBeanDesc + ", new: " + newBeanDesc + ". " + checkLocation); + logger.warn( + CONFIG_DUBBO_BEAN_INITIALIZER, + "", + "", + "Already exists another bean definition with the same bean name [" + referenceBeanName + "], " + + "rename dubbo reference bean to [" + + newReferenceBeanName + "]. " + + "It is recommended to modify the name of one of the beans to avoid injection problems. " + + "prev: " + + prevBeanDesc + ", new: " + newBeanDesc + ". " + checkLocation); referenceBeanName = newReferenceBeanName; } attributes.put(ReferenceAttributes.ID, referenceBeanName); @@ -513,11 +545,13 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean beanDefinition.getPropertyValues().add(ReferenceAttributes.INTERFACE_CLASS, interfaceClass); beanDefinition.getPropertyValues().add(ReferenceAttributes.INTERFACE_NAME, interfaceName); - // create decorated definition for reference bean, Avoid being instantiated when getting the beanType of ReferenceBean + // create decorated definition for reference bean, Avoid being instantiated when getting the beanType of + // ReferenceBean // see org.springframework.beans.factory.support.AbstractBeanFactory#getTypeForFactoryBean() GenericBeanDefinition targetDefinition = new GenericBeanDefinition(); targetDefinition.setBeanClass(interfaceClass); - beanDefinition.setDecoratedDefinition(new BeanDefinitionHolder(targetDefinition, referenceBeanName + "_decorated")); + beanDefinition.setDecoratedDefinition( + new BeanDefinitionHolder(targetDefinition, referenceBeanName + "_decorated")); // signal object type since Spring 5.2 beanDefinition.setAttribute(Constants.OBJECT_TYPE_ATTRIBUTE, interfaceClass); @@ -529,11 +563,17 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean } @Override - protected Object doGetInjectedBean(AnnotationAttributes attributes, Object bean, String beanName, Class injectedType, - AnnotatedInjectElement injectedElement) throws Exception { + protected Object doGetInjectedBean( + AnnotationAttributes attributes, + Object bean, + String beanName, + Class injectedType, + AnnotatedInjectElement injectedElement) + throws Exception { if (injectedElement.injectedObject == null) { - throw new IllegalStateException("The AnnotatedInjectElement of @DubboReference should be inited before injection"); + throw new IllegalStateException( + "The AnnotatedInjectElement of @DubboReference should be inited before injection"); } return getBeanFactory().getBean((String) injectedElement.injectedObject); @@ -542,7 +582,8 @@ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBean @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; - this.referenceBeanManager = applicationContext.getBean(ReferenceBeanManager.BEAN_NAME, ReferenceBeanManager.class); + this.referenceBeanManager = + applicationContext.getBean(ReferenceBeanManager.BEAN_NAME, ReferenceBeanManager.class); this.beanDefinitionRegistry = (BeanDefinitionRegistry) applicationContext.getAutowireCapableBeanFactory(); } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessor.java index 872c21d54b..ddfc9424da 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessor.java @@ -35,6 +35,20 @@ import org.apache.dubbo.config.spring.schema.AnnotationBeanDefinitionParser; import org.apache.dubbo.config.spring.util.DubboAnnotationUtils; import org.apache.dubbo.config.spring.util.ObjectUtils; import org.apache.dubbo.config.spring.util.SpringCompatUtils; + +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + import org.springframework.beans.BeansException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.BeanClassLoaderAware; @@ -69,19 +83,6 @@ import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.core.type.filter.TypeFilter; import org.springframework.util.CollectionUtils; -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - import static java.util.Arrays.asList; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUPLICATED_BEAN_DEFINITION; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_NO_ANNOTATIONS_FOUND; @@ -101,30 +102,34 @@ import static org.springframework.util.ClassUtils.resolveClassName; * @see BeanDefinitionRegistryPostProcessor * @since 2.7.7 */ -public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPostProcessor, EnvironmentAware, - ResourceLoaderAware, BeanClassLoaderAware, ApplicationContextAware, InitializingBean { +public class ServiceAnnotationPostProcessor + implements BeanDefinitionRegistryPostProcessor, + EnvironmentAware, + ResourceLoaderAware, + BeanClassLoaderAware, + ApplicationContextAware, + InitializingBean { public static final String BEAN_NAME = "dubboServiceAnnotationPostProcessor"; - private final static List> serviceAnnotationTypes = loadServiceAnnotationTypes(); + private static final List> serviceAnnotationTypes = loadServiceAnnotationTypes(); private static List> loadServiceAnnotationTypes() { if (Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isServiceClassLoaded()) { return asList( - // @since 2.7.7 Add the @DubboService , the issue : https://github.com/apache/dubbo/issues/6007 - DubboService.class, - // @since 2.7.0 the substitute @com.alibaba.dubbo.config.annotation.Service - Service.class, - // @since 2.7.3 Add the compatibility for legacy Dubbo's @Service , the issue : https://github.com/apache/dubbo/issues/4330 - Dubbo2CompactUtils.getServiceClass() - ); + // @since 2.7.7 Add the @DubboService , the issue : https://github.com/apache/dubbo/issues/6007 + DubboService.class, + // @since 2.7.0 the substitute @com.alibaba.dubbo.config.annotation.Service + Service.class, + // @since 2.7.3 Add the compatibility for legacy Dubbo's @Service , the issue : + // https://github.com/apache/dubbo/issues/4330 + Dubbo2CompactUtils.getServiceClass()); } else { return asList( - // @since 2.7.7 Add the @DubboService , the issue : https://github.com/apache/dubbo/issues/6007 - DubboService.class, - // @since 2.7.0 the substitute @com.alibaba.dubbo.config.annotation.Service - Service.class - ); + // @since 2.7.7 Add the @DubboService , the issue : https://github.com/apache/dubbo/issues/6007 + DubboService.class, + // @since 2.7.0 the substitute @com.alibaba.dubbo.config.annotation.Service + Service.class); } } @@ -179,7 +184,8 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos Map annotationAttributes = getServiceAnnotationAttributes(beanDefinition); if (annotationAttributes != null) { // process @DubboService at java-config @bean method - processAnnotatedBeanDefinition(beanName, (AnnotatedBeanDefinition) beanDefinition, annotationAttributes); + processAnnotatedBeanDefinition( + beanName, (AnnotatedBeanDefinition) beanDefinition, annotationAttributes); } } @@ -200,13 +206,17 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos scanned = true; if (CollectionUtils.isEmpty(packagesToScan)) { if (logger.isWarnEnabled()) { - logger.warn(CONFIG_NO_BEANS_SCANNED, "", "", "packagesToScan is empty , ServiceBean registry will be ignored!"); + logger.warn( + CONFIG_NO_BEANS_SCANNED, + "", + "", + "packagesToScan is empty , ServiceBean registry will be ignored!"); } return; } DubboClassPathBeanDefinitionScanner scanner = - new DubboClassPathBeanDefinitionScanner(registry, environment, resourceLoader); + new DubboClassPathBeanDefinitionScanner(registry, environment, resourceLoader); BeanNameGenerator beanNameGenerator = resolveBeanNameGenerator(registry); scanner.setBeanNameGenerator(beanNameGenerator); @@ -235,25 +245,34 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos // Finds all BeanDefinitionHolders of @Service whether @ComponentScan scans or not. Set beanDefinitionHolders = - findServiceBeanDefinitionHolders(scanner, packageToScan, registry, beanNameGenerator); + findServiceBeanDefinitionHolders(scanner, packageToScan, registry, beanNameGenerator); if (!CollectionUtils.isEmpty(beanDefinitionHolders)) { if (logger.isInfoEnabled()) { List serviceClasses = new ArrayList<>(beanDefinitionHolders.size()); for (BeanDefinitionHolder beanDefinitionHolder : beanDefinitionHolders) { - serviceClasses.add(beanDefinitionHolder.getBeanDefinition().getBeanClassName()); + serviceClasses.add( + beanDefinitionHolder.getBeanDefinition().getBeanClassName()); } - logger.info("Found " + beanDefinitionHolders.size() + " classes annotated by Dubbo @Service under package [" + packageToScan + "]: " + serviceClasses); + logger.info("Found " + beanDefinitionHolders.size() + + " classes annotated by Dubbo @Service under package [" + packageToScan + "]: " + + serviceClasses); } for (BeanDefinitionHolder beanDefinitionHolder : beanDefinitionHolders) { processScannedBeanDefinition(beanDefinitionHolder); - servicePackagesHolder.addScannedClass(beanDefinitionHolder.getBeanDefinition().getBeanClassName()); + servicePackagesHolder.addScannedClass( + beanDefinitionHolder.getBeanDefinition().getBeanClassName()); } } else { if (logger.isWarnEnabled()) { - logger.warn(CONFIG_NO_ANNOTATIONS_FOUND, "No annotations were found on the class", "", "No class annotated by Dubbo @DubboService or @Service was found under package [" - + packageToScan + "], ignore re-scanned classes: " + scanExcludeFilter.getExcludedCount()); + logger.warn( + CONFIG_NO_ANNOTATIONS_FOUND, + "No annotations were found on the class", + "", + "No class annotated by Dubbo @DubboService or @Service was found under package [" + + packageToScan + "], ignore re-scanned classes: " + + scanExcludeFilter.getExcludedCount()); } } @@ -279,7 +298,8 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos if (registry instanceof SingletonBeanRegistry) { SingletonBeanRegistry singletonBeanRegistry = SingletonBeanRegistry.class.cast(registry); - beanNameGenerator = (BeanNameGenerator) singletonBeanRegistry.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR); + beanNameGenerator = + (BeanNameGenerator) singletonBeanRegistry.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR); } if (beanNameGenerator == null) { @@ -287,18 +307,15 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos if (logger.isInfoEnabled()) { logger.info("BeanNameGenerator bean can't be found in BeanFactory with name [" - + CONFIGURATION_BEAN_NAME_GENERATOR + "]"); - logger.info("BeanNameGenerator will be a instance of " + - AnnotationBeanNameGenerator.class.getName() + - " , it maybe a potential problem on bean name generation."); + + CONFIGURATION_BEAN_NAME_GENERATOR + "]"); + logger.info("BeanNameGenerator will be a instance of " + AnnotationBeanNameGenerator.class.getName() + + " , it maybe a potential problem on bean name generation."); } beanNameGenerator = new AnnotationBeanNameGenerator(); - } return beanNameGenerator; - } /** @@ -312,8 +329,10 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos * @since 2.5.8 */ private Set findServiceBeanDefinitionHolders( - ClassPathBeanDefinitionScanner scanner, String packageToScan, BeanDefinitionRegistry registry, - BeanNameGenerator beanNameGenerator) { + ClassPathBeanDefinitionScanner scanner, + String packageToScan, + BeanDefinitionRegistry registry, + BeanNameGenerator beanNameGenerator) { Set beanDefinitions = scanner.findCandidateComponents(packageToScan); @@ -324,11 +343,9 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos String beanName = beanNameGenerator.generateBeanName(beanDefinition, registry); BeanDefinitionHolder beanDefinitionHolder = new BeanDefinitionHolder(beanDefinition, beanName); beanDefinitionHolders.add(beanDefinitionHolder); - } return beanDefinitionHolders; - } /** @@ -355,10 +372,9 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos String beanName = generateServiceBeanName(serviceAnnotationAttributes, serviceInterface); AbstractBeanDefinition serviceBeanDefinition = - buildServiceBeanDefinition(serviceAnnotationAttributes, serviceInterface, annotatedServiceBeanName); + buildServiceBeanDefinition(serviceAnnotationAttributes, serviceInterface, annotatedServiceBeanName); registerServiceBeanDefinition(beanName, serviceBeanDefinition, serviceInterface); - } /** @@ -369,17 +385,19 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos * @since 2.7.3 */ private Annotation findServiceAnnotation(Class beanClass) { - return serviceAnnotationTypes - .stream() - .map(annotationType -> - ClassUtils.isPresent("org.springframework.core.annotation.AnnotatedElementUtils", - Thread.currentThread().getContextClassLoader()) && - ReflectUtils.hasMethod(org.springframework.core.annotation.AnnotatedElementUtils.class, "findMergedAnnotation") ? - org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation(beanClass, annotationType) : - org.apache.dubbo.common.utils.AnnotationUtils.findAnnotation(beanClass, annotationType)) - .filter(Objects::nonNull) - .findFirst() - .orElse(null); + return serviceAnnotationTypes.stream() + .map(annotationType -> ClassUtils.isPresent( + "org.springframework.core.annotation.AnnotatedElementUtils", + Thread.currentThread().getContextClassLoader()) + && ReflectUtils.hasMethod( + org.springframework.core.annotation.AnnotatedElementUtils.class, + "findMergedAnnotation") + ? org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation( + beanClass, annotationType) + : org.apache.dubbo.common.utils.AnnotationUtils.findAnnotation(beanClass, annotationType)) + .filter(Objects::nonNull) + .findFirst() + .orElse(null); } /** @@ -392,8 +410,8 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos */ private String generateServiceBeanName(Map serviceAnnotationAttributes, String serviceInterface) { ServiceBeanNameBuilder builder = create(serviceInterface, environment) - .group((String) serviceAnnotationAttributes.get("group")) - .version((String) serviceAnnotationAttributes.get("version")); + .group((String) serviceAnnotationAttributes.get("group")) + .version((String) serviceAnnotationAttributes.get("version")); return builder.build(); } @@ -402,7 +420,6 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos BeanDefinition beanDefinition = beanDefinitionHolder.getBeanDefinition(); return resolveClass(beanDefinition); - } private Class resolveClass(BeanDefinition beanDefinition) { @@ -410,7 +427,6 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos String beanClassName = beanDefinition.getBeanClassName(); return resolveClassName(beanClassName, classLoader); - } private Set resolvePackagesToScan(Set packagesToScan) { @@ -433,9 +449,8 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos * @return * @since 2.7.3 */ - private AbstractBeanDefinition buildServiceBeanDefinition(Map serviceAnnotationAttributes, - String serviceInterface, - String refServiceBeanName) { + private AbstractBeanDefinition buildServiceBeanDefinition( + Map serviceAnnotationAttributes, String serviceInterface, String refServiceBeanName) { BeanDefinitionBuilder builder = rootBeanDefinition(ServiceBean.class); @@ -444,19 +459,30 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos MutablePropertyValues propertyValues = beanDefinition.getPropertyValues(); - String[] ignoreAttributeNames = ObjectUtils.of("provider", "monitor", "application", "module", "registry", "protocol", - "methods", "interfaceName", "parameters", "executor"); + String[] ignoreAttributeNames = ObjectUtils.of( + "provider", + "monitor", + "application", + "module", + "registry", + "protocol", + "methods", + "interfaceName", + "parameters", + "executor"); - propertyValues.addPropertyValues(new AnnotationPropertyValuesAdapter(serviceAnnotationAttributes, environment, ignoreAttributeNames)); + propertyValues.addPropertyValues( + new AnnotationPropertyValuesAdapter(serviceAnnotationAttributes, environment, ignoreAttributeNames)); - //set config id, for ConfigManager cache key - //builder.addPropertyValue("id", beanName); + // set config id, for ConfigManager cache key + // builder.addPropertyValue("id", beanName); // References "ref" property to annotated-@Service Bean addPropertyReference(builder, "ref", refServiceBeanName); // Set interface builder.addPropertyValue("interface", serviceInterface); // Convert parameters into map - builder.addPropertyValue("parameters", DubboAnnotationUtils.convertParameters((String[]) serviceAnnotationAttributes.get("parameters"))); + builder.addPropertyValue("parameters", DubboAnnotationUtils.convertParameters((String[]) + serviceAnnotationAttributes.get("parameters"))); // Add methods parameters List methodConfigs = convertMethodConfigs(serviceAnnotationAttributes.get("methods")); if (!methodConfigs.isEmpty()) { @@ -502,7 +528,6 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos } return builder.getBeanDefinition(); - } private String[] resolveStringArray(String[] strs) { @@ -546,9 +571,11 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos for (Class annotationType : serviceAnnotationTypes) { if (factoryMethodMetadata.isAnnotated(annotationType.getName())) { // Since Spring 5.2 - // return factoryMethodMetadata.getAnnotations().get(annotationType).filterDefaultValues().asMap(); + // return + // factoryMethodMetadata.getAnnotations().get(annotationType).filterDefaultValues().asMap(); // Compatible with Spring 4.x - Map annotationAttributes = factoryMethodMetadata.getAnnotationAttributes(annotationType.getName()); + Map annotationAttributes = + factoryMethodMetadata.getAnnotationAttributes(annotationType.getName()); return filterDefaultValues(annotationType, annotationAttributes); } } @@ -576,7 +603,10 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos * @param refServiceBeanDefinition * @param attributes */ - private void processAnnotatedBeanDefinition(String refServiceBeanName, AnnotatedBeanDefinition refServiceBeanDefinition, Map attributes) { + private void processAnnotatedBeanDefinition( + String refServiceBeanName, + AnnotatedBeanDefinition refServiceBeanDefinition, + Map attributes) { Map serviceAnnotationAttributes = new LinkedHashMap<>(attributes); @@ -589,7 +619,8 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos // ServiceBean Bean name String serviceBeanName = generateServiceBeanName(serviceAnnotationAttributes, serviceInterface); - AbstractBeanDefinition serviceBeanDefinition = buildServiceBeanDefinition(serviceAnnotationAttributes, serviceInterface, refServiceBeanName); + AbstractBeanDefinition serviceBeanDefinition = + buildServiceBeanDefinition(serviceAnnotationAttributes, serviceInterface, refServiceBeanName); // set id serviceBeanDefinition.getPropertyValues().add(Constants.ID, serviceBeanName); @@ -597,7 +628,8 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos registerServiceBeanDefinition(serviceBeanName, serviceBeanDefinition, serviceInterface); } - private void registerServiceBeanDefinition(String serviceBeanName, AbstractBeanDefinition serviceBeanDefinition, String serviceInterface) { + private void registerServiceBeanDefinition( + String serviceBeanName, AbstractBeanDefinition serviceBeanDefinition, String serviceInterface) { // check service bean if (registry.containsBeanDefinition(serviceBeanName)) { BeanDefinition existingDefinition = registry.getBeanDefinition(serviceBeanName); @@ -606,10 +638,12 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos return; } - String msg = "Found duplicated BeanDefinition of service interface [" + serviceInterface + "] with bean name [" + serviceBeanName + - "], existing definition [ " + existingDefinition + "], new definition [" + serviceBeanDefinition + "]"; + String msg = "Found duplicated BeanDefinition of service interface [" + serviceInterface + + "] with bean name [" + serviceBeanName + "], existing definition [ " + existingDefinition + + "], new definition [" + serviceBeanDefinition + "]"; logger.error(CONFIG_DUPLICATED_BEAN_DEFINITION, "", "", msg); - throw new BeanDefinitionStoreException(serviceBeanDefinition.getResourceDescription(), serviceBeanName, msg); + throw new BeanDefinitionStoreException( + serviceBeanDefinition.getResourceDescription(), serviceBeanName, msg); } registry.registerBeanDefinition(serviceBeanName, serviceBeanDefinition); @@ -635,7 +669,8 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - this.servicePackagesHolder = applicationContext.getBean(ServicePackagesHolder.BEAN_NAME, ServicePackagesHolder.class); + this.servicePackagesHolder = + applicationContext.getBean(ServicePackagesHolder.BEAN_NAME, ServicePackagesHolder.class); } private class ScanExcludeFilter implements TypeFilter { @@ -643,7 +678,8 @@ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPos private int excludedCount; @Override - public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException { + public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) + throws IOException { String className = metadataReader.getClassMetadata().getClassName(); boolean excluded = servicePackagesHolder.isClassScanned(className); if (excluded) { diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java index a3957f6076..a10c034629 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java @@ -61,10 +61,11 @@ public class ServiceBeanNameBuilder { this.environment = environment; } - private ServiceBeanNameBuilder(AnnotationAttributes attributes, Class defaultInterfaceClass, Environment environment) { + private ServiceBeanNameBuilder( + AnnotationAttributes attributes, Class defaultInterfaceClass, Environment environment) { this(resolveInterfaceName(attributes, defaultInterfaceClass), environment); - this.group(AnnotationUtils.getAttribute(attributes,"group")); - this.version(AnnotationUtils.getAttribute(attributes,"version")); + this.group(AnnotationUtils.getAttribute(attributes, "group")); + this.version(AnnotationUtils.getAttribute(attributes, "version")); } /** @@ -74,7 +75,8 @@ public class ServiceBeanNameBuilder { * @return * @since 2.7.3 */ - public static ServiceBeanNameBuilder create(AnnotationAttributes attributes, Class defaultInterfaceClass, Environment environment) { + public static ServiceBeanNameBuilder create( + AnnotationAttributes attributes, Class defaultInterfaceClass, Environment environment) { return new ServiceBeanNameBuilder(attributes, defaultInterfaceClass, environment); } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServicePackagesHolder.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServicePackagesHolder.java index 75eb6ca2be..b689e51294 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServicePackagesHolder.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServicePackagesHolder.java @@ -30,7 +30,6 @@ public class ServicePackagesHolder { private final Set scannedClasses = new HashSet<>(); - public void addScannedPackage(String apackage) { apackage = normalizePackage(apackage); synchronized (scannedPackages) { @@ -82,5 +81,4 @@ public class ServicePackagesHolder { } return apackage; } - } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/config/DubboConfigDefaultPropertyValueBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/config/DubboConfigDefaultPropertyValueBeanPostProcessor.java index a3599cae3d..44155ea28c 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/config/DubboConfigDefaultPropertyValueBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/config/DubboConfigDefaultPropertyValueBeanPostProcessor.java @@ -21,6 +21,12 @@ import org.apache.dubbo.config.Constants; import org.apache.dubbo.config.spring.util.GenericBeanPostProcessorAdapter; import org.apache.dubbo.config.spring.util.ObjectUtils; +import javax.annotation.PostConstruct; + +import java.beans.PropertyDescriptor; +import java.lang.reflect.Method; +import java.util.Arrays; + import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor; import org.springframework.beans.factory.config.BeanPostProcessor; @@ -30,11 +36,6 @@ import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor; import org.springframework.core.Ordered; import org.springframework.core.PriorityOrdered; -import javax.annotation.PostConstruct; -import java.beans.PropertyDescriptor; -import java.lang.reflect.Method; -import java.util.Arrays; - import static org.springframework.aop.support.AopUtils.getTargetClass; import static org.springframework.beans.BeanUtils.getPropertyDescriptor; import static org.springframework.util.ReflectionUtils.invokeMethod; @@ -60,7 +61,7 @@ public class DubboConfigDefaultPropertyValueBeanPostProcessor extends GenericBea setPropertyIfAbsent(dubboConfigBean, Constants.ID, beanName); // beanName should not be used as config name, fix https://github.com/apache/dubbo/pull/7624 - //setPropertyIfAbsent(dubboConfigBean, "name", beanName); + // setPropertyIfAbsent(dubboConfigBean, "name", beanName); } } @@ -91,13 +92,13 @@ public class DubboConfigDefaultPropertyValueBeanPostProcessor extends GenericBea Method setterMethod = propertyDescriptor.getWriteMethod(); if (setterMethod != null) { // the getter and setter methods are present - if (Arrays.equals(ObjectUtils.of(String.class), setterMethod.getParameterTypes())) { // the param type is String + if (Arrays.equals( + ObjectUtils.of(String.class), setterMethod.getParameterTypes())) { // the param type is String // set bean name to the value of the property invokeMethod(setterMethod, bean, beanName); } } } - } /** diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboBootstrapApplicationListener.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboBootstrapApplicationListener.java index 802e32d9d4..6091656343 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboBootstrapApplicationListener.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboBootstrapApplicationListener.java @@ -61,8 +61,7 @@ public class DubboBootstrapApplicationListener implements ApplicationListener, A private boolean shouldInitConfigBeans; private ModuleModel moduleModel; - public DubboBootstrapApplicationListener() { - } + public DubboBootstrapApplicationListener() {} public DubboBootstrapApplicationListener(boolean shouldInitConfigBeans) { // maybe register DubboBootstrapApplicationListener manual during spring context starting @@ -94,7 +93,11 @@ public class DubboBootstrapApplicationListener implements ApplicationListener, A if (applicationContext.containsBean(DubboConfigBeanInitializer.BEAN_NAME)) { applicationContext.getBean(DubboConfigBeanInitializer.BEAN_NAME, DubboConfigBeanInitializer.class); } else { - logger.warn(CONFIG_DUBBO_BEAN_NOT_FOUND, "", "", "Bean '" + DubboConfigBeanInitializer.BEAN_NAME + "' was not found"); + logger.warn( + CONFIG_DUBBO_BEAN_NOT_FOUND, + "", + "", + "Bean '" + DubboConfigBeanInitializer.BEAN_NAME + "' was not found"); } // All infrastructure config beans are loaded, initialize dubbo here @@ -122,7 +125,7 @@ public class DubboBootstrapApplicationListener implements ApplicationListener, A private void onContextClosedEvent(ContextClosedEvent event) { if (bootstrap.getTakeoverMode() == BootstrapTakeoverMode.SPRING) { // will call dubboBootstrap.stop() through shutdown callback. - //bootstrap.getApplicationModel().getBeanFactory().getBean(DubboShutdownHook.class).run(); + // bootstrap.getApplicationModel().getBeanFactory().getBean(DubboShutdownHook.class).run(); moduleModel.getDeployer().stop(); } } @@ -155,12 +158,14 @@ public class DubboBootstrapApplicationListener implements ApplicationListener, A } private void checkCallStackAndInit() { - // check call stack whether contains org.springframework.context.support.AbstractApplicationContext.registerListeners() + // check call stack whether contains + // org.springframework.context.support.AbstractApplicationContext.registerListeners() Exception exception = new Exception(); StackTraceElement[] stackTrace = exception.getStackTrace(); boolean found = false; for (StackTraceElement frame : stackTrace) { - if (frame.getMethodName().equals("registerListeners") && frame.getClassName().endsWith("AbstractApplicationContext")) { + if (frame.getMethodName().equals("registerListeners") + && frame.getClassName().endsWith("AbstractApplicationContext")) { found = true; break; } @@ -169,8 +174,13 @@ public class DubboBootstrapApplicationListener implements ApplicationListener, A // init config beans here, compatible with spring 3.x/4.1.x initDubboConfigBeans(); } else { - logger.warn(CONFIG_DUBBO_BEAN_INITIALIZER, "", "", "DubboBootstrapApplicationListener initialization is unexpected, " + - "it should be created in AbstractApplicationContext.registerListeners() method", exception); + logger.warn( + CONFIG_DUBBO_BEAN_INITIALIZER, + "", + "", + "DubboBootstrapApplicationListener initialization is unexpected, " + + "it should be created in AbstractApplicationContext.registerListeners() method", + exception); } } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboConfigApplicationListener.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboConfigApplicationListener.java index 2cdf512053..fa9d5b2b0b 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboConfigApplicationListener.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboConfigApplicationListener.java @@ -22,22 +22,24 @@ import org.apache.dubbo.config.spring.context.event.DubboConfigInitEvent; import org.apache.dubbo.config.spring.util.DubboBeanUtils; import org.apache.dubbo.rpc.model.ModuleModel; +import java.util.concurrent.atomic.AtomicBoolean; + import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationListener; -import java.util.concurrent.atomic.AtomicBoolean; - import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_NOT_FOUND; import static org.springframework.util.ObjectUtils.nullSafeEquals; /** * An ApplicationListener to load config beans */ -public class DubboConfigApplicationListener implements ApplicationListener, ApplicationContextAware { +public class DubboConfigApplicationListener + implements ApplicationListener, ApplicationContextAware { - private final static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboConfigApplicationListener.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(DubboConfigApplicationListener.class); private ApplicationContext applicationContext; @@ -59,7 +61,8 @@ public class DubboConfigApplicationListener implements ApplicationListener configClass, AbstractConfigManager configManager) { + private void loadConfigBeansOfType( + Class configClass, AbstractConfigManager configManager) { String[] beanNames = beanFactory.getBeanNamesForType(configClass, true, false); for (String beanName : beanNames) { AbstractConfig configBean = beanFactory.getBean(beanName, configClass); @@ -133,5 +133,4 @@ public class DubboConfigBeanInitializer implements BeanFactoryAware, Initializin configManager.addConfig(configBean); } } - } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboContextPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboContextPostProcessor.java index 3f44969c92..6715b52293 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboContextPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboContextPostProcessor.java @@ -24,6 +24,8 @@ import org.apache.dubbo.config.spring.util.EnvironmentUtils; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; +import java.util.SortedMap; + import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; @@ -34,15 +36,13 @@ import org.springframework.context.EnvironmentAware; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; -import java.util.SortedMap; - - -public class DubboContextPostProcessor implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware, EnvironmentAware { +public class DubboContextPostProcessor + implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware, EnvironmentAware { /** * The bean name of {@link DubboConfigConfigurationRegistrar} */ - public final static String BEAN_NAME = "dubboContextPostProcessor"; + public static final String BEAN_NAME = "dubboContextPostProcessor"; private ApplicationContext applicationContext; @@ -65,7 +65,6 @@ public class DubboContextPostProcessor implements BeanDefinitionRegistryPostProc // register ConfigManager singleton beanFactory.registerSingleton(ConfigManager.BEAN_NAME, applicationModel.getApplicationConfigManager()); - } @Override diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboDeployApplicationListener.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboDeployApplicationListener.java index 73c07c5b29..869e61b9fb 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboDeployApplicationListener.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboDeployApplicationListener.java @@ -31,6 +31,8 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModelConstants; import org.apache.dubbo.rpc.model.ModuleModel; +import java.util.concurrent.Future; + import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; @@ -40,8 +42,6 @@ import org.springframework.context.event.ContextClosedEvent; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.core.Ordered; -import java.util.concurrent.Future; - import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_START_MODEL; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_STOP_DUBBO_ERROR; import static org.springframework.util.ObjectUtils.nullSafeEquals; @@ -49,9 +49,11 @@ import static org.springframework.util.ObjectUtils.nullSafeEquals; /** * An ApplicationListener to control Dubbo application. */ -public class DubboDeployApplicationListener implements ApplicationListener, ApplicationContextAware, Ordered { +public class DubboDeployApplicationListener + implements ApplicationListener, ApplicationContextAware, Ordered { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboDeployApplicationListener.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(DubboDeployApplicationListener.class); private ApplicationContext applicationContext; @@ -64,7 +66,7 @@ public class DubboDeployApplicationListener implements ApplicationListener(){ + applicationModel.getDeployer().addDeployListener(new DeployListenerAdapter() { @Override public void onStarting(ApplicationModel scopeModel) { publishApplicationEvent(DeployState.STARTING); @@ -90,7 +92,7 @@ public class DubboDeployApplicationListener implements ApplicationListener(){ + moduleModel.getDeployer().addDeployListener(new DeployListenerAdapter() { @Override public void onStarting(ModuleModel scopeModel) { publishModuleEvent(DeployState.STARTING); @@ -160,9 +162,18 @@ public class DubboDeployApplicationListener implements ApplicationListener holders = ThreadLocal.withInitial(DubboSpringInitCustomizerHolder::new); + private static final ThreadLocal holders = + ThreadLocal.withInitial(DubboSpringInitCustomizerHolder::new); public static DubboSpringInitCustomizerHolder get() { return holders.get(); @@ -53,5 +54,4 @@ public class DubboSpringInitCustomizerHolder { public Set getCustomizers() { return customizers; } - } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitializer.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitializer.java index 8dc1a97930..409d4290b0 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitializer.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitializer.java @@ -25,6 +25,10 @@ import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ScopeModel; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; @@ -32,10 +36,6 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.util.ObjectUtils; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - /** * Dubbo spring initialization entry point */ @@ -43,10 +43,10 @@ public class DubboSpringInitializer { private static final Logger logger = LoggerFactory.getLogger(DubboSpringInitializer.class); - private static final Map REGISTRY_CONTEXT_MAP = new ConcurrentHashMap<>(); + private static final Map REGISTRY_CONTEXT_MAP = + new ConcurrentHashMap<>(); - public DubboSpringInitializer() { - } + public DubboSpringInitializer() {} public static void initialize(BeanDefinitionRegistry registry) { @@ -73,13 +73,12 @@ public class DubboSpringInitializer { AutowireCapableBeanFactory autowireCapableBeanFactory = springContext.getAutowireCapableBeanFactory(); for (Map.Entry entry : REGISTRY_CONTEXT_MAP.entrySet()) { DubboSpringInitContext initContext = entry.getValue(); - if (initContext.getApplicationContext() == springContext || - initContext.getBeanFactory() == autowireCapableBeanFactory || - initContext.getRegistry() == autowireCapableBeanFactory - ) { + if (initContext.getApplicationContext() == springContext + || initContext.getBeanFactory() == autowireCapableBeanFactory + || initContext.getRegistry() == autowireCapableBeanFactory) { DubboSpringInitContext context = REGISTRY_CONTEXT_MAP.remove(entry.getKey()); - logger.info("Unbind " + safeGetModelDesc(context.getModuleModel()) + " from spring container: " + - ObjectUtils.identityToString(entry.getKey())); + logger.info("Unbind " + safeGetModelDesc(context.getModuleModel()) + " from spring container: " + + ObjectUtils.identityToString(entry.getKey())); return true; } } @@ -99,8 +98,10 @@ public class DubboSpringInitializer { return null; } - private static void initContext(DubboSpringInitContext context, BeanDefinitionRegistry registry, - ConfigurableListableBeanFactory beanFactory) { + private static void initContext( + DubboSpringInitContext context, + BeanDefinitionRegistry registry, + ConfigurableListableBeanFactory beanFactory) { context.setRegistry(registry); context.setBeanFactory(beanFactory); @@ -128,7 +129,8 @@ public class DubboSpringInitializer { } else { logger.info("Use module model from customizer: " + moduleModel.getDesc()); } - logger.info("Bind " + moduleModel.getDesc() + " to spring container: " + ObjectUtils.identityToString(registry)); + logger.info( + "Bind " + moduleModel.getDesc() + " to spring container: " + ObjectUtils.identityToString(registry)); // set module attributes Map moduleAttributes = context.getModuleAttributes(); @@ -143,7 +145,7 @@ public class DubboSpringInitializer { context.markAsBound(); moduleModel.setLifeCycleManagedExternally(true); - if (!AotWithSpringDetector.useGeneratedArtifacts()){ + if (!AotWithSpringDetector.useGeneratedArtifacts()) { // register common beans DubboBeanUtils.registerCommonBeans(registry); } @@ -161,20 +163,23 @@ public class DubboSpringInitializer { GenericApplicationContext genericApplicationContext = (GenericApplicationContext) registry; beanFactory = genericApplicationContext.getBeanFactory(); } else { - throw new IllegalStateException("Can not find Spring BeanFactory from registry: " + registry.getClass().getName()); + throw new IllegalStateException("Can not find Spring BeanFactory from registry: " + + registry.getClass().getName()); } return beanFactory; } - private static void registerContextBeans(ConfigurableListableBeanFactory beanFactory, DubboSpringInitContext context) { + private static void registerContextBeans( + ConfigurableListableBeanFactory beanFactory, DubboSpringInitContext context) { // register singleton - if (!beanFactory.containsSingleton(DubboSpringInitContext.class.getName())){ + if (!beanFactory.containsSingleton(DubboSpringInitContext.class.getName())) { registerSingleton(beanFactory, context); } - if (!beanFactory.containsSingleton(context.getApplicationModel().getClass().getName())){ + if (!beanFactory.containsSingleton( + context.getApplicationModel().getClass().getName())) { registerSingleton(beanFactory, context.getApplicationModel()); } - if (!beanFactory.containsSingleton(context.getModuleModel().getClass().getName())){ + if (!beanFactory.containsSingleton(context.getModuleModel().getClass().getName())) { registerSingleton(beanFactory, context.getModuleModel()); } } @@ -196,8 +201,8 @@ public class DubboSpringInitializer { // find initialization customizers Set customizers = FrameworkModel.defaultModel() - .getExtensionLoader(DubboSpringInitCustomizer.class) - .getSupportedExtensionInstances(); + .getExtensionLoader(DubboSpringInitCustomizer.class) + .getSupportedExtensionInstances(); for (DubboSpringInitCustomizer customizer : customizers) { customizer.customize(context); } @@ -210,5 +215,4 @@ public class DubboSpringInitializer { } customizerHolder.clearCustomizers(); } - } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboClassPathBeanDefinitionScanner.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboClassPathBeanDefinitionScanner.java index 6ecb422915..0c3e1e810f 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboClassPathBeanDefinitionScanner.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboClassPathBeanDefinitionScanner.java @@ -17,17 +17,18 @@ package org.apache.dubbo.config.spring.context.annotation; import org.apache.dubbo.config.spring.aot.AotWithSpringDetector; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; -import org.springframework.core.env.Environment; -import org.springframework.core.io.ResourceLoader; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; +import org.springframework.core.env.Environment; +import org.springframework.core.io.ResourceLoader; + import static org.springframework.context.annotation.AnnotationConfigUtils.registerAnnotationConfigProcessors; /** @@ -44,9 +45,11 @@ public class DubboClassPathBeanDefinitionScanner extends ClassPathBeanDefinition */ private final ConcurrentMap> beanDefinitionMap = new ConcurrentHashMap<>(); - - public DubboClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters, Environment environment, - ResourceLoader resourceLoader) { + public DubboClassPathBeanDefinitionScanner( + BeanDefinitionRegistry registry, + boolean useDefaultFilters, + Environment environment, + ResourceLoader resourceLoader) { super(registry, useDefaultFilters); @@ -57,14 +60,12 @@ public class DubboClassPathBeanDefinitionScanner extends ClassPathBeanDefinition if (!AotWithSpringDetector.useGeneratedArtifacts()) { registerAnnotationConfigProcessors(registry); } - } - public DubboClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, Environment environment, - ResourceLoader resourceLoader) { + public DubboClassPathBeanDefinitionScanner( + BeanDefinitionRegistry registry, Environment environment, ResourceLoader resourceLoader) { this(registry, false, environment, resourceLoader); - } @Override diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScan.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScan.java index 82f16ecbb4..31983d466b 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScan.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScan.java @@ -19,8 +19,6 @@ package org.apache.dubbo.config.spring.context.annotation; import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.annotation.Service; -import org.springframework.context.annotation.Import; - import java.lang.annotation.Annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; @@ -28,6 +26,8 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.springframework.context.annotation.Import; + /** * Dubbo Component Scan {@link Annotation},scans the classpath for annotated components that will be auto-registered as * Spring beans. Dubbo-provided {@link Service} and {@link Reference}. @@ -70,5 +70,4 @@ public @interface DubboComponentScan { * @return classes from the base packages to scan */ Class[] basePackageClasses() default {}; - } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrar.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrar.java index fe2321bfa0..13c746faac 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrar.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrar.java @@ -21,6 +21,12 @@ import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotati import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor; import org.apache.dubbo.config.spring.context.DubboSpringInitializer; import org.apache.dubbo.config.spring.util.SpringCompatUtils; + +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.Set; + import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; @@ -31,11 +37,6 @@ import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.type.AnnotationMetadata; import org.springframework.util.ClassUtils; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.Set; - import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; /** @@ -75,16 +76,17 @@ public class DubboComponentScanRegistrar implements ImportBeanDefinitionRegistra builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); AbstractBeanDefinition beanDefinition = builder.getBeanDefinition(); BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinition, registry); - } private Set getPackagesToScan(AnnotationMetadata metadata) { - // get from @DubboComponentScan - Set packagesToScan = getPackagesToScan0(metadata, DubboComponentScan.class, "basePackages", "basePackageClasses"); + // get from @DubboComponentScan + Set packagesToScan = + getPackagesToScan0(metadata, DubboComponentScan.class, "basePackages", "basePackageClasses"); // get from @EnableDubbo, compatible with spring 3.x if (packagesToScan.isEmpty()) { - packagesToScan = getPackagesToScan0(metadata, EnableDubbo.class, "scanBasePackages", "scanBasePackageClasses"); + packagesToScan = + getPackagesToScan0(metadata, EnableDubbo.class, "scanBasePackages", "scanBasePackageClasses"); } if (packagesToScan.isEmpty()) { @@ -93,10 +95,14 @@ public class DubboComponentScanRegistrar implements ImportBeanDefinitionRegistra return packagesToScan; } - private Set getPackagesToScan0(AnnotationMetadata metadata, Class annotationClass, String basePackagesName, String basePackageClassesName) { + private Set getPackagesToScan0( + AnnotationMetadata metadata, + Class annotationClass, + String basePackagesName, + String basePackageClassesName) { - AnnotationAttributes attributes = AnnotationAttributes.fromMap( - metadata.getAnnotationAttributes(annotationClass.getName())); + AnnotationAttributes attributes = + AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(annotationClass.getName())); if (attributes == null) { return Collections.emptySet(); } @@ -117,5 +123,4 @@ public class DubboComponentScanRegistrar implements ImportBeanDefinitionRegistra } return packagesToScan; } - } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfiguration.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfiguration.java index 9d698a2e97..2e872c5b78 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfiguration.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfiguration.java @@ -57,40 +57,42 @@ public class DubboConfigConfiguration { * Single Dubbo {@link AbstractConfig Config} Bean Binding */ @EnableConfigurationBeanBindings({ - @EnableConfigurationBeanBinding(prefix = "dubbo.application", type = ApplicationConfig.class), - @EnableConfigurationBeanBinding(prefix = "dubbo.module", type = ModuleConfig.class), - @EnableConfigurationBeanBinding(prefix = "dubbo.registry", type = RegistryConfig.class), - @EnableConfigurationBeanBinding(prefix = "dubbo.protocol", type = ProtocolConfig.class), - @EnableConfigurationBeanBinding(prefix = "dubbo.monitor", type = MonitorConfig.class), - @EnableConfigurationBeanBinding(prefix = "dubbo.provider", type = ProviderConfig.class), - @EnableConfigurationBeanBinding(prefix = "dubbo.consumer", type = ConsumerConfig.class), - @EnableConfigurationBeanBinding(prefix = "dubbo.config-center", type = ConfigCenterBean.class), - @EnableConfigurationBeanBinding(prefix = "dubbo.metadata-report", type = MetadataReportConfig.class), - @EnableConfigurationBeanBinding(prefix = "dubbo.metrics", type = MetricsConfig.class), - @EnableConfigurationBeanBinding(prefix = "dubbo.tracing", type = TracingConfig.class), - @EnableConfigurationBeanBinding(prefix = "dubbo.ssl", type = SslConfig.class) + @EnableConfigurationBeanBinding(prefix = "dubbo.application", type = ApplicationConfig.class), + @EnableConfigurationBeanBinding(prefix = "dubbo.module", type = ModuleConfig.class), + @EnableConfigurationBeanBinding(prefix = "dubbo.registry", type = RegistryConfig.class), + @EnableConfigurationBeanBinding(prefix = "dubbo.protocol", type = ProtocolConfig.class), + @EnableConfigurationBeanBinding(prefix = "dubbo.monitor", type = MonitorConfig.class), + @EnableConfigurationBeanBinding(prefix = "dubbo.provider", type = ProviderConfig.class), + @EnableConfigurationBeanBinding(prefix = "dubbo.consumer", type = ConsumerConfig.class), + @EnableConfigurationBeanBinding(prefix = "dubbo.config-center", type = ConfigCenterBean.class), + @EnableConfigurationBeanBinding(prefix = "dubbo.metadata-report", type = MetadataReportConfig.class), + @EnableConfigurationBeanBinding(prefix = "dubbo.metrics", type = MetricsConfig.class), + @EnableConfigurationBeanBinding(prefix = "dubbo.tracing", type = TracingConfig.class), + @EnableConfigurationBeanBinding(prefix = "dubbo.ssl", type = SslConfig.class) }) - public static class Single { - - } + public static class Single {} /** * Multiple Dubbo {@link AbstractConfig Config} Bean Binding */ @EnableConfigurationBeanBindings({ - @EnableConfigurationBeanBinding(prefix = "dubbo.applications", type = ApplicationConfig.class, multiple = true), - @EnableConfigurationBeanBinding(prefix = "dubbo.modules", type = ModuleConfig.class, multiple = true), - @EnableConfigurationBeanBinding(prefix = "dubbo.registries", type = RegistryConfig.class, multiple = true), - @EnableConfigurationBeanBinding(prefix = "dubbo.protocols", type = ProtocolConfig.class, multiple = true), - @EnableConfigurationBeanBinding(prefix = "dubbo.monitors", type = MonitorConfig.class, multiple = true), - @EnableConfigurationBeanBinding(prefix = "dubbo.providers", type = ProviderConfig.class, multiple = true), - @EnableConfigurationBeanBinding(prefix = "dubbo.consumers", type = ConsumerConfig.class, multiple = true), - @EnableConfigurationBeanBinding(prefix = "dubbo.config-centers", type = ConfigCenterBean.class, multiple = true), - @EnableConfigurationBeanBinding(prefix = "dubbo.metadata-reports", type = MetadataReportConfig.class, multiple = true), - @EnableConfigurationBeanBinding(prefix = "dubbo.metricses", type = MetricsConfig.class, multiple = true), - @EnableConfigurationBeanBinding(prefix = "dubbo.tracings", type = TracingConfig.class, multiple = true) + @EnableConfigurationBeanBinding(prefix = "dubbo.applications", type = ApplicationConfig.class, multiple = true), + @EnableConfigurationBeanBinding(prefix = "dubbo.modules", type = ModuleConfig.class, multiple = true), + @EnableConfigurationBeanBinding(prefix = "dubbo.registries", type = RegistryConfig.class, multiple = true), + @EnableConfigurationBeanBinding(prefix = "dubbo.protocols", type = ProtocolConfig.class, multiple = true), + @EnableConfigurationBeanBinding(prefix = "dubbo.monitors", type = MonitorConfig.class, multiple = true), + @EnableConfigurationBeanBinding(prefix = "dubbo.providers", type = ProviderConfig.class, multiple = true), + @EnableConfigurationBeanBinding(prefix = "dubbo.consumers", type = ConsumerConfig.class, multiple = true), + @EnableConfigurationBeanBinding( + prefix = "dubbo.config-centers", + type = ConfigCenterBean.class, + multiple = true), + @EnableConfigurationBeanBinding( + prefix = "dubbo.metadata-reports", + type = MetadataReportConfig.class, + multiple = true), + @EnableConfigurationBeanBinding(prefix = "dubbo.metricses", type = MetricsConfig.class, multiple = true), + @EnableConfigurationBeanBinding(prefix = "dubbo.tracings", type = TracingConfig.class, multiple = true) }) - public static class Multiple { - - } + public static class Multiple {} } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubbo.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubbo.java index 5e3ef54cac..860c9445de 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubbo.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubbo.java @@ -18,8 +18,6 @@ package org.apache.dubbo.config.spring.context.annotation; import org.apache.dubbo.config.AbstractConfig; -import org.springframework.core.annotation.AliasFor; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; @@ -27,6 +25,8 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.springframework.core.annotation.AliasFor; + /** * Enables Dubbo components as Spring Beans, equals * {@link DubboComponentScan} and {@link EnableDubboConfig} combination. @@ -68,7 +68,6 @@ public @interface EnableDubbo { @AliasFor(annotation = DubboComponentScan.class, attribute = "basePackageClasses") Class[] scanBasePackageClasses() default {}; - /** * It indicates whether {@link AbstractConfig} binding to multiple Spring Beans. * @@ -77,5 +76,4 @@ public @interface EnableDubbo { */ @AliasFor(annotation = EnableDubboConfig.class, attribute = "multiple") boolean multipleConfig() default true; - } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfig.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfig.java index 3d5e085b97..9e1b81e706 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfig.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfig.java @@ -24,9 +24,6 @@ import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.RegistryConfig; -import com.alibaba.spring.beans.factory.annotation.EnableConfigurationBeanBinding; -import org.springframework.context.annotation.Import; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; @@ -34,6 +31,9 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import com.alibaba.spring.beans.factory.annotation.EnableConfigurationBeanBinding; +import org.springframework.context.annotation.Import; + /** * As a convenient and multiple {@link EnableConfigurationBeanBinding} * in default behavior , is equal to single bean bindings with below convention prefixes of properties: @@ -77,5 +77,4 @@ public @interface EnableDubboConfig { * @revised 2.5.9 */ boolean multiple() default true; - } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/config/NamePropertyDefaultValueDubboConfigBeanCustomizer.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/config/NamePropertyDefaultValueDubboConfigBeanCustomizer.java index 298e9e0015..10cf5573af 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/config/NamePropertyDefaultValueDubboConfigBeanCustomizer.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/config/NamePropertyDefaultValueDubboConfigBeanCustomizer.java @@ -20,12 +20,12 @@ import org.apache.dubbo.config.AbstractConfig; import org.apache.dubbo.config.spring.beans.factory.config.DubboConfigDefaultPropertyValueBeanPostProcessor; import org.apache.dubbo.config.spring.util.ObjectUtils; -import org.springframework.util.ReflectionUtils; - import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.Arrays; +import org.springframework.util.ReflectionUtils; + import static org.springframework.beans.BeanUtils.getPropertyDescriptor; /** @@ -71,7 +71,8 @@ public class NamePropertyDefaultValueDubboConfigBeanCustomizer implements DubboC Method setNameMethod = propertyDescriptor.getWriteMethod(); if (setNameMethod != null) { // "setName" and "getName" methods are present - if (Arrays.equals(ObjectUtils.of(String.class), setNameMethod.getParameterTypes())) { // the param type is String + if (Arrays.equals( + ObjectUtils.of(String.class), setNameMethod.getParameterTypes())) { // the param type is String // set bean name to the value of the "name" property ReflectionUtils.invokeMethod(setNameMethod, dubboConfigBean, beanName); } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/event/DubboConfigInitEvent.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/event/DubboConfigInitEvent.java index 252b48230a..28ffa45967 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/event/DubboConfigInitEvent.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/event/DubboConfigInitEvent.java @@ -42,5 +42,4 @@ public class DubboConfigInitEvent extends ApplicationEvent { public final ApplicationContext getApplicationContext() { return (ApplicationContext) getSource(); } - } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/AbstractDubboConfigBinder.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/AbstractDubboConfigBinder.java index 47b3955fea..4a2f532889 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/AbstractDubboConfigBinder.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/AbstractDubboConfigBinder.java @@ -64,6 +64,5 @@ public abstract class AbstractDubboConfigBinder implements DubboConfigBinder { if (environment instanceof ConfigurableEnvironment) { this.propertySources = ((ConfigurableEnvironment) environment).getPropertySources(); } - } } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/DefaultDubboConfigBinder.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/DefaultDubboConfigBinder.java index 117207038f..410e9c3710 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/DefaultDubboConfigBinder.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/DefaultDubboConfigBinder.java @@ -19,15 +19,15 @@ package org.apache.dubbo.config.spring.context.properties; import org.apache.dubbo.config.AbstractConfig; import org.apache.dubbo.config.spring.util.PropertySourcesUtils; +import java.util.List; +import java.util.Map; +import java.util.stream.IntStream; + import org.springframework.beans.MutablePropertyValues; import org.springframework.validation.BindingResult; import org.springframework.validation.DataBinder; import org.springframework.validation.FieldError; -import java.util.List; -import java.util.Map; -import java.util.stream.IntStream; - /** * Default {@link DubboConfigBinder} implementation based on Spring {@link DataBinder} */ @@ -47,16 +47,20 @@ public class DefaultDubboConfigBinder extends AbstractDubboConfigBinder { dataBinder.bind(propertyValues); BindingResult bindingResult = dataBinder.getBindingResult(); if (bindingResult.hasGlobalErrors()) { - throw new RuntimeException("Data bind global error, please check config. config: " + bindingResult.getGlobalError() + ""); + throw new RuntimeException( + "Data bind global error, please check config. config: " + bindingResult.getGlobalError() + ""); } if (bindingResult.hasFieldErrors()) { - throw new RuntimeException(buildErrorMsg(bindingResult.getFieldErrors(), prefix, dubboConfig.getClass().getSimpleName())); + throw new RuntimeException(buildErrorMsg( + bindingResult.getFieldErrors(), + prefix, + dubboConfig.getClass().getSimpleName())); } } private String buildErrorMsg(List errors, String prefix, String config) { - StringBuilder builder = new StringBuilder("Data bind error, please check config. config: " + config + ", prefix: " + prefix - + " , error fields: [" + errors.get(0).getField()); + StringBuilder builder = new StringBuilder("Data bind error, please check config. config: " + config + + ", prefix: " + prefix + " , error fields: [" + errors.get(0).getField()); if (errors.size() > 1) { IntStream.range(1, errors.size()).forEach(i -> { builder.append(", " + errors.get(i).getField()); @@ -66,4 +70,3 @@ public class DefaultDubboConfigBinder extends AbstractDubboConfigBinder { return builder.toString(); } } - diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/extension/SpringExtensionInjector.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/extension/SpringExtensionInjector.java index bf297803b6..d8422dc4aa 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/extension/SpringExtensionInjector.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/extension/SpringExtensionInjector.java @@ -20,11 +20,12 @@ import org.apache.dubbo.common.extension.ExtensionAccessor; import org.apache.dubbo.common.extension.ExtensionInjector; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.common.utils.StringUtils; -import org.springframework.beans.factory.ListableBeanFactory; -import org.springframework.context.ApplicationContext; import java.util.Arrays; +import org.springframework.beans.factory.ListableBeanFactory; +import org.springframework.context.ApplicationContext; + /** * SpringExtensionInjector */ @@ -33,8 +34,7 @@ public class SpringExtensionInjector implements ExtensionInjector { private ApplicationContext context; @Deprecated - public static void addApplicationContext(final ApplicationContext context) { - } + public static void addApplicationContext(final ApplicationContext context) {} public static SpringExtensionInjector get(final ExtensionAccessor extensionAccessor) { return (SpringExtensionInjector) extensionAccessor.getExtension(ExtensionInjector.class, "spring"); @@ -56,7 +56,7 @@ public class SpringExtensionInjector implements ExtensionInjector { return null; } - //check @SPI annotation + // check @SPI annotation if (type.isInterface() && type.isAnnotationPresent(SPI.class)) { return null; } @@ -66,28 +66,29 @@ public class SpringExtensionInjector implements ExtensionInjector { return bean; } - //logger.warn("No spring extension (bean) named:" + name + ", try to find an extension (bean) of type " + type.getName()); + // logger.warn("No spring extension (bean) named:" + name + ", try to find an extension (bean) of type " + + // type.getName()); return null; } private T getOptionalBean(final ListableBeanFactory beanFactory, final String name, final Class type) { if (StringUtils.isEmpty(name)) { return getOptionalBeanByType(beanFactory, type); - } + } if (beanFactory.containsBean(name)) { return beanFactory.getBean(name, type); } return null; } - + private T getOptionalBeanByType(final ListableBeanFactory beanFactory, final Class type) { String[] beanNamesForType = beanFactory.getBeanNamesForType(type, true, false); if (beanNamesForType == null) { return null; } if (beanNamesForType.length > 1) { - throw new IllegalStateException("Expect single but found " + beanNamesForType.length + " beans in spring context: " + - Arrays.toString(beanNamesForType)); + throw new IllegalStateException("Expect single but found " + beanNamesForType.length + + " beans in spring context: " + Arrays.toString(beanNamesForType)); } return beanFactory.getBean(beanNamesForType[0], type); } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceAttributes.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceAttributes.java index efc13f9833..5eeb7889fa 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceAttributes.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceAttributes.java @@ -58,11 +58,11 @@ public interface ReferenceAttributes { String CLIENT = "client"; -// /** -// * When enable, prefer to call local service in the same JVM if it's present, default value is true -// * @deprecated using scope="local" or scope="remote" instead -// */ -// @Deprecated + // /** + // * When enable, prefer to call local service in the same JVM if it's present, default value is true + // * @deprecated using scope="local" or scope="remote" instead + // */ + // @Deprecated String INJVM = "injvm"; String CHECK = "check"; diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceBeanBuilder.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceBeanBuilder.java index 36c7418031..ed0070823e 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceBeanBuilder.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceBeanBuilder.java @@ -137,7 +137,7 @@ public class ReferenceBeanBuilder { return this; } - //@Deprecated + // @Deprecated public ReferenceBeanBuilder setGeneric(Boolean generic) { attributes.put(ReferenceAttributes.GENERIC, generic); return this; @@ -203,10 +203,10 @@ public class ReferenceBeanBuilder { return this; } -// public ReferenceBeanBuilder setRouter(String router) { -// attributes.put(ReferenceAttributes.ROUTER, router); -// return this; -// } + // public ReferenceBeanBuilder setRouter(String router) { + // attributes.put(ReferenceAttributes.ROUTER, router); + // return this; + // } public ReferenceBeanBuilder setStub(String stub) { attributes.put(ReferenceAttributes.STUB, stub); @@ -238,17 +238,17 @@ public class ReferenceBeanBuilder { return this; } -// @Deprecated -// public ReferenceBeanBuilder setApplication(ApplicationConfig application) { -// attributes.put(ReferenceAttributes.APPLICATION, application); -// return this; -// } + // @Deprecated + // public ReferenceBeanBuilder setApplication(ApplicationConfig application) { + // attributes.put(ReferenceAttributes.APPLICATION, application); + // return this; + // } -// @Deprecated -// public ReferenceBeanBuilder setModule(ModuleConfig module) { -// attributes.put(ReferenceAttributes.MODULE, module); -// return this; -// } + // @Deprecated + // public ReferenceBeanBuilder setModule(ModuleConfig module) { + // attributes.put(ReferenceAttributes.MODULE, module); + // return this; + // } public ReferenceBeanBuilder setRegistry(String[] registryIds) { attributes.put(ReferenceAttributes.REGISTRY, registryIds); @@ -357,32 +357,32 @@ public class ReferenceBeanBuilder { return this; } -// public ReferenceBeanBuilder setAuth(Boolean auth) { -// attributes.put(ReferenceAttributes.AUTH, auth); -// return this; -// } -// -// public ReferenceBeanBuilder setForks(Integer forks) { -// attributes.put(ReferenceAttributes.FORKS, forks); -// return this; -// } -// -// @Deprecated -// public ReferenceBeanBuilder setConfigCenter(ConfigCenterConfig configCenter) { -// attributes.put(ReferenceAttributes.CONFIG_CENTER, configCenter); -// return this; -// } -// -// @Deprecated -// public ReferenceBeanBuilder setMetadataReportConfig(MetadataReportConfig metadataReportConfig) { -// attributes.put(ReferenceAttributes.METADATA_REPORT_CONFIG, metadataReportConfig); -// return this; -// } -// -// @Deprecated -// public ReferenceBeanBuilder setMetrics(MetricsConfig metrics) { -// attributes.put(ReferenceAttributes.METRICS, metrics); -// return this; -// } + // public ReferenceBeanBuilder setAuth(Boolean auth) { + // attributes.put(ReferenceAttributes.AUTH, auth); + // return this; + // } + // + // public ReferenceBeanBuilder setForks(Integer forks) { + // attributes.put(ReferenceAttributes.FORKS, forks); + // return this; + // } + // + // @Deprecated + // public ReferenceBeanBuilder setConfigCenter(ConfigCenterConfig configCenter) { + // attributes.put(ReferenceAttributes.CONFIG_CENTER, configCenter); + // return this; + // } + // + // @Deprecated + // public ReferenceBeanBuilder setMetadataReportConfig(MetadataReportConfig metadataReportConfig) { + // attributes.put(ReferenceAttributes.METADATA_REPORT_CONFIG, metadataReportConfig); + // return this; + // } + // + // @Deprecated + // public ReferenceBeanBuilder setMetrics(MetricsConfig metrics) { + // attributes.put(ReferenceAttributes.METRICS, metrics); + // return this; + // } } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceBeanManager.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceBeanManager.java index 0e428a8647..2bdf44362b 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceBeanManager.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceBeanManager.java @@ -26,10 +26,6 @@ import org.apache.dubbo.config.spring.ReferenceBean; import org.apache.dubbo.config.spring.util.DubboBeanUtils; import org.apache.dubbo.rpc.model.ModuleModel; -import org.springframework.beans.BeansException; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; - import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -40,23 +36,26 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_INITIALIZER; +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_INITIALIZER; public class ReferenceBeanManager implements ApplicationContextAware { public static final String BEAN_NAME = "dubboReferenceBeanManager"; private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); - //reference key -> reference bean names + // reference key -> reference bean names private ConcurrentMap> referenceKeyMap = new ConcurrentHashMap<>(); // reference alias -> reference bean name private ConcurrentMap referenceAliasMap = new ConcurrentHashMap<>(); - //reference bean name -> ReferenceBean + // reference bean name -> ReferenceBean private ConcurrentMap referenceBeanMap = new ConcurrentHashMap<>(); - //reference key -> ReferenceConfig instance + // reference key -> ReferenceConfig instance private ConcurrentMap referenceConfigMap = new ConcurrentHashMap<>(); private ApplicationContext applicationContext; @@ -68,10 +67,15 @@ public class ReferenceBeanManager implements ApplicationContextAware { Assert.notEmptyString(referenceBeanName, "The id of ReferenceBean cannot be empty"); if (!initialized) { - //TODO add issue url to describe early initialization - logger.warn(CONFIG_DUBBO_BEAN_INITIALIZER, "", "", "Early initialize reference bean before DubboConfigBeanInitializer," + - " the BeanPostProcessor has not been loaded at this time, which may cause abnormalities in some components (such as seata): " + - referenceBeanName + " = " + ReferenceBeanSupport.generateReferenceKey(referenceBean, applicationContext)); + // TODO add issue url to describe early initialization + logger.warn( + CONFIG_DUBBO_BEAN_INITIALIZER, + "", + "", + "Early initialize reference bean before DubboConfigBeanInitializer," + + " the BeanPostProcessor has not been loaded at this time, which may cause abnormalities in some components (such as seata): " + + referenceBeanName + + " = " + ReferenceBeanSupport.generateReferenceKey(referenceBean, applicationContext)); } String referenceKey = getReferenceKeyByBeanName(referenceBeanName); if (StringUtils.isEmpty(referenceKey)) { @@ -80,14 +84,15 @@ public class ReferenceBeanManager implements ApplicationContextAware { ReferenceBean oldReferenceBean = referenceBeanMap.get(referenceBeanName); if (oldReferenceBean != null) { if (referenceBean != oldReferenceBean) { - String oldReferenceKey = ReferenceBeanSupport.generateReferenceKey(oldReferenceBean, applicationContext); - throw new IllegalStateException("Found duplicated ReferenceBean with id: " + referenceBeanName + - ", old: " + oldReferenceKey + ", new: " + referenceKey); + String oldReferenceKey = + ReferenceBeanSupport.generateReferenceKey(oldReferenceBean, applicationContext); + throw new IllegalStateException("Found duplicated ReferenceBean with id: " + referenceBeanName + + ", old: " + oldReferenceKey + ", new: " + referenceKey); } return; } referenceBeanMap.put(referenceBeanName, referenceBean); - //save cache, map reference key to referenceBeanName + // save cache, map reference key to referenceBeanName this.registerReferenceKeyAndBeanName(referenceKey, referenceBeanName); // if add reference after prepareReferenceBeans(), should init it immediately. @@ -107,7 +112,8 @@ public class ReferenceBeanManager implements ApplicationContextAware { } public void registerReferenceKeyAndBeanName(String referenceKey, String referenceBeanNameOrAlias) { - List list = ConcurrentHashMapUtils.computeIfAbsent(referenceKeyMap, referenceKey, (key) -> new ArrayList<>()); + List list = + ConcurrentHashMapUtils.computeIfAbsent(referenceKeyMap, referenceKey, (key) -> new ArrayList<>()); if (!list.contains(referenceBeanNameOrAlias)) { list.add(referenceBeanNameOrAlias); // register bean name as alias @@ -173,18 +179,18 @@ public class ReferenceBeanManager implements ApplicationContextAware { ReferenceConfig referenceConfig = referenceConfigMap.get(referenceKey); if (referenceConfig == null) { - //create real ReferenceConfig + // create real ReferenceConfig Map referenceAttributes = ReferenceBeanSupport.getReferenceAttributes(referenceBean); referenceConfig = ReferenceCreator.create(referenceAttributes, applicationContext) - .defaultInterfaceClass(referenceBean.getObjectType()) - .build(); + .defaultInterfaceClass(referenceBean.getObjectType()) + .build(); // set id if it is not a generated name if (referenceBean.getId() != null && !referenceBean.getId().contains("#")) { referenceConfig.setId(referenceBean.getId()); } - //cache referenceConfig + // cache referenceConfig referenceConfigMap.put(referenceKey, referenceConfig); // register ReferenceConfig @@ -195,5 +201,4 @@ public class ReferenceBeanManager implements ApplicationContextAware { // associate referenceConfig to referenceBean referenceBean.setKeyAndReferenceConfig(referenceKey, referenceConfig); } - } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceBeanSupport.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceBeanSupport.java index fb3dbe0a6c..24eab95001 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceBeanSupport.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceBeanSupport.java @@ -26,6 +26,16 @@ import org.apache.dubbo.config.spring.util.AnnotationUtils; import org.apache.dubbo.config.spring.util.DubboAnnotationUtils; import org.apache.dubbo.rpc.service.GenericService; +import java.lang.annotation.Annotation; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.PropertyValue; import org.springframework.beans.factory.config.BeanDefinition; @@ -39,23 +49,17 @@ import org.springframework.context.ApplicationContext; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.util.ObjectUtils; -import java.lang.annotation.Annotation; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - import static org.apache.dubbo.common.utils.StringUtils.join; public class ReferenceBeanSupport { - private static final List IGNORED_ATTRS = Arrays.asList(ReferenceAttributes.ID, ReferenceAttributes.GROUP, - ReferenceAttributes.VERSION, ReferenceAttributes.INTERFACE, ReferenceAttributes.INTERFACE_NAME, - ReferenceAttributes.INTERFACE_CLASS); + private static final List IGNORED_ATTRS = Arrays.asList( + ReferenceAttributes.ID, + ReferenceAttributes.GROUP, + ReferenceAttributes.VERSION, + ReferenceAttributes.INTERFACE, + ReferenceAttributes.INTERFACE_NAME, + ReferenceAttributes.INTERFACE_CLASS); public static void convertReferenceProps(Map attributes, Class defaultInterfaceClass) { @@ -96,7 +100,12 @@ public class ReferenceBeanSupport { String[] providedbByServices = new String[providedByReferenceLength + providedByInterfaceLength]; System.arraycopy(providedbBy.name(), 0, providedbByServices, 0, providedByReferenceLength); if (providedByInterfaceLength > 0) { - System.arraycopy(providedByInterfaceServices, 0, providedbByServices, providedByReferenceLength, providedByInterfaceLength); + System.arraycopy( + providedByInterfaceServices, + 0, + providedbByServices, + providedByReferenceLength, + providedByInterfaceLength); } attributes.put(ReferenceAttributes.PROVIDED_BY, providedbByServices); } @@ -104,15 +113,16 @@ public class ReferenceBeanSupport { attributes.remove(ReferenceAttributes.INTERFACE_NAME); attributes.remove(ReferenceAttributes.INTERFACE_CLASS); - //reset generic value + // reset generic value String generic = String.valueOf(defaultInterfaceClass == GenericService.class); - String oldGeneric = attributes.containsValue(ReferenceAttributes.GENERIC) ? - String.valueOf(attributes.get(ReferenceAttributes.GENERIC)) : "false"; + String oldGeneric = attributes.containsValue(ReferenceAttributes.GENERIC) + ? String.valueOf(attributes.get(ReferenceAttributes.GENERIC)) + : "false"; if (!StringUtils.isEquals(oldGeneric, generic)) { attributes.put(ReferenceAttributes.GENERIC, generic); } - //Specially convert @DubboReference attribute name/value to ReferenceConfig property + // Specially convert @DubboReference attribute name/value to ReferenceConfig property // String[] registry => String registryIds String[] registryIds = (String[]) attributes.get(ReferenceAttributes.REGISTRY); if (registryIds != null) { @@ -120,10 +130,8 @@ public class ReferenceBeanSupport { attributes.remove(ReferenceAttributes.REGISTRY); attributes.put(ReferenceAttributes.REGISTRY_IDS, value); } - } - public static String generateReferenceKey(Map attributes, ApplicationContext applicationContext) { String interfaceClass; @@ -136,7 +144,7 @@ public class ReferenceBeanSupport { String group = (String) attributes.get(ReferenceAttributes.GROUP); String version = (String) attributes.get(ReferenceAttributes.VERSION); - //ReferenceBean:group/interface:version + // ReferenceBean:group/interface:version StringBuilder beanNameBuilder = new StringBuilder("ReferenceBean:"); if (StringUtils.isNotEmpty(group)) { beanNameBuilder.append(group).append('/'); @@ -148,7 +156,7 @@ public class ReferenceBeanSupport { // append attributes beanNameBuilder.append('('); - //sort attributes keys + // sort attributes keys List sortedAttrKeys = new ArrayList<>(attributes.keySet()); Collections.sort(sortedAttrKeys); for (String key : sortedAttrKeys) { @@ -158,10 +166,7 @@ public class ReferenceBeanSupport { Object value = attributes.get(key); value = convertToString(key, value); - beanNameBuilder.append(key) - .append('=') - .append(value) - .append(','); + beanNameBuilder.append(key).append('=').append(value).append(','); } // replace the latest "," to be ")" @@ -175,8 +180,10 @@ public class ReferenceBeanSupport { if (applicationContext != null) { // resolve placeholder with Spring Environment referenceKey = applicationContext.getEnvironment().resolvePlaceholders(referenceKey); - // resolve placeholder with Spring BeanFactory ( using PropertyResourceConfigurer/PropertySourcesPlaceholderConfigurer ) - referenceKey = ((AbstractBeanFactory) applicationContext.getAutowireCapableBeanFactory()).resolveEmbeddedValue(referenceKey); + // resolve placeholder with Spring BeanFactory ( using + // PropertyResourceConfigurer/PropertySourcesPlaceholderConfigurer ) + referenceKey = ((AbstractBeanFactory) applicationContext.getAutowireCapableBeanFactory()) + .resolveEmbeddedValue(referenceKey); } return referenceKey; } @@ -186,11 +193,11 @@ public class ReferenceBeanSupport { return null; } if (ReferenceAttributes.PARAMETERS.equals(key) && obj instanceof String[]) { - //convert parameters array pairs to map + // convert parameters array pairs to map obj = DubboAnnotationUtils.convertParameters((String[]) obj); } - //to string + // to string if (obj instanceof Annotation) { AnnotationAttributes attributes = AnnotationUtils.getAnnotationAttributes((Annotation) obj, true); for (Map.Entry entry : attributes.entrySet()) { @@ -225,11 +232,13 @@ public class ReferenceBeanSupport { for (PropertyValue propertyValue : propertyValues.getPropertyValueList()) { String propertyName = propertyValue.getName(); Object value = propertyValue.getValue(); - if (ReferenceAttributes.METHODS.equals(propertyName) || ReferenceAttributes.ARGUMENTS.equals(propertyName)) { + if (ReferenceAttributes.METHODS.equals(propertyName) + || ReferenceAttributes.ARGUMENTS.equals(propertyName)) { ManagedList managedList = (ManagedList) value; List> elementList = new ArrayList<>(); for (Object el : managedList) { - Map element = convertPropertyValues(((BeanDefinitionHolder) el).getBeanDefinition().getPropertyValues()); + Map element = convertPropertyValues( + ((BeanDefinitionHolder) el).getBeanDefinition().getPropertyValues()); element.remove(ReferenceAttributes.ID); elementList.add(element); } @@ -237,16 +246,14 @@ public class ReferenceBeanSupport { } else if (ReferenceAttributes.PARAMETERS.equals(propertyName)) { value = createParameterMap((ManagedMap) value); } - //convert ref + // convert ref if (value instanceof RuntimeBeanReference) { RuntimeBeanReference beanReference = (RuntimeBeanReference) value; value = beanReference.getBeanName(); } - if (value == null || - (value instanceof String && StringUtils.isBlank((String) value)) - ) { - //ignore null or blank string + if (value == null || (value instanceof String && StringUtils.isBlank((String) value))) { + // ignore null or blank string continue; } @@ -278,7 +285,8 @@ public class ReferenceBeanSupport { if (referenceProps == null) { MutablePropertyValues propertyValues = referenceBean.getPropertyValues(); if (propertyValues == null) { - throw new RuntimeException("ReferenceBean is invalid, 'referenceProps' and 'propertyValues' cannot both be empty."); + throw new RuntimeException( + "ReferenceBean is invalid, 'referenceProps' and 'propertyValues' cannot both be empty."); } referenceProps = convertPropertyValues(propertyValues); } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceCreator.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceCreator.java index 0f8e69087d..2ac029e546 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceCreator.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceCreator.java @@ -35,6 +35,8 @@ import org.apache.dubbo.config.spring.util.DubboBeanUtils; import org.apache.dubbo.config.spring.util.ObjectUtils; import org.apache.dubbo.rpc.model.ModuleModel; +import java.util.Map; + import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.context.ApplicationContext; import org.springframework.core.convert.support.DefaultConversionService; @@ -42,8 +44,6 @@ import org.springframework.util.Assert; import org.springframework.util.StringUtils; import org.springframework.validation.DataBinder; -import java.util.Map; - /** * {@link ReferenceConfig} Creator for @{@link DubboReference} * @@ -52,7 +52,8 @@ import java.util.Map; public class ReferenceCreator { // Ignore those fields - static final String[] IGNORE_FIELD_NAMES = ObjectUtils.of("application", "module", "consumer", "monitor", "registry", "interfaceClass"); + static final String[] IGNORE_FIELD_NAMES = + ObjectUtils.of("application", "module", "consumer", "monitor", "registry", "interfaceClass"); private static final String ONRETURN = "onreturn"; @@ -80,8 +81,9 @@ public class ReferenceCreator { Assert.notNull(applicationContext, "The ApplicationContext must not be null!"); this.attributes = attributes; this.applicationContext = applicationContext; - this.classLoader = applicationContext.getClassLoader() != null ? - applicationContext.getClassLoader() : Thread.currentThread().getContextClassLoader(); + this.classLoader = applicationContext.getClassLoader() != null + ? applicationContext.getClassLoader() + : Thread.currentThread().getContextClassLoader(); moduleModel = DubboBeanUtils.getModuleModel(applicationContext); Assert.notNull(moduleModel, "ModuleModel not found in Spring ApplicationContext"); } @@ -93,13 +95,11 @@ public class ReferenceCreator { configureBean(configBean); if (logger.isInfoEnabled()) { - logger.info("The configBean[type:" + - configBean.getClass().getSimpleName() + "<" + defaultInterfaceClass.getTypeName() + ">" + - "] has been built."); + logger.info("The configBean[type:" + configBean.getClass().getSimpleName() + "<" + + defaultInterfaceClass.getTypeName() + ">" + "] has been built."); } return configBean; - } protected void configureBean(ReferenceConfig referenceConfig) throws Exception { @@ -111,7 +111,6 @@ public class ReferenceCreator { configureModuleConfig(referenceConfig); configureConsumerConfig(referenceConfig); - } private void configureMonitorConfig(ReferenceConfig configBean) { @@ -147,7 +146,10 @@ public class ReferenceCreator { private T getConfig(String configIdOrName, Class configType) { // 1. find in ModuleConfigManager - T config = moduleModel.getConfigManager().getConfig(configType, configIdOrName).orElse(null); + T config = moduleModel + .getConfigManager() + .getConfig(configType, configIdOrName) + .orElse(null); if (config == null) { // 2. find in Spring ApplicationContext if (applicationContext.containsBean(configIdOrName)) { @@ -175,16 +177,17 @@ public class ReferenceCreator { // convert String[] to Map (such as @Method.parameters()) conversionService.addConverter(String[].class, Map.class, DubboAnnotationUtils::convertParameters); - //convert Map to MethodConfig - conversionService.addConverter(Map.class, MethodConfig.class, source -> createMethodConfig(source, conversionService)); + // convert Map to MethodConfig + conversionService.addConverter( + Map.class, MethodConfig.class, source -> createMethodConfig(source, conversionService)); - //convert @Method to MethodConfig + // convert @Method to MethodConfig conversionService.addConverter(Method.class, MethodConfig.class, source -> { Map methodAttributes = AnnotationUtils.getAnnotationAttributes(source, true); return createMethodConfig(methodAttributes, conversionService); }); - //convert Map to ArgumentConfig + // convert Map to ArgumentConfig conversionService.addConverter(Map.class, ArgumentConfig.class, source -> { ArgumentConfig argumentConfig = new ArgumentConfig(); DataBinder argDataBinder = new DataBinder(argumentConfig); @@ -193,7 +196,7 @@ public class ReferenceCreator { return argumentConfig; }); - //convert @Argument to ArgumentConfig + // convert @Argument to ArgumentConfig conversionService.addConverter(Argument.class, ArgumentConfig.class, source -> { ArgumentConfig argumentConfig = new ArgumentConfig(); DataBinder argDataBinder = new DataBinder(argumentConfig); @@ -204,16 +207,17 @@ public class ReferenceCreator { // Bind annotation attributes dataBinder.setConversionService(conversionService); - dataBinder.bind(new AnnotationPropertyValuesAdapter(attributes, applicationContext.getEnvironment(), IGNORE_FIELD_NAMES)); - + dataBinder.bind(new AnnotationPropertyValuesAdapter( + attributes, applicationContext.getEnvironment(), IGNORE_FIELD_NAMES)); } - private MethodConfig createMethodConfig(Map methodAttributes, DefaultConversionService conversionService) { - String[] callbacks = new String[]{ONINVOKE, ONRETURN, ONTHROW}; + private MethodConfig createMethodConfig( + Map methodAttributes, DefaultConversionService conversionService) { + String[] callbacks = new String[] {ONINVOKE, ONRETURN, ONTHROW}; for (String callbackName : callbacks) { Object value = methodAttributes.get(callbackName); if (value instanceof String) { - //parse callback: beanName.methodName + // parse callback: beanName.methodName String strValue = (String) value; int index = strValue.lastIndexOf("."); if (index != -1) { @@ -231,7 +235,8 @@ public class ReferenceCreator { DataBinder mcDataBinder = new DataBinder(methodConfig); methodConfig.setReturn((Boolean) methodAttributes.get(ISRETURN)); mcDataBinder.setConversionService(conversionService); - AnnotationPropertyValuesAdapter propertyValues = new AnnotationPropertyValuesAdapter(methodAttributes, applicationContext.getEnvironment()); + AnnotationPropertyValuesAdapter propertyValues = + new AnnotationPropertyValuesAdapter(methodAttributes, applicationContext.getEnvironment()); mcDataBinder.bind(propertyValues); return methodConfig; } @@ -244,5 +249,4 @@ public class ReferenceCreator { this.defaultInterfaceClass = interfaceClass; return this; } - } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/AnnotationBeanDefinitionParser.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/AnnotationBeanDefinitionParser.java index 541a512c84..ebda43dcbe 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/AnnotationBeanDefinitionParser.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/AnnotationBeanDefinitionParser.java @@ -16,10 +16,8 @@ */ package org.apache.dubbo.config.spring.schema; -import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor; -import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor; - import org.apache.dubbo.config.spring.util.SpringCompatUtils; + import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser; @@ -76,5 +74,4 @@ public class AnnotationBeanDefinitionParser extends AbstractSingleBeanDefinition protected Class getBeanClass(Element element) { return SpringCompatUtils.serviceAnnotationPostProcessor(); } - } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboBeanDefinitionParser.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboBeanDefinitionParser.java index 9250b27243..dbdfc369ab 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboBeanDefinitionParser.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboBeanDefinitionParser.java @@ -39,6 +39,17 @@ import org.apache.dubbo.config.spring.ReferenceBean; import org.apache.dubbo.config.spring.ServiceBean; import org.apache.dubbo.config.spring.reference.ReferenceAttributes; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + import org.springframework.beans.PropertyValue; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; @@ -56,17 +67,6 @@ import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; - import static org.apache.dubbo.common.constants.CommonConstants.HIDE_KEY_PREFIX; import static org.apache.dubbo.config.spring.util.SpringCompatUtils.getPropertyValue; @@ -94,7 +94,8 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { } @SuppressWarnings("unchecked") - private static RootBeanDefinition parse(Element element, ParserContext parserContext, Class beanClass, boolean registered) { + private static RootBeanDefinition parse( + Element element, ParserContext parserContext, Class beanClass, boolean registered) { RootBeanDefinition beanDefinition = new RootBeanDefinition(); beanDefinition.setBeanClass(beanClass); beanDefinition.setLazyInit(false); @@ -125,18 +126,19 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { } beanDefinition.setAttribute(BEAN_NAME, beanName); - if (ProtocolConfig.class.equals(beanClass)) { -// for (String name : parserContext.getRegistry().getBeanDefinitionNames()) { -// BeanDefinition definition = parserContext.getRegistry().getBeanDefinition(name); -// PropertyValue property = definition.getPropertyValues().getPropertyValue("protocol"); -// if (property != null) { -// Object value = property.getValue(); -// if (value instanceof ProtocolConfig && beanName.equals(((ProtocolConfig) value).getName())) { -// definition.getPropertyValues().addPropertyValue("protocol", new RuntimeBeanReference(beanName)); -// } -// } -// } + // for (String name : parserContext.getRegistry().getBeanDefinitionNames()) { + // BeanDefinition definition = parserContext.getRegistry().getBeanDefinition(name); + // PropertyValue property = definition.getPropertyValues().getPropertyValue("protocol"); + // if (property != null) { + // Object value = property.getValue(); + // if (value instanceof ProtocolConfig && beanName.equals(((ProtocolConfig) + // value).getName())) { + // definition.getPropertyValues().addPropertyValue("protocol", new + // RuntimeBeanReference(beanName)); + // } + // } + // } } else if (ServiceBean.class.equals(beanClass)) { String className = resolveAttribute(element, "class", parserContext); if (StringUtils.isNotEmpty(className)) { @@ -144,17 +146,18 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { classDefinition.setBeanClass(ReflectUtils.forName(className)); classDefinition.setLazyInit(false); parseProperties(element.getChildNodes(), classDefinition, parserContext); - beanDefinition.getPropertyValues().addPropertyValue("ref", new BeanDefinitionHolder(classDefinition, beanName + "Impl")); + beanDefinition + .getPropertyValues() + .addPropertyValue("ref", new BeanDefinitionHolder(classDefinition, beanName + "Impl")); } } - Map beanPropTypeMap = beanPropsCache.get(beanClass.getName()); if (beanPropTypeMap == null) { beanPropTypeMap = new HashMap<>(); beanPropsCache.put(beanClass.getName(), beanPropTypeMap); if (ReferenceBean.class.equals(beanClass)) { - //extract bean props from ReferenceConfig + // extract bean props from ReferenceConfig getPropertyMap(ReferenceConfig.class, beanPropTypeMap); } else { getPropertyMap(beanClass, beanPropTypeMap); @@ -177,15 +180,19 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { } else { String value = resolveAttribute(element, property, parserContext); if (StringUtils.isNotBlank(value)) { - value=value.trim(); + value = value.trim(); if ("registry".equals(property) && RegistryConfig.NO_AVAILABLE.equalsIgnoreCase(value)) { RegistryConfig registryConfig = new RegistryConfig(); registryConfig.setAddress(RegistryConfig.NO_AVAILABLE); - // see AbstractInterfaceConfig#registries, It will be invoker setRegistries method when BeanDefinition is registered, + // see AbstractInterfaceConfig#registries, It will be invoker setRegistries method when + // BeanDefinition is registered, beanDefinition.getPropertyValues().addPropertyValue("registries", registryConfig); // If registry is N/A, don't init it until the reference is invoked beanDefinition.setLazyInit(true); - } else if ("provider".equals(property) || "registry".equals(property) || ("protocol".equals(property) && AbstractServiceConfig.class.isAssignableFrom(beanClass))) { + } else if ("provider".equals(property) + || "registry".equals(property) + || ("protocol".equals(property) + && AbstractServiceConfig.class.isAssignableFrom(beanClass))) { /** * For 'provider' 'protocol' 'registry', keep literal value (should be id/name) and set the value to 'registryIds' 'providerIds' protocolIds' * The following process should make sure each id refers to the corresponding instance, here's how to find the instance for different use cases: @@ -204,13 +211,18 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { String method = value.substring(index + 1); reference = new RuntimeBeanReference(ref); beanDefinition.getPropertyValues().addPropertyValue(property + METHOD, method); - } else if (EXECUTOR.equals(property)){ + } else if (EXECUTOR.equals(property)) { reference = new RuntimeBeanReference(value); } else { - if ("ref".equals(property) && parserContext.getRegistry().containsBeanDefinition(value)) { - BeanDefinition refBean = parserContext.getRegistry().getBeanDefinition(value); + if ("ref".equals(property) + && parserContext.getRegistry().containsBeanDefinition(value)) { + BeanDefinition refBean = + parserContext.getRegistry().getBeanDefinition(value); if (!refBean.isSingleton()) { - throw new IllegalStateException("The exported service ref " + value + " must be singleton! Please set the " + value + " bean scope to singleton, eg: "); + throw new IllegalStateException( + "The exported service ref " + value + " must be singleton! Please set the " + + value + " bean scope to singleton, eg: "); } } reference = new RuntimeBeanReference(value); @@ -242,9 +254,18 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { // post-process after parse attributes if (ProviderConfig.class.equals(beanClass)) { - parseNested(element, parserContext, ServiceBean.class, true, "service", "provider", beanName, beanDefinition); + parseNested( + element, parserContext, ServiceBean.class, true, "service", "provider", beanName, beanDefinition); } else if (ConsumerConfig.class.equals(beanClass)) { - parseNested(element, parserContext, ReferenceBean.class, true, "reference", "consumer", beanName, beanDefinition); + parseNested( + element, + parserContext, + ReferenceBean.class, + true, + "reference", + "consumer", + beanName, + beanDefinition); } else if (ReferenceBean.class.equals(beanClass)) { configReferenceBean(element, parserContext, beanDefinition, null); } else if (MetricsConfig.class.equals(beanClass)) { @@ -275,11 +296,12 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { AggregationConfig aggregation = new AggregationConfig(); assignProperties(aggregation, child, parserContext); beanDefinition.getPropertyValues().addPropertyValue("aggregation", aggregation); - }else if("histogram".equals(child.getNodeName()) || "histogram".equals(child.getLocalName())){ + } else if ("histogram".equals(child.getNodeName()) || "histogram".equals(child.getLocalName())) { HistogramConfig histogram = new HistogramConfig(); assignProperties(histogram, child, parserContext); beanDefinition.getPropertyValues().addPropertyValue("histogram", histogram); - } else if ("prometheus-exporter".equals(child.getNodeName()) || "prometheus-exporter".equals(child.getLocalName())) { + } else if ("prometheus-exporter".equals(child.getNodeName()) + || "prometheus-exporter".equals(child.getLocalName())) { if (prometheus == null) { prometheus = new PrometheusConfig(); } @@ -287,7 +309,8 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { PrometheusConfig.Exporter exporter = new PrometheusConfig.Exporter(); assignProperties(exporter, child, parserContext); prometheus.setExporter(exporter); - } else if ("prometheus-pushgateway".equals(child.getNodeName()) || "prometheus-pushgateway".equals(child.getLocalName())) { + } else if ("prometheus-pushgateway".equals(child.getNodeName()) + || "prometheus-pushgateway".equals(child.getLocalName())) { if (prometheus == null) { prometheus = new PrometheusConfig(); } @@ -307,7 +330,8 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { Method[] methods = obj.getClass().getMethods(); for (Method method : methods) { if (MethodUtils.isSetter(method)) { - String beanProperty = method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4); + String beanProperty = method.getName().substring(3, 4).toLowerCase() + + method.getName().substring(4); String property = StringUtils.camelToSplitName(beanProperty, "-"); String value = resolveAttribute(ele, property, parserContext); if (StringUtils.isNotEmpty(value)) { @@ -322,7 +346,11 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { } } - private static void configReferenceBean(Element element, ParserContext parserContext, RootBeanDefinition beanDefinition, BeanDefinition consumerDefinition) { + private static void configReferenceBean( + Element element, + ParserContext parserContext, + RootBeanDefinition beanDefinition, + BeanDefinition consumerDefinition) { // process interface class String interfaceName = resolveAttribute(element, ReferenceAttributes.INTERFACE, parserContext); String generic = resolveAttribute(element, ReferenceAttributes.GENERIC, parserContext); @@ -341,17 +369,18 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { // TODO Only register one reference bean for same (group, interface, version) - // create decorated definition for reference bean, Avoid being instantiated when getting the beanType of ReferenceBean + // create decorated definition for reference bean, Avoid being instantiated when getting the beanType of + // ReferenceBean // see org.springframework.beans.factory.support.AbstractBeanFactory#getTypeForFactoryBean() GenericBeanDefinition targetDefinition = new GenericBeanDefinition(); targetDefinition.setBeanClass(interfaceClass); String beanName = (String) beanDefinition.getAttribute(BEAN_NAME); - beanDefinition.setDecoratedDefinition(new BeanDefinitionHolder(targetDefinition, beanName+"_decorated")); + beanDefinition.setDecoratedDefinition(new BeanDefinitionHolder(targetDefinition, beanName + "_decorated")); // signal object type since Spring 5.2 beanDefinition.setAttribute(Constants.OBJECT_TYPE_ATTRIBUTE, interfaceClass); - //mark property value as optional + // mark property value as optional List propertyValues = beanDefinition.getPropertyValues().getPropertyValueList(); for (PropertyValue propertyValue : propertyValues) { propertyValue.setOptional(true); @@ -361,7 +390,8 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { private static void getPropertyMap(Class beanClass, Map beanPropsMap) { for (Method setter : beanClass.getMethods()) { String name = setter.getName(); - if (name.length() > 3 && name.startsWith("set") + if (name.length() > 3 + && name.startsWith("set") && Modifier.isPublic(setter.getModifiers()) && setter.getParameterTypes().length == 1) { Class type = setter.getParameterTypes()[0]; @@ -374,8 +404,10 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { try { getter = beanClass.getMethod("is" + name.substring(3), new Class[0]); } catch (NoSuchMethodException e2) { - // ignore, there is no need any log here since some class implement the interface: EnvironmentAware, - // ApplicationAware, etc. They only have setter method, otherwise will cause the error log during application start up. + // ignore, there is no need any log here since some class implement the interface: + // EnvironmentAware, + // ApplicationAware, etc. They only have setter method, otherwise will cause the error log + // during application start up. } } if (getter == null @@ -402,13 +434,29 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { } private static boolean isPrimitive(Class cls) { - return cls.isPrimitive() || cls == Boolean.class || cls == Byte.class - || cls == Character.class || cls == Short.class || cls == Integer.class - || cls == Long.class || cls == Float.class || cls == Double.class - || cls == String.class || cls == Date.class || cls == Class.class; + return cls.isPrimitive() + || cls == Boolean.class + || cls == Byte.class + || cls == Character.class + || cls == Short.class + || cls == Integer.class + || cls == Long.class + || cls == Float.class + || cls == Double.class + || cls == String.class + || cls == Date.class + || cls == Class.class; } - private static void parseNested(Element element, ParserContext parserContext, Class beanClass, boolean registered, String tag, String property, String ref, BeanDefinition beanDefinition) { + private static void parseNested( + Element element, + ParserContext parserContext, + Class beanClass, + boolean registered, + String tag, + String property, + String ref, + BeanDefinition beanDefinition) { NodeList nodeList = element.getChildNodes(); if (nodeList == null) { return; @@ -419,8 +467,7 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { if (!(node instanceof Element)) { continue; } - if (tag.equals(node.getNodeName()) - || tag.equals(node.getLocalName())) { + if (tag.equals(node.getNodeName()) || tag.equals(node.getLocalName())) { if (first) { first = false; String isDefault = resolveAttribute(element, "default", parserContext); @@ -441,7 +488,8 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { } } - private static void parseProperties(NodeList nodeList, RootBeanDefinition beanDefinition, ParserContext parserContext) { + private static void parseProperties( + NodeList nodeList, RootBeanDefinition beanDefinition, ParserContext parserContext) { if (nodeList == null) { return; } @@ -450,8 +498,7 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { continue; } Element element = (Element) nodeList.item(i); - if ("property".equals(element.getNodeName()) - || "property".equals(element.getLocalName())) { + if ("property".equals(element.getNodeName()) || "property".equals(element.getLocalName())) { String name = resolveAttribute(element, "name", parserContext); if (StringUtils.isNotEmpty(name)) { String value = resolveAttribute(element, "value", parserContext); @@ -461,7 +508,9 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { } else if (StringUtils.isNotEmpty(ref)) { beanDefinition.getPropertyValues().addPropertyValue(name, new RuntimeBeanReference(ref)); } else { - throw new UnsupportedOperationException("Unsupported sub tag, Only supported or "); + throw new UnsupportedOperationException("Unsupported sub tag, Only supported or "); } } } @@ -469,7 +518,8 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { } @SuppressWarnings("unchecked") - private static ManagedMap parseParameters(NodeList nodeList, RootBeanDefinition beanDefinition, ParserContext parserContext) { + private static ManagedMap parseParameters( + NodeList nodeList, RootBeanDefinition beanDefinition, ParserContext parserContext) { if (nodeList == null) { return null; } @@ -479,8 +529,7 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { continue; } Element element = (Element) nodeList.item(i); - if ("parameter".equals(element.getNodeName()) - || "parameter".equals(element.getLocalName())) { + if ("parameter".equals(element.getNodeName()) || "parameter".equals(element.getLocalName())) { if (parameters == null) { parameters = new ManagedMap(); } @@ -497,8 +546,8 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { } @SuppressWarnings("unchecked") - private static void parseMethods(String id, NodeList nodeList, RootBeanDefinition beanDefinition, - ParserContext parserContext) { + private static void parseMethods( + String id, NodeList nodeList, RootBeanDefinition beanDefinition, ParserContext parserContext) { if (nodeList == null) { return; } @@ -516,8 +565,7 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { if (methods == null) { methods = new ManagedList(); } - RootBeanDefinition methodBeanDefinition = parse(element, - parserContext, MethodConfig.class, false); + RootBeanDefinition methodBeanDefinition = parse(element, parserContext, MethodConfig.class, false); String beanName = id + "." + methodName; // If the PropertyValue named "id" can't be found, @@ -526,8 +574,8 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { addPropertyValue(methodBeanDefinition, "id", beanName); } - BeanDefinitionHolder methodBeanDefinitionHolder = new BeanDefinitionHolder( - methodBeanDefinition, beanName); + BeanDefinitionHolder methodBeanDefinitionHolder = + new BeanDefinitionHolder(methodBeanDefinition, beanName); methods.add(methodBeanDefinitionHolder); } } @@ -540,7 +588,8 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { return beanDefinition.getPropertyValues().contains(propertyName); } - private static void addPropertyValue(AbstractBeanDefinition beanDefinition, String propertyName, String propertyValue) { + private static void addPropertyValue( + AbstractBeanDefinition beanDefinition, String propertyName, String propertyValue) { if (StringUtils.isBlank(propertyName) || StringUtils.isBlank(propertyValue)) { return; } @@ -548,8 +597,8 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { } @SuppressWarnings("unchecked") - private static void parseArguments(String id, NodeList nodeList, RootBeanDefinition beanDefinition, - ParserContext parserContext) { + private static void parseArguments( + String id, NodeList nodeList, RootBeanDefinition beanDefinition, ParserContext parserContext) { if (nodeList == null) { return; } @@ -564,11 +613,10 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { if (arguments == null) { arguments = new ManagedList(); } - BeanDefinition argumentBeanDefinition = parse(element, - parserContext, ArgumentConfig.class, false); + BeanDefinition argumentBeanDefinition = parse(element, parserContext, ArgumentConfig.class, false); String name = id + "." + argumentIndex; - BeanDefinitionHolder argumentBeanDefinitionHolder = new BeanDefinitionHolder( - argumentBeanDefinition, name); + BeanDefinitionHolder argumentBeanDefinitionHolder = + new BeanDefinitionHolder(argumentBeanDefinition, name); arguments.add(argumentBeanDefinitionHolder); } } @@ -584,11 +632,12 @@ public class DubboBeanDefinitionParser implements BeanDefinitionParser { private static String resolveAttribute(Element element, String attributeName, ParserContext parserContext) { String attributeValue = element.getAttribute(attributeName); - // Early resolve place holder may be wrong ( Before PropertySourcesPlaceholderConfigurer/PropertyPlaceholderConfigurer ) - //https://github.com/apache/dubbo/pull/6079 - //https://github.com/apache/dubbo/issues/6035 -// Environment environment = parserContext.getReaderContext().getEnvironment(); -// return environment.resolvePlaceholders(attributeValue); + // Early resolve place holder may be wrong ( Before + // PropertySourcesPlaceholderConfigurer/PropertyPlaceholderConfigurer ) + // https://github.com/apache/dubbo/pull/6079 + // https://github.com/apache/dubbo/issues/6035 + // Environment environment = parserContext.getReaderContext().getEnvironment(); + // return environment.resolvePlaceholders(attributeValue); return attributeValue; } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/DataSourceStatusChecker.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/DataSourceStatusChecker.java index 2f2e44fbac..0b46de0f3a 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/DataSourceStatusChecker.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/DataSourceStatusChecker.java @@ -25,14 +25,15 @@ import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.config.spring.extension.SpringExtensionInjector; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.springframework.context.ApplicationContext; - import javax.sql.DataSource; + import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.util.Map; +import org.springframework.context.ApplicationContext; + import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_WARN_STATUS_CHECKER; /** @@ -41,7 +42,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_WARN_ @Activate public class DataSourceStatusChecker implements StatusChecker { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DataSourceStatusChecker.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(DataSourceStatusChecker.class); private ApplicationModel applicationModel; @@ -66,8 +68,7 @@ public class DataSourceStatusChecker implements StatusChecker { return new Status(Status.Level.UNKNOWN); } - Map dataSources = - applicationContext.getBeansOfType(DataSource.class, false, false); + Map dataSources = applicationContext.getBeansOfType(DataSource.class, false, false); if (CollectionUtils.isEmptyMap(dataSources)) { return new Status(Status.Level.UNKNOWN); } @@ -100,5 +101,4 @@ public class DataSourceStatusChecker implements StatusChecker { } return new Status(level, buf.toString()); } - } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/SpringStatusChecker.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/SpringStatusChecker.java index 4ef77b1aa9..ca42b6ce40 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/SpringStatusChecker.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/SpringStatusChecker.java @@ -24,11 +24,11 @@ import org.apache.dubbo.common.status.StatusChecker; import org.apache.dubbo.config.spring.extension.SpringExtensionInjector; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.lang.reflect.Method; + import org.springframework.context.ApplicationContext; import org.springframework.context.Lifecycle; -import java.lang.reflect.Method; - import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_WARN_STATUS_CHECKER; /** @@ -99,13 +99,12 @@ public class SpringStatusChecker implements StatusChecker { } } } catch (Throwable t) { - if (t.getCause() instanceof UnsupportedOperationException){ + if (t.getCause() instanceof UnsupportedOperationException) { logger.debug(t.getMessage(), t); - }else { + } else { logger.warn(CONFIG_WARN_STATUS_CHECKER, "", "", t.getMessage(), t); } } return new Status(level, buf.toString()); } - } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/AnnotationUtils.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/AnnotationUtils.java index dcef582525..713a191835 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/AnnotationUtils.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/AnnotationUtils.java @@ -16,11 +16,6 @@ */ package org.apache.dubbo.config.spring.util; -import org.springframework.core.annotation.AnnotationAttributes; -import org.springframework.core.env.Environment; -import org.springframework.core.env.PropertyResolver; -import org.springframework.util.ClassUtils; - import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; @@ -33,6 +28,11 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import org.springframework.core.annotation.AnnotationAttributes; +import org.springframework.core.env.Environment; +import org.springframework.core.env.PropertyResolver; +import org.springframework.util.ClassUtils; + import static java.lang.String.valueOf; import static java.util.Arrays.asList; import static org.springframework.core.annotation.AnnotationAttributes.fromMap; @@ -50,7 +50,8 @@ public abstract class AnnotationUtils { /** * The class name of AnnotatedElementUtils that is introduced since Spring Framework 4 */ - public static final String ANNOTATED_ELEMENT_UTILS_CLASS_NAME = "org.springframework.core.annotation.AnnotatedElementUtils"; + public static final String ANNOTATED_ELEMENT_UTILS_CLASS_NAME = + "org.springframework.core.annotation.AnnotatedElementUtils"; private static final Map annotatedElementUtilsPresentCache = new ConcurrentHashMap<>(); @@ -63,8 +64,11 @@ public abstract class AnnotationUtils { * @param ignoreAttributeNames the attribute names of annotation should be ignored * @return non-null */ - public static Map getAttributes(Annotation annotation, PropertyResolver propertyResolver, - boolean ignoreDefaultValue, String... ignoreAttributeNames) { + public static Map getAttributes( + Annotation annotation, + PropertyResolver propertyResolver, + boolean ignoreDefaultValue, + String... ignoreAttributeNames) { return getAttributes(annotation, propertyResolver, false, false, ignoreDefaultValue, ignoreAttributeNames); } @@ -76,8 +80,10 @@ public abstract class AnnotationUtils { * @param ignoreAttributeNames the attribute names of annotation should be ignored * @return non-null */ - public static Map getAttributes(Map annotationAttributes, - PropertyResolver propertyResolver, String... ignoreAttributeNames) { + public static Map getAttributes( + Map annotationAttributes, + PropertyResolver propertyResolver, + String... ignoreAttributeNames) { Set ignoreAttributeNamesSet = new HashSet<>(Arrays.asList(ignoreAttributeNames)); @@ -121,14 +127,17 @@ public abstract class AnnotationUtils { * @param ignoreAttributeNames the attribute names of annotation should be ignored * @return */ - public static Map getAttributes(Annotation annotation, - PropertyResolver propertyResolver, - boolean classValuesAsString, - boolean nestedAnnotationsAsMap, - boolean ignoreDefaultValue, - String... ignoreAttributeNames) { + public static Map getAttributes( + Annotation annotation, + PropertyResolver propertyResolver, + boolean classValuesAsString, + boolean nestedAnnotationsAsMap, + boolean ignoreDefaultValue, + String... ignoreAttributeNames) { - Map annotationAttributes = org.springframework.core.annotation.AnnotationUtils.getAnnotationAttributes(annotation, classValuesAsString, nestedAnnotationsAsMap); + Map annotationAttributes = + org.springframework.core.annotation.AnnotationUtils.getAnnotationAttributes( + annotation, classValuesAsString, nestedAnnotationsAsMap); String[] actualIgnoreAttributeNames = ignoreAttributeNames; @@ -225,8 +234,8 @@ public abstract class AnnotationUtils { * @return non-null * @see #getAnnotationAttributes(Annotation, PropertyResolver, boolean, String...) */ - public static AnnotationAttributes getAnnotationAttributes(Annotation annotation, boolean ignoreDefaultValue, - String... ignoreAttributeNames) { + public static AnnotationAttributes getAnnotationAttributes( + Annotation annotation, boolean ignoreDefaultValue, String... ignoreAttributeNames) { return getAnnotationAttributes(annotation, null, ignoreDefaultValue, ignoreAttributeNames); } @@ -248,14 +257,20 @@ public abstract class AnnotationUtils { * @see #getAttributes(Annotation, PropertyResolver, boolean, String...) * @see #getAnnotationAttributes(AnnotatedElement, Class, PropertyResolver, boolean, String...) */ - public static AnnotationAttributes getAnnotationAttributes(Annotation annotation, - PropertyResolver propertyResolver, - boolean classValuesAsString, - boolean nestedAnnotationsAsMap, - boolean ignoreDefaultValue, - String... ignoreAttributeNames) { - return fromMap(getAttributes(annotation, propertyResolver, classValuesAsString, nestedAnnotationsAsMap, - ignoreDefaultValue, ignoreAttributeNames)); + public static AnnotationAttributes getAnnotationAttributes( + Annotation annotation, + PropertyResolver propertyResolver, + boolean classValuesAsString, + boolean nestedAnnotationsAsMap, + boolean ignoreDefaultValue, + String... ignoreAttributeNames) { + return fromMap(getAttributes( + annotation, + propertyResolver, + classValuesAsString, + nestedAnnotationsAsMap, + ignoreDefaultValue, + ignoreAttributeNames)); } /** @@ -269,9 +284,13 @@ public abstract class AnnotationUtils { * @see #getAttributes(Annotation, PropertyResolver, boolean, String...) * @see #getAnnotationAttributes(AnnotatedElement, Class, PropertyResolver, boolean, String...) */ - public static AnnotationAttributes getAnnotationAttributes(Annotation annotation, PropertyResolver propertyResolver, - boolean ignoreDefaultValue, String... ignoreAttributeNames) { - return getAnnotationAttributes(annotation, propertyResolver, false, false, ignoreDefaultValue, ignoreAttributeNames); + public static AnnotationAttributes getAnnotationAttributes( + Annotation annotation, + PropertyResolver propertyResolver, + boolean ignoreDefaultValue, + String... ignoreAttributeNames) { + return getAnnotationAttributes( + annotation, propertyResolver, false, false, ignoreDefaultValue, ignoreAttributeNames); } /** @@ -284,16 +303,24 @@ public abstract class AnnotationUtils { * @param ignoreAttributeNames the attribute names of annotation should be ignored * @return if annotatedElement can't be found in annotatedElement, return null */ - public static AnnotationAttributes getAnnotationAttributes(AnnotatedElement annotatedElement, - Class annotationType, - PropertyResolver propertyResolver, - boolean classValuesAsString, - boolean nestedAnnotationsAsMap, - boolean ignoreDefaultValue, - String... ignoreAttributeNames) { + public static AnnotationAttributes getAnnotationAttributes( + AnnotatedElement annotatedElement, + Class annotationType, + PropertyResolver propertyResolver, + boolean classValuesAsString, + boolean nestedAnnotationsAsMap, + boolean ignoreDefaultValue, + String... ignoreAttributeNames) { Annotation annotation = annotatedElement.getAnnotation(annotationType); - return annotation == null ? null : getAnnotationAttributes(annotation, propertyResolver, - classValuesAsString, nestedAnnotationsAsMap, ignoreDefaultValue, ignoreAttributeNames); + return annotation == null + ? null + : getAnnotationAttributes( + annotation, + propertyResolver, + classValuesAsString, + nestedAnnotationsAsMap, + ignoreDefaultValue, + ignoreAttributeNames); } /** @@ -311,14 +338,22 @@ public abstract class AnnotationUtils { * @param ignoreAttributeNames the attribute names of annotation should be ignored * @return if annotatedElement can't be found in annotatedElement, return null */ - public static AnnotationAttributes getAnnotationAttributes(AnnotatedElement annotatedElement, - Class annotationType, - PropertyResolver propertyResolver, - boolean ignoreDefaultValue, - boolean tryMergedAnnotation, - String... ignoreAttributeNames) { - return getAnnotationAttributes(annotatedElement, annotationType, propertyResolver, - false, false, ignoreDefaultValue, tryMergedAnnotation, ignoreAttributeNames); + public static AnnotationAttributes getAnnotationAttributes( + AnnotatedElement annotatedElement, + Class annotationType, + PropertyResolver propertyResolver, + boolean ignoreDefaultValue, + boolean tryMergedAnnotation, + String... ignoreAttributeNames) { + return getAnnotationAttributes( + annotatedElement, + annotationType, + propertyResolver, + false, + false, + ignoreDefaultValue, + tryMergedAnnotation, + ignoreAttributeNames); } /** @@ -343,25 +378,38 @@ public abstract class AnnotationUtils { * @param ignoreAttributeNames the attribute names of annotation should be ignored * @return if annotatedElement can't be found in annotatedElement, return null */ - public static AnnotationAttributes getAnnotationAttributes(AnnotatedElement annotatedElement, - Class annotationType, - PropertyResolver propertyResolver, - boolean classValuesAsString, - boolean nestedAnnotationsAsMap, - boolean ignoreDefaultValue, - boolean tryMergedAnnotation, - String... ignoreAttributeNames) { + public static AnnotationAttributes getAnnotationAttributes( + AnnotatedElement annotatedElement, + Class annotationType, + PropertyResolver propertyResolver, + boolean classValuesAsString, + boolean nestedAnnotationsAsMap, + boolean ignoreDefaultValue, + boolean tryMergedAnnotation, + String... ignoreAttributeNames) { AnnotationAttributes attributes = null; if (tryMergedAnnotation) { - attributes = tryGetMergedAnnotationAttributes(annotatedElement, annotationType, propertyResolver, - classValuesAsString, nestedAnnotationsAsMap, ignoreDefaultValue, ignoreAttributeNames); + attributes = tryGetMergedAnnotationAttributes( + annotatedElement, + annotationType, + propertyResolver, + classValuesAsString, + nestedAnnotationsAsMap, + ignoreDefaultValue, + ignoreAttributeNames); } if (attributes == null) { - attributes = getAnnotationAttributes(annotatedElement, annotationType, propertyResolver, - classValuesAsString, nestedAnnotationsAsMap, ignoreDefaultValue, ignoreAttributeNames); + attributes = getAnnotationAttributes( + annotatedElement, + annotationType, + propertyResolver, + classValuesAsString, + nestedAnnotationsAsMap, + ignoreDefaultValue, + ignoreAttributeNames); } return attributes; @@ -381,24 +429,36 @@ public abstract class AnnotationUtils { * Annotation instances * @return If current version of Spring Framework is below 4.2, return null */ - public static Annotation tryGetMergedAnnotation(AnnotatedElement annotatedElement, - Class annotationType, - boolean classValuesAsString, - boolean nestedAnnotationsAsMap) { + public static Annotation tryGetMergedAnnotation( + AnnotatedElement annotatedElement, + Class annotationType, + boolean classValuesAsString, + boolean nestedAnnotationsAsMap) { Annotation mergedAnnotation = null; ClassLoader classLoader = annotationType.getClassLoader(); - if (annotatedElementUtilsPresentCache.computeIfAbsent(System.identityHashCode(classLoader), - (_k) -> ClassUtils.isPresent(ANNOTATED_ELEMENT_UTILS_CLASS_NAME, classLoader))) { + if (annotatedElementUtilsPresentCache.computeIfAbsent( + System.identityHashCode(classLoader), + (_k) -> ClassUtils.isPresent(ANNOTATED_ELEMENT_UTILS_CLASS_NAME, classLoader))) { Class annotatedElementUtilsClass = resolveClassName(ANNOTATED_ELEMENT_UTILS_CLASS_NAME, classLoader); // getMergedAnnotation method appears in the Spring Framework 4.2 - Method getMergedAnnotationMethod = findMethod(annotatedElementUtilsClass, "getMergedAnnotation", - AnnotatedElement.class, Class.class, boolean.class, boolean.class); + Method getMergedAnnotationMethod = findMethod( + annotatedElementUtilsClass, + "getMergedAnnotation", + AnnotatedElement.class, + Class.class, + boolean.class, + boolean.class); if (getMergedAnnotationMethod != null) { - mergedAnnotation = (Annotation) invokeMethod(getMergedAnnotationMethod, null, - annotatedElement, annotationType, classValuesAsString, nestedAnnotationsAsMap); + mergedAnnotation = (Annotation) invokeMethod( + getMergedAnnotationMethod, + null, + annotatedElement, + annotationType, + classValuesAsString, + nestedAnnotationsAsMap); } } @@ -422,16 +482,24 @@ public abstract class AnnotationUtils { * @param ignoreAttributeNames the attribute names of annotation should be ignored * @return If the specified annotation type is not found, return null */ - public static AnnotationAttributes tryGetMergedAnnotationAttributes(AnnotatedElement annotatedElement, - Class annotationType, - PropertyResolver propertyResolver, - boolean classValuesAsString, - boolean nestedAnnotationsAsMap, - boolean ignoreDefaultValue, - String... ignoreAttributeNames) { - Annotation annotation = tryGetMergedAnnotation(annotatedElement, annotationType, classValuesAsString, nestedAnnotationsAsMap); - return annotation == null ? null : getAnnotationAttributes(annotation, propertyResolver, - classValuesAsString, nestedAnnotationsAsMap, ignoreDefaultValue, ignoreAttributeNames); + public static AnnotationAttributes tryGetMergedAnnotationAttributes( + AnnotatedElement annotatedElement, + Class annotationType, + PropertyResolver propertyResolver, + boolean classValuesAsString, + boolean nestedAnnotationsAsMap, + boolean ignoreDefaultValue, + String... ignoreAttributeNames) { + Annotation annotation = + tryGetMergedAnnotation(annotatedElement, annotationType, classValuesAsString, nestedAnnotationsAsMap); + return annotation == null + ? null + : getAnnotationAttributes( + annotation, + propertyResolver, + classValuesAsString, + nestedAnnotationsAsMap, + ignoreDefaultValue, + ignoreAttributeNames); } - } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/DubboAnnotationUtils.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/DubboAnnotationUtils.java index 6a3ffb62c3..08a46a67f4 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/DubboAnnotationUtils.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/DubboAnnotationUtils.java @@ -23,8 +23,6 @@ import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.rpc.service.GenericService; -import org.springframework.util.Assert; - import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -32,6 +30,8 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import org.springframework.util.Assert; + import static org.springframework.util.ClassUtils.getAllInterfacesForClass; import static org.springframework.util.StringUtils.hasText; @@ -43,7 +43,6 @@ import static org.springframework.util.StringUtils.hasText; */ public class DubboAnnotationUtils { - @Deprecated public static String resolveInterfaceName(Service service, Class defaultInterfaceClass) throws IllegalStateException { @@ -56,13 +55,11 @@ public class DubboAnnotationUtils { } else if (defaultInterfaceClass.isInterface()) { interfaceName = defaultInterfaceClass.getName(); } else { - throw new IllegalStateException( - "The @Service undefined interfaceClass or interfaceName, and the type " - + defaultInterfaceClass.getName() + " is not a interface."); + throw new IllegalStateException("The @Service undefined interfaceClass or interfaceName, and the type " + + defaultInterfaceClass.getName() + " is not a interface."); } return interfaceName; - } /** @@ -79,9 +76,10 @@ public class DubboAnnotationUtils { // 1. get from DubboService.interfaceName() String interfaceClassName = AnnotationUtils.getAttribute(attributes, "interfaceName"); if (StringUtils.hasText(interfaceClassName)) { - if ("org.apache.dubbo.rpc.service.GenericService".equals(interfaceClassName) || - "com.alibaba.dubbo.rpc.service.GenericService".equals(interfaceClassName)) { - throw new IllegalStateException("@Service interfaceName() cannot be GenericService: " + interfaceClassName); + if ("org.apache.dubbo.rpc.service.GenericService".equals(interfaceClassName) + || "com.alibaba.dubbo.rpc.service.GenericService".equals(interfaceClassName)) { + throw new IllegalStateException( + "@Service interfaceName() cannot be GenericService: " + interfaceClassName); } return interfaceClassName; } @@ -90,12 +88,15 @@ public class DubboAnnotationUtils { Class interfaceClass = AnnotationUtils.getAttribute(attributes, "interfaceClass"); if (interfaceClass == null || void.class.equals(interfaceClass)) { // default or set void.class for purpose. interfaceClass = null; - } else if (GenericService.class.isAssignableFrom(interfaceClass)) { - throw new IllegalStateException("@Service interfaceClass() cannot be GenericService :" + interfaceClass.getName()); + } else if (GenericService.class.isAssignableFrom(interfaceClass)) { + throw new IllegalStateException( + "@Service interfaceClass() cannot be GenericService :" + interfaceClass.getName()); } // 3. get from annotation element type, ignore GenericService - if (interfaceClass == null && defaultInterfaceClass != null && !GenericService.class.isAssignableFrom(defaultInterfaceClass)) { + if (interfaceClass == null + && defaultInterfaceClass != null + && !GenericService.class.isAssignableFrom(defaultInterfaceClass)) { // Find all interfaces from the annotated class // To resolve an issue : https://github.com/apache/dubbo/issues/3251 Class[] allInterfaces = getAllInterfacesForClass(defaultInterfaceClass); @@ -104,7 +105,8 @@ public class DubboAnnotationUtils { } } - Assert.notNull(interfaceClass, "@Service interfaceClass() or interfaceName() or interface class must be present!"); + Assert.notNull( + interfaceClass, "@Service interfaceClass() or interfaceName() or interface class must be present!"); Assert.isTrue(interfaceClass.isInterface(), "The annotated type must be an interface!"); return interfaceClass.getName(); } @@ -121,9 +123,8 @@ public class DubboAnnotationUtils { } else if (defaultInterfaceClass.isInterface()) { interfaceName = defaultInterfaceClass.getName(); } else { - throw new IllegalStateException( - "The @Reference undefined interfaceClass or interfaceName, and the type " - + defaultInterfaceClass.getName() + " is not a interface."); + throw new IllegalStateException("The @Reference undefined interfaceClass or interfaceName, and the type " + + defaultInterfaceClass.getName() + " is not a interface."); } return interfaceName; @@ -157,30 +158,31 @@ public class DubboAnnotationUtils { } List compatibleParameterArray = Arrays.stream(parameters) - .map(String::trim) - .reduce(new ArrayList<>(parameters.length), (list, parameter) -> - { - if (list.size() % 2 == 1) { - //value doesn't split - list.add(parameter); - return list; - } + .map(String::trim) + .reduce( + new ArrayList<>(parameters.length), + (list, parameter) -> { + if (list.size() % 2 == 1) { + // value doesn't split + list.add(parameter); + return list; + } - String[] sp1 = parameter.split(":"); - if (sp1.length > 0 && sp1.length % 2 == 0) { - //key split - list.addAll(Arrays.stream(sp1).map(String::trim).collect(Collectors.toList())); - return list; - } - sp1 = parameter.split("="); - if (sp1.length > 0 && sp1.length % 2 == 0) { - list.addAll(Arrays.stream(sp1).map(String::trim).collect(Collectors.toList())); - return list; - } - list.add(parameter); - return list; - } - , (a, b) -> a); + String[] sp1 = parameter.split(":"); + if (sp1.length > 0 && sp1.length % 2 == 0) { + // key split + list.addAll(Arrays.stream(sp1).map(String::trim).collect(Collectors.toList())); + return list; + } + sp1 = parameter.split("="); + if (sp1.length > 0 && sp1.length % 2 == 0) { + list.addAll(Arrays.stream(sp1).map(String::trim).collect(Collectors.toList())); + return list; + } + list.add(parameter); + return list; + }, + (a, b) -> a); return CollectionUtils.toStringMap(compatibleParameterArray.toArray(new String[0])); } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/DubboBeanUtils.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/DubboBeanUtils.java index fd53a3d076..a94226a342 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/DubboBeanUtils.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/DubboBeanUtils.java @@ -16,8 +16,6 @@ */ package org.apache.dubbo.config.spring.util; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.config.spring.beans.factory.annotation.DubboConfigAliasPostProcessor; import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor; @@ -32,6 +30,12 @@ import org.apache.dubbo.config.spring.context.DubboSpringInitContext; import org.apache.dubbo.config.spring.reference.ReferenceBeanManager; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanPostProcessor; @@ -43,9 +47,6 @@ import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.ApplicationContext; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import java.util.HashMap; -import java.util.Map; - /** * Dubbo Bean utilities class * @@ -72,27 +73,36 @@ public interface DubboBeanUtils { registerInfrastructureBean(registry, ReferenceBeanManager.BEAN_NAME, ReferenceBeanManager.class); // Since 2.5.7 Register @Reference Annotation Bean Processor as an infrastructure Bean - registerInfrastructureBean(registry, SpringCompatUtils.referenceAnnotationBeanPostProcessor().getName(), - SpringCompatUtils.referenceAnnotationBeanPostProcessor()); + registerInfrastructureBean( + registry, + SpringCompatUtils.referenceAnnotationBeanPostProcessor().getName(), + SpringCompatUtils.referenceAnnotationBeanPostProcessor()); // TODO Whether DubboConfigAliasPostProcessor can be removed ? // Since 2.7.4 [Feature] https://github.com/apache/dubbo/issues/5093 - registerInfrastructureBean(registry, DubboConfigAliasPostProcessor.BEAN_NAME, - DubboConfigAliasPostProcessor.class); + registerInfrastructureBean( + registry, DubboConfigAliasPostProcessor.BEAN_NAME, DubboConfigAliasPostProcessor.class); // register ApplicationListeners - registerInfrastructureBean(registry, DubboDeployApplicationListener.class.getName(), DubboDeployApplicationListener.class); - registerInfrastructureBean(registry, DubboConfigApplicationListener.class.getName(), DubboConfigApplicationListener.class); + registerInfrastructureBean( + registry, DubboDeployApplicationListener.class.getName(), DubboDeployApplicationListener.class); + registerInfrastructureBean( + registry, DubboConfigApplicationListener.class.getName(), DubboConfigApplicationListener.class); // Since 2.7.6 Register DubboConfigDefaultPropertyValueBeanPostProcessor as an infrastructure Bean - registerInfrastructureBean(registry, DubboConfigDefaultPropertyValueBeanPostProcessor.BEAN_NAME, - DubboConfigDefaultPropertyValueBeanPostProcessor.class); + registerInfrastructureBean( + registry, + DubboConfigDefaultPropertyValueBeanPostProcessor.BEAN_NAME, + DubboConfigDefaultPropertyValueBeanPostProcessor.class); // Dubbo config initializer registerInfrastructureBean(registry, DubboConfigBeanInitializer.BEAN_NAME, DubboConfigBeanInitializer.class); // register infra bean if not exists later - registerInfrastructureBean(registry, DubboInfraBeanRegisterPostProcessor.BEAN_NAME, SpringCompatUtils.dubboInfraBeanRegisterPostProcessor()); + registerInfrastructureBean( + registry, + DubboInfraBeanRegisterPostProcessor.BEAN_NAME, + SpringCompatUtils.dubboInfraBeanRegisterPostProcessor()); } /** @@ -103,9 +113,8 @@ public interface DubboBeanUtils { * @param beanName the name of bean * @return if it's a first time to register, return true, or false */ - static boolean registerInfrastructureBean(BeanDefinitionRegistry beanDefinitionRegistry, - String beanName, - Class beanType) { + static boolean registerInfrastructureBean( + BeanDefinitionRegistry beanDefinitionRegistry, String beanName, Class beanType) { boolean registered = false; @@ -116,8 +125,8 @@ public interface DubboBeanUtils { registered = true; if (log.isDebugEnabled()) { - log.debug("The Infrastructure bean definition [" + beanDefinition - + "with name [" + beanName + "] has been registered."); + log.debug("The Infrastructure bean definition [" + beanDefinition + "with name [" + beanName + + "] has been registered."); } } @@ -134,25 +143,34 @@ public interface DubboBeanUtils { * @see DubboInfraBeanRegisterPostProcessor * @see org.springframework.context.support.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors(org.springframework.beans.factory.config.ConfigurableListableBeanFactory, java.util.List) */ - static void registerPlaceholderConfigurerBeanIfNotExists(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry) { - // Auto register a PropertyPlaceholderConfigurer bean to resolve placeholders with Spring Environment PropertySources + static void registerPlaceholderConfigurerBeanIfNotExists( + ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry) { + // Auto register a PropertyPlaceholderConfigurer bean to resolve placeholders with Spring Environment + // PropertySources // when loading dubbo xml config with @ImportResource if (!checkBeanExists(beanFactory, PropertySourcesPlaceholderConfigurer.class)) { Map propertySourcesPlaceholderPropertyValues = new HashMap<>(); propertySourcesPlaceholderPropertyValues.put("ignoreUnresolvablePlaceholders", true); - registerBeanDefinition(registry, PropertySourcesPlaceholderConfigurer.class.getName(), - PropertySourcesPlaceholderConfigurer.class, propertySourcesPlaceholderPropertyValues); + registerBeanDefinition( + registry, + PropertySourcesPlaceholderConfigurer.class.getName(), + PropertySourcesPlaceholderConfigurer.class, + propertySourcesPlaceholderPropertyValues); } } - static boolean registerBeanDefinition(BeanDefinitionRegistry registry, String beanName, - Class beanClass, Map extraPropertyValues) { + static boolean registerBeanDefinition( + BeanDefinitionRegistry registry, + String beanName, + Class beanClass, + Map extraPropertyValues) { if (registry.containsBeanDefinition(beanName)) { return false; } - BeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(beanClass).getBeanDefinition(); + BeanDefinition beanDefinition = + BeanDefinitionBuilder.genericBeanDefinition(beanClass).getBeanDefinition(); if (extraPropertyValues != null) { for (Map.Entry entry : extraPropertyValues.entrySet()) { beanDefinition.getPropertyValues().add(entry.getKey(), entry.getValue()); @@ -168,8 +186,8 @@ public interface DubboBeanUtils { return (beanNames != null && beanNames.length > 0); } - - static ReferenceAnnotationBeanPostProcessor getReferenceAnnotationBeanPostProcessor(AbstractBeanFactory beanFactory) { + static ReferenceAnnotationBeanPostProcessor getReferenceAnnotationBeanPostProcessor( + AbstractBeanFactory beanFactory) { for (BeanPostProcessor beanPostProcessor : beanFactory.getBeanPostProcessors()) { if (beanPostProcessor instanceof ReferenceAnnotationBeanPostProcessor) { return (ReferenceAnnotationBeanPostProcessor) beanPostProcessor; @@ -178,8 +196,10 @@ public interface DubboBeanUtils { return null; } - static ReferenceAnnotationBeanPostProcessor getReferenceAnnotationBeanPostProcessor(ApplicationContext applicationContext) { - return getReferenceAnnotationBeanPostProcessor((AbstractBeanFactory) applicationContext.getAutowireCapableBeanFactory()); + static ReferenceAnnotationBeanPostProcessor getReferenceAnnotationBeanPostProcessor( + ApplicationContext applicationContext) { + return getReferenceAnnotationBeanPostProcessor( + (AbstractBeanFactory) applicationContext.getAutowireCapableBeanFactory()); } static DubboSpringInitContext getInitializationContext(BeanFactory beanFactory) { @@ -213,5 +233,4 @@ public interface DubboBeanUtils { } return null; } - } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/EnvironmentUtils.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/EnvironmentUtils.java index c6bbde0c7c..38f9b7d646 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/EnvironmentUtils.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/EnvironmentUtils.java @@ -16,6 +16,12 @@ */ package org.apache.dubbo.config.spring.util; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.SortedMap; +import java.util.TreeMap; + import org.springframework.core.env.CompositePropertySource; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.EnumerablePropertySource; @@ -24,12 +30,6 @@ import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource; import org.springframework.util.ObjectUtils; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.SortedMap; -import java.util.TreeMap; - /** * The utilities class for {@link Environment} * @@ -81,15 +81,11 @@ public abstract class EnvironmentUtils { if (!properties.containsKey(propertyName)) { // put If absent properties.put(propertyName, propertySource.getProperty(propertyName)); } - } - } - } return properties; - } private static Map> doGetPropertySources(ConfigurableEnvironment environment) { @@ -101,11 +97,9 @@ public abstract class EnvironmentUtils { return map; } - private static void extract(String root, Map> map, - PropertySource source) { + private static void extract(String root, Map> map, PropertySource source) { if (source instanceof CompositePropertySource) { - for (PropertySource nest : ((CompositePropertySource) source) - .getPropertySources()) { + for (PropertySource nest : ((CompositePropertySource) source).getPropertySources()) { extract(source.getName() + ":", map, nest); } } else { @@ -128,9 +122,10 @@ public abstract class EnvironmentUtils { for (Map.Entry entry : properties.entrySet()) { String propertyName = entry.getKey(); - if (propertyName.startsWith(DUBBO_PREFIX + PROPERTY_NAME_SEPARATOR) - && entry.getValue() != null) { - dubboProperties.put(propertyName, environment.resolvePlaceholders(entry.getValue().toString())); + if (propertyName.startsWith(DUBBO_PREFIX + PROPERTY_NAME_SEPARATOR) && entry.getValue() != null) { + dubboProperties.put( + propertyName, + environment.resolvePlaceholders(entry.getValue().toString())); } } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/GenericBeanPostProcessorAdapter.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/GenericBeanPostProcessorAdapter.java index c7678f8a96..8defa85657 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/GenericBeanPostProcessorAdapter.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/GenericBeanPostProcessorAdapter.java @@ -16,13 +16,13 @@ */ package org.apache.dubbo.config.spring.util; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.util.ClassUtils; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; - /** * Generic {@link BeanPostProcessor} Adapter * @@ -78,7 +78,6 @@ public abstract class GenericBeanPostProcessorAdapter implements BeanPostProc processBeforeInitialization(bean, beanName); return bean; - } /** @@ -95,7 +94,6 @@ public abstract class GenericBeanPostProcessorAdapter implements BeanPostProc processAfterInitialization(bean, beanName); return bean; - } /** @@ -107,8 +105,7 @@ public abstract class GenericBeanPostProcessorAdapter implements BeanPostProc * @param beanName Bean Name * @throws BeansException in case of errors */ - protected void processBeforeInitialization(T bean, String beanName) throws BeansException { - } + protected void processBeforeInitialization(T bean, String beanName) throws BeansException {} /** * Process {@link T Bean} with name without return value after initialization, @@ -119,7 +116,5 @@ public abstract class GenericBeanPostProcessorAdapter implements BeanPostProc * @param beanName Bean Name * @throws BeansException in case of errors */ - protected void processAfterInitialization(T bean, String beanName) throws BeansException { - } - + protected void processAfterInitialization(T bean, String beanName) throws BeansException {} } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/LazyTargetInvocationHandler.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/LazyTargetInvocationHandler.java index 043c86a612..1b3ec0e0b6 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/LazyTargetInvocationHandler.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/LazyTargetInvocationHandler.java @@ -59,7 +59,7 @@ public class LazyTargetInvocationHandler implements InvocationHandler { } } } - throw new IllegalStateException("The proxied interface [" + method.getDeclaringClass() + - "] contains a method [" + method + "] that is not implemented by the proxy class [" + target.getClass() + "]"); + throw new IllegalStateException("The proxied interface [" + method.getDeclaringClass() + "] contains a method [" + + method + "] that is not implemented by the proxy class [" + target.getClass() + "]"); } } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/LockUtils.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/LockUtils.java index 7b469c5c55..b11b80b4a6 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/LockUtils.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/LockUtils.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.config.spring.util; +import java.lang.reflect.Method; + import org.springframework.beans.factory.support.DefaultSingletonBeanRegistry; import org.springframework.context.ApplicationContext; -import java.lang.reflect.Method; - public class LockUtils { private static final String DUBBO_SINGLETON_MUTEX_KEY = "DUBBO_SINGLETON_MUTEX"; @@ -29,7 +29,8 @@ public class LockUtils { * Get the mutex to lock the singleton in the specified {@link ApplicationContext} */ public static synchronized Object getSingletonMutex(ApplicationContext applicationContext) { - DefaultSingletonBeanRegistry autowireCapableBeanFactory = (DefaultSingletonBeanRegistry) applicationContext.getAutowireCapableBeanFactory(); + DefaultSingletonBeanRegistry autowireCapableBeanFactory = + (DefaultSingletonBeanRegistry) applicationContext.getAutowireCapableBeanFactory(); try { return autowireCapableBeanFactory.getSingletonMutex(); } catch (Throwable t1) { diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/PropertySourcesUtils.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/PropertySourcesUtils.java index e2f8145711..15e164b5ee 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/PropertySourcesUtils.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/PropertySourcesUtils.java @@ -16,6 +16,11 @@ */ package org.apache.dubbo.config.spring.util; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Properties; + import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.EnumerablePropertySource; import org.springframework.core.env.MutablePropertySources; @@ -24,11 +29,6 @@ import org.springframework.core.env.PropertySource; import org.springframework.core.env.PropertySources; import org.springframework.core.env.PropertySourcesPropertyResolver; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Properties; - import static java.util.Collections.unmodifiableMap; /** @@ -55,7 +55,6 @@ public abstract class PropertySourcesUtils { } return getSubProperties(mutablePropertySources, prefix); - } /** @@ -101,7 +100,8 @@ public abstract class PropertySourcesUtils { * @return Map * @see Properties */ - public static Map getSubProperties(PropertySources propertySources, PropertyResolver propertyResolver, String prefix) { + public static Map getSubProperties( + PropertySources propertySources, PropertyResolver propertyResolver, String prefix) { Map subProperties = new LinkedHashMap(); @@ -136,8 +136,9 @@ public abstract class PropertySourcesUtils { * @return non-null */ public static String[] getPropertyNames(PropertySource propertySource) { - String[] propertyNames = propertySource instanceof EnumerablePropertySource ? - ((EnumerablePropertySource) propertySource).getPropertyNames() : null; + String[] propertyNames = propertySource instanceof EnumerablePropertySource + ? ((EnumerablePropertySource) propertySource).getPropertyNames() + : null; if (propertyNames == null) { propertyNames = ObjectUtils.EMPTY_STRING_ARRAY; diff --git a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/SpringCompatUtils.java b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/SpringCompatUtils.java index b06784bbbf..9030634c24 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/SpringCompatUtils.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/SpringCompatUtils.java @@ -16,11 +16,16 @@ */ package org.apache.dubbo.config.spring.util; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor; import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor; import org.apache.dubbo.config.spring.context.DubboInfraBeanRegisterPostProcessor; + +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.springframework.beans.PropertyValue; import org.springframework.beans.PropertyValues; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; @@ -28,10 +33,6 @@ import org.springframework.beans.factory.config.TypedStringValue; import org.springframework.core.type.MethodMetadata; import org.springframework.core.type.StandardMethodMetadata; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; - /** * Spring Compatibility Utils for spring 3.x/4.x/5.x/6.x */ @@ -54,7 +55,7 @@ public class SpringCompatUtils { public static boolean isFactoryMethodMetadataEnabled() { if (factoryMethodMetadataEnabled == null) { try { - //check AnnotatedBeanDefinition.getFactoryMethodMetadata() since spring 4.1 + // check AnnotatedBeanDefinition.getFactoryMethodMetadata() since spring 4.1 AnnotatedBeanDefinition.class.getMethod("getFactoryMethodMetadata"); // check MethodMetadata.getReturnTypeName() since spring 4.2 @@ -131,23 +132,25 @@ public class SpringCompatUtils { return null; } - public static Class referenceAnnotationBeanPostProcessor(){ + public static Class referenceAnnotationBeanPostProcessor() { try { - return Class.forName("org.apache.dubbo.config.spring6.beans.factory.annotation.ReferenceAnnotationWithAotBeanPostProcessor"); + return Class.forName( + "org.apache.dubbo.config.spring6.beans.factory.annotation.ReferenceAnnotationWithAotBeanPostProcessor"); } catch (ClassNotFoundException e) { return ReferenceAnnotationBeanPostProcessor.class; } } - public static Class serviceAnnotationPostProcessor(){ + public static Class serviceAnnotationPostProcessor() { try { - return Class.forName("org.apache.dubbo.config.spring6.beans.factory.annotation.ServiceAnnotationWithAotPostProcessor"); + return Class.forName( + "org.apache.dubbo.config.spring6.beans.factory.annotation.ServiceAnnotationWithAotPostProcessor"); } catch (ClassNotFoundException e) { return ServiceAnnotationPostProcessor.class; } } - public static Class dubboInfraBeanRegisterPostProcessor(){ + public static Class dubboInfraBeanRegisterPostProcessor() { try { return Class.forName("org.apache.dubbo.config.spring6.context.DubboInfraBeanRegisterPostProcessor"); } catch (ClassNotFoundException e) { diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/AbstractRegistryService.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/AbstractRegistryService.java index 4a7e85410e..52fbbb2c2a 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/AbstractRegistryService.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/AbstractRegistryService.java @@ -49,7 +49,8 @@ public abstract class AbstractRegistryService implements RegistryService { // subscribed services // Map - private final ConcurrentMap> subscribed = new ConcurrentHashMap>(); + private final ConcurrentMap> subscribed = + new ConcurrentHashMap>(); // notified services // Map> @@ -57,7 +58,8 @@ public abstract class AbstractRegistryService implements RegistryService { // notification listeners for the subscribed services // Map> - private final ConcurrentMap> notifyListeners = new ConcurrentHashMap>(); + private final ConcurrentMap> notifyListeners = + new ConcurrentHashMap>(); @Override public void register(URL url) { @@ -163,7 +165,8 @@ public abstract class AbstractRegistryService implements RegistryService { if (listener == null) { return; } - List listeners = ConcurrentHashMapUtils.computeIfAbsent(notifyListeners, service, k -> new CopyOnWriteArrayList<>()); + List listeners = + ConcurrentHashMapUtils.computeIfAbsent(notifyListeners, service, k -> new CopyOnWriteArrayList<>()); if (!listeners.contains(listener)) { listeners.add(listener); } @@ -187,7 +190,13 @@ public abstract class AbstractRegistryService implements RegistryService { try { notify(service, urls, listener); } catch (Throwable t) { - logger.error(CONFIG_FAILED_NOTIFY_EVENT, "", "", "Failed to notify registry event, service: " + service + ", urls: " + urls + ", cause: " + t.getMessage(), t); + logger.error( + CONFIG_FAILED_NOTIFY_EVENT, + "", + "", + "Failed to notify registry event, service: " + service + ", urls: " + urls + ", cause: " + + t.getMessage(), + t); } } } @@ -202,8 +211,7 @@ public abstract class AbstractRegistryService implements RegistryService { } protected final void notify(String service, List urls) { - if (StringUtils.isEmpty(service) - || CollectionUtils.isEmpty(urls)) { + if (StringUtils.isEmpty(service) || CollectionUtils.isEmpty(urls)) { return; } doNotify(service, urls); @@ -236,5 +244,4 @@ public abstract class AbstractRegistryService implements RegistryService { public Map> getListeners() { return Collections.unmodifiableMap(notifyListeners); } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ConfigTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ConfigTest.java index 8eadd48674..cb2211d7b9 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ConfigTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ConfigTest.java @@ -52,6 +52,10 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.service.GenericService; +import java.util.Collection; +import java.util.List; +import java.util.Map; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -61,10 +65,6 @@ import org.springframework.beans.factory.BeanCreationException; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -import java.util.Collection; -import java.util.List; -import java.util.Map; - import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_BEAN; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; import static org.hamcrest.CoreMatchers.containsString; @@ -75,7 +75,6 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; - /** * ConfigTest */ @@ -95,14 +94,15 @@ class ConfigTest { DubboBootstrap.reset(); } - @Test @Disabled("waiting-to-fix") public void testSpringExtensionInject() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/spring-extension-inject.xml"); + ClassPathXmlApplicationContext ctx = + new ClassPathXmlApplicationContext(resourcePath + "/spring-extension-inject.xml"); try { ctx.start(); - MockFilter filter = (MockFilter) ExtensionLoader.getExtensionLoader(Filter.class).getExtension("mymock"); + MockFilter filter = (MockFilter) + ExtensionLoader.getExtensionLoader(Filter.class).getExtension("mymock"); assertNotNull(filter.getMockDao()); assertNotNull(filter.getProtocol()); assertNotNull(filter.getLoadBalance()); @@ -155,13 +155,13 @@ class ConfigTest { consumerBootstrap.stop(); } } - } @Test @SuppressWarnings("unchecked") public void testProviderNestedService() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/provider-nested-service.xml"); + ClassPathXmlApplicationContext ctx = + new ClassPathXmlApplicationContext(resourcePath + "/provider-nested-service.xml"); try { ctx.start(); ServiceConfig serviceConfig = (ServiceConfig) ctx.getBean("serviceConfig"); @@ -239,7 +239,8 @@ class ConfigTest { @Test @Disabled("waiting-to-fix") public void testMultiProtocolDefault() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/multi-protocol-default.xml"); + ClassPathXmlApplicationContext ctx = + new ClassPathXmlApplicationContext(resourcePath + "/multi-protocol-default.xml"); try { ctx.start(); DemoService demoService = refer("rmi://127.0.0.1:10991"); @@ -254,7 +255,8 @@ class ConfigTest { @Test @Disabled("waiting-to-fix") public void testMultiProtocolError() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/multi-protocol-error.xml"); + ClassPathXmlApplicationContext ctx = + new ClassPathXmlApplicationContext(resourcePath + "/multi-protocol-error.xml"); try { ctx.start(); ctx.stop(); @@ -275,13 +277,16 @@ class ConfigTest { public void testMultiProtocolRegister() { SimpleRegistryService registryService = new SimpleRegistryService(); Exporter exporter = SimpleRegistryExporter.export(4547, registryService); - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/multi-protocol-register.xml"); + ClassPathXmlApplicationContext ctx = + new ClassPathXmlApplicationContext(resourcePath + "/multi-protocol-register.xml"); try { ctx.start(); List urls = registryService.getRegistered().get("org.apache.dubbo.config.spring.api.DemoService"); assertNotNull(urls); assertEquals(1, urls.size()); - assertEquals("dubbo://" + NetUtils.getLocalHost() + ":20824/org.apache.dubbo.config.spring.api.DemoService", urls.get(0).toIdentityString()); + assertEquals( + "dubbo://" + NetUtils.getLocalHost() + ":20824/org.apache.dubbo.config.spring.api.DemoService", + urls.get(0).toIdentityString()); } finally { ctx.stop(); ctx.close(); @@ -304,7 +309,9 @@ class ConfigTest { List urls2 = registryService2.getRegistered().get("org.apache.dubbo.config.spring.api.DemoService"); assertNotNull(urls2); assertEquals(1, urls2.size()); - assertEquals("dubbo://" + NetUtils.getLocalHost() + ":20880/org.apache.dubbo.config.spring.api.DemoService", urls2.get(0).toIdentityString()); + assertEquals( + "dubbo://" + NetUtils.getLocalHost() + ":20880/org.apache.dubbo.config.spring.api.DemoService", + urls2.get(0).toIdentityString()); } finally { ctx.stop(); ctx.close(); @@ -330,7 +337,9 @@ class ConfigTest { } assertNotNull(urls); assertEquals(1, urls.size()); - assertEquals("dubbo://" + NetUtils.getLocalHost() + ":20888/org.apache.dubbo.config.spring.api.DemoService", urls.get(0).toIdentityString()); + assertEquals( + "dubbo://" + NetUtils.getLocalHost() + ":20888/org.apache.dubbo.config.spring.api.DemoService", + urls.get(0).toIdentityString()); } finally { ctx.stop(); ctx.close(); @@ -343,13 +352,16 @@ class ConfigTest { public void testDelayOnInitialized() throws Exception { SimpleRegistryService registryService = new SimpleRegistryService(); Exporter exporter = SimpleRegistryExporter.export(4548, registryService); - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/delay-on-initialized.xml"); + ClassPathXmlApplicationContext ctx = + new ClassPathXmlApplicationContext(resourcePath + "/delay-on-initialized.xml"); try { - //ctx.start(); + // ctx.start(); List urls = registryService.getRegistered().get("org.apache.dubbo.config.spring.api.DemoService"); assertNotNull(urls); assertEquals(1, urls.size()); - assertEquals("dubbo://" + NetUtils.getLocalHost() + ":20888/org.apache.dubbo.config.spring.api.DemoService", urls.get(0).toIdentityString()); + assertEquals( + "dubbo://" + NetUtils.getLocalHost() + ":20888/org.apache.dubbo.config.spring.api.DemoService", + urls.get(0).toIdentityString()); } finally { ctx.stop(); ctx.close(); @@ -371,32 +383,41 @@ class ConfigTest { @Disabled("waiting-to-fix") public void testAutowireAndAOP() throws Exception { ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext( - resourcePath + "/demo-provider.xml", - resourcePath + "/demo-provider-properties.xml"); + resourcePath + "/demo-provider.xml", resourcePath + "/demo-provider-properties.xml"); try { providerContext.start(); - ClassPathXmlApplicationContext byNameContext = new ClassPathXmlApplicationContext(resourcePath + "/aop-autowire-byname.xml"); + ClassPathXmlApplicationContext byNameContext = + new ClassPathXmlApplicationContext(resourcePath + "/aop-autowire-byname.xml"); try { byNameContext.start(); - DemoActionBySetter demoActionBySetter = (DemoActionBySetter) byNameContext.getBean("demoActionBySetter"); + DemoActionBySetter demoActionBySetter = + (DemoActionBySetter) byNameContext.getBean("demoActionBySetter"); assertNotNull(demoActionBySetter.getDemoService()); - assertEquals("aop:say:hello", demoActionBySetter.getDemoService().sayName("hello")); - DemoActionByAnnotation demoActionByAnnotation = (DemoActionByAnnotation) byNameContext.getBean("demoActionByAnnotation"); + assertEquals( + "aop:say:hello", demoActionBySetter.getDemoService().sayName("hello")); + DemoActionByAnnotation demoActionByAnnotation = + (DemoActionByAnnotation) byNameContext.getBean("demoActionByAnnotation"); assertNotNull(demoActionByAnnotation.getDemoService()); - assertEquals("aop:say:hello", demoActionByAnnotation.getDemoService().sayName("hello")); + assertEquals( + "aop:say:hello", demoActionByAnnotation.getDemoService().sayName("hello")); } finally { byNameContext.stop(); byNameContext.close(); } - ClassPathXmlApplicationContext byTypeContext = new ClassPathXmlApplicationContext(resourcePath + "/aop-autowire-bytype.xml"); + ClassPathXmlApplicationContext byTypeContext = + new ClassPathXmlApplicationContext(resourcePath + "/aop-autowire-bytype.xml"); try { byTypeContext.start(); - DemoActionBySetter demoActionBySetter = (DemoActionBySetter) byTypeContext.getBean("demoActionBySetter"); + DemoActionBySetter demoActionBySetter = + (DemoActionBySetter) byTypeContext.getBean("demoActionBySetter"); assertNotNull(demoActionBySetter.getDemoService()); - assertEquals("aop:say:hello", demoActionBySetter.getDemoService().sayName("hello")); - DemoActionByAnnotation demoActionByAnnotation = (DemoActionByAnnotation) byTypeContext.getBean("demoActionByAnnotation"); + assertEquals( + "aop:say:hello", demoActionBySetter.getDemoService().sayName("hello")); + DemoActionByAnnotation demoActionByAnnotation = + (DemoActionByAnnotation) byTypeContext.getBean("demoActionByAnnotation"); assertNotNull(demoActionByAnnotation.getDemoService()); - assertEquals("aop:say:hello", demoActionByAnnotation.getDemoService().sayName("hello")); + assertEquals( + "aop:say:hello", demoActionByAnnotation.getDemoService().sayName("hello")); } finally { byTypeContext.stop(); byTypeContext.close(); @@ -430,16 +451,16 @@ class ConfigTest { reference.setConsumer(consumer); reference.setRegistry(new RegistryConfig(RegistryConfig.NO_AVAILABLE)); reference.setInterface(DemoService.class); - reference.setUrl("dubbo://" + NetUtils.getLocalHost() + ":20880?" + DemoService.class.getName() + "?check=false"); - + reference.setUrl( + "dubbo://" + NetUtils.getLocalHost() + ":20880?" + DemoService.class.getName() + "?check=false"); try { DubboBootstrap.getInstance() - .application(application) - .provider(provider) - .service(service) - .reference(reference) - .start(); + .application(application) + .provider(provider) + .service(service) + .reference(reference) + .start(); List urls = service.getExportedUrls(); assertNotNull(urls); @@ -459,15 +480,14 @@ class ConfigTest { @Test void testInitReference() throws Exception { ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext( - resourcePath + "/demo-provider.xml", - resourcePath + "/demo-provider-properties.xml"); + resourcePath + "/demo-provider.xml", resourcePath + "/demo-provider-properties.xml"); try { providerContext.start(); // consumer app - ClassPathXmlApplicationContext consumerContext = new ClassPathXmlApplicationContext(resourcePath + "/init-reference.xml", - resourcePath + "/init-reference-properties.xml"); + ClassPathXmlApplicationContext consumerContext = new ClassPathXmlApplicationContext( + resourcePath + "/init-reference.xml", resourcePath + "/init-reference-properties.xml"); try { consumerContext.start(); @@ -483,7 +503,7 @@ class ConfigTest { Assertions.assertNotNull(referenceConfig.getParameters().get("connec.timeout")); Assertions.assertEquals("demo_tag", referenceConfig.getTag()); - //methods + // methods Assertions.assertEquals(1, referenceConfig.getMethods().size()); MethodConfig methodConfig = referenceConfig.getMethods().get(0); Assertions.assertEquals("sayName", methodConfig.getName()); @@ -494,7 +514,7 @@ class ConfigTest { Assertions.assertEquals("onReturn", methodConfig.getOnreturnMethod()); Assertions.assertEquals("onThrow", methodConfig.getOnthrowMethod()); - //method arguments + // method arguments Assertions.assertEquals(1, methodConfig.getArguments().size()); ArgumentConfig argumentConfig = methodConfig.getArguments().get(0); Assertions.assertEquals(0, argumentConfig.getIndex()); @@ -504,13 +524,14 @@ class ConfigTest { Assertions.assertEquals(1, methodConfig.getParameters().size()); Assertions.assertEquals("my-token", methodConfig.getParameters().get("access-token")); - // do call DemoService demoService = (DemoService) consumerContext.getBean("demoService"); assertEquals("say:world", demoService.sayName("world")); GenericService demoService2 = (GenericService) consumerContext.getBean("demoService2"); - assertEquals("say:world", demoService2.$invoke("sayName", new String[]{"java.lang.String"}, new Object[]{"world"})); + assertEquals( + "say:world", + demoService2.$invoke("sayName", new String[] {"java.lang.String"}, new Object[] {"world"})); } finally { consumerContext.stop(); @@ -526,7 +547,8 @@ class ConfigTest { @Test void test_noMethodInterface_methodsKeyHasValue() throws Exception { List urls = null; - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/demo-provider-no-methods-interface.xml"); + ClassPathXmlApplicationContext ctx = + new ClassPathXmlApplicationContext(resourcePath + "/demo-provider-no-methods-interface.xml"); try { ctx.start(); @@ -551,13 +573,14 @@ class ConfigTest { @Disabled("waiting-to-fix") @Test void test_RpcContext_getUrls() throws Exception { - ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext( - resourcePath + "/demo-provider-long-waiting.xml"); + ClassPathXmlApplicationContext providerContext = + new ClassPathXmlApplicationContext(resourcePath + "/demo-provider-long-waiting.xml"); try { providerContext.start(); - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/init-reference-getUrls.xml"); + ClassPathXmlApplicationContext ctx = + new ClassPathXmlApplicationContext(resourcePath + "/init-reference-getUrls.xml"); try { ctx.start(); DemoService demoService = (DemoService) ctx.getBean("demoService"); @@ -583,12 +606,13 @@ class ConfigTest { @Test @Disabled("waiting-to-fix") public void test_retrySettingFail() throws Exception { - ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(resourcePath + "/demo-provider-long-waiting.xml"); + ClassPathXmlApplicationContext providerContext = + new ClassPathXmlApplicationContext(resourcePath + "/demo-provider-long-waiting.xml"); try { providerContext.start(); - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( - resourcePath + "/init-reference-retry-false.xml"); + ClassPathXmlApplicationContext ctx = + new ClassPathXmlApplicationContext(resourcePath + "/init-reference-retry-false.xml"); try { ctx.start(); DemoService demoService = (DemoService) ctx.getBean("demoService"); @@ -615,11 +639,12 @@ class ConfigTest { @Test @Disabled("waiting-to-fix") public void test_returnSerializationFail() throws Exception { - ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(resourcePath + "/demo-provider-UnserializableBox.xml"); + ClassPathXmlApplicationContext providerContext = + new ClassPathXmlApplicationContext(resourcePath + "/demo-provider-UnserializableBox.xml"); try { providerContext.start(); - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/init-reference.xml", - resourcePath + "/init-reference-properties.xml"); + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( + resourcePath + "/init-reference.xml", resourcePath + "/init-reference-properties.xml"); try { ctx.start(); DemoService demoService = (DemoService) ctx.getBean("demoService"); @@ -642,7 +667,8 @@ class ConfigTest { @Test @Disabled("waiting-to-fix") public void testXmlOverrideProperties() throws Exception { - ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(resourcePath + "/xml-override-properties.xml"); + ClassPathXmlApplicationContext providerContext = + new ClassPathXmlApplicationContext(resourcePath + "/xml-override-properties.xml"); try { providerContext.start(); ApplicationConfig application = (ApplicationConfig) providerContext.getBean("application"); @@ -687,12 +713,12 @@ class ConfigTest { try { DubboBootstrap.getInstance() - .application(application) - .registry(registry) - .protocol(protocol) - .service(service) - .reference(reference) - .start(); + .application(application) + .registry(registry) + .protocol(protocol) + .service(service) + .reference(reference) + .start(); URL url = service.getExportedUrls().get(0); assertEquals("api-override-properties", url.getParameter("application")); @@ -711,7 +737,8 @@ class ConfigTest { SysProps.setProperty("dubbo.protocols.tri.port", ""); // empty config should be ignored SysProps.setProperty("dubbo.protocols.dubbo.port", "20812"); // override success SysProps.setProperty("dubbo.protocol.port", "20899"); // override fail - ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(resourcePath + "/override-protocol.xml"); + ClassPathXmlApplicationContext providerContext = + new ClassPathXmlApplicationContext(resourcePath + "/override-protocol.xml"); try { providerContext.start(); ConfigManager configManager = ApplicationModel.defaultModel().getApplicationConfigManager(); @@ -726,8 +753,8 @@ class ConfigTest { void testSystemPropertyOverrideMultiProtocol() throws Exception { SysProps.setProperty("dubbo.protocols.dubbo.port", "20814"); SysProps.setProperty("dubbo.protocols.tri.port", "10914"); - ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(resourcePath + - "/override-multi-protocol.xml"); + ClassPathXmlApplicationContext providerContext = + new ClassPathXmlApplicationContext(resourcePath + "/override-multi-protocol.xml"); try { providerContext.start(); ConfigManager configManager = ApplicationModel.defaultModel().getApplicationConfigManager(); @@ -751,10 +778,12 @@ class ConfigTest { SysProps.setProperty("dubbo.registry.address", "N/A"); SysProps.setProperty("dubbo.protocol.name", "dubbo"); SysProps.setProperty("dubbo.protocol.port", "20819"); - ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(resourcePath + "/system-properties-override-default.xml"); + ClassPathXmlApplicationContext providerContext = + new ClassPathXmlApplicationContext(resourcePath + "/system-properties-override-default.xml"); try { providerContext.start(); - ServiceConfig service = (ServiceConfig) providerContext.getBean("demoServiceConfig"); + ServiceConfig service = + (ServiceConfig) providerContext.getBean("demoServiceConfig"); assertEquals("sysover", service.getApplication().getName()); assertEquals("sysowner", service.getApplication().getOwner()); assertEquals("N/A", service.getRegistry().getAddress()); @@ -776,10 +805,12 @@ class ConfigTest { SysProps.setProperty("dubbo.protocol.name", "dubbo"); SysProps.setProperty("dubbo.protocol.port", "20819"); SysProps.setProperty("dubbo.service.register", "false"); - ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(resourcePath + "/system-properties-override.xml"); + ClassPathXmlApplicationContext providerContext = + new ClassPathXmlApplicationContext(resourcePath + "/system-properties-override.xml"); try { providerContext.start(); - ServiceConfig service = (ServiceConfig) providerContext.getBean("demoServiceConfig"); + ServiceConfig service = + (ServiceConfig) providerContext.getBean("demoServiceConfig"); URL url = service.getExportedUrls().get(0); assertEquals("sysover", url.getParameter("application")); assertEquals("sysowner", url.getParameter("owner")); @@ -824,8 +855,10 @@ class ConfigTest { // set default value of check assertEquals(false, reference.shouldCheck()); - ModuleConfigManager moduleConfigManager = ApplicationModel.defaultModel().getDefaultModule().getConfigManager(); - ConsumerConfig defaultConsumer = moduleConfigManager.getDefaultConsumer().get(); + ModuleConfigManager moduleConfigManager = + ApplicationModel.defaultModel().getDefaultModule().getConfigManager(); + ConsumerConfig defaultConsumer = + moduleConfigManager.getDefaultConsumer().get(); assertEquals(1234, defaultConsumer.getTimeout()); assertEquals(false, defaultConsumer.isCheck()); } finally { @@ -848,9 +881,7 @@ class ConfigTest { serviceConfig.setInterface(DemoService.class); serviceConfig.setRef(new DemoServiceImpl()); - DubboBootstrap.getInstance() - .service(serviceConfig) - .start(); + DubboBootstrap.getInstance().service(serviceConfig).start(); assertEquals("sysover", serviceConfig.getApplication().getName()); assertEquals("sysowner", serviceConfig.getApplication().getOwner()); @@ -984,11 +1015,13 @@ class ConfigTest { Exporter exporter = SimpleRegistryExporter.export(4548, registryService); try { SysProps.setProperty("provider.version", "1.2"); - ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(resourcePath + "/annotation-provider.xml"); + ClassPathXmlApplicationContext providerContext = + new ClassPathXmlApplicationContext(resourcePath + "/annotation-provider.xml"); try { providerContext.start(); - ClassPathXmlApplicationContext consumerContext = new ClassPathXmlApplicationContext(resourcePath + "/annotation-consumer.xml"); + ClassPathXmlApplicationContext consumerContext = + new ClassPathXmlApplicationContext(resourcePath + "/annotation-consumer.xml"); try { consumerContext.start(); AnnotationAction annotationAction = (AnnotationAction) consumerContext.getBean("annotationAction"); @@ -1029,7 +1062,6 @@ class ConfigTest { service.setRegistry(registry); service.setProtocol(protocol); - DubboBootstrap.getInstance() .application(application) .registry(registry) @@ -1075,14 +1107,15 @@ class ConfigTest { try { DubboBootstrap.getInstance() - .application(application) - .registry(registry) - .protocol(protocol) - .service(demoService) - .service(helloService) - .start(); + .application(application) + .registry(registry) + .protocol(protocol) + .service(demoService) + .service(helloService) + .start(); - assertEquals(demoService.getExportedUrls().get(0).getPort(), + assertEquals( + demoService.getExportedUrls().get(0).getPort(), helloService.getExportedUrls().get(0).getPort()); } finally { DubboBootstrap.getInstance().stop(); @@ -1106,10 +1139,10 @@ class ConfigTest { try { DubboBootstrap.getInstance() - .application(new ApplicationConfig("test-refer-generic-export")) - .service(sc) - .reference(ref) - .start(); + .application(new ApplicationConfig("test-refer-generic-export")) + .service(sc) + .reference(ref) + .start(); fail(); } catch (Exception e) { e.printStackTrace(); @@ -1128,9 +1161,9 @@ class ConfigTest { try { DubboBootstrap.getInstance() - .application(new ApplicationConfig("test")) - .service(service) - .start(); + .application(new ApplicationConfig("test")) + .service(service) + .start(); Collection collection = MockRegistryFactory.getCachedRegistry(); MockRegistry registry = (MockRegistry) collection.iterator().next(); @@ -1154,5 +1187,4 @@ class ConfigTest { ctx.close(); } } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ControllerServiceConfigTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ControllerServiceConfigTest.java index 6f059143a8..2d2de09b8d 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ControllerServiceConfigTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ControllerServiceConfigTest.java @@ -20,6 +20,7 @@ import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.spring.api.SpringControllerService; + import org.junit.jupiter.api.Test; public class ControllerServiceConfigTest { @@ -31,12 +32,10 @@ public class ControllerServiceConfigTest { ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("dubbo"); serviceServiceConfig.setApplication(applicationConfig); - serviceServiceConfig.setProtocol(new ProtocolConfig("rest",8080)); + serviceServiceConfig.setProtocol(new ProtocolConfig("rest", 8080)); serviceServiceConfig.setRef(new SpringControllerService()); serviceServiceConfig.setInterface(SpringControllerService.class.getName()); serviceServiceConfig.export(); serviceServiceConfig.unexport(); - - } } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/DubboStateListener.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/DubboStateListener.java index b2c33071a6..cb93ece362 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/DubboStateListener.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/DubboStateListener.java @@ -24,12 +24,12 @@ import org.springframework.context.ApplicationListener; public class DubboStateListener implements ApplicationListener { private DeployState state; - + @Override public void onApplicationEvent(DubboApplicationStateEvent event) { state = event.getState(); } - + public DeployState getState() { return state; } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/JavaConfigBeanTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/JavaConfigBeanTest.java index 769271248a..25f6f9523f 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/JavaConfigBeanTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/JavaConfigBeanTest.java @@ -33,6 +33,9 @@ import org.apache.dubbo.rpc.Constants; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; +import java.util.Collection; +import java.util.Map; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -41,9 +44,6 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import java.util.Collection; -import java.util.Map; - class JavaConfigBeanTest { private static final String MY_PROTOCOL_ID = "myProtocol"; @@ -91,8 +91,10 @@ class JavaConfigBeanTest { Assertions.assertEquals(MY_PROTOCOL_ID, protocolConfig.getId()); ApplicationModel applicationModel = consumerContext.getBean(ApplicationModel.class); - ModuleConfigManager moduleConfigManager = applicationModel.getDefaultModule().getConfigManager(); - ConsumerConfig consumerConfig = moduleConfigManager.getDefaultConsumer().get(); + ModuleConfigManager moduleConfigManager = + applicationModel.getDefaultModule().getConfigManager(); + ConsumerConfig consumerConfig = + moduleConfigManager.getDefaultConsumer().get(); Assertions.assertEquals(1000, consumerConfig.getTimeout()); Assertions.assertEquals("demo", consumerConfig.getGroup()); Assertions.assertEquals(false, consumerConfig.isCheck()); @@ -110,17 +112,15 @@ class JavaConfigBeanTest { Assertions.assertEquals(5, referenceConfig.getRetries()); DemoService referProxy = (DemoService) referenceConfig.get(); - Assertions.assertTrue( referProxy instanceof DemoService); + Assertions.assertTrue(referProxy instanceof DemoService); String result = referProxy.sayName("dubbo"); Assertions.assertEquals("say:dubbo", result); } finally { consumerContext.close(); } - } - @EnableDubbo(scanBasePackages = "org.apache.dubbo.config.spring.annotation.consumer") @Configuration static class TestConfiguration { @@ -166,7 +166,6 @@ class JavaConfigBeanTest { public ReferenceBean demoService() { return new ReferenceBean<>(); } - } @Configuration @@ -178,4 +177,4 @@ class JavaConfigBeanTest { return new DemoServiceImpl(); } } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ServiceBeanTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ServiceBeanTest.java index 804575eac4..3a7755847c 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ServiceBeanTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ServiceBeanTest.java @@ -49,7 +49,5 @@ class ServiceBeanTest { MatcherAssert.assertThat(beanService, not(nullValue())); } - abstract class TestService implements Service { - - } + abstract class TestService implements Service {} } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java index ab82523300..4c1a04fb8f 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java @@ -37,11 +37,13 @@ import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_STICKY_KEY; */ public class SimpleRegistryExporter { - private static final Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); + private static final Protocol protocol = + ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - private static final ProxyFactory PROXY_FACTORY = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + private static final ProxyFactory PROXY_FACTORY = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - public synchronized static Exporter exportIfAbsent(int port) { + public static synchronized Exporter exportIfAbsent(int port) { try { new ServerSocket(port).close(); return export(port); @@ -55,7 +57,9 @@ public class SimpleRegistryExporter { } public static Exporter export(int port, RegistryService registryService) { - return protocol.export(PROXY_FACTORY.getInvoker(registryService, RegistryService.class, + return protocol.export(PROXY_FACTORY.getInvoker( + registryService, + RegistryService.class, new URLBuilder(DUBBO_PROTOCOL, NetUtils.getLocalHost(), port, RegistryService.class.getName()) .setPath(RegistryService.class.getName()) .addParameter(INTERFACE_KEY, RegistryService.class.getName()) @@ -66,5 +70,4 @@ public class SimpleRegistryExporter { .addParameter("unsubscribe.1.callback", "false") .build())); } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryService.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryService.java index a8e8d74575..5d0f720fb5 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryService.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryService.java @@ -38,16 +38,19 @@ import java.util.concurrent.ConcurrentMap; */ public class SimpleRegistryService extends AbstractRegistryService { - private final static Logger logger = LoggerFactory.getLogger(SimpleRegistryService.class); - private final ConcurrentMap> remoteRegistered = new ConcurrentHashMap>(); - private final ConcurrentMap> remoteListeners = new ConcurrentHashMap>(); + private static final Logger logger = LoggerFactory.getLogger(SimpleRegistryService.class); + private final ConcurrentMap> remoteRegistered = + new ConcurrentHashMap>(); + private final ConcurrentMap> remoteListeners = + new ConcurrentHashMap>(); private List registries; @Override public void register(String service, URL url) { super.register(service, url); String client = RpcContext.getServiceContext().getRemoteAddressString(); - Map urls = ConcurrentHashMapUtils.computeIfAbsent(remoteRegistered, client, k -> new ConcurrentHashMap<>()); + Map urls = + ConcurrentHashMapUtils.computeIfAbsent(remoteRegistered, client, k -> new ConcurrentHashMap<>()); urls.put(service, url); notify(service, getRegistered().get(service)); } @@ -70,13 +73,15 @@ public class SimpleRegistryService extends AbstractRegistryService { logger.info("[subscribe] service: " + service + ",client:" + client); } List urls = getRegistered().get(service); - if ((RegistryService.class.getName() + ":0.0.0").equals(service) - && CollectionUtils.isEmpty(urls)) { - register(service, new ServiceConfigURL("dubbo", - NetUtils.getLocalHost(), - RpcContext.getServiceContext().getLocalPort(), - RegistryService.class.getName(), - url.getParameters())); + if ((RegistryService.class.getName() + ":0.0.0").equals(service) && CollectionUtils.isEmpty(urls)) { + register( + service, + new ServiceConfigURL( + "dubbo", + NetUtils.getLocalHost(), + RpcContext.getServiceContext().getLocalPort(), + RegistryService.class.getName(), + url.getParameters())); List rs = registries; if (rs != null && rs.size() > 0) { for (String registry : rs) { @@ -86,14 +91,13 @@ public class SimpleRegistryService extends AbstractRegistryService { } super.subscribe(service, url, listener); - Map listeners = ConcurrentHashMapUtils.computeIfAbsent(remoteListeners, client, k -> new ConcurrentHashMap<>()); + Map listeners = + ConcurrentHashMapUtils.computeIfAbsent(remoteListeners, client, k -> new ConcurrentHashMap<>()); listeners.put(service, listener); urls = getRegistered().get(service); if (urls != null && urls.size() > 0) { listener.notify(urls); } - - } @Override @@ -125,10 +129,15 @@ public class SimpleRegistryService extends AbstractRegistryService { if (listeners != null && listeners.size() > 0) { for (Map.Entry entry : listeners.entrySet()) { String service = entry.getKey(); - super.unsubscribe(service, new ServiceConfigURL("subscribe", - RpcContext.getServiceContext().getRemoteHost(), - RpcContext.getServiceContext().getRemotePort(), - RegistryService.class.getName(), getSubscribed(service)), entry.getValue()); + super.unsubscribe( + service, + new ServiceConfigURL( + "subscribe", + RpcContext.getServiceContext().getRemoteHost(), + RpcContext.getServiceContext().getRemotePort(), + RegistryService.class.getName(), + getSubscribed(service)), + entry.getValue()); } } } @@ -140,5 +149,4 @@ public class SimpleRegistryService extends AbstractRegistryService { public void setRegistries(List registries) { this.registries = registries; } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SysProps.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SysProps.java index 57ec18ab12..cb4b4d88e1 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SysProps.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SysProps.java @@ -41,5 +41,4 @@ public class SysProps { } reset(); } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/action/DemoActionByAnnotation.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/action/DemoActionByAnnotation.java index 1163b860ed..95022f3150 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/action/DemoActionByAnnotation.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/action/DemoActionByAnnotation.java @@ -31,5 +31,4 @@ public class DemoActionByAnnotation { public DemoService getDemoService() { return demoService; } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/action/DemoActionBySetter.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/action/DemoActionBySetter.java index 1e3d762d4f..e856cbc296 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/action/DemoActionBySetter.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/action/DemoActionBySetter.java @@ -32,5 +32,4 @@ public class DemoActionBySetter { public void setDemoService(DemoService demoService) { this.demoService = demoService; } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/action/DemoInterceptor.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/action/DemoInterceptor.java index a8f3faeec1..2933d92d8a 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/action/DemoInterceptor.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/action/DemoInterceptor.java @@ -27,5 +27,4 @@ public class DemoInterceptor implements MethodInterceptor { public Object invoke(MethodInvocation invocation) throws Throwable { return "aop:" + invocation.proceed(); } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/consumer/AnnotationAction.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/consumer/AnnotationAction.java index 580edda1d8..f1c044789b 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/consumer/AnnotationAction.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/consumer/AnnotationAction.java @@ -28,11 +28,12 @@ import org.springframework.stereotype.Controller; @Controller("annotationAction") public class AnnotationAction { - @Reference(version = "1.2", methods = {@Method(name = "sayName", timeout = 5000)}) + @Reference( + version = "1.2", + methods = {@Method(name = "sayName", timeout = 5000)}) private DemoService demoService; public String doSayName(String name) { return demoService.sayName(name); } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/merged/MergedReference.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/merged/MergedReference.java index 9d3407782d..c86649684e 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/merged/MergedReference.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/merged/MergedReference.java @@ -16,17 +16,16 @@ */ package org.apache.dubbo.config.spring.annotation.merged; - import org.apache.dubbo.config.annotation.Reference; -import org.springframework.core.annotation.AliasFor; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.springframework.core.annotation.AliasFor; + @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/merged/MergedService.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/merged/MergedService.java index cfe124362c..a46f062fb4 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/merged/MergedService.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/merged/MergedService.java @@ -16,17 +16,16 @@ */ package org.apache.dubbo.config.spring.annotation.merged; - import org.apache.dubbo.config.annotation.Service; -import org.springframework.core.annotation.AliasFor; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.springframework.core.annotation.AliasFor; + @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/provider/AnnotationServiceImpl.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/provider/AnnotationServiceImpl.java index c5b5ba20c1..17893c7f66 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/provider/AnnotationServiceImpl.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/provider/AnnotationServiceImpl.java @@ -33,5 +33,4 @@ public class AnnotationServiceImpl implements DemoService { public Box getBox() { return null; } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/Box.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/Box.java index ed168fc37a..9fc3119aa4 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/Box.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/Box.java @@ -19,5 +19,4 @@ package org.apache.dubbo.config.spring.api; public interface Box { String getName(); - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/DemoService.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/DemoService.java index 84fd939716..a0314e6f58 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/DemoService.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/DemoService.java @@ -24,5 +24,4 @@ public interface DemoService { String sayName(String name); Box getBox(); - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/HelloService.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/HelloService.java index 3cc5416096..d6e9fbcf64 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/HelloService.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/HelloService.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config.spring.api; public interface HelloService { diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/DubboConfigAliasPostProcessorTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/DubboConfigAliasPostProcessorTest.java index b8c610df35..2d5c74094c 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/DubboConfigAliasPostProcessorTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/DubboConfigAliasPostProcessorTest.java @@ -54,6 +54,5 @@ class DubboConfigAliasPostProcessorTest { applicationConfig.setId(APP_ID); return applicationConfig; } - } } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/MergedAnnotationTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/MergedAnnotationTest.java index 3a4f4886b6..15d9999b64 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/MergedAnnotationTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/MergedAnnotationTest.java @@ -22,13 +22,13 @@ import org.apache.dubbo.config.spring.annotation.merged.MergedReference; import org.apache.dubbo.config.spring.annotation.merged.MergedService; import org.apache.dubbo.config.spring.api.DemoService; +import java.lang.reflect.Field; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.util.ReflectionUtils; -import java.lang.reflect.Field; - class MergedAnnotationTest { @Test @@ -56,12 +56,10 @@ class MergedAnnotationTest { } @MergedService - public static class DemoServiceImpl1 { - } + public static class DemoServiceImpl1 {} @MergedService(group = "group", version = "2.0") - public static class DemoServiceImpl2 { - } + public static class DemoServiceImpl2 {} private static class TestBean1 { @MergedReference @@ -72,5 +70,4 @@ class MergedAnnotationTest { @MergedReference(group = "group", version = "2.0") private DemoService demoService; } - -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/MethodConfigCallbackTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/MethodConfigCallbackTest.java index 01b70a8dc4..907141f2c3 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/MethodConfigCallbackTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/MethodConfigCallbackTest.java @@ -43,15 +43,12 @@ import static org.awaitility.Awaitility.await; @ExtendWith(SpringExtension.class) @ContextConfiguration( - classes = { - ProviderConfiguration.class, - MethodConfigCallbackTest.class, - MethodConfigCallbackTest.MethodCallbackConfiguration.class - }) -@TestPropertySource(properties = { - "dubbo.protocol.port=-1", - "dubbo.registry.address=${zookeeper.connection.address}" -}) + classes = { + ProviderConfiguration.class, + MethodConfigCallbackTest.class, + MethodConfigCallbackTest.MethodCallbackConfiguration.class + }) +@TestPropertySource(properties = {"dubbo.protocol.port=-1", "dubbo.registry.address=${zookeeper.connection.address}"}) @EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) class MethodConfigCallbackTest { @@ -69,20 +66,32 @@ class MethodConfigCallbackTest { @Autowired private ConfigurableApplicationContext context; - @DubboReference(check = false, async = true, - injvm = false, // Currently, local call is not supported method callback cause by Injvm protocol is not supported ClusterFilter - methods = {@Method(name = "sayHello", - oninvoke = "methodCallback.oninvoke1", - onreturn = "methodCallback.onreturn1", - onthrow = "methodCallback.onthrow1")}) + @DubboReference( + check = false, + async = true, + injvm = false, // Currently, local call is not supported method callback cause by Injvm protocol is not + // supported ClusterFilter + methods = { + @Method( + name = "sayHello", + oninvoke = "methodCallback.oninvoke1", + onreturn = "methodCallback.onreturn1", + onthrow = "methodCallback.onthrow1") + }) private HelloService helloServiceMethodCallBack; - @DubboReference(check = false, async = true, - injvm = false, // Currently, local call is not supported method callback cause by Injvm protocol is not supported ClusterFilter - methods = {@Method(name = "sayHello", - oninvoke = "methodCallback.oninvoke2", - onreturn = "methodCallback.onreturn2", - onthrow = "methodCallback.onthrow2")}) + @DubboReference( + check = false, + async = true, + injvm = false, // Currently, local call is not supported method callback cause by Injvm protocol is not + // supported ClusterFilter + methods = { + @Method( + name = "sayHello", + oninvoke = "methodCallback.oninvoke2", + onreturn = "methodCallback.onreturn2", + onthrow = "methodCallback.onthrow2") + }) private HelloService helloServiceMethodCallBack2; @Test @@ -91,11 +100,12 @@ class MethodConfigCallbackTest { int callCnt = 2 * threadCnt; for (int i = 0; i < threadCnt; i++) { new Thread(() -> { - for (int j = 0; j < callCnt; j++) { - helloServiceMethodCallBack.sayHello("dubbo"); - helloServiceMethodCallBack2.sayHello("dubbo(2)"); - } - }).start(); + for (int j = 0; j < callCnt; j++) { + helloServiceMethodCallBack.sayHello("dubbo"); + helloServiceMethodCallBack2.sayHello("dubbo(2)"); + } + }) + .start(); } await().until(() -> MethodCallbackImpl.cnt.get() >= (2 * threadCnt * callCnt)); MethodCallback notify = (MethodCallback) context.getBean("methodCallback"); @@ -122,6 +132,5 @@ class MethodConfigCallbackTest { public MethodCallback methodCallback() { return new MethodCallbackImpl(); } - } } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ParameterConvertTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ParameterConvertTest.java index a5bf17bb7c..eb20030d43 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ParameterConvertTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ParameterConvertTest.java @@ -18,13 +18,13 @@ package org.apache.dubbo.config.spring.beans.factory.annotation; import org.apache.dubbo.config.spring.util.DubboAnnotationUtils; +import java.util.HashMap; +import java.util.Map; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.test.annotation.DirtiesContext; -import java.util.HashMap; -import java.util.Map; - /** * {@link DubboAnnotationUtils#convertParameters} Test */ @@ -45,22 +45,21 @@ class ParameterConvertTest { */ Map parametersMap = new HashMap<>(); parametersMap.put("a", "b"); - Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[]{"a", "b"})); - Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[]{" a ", " b "})); - Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[]{"a=b"})); - Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[]{"a:b"})); + Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[] {"a", "b"})); + Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[] {" a ", " b "})); + Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[] {"a=b"})); + Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[] {"a:b"})); parametersMap.put("c", "d"); - Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[]{"a=b", "c", "d"})); - Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[]{"a:b", "c=d"})); + Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[] {"a=b", "c", "d"})); + Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[] {"a:b", "c=d"})); parametersMap.clear(); parametersMap.put("a", "a:b"); - Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[]{"a", "a:b"})); + Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[] {"a", "a:b"})); parametersMap.clear(); parametersMap.put("a", "0,100"); - Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[]{"a", "0,100"})); - + Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[] {"a", "0,100"})); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java index a4fbcff02d..851ebf9a8b 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java @@ -30,6 +30,11 @@ import org.apache.dubbo.config.spring.reference.ReferenceBeanManager; import org.apache.dubbo.config.spring.util.DubboBeanUtils; import org.apache.dubbo.rpc.RpcContext; +import java.net.InetSocketAddress; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; @@ -51,11 +56,6 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.net.InetSocketAddress; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; /** @@ -67,16 +67,17 @@ import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER @ExtendWith(SpringExtension.class) @ContextConfiguration( classes = { - ServiceAnnotationTestConfiguration.class, - ReferenceAnnotationBeanPostProcessorTest.class, - ReferenceAnnotationBeanPostProcessorTest.MyConfiguration.class, - ReferenceAnnotationBeanPostProcessorTest.TestAspect.class + ServiceAnnotationTestConfiguration.class, + ReferenceAnnotationBeanPostProcessorTest.class, + ReferenceAnnotationBeanPostProcessorTest.MyConfiguration.class, + ReferenceAnnotationBeanPostProcessorTest.TestAspect.class }) @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) -@TestPropertySource(properties = { - "consumer.version = ${demo.service.version}", - "consumer.url = dubbo://127.0.0.1:12345?version=2.5.7", -}) +@TestPropertySource( + properties = { + "consumer.version = ${demo.service.version}", + "consumer.url = dubbo://127.0.0.1:12345?version=2.5.7", + }) @EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true) class ReferenceAnnotationBeanPostProcessorTest { @@ -98,14 +99,15 @@ class ReferenceAnnotationBeanPostProcessorTest { @Around("execution(* org.apache.dubbo.config.spring.context.annotation.provider.DemoServiceImpl.*(..))") public Object aroundDemoService(ProceedingJoinPoint pjp) throws Throwable { - return pjp.proceed() + AOP_SUFFIX + " from " + RpcContext.getContext().getLocalAddress(); + return pjp.proceed() + AOP_SUFFIX + " from " + + RpcContext.getContext().getLocalAddress(); } @Around("execution(* org.apache.dubbo.config.spring.context.annotation.provider.*HelloService*.*(..))") public Object aroundHelloService(ProceedingJoinPoint pjp) throws Throwable { - return pjp.proceed() + AOP_SUFFIX + " from " + RpcContext.getContext().getLocalAddress(); + return pjp.proceed() + AOP_SUFFIX + " from " + + RpcContext.getContext().getLocalAddress(); } - } @Autowired @@ -129,22 +131,25 @@ class ReferenceAnnotationBeanPostProcessorTest { private HelloService helloService2; // #7 ReferenceBean (Field Injection #5) - // The HelloService is the same as above service(#6 ReferenceBean (Field Injection #4)), helloService3 will be registered as an alias of helloService2 + // The HelloService is the same as above service(#6 ReferenceBean (Field Injection #4)), helloService3 will be + // registered as an alias of helloService2 @DubboReference(version = "2", url = "dubbo://127.0.0.1:12345?version=2", tag = "demo_tag") private HelloService helloService3; // #8 ReferenceBean (Method Injection #3) @DubboReference(version = "3", url = "dubbo://127.0.0.1:12345?version=2", tag = "demo_tag") public void setHelloService2(HelloService helloService2) { - // The helloService2 beanName is the same as above(#6 ReferenceBean (Field Injection #4)), and this will rename to helloService2#2 + // The helloService2 beanName is the same as above(#6 ReferenceBean (Field Injection #4)), and this will rename + // to helloService2#2 renamedHelloService2 = helloService2; } // #9 ReferenceBean (Method Injection #4) @DubboReference(version = "4", url = "dubbo://127.0.0.1:12345?version=2") - public void setHelloService3(DemoService helloService3){ + public void setHelloService3(DemoService helloService3) { // The helloService3 beanName is the same as above(#7 ReferenceBean (Field Injection #5) is an alias), - // The current beanName(helloService3) is not registered in the beanDefinitionMap, but it is already an alias. so this will rename to helloService3#2 + // The current beanName(helloService3) is not registered in the beanDefinitionMap, but it is already an alias. + // so this will rename to helloService3#2 this.renamedHelloService3 = helloService3; } @@ -172,7 +177,7 @@ class ReferenceAnnotationBeanPostProcessorTest { Assertions.assertNotNull(context.getBean("demoService")); Assertions.assertNotNull(context.getBean("demoServiceFromParent")); - String callSuffix = AOP_SUFFIX + " from "+ InetSocketAddress.createUnresolved(NetUtils.getLocalHost(), 12345); + String callSuffix = AOP_SUFFIX + " from " + InetSocketAddress.createUnresolved(NetUtils.getLocalHost(), 12345); String localCallSuffix = AOP_SUFFIX + " from " + InetSocketAddress.createUnresolved("127.0.0.1", 0); String directInvokeSuffix = AOP_SUFFIX + " from null"; @@ -186,14 +191,18 @@ class ReferenceAnnotationBeanPostProcessorTest { String demoServiceResult = "Hello,Mercy"; Assertions.assertEquals(demoServiceResult + directInvokeSuffix, demoServiceImpl.sayName("Mercy")); - Assertions.assertEquals(demoServiceResult + callSuffix, testBean.getDemoServiceFromAncestor().sayName("Mercy")); + Assertions.assertEquals( + demoServiceResult + callSuffix, + testBean.getDemoServiceFromAncestor().sayName("Mercy")); Assertions.assertEquals(demoServiceResult + callSuffix, testBean.myDemoService.sayName("Mercy")); - Assertions.assertEquals(demoServiceResult + callSuffix, testBean.getDemoService().sayName("Mercy")); - Assertions.assertEquals(demoServiceResult + callSuffix, testBean.getDemoServiceFromParent().sayName("Mercy")); + Assertions.assertEquals( + demoServiceResult + callSuffix, testBean.getDemoService().sayName("Mercy")); + Assertions.assertEquals( + demoServiceResult + callSuffix, + testBean.getDemoServiceFromParent().sayName("Mercy")); DemoService myDemoService = context.getBean("myDemoService", DemoService.class); Assertions.assertEquals(demoServiceResult + callSuffix, myDemoService.sayName("Mercy")); - } @Test @@ -207,11 +216,21 @@ class ReferenceAnnotationBeanPostProcessorTest { Assertions.assertEquals(5, referenceBeanMap.size()); Map checkingFieldNames = new HashMap<>(); - checkingFieldNames.put("private org.apache.dubbo.config.spring.api.HelloService org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessorTest$MyConfiguration.helloService", 0); - checkingFieldNames.put("private org.apache.dubbo.config.spring.api.HelloService org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessorTest.helloService", 0); - checkingFieldNames.put("private org.apache.dubbo.config.spring.api.HelloService org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessorTest.helloService2", 0); - checkingFieldNames.put("private org.apache.dubbo.config.spring.api.HelloService org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessorTest.helloService3", 0); - checkingFieldNames.put("private org.apache.dubbo.config.spring.api.DemoService org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessorTest$ParentBean.demoServiceFromParent", 0); + checkingFieldNames.put( + "private org.apache.dubbo.config.spring.api.HelloService org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessorTest$MyConfiguration.helloService", + 0); + checkingFieldNames.put( + "private org.apache.dubbo.config.spring.api.HelloService org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessorTest.helloService", + 0); + checkingFieldNames.put( + "private org.apache.dubbo.config.spring.api.HelloService org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessorTest.helloService2", + 0); + checkingFieldNames.put( + "private org.apache.dubbo.config.spring.api.HelloService org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessorTest.helloService3", + 0); + checkingFieldNames.put( + "private org.apache.dubbo.config.spring.api.DemoService org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessorTest$ParentBean.demoServiceFromParent", + 0); for (Map.Entry> entry : referenceBeanMap.entrySet()) { InjectionMetadata.InjectedElement injectedElement = entry.getKey(); @@ -264,8 +283,8 @@ class ReferenceAnnotationBeanPostProcessorTest { @Test void testReferenceBeansMethodAnnotation() { - ReferenceBeanManager referenceBeanManager = context.getBean(ReferenceBeanManager.BEAN_NAME, - ReferenceBeanManager.class); + ReferenceBeanManager referenceBeanManager = + context.getBean(ReferenceBeanManager.BEAN_NAME, ReferenceBeanManager.class); Collection referenceBeans = referenceBeanManager.getReferences(); @@ -285,17 +304,18 @@ class ReferenceAnnotationBeanPostProcessorTest { ReferenceBean demoServiceFromParentReferenceBean = referenceBeanManager.getById("demoServiceFromParent"); ReferenceBean demoServiceReferenceBean = referenceBeanManager.getById("demoService"); Assertions.assertEquals(demoServiceFromParentReferenceBean.getKey(), demoServiceReferenceBean.getKey()); - Assertions.assertEquals(demoServiceFromParentReferenceBean.getReferenceConfig(), demoServiceReferenceBean.getReferenceConfig()); + Assertions.assertEquals( + demoServiceFromParentReferenceBean.getReferenceConfig(), demoServiceReferenceBean.getReferenceConfig()); Assertions.assertSame(demoServiceFromParentReferenceBean, demoServiceReferenceBean); ReferenceBean helloService2Bean = referenceBeanManager.getById("helloService2"); Assertions.assertNotNull(helloService2Bean); Assertions.assertNotNull(helloService2Bean.getReferenceConfig()); - Assertions.assertEquals("demo_tag", helloService2Bean.getReferenceConfig().getTag()); + Assertions.assertEquals( + "demo_tag", helloService2Bean.getReferenceConfig().getTag()); Assertions.assertNotNull(referenceBeanManager.getById("myDemoService")); Assertions.assertNotNull(referenceBeanManager.getById("helloService2#2")); - } private static class AncestorBean { @@ -318,7 +338,6 @@ class ReferenceAnnotationBeanPostProcessorTest { public ApplicationContext getApplicationContext() { return applicationContext; } - } private static class ParentBean extends AncestorBean { @@ -330,7 +349,6 @@ class ReferenceAnnotationBeanPostProcessorTest { public DemoService getDemoServiceFromParent() { return demoServiceFromParent; } - } static class TestBean extends ParentBean { @@ -365,6 +383,5 @@ class ReferenceAnnotationBeanPostProcessorTest { public TestBean testBean() { return new TestBean(); } - } } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceCreatorTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceCreatorTest.java index 60533b195d..cf0e5c7375 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceCreatorTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceCreatorTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config.spring.beans.factory.annotation; - import org.apache.dubbo.config.ArgumentConfig; import org.apache.dubbo.config.ConsumerConfig; import org.apache.dubbo.config.MethodConfig; @@ -34,6 +33,11 @@ import org.apache.dubbo.config.spring.reference.ReferenceCreator; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import com.alibaba.spring.util.AnnotationUtils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -48,11 +52,6 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.lang.reflect.Field; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import static org.apache.dubbo.common.utils.CollectionUtils.ofSet; import static org.springframework.core.annotation.AnnotationUtils.findAnnotation; import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; @@ -77,37 +76,62 @@ class ReferenceCreatorTest { private static final String REGISTRY_CONFIG_ID = "myregistry"; @DubboReference( - //interfaceClass = HelloService.class, - version = "1.0.0", group = "TEST_GROUP", url = "dubbo://localhost:12345", - client = "client", generic = false, injvm = false, - check = false, init = false, lazy = true, - stubevent = true, reconnect = "reconnect", sticky = true, - proxy = "javassist", stub = "org.apache.dubbo.config.spring.api.HelloService", cluster = "failover", - connections = 3, callbacks = 1, onconnect = "onconnect", ondisconnect = "ondisconnect", - owner = "owner", layer = "layer", retries = 1, - loadbalance = "random", async = true, actives = 3, - sent = true, mock = "mock", validation = "validation", - timeout = 3, cache = "cache", filter = {"echo", "generic", "accesslog"}, - listener = {"deprecated"}, parameters = {"n1=v1 ", "n2 = v2 ", " n3 = v3 "}, - application = "application", - module = MODULE_CONFIG_ID, consumer = CONSUMER_CONFIG_ID, monitor = MONITOR_CONFIG_ID, registry = {REGISTRY_CONFIG_ID}, - // @since 2.7.3 - id = "reference", - // @since 2.7.8 - services = {"service1", "service2", "service3", "service2", "service1"}, - providedBy = {"service1", "service2", "service3"}, - methods = @Method(name = "sayHello", - isReturn = false, - loadbalance = "loadbalance", - oninvoke = "notifyService.onInvoke", - onreturn = "notifyService.onReturn", - onthrow = "notifyService.onThrow", - timeout = 1000, - retries = 2, - parameters = {"a", "1", "b", "2"}, - arguments = @Argument(index = 0, callback = true) - ) - ) + // interfaceClass = HelloService.class, + version = "1.0.0", + group = "TEST_GROUP", + url = "dubbo://localhost:12345", + client = "client", + generic = false, + injvm = false, + check = false, + init = false, + lazy = true, + stubevent = true, + reconnect = "reconnect", + sticky = true, + proxy = "javassist", + stub = "org.apache.dubbo.config.spring.api.HelloService", + cluster = "failover", + connections = 3, + callbacks = 1, + onconnect = "onconnect", + ondisconnect = "ondisconnect", + owner = "owner", + layer = "layer", + retries = 1, + loadbalance = "random", + async = true, + actives = 3, + sent = true, + mock = "mock", + validation = "validation", + timeout = 3, + cache = "cache", + filter = {"echo", "generic", "accesslog"}, + listener = {"deprecated"}, + parameters = {"n1=v1 ", "n2 = v2 ", " n3 = v3 "}, + application = "application", + module = MODULE_CONFIG_ID, + consumer = CONSUMER_CONFIG_ID, + monitor = MONITOR_CONFIG_ID, + registry = {REGISTRY_CONFIG_ID}, + // @since 2.7.3 + id = "reference", + // @since 2.7.8 + services = {"service1", "service2", "service3", "service2", "service1"}, + providedBy = {"service1", "service2", "service3"}, + methods = + @Method( + name = "sayHello", + isReturn = false, + loadbalance = "loadbalance", + oninvoke = "notifyService.onInvoke", + onreturn = "notifyService.onReturn", + onthrow = "notifyService.onThrow", + timeout = 1000, + retries = 2, + parameters = {"a", "1", "b", "2"}, + arguments = @Argument(index = 0, callback = true))) private HelloService helloService; @Autowired @@ -129,8 +153,8 @@ class ReferenceCreatorTest { // filter default value AnnotationAttributes attributes = AnnotationUtils.getAnnotationAttributes(reference, true); ReferenceConfig referenceBean = ReferenceCreator.create(attributes, context) - .defaultInterfaceClass(helloServiceField.getType()) - .build(); + .defaultInterfaceClass(helloServiceField.getType()) + .build(); Assertions.assertEquals(HelloService.class, referenceBean.getInterfaceClass()); Assertions.assertEquals("org.apache.dubbo.config.spring.api.HelloService", referenceBean.getInterface()); Assertions.assertEquals("1.0.0", referenceBean.getVersion()); @@ -213,7 +237,6 @@ class ReferenceCreatorTest { Assertions.assertNotNull(referenceBean.getMonitor()); } - @Configuration public static class ConsumerConfiguration { @@ -241,7 +264,5 @@ class ReferenceCreatorTest { public ModuleConfig moduleConfig() { return new ModuleConfig(); } - } - -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessorTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessorTest.java index 52980c7f65..9c51b1f74a 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessorTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessorTest.java @@ -22,6 +22,8 @@ import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; +import java.util.Map; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -34,8 +36,6 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.util.Map; - import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; /** @@ -46,14 +46,15 @@ import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER @ExtendWith(SpringExtension.class) @ContextConfiguration( classes = { - ServiceAnnotationTestConfiguration.class, - ServiceAnnotationPostProcessorTest.class, - ServiceAnnotationPostProcessorTest.DuplicatedScanConfig.class + ServiceAnnotationTestConfiguration.class, + ServiceAnnotationPostProcessorTest.class, + ServiceAnnotationPostProcessorTest.DuplicatedScanConfig.class }) @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) -@TestPropertySource(properties = { - "provider.package = org.apache.dubbo.config.spring.context.annotation.provider", -}) +@TestPropertySource( + properties = { + "provider.package = org.apache.dubbo.config.spring.context.annotation.provider", + }) @EnableDubbo(scanBasePackages = "${provider.package}") class ServiceAnnotationPostProcessorTest { @@ -85,7 +86,6 @@ class ServiceAnnotationPostProcessorTest { beanFactory.getBeansOfType(ServiceAnnotationPostProcessor.class); Assertions.assertEquals(2, beanPostProcessorsMap.size()); - } @Test @@ -95,15 +95,12 @@ class ServiceAnnotationPostProcessorTest { Assertions.assertEquals(3, serviceBeansMap.size()); - ServiceBean demoServiceBean = serviceBeansMap.get("ServiceBean:org.apache.dubbo.config.spring.api.DemoService:2.5.7:"); + ServiceBean demoServiceBean = + serviceBeansMap.get("ServiceBean:org.apache.dubbo.config.spring.api.DemoService:2.5.7:"); Assertions.assertNotNull(demoServiceBean.getMethods()); - } @DubboComponentScan({"org.apache.dubbo.config.spring.context.annotation", "${provider.package}"}) - static class DuplicatedScanConfig { - - } - -} \ No newline at end of file + static class DuplicatedScanConfig {} +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationTestConfiguration.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationTestConfiguration.java index 59f1385a13..358bda2dc6 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationTestConfiguration.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationTestConfiguration.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config.spring.beans.factory.annotation; - import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.RegistryConfig; @@ -76,7 +75,7 @@ public class ServiceAnnotationTestConfiguration { * * @return {@link ProtocolConfig} Bean */ - @Bean//("dubbo") + @Bean // ("dubbo") public ProtocolConfig protocolConfig() { ProtocolConfig protocolConfig = new ProtocolConfig(); protocolConfig.setName("dubbo"); @@ -95,15 +94,10 @@ public class ServiceAnnotationTestConfiguration { } @Override - public void commit(TransactionStatus status) throws TransactionException { - - } + public void commit(TransactionStatus status) throws TransactionException {} @Override - public void rollback(TransactionStatus status) throws TransactionException { - - } + public void rollback(TransactionStatus status) throws TransactionException {} }; } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilderTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilderTest.java index 7f9cf28bb0..43093c43a8 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilderTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilderTest.java @@ -36,12 +36,22 @@ import static org.apache.dubbo.config.spring.beans.factory.annotation.ServiceBea * @see ServiceBeanNameBuilder * @since 2.6.6 */ -@Service(interfaceClass = DemoService.class, group = GROUP, version = VERSION, - application = "application", module = "module", registry = {"1", "2", "3"}) +@Service( + interfaceClass = DemoService.class, + group = GROUP, + version = VERSION, + application = "application", + module = "module", + registry = {"1", "2", "3"}) class ServiceBeanNameBuilderTest { - @Reference(interfaceClass = DemoService.class, group = "DUBBO", version = "${dubbo.version}", - application = "application", module = "module", registry = {"1", "2", "3"}) + @Reference( + interfaceClass = DemoService.class, + group = "DUBBO", + version = "${dubbo.version}", + application = "application", + module = "module", + registry = {"1", "2", "3"}) static final Class INTERFACE_CLASS = DemoService.class; static final String GROUP = "DUBBO"; @@ -60,16 +70,17 @@ class ServiceBeanNameBuilderTest { void testServiceAnnotation() { Service service = AnnotationUtils.getAnnotation(ServiceBeanNameBuilderTest.class, Service.class); ServiceBeanNameBuilder builder = ServiceBeanNameBuilder.create(service, INTERFACE_CLASS, environment); - Assertions.assertEquals("ServiceBean:org.apache.dubbo.config.spring.api.DemoService:1.0.0:DUBBO", - builder.build()); + Assertions.assertEquals( + "ServiceBean:org.apache.dubbo.config.spring.api.DemoService:1.0.0:DUBBO", builder.build()); } @Test void testReferenceAnnotation() { - Reference reference = AnnotationUtils.getAnnotation(ReflectionUtils.findField(ServiceBeanNameBuilderTest.class, "INTERFACE_CLASS"), Reference.class); + Reference reference = AnnotationUtils.getAnnotation( + ReflectionUtils.findField(ServiceBeanNameBuilderTest.class, "INTERFACE_CLASS"), Reference.class); ServiceBeanNameBuilder builder = ServiceBeanNameBuilder.create(reference, INTERFACE_CLASS, environment); - Assertions.assertEquals("ServiceBean:org.apache.dubbo.config.spring.api.DemoService:1.0.0:DUBBO", - builder.build()); + Assertions.assertEquals( + "ServiceBean:org.apache.dubbo.config.spring.api.DemoService:1.0.0:DUBBO", builder.build()); } @Test @@ -82,4 +93,4 @@ class ServiceBeanNameBuilderTest { Assertions.assertNotEquals(vBeanName, gBeanName); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/config/DubboConfigDefaultPropertyValueBeanPostProcessorTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/config/DubboConfigDefaultPropertyValueBeanPostProcessorTest.java index cdd05ff839..ddb3af0d7d 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/config/DubboConfigDefaultPropertyValueBeanPostProcessorTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/config/DubboConfigDefaultPropertyValueBeanPostProcessorTest.java @@ -24,12 +24,12 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; - class DubboConfigDefaultPropertyValueBeanPostProcessorTest { @Test void test() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ProviderConfiguration.class); + AnnotationConfigApplicationContext context = + new AnnotationConfigApplicationContext(ProviderConfiguration.class); try { context.start(); ApplicationConfig applicationConfig = context.getBean(ApplicationConfig.class); @@ -41,5 +41,4 @@ class DubboConfigDefaultPropertyValueBeanPostProcessorTest { context.close(); } } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/config/MultipleServicesWithMethodConfigsTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/config/MultipleServicesWithMethodConfigsTest.java index b9caff8a84..d78568bd9c 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/config/MultipleServicesWithMethodConfigsTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/config/MultipleServicesWithMethodConfigsTest.java @@ -19,6 +19,8 @@ package org.apache.dubbo.config.spring.beans.factory.config; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.ServiceBean; +import java.util.Map; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -30,8 +32,6 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.util.Map; - import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; @ExtendWith(SpringExtension.class) @@ -57,4 +57,3 @@ class MultipleServicesWithMethodConfigsTest { } } } - diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/config/YamlPropertySourceFactory.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/config/YamlPropertySourceFactory.java index 225bcd1463..5fb91df029 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/config/YamlPropertySourceFactory.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/config/YamlPropertySourceFactory.java @@ -16,6 +16,13 @@ */ package org.apache.dubbo.config.spring.beans.factory.config; +import java.io.IOException; +import java.util.AbstractMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + import org.springframework.beans.factory.config.YamlProcessor; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.PropertySource; @@ -31,13 +38,6 @@ import org.yaml.snakeyaml.parser.ParserException; import org.yaml.snakeyaml.representer.Representer; import org.yaml.snakeyaml.resolver.Resolver; -import java.io.IOException; -import java.util.AbstractMap; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; - /** * YAML {@link PropertySourceFactory} implementation, some source code is copied Spring Boot * org.springframework.boot.env.YamlPropertySourceLoader , see {@link #createYaml()} and {@link #process()} @@ -54,46 +54,51 @@ public class YamlPropertySourceFactory extends YamlProcessor implements Property @Override protected Yaml createYaml() { - return new Yaml(new Constructor(new LoaderOptions()) { - @Override - protected Map constructMapping(MappingNode node) { - try { - return super.constructMapping(node); - } catch (IllegalStateException ex) { - throw new ParserException("while parsing MappingNode", - node.getStartMark(), ex.getMessage(), node.getEndMark()); - } - } - - @Override - protected Map createDefaultMap(int initSize) { - final Map delegate = super.createDefaultMap(initSize); - return new AbstractMap() { + return new Yaml( + new Constructor(new LoaderOptions()) { @Override - public Object put(Object key, Object value) { - if (delegate.containsKey(key)) { - throw new IllegalStateException("Duplicate key: " + key); + protected Map constructMapping(MappingNode node) { + try { + return super.constructMapping(node); + } catch (IllegalStateException ex) { + throw new ParserException( + "while parsing MappingNode", + node.getStartMark(), + ex.getMessage(), + node.getEndMark()); } - return delegate.put(key, value); } @Override - public Set> entrySet() { - return delegate.entrySet(); + protected Map createDefaultMap(int initSize) { + final Map delegate = super.createDefaultMap(initSize); + return new AbstractMap() { + @Override + public Object put(Object key, Object value) { + if (delegate.containsKey(key)) { + throw new IllegalStateException("Duplicate key: " + key); + } + return delegate.put(key, value); + } + + @Override + public Set> entrySet() { + return delegate.entrySet(); + } + }; } - }; - } - }, new Representer(new DumperOptions()), - new DumperOptions(), new Resolver() { - @Override - public void addImplicitResolver(Tag tag, Pattern regexp, - String first) { - if (tag == Tag.TIMESTAMP) { - return; - } - super.addImplicitResolver(tag, regexp, first); - } - }); + }, + new Representer(new DumperOptions()), + new DumperOptions(), + new Resolver() { + @Override + public void addImplicitResolver(Tag tag, Pattern regexp, String first) { + if (tag == Tag.TIMESTAMP) { + return; + } + super.addImplicitResolver(tag, regexp, first); + } + }); } /** diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/config/YamlPropertySourceFactoryTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/config/YamlPropertySourceFactoryTest.java index a0f6b9eace..a951db0a11 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/config/YamlPropertySourceFactoryTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/config/YamlPropertySourceFactoryTest.java @@ -36,7 +36,10 @@ import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER * @since 2.6.5 */ @ExtendWith(SpringExtension.class) -@PropertySource(name = "yaml-source", value = {"classpath:/META-INF/dubbo.yml"}, factory = YamlPropertySourceFactory.class) +@PropertySource( + name = "yaml-source", + value = {"classpath:/META-INF/dubbo.yml"}, + factory = YamlPropertySourceFactory.class) @Configuration @ContextConfiguration(classes = YamlPropertySourceFactoryTest.class) @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) @@ -72,4 +75,4 @@ class YamlPropertySourceFactoryTest { Assertions.assertEquals(threads, environment.getProperty("dubbo.consumer.threads", Integer.class)); Assertions.assertEquals(queues, environment.getProperty("dubbo.consumer.queues", Integer.class)); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional1/XmlReferenceBeanConditionalTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional1/XmlReferenceBeanConditionalTest.java index 468d1e0fd5..ca357c592f 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional1/XmlReferenceBeanConditionalTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional1/XmlReferenceBeanConditionalTest.java @@ -19,6 +19,8 @@ package org.apache.dubbo.config.spring.boot.conditional1; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.api.HelloService; +import java.util.Map; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -32,30 +34,23 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.core.annotation.Order; -import java.util.Map; - /** * issue: https://github.com/apache/dubbo-spring-boot-project/issues/779 */ @SpringBootTest( - properties = { - "dubbo.registry.address=N/A" - }, - classes = { - XmlReferenceBeanConditionalTest.class - } -) + properties = {"dubbo.registry.address=N/A"}, + classes = {XmlReferenceBeanConditionalTest.class}) @Configuration -//@ComponentScan +// @ComponentScan class XmlReferenceBeanConditionalTest { @BeforeAll - public static void beforeAll(){ + public static void beforeAll() { DubboBootstrap.reset(); } @AfterAll - public static void afterAll(){ + public static void afterAll() { DubboBootstrap.reset(); } @@ -74,18 +69,16 @@ class XmlReferenceBeanConditionalTest { Assertions.assertNull(helloServiceMap.get("myHelloService")); } - @Order(Integer.MAX_VALUE-2) + @Order(Integer.MAX_VALUE - 2) @Configuration @ImportResource("classpath:/org/apache/dubbo/config/spring/boot/conditional1/consumer/dubbo-consumer.xml") - public static class ConsumerConfiguration { + public static class ConsumerConfiguration {} - } - - @Order(Integer.MAX_VALUE-1) + @Order(Integer.MAX_VALUE - 1) @Configuration public static class ConsumerConfiguration2 { - //TEST Conditional, this bean should be ignored + // TEST Conditional, this bean should be ignored @Bean @ConditionalOnMissingBean public HelloService myHelloService() { @@ -97,4 +90,4 @@ class XmlReferenceBeanConditionalTest { }; } } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional2/JavaConfigAnnotationReferenceBeanConditionalTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional2/JavaConfigAnnotationReferenceBeanConditionalTest.java index 04adaba2dc..bea403d9c9 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional2/JavaConfigAnnotationReferenceBeanConditionalTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional2/JavaConfigAnnotationReferenceBeanConditionalTest.java @@ -23,6 +23,8 @@ import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.config.spring.context.annotation.provider.HelloServiceImpl; +import java.util.Map; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -35,33 +37,24 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; -import java.util.Map; - /** * issue: https://github.com/apache/dubbo-spring-boot-project/issues/779 */ @SpringBootTest( - properties = { - "dubbo.application.name=consumer-app", - "dubbo.registry.address=N/A", - "myapp.group=demo" - }, - classes = { - JavaConfigAnnotationReferenceBeanConditionalTest.class - } -) + properties = {"dubbo.application.name=consumer-app", "dubbo.registry.address=N/A", "myapp.group=demo"}, + classes = {JavaConfigAnnotationReferenceBeanConditionalTest.class}) @Configuration -//@ComponentScan +// @ComponentScan @EnableDubbo class JavaConfigAnnotationReferenceBeanConditionalTest { @BeforeAll - public static void beforeAll(){ + public static void beforeAll() { DubboBootstrap.reset(); } @AfterAll - public static void afterAll(){ + public static void afterAll() { DubboBootstrap.reset(); } @@ -80,7 +73,7 @@ class JavaConfigAnnotationReferenceBeanConditionalTest { Assertions.assertNull(helloServiceMap.get("myHelloService")); } - @Order(Integer.MAX_VALUE-2) + @Order(Integer.MAX_VALUE - 2) @Configuration public static class AnnotationBeanConfiguration { @@ -89,20 +82,17 @@ class JavaConfigAnnotationReferenceBeanConditionalTest { public ReferenceBean helloService() { return new ReferenceBean(); } - } - - @Order(Integer.MAX_VALUE-1) + @Order(Integer.MAX_VALUE - 1) @Configuration public static class ConditionalBeanConfiguration { - //TEST Conditional, this bean should be ignored + // TEST Conditional, this bean should be ignored @Bean @ConditionalOnMissingBean public HelloService myHelloService() { return new HelloServiceImpl(); } } - -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional3/JavaConfigRawReferenceBeanConditionalTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional3/JavaConfigRawReferenceBeanConditionalTest.java index d3fa5204e7..2738b55748 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional3/JavaConfigRawReferenceBeanConditionalTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional3/JavaConfigRawReferenceBeanConditionalTest.java @@ -23,6 +23,8 @@ import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.config.spring.context.annotation.provider.HelloServiceImpl; import org.apache.dubbo.config.spring.reference.ReferenceBeanBuilder; +import java.util.Map; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -35,33 +37,24 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; -import java.util.Map; - /** * issue: https://github.com/apache/dubbo-spring-boot-project/issues/779 */ @SpringBootTest( - properties = { - "dubbo.application.name=consumer-app", - "dubbo.registry.address=N/A", - "myapp.group=demo" - }, - classes = { - JavaConfigRawReferenceBeanConditionalTest.class - } -) + properties = {"dubbo.application.name=consumer-app", "dubbo.registry.address=N/A", "myapp.group=demo"}, + classes = {JavaConfigRawReferenceBeanConditionalTest.class}) @Configuration -//@ComponentScan +// @ComponentScan @EnableDubbo class JavaConfigRawReferenceBeanConditionalTest { @BeforeAll - public static void beforeAll(){ + public static void beforeAll() { DubboBootstrap.reset(); } @AfterAll - public static void afterAll(){ + public static void afterAll() { DubboBootstrap.reset(); } @@ -80,7 +73,7 @@ class JavaConfigRawReferenceBeanConditionalTest { Assertions.assertNull(helloServiceMap.get("myHelloService")); } - @Order(Integer.MAX_VALUE-2) + @Order(Integer.MAX_VALUE - 2) @Configuration public static class RawReferenceBeanConfiguration { @@ -91,20 +84,17 @@ class JavaConfigRawReferenceBeanConditionalTest { .setInit(false) .build(); } - } - - @Order(Integer.MAX_VALUE-1) + @Order(Integer.MAX_VALUE - 1) @Configuration public static class ConditionalBeanConfiguration { - //TEST Conditional, this bean should be ignored + // TEST Conditional, this bean should be ignored @Bean @ConditionalOnMissingBean public HelloService myHelloService() { return new HelloServiceImpl(); } } - -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional4/JavaConfigReferenceBeanConditionalTest4.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional4/JavaConfigReferenceBeanConditionalTest4.java index 3e01fe0722..4ebe99915b 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional4/JavaConfigReferenceBeanConditionalTest4.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional4/JavaConfigReferenceBeanConditionalTest4.java @@ -23,6 +23,8 @@ import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.config.spring.context.annotation.provider.HelloServiceImpl; +import java.util.Map; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -35,33 +37,24 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; -import java.util.Map; - /** * issue: https://github.com/apache/dubbo-spring-boot-project/issues/779 */ @SpringBootTest( - properties = { - "dubbo.application.name=consumer-app", - "dubbo.registry.address=N/A", - "myapp.group=demo" - }, - classes = { - JavaConfigReferenceBeanConditionalTest4.class - } -) + properties = {"dubbo.application.name=consumer-app", "dubbo.registry.address=N/A", "myapp.group=demo"}, + classes = {JavaConfigReferenceBeanConditionalTest4.class}) @Configuration -//@ComponentScan +// @ComponentScan @EnableDubbo public class JavaConfigReferenceBeanConditionalTest4 { @BeforeAll - public static void beforeAll(){ + public static void beforeAll() { DubboBootstrap.reset(); } @AfterAll - public static void afterAll(){ + public static void afterAll() { DubboBootstrap.reset(); } @@ -79,10 +72,11 @@ public class JavaConfigReferenceBeanConditionalTest4 { Assertions.assertNull(helloServiceMap.get("helloService")); HelloService helloService = helloServiceMap.get("helloServiceImpl"); Assertions.assertNotNull(helloService); - Assertions.assertTrue(helloService instanceof HelloServiceImpl, "Not expected bean type: "+helloService.getClass()); + Assertions.assertTrue( + helloService instanceof HelloServiceImpl, "Not expected bean type: " + helloService.getClass()); } - @Order(Integer.MAX_VALUE-2) + @Order(Integer.MAX_VALUE - 2) @Configuration public static class ServiceBeanConfiguration { @@ -93,18 +87,16 @@ public class JavaConfigReferenceBeanConditionalTest4 { } // make sure that the one using condition runs after. - @Order(Integer.MAX_VALUE-1) + @Order(Integer.MAX_VALUE - 1) @Configuration public static class AnnotationBeanConfiguration { - //TEST Conditional, this bean should be ignored + // TEST Conditional, this bean should be ignored @Bean @ConditionalOnMissingBean(HelloService.class) @DubboReference(group = "${myapp.group}", init = false) public ReferenceBean helloService() { return new ReferenceBean(); } - } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/configprops/SpringBootConfigPropsTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/configprops/SpringBootConfigPropsTest.java index cffb7e40c5..cf42633507 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/configprops/SpringBootConfigPropsTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/configprops/SpringBootConfigPropsTest.java @@ -33,6 +33,9 @@ import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; +import java.util.Collection; +import java.util.List; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -42,39 +45,33 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import java.util.Collection; -import java.util.List; - import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS; @SpringBootTest( - properties = { - "dubbo.application.NAME = dubbo-demo-application", - "dubbo.module.name = dubbo-demo-module", - "dubbo.registry.address = zookeeper://192.168.99.100:32770", - "dubbo.protocol.name=dubbo", - "dubbo.protocol.port=20880", - "dubbo.metrics.protocol=prometheus", - "dubbo.metrics.enable-jvm=true", - "dubbo.metrics.prometheus.exporter.enabled=true", - "dubbo.metrics.prometheus.exporter.enable-http-service-discovery=true", - "dubbo.metrics.prometheus.exporter.http-service-discovery-url=localhost:8080", - "dubbo.metrics.aggregation.enabled=true", - "dubbo.metrics.aggregation.bucket-num=5", - "dubbo.metrics.aggregation.time-window-seconds=120", - "dubbo.metrics.histogram.enabled=true", - "dubbo.monitor.address=zookeeper://127.0.0.1:32770", - "dubbo.Config-center.address=${zookeeper.connection.address.1}", - "dubbo.config-Center.group=group1", - "dubbo.metadata-report.address=${zookeeper.connection.address.2}", - "dubbo.METADATA-REPORT.username=User", - "dubbo.provider.host=127.0.0.1", - "dubbo.consumer.client=netty" - }, - classes = { - SpringBootConfigPropsTest.class - } -) + properties = { + "dubbo.application.NAME = dubbo-demo-application", + "dubbo.module.name = dubbo-demo-module", + "dubbo.registry.address = zookeeper://192.168.99.100:32770", + "dubbo.protocol.name=dubbo", + "dubbo.protocol.port=20880", + "dubbo.metrics.protocol=prometheus", + "dubbo.metrics.enable-jvm=true", + "dubbo.metrics.prometheus.exporter.enabled=true", + "dubbo.metrics.prometheus.exporter.enable-http-service-discovery=true", + "dubbo.metrics.prometheus.exporter.http-service-discovery-url=localhost:8080", + "dubbo.metrics.aggregation.enabled=true", + "dubbo.metrics.aggregation.bucket-num=5", + "dubbo.metrics.aggregation.time-window-seconds=120", + "dubbo.metrics.histogram.enabled=true", + "dubbo.monitor.address=zookeeper://127.0.0.1:32770", + "dubbo.Config-center.address=${zookeeper.connection.address.1}", + "dubbo.config-Center.group=group1", + "dubbo.metadata-report.address=${zookeeper.connection.address.2}", + "dubbo.METADATA-REPORT.username=User", + "dubbo.provider.host=127.0.0.1", + "dubbo.consumer.client=netty" + }, + classes = {SpringBootConfigPropsTest.class}) @Configuration @ComponentScan @EnableDubbo @@ -109,7 +106,8 @@ class SpringBootConfigPropsTest { Assertions.assertEquals(PROTOCOL_PROMETHEUS, metricsConfig.getProtocol()); Assertions.assertTrue(metricsConfig.getPrometheus().getExporter().getEnabled()); Assertions.assertTrue(metricsConfig.getPrometheus().getExporter().getEnableHttpServiceDiscovery()); - Assertions.assertEquals("localhost:8080", metricsConfig.getPrometheus().getExporter().getHttpServiceDiscoveryUrl()); + Assertions.assertEquals( + "localhost:8080", metricsConfig.getPrometheus().getExporter().getHttpServiceDiscoveryUrl()); Assertions.assertEquals(5, metricsConfig.getAggregation().getBucketNum()); Assertions.assertEquals(120, metricsConfig.getAggregation().getTimeWindowSeconds()); Assertions.assertTrue(metricsConfig.getAggregation().getEnabled()); @@ -148,7 +146,5 @@ class SpringBootConfigPropsTest { ConsumerConfig consumerConfig = moduleConfigManager.getDefaultConsumer().get(); Assertions.assertEquals("netty", consumerConfig.getClient()); - } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/configprops/SpringBootMultipleConfigPropsTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/configprops/SpringBootMultipleConfigPropsTest.java index 482cd054cd..a8022071e6 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/configprops/SpringBootMultipleConfigPropsTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/configprops/SpringBootMultipleConfigPropsTest.java @@ -33,6 +33,9 @@ import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; +import java.util.Collection; +import java.util.List; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -42,40 +45,34 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import java.util.Collection; -import java.util.List; - import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS; @SpringBootTest( - properties = { - "dubbo.applications.application1.name = dubbo-demo-application", - "dubbo.modules.demo-module.name = dubbo-demo-module", - "dubbo.registries.my-registry.address = zookeeper://192.168.99.100:32770", - "dubbo.protocols.dubbo.port=20880", - "dubbo.metricses.my-metrics.protocol=prometheus", - "dubbo.metricses.my-metrics.prometheus.pushgateway.enabled=true", - "dubbo.metricses.my-metrics.prometheus.pushgateway.base-url=localhost:9091", - "dubbo.metricses.my-metrics.prometheus.pushgateway.username=username", - "dubbo.metricses.my-metrics.prometheus.pushgateway.password=password", - "dubbo.metricses.my-metrics.prometheus.pushgateway.job=job", - "dubbo.metricses.my-metrics.prometheus.pushgateway.push-interval=30", - "dubbo.metricses.my-metrics.aggregation.enabled=true", - "dubbo.metricses.my-metrics.aggregation.bucket-num=5", - "dubbo.metricses.my-metrics.aggregation.time-window-seconds=120", - "dubbo.metricses.my-metrics.histogram.enabled=true", - "dubbo.monitors.my-monitor.address=zookeeper://127.0.0.1:32770", - "dubbo.config-centers.my-configcenter.address=${zookeeper.connection.address.1}", - "dubbo.config-centers.my-configcenter.group=group1", - "dubbo.metadata-reports.my-metadata.address=${zookeeper.connection.address.2}", - "dubbo.metadata-reports.my-metadata.username=User", - "dubbo.providers.my-provider.host=127.0.0.1", - "dubbo.consumers.my-consumer.client=netty" - }, - classes = { - SpringBootMultipleConfigPropsTest.class - } -) + properties = { + "dubbo.applications.application1.name = dubbo-demo-application", + "dubbo.modules.demo-module.name = dubbo-demo-module", + "dubbo.registries.my-registry.address = zookeeper://192.168.99.100:32770", + "dubbo.protocols.dubbo.port=20880", + "dubbo.metricses.my-metrics.protocol=prometheus", + "dubbo.metricses.my-metrics.prometheus.pushgateway.enabled=true", + "dubbo.metricses.my-metrics.prometheus.pushgateway.base-url=localhost:9091", + "dubbo.metricses.my-metrics.prometheus.pushgateway.username=username", + "dubbo.metricses.my-metrics.prometheus.pushgateway.password=password", + "dubbo.metricses.my-metrics.prometheus.pushgateway.job=job", + "dubbo.metricses.my-metrics.prometheus.pushgateway.push-interval=30", + "dubbo.metricses.my-metrics.aggregation.enabled=true", + "dubbo.metricses.my-metrics.aggregation.bucket-num=5", + "dubbo.metricses.my-metrics.aggregation.time-window-seconds=120", + "dubbo.metricses.my-metrics.histogram.enabled=true", + "dubbo.monitors.my-monitor.address=zookeeper://127.0.0.1:32770", + "dubbo.config-centers.my-configcenter.address=${zookeeper.connection.address.1}", + "dubbo.config-centers.my-configcenter.group=group1", + "dubbo.metadata-reports.my-metadata.address=${zookeeper.connection.address.2}", + "dubbo.metadata-reports.my-metadata.username=User", + "dubbo.providers.my-provider.host=127.0.0.1", + "dubbo.consumers.my-consumer.client=netty" + }, + classes = {SpringBootMultipleConfigPropsTest.class}) @Configuration @ComponentScan @EnableDubbo @@ -109,11 +106,16 @@ class SpringBootMultipleConfigPropsTest { MetricsConfig metricsConfig = configManager.getMetrics().get(); Assertions.assertEquals(PROTOCOL_PROMETHEUS, metricsConfig.getProtocol()); Assertions.assertTrue(metricsConfig.getPrometheus().getPushgateway().getEnabled()); - Assertions.assertEquals("localhost:9091", metricsConfig.getPrometheus().getPushgateway().getBaseUrl()); - Assertions.assertEquals("username", metricsConfig.getPrometheus().getPushgateway().getUsername()); - Assertions.assertEquals("password", metricsConfig.getPrometheus().getPushgateway().getPassword()); - Assertions.assertEquals("job", metricsConfig.getPrometheus().getPushgateway().getJob()); - Assertions.assertEquals(30, metricsConfig.getPrometheus().getPushgateway().getPushInterval()); + Assertions.assertEquals( + "localhost:9091", metricsConfig.getPrometheus().getPushgateway().getBaseUrl()); + Assertions.assertEquals( + "username", metricsConfig.getPrometheus().getPushgateway().getUsername()); + Assertions.assertEquals( + "password", metricsConfig.getPrometheus().getPushgateway().getPassword()); + Assertions.assertEquals( + "job", metricsConfig.getPrometheus().getPushgateway().getJob()); + Assertions.assertEquals( + 30, metricsConfig.getPrometheus().getPushgateway().getPushInterval()); Assertions.assertEquals(5, metricsConfig.getAggregation().getBucketNum()); Assertions.assertEquals(120, metricsConfig.getAggregation().getTimeWindowSeconds()); Assertions.assertTrue(metricsConfig.getAggregation().getEnabled()); @@ -153,7 +155,5 @@ class SpringBootMultipleConfigPropsTest { ConsumerConfig consumerConfig = moduleConfigManager.getDefaultConsumer().get(); Assertions.assertEquals("netty", consumerConfig.getClient()); - } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/importxml/SpringBootImportDubboXmlTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/importxml/SpringBootImportDubboXmlTest.java index d116d82f45..6436cce82f 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/importxml/SpringBootImportDubboXmlTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/importxml/SpringBootImportDubboXmlTest.java @@ -30,26 +30,20 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; @SpringBootTest( - properties = { - "dubbo.registry.protocol=zookeeper", - "dubbo.registry.address=localhost:2181" - }, - classes = { - SpringBootImportDubboXmlTest.class - } -) + properties = {"dubbo.registry.protocol=zookeeper", "dubbo.registry.address=localhost:2181"}, + classes = {SpringBootImportDubboXmlTest.class}) @Configuration @ComponentScan @ImportResource("classpath:/org/apache/dubbo/config/spring/boot/importxml/consumer/dubbo-consumer.xml") class SpringBootImportDubboXmlTest { @BeforeAll - public static void beforeAll(){ + public static void beforeAll() { DubboBootstrap.reset(); } @AfterAll - public static void afterAll(){ + public static void afterAll() { DubboBootstrap.reset(); } @@ -67,5 +61,4 @@ class SpringBootImportDubboXmlTest { Assertions.assertTrue(s.contains("service org.apache.dubbo.config.spring.api.HelloService"), s); } } - -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/importxml2/HelloServiceImpl.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/importxml2/HelloServiceImpl.java index 789cfaa5a1..097684f955 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/importxml2/HelloServiceImpl.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/importxml2/HelloServiceImpl.java @@ -26,5 +26,4 @@ public class HelloServiceImpl implements HelloService { public String sayHello(String name) { return "Hello, " + name; } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/importxml2/SpringBootImportAndScanTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/importxml2/SpringBootImportAndScanTest.java index 4e5f5bec5e..8ad0b82895 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/importxml2/SpringBootImportAndScanTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/importxml2/SpringBootImportAndScanTest.java @@ -23,6 +23,8 @@ import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan; import org.apache.dubbo.config.spring.reference.ReferenceBeanManager; +import java.util.Map; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -36,15 +38,15 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; -import java.util.Map; - -@SpringBootTest(properties = { - //"dubbo.scan.base-packages=org.apache.dubbo.config.spring.boot.importxml2", - "dubbo.registry.address=N/A", - "myapp.dubbo.port=20881", - "myapp.name=dubbo-provider", - "myapp.group=test" -}, classes = SpringBootImportAndScanTest.class) +@SpringBootTest( + properties = { + // "dubbo.scan.base-packages=org.apache.dubbo.config.spring.boot.importxml2", + "dubbo.registry.address=N/A", + "myapp.dubbo.port=20881", + "myapp.name=dubbo-provider", + "myapp.group=test" + }, + classes = SpringBootImportAndScanTest.class) @Configuration @ComponentScan @DubboComponentScan @@ -76,7 +78,8 @@ class SpringBootImportAndScanTest implements ApplicationContextAware { Assertions.assertEquals(1, referenceBeanMap.size()); Assertions.assertNotNull(referenceBeanMap.get("&helloService")); - ReferenceBeanManager referenceBeanManager = applicationContext.getBean(ReferenceBeanManager.BEAN_NAME, ReferenceBeanManager.class); + ReferenceBeanManager referenceBeanManager = + applicationContext.getBean(ReferenceBeanManager.BEAN_NAME, ReferenceBeanManager.class); Assertions.assertNotNull(referenceBeanManager.getById("helloService")); } @@ -85,14 +88,11 @@ class SpringBootImportAndScanTest implements ApplicationContextAware { this.applicationContext = applicationContext; } - @Configuration public static class ConsumerConfiguration { // Match and reuse 'helloService' reference bean definition in dubbo-provider.xml @DubboReference(group = "${myapp.group}") private HelloService helloService; - } - -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/KeepRunningOnSpringClosedTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/KeepRunningOnSpringClosedTest.java index f09fa55082..4d1fe654b8 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/KeepRunningOnSpringClosedTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/KeepRunningOnSpringClosedTest.java @@ -31,10 +31,10 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; class KeepRunningOnSpringClosedTest { @Test - void test(){ + void test() { // set KeepRunningOnSpringClosed flag for next spring context - DubboSpringInitCustomizerHolder.get().addCustomizer(context-> { + DubboSpringInitCustomizerHolder.get().addCustomizer(context -> { context.setKeepRunningOnSpringClosed(true); }); @@ -42,8 +42,7 @@ class KeepRunningOnSpringClosedTest { try { String resourcePath = "org/apache/dubbo/config/spring"; providerContext = new ClassPathXmlApplicationContext( - resourcePath + "/demo-provider.xml", - resourcePath + "/demo-provider-properties.xml"); + resourcePath + "/demo-provider.xml", resourcePath + "/demo-provider-properties.xml"); providerContext.start(); // Expect 1: dubbo application state is STARTED after spring context start finish. @@ -56,7 +55,8 @@ class KeepRunningOnSpringClosedTest { ModuleDeployer moduleDeployer = moduleModel.getDeployer(); Assertions.assertTrue(moduleDeployer.isStarted()); - ApplicationDeployer applicationDeployer = moduleModel.getApplicationModel().getDeployer(); + ApplicationDeployer applicationDeployer = + moduleModel.getApplicationModel().getDeployer(); Assertions.assertEquals(DeployState.STARTED, applicationDeployer.getState()); Assertions.assertEquals(true, applicationDeployer.isStarted()); Assertions.assertEquals(false, applicationDeployer.isStopped()); @@ -65,7 +65,8 @@ class KeepRunningOnSpringClosedTest { // close spring context providerContext.close(); - // Expect 2: dubbo application will not be destroyed after closing spring context cause setKeepRunningOnSpringClosed(true) + // Expect 2: dubbo application will not be destroyed after closing spring context cause + // setKeepRunningOnSpringClosed(true) Assertions.assertEquals(DeployState.STARTED, applicationDeployer.getState()); Assertions.assertEquals(true, applicationDeployer.isStarted()); Assertions.assertEquals(false, applicationDeployer.isStopped()); @@ -78,4 +79,4 @@ class KeepRunningOnSpringClosedTest { } } } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrarTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrarTest.java index e165f933db..5f5d4ac3aa 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrarTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrarTest.java @@ -45,8 +45,7 @@ class DubboComponentScanRegistrarTest { } @AfterEach - public void tearDown() { - } + public void tearDown() {} @Test void test() { @@ -71,7 +70,6 @@ class DubboComponentScanRegistrarTest { // Test @Transactional is present or not Assertions.assertNotNull(findAnnotation(beanClass, Transactional.class)); - // consumer app AnnotationConfigApplicationContext consumerContext = new AnnotationConfigApplicationContext(); @@ -121,9 +119,5 @@ class DubboComponentScanRegistrarTest { providerContext.close(); consumerContext.close(); - - } - - -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationTest.java index f4b705315e..69acec2129 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationTest.java @@ -22,6 +22,8 @@ import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; +import java.io.IOException; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -29,8 +31,6 @@ import org.junit.jupiter.api.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.core.io.support.ResourcePropertySource; -import java.io.IOException; - /** * {@link DubboConfigConfiguration} Test * @@ -47,7 +47,6 @@ class DubboConfigConfigurationTest { context = new AnnotationConfigApplicationContext(); ResourcePropertySource propertySource = new ResourcePropertySource("META-INF/config.properties"); context.getEnvironment().getPropertySources().addFirst(propertySource); - } @AfterEach @@ -90,5 +89,4 @@ class DubboConfigConfigurationTest { RegistryConfig registry2 = context.getBean("registry2", RegistryConfig.class); Assertions.assertEquals(2182, registry2.getPort()); } - -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfigTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfigTest.java index 803241d535..ba5392a02d 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfigTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfigTest.java @@ -27,18 +27,17 @@ import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.Collection; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.PropertySource; -import java.util.Collection; - import static com.alibaba.spring.util.BeanRegistrar.hasAlias; import static org.junit.jupiter.api.Assertions.assertFalse; - /** * {@link EnableDubboConfig} Test * @@ -56,7 +55,7 @@ class EnableDubboConfigTest { DubboBootstrap.reset(); } - //@Test + // @Test public void testSingle() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @@ -88,7 +87,6 @@ class EnableDubboConfigTest { ProviderConfig providerConfig = context.getBean(ProviderConfig.class); Assertions.assertEquals("127.0.0.1", providerConfig.getHost()); - // consumer ConsumerConfig consumerConfig = context.getBean(ConsumerConfig.class); Assertions.assertEquals("netty", consumerConfig.getClient()); @@ -98,7 +96,7 @@ class EnableDubboConfigTest { assertFalse(hasAlias(context, "org.apache.dubbo.config.MonitorConfig#0", "zookeeper")); } - //@Test + // @Test public void testMultiple() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @@ -119,22 +117,17 @@ class EnableDubboConfigTest { configManager.getProtocol("rest").get(); configManager.getProtocol("thrift").get(); - // asserts aliases -// assertTrue(hasAlias(context, "applicationBean2", "dubbo-demo-application2")); -// assertTrue(hasAlias(context, "applicationBean3", "dubbo-demo-application3")); + // assertTrue(hasAlias(context, "applicationBean2", "dubbo-demo-application2")); + // assertTrue(hasAlias(context, "applicationBean3", "dubbo-demo-application3")); } @EnableDubboConfig @PropertySource("META-INF/config.properties") - private static class TestMultipleConfig { - - } + private static class TestMultipleConfig {} @EnableDubboConfig(multiple = false) @PropertySource("META-INF/config.properties") - private static class TestConfig { - - } -} \ No newline at end of file + private static class TestConfig {} +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboTest.java index 6230db4822..b171a6cf0c 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboTest.java @@ -84,7 +84,6 @@ class EnableDubboTest { // Test @Transactional is present or not Assertions.assertNotNull(findAnnotation(beanClass, Transactional.class)); - } @Test @@ -119,13 +118,13 @@ class EnableDubboTest { // From Parent -// demoService = child.getDemoServiceFromParent(); -// -// Assertions.assertNotNull(demoService); -// -// value = demoService.sayName("Mercy"); -// -// Assertions.assertEquals("Hello,Mercy", value); + // demoService = child.getDemoServiceFromParent(); + // + // Assertions.assertNotNull(demoService); + // + // value = demoService.sayName("Mercy"); + // + // Assertions.assertEquals("Hello,Mercy", value); // From Ancestor @@ -142,7 +141,6 @@ class EnableDubboTest { // Test multiple binding Assertions.assertEquals("N/A", registryConfig.getAddress()); - } @EnableDubbo(scanBasePackages = "org.apache.dubbo.config.spring.context.annotation.provider") @@ -163,17 +161,11 @@ class EnableDubboTest { } @Override - public void commit(TransactionStatus status) throws TransactionException { - - } + public void commit(TransactionStatus status) throws TransactionException {} @Override - public void rollback(TransactionStatus status) throws TransactionException { - - } + public void rollback(TransactionStatus status) throws TransactionException {} }; } } - - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/ConsumerConfiguration.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/ConsumerConfiguration.java index 9fd7b2e1b7..5f3aabb3f9 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/ConsumerConfiguration.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/ConsumerConfiguration.java @@ -28,9 +28,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @Configuration("consumerConfiguration") -@DubboComponentScan( - basePackageClasses = ConsumerConfiguration.class -) +@DubboComponentScan(basePackageClasses = ConsumerConfiguration.class) @PropertySource("META-INF/default.properties") public class ConsumerConfiguration { @@ -80,13 +78,12 @@ public class ConsumerConfiguration { this.demoService = demoService; } - @Bean public Child c() { return new Child(); } - public static abstract class Ancestor { + public abstract static class Ancestor { @Reference(version = "2.5.7", url = remoteURL) private DemoService demoServiceFromAncestor; @@ -100,7 +97,7 @@ public class ConsumerConfiguration { } } - public static abstract class Parent extends Ancestor { + public abstract static class Parent extends Ancestor { private DemoService demoServiceFromParent; @@ -112,7 +109,6 @@ public class ConsumerConfiguration { public void setDemoServiceFromParent(DemoService demoServiceFromParent) { this.demoServiceFromParent = demoServiceFromParent; } - } public static class Child extends Parent { @@ -123,7 +119,6 @@ public class ConsumerConfiguration { @Reference(version = "2.5.7", url = remoteURL) private DemoService demoServiceFromChild; - public DemoService getDemoService() { return demoService; } @@ -136,5 +131,4 @@ public class ConsumerConfiguration { this.demoServiceFromChild = demoServiceFromChild; } } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/test/TestConsumerConfiguration.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/test/TestConsumerConfiguration.java index 57b8669fe4..ca09eedda0 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/test/TestConsumerConfiguration.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/test/TestConsumerConfiguration.java @@ -39,7 +39,8 @@ public class TestConsumerConfiguration { private static final String remoteURL = "dubbo://127.0.0.1:12345?version=2.5.7"; - @Reference(id = "demoService", + @Reference( + id = "demoService", version = "2.5.7", url = remoteURL, application = "dubbo-demo-application", @@ -70,15 +71,14 @@ public class TestConsumerConfiguration { this.demoService = demoService; } - @Bean public Child c() { return new Child(); } - public static abstract class Ancestor { + public abstract static class Ancestor { - @DubboReference(version = "2.5.7", url = remoteURL,filter = "mymock", application = "dubbo-demo-application") + @DubboReference(version = "2.5.7", url = remoteURL, filter = "mymock", application = "dubbo-demo-application") private DemoService demoServiceFromAncestor; public DemoService getDemoServiceFromAncestor() { diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DefaultHelloService.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DefaultHelloService.java index c4df6f4340..8b50e8780b 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DefaultHelloService.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DefaultHelloService.java @@ -34,5 +34,4 @@ public class DefaultHelloService implements HelloService { public String sayHello(String name) { return "Greeting, " + name; } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DemoServiceImpl.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DemoServiceImpl.java index 8ee2a8a09f..62f7e24b74 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DemoServiceImpl.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DemoServiceImpl.java @@ -23,7 +23,6 @@ import org.apache.dubbo.config.spring.api.DemoService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; - /** * {@link DemoService} Service implementation * @@ -34,8 +33,7 @@ import org.springframework.transaction.annotation.Transactional; application = "${demo.service.application}", protocol = "${demo.service.protocol}", registry = "${demo.service.registry}", - methods = @Method(timeout = 100,name = "sayName") -) + methods = @Method(timeout = 100, name = "sayName")) @Service @Transactional public class DemoServiceImpl implements DemoService { diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/HelloServiceImpl.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/HelloServiceImpl.java index 1841abb075..80cc2cd9fd 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/HelloServiceImpl.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/HelloServiceImpl.java @@ -19,7 +19,6 @@ package org.apache.dubbo.config.spring.context.annotation.provider; import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.config.spring.api.HelloService; - /** * {@link HelloService} Implementation just annotating Dubbo's {@link Service} * diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/ProviderConfiguration.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/ProviderConfiguration.java index 59e0cb3d77..d4e103aad7 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/ProviderConfiguration.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/ProviderConfiguration.java @@ -21,6 +21,8 @@ import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan; +import java.util.UUID; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; @@ -33,8 +35,6 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.support.AbstractPlatformTransactionManager; import org.springframework.transaction.support.DefaultTransactionStatus; -import java.util.UUID; - @DubboComponentScan(basePackages = "org.apache.dubbo.config.spring.context.annotation.provider") @PropertySource("classpath:/META-INF/default.properties") @EnableTransactionManagement @@ -115,6 +115,4 @@ public class ProviderConfiguration { } }; } - } - diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/customize/DubboSpringInitCustomizerTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/customize/DubboSpringInitCustomizerTest.java index 4662a62acc..b2810064fa 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/customize/DubboSpringInitCustomizerTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/customize/DubboSpringInitCustomizerTest.java @@ -38,7 +38,6 @@ class DubboSpringInitCustomizerTest { public static void beforeAll() { DubboBootstrap.reset(); SysProps.setProperty("dubbo.registry.address", ZookeeperRegistryCenterConfig.getConnectionAddress()); - } @AfterAll @@ -67,7 +66,8 @@ class DubboSpringInitCustomizerTest { ModuleModel moduleModelFromSpring1 = providerContext1.getBean(ModuleModel.class); Assertions.assertSame(moduleModel1, moduleModelFromSpring1); String serviceKey1 = HelloService.class.getName() + ":1.0.0"; - ServiceDescriptor serviceDescriptor1 = moduleModelFromSpring1.getServiceRepository().lookupService(serviceKey1); + ServiceDescriptor serviceDescriptor1 = + moduleModelFromSpring1.getServiceRepository().lookupService(serviceKey1); Assertions.assertNotNull(serviceDescriptor1); // close spring context 1 @@ -87,13 +87,14 @@ class DubboSpringInitCustomizerTest { Assertions.assertSame(moduleModel2, moduleModelFromSpring2); Assertions.assertNotSame(moduleModelFromSpring1, moduleModelFromSpring2); String serviceKey2 = HelloService.class.getName() + ":2.0.0"; - ServiceDescriptor serviceDescriptor2 = moduleModelFromSpring2.getServiceRepository().lookupService(serviceKey2); + ServiceDescriptor serviceDescriptor2 = + moduleModelFromSpring2.getServiceRepository().lookupService(serviceKey2); Assertions.assertNotNull(serviceDescriptor2); Assertions.assertNotSame(serviceDescriptor1, serviceDescriptor2); providerContext2.close(); providerContext2 = null; - }finally { + } finally { if (providerContext1 != null) { providerContext1.close(); } @@ -103,6 +104,4 @@ class DubboSpringInitCustomizerTest { applicationModel.destroy(); } } - - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/properties/DefaultDubboConfigBinderTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/properties/DefaultDubboConfigBinderTest.java index 73240d56f9..f0ec93a8de 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/properties/DefaultDubboConfigBinderTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/properties/DefaultDubboConfigBinderTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config.spring.context.properties; - import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.RegistryConfig; @@ -63,6 +62,5 @@ class DefaultDubboConfigBinderTest { ProtocolConfig protocolConfig = new ProtocolConfig(); dubboConfigBinder.bind("dubbo.protocol", protocolConfig); Assertions.assertEquals(Integer.valueOf(20881), protocolConfig.getPort()); - } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/extension/SpringExtensionInjectorTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/extension/SpringExtensionInjectorTest.java index c27f07595c..463727c70f 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/extension/SpringExtensionInjectorTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/extension/SpringExtensionInjectorTest.java @@ -44,8 +44,7 @@ class SpringExtensionInjectorTest { } @AfterEach - public void destroy() { - } + public void destroy() {} @Test void testSpringInjector() { @@ -55,8 +54,9 @@ class SpringExtensionInjectorTest { context.register(getClass()); context.refresh(); - SpringExtensionInjector springExtensionInjector = SpringExtensionInjector.get(DubboBeanUtils.getApplicationModel(context)); - Assertions.assertEquals(springExtensionInjector.getContext(),context); + SpringExtensionInjector springExtensionInjector = + SpringExtensionInjector.get(DubboBeanUtils.getApplicationModel(context)); + Assertions.assertEquals(springExtensionInjector.getContext(), context); Protocol protocol = springExtensionInjector.getInstance(Protocol.class, "protocol"); Assertions.assertNull(protocol); @@ -70,10 +70,12 @@ class SpringExtensionInjectorTest { Assertions.assertNotNull(helloServiceBean); HelloService helloService = springExtensionInjector.getInstance(HelloService.class, null); - Assertions.assertEquals(helloService,helloServiceBean); + Assertions.assertEquals(helloService, helloServiceBean); - Assertions.assertThrows(IllegalStateException.class, () -> springExtensionInjector.getInstance(DemoService.class, null), - "Expect single but found 2 beans in spring context: [bean1, bean2]"); + Assertions.assertThrows( + IllegalStateException.class, + () -> springExtensionInjector.getInstance(DemoService.class, null), + "Expect single but found 2 beans in spring context: [bean1, bean2]"); } finally { context.close(); @@ -99,4 +101,4 @@ class SpringExtensionInjectorTest { public ApplicationConfig applicationConfig() { return new ApplicationConfig("test-app"); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/filter/MockDao.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/filter/MockDao.java index 9006995903..c43c9bd1b8 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/filter/MockDao.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/filter/MockDao.java @@ -19,6 +19,4 @@ package org.apache.dubbo.config.spring.filter; /** * MockDao */ -public interface MockDao { - -} +public interface MockDao {} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/filter/MockDaoImpl.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/filter/MockDaoImpl.java index d8f6f9cd75..470e50db88 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/filter/MockDaoImpl.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/filter/MockDaoImpl.java @@ -19,6 +19,4 @@ package org.apache.dubbo.config.spring.filter; /** * MockDaoImpl */ -public class MockDaoImpl implements MockDao { - -} +public class MockDaoImpl implements MockDao {} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/filter/MockFilter.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/filter/MockFilter.java index e41d734c60..daedbb3990 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/filter/MockFilter.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/filter/MockFilter.java @@ -62,5 +62,4 @@ public class MockFilter implements Filter { public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { return invoker.invoke(invocation); } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/DemoServiceImpl.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/DemoServiceImpl.java index 0413314630..12e7c385ce 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/DemoServiceImpl.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/DemoServiceImpl.java @@ -41,5 +41,4 @@ public class DemoServiceImpl implements DemoService { public void setPrefix(String prefix) { this.prefix = prefix; } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/DemoServiceSonImpl.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/DemoServiceSonImpl.java index f97d3b307a..5b979abbd6 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/DemoServiceSonImpl.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/DemoServiceSonImpl.java @@ -38,5 +38,4 @@ public class DemoServiceSonImpl implements DemoServiceSon { public void setPrefix(String prefix) { this.prefix = prefix; } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/MethodCallbackImpl.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/MethodCallbackImpl.java index a8fe9bc23a..6edac1b879 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/MethodCallbackImpl.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/MethodCallbackImpl.java @@ -18,15 +18,16 @@ package org.apache.dubbo.config.spring.impl; import org.apache.dubbo.config.spring.api.MethodCallback; +import javax.annotation.PostConstruct; + +import java.util.concurrent.atomic.AtomicInteger; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.core.env.Environment; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronizationManager; -import javax.annotation.PostConstruct; -import java.util.concurrent.atomic.AtomicInteger; - public class MethodCallbackImpl implements MethodCallback { private String onInvoke1 = ""; @@ -196,5 +197,4 @@ public class MethodCallbackImpl implements MethodCallback { throw new IllegalStateException("No active transaction"); } } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/UnserializableBoxDemoServiceImpl.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/UnserializableBoxDemoServiceImpl.java index 14df2a0dff..e681335a77 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/UnserializableBoxDemoServiceImpl.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/UnserializableBoxDemoServiceImpl.java @@ -31,5 +31,4 @@ public class UnserializableBoxDemoServiceImpl implements DemoService { public Box getBox() { return new UnserializableBox(); } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/api/ApiIsolationTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/api/ApiIsolationTest.java index ec728db29a..c9cbcdd9ba 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/api/ApiIsolationTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/api/ApiIsolationTest.java @@ -33,17 +33,17 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.atomic.AtomicInteger; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.atomic.AtomicInteger; - import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_ISOLATION; public class ApiIsolationTest { @@ -64,12 +64,10 @@ public class ApiIsolationTest { private String version2 = "2.0"; private String version3 = "3.0"; - @Test @Disabled public void test() throws Exception { - DubboBootstrap providerBootstrap = null; DubboBootstrap consumerBootstrap1 = null; DubboBootstrap consumerBootstrap2 = null; @@ -110,14 +108,14 @@ public class ApiIsolationTest { applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_ISOLATION); providerBootstrap - .application(applicationConfig) - .registry(registryConfig) - // export with tri and dubbo protocol - .protocol(new ProtocolConfig("tri", 20001)) - .protocol(new ProtocolConfig("dubbo", 20002)) - .service(serviceConfig1) - .service(serviceConfig2) - .service(serviceConfig3); + .application(applicationConfig) + .registry(registryConfig) + // export with tri and dubbo protocol + .protocol(new ProtocolConfig("tri", 20001)) + .protocol(new ProtocolConfig("dubbo", 20002)) + .service(serviceConfig1) + .service(serviceConfig2) + .service(serviceConfig3); providerBootstrap.start(); @@ -180,13 +178,22 @@ public class ApiIsolationTest { private DubboBootstrap configConsumerBootstrapWithProtocol(String protocol) { DubboBootstrap consumerBootstrap; consumerBootstrap = DubboBootstrap.newInstance(); - consumerBootstrap.application("consumer-app") - .registry(registryConfig) - .reference(builder -> builder.interfaceClass(DemoService.class).version(version1).protocol(protocol).injvm(false)) - .reference(builder -> builder.interfaceClass(HelloService.class).version(version2).protocol(protocol).injvm(false)) - .reference(builder -> builder.interfaceClass(HelloService.class).version(version3).protocol(protocol).injvm(false)); + consumerBootstrap + .application("consumer-app") + .registry(registryConfig) + .reference(builder -> builder.interfaceClass(DemoService.class) + .version(version1) + .protocol(protocol) + .injvm(false)) + .reference(builder -> builder.interfaceClass(HelloService.class) + .version(version2) + .protocol(protocol) + .injvm(false)) + .reference(builder -> builder.interfaceClass(HelloService.class) + .version(version3) + .protocol(protocol) + .injvm(false)); consumerBootstrap.start(); return consumerBootstrap; } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/BaseTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/BaseTest.java index eb6c121c8f..80afe78b5f 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/BaseTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/BaseTest.java @@ -26,14 +26,15 @@ import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.isolation.spring.support.DemoServiceExecutor; import org.apache.dubbo.config.spring.isolation.spring.support.HelloServiceExecutor; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.springframework.context.ApplicationContext; import java.util.Map; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.springframework.context.ApplicationContext; + public abstract class BaseTest { protected ServiceConfig serviceConfig1; @@ -102,5 +103,4 @@ public abstract class BaseTest { helloServiceV3.sayHello("hello"); } } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/AnnotationIsolationTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/AnnotationIsolationTest.java index 3a994e937a..eda4503d08 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/AnnotationIsolationTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/AnnotationIsolationTest.java @@ -24,15 +24,16 @@ import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.config.spring.isolation.spring.BaseTest; import org.apache.dubbo.config.spring.isolation.spring.support.DemoServiceExecutor; import org.apache.dubbo.config.spring.isolation.spring.support.HelloServiceExecutor; + +import java.util.Map; +import java.util.concurrent.Executor; + import org.junit.jupiter.api.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import java.util.Map; -import java.util.concurrent.Executor; - import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_ISOLATION; public class AnnotationIsolationTest extends BaseTest { @@ -40,11 +41,13 @@ public class AnnotationIsolationTest extends BaseTest { @Test public void test() throws Exception { // start provider app - AnnotationConfigApplicationContext providerContext = new AnnotationConfigApplicationContext(ProviderConfiguration.class); + AnnotationConfigApplicationContext providerContext = + new AnnotationConfigApplicationContext(ProviderConfiguration.class); providerContext.start(); // start consumer app - AnnotationConfigApplicationContext consumerContext = new AnnotationConfigApplicationContext(ConsumerConfiguration.class); + AnnotationConfigApplicationContext consumerContext = + new AnnotationConfigApplicationContext(ConsumerConfiguration.class); consumerContext.start(); // getAndSet serviceConfig @@ -56,14 +59,16 @@ public class AnnotationIsolationTest extends BaseTest { // close context providerContext.close(); consumerContext.close(); - } private void setServiceConfig(AnnotationConfigApplicationContext providerContext) { Map serviceConfigMap = providerContext.getBeansOfType(ServiceConfig.class); - serviceConfig1 = serviceConfigMap.get("ServiceBean:org.apache.dubbo.config.spring.api.DemoService:1.0.0:Group1"); - serviceConfig2 = serviceConfigMap.get("ServiceBean:org.apache.dubbo.config.spring.api.HelloService:2.0.0:Group2"); - serviceConfig3 = serviceConfigMap.get("ServiceBean:org.apache.dubbo.config.spring.api.HelloService:3.0.0:Group3"); + serviceConfig1 = + serviceConfigMap.get("ServiceBean:org.apache.dubbo.config.spring.api.DemoService:1.0.0:Group1"); + serviceConfig2 = + serviceConfigMap.get("ServiceBean:org.apache.dubbo.config.spring.api.HelloService:2.0.0:Group2"); + serviceConfig3 = + serviceConfigMap.get("ServiceBean:org.apache.dubbo.config.spring.api.HelloService:3.0.0:Group3"); } // note scanBasePackages, refer three service with dubbo and tri protocol diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/dubbo/DemoServiceV1.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/dubbo/DemoServiceV1.java index 9c40bb1953..a63144fbf2 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/dubbo/DemoServiceV1.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/dubbo/DemoServiceV1.java @@ -19,6 +19,7 @@ package org.apache.dubbo.config.spring.isolation.spring.annotation.consumer.dubb import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.spring.api.Box; import org.apache.dubbo.config.spring.api.DemoService; + import org.springframework.stereotype.Component; @Component("dubbo-demoServiceV1") diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/dubbo/HelloServiceV2.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/dubbo/HelloServiceV2.java index a70b7884e6..09da5a46dc 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/dubbo/HelloServiceV2.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/dubbo/HelloServiceV2.java @@ -18,6 +18,7 @@ package org.apache.dubbo.config.spring.isolation.spring.annotation.consumer.dubb import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.spring.api.HelloService; + import org.springframework.stereotype.Component; @Component("dubbo-helloServiceV2") diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/dubbo/HelloServiceV3.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/dubbo/HelloServiceV3.java index e807ffeab2..b158580103 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/dubbo/HelloServiceV3.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/dubbo/HelloServiceV3.java @@ -18,6 +18,7 @@ package org.apache.dubbo.config.spring.isolation.spring.annotation.consumer.dubb import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.spring.api.HelloService; + import org.springframework.stereotype.Component; @Component("dubbo-helloServiceV3") diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/tri/DemoServiceV1.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/tri/DemoServiceV1.java index cd8131f717..7f65b50fbc 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/tri/DemoServiceV1.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/tri/DemoServiceV1.java @@ -19,11 +19,12 @@ package org.apache.dubbo.config.spring.isolation.spring.annotation.consumer.tri; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.spring.api.Box; import org.apache.dubbo.config.spring.api.DemoService; + import org.springframework.stereotype.Component; @Component("tri-demoServiceV1") public class DemoServiceV1 implements DemoService { - @DubboReference(version = "1.0.0",group = "Group1", scope = "remote", protocol = "tri") + @DubboReference(version = "1.0.0", group = "Group1", scope = "remote", protocol = "tri") private DemoService demoService; @Override diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/tri/HelloServiceV2.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/tri/HelloServiceV2.java index 6c3c4c2dad..44a6619318 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/tri/HelloServiceV2.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/tri/HelloServiceV2.java @@ -18,6 +18,7 @@ package org.apache.dubbo.config.spring.isolation.spring.annotation.consumer.tri; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.spring.api.HelloService; + import org.springframework.stereotype.Component; @Component("tri-helloServiceV2") diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/tri/HelloServiceV3.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/tri/HelloServiceV3.java index 61812f868c..acd6eed5fe 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/tri/HelloServiceV3.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/tri/HelloServiceV3.java @@ -18,6 +18,7 @@ package org.apache.dubbo.config.spring.isolation.spring.annotation.consumer.tri; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.spring.api.HelloService; + import org.springframework.stereotype.Component; @Component("tri-helloServiceV3") diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/provider/HelloServiceImplV2.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/provider/HelloServiceImplV2.java index 1d23403c77..a9e6769e62 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/provider/HelloServiceImplV2.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/provider/HelloServiceImplV2.java @@ -18,6 +18,7 @@ package org.apache.dubbo.config.spring.isolation.spring.annotation.provider; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.config.spring.api.HelloService; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/provider/HelloServiceImplV3.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/provider/HelloServiceImplV3.java index a99bf24754..0bb66f96e5 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/provider/HelloServiceImplV3.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/provider/HelloServiceImplV3.java @@ -18,6 +18,7 @@ package org.apache.dubbo.config.spring.isolation.spring.annotation.provider; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.config.spring.api.HelloService; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -29,5 +30,4 @@ public class HelloServiceImplV3 implements HelloService { public String sayHello(String name) { return "server hello"; } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/support/DemoServiceExecutor.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/support/DemoServiceExecutor.java index 099b51db02..6ad5560f34 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/support/DemoServiceExecutor.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/support/DemoServiceExecutor.java @@ -24,7 +24,6 @@ import java.util.concurrent.TimeUnit; public class DemoServiceExecutor extends ThreadPoolExecutor { public DemoServiceExecutor() { - super(10, 10, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>(), - new NamedThreadFactory("DemoServiceExecutor")); + super(10, 10, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>(), new NamedThreadFactory("DemoServiceExecutor")); } } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/support/HelloServiceExecutor.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/support/HelloServiceExecutor.java index 1ba6eca5c4..27b7e7bd5b 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/support/HelloServiceExecutor.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/support/HelloServiceExecutor.java @@ -24,8 +24,12 @@ import java.util.concurrent.TimeUnit; public class HelloServiceExecutor extends ThreadPoolExecutor { public HelloServiceExecutor() { - super(100, 100, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>(), - new NamedThreadFactory("HelloServiceExecutor")); + super( + 100, + 100, + 60, + TimeUnit.SECONDS, + new LinkedBlockingDeque<>(), + new NamedThreadFactory("HelloServiceExecutor")); } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/xml/XmlIsolationTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/xml/XmlIsolationTest.java index 61d5ed3fb3..08297c0a3e 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/xml/XmlIsolationTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/xml/XmlIsolationTest.java @@ -18,21 +18,24 @@ package org.apache.dubbo.config.spring.isolation.spring.xml; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.spring.isolation.spring.BaseTest; -import org.junit.jupiter.api.Test; -import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.Map; +import org.junit.jupiter.api.Test; +import org.springframework.context.support.ClassPathXmlApplicationContext; + public class XmlIsolationTest extends BaseTest { @Test public void test() throws Exception { // start provider app - ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext("META-INF/isolation/dubbo-provider.xml"); + ClassPathXmlApplicationContext providerContext = + new ClassPathXmlApplicationContext("META-INF/isolation/dubbo-provider.xml"); providerContext.start(); // start consumer app - ClassPathXmlApplicationContext consumerContext = new ClassPathXmlApplicationContext("META-INF/isolation/dubbo-consumer.xml"); + ClassPathXmlApplicationContext consumerContext = + new ClassPathXmlApplicationContext("META-INF/isolation/dubbo-consumer.xml"); consumerContext.start(); // getAndSet serviceConfig @@ -52,5 +55,4 @@ public class XmlIsolationTest extends BaseTest { serviceConfig2 = serviceConfigMap.get("org.apache.dubbo.config.spring.ServiceBean#1"); serviceConfig3 = serviceConfigMap.get("org.apache.dubbo.config.spring.ServiceBean#2"); } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue6000/Issue6000Test.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue6000/Issue6000Test.java index b71662cd3b..92b3baeebb 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue6000/Issue6000Test.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue6000/Issue6000Test.java @@ -58,7 +58,7 @@ class Issue6000Test { String result = helloDubbo.sayHello("dubbo"); System.out.println(result); - } catch (Exception e){ + } catch (Exception e) { String s = e.toString(); Assertions.assertTrue(s.contains("No provider available"), s); Assertions.assertTrue(s.contains("org.apache.dubbo.config.spring.api.HelloService:1.0.0"), s); @@ -66,5 +66,4 @@ class Issue6000Test { context.close(); } } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue6252/Issue6252Test.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue6252/Issue6252Test.java index b3c996b36a..d4fcf9e0ed 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue6252/Issue6252Test.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue6252/Issue6252Test.java @@ -60,5 +60,4 @@ class Issue6252Test { context.close(); } } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue7003/Issue7003Test.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue7003/Issue7003Test.java index 84f7cb494c..4872370a77 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue7003/Issue7003Test.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue7003/Issue7003Test.java @@ -24,6 +24,9 @@ import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.Collection; +import java.util.Map; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -34,9 +37,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; -import java.util.Collection; -import java.util.Map; - /** * * Multiple duplicate Dubbo Reference annotations with the same attribute generate only one instance. @@ -66,7 +66,10 @@ class Issue7003Test { Map referenceBeanMap = context.getBeansOfType(ReferenceBean.class); Assertions.assertEquals(1, referenceBeanMap.size()); - Collection> references = ApplicationModel.defaultModel().getDefaultModule().getConfigManager().getReferences(); + Collection> references = ApplicationModel.defaultModel() + .getDefaultModule() + .getConfigManager() + .getReferences(); Assertions.assertEquals(1, references.size()); } finally { @@ -74,13 +77,11 @@ class Issue7003Test { } } - @Component static class ClassA { @DubboReference(group = "demo", version = "1.2.3", check = false) private HelloService helloService; - } @Component @@ -88,6 +89,5 @@ class Issue7003Test { @DubboReference(check = false, version = "1.2.3", group = "demo") private HelloService helloService; - } } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue9172/MultipleConsumerAndProviderTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue9172/MultipleConsumerAndProviderTest.java index 716ba61a81..4e1249296b 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue9172/MultipleConsumerAndProviderTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue9172/MultipleConsumerAndProviderTest.java @@ -53,10 +53,14 @@ class MultipleConsumerAndProviderTest { ModuleConfigManager consumerConfigManager = consumerModuleModel.getConfigManager(); ReferenceConfigBase helloServiceOneConfig = consumerConfigManager.getReference("helloServiceOne"); ReferenceConfigBase demoServiceTwoConfig = consumerConfigManager.getReference("demoServiceTwo"); - Assertions.assertEquals(consumerConfigManager.getConsumer("consumer-one").get(), helloServiceOneConfig.getConsumer()); - Assertions.assertEquals(consumerConfigManager.getConsumer("consumer-two").get(), demoServiceTwoConfig.getConsumer()); - Assertions.assertEquals(consumerConfigManager.getRegistry("registry-one").get(), helloServiceOneConfig.getRegistry()); - Assertions.assertEquals(consumerConfigManager.getRegistry("registry-two").get(), demoServiceTwoConfig.getRegistry()); + Assertions.assertEquals( + consumerConfigManager.getConsumer("consumer-one").get(), helloServiceOneConfig.getConsumer()); + Assertions.assertEquals( + consumerConfigManager.getConsumer("consumer-two").get(), demoServiceTwoConfig.getConsumer()); + Assertions.assertEquals( + consumerConfigManager.getRegistry("registry-one").get(), helloServiceOneConfig.getRegistry()); + Assertions.assertEquals( + consumerConfigManager.getRegistry("registry-two").get(), demoServiceTwoConfig.getRegistry()); HelloService helloServiceOne = consumerContext.getBean("helloServiceOne", HelloService.class); DemoService demoServiceTwo = consumerContext.getBean("demoServiceTwo", DemoService.class); @@ -74,7 +78,6 @@ class MultipleConsumerAndProviderTest { } } - @EnableDubbo(scanBasePackages = "") @PropertySource("classpath:/META-INF/issues/issue9172/consumer.properties") static class ConsumerConfiguration { @@ -84,7 +87,6 @@ class MultipleConsumerAndProviderTest { @DubboReference(consumer = "consumer-two") private DemoService demoServiceTwo; - } @EnableDubbo(scanBasePackages = "") @@ -103,4 +105,4 @@ class MultipleConsumerAndProviderTest { return new DemoServiceImpl(); } } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue9207/ConfigCenterBeanTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue9207/ConfigCenterBeanTest.java index 7d086cd199..3f3777cec2 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue9207/ConfigCenterBeanTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue9207/ConfigCenterBeanTest.java @@ -23,6 +23,16 @@ import org.apache.dubbo.config.spring.SysProps; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.config.spring.util.DubboBeanUtils; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.StringReader; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Collectors; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.BeansException; @@ -34,19 +44,10 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MapPropertySource; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.StringReader; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; -import java.util.stream.Collectors; - class ConfigCenterBeanTest { - private static final String DUBBO_PROPERTIES_FILE = "/META-INF/issues/issue9207/dubbo-properties-in-configcenter.properties"; + private static final String DUBBO_PROPERTIES_FILE = + "/META-INF/issues/issue9207/dubbo-properties-in-configcenter.properties"; private static final String DUBBO_EXTERNAL_CONFIG_KEY = "my-dubbo.properties"; @Test @@ -54,15 +55,17 @@ class ConfigCenterBeanTest { SysProps.setProperty("dubbo.config-center.include-spring-env", "true"); SysProps.setProperty("dubbo.config-center.config-file", DUBBO_EXTERNAL_CONFIG_KEY); - AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ProviderConfiguration.class); + AnnotationConfigApplicationContext applicationContext = + new AnnotationConfigApplicationContext(ProviderConfiguration.class); try { - ConfigManager configManager = DubboBeanUtils.getApplicationModel(applicationContext).getApplicationConfigManager(); + ConfigManager configManager = + DubboBeanUtils.getApplicationModel(applicationContext).getApplicationConfigManager(); Collection configCenters = configManager.getConfigCenters(); Assertions.assertEquals(1, configCenters.size()); ConfigCenterConfig cc = configCenters.stream().findFirst().get(); Assertions.assertFalse(cc.getExternalConfiguration().isEmpty()); - Assertions.assertTrue( cc instanceof ConfigCenterBean); + Assertions.assertTrue(cc instanceof ConfigCenterBean); // check loaded external config String content = readContent(DUBBO_PROPERTIES_FILE); @@ -76,7 +79,6 @@ class ConfigCenterBeanTest { applicationContext.close(); } } - } @EnableDubbo(scanBasePackages = "") @@ -93,17 +95,18 @@ class ConfigCenterBeanTest { Map dubboProperties = new HashMap<>(); String content = readContent(DUBBO_PROPERTIES_FILE); dubboProperties.put(DUBBO_EXTERNAL_CONFIG_KEY, content); - MapPropertySource dubboPropertySource = new MapPropertySource("dubbo external config", dubboProperties); + MapPropertySource dubboPropertySource = + new MapPropertySource("dubbo external config", dubboProperties); environment.getPropertySources().addLast(dubboPropertySource); } }; } - } private static String readContent(String file) { - BufferedReader reader = new BufferedReader(new InputStreamReader(ConfigCenterBeanTest.class.getResourceAsStream(file))); + BufferedReader reader = + new BufferedReader(new InputStreamReader(ConfigCenterBeanTest.class.getResourceAsStream(file))); String content = reader.lines().collect(Collectors.joining("\n")); return content; } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/metrics/SpringBootConfigMetricsTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/metrics/SpringBootConfigMetricsTest.java index 3f667bd65e..8f7fc61e7f 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/metrics/SpringBootConfigMetricsTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/metrics/SpringBootConfigMetricsTest.java @@ -20,6 +20,7 @@ import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -32,29 +33,26 @@ import org.springframework.context.annotation.Configuration; import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS; @SpringBootTest( - properties = { - "dubbo.application.NAME = dubbo-demo-application", - "dubbo.module.name = dubbo-demo-module", - "dubbo.registry.address = zookeeper://localhost:2181", - "dubbo.protocol.name=dubbo", - "dubbo.protocol.port=20880", - "dubbo.metrics.protocol=prometheus", - "dubbo.metrics.export-service-protocol=tri", - "dubbo.metrics.export-service-port=9999", - "dubbo.metrics.enable-jvm=true", - "dubbo.metrics.prometheus.exporter.enabled=true", - "dubbo.metrics.prometheus.exporter.enable-http-service-discovery=true", - "dubbo.metrics.prometheus.exporter.http-service-discovery-url=localhost:8080", - "dubbo.metrics.aggregation.enabled=true", - "dubbo.metrics.aggregation.bucket-num=5", - "dubbo.metrics.aggregation.time-window-seconds=120", - "dubbo.metrics.histogram.enabled=true", - "dubbo.metadata-report.address=${zookeeper.connection.address.2}" - }, - classes = { - SpringBootConfigMetricsTest.class - } -) + properties = { + "dubbo.application.NAME = dubbo-demo-application", + "dubbo.module.name = dubbo-demo-module", + "dubbo.registry.address = zookeeper://localhost:2181", + "dubbo.protocol.name=dubbo", + "dubbo.protocol.port=20880", + "dubbo.metrics.protocol=prometheus", + "dubbo.metrics.export-service-protocol=tri", + "dubbo.metrics.export-service-port=9999", + "dubbo.metrics.enable-jvm=true", + "dubbo.metrics.prometheus.exporter.enabled=true", + "dubbo.metrics.prometheus.exporter.enable-http-service-discovery=true", + "dubbo.metrics.prometheus.exporter.http-service-discovery-url=localhost:8080", + "dubbo.metrics.aggregation.enabled=true", + "dubbo.metrics.aggregation.bucket-num=5", + "dubbo.metrics.aggregation.time-window-seconds=120", + "dubbo.metrics.histogram.enabled=true", + "dubbo.metadata-report.address=${zookeeper.connection.address.2}" + }, + classes = {SpringBootConfigMetricsTest.class}) @Configuration @ComponentScan @EnableDubbo @@ -79,15 +77,15 @@ public class SpringBootConfigMetricsTest { Assertions.assertEquals(PROTOCOL_PROMETHEUS, metricsConfig.getProtocol()); Assertions.assertTrue(metricsConfig.getEnableJvm()); - Assertions.assertEquals("tri",metricsConfig.getExportServiceProtocol()); + Assertions.assertEquals("tri", metricsConfig.getExportServiceProtocol()); Assertions.assertEquals(9999, metricsConfig.getExportServicePort()); Assertions.assertTrue(metricsConfig.getPrometheus().getExporter().getEnabled()); Assertions.assertTrue(metricsConfig.getPrometheus().getExporter().getEnableHttpServiceDiscovery()); - Assertions.assertEquals("localhost:8080", metricsConfig.getPrometheus().getExporter().getHttpServiceDiscoveryUrl()); + Assertions.assertEquals( + "localhost:8080", metricsConfig.getPrometheus().getExporter().getHttpServiceDiscoveryUrl()); Assertions.assertEquals(5, metricsConfig.getAggregation().getBucketNum()); Assertions.assertEquals(120, metricsConfig.getAggregation().getTimeWindowSeconds()); Assertions.assertTrue(metricsConfig.getAggregation().getEnabled()); Assertions.assertTrue(metricsConfig.getHistogram().getEnabled()); } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer/PropertyConfigurerTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer/PropertyConfigurerTest.java index 77e757c84d..bab9652a35 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer/PropertyConfigurerTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer/PropertyConfigurerTest.java @@ -20,6 +20,8 @@ import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; +import java.net.InetSocketAddress; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -31,8 +33,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.context.support.ClassPathXmlApplicationContext; -import java.net.InetSocketAddress; - class PropertyConfigurerTest { @BeforeAll @@ -48,25 +48,29 @@ class PropertyConfigurerTest { @Test void testEarlyInit() { - ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext("org/apache/dubbo/config/spring/propertyconfigurer/provider/dubbo-provider.xml"); + ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext( + "org/apache/dubbo/config/spring/propertyconfigurer/provider/dubbo-provider.xml"); try { providerContext.start(); - // Resolve placeholder by PropertyPlaceholderConfigurer in dubbo-consumer.xml, without import property source. - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfiguration.class); + // Resolve placeholder by PropertyPlaceholderConfigurer in dubbo-consumer.xml, without import property + // source. + AnnotationConfigApplicationContext context = + new AnnotationConfigApplicationContext(ConsumerConfiguration.class); context.start(); HelloService service = (HelloService) context.getBean("demoService"); String result = service.sayHello("world"); System.out.println("result: " + result); - Assertions.assertEquals("Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); + Assertions.assertEquals( + "Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), + result); context.close(); } finally { providerContext.close(); } - } @Configuration @@ -79,4 +83,4 @@ class PropertyConfigurerTest { return new DemoBeanFactoryPostProcessor(service); } } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer2/PropertySourcesConfigurerTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer2/PropertySourcesConfigurerTest.java index 4dcb6b29b9..dee638e145 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer2/PropertySourcesConfigurerTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer2/PropertySourcesConfigurerTest.java @@ -21,6 +21,8 @@ import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.config.spring.propertyconfigurer.consumer.DemoBeanFactoryPostProcessor; +import java.net.InetSocketAddress; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -32,8 +34,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.context.support.ClassPathXmlApplicationContext; -import java.net.InetSocketAddress; - class PropertySourcesConfigurerTest { @BeforeAll @@ -49,19 +49,24 @@ class PropertySourcesConfigurerTest { @Test void testEarlyInit() { - ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext("org/apache/dubbo/config/spring/propertyconfigurer/provider/dubbo-provider.xml"); + ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext( + "org/apache/dubbo/config/spring/propertyconfigurer/provider/dubbo-provider.xml"); try { providerContext.start(); // consumer app - // Resolve placeholder by PropertySourcesPlaceholderConfigurer in dubbo-consumer.xml, without import property source. - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfiguration.class); + // Resolve placeholder by PropertySourcesPlaceholderConfigurer in dubbo-consumer.xml, without import + // property source. + AnnotationConfigApplicationContext context = + new AnnotationConfigApplicationContext(ConsumerConfiguration.class); try { context.start(); HelloService service = (HelloService) context.getBean("demoService"); String result = service.sayHello("world"); System.out.println("result: " + result); - Assertions.assertEquals("Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); + Assertions.assertEquals( + "Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), + result); } finally { context.close(); } @@ -81,4 +86,4 @@ class PropertySourcesConfigurerTest { return new DemoBeanFactoryPostProcessor(service); } } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer3/PropertySourcesInJavaConfigTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer3/PropertySourcesInJavaConfigTest.java index b8128b3044..f7556f57f2 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer3/PropertySourcesInJavaConfigTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer3/PropertySourcesInJavaConfigTest.java @@ -21,6 +21,9 @@ import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.config.spring.propertyconfigurer.consumer.DemoBeanFactoryPostProcessor; +import java.io.IOException; +import java.net.InetSocketAddress; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -35,14 +38,13 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.io.ClassPathResource; -import java.io.IOException; -import java.net.InetSocketAddress; - class PropertySourcesInJavaConfigTest { - private static final String SCAN_PACKAGE_NAME = "org.apache.dubbo.config.spring.propertyconfigurer.consumer3.notexist"; + private static final String SCAN_PACKAGE_NAME = + "org.apache.dubbo.config.spring.propertyconfigurer.consumer3.notexist"; private static final String PACKAGE_PATH = "/org/apache/dubbo/config/spring/propertyconfigurer/consumer3"; - private static final String PROVIDER_CONFIG_PATH = "org/apache/dubbo/config/spring/propertyconfigurer/provider/dubbo-provider.xml"; + private static final String PROVIDER_CONFIG_PATH = + "org/apache/dubbo/config/spring/propertyconfigurer/provider/dubbo-provider.xml"; @BeforeEach public void setUp() throws Exception { @@ -67,7 +69,8 @@ class PropertySourcesInJavaConfigTest { providerContext.start(); // Resolve placeholder by import property sources - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfiguration.class, ImportPropertyConfiguration.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( + ConsumerConfiguration.class, ImportPropertyConfiguration.class); try { // expect auto create PropertySourcesPlaceholderConfigurer bean String[] beanNames = context.getBeanNamesForType(PropertySourcesPlaceholderConfigurer.class); @@ -77,7 +80,9 @@ class PropertySourcesInJavaConfigTest { HelloService service = (HelloService) context.getBean("demoService"); String result = service.sayHello("world"); System.out.println("result: " + result); - Assertions.assertEquals("Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); + Assertions.assertEquals( + "Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), + result); } finally { context.close(); } @@ -95,7 +100,8 @@ class PropertySourcesInJavaConfigTest { providerContext.start(); // Resolve placeholder by custom PropertySourcesPlaceholderConfigurer bean - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfiguration.class, PropertyBeanConfiguration.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( + ConsumerConfiguration.class, PropertyBeanConfiguration.class); try { // expect using custom PropertySourcesPlaceholderConfigurer bean String[] beanNames = context.getBeanNamesForType(PropertySourcesPlaceholderConfigurer.class); @@ -105,7 +111,9 @@ class PropertySourcesInJavaConfigTest { HelloService service = (HelloService) context.getBean("demoService"); String result = service.sayHello("world"); System.out.println("result: " + result); - Assertions.assertEquals("Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); + Assertions.assertEquals( + "Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), + result); } finally { context.close(); } @@ -128,9 +136,7 @@ class PropertySourcesInJavaConfigTest { @Configuration @PropertySource("classpath:" + PACKAGE_PATH + "/app.properties") - static class ImportPropertyConfiguration { - - } + static class ImportPropertyConfiguration {} @Configuration static class PropertyBeanConfiguration { @@ -149,4 +155,4 @@ class PropertySourcesInJavaConfigTest { return propertyValue; } } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/provider/HelloServiceImpl.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/provider/HelloServiceImpl.java index ef58855ceb..c1b6809245 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/provider/HelloServiceImpl.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/provider/HelloServiceImpl.java @@ -27,13 +27,14 @@ public class HelloServiceImpl implements HelloService { @Override public String sayHello(String name) { - logger.info("Hello " + name + ", request from consumer: " + RpcContext.getContext().getRemoteAddress()); + logger.info("Hello " + name + ", request from consumer: " + + RpcContext.getContext().getRemoteAddress()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } - return "Hello " + name + ", response from provider: " + RpcContext.getContext().getLocalAddress(); + return "Hello " + name + ", response from provider: " + + RpcContext.getContext().getLocalAddress(); } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/DubboConfigBeanInitializerTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/DubboConfigBeanInitializerTest.java index 9afc815496..97d1df45c1 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/DubboConfigBeanInitializerTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/DubboConfigBeanInitializerTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config.spring.reference; - import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.api.HelloService; @@ -24,6 +23,9 @@ import org.apache.dubbo.config.spring.context.DubboConfigBeanInitializer; import org.apache.dubbo.config.spring.context.annotation.provider.ProviderConfiguration; import org.apache.dubbo.config.spring.util.DubboBeanUtils; +import java.util.Arrays; +import java.util.List; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -40,22 +42,16 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.util.Arrays; -import java.util.List; - /** * Tests for {@link org.apache.dubbo.config.spring.context.DubboConfigBeanInitializer} */ @ExtendWith(SpringExtension.class) @ContextConfiguration( - classes = { - DubboConfigBeanInitializerTest.class, - DubboConfigBeanInitializerTest.AppConfiguration.class, - }) -@TestPropertySource(properties = { - "dubbo.protocol.port=-1", - "dubbo.registry.address=${zookeeper.connection.address}" -}) + classes = { + DubboConfigBeanInitializerTest.class, + DubboConfigBeanInitializerTest.AppConfiguration.class, + }) +@TestPropertySource(properties = {"dubbo.protocol.port=-1", "dubbo.registry.address=${zookeeper.connection.address}"}) @EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) class DubboConfigBeanInitializerTest { @@ -70,7 +66,6 @@ class DubboConfigBeanInitializerTest { DubboBootstrap.reset(); } - @Autowired private FooService fooService; @@ -97,17 +92,19 @@ class DubboConfigBeanInitializerTest { // Import BusinessConfig first, make sure FooService bean is register early, // expect dubbo config beans are initialized before FooService bean @Import({BusinessConfig.class, ConsumerConfig.class, ProviderConfiguration.class}) - static class AppConfiguration { - - } + static class AppConfiguration {} @Configuration static class BusinessConfig { @Bean public FooService fooService(ApplicationContext applicationContext) { // Dubbo config beans should be initialized at DubboConfigInitializer, before init FooService bean - Assertions.assertTrue(DubboBeanUtils.getModuleModel(applicationContext).getDeployer().isInitialized()); - Assertions.assertTrue(DubboBeanUtils.getApplicationModel(applicationContext).getDeployer().isInitialized()); + Assertions.assertTrue(DubboBeanUtils.getModuleModel(applicationContext) + .getDeployer() + .isInitialized()); + Assertions.assertTrue(DubboBeanUtils.getApplicationModel(applicationContext) + .getDeployer() + .isInitialized()); Assertions.assertTrue(DubboBootstrap.getInstance().isInitialized()); return new FooService(); } @@ -123,4 +120,4 @@ class DubboConfigBeanInitializerTest { @Autowired private HelloService helloService; } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/ReferenceKeyTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/ReferenceKeyTest.java index 69fe8211b2..f2a0537b1c 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/ReferenceKeyTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/ReferenceKeyTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config.spring.reference; -import com.alibaba.spring.util.AnnotationUtils; import org.apache.dubbo.config.annotation.Argument; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.annotation.Method; @@ -29,6 +28,15 @@ import org.apache.dubbo.config.spring.api.ProvidedByDemoService2; import org.apache.dubbo.config.spring.api.ProvidedByDemoService3; import org.apache.dubbo.config.spring.impl.DemoServiceImpl; import org.apache.dubbo.config.spring.impl.HelloServiceImpl; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.alibaba.spring.util.AnnotationUtils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; @@ -41,13 +49,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.core.annotation.AnnotationAttributes; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - class ReferenceKeyTest { @BeforeEach @@ -63,15 +64,16 @@ class ReferenceKeyTest { String helloService3 = getReferenceKey("helloService3"); String helloService4 = getReferenceKey("helloService4"); - Assertions.assertEquals("ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(methods=[{name=sayHello, retries=0, timeout=100}])", + Assertions.assertEquals( + "ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(methods=[{name=sayHello, retries=0, timeout=100}])", helloService1); Assertions.assertEquals(helloService1, helloService2); - Assertions.assertEquals("ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(methods=[{arguments=[{callback=true, index=0}], name=sayHello, timeout=100}])", + Assertions.assertEquals( + "ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(methods=[{arguments=[{callback=true, index=0}], name=sayHello, timeout=100}])", helloService3); Assertions.assertEquals(helloService3, helloService4); - String helloServiceWithArray0 = getReferenceKey("helloServiceWithArray0"); String helloServiceWithArray1 = getReferenceKey("helloServiceWithArray1"); String helloServiceWithArray2 = getReferenceKey("helloServiceWithArray2"); @@ -82,57 +84,66 @@ class ReferenceKeyTest { String helloServiceWithArgument1 = getReferenceKey("helloServiceWithArgument1"); String helloServiceWithArgument2 = getReferenceKey("helloServiceWithArgument2"); - Assertions.assertEquals("ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(check=false,filter=[echo],parameters={a=2, b=1})", + Assertions.assertEquals( + "ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(check=false,filter=[echo],parameters={a=2, b=1})", helloServiceWithArray0); Assertions.assertNotEquals(helloServiceWithArray0, helloServiceWithArray1); - Assertions.assertEquals("ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(check=false,filter=[echo],parameters={a=1, b=2})", + Assertions.assertEquals( + "ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(check=false,filter=[echo],parameters={a=1, b=2})", helloServiceWithArray1); Assertions.assertEquals(helloServiceWithArray1, helloServiceWithArray2); - Assertions.assertEquals("ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(check=false,filter=[echo],methods=[{name=sayHello, parameters={c=1, d=2}, timeout=100}],parameters={a=1, b=2})", + Assertions.assertEquals( + "ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(check=false,filter=[echo],methods=[{name=sayHello, parameters={c=1, d=2}, timeout=100}],parameters={a=1, b=2})", helloServiceWithMethod1); Assertions.assertEquals(helloServiceWithMethod1, helloServiceWithMethod2); - Assertions.assertEquals("ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(check=false,filter=[echo],methods=[{arguments=[{callback=true, type=String}, {type=int}], name=sayHello, timeout=100}],parameters={a=1, b=2})", + Assertions.assertEquals( + "ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(check=false,filter=[echo],methods=[{arguments=[{callback=true, type=String}, {type=int}], name=sayHello, timeout=100}],parameters={a=1, b=2})", helloServiceWithArgument1); Assertions.assertEquals(helloServiceWithArgument1, helloServiceWithArgument2); - } - @Test void testConfig() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfiguration.class); + AnnotationConfigApplicationContext context = + new AnnotationConfigApplicationContext(ConsumerConfiguration.class); context.start(); Map referenceBeanMap = context.getBeansOfType(ReferenceBean.class); Assertions.assertEquals(2, referenceBeanMap.size()); - Assertions.assertEquals("ReferenceBean:demo/org.apache.dubbo.config.spring.api.DemoService:1.2.3(consumer=my-consumer,init=false,methods=[{arguments=[{callback=true, index=0}], name=sayName, parameters={access-token=my-token, b=2}, retries=0}],parameters={connec.timeout=1000},protocol=dubbo,registryIds=my-registry,scope=remote,timeout=1000,url=dubbo://127.0.0.1:20813)", + Assertions.assertEquals( + "ReferenceBean:demo/org.apache.dubbo.config.spring.api.DemoService:1.2.3(consumer=my-consumer,init=false,methods=[{arguments=[{callback=true, index=0}], name=sayName, parameters={access-token=my-token, b=2}, retries=0}],parameters={connec.timeout=1000},protocol=dubbo,registryIds=my-registry,scope=remote,timeout=1000,url=dubbo://127.0.0.1:20813)", referenceBeanMap.get("&demoService").getKey()); - } @Test @Disabled("support multi reference config") public void testConfig2() { try { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfiguration2.class); + AnnotationConfigApplicationContext context = + new AnnotationConfigApplicationContext(ConsumerConfiguration2.class); context.start(); Map referenceBeanMap = context.getBeansOfType(ReferenceBean.class); Assertions.fail("Reference bean check failed"); } catch (BeansException e) { String msg = getStackTrace(e); - Assertions.assertTrue(msg.contains("Found multiple ReferenceConfigs with unique service name [demo/org.apache.dubbo.config.spring.api.DemoService:1.2.3]"), msg); -// Assertions.assertTrue(msg.contains("Already exists another reference bean with the same bean name and type but difference attributes"), msg); -// Assertions.assertTrue(msg.contains("ConsumerConfiguration2.demoService"), msg); + Assertions.assertTrue( + msg.contains( + "Found multiple ReferenceConfigs with unique service name [demo/org.apache.dubbo.config.spring.api.DemoService:1.2.3]"), + msg); + // Assertions.assertTrue(msg.contains("Already exists another reference bean with the same bean + // name and type but difference attributes"), msg); + // Assertions.assertTrue(msg.contains("ConsumerConfiguration2.demoService"), msg); } } @Test void testConfig3() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfiguration3.class); + AnnotationConfigApplicationContext context = + new AnnotationConfigApplicationContext(ConsumerConfiguration3.class); context.start(); Map referenceBeanMap = context.getBeansOfType(ReferenceBean.class); Assertions.assertEquals(3, referenceBeanMap.size()); @@ -163,7 +174,8 @@ class ReferenceKeyTest { @Test void testConfig5() { try { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfiguration5.class); + AnnotationConfigApplicationContext context = + new AnnotationConfigApplicationContext(ConsumerConfiguration5.class); context.start(); Map referenceBeanMap = context.getBeansOfType(ReferenceBean.class); Assertions.fail("Reference bean check failed"); @@ -175,12 +187,14 @@ class ReferenceKeyTest { @Test void testConfig6() { try { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfiguration6.class); + AnnotationConfigApplicationContext context = + new AnnotationConfigApplicationContext(ConsumerConfiguration6.class); context.start(); Map referenceBeanMap = context.getBeansOfType(ReferenceBean.class); Assertions.fail("Reference bean check failed"); } catch (BeansException e) { - String checkString = "Already exists another bean definition with the same bean name [demoService], but cannot rename the reference bean name"; + String checkString = + "Already exists another bean definition with the same bean name [demoService], but cannot rename the reference bean name"; String msg = getStackTrace(e); Assertions.assertTrue(msg.contains(checkString), msg); Assertions.assertTrue(msg.contains("ConsumerConfiguration6.demoService"), msg); @@ -188,25 +202,27 @@ class ReferenceKeyTest { } @Test - void testConfig7() throws Exception{ + void testConfig7() throws Exception { String fieldName1 = "providedByDemoService1"; String fieldName2 = "providedByDemoService2"; String fieldName3 = "providedByDemoServiceInterface"; String fieldName4 = "multiProvidedByDemoServiceInterface"; - Map attributes1= getReferenceAttributes(fieldName1); - Map attributes2= getReferenceAttributes(fieldName2); - Map attributes3= getReferenceAttributes(fieldName3); - Map attributes4= getReferenceAttributes(fieldName4); + Map attributes1 = getReferenceAttributes(fieldName1); + Map attributes2 = getReferenceAttributes(fieldName2); + Map attributes3 = getReferenceAttributes(fieldName3); + Map attributes4 = getReferenceAttributes(fieldName4); - Assertions.assertEquals("provided-demo-service-interface", ((String[])attributes1.get("providedBy"))[0]); - Assertions.assertEquals("provided-demo-service1", ((String[])attributes1.get("providedBy"))[1]); + Assertions.assertEquals("provided-demo-service-interface", ((String[]) attributes1.get("providedBy"))[0]); + Assertions.assertEquals("provided-demo-service1", ((String[]) attributes1.get("providedBy"))[1]); Assertions.assertEquals("provided-demo-service2", ((String[]) attributes2.get("providedBy"))[0]); Assertions.assertEquals("provided-demo-service-interface", ((String[]) attributes3.get("providedBy"))[0]); String[] serviceName4 = (String[]) attributes4.get("providedBy"); List expectServices = new ArrayList<>(); expectServices.add("provided-demo-service-interface1"); expectServices.add("provided-demo-service-interface2"); - Assertions.assertTrue(serviceName4.length == 2 && expectServices.contains(serviceName4[0]) && expectServices.contains(serviceName4[1])); + Assertions.assertTrue(serviceName4.length == 2 + && expectServices.contains(serviceName4[0]) + && expectServices.contains(serviceName4[1])); Assertions.assertEquals("provided-demo-service-interface", ((String[]) attributes3.get("providedBy"))[0]); } @@ -218,14 +234,16 @@ class ReferenceKeyTest { private String getReferenceKey(String fieldName) throws NoSuchFieldException { Field field = ReferenceConfiguration.class.getDeclaredField(fieldName); - AnnotationAttributes attributes = AnnotationUtils.getAnnotationAttributes(field, DubboReference.class, null, true); + AnnotationAttributes attributes = + AnnotationUtils.getAnnotationAttributes(field, DubboReference.class, null, true); ReferenceBeanSupport.convertReferenceProps(attributes, field.getType()); return ReferenceBeanSupport.generateReferenceKey(attributes, null); } private Map getReferenceAttributes(String fieldName) throws NoSuchFieldException { Field field = ConsumerConfiguration7.class.getDeclaredField(fieldName); - AnnotationAttributes attributes = AnnotationUtils.getAnnotationAttributes(field, DubboReference.class, null, true); + AnnotationAttributes attributes = + AnnotationUtils.getAnnotationAttributes(field, DubboReference.class, null, true); ReferenceBeanSupport.convertReferenceProps(attributes, field.getType()); return attributes; } @@ -237,76 +255,152 @@ class ReferenceKeyTest { @DubboReference(methods = @Method(timeout = 100, name = "sayHello", retries = 0)) private HelloService helloService2; - @DubboReference(methods = @Method(name = "sayHello", timeout = 100, arguments = @Argument(index = 0, callback = true))) + @DubboReference( + methods = @Method(name = "sayHello", timeout = 100, arguments = @Argument(index = 0, callback = true))) private HelloService helloService3; - @DubboReference(methods = @Method(arguments = @Argument(callback = true, index = 0), name = "sayHello", timeout = 100)) + @DubboReference( + methods = @Method(arguments = @Argument(callback = true, index = 0), name = "sayHello", timeout = 100)) private HelloService helloService4; // Instance 1 - @DubboReference(check = false, parameters = {"a", "2", "b", "1"}, filter = {"echo"}) + @DubboReference( + check = false, + parameters = {"a", "2", "b", "1"}, + filter = {"echo"}) private HelloService helloServiceWithArray0; // Instance 2 - @DubboReference(check = false, parameters = {"a=1", "b", "2"}, filter = {"echo"}) + @DubboReference( + check = false, + parameters = {"a=1", "b", "2"}, + filter = {"echo"}) private HelloService helloServiceWithArray1; - @DubboReference(parameters = {"b", "2", "a", "1"}, filter = {"echo"}, check = false) + @DubboReference( + parameters = {"b", "2", "a", "1"}, + filter = {"echo"}, + check = false) private HelloService helloServiceWithArray2; // Instance 3 - @DubboReference(check = false, parameters = {"a", "1", "b", "2"}, filter = {"echo"}, methods = {@Method(parameters = {"d", "2", "c", "1"}, name = "sayHello", timeout = 100)}) + @DubboReference( + check = false, + parameters = {"a", "1", "b", "2"}, + filter = {"echo"}, + methods = { + @Method( + parameters = {"d", "2", "c", "1"}, + name = "sayHello", + timeout = 100) + }) private HelloService helloServiceWithMethod1; - @DubboReference(parameters = {"b=2", "a=1"}, filter = {"echo"}, check = false, methods = {@Method(name = "sayHello", timeout = 100, parameters = {"c", "1", "d", "2"})}) + @DubboReference( + parameters = {"b=2", "a=1"}, + filter = {"echo"}, + check = false, + methods = { + @Method( + name = "sayHello", + timeout = 100, + parameters = {"c", "1", "d", "2"}) + }) private HelloService helloServiceWithMethod2; // Instance 4 - @DubboReference(parameters = {"a", "1", "b", "2"}, filter = {"echo"}, methods = {@Method(name = "sayHello", arguments = {@Argument(callback = true, type = "String"), @Argument(callback = false, type = "int")}, timeout = 100)}, check = false) + @DubboReference( + parameters = {"a", "1", "b", "2"}, + filter = {"echo"}, + methods = { + @Method( + name = "sayHello", + arguments = { + @Argument(callback = true, type = "String"), + @Argument(callback = false, type = "int") + }, + timeout = 100) + }, + check = false) private HelloService helloServiceWithArgument1; - @DubboReference(check = false, filter = {"echo"}, parameters = {"b", "2", "a", "1"}, methods = {@Method(name = "sayHello", timeout = 100, arguments = {@Argument(callback = false, type = "int"), @Argument(callback = true, type = "String")})}) + @DubboReference( + check = false, + filter = {"echo"}, + parameters = {"b", "2", "a", "1"}, + methods = { + @Method( + name = "sayHello", + timeout = 100, + arguments = { + @Argument(callback = false, type = "int"), + @Argument(callback = true, type = "String") + }) + }) private HelloService helloServiceWithArgument2; } @Configuration - @ImportResource({"classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml", - "classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml"}) + @ImportResource({ + "classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml", + "classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml" + }) static class ConsumerConfiguration { - //both are reference beans, same as xml config - @DubboReference(group = "demo", version = "1.2.3", consumer="my-consumer", init=false, - methods={@Method(arguments={@Argument(callback=true, index=0)}, name="sayName", parameters={"access-token", "my-token", "b", "2"}, retries=0)}, - parameters={"connec.timeout", "1000"}, - protocol="dubbo", - registry="my-registry", - scope="remote", - timeout=1000, - url="dubbo://127.0.0.1:20813") + // both are reference beans, same as xml config + @DubboReference( + group = "demo", + version = "1.2.3", + consumer = "my-consumer", + init = false, + methods = { + @Method( + arguments = {@Argument(callback = true, index = 0)}, + name = "sayName", + parameters = {"access-token", "my-token", "b", "2"}, + retries = 0) + }, + parameters = {"connec.timeout", "1000"}, + protocol = "dubbo", + registry = "my-registry", + scope = "remote", + timeout = 1000, + url = "dubbo://127.0.0.1:20813") private DemoService demoService; } - @Configuration - @ImportResource({"classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml", - "classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml"}) + @ImportResource({ + "classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml", + "classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml" + }) static class ConsumerConfiguration2 { - //both are reference beans, same bean name and type, but difference attributes from xml config - @DubboReference(group = "demo", version = "1.2.3", consumer="my-consumer", init=false, - scope="local", - timeout=100) + // both are reference beans, same bean name and type, but difference attributes from xml config + @DubboReference( + group = "demo", + version = "1.2.3", + consumer = "my-consumer", + init = false, + scope = "local", + timeout = 100) private DemoService demoService; } @Configuration - @ImportResource({"classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml", - "classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml"}) + @ImportResource({ + "classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml", + "classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml" + }) static class ConsumerConfiguration3 { - //both are reference beans, same bean name but difference interface type - @DubboReference(group = "demo", version = "1.2.4", consumer="my-consumer", init=false, - url="dubbo://127.0.0.1:20813") + // both are reference beans, same bean name but difference interface type + @DubboReference( + group = "demo", + version = "1.2.4", + consumer = "my-consumer", + init = false, + url = "dubbo://127.0.0.1:20813") private HelloService demoService; @Autowired @@ -314,11 +408,13 @@ class ReferenceKeyTest { } @Configuration - @ImportResource({"classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml", - "classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml"}) + @ImportResource({ + "classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml", + "classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml" + }) static class ConsumerConfiguration4 { - //not reference bean: same bean name and type + // not reference bean: same bean name and type @Bean public DemoService demoService() { return new DemoServiceImpl(); @@ -326,11 +422,13 @@ class ReferenceKeyTest { } @Configuration - @ImportResource({"classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml", - "classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml"}) + @ImportResource({ + "classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml", + "classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml" + }) static class ConsumerConfiguration5 { - //not reference bean: same bean name but difference type + // not reference bean: same bean name but difference type @Bean public HelloService demoService() { return new HelloServiceImpl(); @@ -338,23 +436,30 @@ class ReferenceKeyTest { } @Configuration - @ImportResource({"classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml", - "classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml"}) + @ImportResource({ + "classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml", + "classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml" + }) static class ConsumerConfiguration6 { - //both are reference beans, same bean name but difference interface type, fixed bean name - @DubboReference(id = "demoService", group = "demo", version = "1.2.3", consumer="my-consumer", init=false, - url="dubbo://127.0.0.1:20813") + // both are reference beans, same bean name but difference interface type, fixed bean name + @DubboReference( + id = "demoService", + group = "demo", + version = "1.2.3", + consumer = "my-consumer", + init = false, + url = "dubbo://127.0.0.1:20813") private HelloService demoService; -// @Autowired -// private HelloService helloService; + // @Autowired + // private HelloService helloService; } @Configuration static class ConsumerConfiguration7 { - //both are reference beans, same as xml config + // both are reference beans, same as xml config @DubboReference(providedBy = "provided-demo-service1") private ProvidedByDemoService1 providedByDemoService1; @@ -370,5 +475,4 @@ class ReferenceKeyTest { @DubboReference private ProvidedByDemoService3 multiProvidedByDemoServiceInterface; } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/javaconfig/JavaConfigReferenceBeanTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/javaconfig/JavaConfigReferenceBeanTest.java index 2d020d8c8b..9e472f5a5a 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/javaconfig/JavaConfigReferenceBeanTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/javaconfig/JavaConfigReferenceBeanTest.java @@ -29,6 +29,13 @@ import org.apache.dubbo.config.spring.reference.ReferenceBeanBuilder; import org.apache.dubbo.rpc.service.GenericException; import org.apache.dubbo.rpc.service.GenericService; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -39,13 +46,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.lang.reflect.Modifier; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - class JavaConfigReferenceBeanTest { @BeforeEach @@ -60,8 +60,8 @@ class JavaConfigReferenceBeanTest { @Test void testAnnotationAtField() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(CommonConfig.class, - AnnotationAtFieldConfiguration.class); + AnnotationConfigApplicationContext context = + new AnnotationConfigApplicationContext(CommonConfig.class, AnnotationAtFieldConfiguration.class); try { Map helloServiceMap = context.getBeansOfType(HelloService.class); @@ -85,12 +85,15 @@ class JavaConfigReferenceBeanTest { public void testAnnotationAtField2() { AnnotationConfigApplicationContext context = null; try { - context = new AnnotationConfigApplicationContext(CommonConfig.class, - AnnotationAtFieldConfiguration.class, AnnotationAtFieldConfiguration2.class); + context = new AnnotationConfigApplicationContext( + CommonConfig.class, AnnotationAtFieldConfiguration.class, AnnotationAtFieldConfiguration2.class); Assertions.fail("Should not load duplicated @DubboReference fields"); } catch (Exception e) { String msg = getStackTrace(e); - Assertions.assertTrue(msg.contains("Found multiple ReferenceConfigs with unique service name [demo/org.apache.dubbo.config.spring.api.HelloService]"), msg); + Assertions.assertTrue( + msg.contains( + "Found multiple ReferenceConfigs with unique service name [demo/org.apache.dubbo.config.spring.api.HelloService]"), + msg); } finally { if (context != null) { context.close(); @@ -102,8 +105,7 @@ class JavaConfigReferenceBeanTest { void testLazyProxy1() { AnnotationConfigApplicationContext context = null; try { - context = new AnnotationConfigApplicationContext(CommonConfig.class, - LazyProxyConfiguration1.class); + context = new AnnotationConfigApplicationContext(CommonConfig.class, LazyProxyConfiguration1.class); HelloService helloServiceClient = context.getBean("helloServiceClient", HelloService.class); Assertions.assertNotNull(helloServiceClient); Assertions.assertInstanceOf(HelloService.class, helloServiceClient); @@ -121,8 +123,7 @@ class JavaConfigReferenceBeanTest { void testLazyProxy2() { AnnotationConfigApplicationContext context = null; try { - context = new AnnotationConfigApplicationContext(CommonConfig.class, - LazyProxyConfiguration2.class); + context = new AnnotationConfigApplicationContext(CommonConfig.class, LazyProxyConfiguration2.class); HelloService helloServiceClient = context.getBean("helloServiceClient", HelloService.class); Assertions.assertNotNull(helloServiceClient); Assertions.assertInstanceOf(HelloService.class, helloServiceClient); @@ -140,8 +141,7 @@ class JavaConfigReferenceBeanTest { void testLazyProxy3() { AnnotationConfigApplicationContext context = null; try { - context = new AnnotationConfigApplicationContext(CommonConfig.class, - LazyProxyConfiguration3.class); + context = new AnnotationConfigApplicationContext(CommonConfig.class, LazyProxyConfiguration3.class); HelloService helloServiceClient = context.getBean("helloServiceClient", HelloService.class); Assertions.assertNotNull(helloServiceClient); Assertions.assertInstanceOf(HelloService.class, helloServiceClient); @@ -163,8 +163,8 @@ class JavaConfigReferenceBeanTest { @Test void testAnnotationBean() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(CommonConfig.class, - AnnotationBeanConfiguration.class); + AnnotationConfigApplicationContext context = + new AnnotationConfigApplicationContext(CommonConfig.class, AnnotationBeanConfiguration.class); try { Map helloServiceMap = context.getBeansOfType(HelloService.class); @@ -185,8 +185,8 @@ class JavaConfigReferenceBeanTest { @Test void testGenericServiceAnnotationBean() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(CommonConfig.class, - GenericServiceAnnotationBeanConfiguration.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( + CommonConfig.class, GenericServiceAnnotationBeanConfiguration.class); try { Map helloServiceMap = context.getBeansOfType(HelloService.class); @@ -203,27 +203,31 @@ class JavaConfigReferenceBeanTest { ReferenceBean genericHelloServiceReferenceBean = referenceBeanMap.get("&genericHelloService"); Assertions.assertEquals("demo", genericHelloServiceReferenceBean.getGroup()); Assertions.assertEquals(GenericService.class, genericHelloServiceReferenceBean.getInterfaceClass()); - Assertions.assertEquals(HelloService.class.getName(), genericHelloServiceReferenceBean.getServiceInterface()); + Assertions.assertEquals( + HelloService.class.getName(), genericHelloServiceReferenceBean.getServiceInterface()); ReferenceBean genericServiceWithoutInterfaceBean = referenceBeanMap.get("&genericServiceWithoutInterface"); Assertions.assertEquals("demo", genericServiceWithoutInterfaceBean.getGroup()); Assertions.assertEquals(GenericService.class, genericServiceWithoutInterfaceBean.getInterfaceClass()); - Assertions.assertEquals("org.apache.dubbo.config.spring.api.LocalMissClass", genericServiceWithoutInterfaceBean.getServiceInterface()); + Assertions.assertEquals( + "org.apache.dubbo.config.spring.api.LocalMissClass", + genericServiceWithoutInterfaceBean.getServiceInterface()); - GenericService genericServiceWithoutInterface = context.getBean("genericServiceWithoutInterface", GenericService.class); + GenericService genericServiceWithoutInterface = + context.getBean("genericServiceWithoutInterface", GenericService.class); Assertions.assertNotNull(genericServiceWithoutInterface); - Object sayHelloResult = genericServiceWithoutInterface.$invoke("sayHello", new String[]{"java.lang.String"}, new Object[]{"Dubbo"}); + Object sayHelloResult = genericServiceWithoutInterface.$invoke( + "sayHello", new String[] {"java.lang.String"}, new Object[] {"Dubbo"}); Assertions.assertEquals("Hello Dubbo", sayHelloResult); } finally { context.close(); } - } @Test void testReferenceBean() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(CommonConfig.class, - ReferenceBeanConfiguration.class); + AnnotationConfigApplicationContext context = + new AnnotationConfigApplicationContext(CommonConfig.class, ReferenceBeanConfiguration.class); try { Map helloServiceMap = context.getBeansOfType(HelloService.class); @@ -247,8 +251,8 @@ class JavaConfigReferenceBeanTest { @Test void testGenericServiceReferenceBean() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(CommonConfig.class, - GenericServiceReferenceBeanConfiguration.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( + CommonConfig.class, GenericServiceReferenceBeanConfiguration.class); try { Map helloServiceMap = context.getBeansOfType(HelloService.class); @@ -266,7 +270,8 @@ class JavaConfigReferenceBeanTest { ReferenceBean genericHelloServiceReferenceBean = referenceBeanMap.get("&genericHelloService"); Assertions.assertEquals("demo", genericHelloServiceReferenceBean.getGroup()); Assertions.assertEquals(GenericService.class, genericHelloServiceReferenceBean.getInterfaceClass()); - Assertions.assertEquals(HelloService.class.getName(), genericHelloServiceReferenceBean.getServiceInterface()); + Assertions.assertEquals( + HelloService.class.getName(), genericHelloServiceReferenceBean.getServiceInterface()); } finally { context.close(); } @@ -276,7 +281,8 @@ class JavaConfigReferenceBeanTest { void testRawReferenceBean() { AnnotationConfigApplicationContext context = null; try { - context = new AnnotationConfigApplicationContext(CommonConfig.class, ReferenceBeanWithoutGenericTypeConfiguration.class); + context = new AnnotationConfigApplicationContext( + CommonConfig.class, ReferenceBeanWithoutGenericTypeConfiguration.class); Assertions.fail("Should not load application"); } catch (Exception e) { @@ -288,7 +294,6 @@ class JavaConfigReferenceBeanTest { context.close(); } } - } @Test @@ -299,7 +304,9 @@ class JavaConfigReferenceBeanTest { Assertions.fail("Should not load application"); } catch (Exception e) { String s = e.toString(); - Assertions.assertTrue(s.contains("@DubboReference annotation is inconsistent with the generic type of the ReferenceBean"), s); + Assertions.assertTrue( + s.contains("@DubboReference annotation is inconsistent with the generic type of the ReferenceBean"), + s); Assertions.assertTrue(s.contains("ReferenceBean"), s); Assertions.assertTrue(s.contains("InconsistentBeanConfiguration#helloService()"), s); } finally { @@ -313,7 +320,8 @@ class JavaConfigReferenceBeanTest { void testMissingGenericTypeBean() { AnnotationConfigApplicationContext context = null; try { - context = new AnnotationConfigApplicationContext(CommonConfig.class, MissingGenericTypeAnnotationBeanConfiguration.class); + context = new AnnotationConfigApplicationContext( + CommonConfig.class, MissingGenericTypeAnnotationBeanConfiguration.class); Assertions.fail("Should not load application"); } catch (Exception e) { String s = e.toString(); @@ -330,7 +338,8 @@ class JavaConfigReferenceBeanTest { void testMissingInterfaceTypeBean() { AnnotationConfigApplicationContext context = null; try { - context = new AnnotationConfigApplicationContext(CommonConfig.class, MissingInterfaceTypeAnnotationBeanConfiguration.class); + context = new AnnotationConfigApplicationContext( + CommonConfig.class, MissingInterfaceTypeAnnotationBeanConfiguration.class); Assertions.fail("Should not load application"); } catch (Exception e) { String s = e.toString(); @@ -373,7 +382,6 @@ class JavaConfigReferenceBeanTest { } } - @Configuration public static class LazyProxyConfiguration1 { @@ -415,7 +423,6 @@ class JavaConfigReferenceBeanTest { @DubboReference(group = "${myapp.group}") private HelloService helloService; - } @Configuration @@ -423,7 +430,6 @@ class JavaConfigReferenceBeanTest { @DubboReference(group = "${myapp.group}", timeout = 2000) private HelloService helloService; - } @Configuration @@ -434,7 +440,6 @@ class JavaConfigReferenceBeanTest { public ReferenceBean helloService() { return new ReferenceBean(); } - } @Configuration @@ -447,7 +452,10 @@ class JavaConfigReferenceBeanTest { } @Bean - @DubboReference(group = "${myapp.group}", interfaceName = "org.apache.dubbo.config.spring.api.LocalMissClass", scope = "local") + @DubboReference( + group = "${myapp.group}", + interfaceName = "org.apache.dubbo.config.spring.api.LocalMissClass", + scope = "local") public ReferenceBean genericServiceWithoutInterface() { return new ReferenceBean(); } @@ -458,9 +466,7 @@ class JavaConfigReferenceBeanTest { @Bean public ReferenceBean helloService() { - return new ReferenceBeanBuilder() - .setGroup("${myapp.group}") - .build(); + return new ReferenceBeanBuilder().setGroup("${myapp.group}").build(); } @Bean @@ -475,9 +481,9 @@ class JavaConfigReferenceBeanTest { @Bean public ReferenceBean genericHelloService() { return new ReferenceBeanBuilder() - .setGroup("${myapp.group}") - .setInterface(HelloService.class) - .build(); + .setGroup("${myapp.group}") + .setInterface(HelloService.class) + .build(); } } @@ -488,11 +494,10 @@ class JavaConfigReferenceBeanTest { @Bean public ReferenceBean helloService() { return new ReferenceBeanBuilder() - .setGroup("${myapp.group}") - .setInterface(HelloService.class) - .build(); + .setGroup("${myapp.group}") + .setInterface(HelloService.class) + .build(); } - } @Configuration @@ -528,5 +533,4 @@ class JavaConfigReferenceBeanTest { return new ReferenceBean(); } } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcall/LocalCallTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcall/LocalCallTest.java index 235e432ef6..5af4ada5ea 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcall/LocalCallTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcall/LocalCallTest.java @@ -19,6 +19,8 @@ package org.apache.dubbo.config.spring.reference.localcall; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.api.HelloService; +import java.net.InetSocketAddress; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -29,13 +31,14 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.net.InetSocketAddress; - import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; @ExtendWith(SpringExtension.class) -@ContextConfiguration(locations = {"classpath:/org/apache/dubbo/config/spring/reference/localcall/local-call-provider.xml", - "classpath:/org/apache/dubbo/config/spring/reference/localcall/local-call-consumer.xml"}) +@ContextConfiguration( + locations = { + "classpath:/org/apache/dubbo/config/spring/reference/localcall/local-call-provider.xml", + "classpath:/org/apache/dubbo/config/spring/reference/localcall/local-call-consumer.xml" + }) @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) class LocalCallTest { @@ -53,7 +56,7 @@ class LocalCallTest { private HelloService helloService; @Autowired - //@Qualifier("localHelloService") + // @Qualifier("localHelloService") private HelloService localHelloService; @Test @@ -61,11 +64,11 @@ class LocalCallTest { // see also: org.apache.dubbo.rpc.protocol.injvm.InjvmInvoker.doInvoke // InjvmInvoker set remote address to 127.0.0.1:0 String result = helloService.sayHello("world"); - Assertions.assertEquals("Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); + Assertions.assertEquals( + "Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); // direct call local service, the remote address is null String originResult = localHelloService.sayHello("world"); Assertions.assertEquals("Hello world, response from provider: null", originResult); } - -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcall/LocalCallTest2.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcall/LocalCallTest2.java index 4b76ad623c..fc845ba80c 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcall/LocalCallTest2.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcall/LocalCallTest2.java @@ -20,6 +20,8 @@ import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.api.HelloService; +import java.net.InetSocketAddress; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -31,12 +33,11 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.net.InetSocketAddress; - import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; @ExtendWith(SpringExtension.class) -@ContextConfiguration(locations = {"classpath:/org/apache/dubbo/config/spring/reference/localcall/local-call-provider.xml"}) +@ContextConfiguration( + locations = {"classpath:/org/apache/dubbo/config/spring/reference/localcall/local-call-provider.xml"}) @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) public class LocalCallTest2 { @@ -61,7 +62,7 @@ public class LocalCallTest2 { // see also: org.apache.dubbo.rpc.protocol.injvm.InjvmInvoker.doInvoke // InjvmInvoker set remote address to 127.0.0.1:0 String result = helloService.sayHello("world"); - Assertions.assertEquals("Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); + Assertions.assertEquals( + "Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcall/LocalHelloServiceImpl.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcall/LocalHelloServiceImpl.java index 08fad7451c..e46581f728 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcall/LocalHelloServiceImpl.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcall/LocalHelloServiceImpl.java @@ -23,8 +23,7 @@ public class LocalHelloServiceImpl implements HelloService { @Override public String sayHello(String name) { - return "Hello " + name + ", response from provider: " + RpcContext.getContext().getLocalAddress(); - + return "Hello " + name + ", response from provider: " + + RpcContext.getContext().getLocalAddress(); } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcalla/LocalCallReferenceAnnotationTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcalla/LocalCallReferenceAnnotationTest.java index 9c3edd00fe..9c4bd6ae45 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcalla/LocalCallReferenceAnnotationTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcalla/LocalCallReferenceAnnotationTest.java @@ -23,6 +23,8 @@ import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.rpc.RpcContext; +import java.net.InetSocketAddress; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -36,14 +38,14 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.net.InetSocketAddress; - import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; @EnableDubbo @ExtendWith(SpringExtension.class) @PropertySource("classpath:/org/apache/dubbo/config/spring/reference/localcalla/local-call-config.properties") -@ContextConfiguration(classes = {LocalCallReferenceAnnotationTest.class, LocalCallReferenceAnnotationTest.LocalCallConfiguration.class}) +@ContextConfiguration( + classes = {LocalCallReferenceAnnotationTest.class, LocalCallReferenceAnnotationTest.LocalCallConfiguration.class + }) @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) class LocalCallReferenceAnnotationTest { @@ -68,7 +70,8 @@ class LocalCallReferenceAnnotationTest { // see also: org.apache.dubbo.rpc.protocol.injvm.InjvmInvoker.doInvoke // InjvmInvoker set remote address to 127.0.0.1:0 String result = helloService.sayHello("world"); - Assertions.assertEquals("Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); + Assertions.assertEquals( + "Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); } @Configuration @@ -81,7 +84,8 @@ class LocalCallReferenceAnnotationTest { public static class AnotherLocalHelloServiceImpl implements HelloService { @Override public String sayHello(String name) { - return "Hello " + name + ", response from provider: " + RpcContext.getContext().getLocalAddress(); + return "Hello " + name + ", response from provider: " + + RpcContext.getContext().getLocalAddress(); } } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcallam/LocalCallMultipleReferenceAnnotationsTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcallam/LocalCallMultipleReferenceAnnotationsTest.java index f579e00076..f253ab00a5 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcallam/LocalCallMultipleReferenceAnnotationsTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcallam/LocalCallMultipleReferenceAnnotationsTest.java @@ -24,6 +24,9 @@ import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.rpc.RpcContext; +import java.net.InetSocketAddress; +import java.util.Map; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -36,15 +39,16 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.net.InetSocketAddress; -import java.util.Map; - import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; @EnableDubbo @ExtendWith(SpringExtension.class) @PropertySource("classpath:/org/apache/dubbo/config/spring/reference/localcallam/local-call-config.properties") -@ContextConfiguration(classes = {LocalCallMultipleReferenceAnnotationsTest.class, LocalCallMultipleReferenceAnnotationsTest.LocalCallConfiguration.class}) +@ContextConfiguration( + classes = { + LocalCallMultipleReferenceAnnotationsTest.class, + LocalCallMultipleReferenceAnnotationsTest.LocalCallConfiguration.class + }) @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) class LocalCallMultipleReferenceAnnotationsTest { @@ -67,21 +71,24 @@ class LocalCallMultipleReferenceAnnotationsTest { // see also: org.apache.dubbo.rpc.protocol.injvm.InjvmInvoker.doInvoke // InjvmInvoker set remote address to 127.0.0.1:0 String result = helloService.sayHello("world"); - Assertions.assertEquals("Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); + Assertions.assertEquals( + "Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); String demoResult = demoHelloService.sayHello("world"); - Assertions.assertEquals("Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), demoResult); + Assertions.assertEquals( + "Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), + demoResult); Map referenceBeanMap = applicationContext.getBeansOfType(ReferenceBean.class); Assertions.assertEquals(2, referenceBeanMap.size()); Assertions.assertTrue(referenceBeanMap.containsKey("&helloService")); Assertions.assertTrue(referenceBeanMap.containsKey("&demoHelloService")); - //helloService3 and demoHelloService share the same ReferenceConfig instance + // helloService3 and demoHelloService share the same ReferenceConfig instance ReferenceBean helloService3ReferenceBean = applicationContext.getBean("&helloService3", ReferenceBean.class); - ReferenceBean demoHelloServiceReferenceBean = applicationContext.getBean("&demoHelloService", ReferenceBean.class); + ReferenceBean demoHelloServiceReferenceBean = + applicationContext.getBean("&demoHelloService", ReferenceBean.class); Assertions.assertSame(helloService3ReferenceBean, demoHelloServiceReferenceBean); - } @Configuration @@ -94,7 +101,6 @@ class LocalCallMultipleReferenceAnnotationsTest { @DubboReference(group = "${biz.group}", version = "${biz.version}") private HelloService helloService3; - } @Configuration @@ -105,7 +111,6 @@ class LocalCallMultipleReferenceAnnotationsTest { @DubboReference(group = "${biz.group}", version = "2.0.0") private HelloService demoHelloService; - } @Configuration @@ -113,14 +118,14 @@ class LocalCallMultipleReferenceAnnotationsTest { @DubboReference(group = "foo") private HelloService demoHelloService; - } @DubboService public static class AnotherLocalHelloServiceImpl implements HelloService { @Override public String sayHello(String name) { - return "Hello " + name + ", response from provider: " + RpcContext.getContext().getLocalAddress(); + return "Hello " + name + ", response from provider: " + + RpcContext.getContext().getLocalAddress(); } } @@ -128,7 +133,8 @@ class LocalCallMultipleReferenceAnnotationsTest { public static class DemoHelloServiceImpl implements HelloService { @Override public String sayHello(String name) { - return "Hello " + name + ", response from provider: " + RpcContext.getContext().getLocalAddress(); + return "Hello " + name + ", response from provider: " + + RpcContext.getContext().getLocalAddress(); } } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcallmix/LocalCallReferenceMixTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcallmix/LocalCallReferenceMixTest.java index e05ef64b99..90c08561f0 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcallmix/LocalCallReferenceMixTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcallmix/LocalCallReferenceMixTest.java @@ -23,6 +23,8 @@ import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.rpc.RpcContext; +import java.net.InetSocketAddress; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -37,14 +39,13 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.net.InetSocketAddress; - import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; @EnableDubbo @ExtendWith(SpringExtension.class) @PropertySource("classpath:/org/apache/dubbo/config/spring/reference/localcallmix/local-call-config.properties") -@ContextConfiguration(classes = {LocalCallReferenceMixTest.class, LocalCallReferenceMixTest.LocalCallConfiguration.class}) +@ContextConfiguration( + classes = {LocalCallReferenceMixTest.class, LocalCallReferenceMixTest.LocalCallConfiguration.class}) @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) @ImportResource("classpath:/org/apache/dubbo/config/spring/reference/localcallmix/local-call-consumer.xml") class LocalCallReferenceMixTest { @@ -70,7 +71,8 @@ class LocalCallReferenceMixTest { // see also: org.apache.dubbo.rpc.protocol.injvm.InjvmInvoker.doInvoke // InjvmInvoker set remote address to 127.0.0.1:0 String result = helloService.sayHello("world"); - Assertions.assertEquals("Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); + Assertions.assertEquals( + "Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); } @Configuration @@ -83,7 +85,8 @@ class LocalCallReferenceMixTest { public static class AnotherLocalHelloServiceImpl implements HelloService { @Override public String sayHello(String name) { - return "Hello " + name + ", response from provider: " + RpcContext.getContext().getLocalAddress(); + return "Hello " + name + ", response from provider: " + + RpcContext.getContext().getLocalAddress(); } } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/consumer/DubboXmlConsumerTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/consumer/DubboXmlConsumerTest.java index af17e997cc..b3a7864767 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/consumer/DubboXmlConsumerTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/consumer/DubboXmlConsumerTest.java @@ -17,20 +17,23 @@ package org.apache.dubbo.config.spring.reference.registryNA.consumer; import org.apache.dubbo.config.spring.api.HelloService; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; class DubboXmlConsumerTest { - @Test void testConsumer() { - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:/org/apache/dubbo/config/spring/reference/registryNA/consumer/dubbo-registryNA-consumer.xml"); + ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( + "classpath:/org/apache/dubbo/config/spring/reference/registryNA/consumer/dubbo-registryNA-consumer.xml"); context.start(); HelloService helloService = context.getBean("helloService", HelloService.class); - IllegalStateException exception = Assertions.assertThrows(IllegalStateException.class, () -> helloService.sayHello("dubbo")); - Assertions.assertTrue(exception.getMessage().contains("No such any registry to reference org.apache.dubbo.config.spring.api.HelloService")); + IllegalStateException exception = + Assertions.assertThrows(IllegalStateException.class, () -> helloService.sayHello("dubbo")); + Assertions.assertTrue(exception + .getMessage() + .contains("No such any registry to reference org.apache.dubbo.config.spring.api.HelloService")); } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/provider/DubboXmlProviderTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/provider/DubboXmlProviderTest.java index b45a649901..ef7b1005fe 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/provider/DubboXmlProviderTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/provider/DubboXmlProviderTest.java @@ -18,6 +18,7 @@ package org.apache.dubbo.config.spring.reference.registryNA.provider; import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.rpc.RpcException; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; @@ -29,7 +30,8 @@ public class DubboXmlProviderTest { @Test void testProvider() { - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:/org/apache/dubbo/config/spring/reference/registryNA/provider/dubbo-provider.xml"); + ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( + "classpath:/org/apache/dubbo/config/spring/reference/registryNA/provider/dubbo-provider.xml"); context.start(); Object bean = context.getBean("helloService"); Assertions.assertNotNull(bean); @@ -37,15 +39,20 @@ public class DubboXmlProviderTest { @Test void testProvider2() { - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:/org/apache/dubbo/config/spring/reference/registryNA/provider/dubbo-provider.xml"); + ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( + "classpath:/org/apache/dubbo/config/spring/reference/registryNA/provider/dubbo-provider.xml"); context.start(); Assertions.assertNotNull(context.getBean("helloService")); - ClassPathXmlApplicationContext context2 = new ClassPathXmlApplicationContext("classpath:/org/apache/dubbo/config/spring/reference/registryNA/consumer/dubbo-consumer.xml"); + ClassPathXmlApplicationContext context2 = new ClassPathXmlApplicationContext( + "classpath:/org/apache/dubbo/config/spring/reference/registryNA/consumer/dubbo-consumer.xml"); context2.start(); HelloService helloService = context2.getBean("helloService", HelloService.class); Assertions.assertNotNull(helloService); RpcException exception = Assertions.assertThrows(RpcException.class, () -> helloService.sayHello("dubbo")); - Assertions.assertTrue(exception.getMessage().contains("Failed to invoke the method sayHello in the service org.apache.dubbo.config.spring.api.HelloService. No provider available for the service org.apache.dubbo.config.spring.api.HelloService")); + Assertions.assertTrue( + exception + .getMessage() + .contains( + "Failed to invoke the method sayHello in the service org.apache.dubbo.config.spring.api.HelloService. No provider available for the service org.apache.dubbo.config.spring.api.HelloService")); } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/MockRegistry.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/MockRegistry.java index bf6a7865f4..d587f00d56 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/MockRegistry.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/MockRegistry.java @@ -56,9 +56,7 @@ public class MockRegistry implements Registry { } @Override - public void destroy() { - - } + public void destroy() {} @Override public void register(URL url) { diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/MockServiceDiscovery.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/MockServiceDiscovery.java index 3e4608768b..416c4e4f08 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/MockServiceDiscovery.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/MockServiceDiscovery.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -16,16 +16,16 @@ */ package org.apache.dubbo.config.spring.registry; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.client.AbstractServiceDiscovery; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + public class MockServiceDiscovery extends AbstractServiceDiscovery { private URL registryURL; @@ -38,21 +38,17 @@ public class MockServiceDiscovery extends AbstractServiceDiscovery { } @Override - public void doDestroy() throws Exception { - - } + public void doDestroy() throws Exception {} @Override - public void doRegister(ServiceInstance serviceInstance) throws RuntimeException { - } + public void doRegister(ServiceInstance serviceInstance) throws RuntimeException {} @Override - public void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance) throws RuntimeException { - } + public void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance) + throws RuntimeException {} @Override - public void doUnregister(ServiceInstance serviceInstance) throws RuntimeException { - } + public void doUnregister(ServiceInstance serviceInstance) throws RuntimeException {} @Override public Set getServices() { diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/consumer/DemoServiceConsumerBootstrap.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/consumer/DemoServiceConsumerBootstrap.java index 9fefd1c27e..23273aa607 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/consumer/DemoServiceConsumerBootstrap.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/consumer/DemoServiceConsumerBootstrap.java @@ -20,13 +20,14 @@ import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.config.spring.registry.nacos.demo.service.DemoService; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.PropertySource; - import javax.annotation.PostConstruct; + import java.io.IOException; import java.util.concurrent.TimeUnit; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.PropertySource; + /** * {@link DemoService} consumer demo */ diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/consumer/DemoServiceConsumerXmlBootstrap.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/consumer/DemoServiceConsumerXmlBootstrap.java index 3d09603060..58c3fcda1c 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/consumer/DemoServiceConsumerXmlBootstrap.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/consumer/DemoServiceConsumerXmlBootstrap.java @@ -18,10 +18,10 @@ package org.apache.dubbo.config.spring.registry.nacos.demo.consumer; import org.apache.dubbo.config.spring.registry.nacos.demo.service.DemoService; -import org.springframework.context.support.ClassPathXmlApplicationContext; - import java.io.IOException; +import org.springframework.context.support.ClassPathXmlApplicationContext; + /** * {@link DemoService} consumer demo XML bootstrap */ diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/provider/DemoServiceProviderBootstrap.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/provider/DemoServiceProviderBootstrap.java index 52d1bf8cd2..e81b357a38 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/provider/DemoServiceProviderBootstrap.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/provider/DemoServiceProviderBootstrap.java @@ -18,11 +18,11 @@ package org.apache.dubbo.config.spring.registry.nacos.demo.provider; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; +import java.io.IOException; + import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.PropertySource; -import java.io.IOException; - /** * {@link org.apache.dubbo.config.spring.registry.nacos.demo.service.DemoService} provider demo */ diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/provider/DemoServiceProviderXmlBootstrap.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/provider/DemoServiceProviderXmlBootstrap.java index ac5300d2a2..05ef4e68e9 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/provider/DemoServiceProviderXmlBootstrap.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/provider/DemoServiceProviderXmlBootstrap.java @@ -16,10 +16,10 @@ */ package org.apache.dubbo.config.spring.registry.nacos.demo.provider; -import org.springframework.context.support.ClassPathXmlApplicationContext; - import java.io.IOException; +import org.springframework.context.support.ClassPathXmlApplicationContext; + /** * {@link org.apache.dubbo.config.spring.registry.nacos.demo.service.DemoService} provider demo XML bootstrap */ diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/service/DefaultService.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/service/DefaultService.java index 405e58906a..aa5213e831 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/service/DefaultService.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/service/DefaultService.java @@ -21,7 +21,6 @@ import org.apache.dubbo.rpc.RpcContext; import org.springframework.beans.factory.annotation.Value; - /** * Default {@link DemoService} * @@ -35,7 +34,8 @@ public class DefaultService implements DemoService { public String sayName(String name) { RpcContext rpcContext = RpcContext.getServiceContext(); - return String.format("Service [name :%s , protocol: %s , port : %d] %s(\"%s\") : Hello,%s", + return String.format( + "Service [name :%s , protocol: %s , port : %d] %s(\"%s\") : Hello,%s", serviceName, rpcContext.getUrl().getProtocol(), rpcContext.getLocalPort(), diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/service/DemoService.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/service/DemoService.java index f685f3d268..5a1eea55ae 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/service/DemoService.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/service/DemoService.java @@ -24,5 +24,4 @@ package org.apache.dubbo.config.spring.registry.nacos.demo.service; public interface DemoService { String sayName(String name); - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/nacos/NacosServiceNameTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/nacos/NacosServiceNameTest.java index 58714a50e8..f4d424d998 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/nacos/NacosServiceNameTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/nacos/NacosServiceNameTest.java @@ -82,7 +82,6 @@ class NacosServiceNameTest { name.setGroup(null); name.setVersion(null); assertTrue(name.isConcrete()); - } @Test @@ -122,4 +121,4 @@ class NacosServiceNameTest { name.setVersion(version + ",2.0.0"); assertTrue(name.isCompatible(concrete)); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/DubboNamespaceHandlerTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/DubboNamespaceHandlerTest.java index 33efb6f9e4..cbc1accd2d 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/DubboNamespaceHandlerTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/DubboNamespaceHandlerTest.java @@ -32,6 +32,9 @@ import org.apache.dubbo.config.spring.api.DemoService; import org.apache.dubbo.config.spring.impl.DemoServiceImpl; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.Collection; +import java.util.Map; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -44,9 +47,6 @@ import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.ClassPathXmlApplicationContext; -import java.util.Collection; -import java.util.Map; - import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; @@ -73,9 +73,7 @@ class DubboNamespaceHandlerTest { @Configuration @PropertySource("classpath:/META-INF/demo-provider.properties") @ImportResource(locations = "classpath:/org/apache/dubbo/config/spring/demo-provider.xml") - static class XmlConfiguration { - - } + static class XmlConfiguration {} @Test void testProviderXmlOnConfigurationClass() { @@ -88,9 +86,7 @@ class DubboNamespaceHandlerTest { @Test void testProviderXml() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( - resourcePath + "/demo-provider.xml", - resourcePath + "/demo-provider-properties.xml" - ); + resourcePath + "/demo-provider.xml", resourcePath + "/demo-provider-properties.xml"); ctx.start(); testProviderXml(ctx); @@ -104,7 +100,7 @@ class DubboNamespaceHandlerTest { ApplicationConfig providerAppConfig = context.getBean(configId, ApplicationConfig.class); assertNotNull(providerAppConfig); assertEquals(appName, providerAppConfig.getName()); -// assertEquals(configId, providerAppConfig.getId()); + // assertEquals(configId, providerAppConfig.getId()); ProtocolConfig protocolConfig = context.getBean(ProtocolConfig.class); assertThat(protocolConfig, not(nullValue())); @@ -144,7 +140,8 @@ class DubboNamespaceHandlerTest { @Test void testDefaultProtocol() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/override-protocol.xml"); + ClassPathXmlApplicationContext ctx = + new ClassPathXmlApplicationContext(resourcePath + "/override-protocol.xml"); ctx.start(); ProtocolConfig protocolConfig = ctx.getBean(ProtocolConfig.class); @@ -154,7 +151,8 @@ class DubboNamespaceHandlerTest { @Test void testCustomParameter() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/customize-parameter.xml"); + ClassPathXmlApplicationContext ctx = + new ClassPathXmlApplicationContext(resourcePath + "/customize-parameter.xml"); ctx.start(); ProtocolConfig protocolConfig = ctx.getBean(ProtocolConfig.class); @@ -166,10 +164,10 @@ class DubboNamespaceHandlerTest { assertThat(serviceBean.getParameters().get("service-paramA"), is("service-paramA")); } - @Test void testDelayFixedTime() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:/" + resourcePath + "/delay-fixed-time.xml"); + ClassPathXmlApplicationContext ctx = + new ClassPathXmlApplicationContext("classpath:/" + resourcePath + "/delay-fixed-time.xml"); ctx.start(); assertThat(ctx.getBean(ServiceBean.class).getDelay(), is(300)); @@ -177,10 +175,12 @@ class DubboNamespaceHandlerTest { @Test void testTimeoutConfig() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/provider-nested-service.xml"); + ClassPathXmlApplicationContext ctx = + new ClassPathXmlApplicationContext(resourcePath + "/provider-nested-service.xml"); ctx.start(); - ModuleConfigManager configManager = ApplicationModel.defaultModel().getDefaultModule().getConfigManager(); + ModuleConfigManager configManager = + ApplicationModel.defaultModel().getDefaultModule().getConfigManager(); Collection providerConfigs = configManager.getProviders(); Assertions.assertEquals(2, providerConfigs.size()); @@ -192,36 +192,39 @@ class DubboNamespaceHandlerTest { ServiceConfigBase serviceConfig2 = configManager.getService("serviceConfig2"); Assertions.assertEquals(1000, provider2.getTimeout()); Assertions.assertEquals(provider2.getTimeout(), serviceConfig2.getTimeout()); - } @Test void testMonitor() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/provider-with-monitor.xml"); + ClassPathXmlApplicationContext ctx = + new ClassPathXmlApplicationContext(resourcePath + "/provider-with-monitor.xml"); ctx.start(); assertThat(ctx.getBean(MonitorConfig.class), not(nullValue())); } -// @Test -// public void testMultiMonitor() { -// Assertions.assertThrows(BeanCreationException.class, () -> { -// ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/multi-monitor.xml"); -// ctx.start(); -// }); -// } -// -// @Test -// public void testMultiProviderConfig() { -// Assertions.assertThrows(BeanCreationException.class, () -> { -// ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/provider-multi.xml"); -// ctx.start(); -// }); -// } + // @Test + // public void testMultiMonitor() { + // Assertions.assertThrows(BeanCreationException.class, () -> { + // ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + + // "/multi-monitor.xml"); + // ctx.start(); + // }); + // } + // + // @Test + // public void testMultiProviderConfig() { + // Assertions.assertThrows(BeanCreationException.class, () -> { + // ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + + // "/provider-multi.xml"); + // ctx.start(); + // }); + // } @Test void testModuleInfo() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/provider-with-module.xml"); + ClassPathXmlApplicationContext ctx = + new ClassPathXmlApplicationContext(resourcePath + "/provider-with-module.xml"); ctx.start(); ModuleConfig moduleConfig = ctx.getBean(ModuleConfig.class); @@ -231,7 +234,8 @@ class DubboNamespaceHandlerTest { @Test void testNotificationWithWrongBean() { Assertions.assertThrows(BeanCreationException.class, () -> { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/consumer-notification.xml"); + ClassPathXmlApplicationContext ctx = + new ClassPathXmlApplicationContext(resourcePath + "/consumer-notification.xml"); ctx.start(); }); } @@ -249,7 +253,8 @@ class DubboNamespaceHandlerTest { @Test void testMetricsAggregation() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/metrics-aggregation.xml"); + ClassPathXmlApplicationContext ctx = + new ClassPathXmlApplicationContext(resourcePath + "/metrics-aggregation.xml"); ctx.start(); ConfigManager configManager = ApplicationModel.defaultModel().getApplicationConfigManager(); @@ -263,14 +268,21 @@ class DubboNamespaceHandlerTest { assertEquals(metrics.getAggregation().getBucketNum(), 5); assertEquals(metrics.getAggregation().getTimeWindowSeconds(), 120); - assertEquals(metrics.getAggregation().getEnabled(), metricsBean.getAggregation().getEnabled()); - assertEquals(metrics.getAggregation().getBucketNum(), metricsBean.getAggregation().getBucketNum()); - assertEquals(metrics.getAggregation().getTimeWindowSeconds(), metricsBean.getAggregation().getTimeWindowSeconds()); + assertEquals( + metrics.getAggregation().getEnabled(), + metricsBean.getAggregation().getEnabled()); + assertEquals( + metrics.getAggregation().getBucketNum(), + metricsBean.getAggregation().getBucketNum()); + assertEquals( + metrics.getAggregation().getTimeWindowSeconds(), + metricsBean.getAggregation().getTimeWindowSeconds()); } @Test void testMetricsPrometheus() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/metrics-prometheus.xml"); + ClassPathXmlApplicationContext ctx = + new ClassPathXmlApplicationContext(resourcePath + "/metrics-prometheus.xml"); ctx.start(); ConfigManager configManager = ApplicationModel.defaultModel().getApplicationConfigManager(); diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/GenericServiceTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/GenericServiceTest.java index 4103f9c569..25e932fb09 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/GenericServiceTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/GenericServiceTest.java @@ -67,13 +67,15 @@ class GenericServiceTest { assertNotNull(demoServiceRef); assertNotNull(serviceBean); - ModuleConfigManager configManager = DubboBootstrap.getInstance().getApplicationModel().getDefaultModule().getConfigManager(); + ModuleConfigManager configManager = DubboBootstrap.getInstance() + .getApplicationModel() + .getDefaultModule() + .getConfigManager(); ServiceConfigBase serviceConfig = configManager.getService("demoService"); Assertions.assertEquals(DemoService.class.getName(), serviceConfig.getInterface()); Assertions.assertEquals(true, serviceConfig.isExported()); - Object result = demoServiceRef.$invoke("sayHello", new String[]{"java.lang.String"}, new Object[]{"dubbo"}); + Object result = demoServiceRef.$invoke("sayHello", new String[] {"java.lang.String"}, new Object[] {"dubbo"}); Assertions.assertEquals("Welcome dubbo", result); - } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/GenericServiceWithoutInterfaceTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/GenericServiceWithoutInterfaceTest.java index 8fbb450817..6d74fab541 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/GenericServiceWithoutInterfaceTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/GenericServiceWithoutInterfaceTest.java @@ -59,12 +59,17 @@ class GenericServiceWithoutInterfaceTest { void testGenericWithoutInterface() { // Test generic service without interface class locally - Object result = genericServiceWithoutInterfaceRef.$invoke("sayHello", new String[]{"java.lang.String"}, new Object[]{"generic"}); + Object result = genericServiceWithoutInterfaceRef.$invoke( + "sayHello", new String[] {"java.lang.String"}, new Object[] {"generic"}); Assertions.assertEquals("Welcome generic", result); - ReferenceConfigBase reference = DubboBootstrap.getInstance().getApplicationModel().getDefaultModule().getConfigManager().getReference("genericServiceWithoutInterfaceRef"); + ReferenceConfigBase reference = DubboBootstrap.getInstance() + .getApplicationModel() + .getDefaultModule() + .getConfigManager() + .getReference("genericServiceWithoutInterfaceRef"); Assertions.assertNull(reference.getServiceInterfaceClass()); Assertions.assertEquals("org.apache.dubbo.config.spring.api.LocalMissClass", reference.getInterface()); Assertions.assertThrows(ClassNotFoundException.class, () -> ClassUtils.forName(reference.getInterface())); } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/status/DataSourceStatusCheckerTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/status/DataSourceStatusCheckerTest.java index b17e04a7f2..7edf41135d 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/status/DataSourceStatusCheckerTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/status/DataSourceStatusCheckerTest.java @@ -19,6 +19,13 @@ package org.apache.dubbo.config.spring.status; import org.apache.dubbo.common.status.Status; import org.apache.dubbo.config.spring.ServiceBean; +import javax.sql.DataSource; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Map; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -27,12 +34,6 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.springframework.context.ApplicationContext; -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.HashMap; -import java.util.Map; - import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.anyBoolean; @@ -69,7 +70,8 @@ class DataSourceStatusCheckerTest { @Test void testWithoutDatasource() { Map map = new HashMap(); - given(applicationContext.getBeansOfType(eq(DataSource.class), anyBoolean(), anyBoolean())).willReturn(map); + given(applicationContext.getBeansOfType(eq(DataSource.class), anyBoolean(), anyBoolean())) + .willReturn(map); Status status = dataSourceStatusChecker.check(); @@ -85,7 +87,8 @@ class DataSourceStatusCheckerTest { given(connection.getMetaData().getTypeInfo().next()).willReturn(true); map.put("mockDatabase", dataSource); - given(applicationContext.getBeansOfType(eq(DataSource.class), anyBoolean(), anyBoolean())).willReturn(map); + given(applicationContext.getBeansOfType(eq(DataSource.class), anyBoolean(), anyBoolean())) + .willReturn(map); Status status = dataSourceStatusChecker.check(); assertThat(status.getLevel(), is(Status.Level.OK)); @@ -100,7 +103,8 @@ class DataSourceStatusCheckerTest { given(connection.getMetaData().getTypeInfo().next()).willReturn(false); map.put("mockDatabase", dataSource); - given(applicationContext.getBeansOfType(eq(DataSource.class), anyBoolean(), anyBoolean())).willReturn(map); + given(applicationContext.getBeansOfType(eq(DataSource.class), anyBoolean(), anyBoolean())) + .willReturn(map); Status status = dataSourceStatusChecker.check(); assertThat(status.getLevel(), is(Status.Level.ERROR)); diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/status/SpringStatusCheckerTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/status/SpringStatusCheckerTest.java index da3fe0061b..4678e41fb8 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/status/SpringStatusCheckerTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/status/SpringStatusCheckerTest.java @@ -33,17 +33,17 @@ import static org.mockito.Mockito.mock; class SpringStatusCheckerTest { -// @Mock -// private ApplicationLifeCycle applicationContext; + // @Mock + // private ApplicationLifeCycle applicationContext; @BeforeEach public void setUp() throws Exception { - //initMocks(this); + // initMocks(this); } @AfterEach public void tearDown() throws Exception { - //Mockito.reset(applicationContext); + // Mockito.reset(applicationContext); } @Test @@ -57,7 +57,7 @@ class SpringStatusCheckerTest { @Test void testWithLifeCycleRunning() { ApplicationLifeCycle applicationLifeCycle = mock(ApplicationLifeCycle.class); - given(applicationLifeCycle.getConfigLocations()).willReturn(new String[]{"test1", "test2"}); + given(applicationLifeCycle.getConfigLocations()).willReturn(new String[] {"test1", "test2"}); given(applicationLifeCycle.isRunning()).willReturn(true); SpringStatusChecker springStatusChecker = new SpringStatusChecker(applicationLifeCycle); @@ -92,5 +92,4 @@ class SpringStatusCheckerTest { Status status = checker.check(); Assertions.assertEquals(Status.Level.OK, status.getLevel()); } - -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/util/EnvironmentUtilsTest.java b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/util/EnvironmentUtilsTest.java index 96f995bba3..6782a4f5ae 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/util/EnvironmentUtilsTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/util/EnvironmentUtilsTest.java @@ -16,6 +16,10 @@ */ package org.apache.dubbo.config.spring.util; +import java.util.HashMap; +import java.util.Map; +import java.util.SortedMap; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.core.env.CompositePropertySource; @@ -24,10 +28,6 @@ import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.StandardEnvironment; import org.springframework.mock.env.MockEnvironment; -import java.util.HashMap; -import java.util.Map; -import java.util.SortedMap; - import static org.apache.dubbo.config.spring.util.EnvironmentUtils.filterDubboProperties; /** @@ -67,7 +67,6 @@ class EnvironmentUtilsTest { } finally { System.clearProperty(key); } - } @Test @@ -83,6 +82,5 @@ class EnvironmentUtilsTest { Assertions.assertEquals(2, dubboProperties.size()); Assertions.assertEquals("zookeeper://10.10.10.1:2181", dubboProperties.get("dubbo.registry.address")); Assertions.assertEquals("false", dubboProperties.get("dubbo.consumer.check")); - } -} \ No newline at end of file +} diff --git a/dubbo-config/dubbo-config-spring6/pom.xml b/dubbo-config/dubbo-config-spring6/pom.xml index 3298274342..3f067b3dfd 100644 --- a/dubbo-config/dubbo-config-spring6/pom.xml +++ b/dubbo-config/dubbo-config-spring6/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-config - ${revision} - + 4.0.0 + + org.apache.dubbo + dubbo-config + ${revision} + - dubbo-config-spring6 + dubbo-config-spring6 - - 17 - 17 - 6.0.11 - 3.0.9 - + + 17 + 17 + 6.0.11 + 3.0.9 + - - - org.apache.dubbo - dubbo-config-api - ${project.parent.version} - + + + org.apache.dubbo + dubbo-config-api + ${project.parent.version} + - - org.apache.dubbo - dubbo-config-spring - ${project.parent.version} - + + org.apache.dubbo + dubbo-config-spring + ${project.parent.version} + - - org.springframework - spring-beans - ${spring.version} - - - org.springframework - spring-core - ${spring.version} - - - org.springframework - spring-web - ${spring.version} - - - org.springframework - spring-context - ${spring.version} - - - javax.servlet - javax.servlet-api - provided - + + org.springframework + spring-beans + ${spring.version} + + + org.springframework + spring-core + ${spring.version} + + + org.springframework + spring-web + ${spring.version} + + + org.springframework + spring-context + ${spring.version} + + + javax.servlet + javax.servlet-api + provided + - - org.springframework.boot - spring-boot-starter-test - ${spring-boot.version} - test - - - logback-classic - ch.qos.logback - - - log4j-to-slf4j - org.apache.logging.log4j - - - - - org.slf4j - slf4j-log4j12 - test - - + + org.springframework.boot + spring-boot-starter-test + ${spring-boot.version} + test + + + ch.qos.logback + logback-classic + + + org.apache.logging.log4j + log4j-to-slf4j + + + + + org.slf4j + slf4j-log4j12 + test + + diff --git a/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/annotation/ReferenceAnnotationWithAotBeanPostProcessor.java b/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/annotation/ReferenceAnnotationWithAotBeanPostProcessor.java index 3104ef00c3..ca3435eb9a 100644 --- a/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/annotation/ReferenceAnnotationWithAotBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/annotation/ReferenceAnnotationWithAotBeanPostProcessor.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config.spring6.beans.factory.annotation; - import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ClassUtils; @@ -30,6 +29,12 @@ import org.apache.dubbo.config.spring6.beans.factory.aot.ReferencedMethodArgumen import org.apache.dubbo.config.spring6.utils.AotUtils; import org.apache.dubbo.rpc.service.Destroyable; import org.apache.dubbo.rpc.service.EchoService; + +import java.lang.reflect.Field; +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.lang.reflect.Parameter; + import org.springframework.aop.SpringProxy; import org.springframework.aop.framework.Advised; import org.springframework.aot.generate.AccessControl; @@ -62,11 +67,6 @@ import org.springframework.javapoet.CodeBlock; import org.springframework.lang.Nullable; import org.springframework.util.CollectionUtils; -import java.lang.reflect.Field; -import java.lang.reflect.Member; -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; - import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_INITIALIZER; /** @@ -76,11 +76,10 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO * @since 3.3 */ public class ReferenceAnnotationWithAotBeanPostProcessor extends ReferenceAnnotationBeanPostProcessor - implements BeanRegistrationAotProcessor { + implements BeanRegistrationAotProcessor { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); - @Nullable private ConfigurableListableBeanFactory beanFactory; @@ -128,11 +127,16 @@ public class ReferenceAnnotationWithAotBeanPostProcessor extends ReferenceAnnota } try { - // this is an early event, it will be notified at org.springframework.context.support.AbstractApplicationContext.registerListeners() + // this is an early event, it will be notified at + // org.springframework.context.support.AbstractApplicationContext.registerListeners() applicationContext.publishEvent(new DubboConfigInitEvent(applicationContext)); } catch (Exception e) { // if spring version is less than 4.2, it does not support early application event - logger.warn(CONFIG_DUBBO_BEAN_INITIALIZER, "", "", "publish early application event failed, please upgrade spring version to 4.2.x or later: " + e); + logger.warn( + CONFIG_DUBBO_BEAN_INITIALIZER, + "", + "", + "publish early application event failed, please upgrade spring version to 4.2.x or later: " + e); } } @@ -161,13 +165,15 @@ public class ReferenceAnnotationWithAotBeanPostProcessor extends ReferenceAnnota String beanName = registeredBean.getBeanName(); RootBeanDefinition beanDefinition = registeredBean.getMergedBeanDefinition(); AnnotatedInjectionMetadata metadata = findInjectionMetadata(beanDefinition, beanClass, beanName); - if (!CollectionUtils.isEmpty(metadata.getFieldElements()) || !CollectionUtils.isEmpty(metadata.getMethodElements())) { + if (!CollectionUtils.isEmpty(metadata.getFieldElements()) + || !CollectionUtils.isEmpty(metadata.getMethodElements())) { return new AotContribution(beanClass, metadata, getAutowireCandidateResolver()); } return null; } - private AnnotatedInjectionMetadata findInjectionMetadata(RootBeanDefinition beanDefinition, Class beanType, String beanName) { + private AnnotatedInjectionMetadata findInjectionMetadata( + RootBeanDefinition beanDefinition, Class beanType, String beanName) { AnnotatedInjectionMetadata metadata = findInjectionMetadata(beanName, beanType, null); metadata.checkConfigMembers(beanDefinition); return metadata; @@ -181,7 +187,6 @@ public class ReferenceAnnotationWithAotBeanPostProcessor extends ReferenceAnnota return null; } - private static class AotContribution implements BeanRegistrationAotContribution { private static final String REGISTERED_BEAN_PARAMETER = "registeredBean"; @@ -195,7 +200,10 @@ public class ReferenceAnnotationWithAotBeanPostProcessor extends ReferenceAnnota @Nullable private final AutowireCandidateResolver candidateResolver; - AotContribution(Class target, AnnotatedInjectionMetadata annotatedInjectionMetadata, AutowireCandidateResolver candidateResolver) { + AotContribution( + Class target, + AnnotatedInjectionMetadata annotatedInjectionMetadata, + AutowireCandidateResolver candidateResolver) { this.target = target; this.annotatedInjectionMetadata = annotatedInjectionMetadata; @@ -204,20 +212,19 @@ public class ReferenceAnnotationWithAotBeanPostProcessor extends ReferenceAnnota @Override public void applyTo(GenerationContext generationContext, BeanRegistrationCode beanRegistrationCode) { - GeneratedClass generatedClass = generationContext.getGeneratedClasses() - .addForFeatureComponent("DubboReference", this.target, type -> { - type.addJavadoc("DubboReference for {@link $T}.", this.target); - type.addModifiers(javax.lang.model.element.Modifier.PUBLIC); - }); + GeneratedClass generatedClass = generationContext + .getGeneratedClasses() + .addForFeatureComponent("DubboReference", this.target, type -> { + type.addJavadoc("DubboReference for {@link $T}.", this.target); + type.addModifiers(javax.lang.model.element.Modifier.PUBLIC); + }); GeneratedMethod generateMethod = generatedClass.getMethods().add("apply", method -> { method.addJavadoc("Apply the dubbo reference."); - method.addModifiers(javax.lang.model.element.Modifier.PUBLIC, - javax.lang.model.element.Modifier.STATIC); + method.addModifiers(javax.lang.model.element.Modifier.PUBLIC, javax.lang.model.element.Modifier.STATIC); method.addParameter(RegisteredBean.class, REGISTERED_BEAN_PARAMETER); method.addParameter(this.target, INSTANCE_PARAMETER); method.returns(this.target); - method.addCode(generateMethodCode(generatedClass.getName(), - generationContext.getRuntimeHints())); + method.addCode(generateMethodCode(generatedClass.getName(), generationContext.getRuntimeHints())); }); beanRegistrationCode.addInstancePostProcessor(generateMethod.toMethodReference()); @@ -230,22 +237,20 @@ public class ReferenceAnnotationWithAotBeanPostProcessor extends ReferenceAnnota CodeBlock.Builder code = CodeBlock.builder(); if (!CollectionUtils.isEmpty(this.annotatedInjectionMetadata.getFieldElements())) { for (AnnotatedInjectElement referenceElement : this.annotatedInjectionMetadata.getFieldElements()) { - code.addStatement(generateMethodStatementForElement( - targetClassName, referenceElement, hints)); + code.addStatement(generateMethodStatementForElement(targetClassName, referenceElement, hints)); } } if (!CollectionUtils.isEmpty(this.annotatedInjectionMetadata.getMethodElements())) { for (AnnotatedInjectElement referenceElement : this.annotatedInjectionMetadata.getMethodElements()) { - code.addStatement(generateMethodStatementForElement( - targetClassName, referenceElement, hints)); + code.addStatement(generateMethodStatementForElement(targetClassName, referenceElement, hints)); } } code.addStatement("return $L", INSTANCE_PARAMETER); return code.build(); } - private CodeBlock generateMethodStatementForElement(ClassName targetClassName, - AnnotatedInjectElement referenceElement, RuntimeHints hints) { + private CodeBlock generateMethodStatementForElement( + ClassName targetClassName, AnnotatedInjectElement referenceElement, RuntimeHints hints) { Member member = referenceElement.getMember(); AnnotationAttributes attributes = referenceElement.attributes; @@ -256,43 +261,61 @@ public class ReferenceAnnotationWithAotBeanPostProcessor extends ReferenceAnnota AotUtils.registerSerializationForService(c, hints); hints.reflection().registerType(TypeReference.of(c), MemberCategory.INVOKE_PUBLIC_METHODS); hints.proxies().registerJdkProxy(c, EchoService.class, Destroyable.class); - hints.proxies().registerJdkProxy(c, EchoService.class, Destroyable.class, SpringProxy.class, Advised.class, DecoratingProxy.class); + hints.proxies() + .registerJdkProxy( + c, + EchoService.class, + Destroyable.class, + SpringProxy.class, + Advised.class, + DecoratingProxy.class); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } if (member instanceof Field) { return generateMethodStatementForField( - targetClassName, (Field) member, attributes, injectedObject, hints); + targetClassName, (Field) member, attributes, injectedObject, hints); } if (member instanceof Method) { return generateMethodStatementForMethod( - targetClassName, (Method) member, attributes, injectedObject, hints); + targetClassName, (Method) member, attributes, injectedObject, hints); } throw new IllegalStateException( - "Unsupported member type " + member.getClass().getName()); + "Unsupported member type " + member.getClass().getName()); } - private CodeBlock generateMethodStatementForField(ClassName targetClassName, - Field field, AnnotationAttributes attributes, Object injectedObject, RuntimeHints hints) { + private CodeBlock generateMethodStatementForField( + ClassName targetClassName, + Field field, + AnnotationAttributes attributes, + Object injectedObject, + RuntimeHints hints) { hints.reflection().registerField(field); - CodeBlock resolver = CodeBlock.of("$T.$L($S)", - ReferencedFieldValueResolver.class, - "forRequiredField", field.getName()); + CodeBlock resolver = + CodeBlock.of("$T.$L($S)", ReferencedFieldValueResolver.class, "forRequiredField", field.getName()); CodeBlock shortcutResolver = CodeBlock.of("$L.withShortcut($S)", resolver, injectedObject); AccessControl accessControl = AccessControl.forMember(field); if (!accessControl.isAccessibleFrom(targetClassName)) { - return CodeBlock.of("$L.resolveAndSet($L, $L)", shortcutResolver, - REGISTERED_BEAN_PARAMETER, INSTANCE_PARAMETER); + return CodeBlock.of( + "$L.resolveAndSet($L, $L)", shortcutResolver, REGISTERED_BEAN_PARAMETER, INSTANCE_PARAMETER); } - return CodeBlock.of("$L.$L = $L.resolve($L)", INSTANCE_PARAMETER, - field.getName(), shortcutResolver, REGISTERED_BEAN_PARAMETER); + return CodeBlock.of( + "$L.$L = $L.resolve($L)", + INSTANCE_PARAMETER, + field.getName(), + shortcutResolver, + REGISTERED_BEAN_PARAMETER); } - private CodeBlock generateMethodStatementForMethod(ClassName targetClassName, - Method method, AnnotationAttributes attributes, Object injectedObject, RuntimeHints hints) { + private CodeBlock generateMethodStatementForMethod( + ClassName targetClassName, + Method method, + AnnotationAttributes attributes, + Object injectedObject, + RuntimeHints hints) { CodeBlock.Builder code = CodeBlock.builder(); code.add("$T.$L", ReferencedMethodArgumentsResolver.class, "forRequiredMethod"); @@ -315,10 +338,10 @@ public class ReferenceAnnotationWithAotBeanPostProcessor extends ReferenceAnnota code.add(".resolveAndInvoke($L, $L)", REGISTERED_BEAN_PARAMETER, INSTANCE_PARAMETER); } else { hints.reflection().registerMethod(method, ExecutableMode.INTROSPECT); - CodeBlock arguments = new AutowiredArgumentsCodeGenerator(this.target, - method).generateCode(method.getParameterTypes()); - CodeBlock injectionCode = CodeBlock.of("args -> $L.$L($L)", - INSTANCE_PARAMETER, method.getName(), arguments); + CodeBlock arguments = new AutowiredArgumentsCodeGenerator(this.target, method) + .generateCode(method.getParameterTypes()); + CodeBlock injectionCode = + CodeBlock.of("args -> $L.$L($L)", INSTANCE_PARAMETER, method.getName(), arguments); code.add(".resolve($L, $L)", REGISTERED_BEAN_PARAMETER, injectionCode); } return code.build(); @@ -371,13 +394,11 @@ public class ReferenceAnnotationWithAotBeanPostProcessor extends ReferenceAnnota private void registerProxyIfNecessary(RuntimeHints runtimeHints, DependencyDescriptor dependencyDescriptor) { if (this.candidateResolver != null) { - Class proxyClass = - this.candidateResolver.getLazyResolutionProxyClass(dependencyDescriptor, null); + Class proxyClass = this.candidateResolver.getLazyResolutionProxyClass(dependencyDescriptor, null); if (proxyClass != null) { ClassHintUtils.registerProxyIfNecessary(proxyClass, runtimeHints); } } } - } } diff --git a/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/annotation/ServiceAnnotationWithAotPostProcessor.java b/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/annotation/ServiceAnnotationWithAotPostProcessor.java index 738b1b940a..b1490c4ade 100644 --- a/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/annotation/ServiceAnnotationWithAotPostProcessor.java +++ b/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/annotation/ServiceAnnotationWithAotPostProcessor.java @@ -22,6 +22,9 @@ import org.apache.dubbo.config.spring.ServiceBean; import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor; import org.apache.dubbo.config.spring.schema.AnnotationBeanDefinitionParser; import org.apache.dubbo.config.spring6.utils.AotUtils; + +import java.util.Collection; + import org.springframework.aot.generate.GenerationContext; import org.springframework.aot.hint.MemberCategory; import org.springframework.aot.hint.TypeReference; @@ -32,8 +35,6 @@ import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProce import org.springframework.beans.factory.support.RegisteredBean; import org.springframework.beans.factory.support.RootBeanDefinition; -import java.util.Collection; - /** * The purpose of implementing {@link BeanRegistrationAotProcessor} is to * supplement for {@link ServiceAnnotationPostProcessor} ability of AOT. @@ -42,7 +43,8 @@ import java.util.Collection; * @see BeanDefinitionRegistryPostProcessor * @since 3.3 */ -public class ServiceAnnotationWithAotPostProcessor extends ServiceAnnotationPostProcessor implements BeanRegistrationAotProcessor { +public class ServiceAnnotationWithAotPostProcessor extends ServiceAnnotationPostProcessor + implements BeanRegistrationAotProcessor { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); @@ -83,11 +85,11 @@ public class ServiceAnnotationWithAotPostProcessor extends ServiceAnnotationPost @Override public void applyTo(GenerationContext generationContext, BeanRegistrationCode beanRegistrationCode) { - generationContext.getRuntimeHints().reflection().registerType(TypeReference.of(cl), - MemberCategory.INVOKE_PUBLIC_METHODS); + generationContext + .getRuntimeHints() + .reflection() + .registerType(TypeReference.of(cl), MemberCategory.INVOKE_PUBLIC_METHODS); AotUtils.registerSerializationForService(cl, generationContext.getRuntimeHints()); - } } - } diff --git a/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/aot/AutowiredElementResolver.java b/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/aot/AutowiredElementResolver.java index b71411b995..4dc0ad8e5b 100644 --- a/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/aot/AutowiredElementResolver.java +++ b/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/aot/AutowiredElementResolver.java @@ -14,9 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config.spring6.beans.factory.aot; +import javax.lang.model.element.Element; + +import java.util.Set; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.BeanFactory; @@ -24,9 +27,6 @@ import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.config.DependencyDescriptor; import org.springframework.core.log.LogMessage; -import javax.lang.model.element.Element; -import java.util.Set; - /** * Base class for resolvers that support autowiring related to an * {@link Element}. @@ -35,20 +35,18 @@ abstract class AutowiredElementResolver { private final Log logger = LogFactory.getLog(getClass()); - protected final void registerDependentBeans(ConfigurableBeanFactory beanFactory, - String beanName, Set autowiredBeanNames) { + protected final void registerDependentBeans( + ConfigurableBeanFactory beanFactory, String beanName, Set autowiredBeanNames) { for (String autowiredBeanName : autowiredBeanNames) { if (beanFactory.containsBean(autowiredBeanName)) { beanFactory.registerDependentBean(autowiredBeanName, beanName); } logger.trace(LogMessage.format( - "Autowiring by type from bean name %s' to bean named '%s'", beanName, - autowiredBeanName)); + "Autowiring by type from bean name %s' to bean named '%s'", beanName, autowiredBeanName)); } } - /** * {@link DependencyDescriptor} that supports shortcut bean resolution. */ @@ -59,19 +57,15 @@ abstract class AutowiredElementResolver { private final Class requiredType; - - public ShortcutDependencyDescriptor(DependencyDescriptor original, - String shortcut, Class requiredType) { + public ShortcutDependencyDescriptor(DependencyDescriptor original, String shortcut, Class requiredType) { super(original); this.shortcut = shortcut; this.requiredType = requiredType; } - @Override public Object resolveShortcut(BeanFactory beanFactory) { return beanFactory.getBean(this.shortcut, this.requiredType); } } - } diff --git a/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/aot/ReferencedFieldValueResolver.java b/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/aot/ReferencedFieldValueResolver.java index fd8bcfa518..fcea270168 100644 --- a/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/aot/ReferencedFieldValueResolver.java +++ b/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/aot/ReferencedFieldValueResolver.java @@ -17,6 +17,11 @@ package org.apache.dubbo.config.spring6.beans.factory.aot; import org.apache.dubbo.config.spring6.beans.factory.annotation.ReferenceAnnotationWithAotBeanPostProcessor; + +import java.lang.reflect.Field; +import java.util.LinkedHashSet; +import java.util.Set; + import org.springframework.aot.hint.ExecutableMode; import org.springframework.beans.BeansException; import org.springframework.beans.TypeConverter; @@ -31,10 +36,6 @@ import org.springframework.util.Assert; import org.springframework.util.ReflectionUtils; import org.springframework.util.function.ThrowingConsumer; -import java.lang.reflect.Field; -import java.util.LinkedHashSet; -import java.util.Set; - /** * Resolver used to support the autowiring of fields. Typically used in * AOT-processed applications as a targeted alternative to the @@ -57,9 +58,7 @@ public final class ReferencedFieldValueResolver extends AutowiredElementResolver @Nullable private final String shortcut; - - private ReferencedFieldValueResolver(String fieldName, boolean required, - @Nullable String shortcut) { + private ReferencedFieldValueResolver(String fieldName, boolean required, @Nullable String shortcut) { Assert.hasText(fieldName, "'fieldName' must not be empty"); this.fieldName = fieldName; @@ -67,7 +66,6 @@ public final class ReferencedFieldValueResolver extends AutowiredElementResolver this.shortcut = shortcut; } - /** * Create a new {@link ReferencedFieldValueResolver} for the specified field * where injection is optional. @@ -90,7 +88,6 @@ public final class ReferencedFieldValueResolver extends AutowiredElementResolver return new ReferencedFieldValueResolver(fieldName, true, null); } - /** * Return a new {@link ReferencedFieldValueResolver} instance that uses a * direct bean name injection shortcut. @@ -184,8 +181,7 @@ public final class ReferencedFieldValueResolver extends AutowiredElementResolver DependencyDescriptor descriptor = new DependencyDescriptor(field, this.required); descriptor.setContainingClass(beanClass); if (this.shortcut != null) { - descriptor = new ShortcutDependencyDescriptor(descriptor, this.shortcut, - field.getType()); + descriptor = new ShortcutDependencyDescriptor(descriptor, this.shortcut, field.getType()); } Set autowiredBeanNames = new LinkedHashSet<>(1); TypeConverter typeConverter = beanFactory.getTypeConverter(); @@ -194,23 +190,21 @@ public final class ReferencedFieldValueResolver extends AutowiredElementResolver Object injectedObject = beanFactory.getBean(shortcut); - - Object value = ((AutowireCapableBeanFactory) beanFactory).resolveDependency( - descriptor, beanName, autowiredBeanNames, typeConverter); + Object value = ((AutowireCapableBeanFactory) beanFactory) + .resolveDependency(descriptor, beanName, autowiredBeanNames, typeConverter); registerDependentBeans(beanFactory, beanName, autowiredBeanNames); return injectedObject; } catch (BeansException ex) { - throw new UnsatisfiedDependencyException(null, beanName, - new InjectionPoint(field), ex); + throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex); } } private Field getField(RegisteredBean registeredBean) { - Field field = ReflectionUtils.findField(registeredBean.getBeanClass(), - this.fieldName); - Assert.notNull(field, () -> "No field '" + this.fieldName + "' found on " - + registeredBean.getBeanClass().getName()); + Field field = ReflectionUtils.findField(registeredBean.getBeanClass(), this.fieldName); + Assert.notNull( + field, + () -> "No field '" + this.fieldName + "' found on " + + registeredBean.getBeanClass().getName()); return field; } - } diff --git a/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/aot/ReferencedMethodArgumentsResolver.java b/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/aot/ReferencedMethodArgumentsResolver.java index a051dedba1..59ffcfb2c9 100644 --- a/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/aot/ReferencedMethodArgumentsResolver.java +++ b/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/aot/ReferencedMethodArgumentsResolver.java @@ -14,10 +14,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config.spring6.beans.factory.aot; import org.apache.dubbo.config.spring6.beans.factory.annotation.ReferenceAnnotationWithAotBeanPostProcessor; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.stream.Collectors; + import org.springframework.aot.hint.ExecutableMode; import org.springframework.beans.BeansException; import org.springframework.beans.TypeConverter; @@ -35,12 +41,6 @@ import org.springframework.util.Assert; import org.springframework.util.ReflectionUtils; import org.springframework.util.function.ThrowingConsumer; -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.stream.Collectors; - /** * Resolver used to support the autowiring of methods. Typically used in * AOT-processed applications as a targeted alternative to the @@ -65,9 +65,8 @@ public final class ReferencedMethodArgumentsResolver extends AutowiredElementRes @Nullable private final String[] shortcuts; - - private ReferencedMethodArgumentsResolver(String methodName, Class[] parameterTypes, - boolean required, @Nullable String[] shortcuts) { + private ReferencedMethodArgumentsResolver( + String methodName, Class[] parameterTypes, boolean required, @Nullable String[] shortcuts) { Assert.hasText(methodName, "'methodName' must not be empty"); this.methodName = methodName; @@ -84,11 +83,9 @@ public final class ReferencedMethodArgumentsResolver extends AutowiredElementRes * @param parameterTypes the factory method parameter types * @return a new {@link org.springframework.beans.factory.aot.AutowiredFieldValueResolver} instance */ - public static ReferencedMethodArgumentsResolver forMethod(String methodName, - Class... parameterTypes) { + public static ReferencedMethodArgumentsResolver forMethod(String methodName, Class... parameterTypes) { - return new ReferencedMethodArgumentsResolver(methodName, parameterTypes, false, - null); + return new ReferencedMethodArgumentsResolver(methodName, parameterTypes, false, null); } /** @@ -99,11 +96,9 @@ public final class ReferencedMethodArgumentsResolver extends AutowiredElementRes * @param parameterTypes the factory method parameter types * @return a new {@link AutowiredFieldValueResolver} instance */ - public static ReferencedMethodArgumentsResolver forRequiredMethod(String methodName, - Class... parameterTypes) { + public static ReferencedMethodArgumentsResolver forRequiredMethod(String methodName, Class... parameterTypes) { - return new ReferencedMethodArgumentsResolver(methodName, parameterTypes, true, - null); + return new ReferencedMethodArgumentsResolver(methodName, parameterTypes, true, null); } /** @@ -116,8 +111,7 @@ public final class ReferencedMethodArgumentsResolver extends AutowiredElementRes * the shortcuts */ public ReferencedMethodArgumentsResolver withShortcut(String... beanNames) { - return new ReferencedMethodArgumentsResolver(this.methodName, this.parameterTypes, - this.required, beanNames); + return new ReferencedMethodArgumentsResolver(this.methodName, this.parameterTypes, this.required, beanNames); } /** @@ -127,8 +121,7 @@ public final class ReferencedMethodArgumentsResolver extends AutowiredElementRes * @param registeredBean the registered bean * @param action the action to execute with the resolved method arguments */ - public void resolve(RegisteredBean registeredBean, - ThrowingConsumer action) { + public void resolve(RegisteredBean registeredBean, ThrowingConsumer action) { Assert.notNull(registeredBean, "'registeredBean' must not be null"); Assert.notNull(action, "'action' must not be null"); @@ -169,8 +162,7 @@ public final class ReferencedMethodArgumentsResolver extends AutowiredElementRes } @Nullable - private AutowiredArguments resolveArguments(RegisteredBean registeredBean, - Method method) { + private AutowiredArguments resolveArguments(RegisteredBean registeredBean, Method method) { String beanName = registeredBean.getBeanName(); Class beanClass = registeredBean.getBeanClass(); @@ -183,22 +175,19 @@ public final class ReferencedMethodArgumentsResolver extends AutowiredElementRes TypeConverter typeConverter = beanFactory.getTypeConverter(); for (int i = 0; i < argumentCount; i++) { MethodParameter parameter = new MethodParameter(method, i); - DependencyDescriptor descriptor = new DependencyDescriptor(parameter, - this.required); + DependencyDescriptor descriptor = new DependencyDescriptor(parameter, this.required); descriptor.setContainingClass(beanClass); String shortcut = (this.shortcuts != null) ? this.shortcuts[i] : null; if (shortcut != null) { - descriptor = new ShortcutDependencyDescriptor(descriptor, shortcut, - parameter.getParameterType()); + descriptor = new ShortcutDependencyDescriptor(descriptor, shortcut, parameter.getParameterType()); } try { Object injectedArgument = beanFactory.getBean(shortcut); - Object argument = autowireCapableBeanFactory.resolveDependency(descriptor, - beanName, autowiredBeanNames, typeConverter); + Object argument = autowireCapableBeanFactory.resolveDependency( + descriptor, beanName, autowiredBeanNames, typeConverter); arguments[i] = injectedArgument; } catch (BeansException ex) { - throw new UnsatisfiedDependencyException(null, beanName, - new InjectionPoint(parameter), ex); + throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(parameter), ex); } } registerDependentBeans(beanFactory, beanName, autowiredBeanNames); @@ -206,16 +195,16 @@ public final class ReferencedMethodArgumentsResolver extends AutowiredElementRes } private Method getMethod(RegisteredBean registeredBean) { - Method method = ReflectionUtils.findMethod(registeredBean.getBeanClass(), - this.methodName, this.parameterTypes); - Assert.notNull(method, () -> - "Method '" + this.methodName + "' with parameter types [" + toCommaSeparatedNames(this.parameterTypes) + "] declared on " + registeredBean.getBeanClass().getName() + " could not be found."); + Method method = ReflectionUtils.findMethod(registeredBean.getBeanClass(), this.methodName, this.parameterTypes); + Assert.notNull( + method, + () -> "Method '" + this.methodName + "' with parameter types [" + + toCommaSeparatedNames(this.parameterTypes) + "] declared on " + + registeredBean.getBeanClass().getName() + " could not be found."); return method; } private String toCommaSeparatedNames(Class... parameterTypes) { - return Arrays.stream(parameterTypes).map(Class::getName) - .collect(Collectors.joining(", ")); + return Arrays.stream(parameterTypes).map(Class::getName).collect(Collectors.joining(", ")); } - } diff --git a/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/context/DubboInfraBeanRegisterPostProcessor.java b/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/context/DubboInfraBeanRegisterPostProcessor.java index 3595122551..f3da47208f 100644 --- a/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/context/DubboInfraBeanRegisterPostProcessor.java +++ b/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/context/DubboInfraBeanRegisterPostProcessor.java @@ -21,7 +21,6 @@ import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; - /** * Register some infrastructure beans if not exists. * This post-processor MUST impl BeanDefinitionRegistryPostProcessor, @@ -33,11 +32,8 @@ import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProce public class DubboInfraBeanRegisterPostProcessor implements BeanDefinitionRegistryPostProcessor { @Override - public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { - } + public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {} @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { - } - + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {} } diff --git a/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/utils/AotUtils.java b/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/utils/AotUtils.java index 45b24dcf7e..d4b056045f 100644 --- a/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/utils/AotUtils.java +++ b/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/utils/AotUtils.java @@ -14,27 +14,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.config.spring6.utils; import org.apache.dubbo.common.compiler.support.ClassUtils; -import org.springframework.aot.hint.RuntimeHints; -import org.springframework.aot.hint.TypeReference; import java.io.Serializable; import java.util.Arrays; import java.util.Date; +import org.springframework.aot.hint.RuntimeHints; +import org.springframework.aot.hint.TypeReference; public class AotUtils { - private AotUtils() { - - } + private AotUtils() {} public static void registerSerializationForService(Class serviceType, RuntimeHints hints) { Arrays.stream(serviceType.getMethods()).forEach((method) -> { - Arrays.stream(method.getParameterTypes()).forEach((parameterType) -> registerSerializationType(parameterType, hints)); + Arrays.stream(method.getParameterTypes()) + .forEach((parameterType) -> registerSerializationType(parameterType, hints)); registerSerializationType(method.getReturnType(), hints); }); @@ -47,18 +45,26 @@ public class AotUtils { if (Serializable.class.isAssignableFrom(registerType)) { hints.serialization().registerType(TypeReference.of(registerType)); - Arrays.stream(registerType.getDeclaredFields()).forEach((field -> registerSerializationType(field.getType(), hints))); + Arrays.stream(registerType.getDeclaredFields()) + .forEach((field -> registerSerializationType(field.getType(), hints))); registerSerializationType(registerType.getSuperclass(), hints); } } - } private static boolean isPrimitive(Class cls) { - return cls.isPrimitive() || cls == Boolean.class || cls == Byte.class - || cls == Character.class || cls == Short.class || cls == Integer.class - || cls == Long.class || cls == Float.class || cls == Double.class - || cls == String.class || cls == Date.class || cls == Class.class; + return cls.isPrimitive() + || cls == Boolean.class + || cls == Byte.class + || cls == Character.class + || cls == Short.class + || cls == Integer.class + || cls == Long.class + || cls == Float.class + || cls == Double.class + || cls == String.class + || cls == Date.class + || cls == Class.class; } } diff --git a/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/AotUtilsTest.java b/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/AotUtilsTest.java index de14a218d8..392518ba7b 100644 --- a/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/AotUtilsTest.java +++ b/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/AotUtilsTest.java @@ -16,13 +16,12 @@ */ package org.apache.dubbo.config.spring6.utils; +import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.aot.hint.RuntimeHints; -import java.util.concurrent.atomic.AtomicBoolean; - public class AotUtilsTest { @Test @@ -72,5 +71,4 @@ public class AotUtilsTest { Assertions.assertTrue(containHelloRequestSuper.get()); Assertions.assertTrue(containHelloResponse.get()); } - } diff --git a/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/DemoService.java b/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/DemoService.java index 1d8f623bca..73e9541e90 100644 --- a/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/DemoService.java +++ b/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/DemoService.java @@ -16,9 +16,7 @@ */ package org.apache.dubbo.config.spring6.utils; - public interface DemoService { HelloResponse sayHello(HelloRequest request); - } diff --git a/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/HelloRequest.java b/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/HelloRequest.java index f7dbd3e4ef..e2725b6160 100644 --- a/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/HelloRequest.java +++ b/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/HelloRequest.java @@ -21,7 +21,6 @@ import java.io.Serializable; public class HelloRequest extends HelloRequestSuper implements Serializable { private Person person; - public HelloRequest(Person person) { this.person = person; } diff --git a/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/HelloRequestSuper.java b/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/HelloRequestSuper.java index a6c2e49644..9f9798114f 100644 --- a/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/HelloRequestSuper.java +++ b/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/HelloRequestSuper.java @@ -21,8 +21,7 @@ import java.io.Serializable; public class HelloRequestSuper implements Serializable { private String su; - public HelloRequestSuper() { - } + public HelloRequestSuper() {} public HelloRequestSuper(String su) { this.su = su; diff --git a/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/HelloResponse.java b/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/HelloResponse.java index 59389e4e61..5c861e39c5 100644 --- a/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/HelloResponse.java +++ b/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/HelloResponse.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.config.spring6.utils; - import java.io.Serializable; public class HelloResponse implements Serializable { diff --git a/dubbo-config/pom.xml b/dubbo-config/pom.xml index 0c57ca80f3..ecfb4322ec 100644 --- a/dubbo-config/pom.xml +++ b/dubbo-config/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - org.apache.dubbo - dubbo-parent - ${revision} - - dubbo-config - pom - ${project.artifactId} - The config module of dubbo project - - false - - + + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + + dubbo-config + pom + ${project.artifactId} + The config module of dubbo project + + dubbo-config-api + dubbo-config-spring + + + false + + + + + org.apache.dubbo + dubbo-test-check + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-test-common + ${project.parent.version} + test + + + + + + spring6 + + [17,) + + dubbo-config-api dubbo-config-spring - - - - - org.apache.dubbo - dubbo-test-check - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-test-common - ${project.parent.version} - test - - - - - - spring6 - - [17,) - - - dubbo-config-api - dubbo-config-spring - dubbo-config-spring6 - - - - release - - dubbo-config-spring6 - - - - jdk-version-ge-17 - - [17,) - - - dubbo-config-spring6 - - - + dubbo-config-spring6 + + + + release + + dubbo-config-spring6 + + + + jdk-version-ge-17 + + [17,) + + + dubbo-config-spring6 + + + diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml b/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml index fb39e096c2..d561592e9c 100644 --- a/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml +++ b/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 + 4.0.0 - - org.apache.dubbo - dubbo-configcenter - ${revision} - + + org.apache.dubbo + dubbo-configcenter + ${revision} + - dubbo-configcenter-apollo - jar - ${project.artifactId} - The Apollo implementation of the configcenter api - - false - 2.1.0 - + dubbo-configcenter-apollo + jar + ${project.artifactId} + The Apollo implementation of the configcenter api + + false + 2.1.0 + - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-prometheus - ${project.parent.version} - - - com.ctrip.framework.apollo - apollo-client - - - com.ctrip.framework.apollo - apollo-mockserver - ${apollo_mock_server_version} - test - - - org.apache.dubbo - dubbo-metrics-config-center - ${project.parent.version} - - + + + org.apache.dubbo + dubbo-common + ${project.parent.version} + + + org.apache.dubbo + dubbo-metrics-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-metrics-default + ${project.parent.version} + + + org.apache.dubbo + dubbo-metrics-prometheus + ${project.parent.version} + + + com.ctrip.framework.apollo + apollo-client + + + com.ctrip.framework.apollo + apollo-mockserver + ${apollo_mock_server_version} + test + + + org.apache.dubbo + dubbo-metrics-config-center + ${project.parent.version} + + diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java index 75b6973f1f..b9506d3fe3 100644 --- a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java @@ -16,14 +16,6 @@ */ package org.apache.dubbo.configcenter.support.apollo; -import com.ctrip.framework.apollo.Config; -import com.ctrip.framework.apollo.ConfigChangeListener; -import com.ctrip.framework.apollo.ConfigFile; -import com.ctrip.framework.apollo.ConfigService; -import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; -import com.ctrip.framework.apollo.enums.ConfigSourceType; -import com.ctrip.framework.apollo.enums.PropertyChangeType; -import com.ctrip.framework.apollo.model.ConfigChange; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; @@ -44,6 +36,15 @@ import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.stream.Collectors; +import com.ctrip.framework.apollo.Config; +import com.ctrip.framework.apollo.ConfigChangeListener; +import com.ctrip.framework.apollo.ConfigFile; +import com.ctrip.framework.apollo.ConfigService; +import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; +import com.ctrip.framework.apollo.enums.ConfigSourceType; +import com.ctrip.framework.apollo.enums.PropertyChangeType; +import com.ctrip.framework.apollo.model.ConfigChange; + import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY; @@ -67,7 +68,8 @@ import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE; * Please see http://dubbo.apache.org/zh-cn/docs/user/configuration/config-center.html for details. */ public class ApolloDynamicConfiguration implements DynamicConfiguration { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ApolloDynamicConfiguration.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ApolloDynamicConfiguration.class); private static final String APOLLO_ENV_KEY = "env"; private static final String APOLLO_ADDR_KEY = "apollo.meta"; private static final String APOLLO_CLUSTER_KEY = "apollo.cluster"; @@ -84,7 +86,8 @@ public class ApolloDynamicConfiguration implements DynamicConfiguration { ApolloDynamicConfiguration(URL url, ApplicationModel applicationModel) { this.url = url; this.applicationModel = applicationModel; - // Instead of using Dubbo's configuration, I would suggest use the original configuration method Apollo provides. + // Instead of using Dubbo's configuration, I would suggest use the original configuration method Apollo + // provides. String configEnv = url.getParameter(APOLLO_ENV_KEY); String configAddr = getAddressWithProtocolPrefix(url); String configCluster = url.getParameter(CLUSTER_KEY); @@ -111,15 +114,18 @@ public class ApolloDynamicConfiguration implements DynamicConfiguration { boolean check = url.getParameter(CHECK_KEY, true); if (dubboConfig.getSourceType() != ConfigSourceType.REMOTE) { if (check) { - throw new IllegalStateException("Failed to connect to config center, the config center is Apollo, " + - "the address is: " + (StringUtils.isNotEmpty(configAddr) ? configAddr : configEnv)); + throw new IllegalStateException("Failed to connect to config center, the config center is Apollo, " + + "the address is: " + (StringUtils.isNotEmpty(configAddr) ? configAddr : configEnv)); } else { // 5-1 Failed to connect to configuration center. - logger.warn(CONFIG_FAILED_CONNECT_REGISTRY, "configuration server offline", "", - "Failed to connect to config center, the config center is Apollo, " + - "the address is: " + (StringUtils.isNotEmpty(configAddr) ? configAddr : configEnv) + - ", will use the local cache value instead before eventually the connection is established."); + logger.warn( + CONFIG_FAILED_CONNECT_REGISTRY, + "configuration server offline", + "", + "Failed to connect to config center, the config center is Apollo, " + "the address is: " + + (StringUtils.isNotEmpty(configAddr) ? configAddr : configEnv) + + ", will use the local cache value instead before eventually the connection is established."); } } } @@ -129,7 +135,11 @@ public class ApolloDynamicConfiguration implements DynamicConfiguration { try { listeners.clear(); } catch (UnsupportedOperationException e) { - logger.warn(CONFIG_FAILED_CLOSE_CONNECT_APOLLO, "", "", "Failed to close connect from config center, the config center is Apollo"); + logger.warn( + CONFIG_FAILED_CLOSE_CONNECT_APOLLO, + "", + "", + "Failed to close connect from config center, the config center is Apollo"); } } @@ -137,13 +147,13 @@ public class ApolloDynamicConfiguration implements DynamicConfiguration { String address = url.getBackupAddress(); if (StringUtils.isNotEmpty(address)) { address = Arrays.stream(COMMA_SPLIT_PATTERN.split(address)) - .map(addr -> { - if (addr.startsWith(APOLLO_PROTOCOL_PREFIX)) { - return addr; - } - return APOLLO_PROTOCOL_PREFIX + addr; - }) - .collect(Collectors.joining(",")); + .map(addr -> { + if (addr.startsWith(APOLLO_PROTOCOL_PREFIX)) { + return addr; + } + return APOLLO_PROTOCOL_PREFIX + addr; + }) + .collect(Collectors.joining(",")); } return address; } @@ -200,7 +210,8 @@ public class ApolloDynamicConfiguration implements DynamicConfiguration { return dubboConfigFile.getContent(); } if (group.equals(url.getApplication())) { - return ConfigService.getConfigFile(APOLLO_APPLICATION_KEY, ConfigFileFormat.Properties).getContent(); + return ConfigService.getConfigFile(APOLLO_APPLICATION_KEY, ConfigFileFormat.Properties) + .getContent(); } ConfigFile configFile = ConfigService.getConfigFile(group, ConfigFileFormat.Properties); @@ -235,24 +246,33 @@ public class ApolloDynamicConfiguration implements DynamicConfiguration { private Set listeners = new CopyOnWriteArraySet<>(); - ApolloListener() { - } + ApolloListener() {} @Override public void onChange(com.ctrip.framework.apollo.model.ConfigChangeEvent changeEvent) { for (String key : changeEvent.changedKeys()) { ConfigChange change = changeEvent.getChange(key); if ("".equals(change.getNewValue())) { - logger.warn(CONFIG_NOT_EFFECT_EMPTY_RULE_APOLLO, "", "", "an empty rule is received for " + key + ", the current working rule is " + - change.getOldValue() + ", the empty rule will not take effect."); + logger.warn( + CONFIG_NOT_EFFECT_EMPTY_RULE_APOLLO, + "", + "", + "an empty rule is received for " + key + ", the current working rule is " + + change.getOldValue() + ", the empty rule will not take effect."); return; } - ConfigChangedEvent event = new ConfigChangedEvent(key, change.getNamespace(), change.getNewValue(), getChangeType(change)); + ConfigChangedEvent event = + new ConfigChangedEvent(key, change.getNamespace(), change.getNewValue(), getChangeType(change)); listeners.forEach(listener -> listener.process(event)); - MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent(applicationModel, event.getKey(), event.getGroup(), - ConfigCenterEvent.APOLLO_PROTOCOL, ConfigChangeType.ADDED.name(), SELF_INCREMENT_SIZE)); + MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent( + applicationModel, + event.getKey(), + event.getGroup(), + ConfigCenterEvent.APOLLO_PROTOCOL, + ConfigChangeType.ADDED.name(), + SELF_INCREMENT_SIZE)); } } @@ -275,5 +295,4 @@ public class ApolloDynamicConfiguration implements DynamicConfiguration { return listeners != null && listeners.size() > 0; } } - } diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationFactory.java b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationFactory.java index 64331d886b..64c93f65c4 100644 --- a/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationFactory.java +++ b/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationFactory.java @@ -27,11 +27,11 @@ import org.apache.dubbo.rpc.model.ApplicationModel; public class ApolloDynamicConfigurationFactory extends AbstractDynamicConfigurationFactory { private ApplicationModel applicationModel; - + public ApolloDynamicConfigurationFactory(ApplicationModel applicationModel) { this.applicationModel = applicationModel; } - + @Override protected DynamicConfiguration createDynamicConfiguration(URL url) { return new ApolloDynamicConfiguration(url, applicationModel); diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationTest.java index 07aa131e67..3558272881 100644 --- a/dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationTest.java +++ b/dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationTest.java @@ -19,13 +19,7 @@ package org.apache.dubbo.configcenter.support.apollo; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; import org.apache.dubbo.common.config.configcenter.ConfigurationListener; - -import com.google.common.util.concurrent.SettableFuture; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; import java.io.FileOutputStream; import java.io.IOException; @@ -33,6 +27,12 @@ import java.util.Properties; import java.util.Random; import java.util.concurrent.TimeUnit; +import com.google.common.util.concurrent.SettableFuture; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.fail; @@ -61,27 +61,28 @@ class ApolloDynamicConfigurationTest { @BeforeEach public void setUp() { String apolloUrl = System.getProperty("apollo.configService"); - String urlForDubbo = "apollo://" + apolloUrl.substring(apolloUrl.lastIndexOf("/") + 1) + "/org.apache.dubbo.apollo.testService?namespace=dubbo&check=true"; + String urlForDubbo = "apollo://" + apolloUrl.substring(apolloUrl.lastIndexOf("/") + 1) + + "/org.apache.dubbo.apollo.testService?namespace=dubbo&check=true"; url = URL.valueOf(urlForDubbo).addParameter(SESSION_TIMEOUT_KEY, 15000); applicationModel = ApplicationModel.defaultModel(); } -// /** -// * Embedded Apollo does not work as expected. -// */ -// @Test -// public void testProperties() { -// URL url = this.url.addParameter(GROUP_KEY, "dubbo") -// .addParameter("namespace", "governance"); -// -// apolloDynamicConfiguration = new ApolloDynamicConfiguration(url); -// putData("dubbo", "dubbo.registry.address", "zookeeper://127.0.0.1:2181"); -// assertEquals("zookeeper://127.0.0.1:2181", apolloDynamicConfiguration.getProperties(null, "dubbo")); -// -// putData("governance", "router.tag", "router tag rule"); -// assertEquals("router tag rule", apolloDynamicConfiguration.getConfig("router.tag", "governance")); -// -// } + // /** + // * Embedded Apollo does not work as expected. + // */ + // @Test + // public void testProperties() { + // URL url = this.url.addParameter(GROUP_KEY, "dubbo") + // .addParameter("namespace", "governance"); + // + // apolloDynamicConfiguration = new ApolloDynamicConfiguration(url); + // putData("dubbo", "dubbo.registry.address", "zookeeper://127.0.0.1:2181"); + // assertEquals("zookeeper://127.0.0.1:2181", apolloDynamicConfiguration.getProperties(null, "dubbo")); + // + // putData("governance", "router.tag", "router tag rule"); + // assertEquals("router tag rule", apolloDynamicConfiguration.getConfig("router.tag", "governance")); + // + // } /** * Test get rule. @@ -130,7 +131,8 @@ class ApolloDynamicConfigurationTest { String mockKey = "mockKey3"; String mockValue = String.valueOf(new Random().nextInt()); - final SettableFuture future = SettableFuture.create(); + final SettableFuture future = + SettableFuture.create(); apolloDynamicConfiguration = new ApolloDynamicConfiguration(url, applicationModel); @@ -157,7 +159,8 @@ class ApolloDynamicConfigurationTest { } private static void putMockRuleData(String key, String value, String group) { - String fileName = ApolloDynamicConfigurationTest.class.getResource("/").getPath() + "mockdata-" + group + ".properties"; + String fileName = + ApolloDynamicConfigurationTest.class.getResource("/").getPath() + "mockdata-" + group + ".properties"; putMockData(key, value, fileName); } @@ -186,8 +189,5 @@ class ApolloDynamicConfigurationTest { * Tear down. */ @AfterEach - public void tearDown() { - - } - + public void tearDown() {} } diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support/apollo/EmbeddedApolloJunit5.java b/dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support/apollo/EmbeddedApolloJunit5.java index 1bb7f5527a..e234150ff6 100644 --- a/dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support/apollo/EmbeddedApolloJunit5.java +++ b/dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support/apollo/EmbeddedApolloJunit5.java @@ -14,13 +14,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.configcenter.support.apollo; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.JsonUtils; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.core.dto.ApolloConfig; import com.ctrip.framework.apollo.core.dto.ApolloConfigNotification; @@ -36,17 +42,11 @@ import org.junit.jupiter.api.extension.AfterAllCallback; import org.junit.jupiter.api.extension.BeforeAllCallback; import org.junit.jupiter.api.extension.ExtensionContext; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_CLOSE_CONNECT_APOLLO; public class EmbeddedApolloJunit5 implements BeforeAllCallback, AfterAllCallback { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(EmbeddedApolloJunit5.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(EmbeddedApolloJunit5.class); private static Method CONFIG_SERVICE_LOCATOR_CLEAR; private static ConfigServiceLocator CONFIG_SERVICE_LOCATOR; @@ -92,11 +92,12 @@ public class EmbeddedApolloJunit5 implements BeforeAllCallback, AfterAllCallback } private String mockLongPollBody(String notificationsStr) { - List oldNotifications = JsonUtils.toJavaList(notificationsStr, ApolloConfigNotification.class); + List oldNotifications = + JsonUtils.toJavaList(notificationsStr, ApolloConfigNotification.class); List newNotifications = new ArrayList<>(); for (ApolloConfigNotification notification : oldNotifications) { - newNotifications - .add(new ApolloConfigNotification(notification.getNamespaceName(), notification.getNotificationId() + 1)); + newNotifications.add(new ApolloConfigNotification( + notification.getNamespaceName(), notification.getNotificationId() + 1)); } return JsonUtils.toJson(newNotifications); } diff --git a/dubbo-configcenter/dubbo-configcenter-file/pom.xml b/dubbo-configcenter/dubbo-configcenter-file/pom.xml index 5341422843..c6c403fcfa 100644 --- a/dubbo-configcenter/dubbo-configcenter-file/pom.xml +++ b/dubbo-configcenter/dubbo-configcenter-file/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 + 4.0.0 - - org.apache.dubbo - dubbo-configcenter - ${revision} - + + org.apache.dubbo + dubbo-configcenter + ${revision} + - dubbo-configcenter-file - jar - ${project.artifactId} - The File implementation of the configcenter api - - false - + dubbo-configcenter-file + jar + ${project.artifactId} + The File implementation of the configcenter api + + false + - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-prometheus - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-config-center - ${project.parent.version} - - + + + org.apache.dubbo + dubbo-common + ${project.parent.version} + + + org.apache.dubbo + dubbo-metrics-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-metrics-default + ${project.parent.version} + + + org.apache.dubbo + dubbo-metrics-prometheus + ${project.parent.version} + + + org.apache.dubbo + dubbo-metrics-config-center + ${project.parent.version} + + diff --git a/dubbo-configcenter/dubbo-configcenter-file/src/main/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-file/src/main/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfiguration.java index cf055349aa..c18bd074e6 100644 --- a/dubbo-configcenter/dubbo-configcenter-file/src/main/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-file/src/main/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfiguration.java @@ -32,8 +32,6 @@ import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.model.ScopeModel; import org.apache.dubbo.rpc.model.ScopeModelUtil; -import org.apache.commons.io.FileUtils; - import java.io.File; import java.io.IOException; import java.nio.file.FileSystem; @@ -61,6 +59,8 @@ import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.apache.commons.io.FileUtils; + import static java.lang.String.format; import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE; import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE; @@ -83,8 +83,8 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration public static final String CONFIG_CENTER_ENCODING_PARAM_NAME = PARAM_NAME_PREFIX + "encoding"; - public static final String DEFAULT_CONFIG_CENTER_DIR_PATH = System.getProperty("user.home") + File.separator - + ".dubbo" + File.separator + "config-center"; + public static final String DEFAULT_CONFIG_CENTER_DIR_PATH = + System.getProperty("user.home") + File.separator + ".dubbo" + File.separator + "config-center"; public static final int DEFAULT_THREAD_POOL_SIZE = 1; @@ -102,22 +102,22 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration /** * Logger */ - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FileSystemDynamicConfiguration.class); - + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(FileSystemDynamicConfiguration.class); /** * The unmodifiable map for {@link ConfigChangeType} whose key is the {@link WatchEvent.Kind#name() name} of * {@link WatchEvent.Kind WatchEvent's Kind} */ private static final Map CONFIG_CHANGE_TYPES_MAP = - unmodifiableMap(new HashMap() { - // Initializes the elements that is mapping ConfigChangeType - { - put(ENTRY_CREATE.name(), ConfigChangeType.ADDED); - put(ENTRY_DELETE.name(), ConfigChangeType.DELETED); - put(ENTRY_MODIFY.name(), ConfigChangeType.MODIFIED); - } - }); + unmodifiableMap(new HashMap() { + // Initializes the elements that is mapping ConfigChangeType + { + put(ENTRY_CREATE.name(), ConfigChangeType.ADDED); + put(ENTRY_DELETE.name(), ConfigChangeType.DELETED); + put(ENTRY_MODIFY.name(), ConfigChangeType.MODIFIED); + } + }); private static final Optional watchService; @@ -189,15 +189,13 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration this(rootDirectory, encoding, threadPoolPrefixName, DEFAULT_THREAD_POOL_SIZE); } - public FileSystemDynamicConfiguration(File rootDirectory, String encoding, String threadPoolPrefixName, - int threadPoolSize) { + public FileSystemDynamicConfiguration( + File rootDirectory, String encoding, String threadPoolPrefixName, int threadPoolSize) { this(rootDirectory, encoding, threadPoolPrefixName, threadPoolSize, DEFAULT_THREAD_POOL_KEEP_ALIVE_TIME); } - public FileSystemDynamicConfiguration(File rootDirectory, String encoding, - String threadPoolPrefixName, - int threadPoolSize, - long keepAliveTime) { + public FileSystemDynamicConfiguration( + File rootDirectory, String encoding, String threadPoolPrefixName, int threadPoolSize, long keepAliveTime) { super(rootDirectory.getAbsolutePath(), threadPoolPrefixName, threadPoolSize, keepAliveTime, DEFAULT_GROUP, -1L); this.rootDirectory = rootDirectory; this.encoding = encoding; @@ -206,11 +204,13 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration registerDubboShutdownHook(); } - public FileSystemDynamicConfiguration(File rootDirectory, String encoding, - String threadPoolPrefixName, - int threadPoolSize, - long keepAliveTime, - ScopeModel scopeModel) { + public FileSystemDynamicConfiguration( + File rootDirectory, + String encoding, + String threadPoolPrefixName, + int threadPoolSize, + long keepAliveTime, + ScopeModel scopeModel) { super(rootDirectory.getAbsolutePath(), threadPoolPrefixName, threadPoolSize, keepAliveTime, DEFAULT_GROUP, -1L); this.rootDirectory = rootDirectory; this.encoding = encoding; @@ -221,8 +221,13 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration } public FileSystemDynamicConfiguration(URL url) { - this(initDirectory(url), getEncoding(url), getThreadPoolPrefixName(url), getThreadPoolSize(url), - getThreadPoolKeepAliveTime(url), url.getScopeModel()); + this( + initDirectory(url), + getEncoding(url), + getThreadPoolPrefixName(url), + getThreadPoolSize(url), + getThreadPoolKeepAliveTime(url), + url.getScopeModel()); } private Set initProcessingDirectories() { @@ -260,7 +265,8 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration if (!hasRegisteredShutdownHook.compareAndSet(false, true)) { return; } - ShutdownHookCallbacks shutdownHookCallbacks = ScopeModelUtil.getApplicationModel(scopeModel).getBeanFactory().getBean(ShutdownHookCallbacks.class); + ShutdownHookCallbacks shutdownHookCallbacks = + ScopeModelUtil.getApplicationModel(scopeModel).getBeanFactory().getBean(ShutdownHookCallbacks.class); shutdownHookCallbacks.addCallback(() -> { watchService.ifPresent(w -> { try { @@ -283,47 +289,50 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration * @param watchService {@link WatchService} */ private void processWatchEvents(WatchService watchService) { - getWatchEventsLoopThreadPool().execute(() -> { // WatchEvents Loop - while (true) { - WatchKey watchKey = null; - try { - watchKey = watchService.take(); + getWatchEventsLoopThreadPool() + .execute( + () -> { // WatchEvents Loop + while (true) { + WatchKey watchKey = null; + try { + watchKey = watchService.take(); - if (!watchKey.isValid()) { - continue; - } + if (!watchKey.isValid()) { + continue; + } - for (WatchEvent event : watchKey.pollEvents()) { - WatchEvent.Kind kind = event.kind(); - // configChangeType's key to match WatchEvent's Kind - ConfigChangeType configChangeType = CONFIG_CHANGE_TYPES_MAP.get(kind.name()); + for (WatchEvent event : watchKey.pollEvents()) { + WatchEvent.Kind kind = event.kind(); + // configChangeType's key to match WatchEvent's Kind + ConfigChangeType configChangeType = CONFIG_CHANGE_TYPES_MAP.get(kind.name()); - if (configChangeType == null) { - continue; - } + if (configChangeType == null) { + continue; + } - Path configDirectoryPath = (Path) watchKey.watchable(); - Path currentPath = (Path) event.context(); - Path configFilePath = configDirectoryPath.resolve(currentPath); - File configDirectory = configDirectoryPath.toFile(); + Path configDirectoryPath = (Path) watchKey.watchable(); + Path currentPath = (Path) event.context(); + Path configFilePath = configDirectoryPath.resolve(currentPath); + File configDirectory = configDirectoryPath.toFile(); - executeMutually(configDirectory, () -> { - fireConfigChangeEvent(configDirectory, configFilePath.toFile(), configChangeType); - signalConfigDirectory(configDirectory); - return null; + executeMutually(configDirectory, () -> { + fireConfigChangeEvent( + configDirectory, configFilePath.toFile(), configChangeType); + signalConfigDirectory(configDirectory); + return null; + }); + } + + } catch (Exception e) { + return; + } finally { + if (watchKey != null) { + // reset + watchKey.reset(); + } + } + } }); - } - - } catch (Exception e) { - return; - } finally { - if (watchKey != null) { - // reset - watchKey.reset(); - } - } - } - }); } private void signalConfigDirectory(File configDirectory) { @@ -404,9 +413,7 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration if (files == null) { return new TreeSet<>(); } else { - return Stream.of(files) - .map(File::getName) - .collect(Collectors.toList()); + return Stream.of(files).map(File::getName).collect(Collectors.toList()); } } @@ -457,8 +464,8 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration // wait for delay in seconds long timeout = SECONDS.toMillis(delay); if (logger.isDebugEnabled()) { - logger.debug(format("The config[path : %s] is about to delay in %d ms.", - configFilePath, timeout)); + logger.debug(format( + "The config[path : %s] is about to delay in %d ms.", configFilePath, timeout)); } configDirectory.wait(timeout); } @@ -501,20 +508,18 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration public Set getConfigGroups() { return Stream.of(getRootDirectory().listFiles()) - .filter(File::isDirectory) - .map(File::getName) - .collect(Collectors.toSet()); + .filter(File::isDirectory) + .map(File::getName) + .collect(Collectors.toSet()); } protected String getConfig(File configFile) { - return ThrowableFunction.execute(configFile, - file -> canRead(configFile) ? readFileToString(configFile, getEncoding()) : null); + return ThrowableFunction.execute( + configFile, file -> canRead(configFile) ? readFileToString(configFile, getEncoding()) : null); } @Override - protected void doClose() throws Exception { - - } + protected void doClose() throws Exception {} public File getRootDirectory() { return rootDirectory; @@ -589,7 +594,8 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration * @return if based, return true, or false */ private static boolean detectPoolingBasedWatchService(Optional watchService) { - String className = watchService.map(Object::getClass).map(Class::getName).orElse(null); + String className = + watchService.map(Object::getClass).map(Class::getName).orElse(null); return POLLING_WATCH_SERVICE_CLASS_NAME.equals(className); } @@ -619,8 +625,8 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration } if (!rootDirectory.exists() && !rootDirectory.mkdirs()) { - throw new IllegalStateException(format("Dubbo config center rootDirectory[%s] can't be created!", - rootDirectory.getAbsolutePath())); + throw new IllegalStateException( + format("Dubbo config center rootDirectory[%s] can't be created!", rootDirectory.getAbsolutePath())); } return rootDirectory; } @@ -630,9 +636,12 @@ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration } private static ThreadPoolExecutor newWatchEventsLoopThreadPool() { - return new ThreadPoolExecutor(THREAD_POOL_SIZE, THREAD_POOL_SIZE, - 0L, MILLISECONDS, - new SynchronousQueue(), - new NamedThreadFactory("dubbo-config-center-watch-events-loop", true)); + return new ThreadPoolExecutor( + THREAD_POOL_SIZE, + THREAD_POOL_SIZE, + 0L, + MILLISECONDS, + new SynchronousQueue(), + new NamedThreadFactory("dubbo-config-center-watch-events-loop", true)); } } diff --git a/dubbo-configcenter/dubbo-configcenter-file/src/test/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfigurationFactoryTest.java b/dubbo-configcenter/dubbo-configcenter-file/src/test/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfigurationFactoryTest.java index 37c3f22847..99e954d392 100644 --- a/dubbo-configcenter/dubbo-configcenter-file/src/test/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfigurationFactoryTest.java +++ b/dubbo-configcenter/dubbo-configcenter-file/src/test/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfigurationFactoryTest.java @@ -32,6 +32,9 @@ class FileSystemDynamicConfigurationFactoryTest { @Test void testGetFactory() { - assertEquals(FileSystemDynamicConfigurationFactory.class, ConfigurationUtils.getDynamicConfigurationFactory(ApplicationModel.defaultModel(), "file").getClass()); + assertEquals( + FileSystemDynamicConfigurationFactory.class, + ConfigurationUtils.getDynamicConfigurationFactory(ApplicationModel.defaultModel(), "file") + .getClass()); } -} \ No newline at end of file +} diff --git a/dubbo-configcenter/dubbo-configcenter-file/src/test/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-file/src/test/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfigurationTest.java index 111b71bd44..7b4dfe8603 100644 --- a/dubbo-configcenter/dubbo-configcenter-file/src/test/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfigurationTest.java +++ b/dubbo-configcenter/dubbo-configcenter-file/src/test/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfigurationTest.java @@ -20,17 +20,17 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; +import java.io.File; +import java.io.IOException; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.atomic.AtomicBoolean; + import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import java.io.File; -import java.io.IOException; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.atomic.AtomicBoolean; - import static org.apache.dubbo.common.URL.valueOf; import static org.apache.dubbo.common.config.configcenter.DynamicConfiguration.DEFAULT_GROUP; import static org.apache.dubbo.common.config.configcenter.file.FileSystemDynamicConfiguration.CONFIG_CENTER_DIR_PARAM_NAME; @@ -64,7 +64,8 @@ class FileSystemDynamicConfigurationTest { } catch (IOException e) { e.printStackTrace(); } - URL url = valueOf("dubbo://127.0.0.1:20880").addParameter(CONFIG_CENTER_DIR_PARAM_NAME, rootDirectory.getAbsolutePath()); + URL url = valueOf("dubbo://127.0.0.1:20880") + .addParameter(CONFIG_CENTER_DIR_PARAM_NAME, rootDirectory.getAbsolutePath()); configuration = new FileSystemDynamicConfiguration(url); } @@ -83,7 +84,8 @@ class FileSystemDynamicConfigurationTest { assertEquals(new File(getClassPath(), "config-center"), configuration.getRootDirectory()); assertEquals("UTF-8", configuration.getEncoding()); - assertEquals(ThreadPoolExecutor.class, configuration.getWorkersThreadPool().getClass()); + assertEquals( + ThreadPoolExecutor.class, configuration.getWorkersThreadPool().getClass()); assertEquals(1, (configuration.getWorkersThreadPool()).getCorePoolSize()); assertEquals(1, (configuration.getWorkersThreadPool()).getMaximumPoolSize()); @@ -110,13 +112,12 @@ class FileSystemDynamicConfigurationTest { AtomicBoolean processedEvent = new AtomicBoolean(); configuration.addListener(KEY, event -> { - processedEvent.set(true); assertEquals(KEY, event.getKey()); - logger.info(String.format("[%s] " + event + "\n", Thread.currentThread().getName())); + logger.info( + String.format("[%s] " + event + "\n", Thread.currentThread().getName())); }); - configuration.publishConfig(KEY, "B"); while (!processedEvent.get()) { Thread.sleep(1 * 1000L); @@ -137,7 +138,8 @@ class FileSystemDynamicConfigurationTest { configuration.addListener("test", "test", event -> { processedEvent.set(true); assertEquals("test", event.getKey()); - logger.info(String.format("[%s] " + event + "\n", Thread.currentThread().getName())); + logger.info( + String.format("[%s] " + event + "\n", Thread.currentThread().getName())); }); processedEvent.set(false); configuration.publishConfig("test", "test", "TEST"); @@ -149,7 +151,6 @@ class FileSystemDynamicConfigurationTest { configuration.publishConfig("test", "test", "TEST"); configuration.publishConfig("test", "test", "TEST"); - processedEvent.set(false); configuration.getRootDirectory(); File keyFile = new File(KEY, DEFAULT_GROUP); @@ -164,23 +165,24 @@ class FileSystemDynamicConfigurationTest { assertTrue(configuration.publishConfig(KEY, DEFAULT_GROUP, "A")); - assertEquals("A", FileUtils.readFileToString(configuration.configFile(KEY, DEFAULT_GROUP), configuration.getEncoding())); + assertEquals( + "A", + FileUtils.readFileToString(configuration.configFile(KEY, DEFAULT_GROUP), configuration.getEncoding())); assertTrue(configuration.removeConfig(KEY, DEFAULT_GROUP)); assertFalse(configuration.configFile(KEY, DEFAULT_GROUP).exists()); - } -// -// @Test -// public void testGetConfigKeys() throws Exception { -// -// assertTrue(configuration.publishConfig("A", DEFAULT_GROUP, "A")); -// -// assertTrue(configuration.publishConfig("B", DEFAULT_GROUP, "B")); -// -// assertTrue(configuration.publishConfig("C", DEFAULT_GROUP, "C")); -// -// assertEquals(new TreeSet(asList("A", "B", "C")), configuration.getConfigKeys(DEFAULT_GROUP)); -// } + // + // @Test + // public void testGetConfigKeys() throws Exception { + // + // assertTrue(configuration.publishConfig("A", DEFAULT_GROUP, "A")); + // + // assertTrue(configuration.publishConfig("B", DEFAULT_GROUP, "B")); + // + // assertTrue(configuration.publishConfig("C", DEFAULT_GROUP, "C")); + // + // assertEquals(new TreeSet(asList("A", "B", "C")), configuration.getConfigKeys(DEFAULT_GROUP)); + // } } diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml b/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml index 730c695b31..e3cce7faf9 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml +++ b/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml @@ -15,51 +15,48 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> + + 4.0.0 + + org.apache.dubbo + dubbo-configcenter + ${revision} + - - - org.apache.dubbo - dubbo-configcenter - ${revision} - - 4.0.0 + dubbo-configcenter-nacos + jar + ${project.artifactId} + The nacos implementation of the config-center api - dubbo-configcenter-nacos - jar - ${project.artifactId} - The nacos implementation of the config-center api - - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - com.alibaba.nacos - nacos-client - - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-prometheus - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-config-center - ${project.parent.version} - - + + + org.apache.dubbo + dubbo-common + ${project.parent.version} + + + com.alibaba.nacos + nacos-client + + + org.apache.dubbo + dubbo-metrics-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-metrics-default + ${project.parent.version} + + + org.apache.dubbo + dubbo-metrics-prometheus + ${project.parent.version} + + + org.apache.dubbo + dubbo-metrics-config-center + ${project.parent.version} + + diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java index 1c1e2afda4..74c530e2b0 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.configcenter.support.nacos; import org.apache.dubbo.common.URL; @@ -33,12 +32,6 @@ import org.apache.dubbo.metrics.config.event.ConfigCenterEvent; import org.apache.dubbo.metrics.event.MetricsEventBus; import org.apache.dubbo.rpc.model.ApplicationModel; -import com.alibaba.nacos.api.NacosFactory; -import com.alibaba.nacos.api.PropertyKeyConst; -import com.alibaba.nacos.api.config.ConfigService; -import com.alibaba.nacos.api.config.listener.AbstractSharedListener; -import com.alibaba.nacos.api.exception.NacosException; - import java.util.Map; import java.util.Properties; import java.util.Set; @@ -47,6 +40,12 @@ import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.Executor; +import com.alibaba.nacos.api.NacosFactory; +import com.alibaba.nacos.api.PropertyKeyConst; +import com.alibaba.nacos.api.config.ConfigService; +import com.alibaba.nacos.api.config.listener.AbstractSharedListener; +import com.alibaba.nacos.api.exception.NacosException; + import static com.alibaba.nacos.api.PropertyKeyConst.PASSWORD; import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; import static com.alibaba.nacos.api.PropertyKeyConst.USERNAME; @@ -113,12 +112,18 @@ public class NacosDynamicConfiguration implements DynamicConfiguration { if (!check || (UP.equals(serverStatus) && configServiceAvailable)) { break; } else { - logger.warn(LoggerCodeConstants.CONFIG_ERROR_NACOS, "", "", - "Failed to connect to nacos config server. " + - "Server status: " + serverStatus + ". " + - "Config Service Available: " + configServiceAvailable + ". " + - (i < retryTimes ? "Dubbo will try to retry in " + sleepMsBetweenRetries + ". " : "Exceed retry max times.") + - "Try times: " + (i + 1)); + logger.warn( + LoggerCodeConstants.CONFIG_ERROR_NACOS, + "", + "", + "Failed to connect to nacos config server. " + "Server status: " + + serverStatus + ". " + "Config Service Available: " + + configServiceAvailable + ". " + + (i < retryTimes + ? "Dubbo will try to retry in " + sleepMsBetweenRetries + ". " + : "Exceed retry max times.") + + "Try times: " + + (i + 1)); } tmpConfigServices.shutDown(); tmpConfigServices = null; @@ -134,8 +139,13 @@ public class NacosDynamicConfiguration implements DynamicConfiguration { } if (tmpConfigServices == null) { - logger.error(CONFIG_ERROR_NACOS, "", "", "Failed to create nacos config service client. Reason: server status check failed."); - throw new IllegalStateException("Failed to create nacos config service client. Reason: server status check failed."); + logger.error( + CONFIG_ERROR_NACOS, + "", + "", + "Failed to create nacos config service client. Reason: server status check failed."); + throw new IllegalStateException( + "Failed to create nacos config service client. Reason: server status check failed."); } return new NacosConfigServiceWrapper(tmpConfigServices); @@ -158,8 +168,7 @@ public class NacosDynamicConfiguration implements DynamicConfiguration { } private void setServerAddr(URL url, Properties properties) { - StringBuilder serverAddrBuilder = - new StringBuilder(url.getHost()) // Host + StringBuilder serverAddrBuilder = new StringBuilder(url.getHost()) // Host .append(':') .append(url.getPort()); // Port @@ -222,7 +231,8 @@ public class NacosDynamicConfiguration implements DynamicConfiguration { @Override public void addListener(String key, String group, ConfigurationListener listener) { String listenerKey = buildListenerKey(key, group); - NacosConfigListener nacosConfigListener = ConcurrentHashMapUtils.computeIfAbsent(watchListenerMap, listenerKey, k -> createTargetListener(key, group)); + NacosConfigListener nacosConfigListener = ConcurrentHashMapUtils.computeIfAbsent( + watchListenerMap, listenerKey, k -> createTargetListener(key, group)); nacosConfigListener.addListener(listener); try { configService.addListener(key, group, nacosConfigListener); @@ -343,7 +353,8 @@ public class NacosDynamicConfiguration implements DynamicConfiguration { @Override public void innerReceive(String dataId, String group, String configInfo) { String oldValue = cacheData.get(dataId); - ConfigChangedEvent event = new ConfigChangedEvent(dataId, group, configInfo, getChangeType(configInfo, oldValue)); + ConfigChangedEvent event = + new ConfigChangedEvent(dataId, group, configInfo, getChangeType(configInfo, oldValue)); if (configInfo == null) { cacheData.remove(dataId); } else { @@ -351,8 +362,13 @@ public class NacosDynamicConfiguration implements DynamicConfiguration { } listeners.forEach(listener -> listener.process(event)); - MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent(applicationModel, event.getKey(), event.getGroup(), - ConfigCenterEvent.NACOS_PROTOCOL, ConfigChangeType.ADDED.name(), SELF_INCREMENT_SIZE)); + MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent( + applicationModel, + event.getKey(), + event.getGroup(), + ConfigCenterEvent.NACOS_PROTOCOL, + ConfigChangeType.ADDED.name(), + SELF_INCREMENT_SIZE)); } void addListener(ConfigurationListener configurationListener) { diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationFactory.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationFactory.java index 5d2196726d..762b0161b3 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationFactory.java +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationFactory.java @@ -14,16 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.configcenter.support.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.AbstractDynamicConfigurationFactory; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.constants.CommonConstants; +import org.apache.dubbo.rpc.model.ApplicationModel; import com.alibaba.nacos.api.PropertyKeyConst; -import org.apache.dubbo.rpc.model.ApplicationModel; /** * The nacos implementation of {@link AbstractDynamicConfigurationFactory} @@ -31,7 +30,7 @@ import org.apache.dubbo.rpc.model.ApplicationModel; public class NacosDynamicConfigurationFactory extends AbstractDynamicConfigurationFactory { private ApplicationModel applicationModel; - + public NacosDynamicConfigurationFactory(ApplicationModel applicationModel) { this.applicationModel = applicationModel; } diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/MockConfigService.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/MockConfigService.java index bba7741e64..399401865a 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/MockConfigService.java +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/MockConfigService.java @@ -27,14 +27,13 @@ public class MockConfigService implements ConfigService { } @Override - public String getConfigAndSignListener(String dataId, String group, long timeoutMs, Listener listener) throws NacosException { + public String getConfigAndSignListener(String dataId, String group, long timeoutMs, Listener listener) + throws NacosException { return null; } @Override - public void addListener(String dataId, String group, Listener listener) throws NacosException { - - } + public void addListener(String dataId, String group, Listener listener) throws NacosException {} @Override public boolean publishConfig(String dataId, String group, String content) throws NacosException { @@ -52,7 +51,8 @@ public class MockConfigService implements ConfigService { } @Override - public boolean publishConfigCas(String dataId, String group, String content, String casMd5, String type) throws NacosException { + public boolean publishConfigCas(String dataId, String group, String content, String casMd5, String type) + throws NacosException { return false; } @@ -62,9 +62,7 @@ public class MockConfigService implements ConfigService { } @Override - public void removeListener(String dataId, String group, Listener listener) { - - } + public void removeListener(String dataId, String group, Listener listener) {} @Override public String getServerStatus() { @@ -72,7 +70,5 @@ public class MockConfigService implements ConfigService { } @Override - public void shutDown() throws NacosException { - - } + public void shutDown() throws NacosException {} } diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java index 831c74c833..58fc570740 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java @@ -14,35 +14,34 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.configcenter.support.nacos; -import com.alibaba.nacos.api.NacosFactory; -import com.alibaba.nacos.api.config.ConfigService; -import com.alibaba.nacos.api.exception.NacosException; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; import org.apache.dubbo.common.config.configcenter.ConfigurationListener; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.rpc.model.ApplicationModel; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.CountDownLatch; + +import com.alibaba.nacos.api.NacosFactory; +import com.alibaba.nacos.api.config.ConfigService; +import com.alibaba.nacos.api.exception.NacosException; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.CountDownLatch; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; - /** * Unit test for nacos config center support */ -//FIXME: waiting for embedded Nacos suport, then we can open the switch. +// FIXME: waiting for embedded Nacos suport, then we can open the switch. @Disabled("https://github.com/alibaba/nacos/issues/1188") class NacosDynamicConfigurationTest { private static final String SESSION_TIMEOUT_KEY = "session"; @@ -62,9 +61,16 @@ class NacosDynamicConfigurationTest { Thread.sleep(200); put("org.apache.dubbo.demo.DemoService:1.0.0.test:xxxx.configurators", "helloworld"); Thread.sleep(200); - Assertions.assertEquals("hello", config.getConfig("org.apache.dubbo.nacos.testService.configurators", DynamicConfiguration.DEFAULT_GROUP)); + Assertions.assertEquals( + "hello", + config.getConfig( + "org.apache.dubbo.nacos.testService.configurators", DynamicConfiguration.DEFAULT_GROUP)); Assertions.assertEquals("aaa=bbb", config.getConfig("dubbo.properties", "test")); - Assertions.assertEquals("helloworld", config.getConfig("org.apache.dubbo.demo.DemoService:1.0.0.test:xxxx.configurators", DynamicConfiguration.DEFAULT_GROUP)); + Assertions.assertEquals( + "helloworld", + config.getConfig( + "org.apache.dubbo.demo.DemoService:1.0.0.test:xxxx.configurators", + DynamicConfiguration.DEFAULT_GROUP)); } @Test @@ -75,7 +81,6 @@ class NacosDynamicConfigurationTest { TestListener listener3 = new TestListener(latch); TestListener listener4 = new TestListener(latch); - config.addListener("AService.configurators", listener1); config.addListener("AService.configurators", listener2); config.addListener("testapp.tag-router", listener3); @@ -99,20 +104,19 @@ class NacosDynamicConfigurationTest { Assertions.assertEquals("new value1", listener2.getValue()); Assertions.assertEquals("new value2", listener3.getValue()); Assertions.assertEquals("new value2", listener4.getValue()); - } -// -// @Test -// public void testGetConfigKeys() { -// -// put("key1", "a"); -// put("key2", "b"); -// -// SortedSet keys = config.getConfigKeys(DynamicConfiguration.DEFAULT_GROUP); -// -// Assertions.assertFalse(keys.isEmpty()); -// -// } + // + // @Test + // public void testGetConfigKeys() { + // + // put("key1", "a"); + // put("key2", "b"); + // + // SortedSet keys = config.getConfigKeys(DynamicConfiguration.DEFAULT_GROUP); + // + // Assertions.assertFalse(keys.isEmpty()); + // + // } private void put(String key, String value) { put(key, DynamicConfiguration.DEFAULT_GROUP, value); @@ -130,11 +134,9 @@ class NacosDynamicConfigurationTest { public static void setUp() { String urlForDubbo = "nacos://" + "127.0.0.1:8848" + "/org.apache.dubbo.nacos.testService"; // timeout in 15 seconds. - URL url = URL.valueOf(urlForDubbo) - .addParameter(SESSION_TIMEOUT_KEY, 15000); + URL url = URL.valueOf(urlForDubbo).addParameter(SESSION_TIMEOUT_KEY, 15000); config = new NacosDynamicConfiguration(url, ApplicationModel.defaultModel()); - try { nacosClient = NacosFactory.createConfigService("127.0.0.1:8848"); } catch (NacosException e) { @@ -153,9 +155,7 @@ class NacosDynamicConfigurationTest { } @AfterAll - public static void tearDown() { - - } + public static void tearDown() {} private class TestListener implements ConfigurationListener { private CountDownLatch latch; @@ -183,5 +183,4 @@ class NacosDynamicConfigurationTest { return value; } } - } diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/RetryTest.java b/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/RetryTest.java index 32116ba247..a2ba32785c 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/RetryTest.java +++ b/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/RetryTest.java @@ -16,26 +16,26 @@ */ package org.apache.dubbo.configcenter.support.nacos; -import java.util.Properties; -import java.util.concurrent.atomic.AtomicInteger; - import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.mockito.MockedStatic; -import org.mockito.Mockito; + +import java.util.Properties; +import java.util.concurrent.atomic.AtomicInteger; import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.exception.NacosException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; import static com.alibaba.nacos.client.constant.Constants.HealthCheck.DOWN; import static com.alibaba.nacos.client.constant.Constants.HealthCheck.UP; import static org.mockito.ArgumentMatchers.any; class RetryTest { - + private static ApplicationModel applicationModel = ApplicationModel.defaultModel(); @Test @@ -48,13 +48,15 @@ class RetryTest { return atomicInteger.incrementAndGet() > 10 ? UP : DOWN; } }; - nacosFactoryMockedStatic.when(() -> NacosFactory.createConfigService((Properties) any())).thenReturn(mock); - + nacosFactoryMockedStatic + .when(() -> NacosFactory.createConfigService((Properties) any())) + .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848") - .addParameter("nacos.retry", 5) - .addParameter("nacos.retry-wait", 10); - Assertions.assertThrows(IllegalStateException.class, () -> new NacosDynamicConfiguration(url, applicationModel)); + .addParameter("nacos.retry", 5) + .addParameter("nacos.retry-wait", 10); + Assertions.assertThrows( + IllegalStateException.class, () -> new NacosDynamicConfiguration(url, applicationModel)); try { new NacosDynamicConfiguration(url, applicationModel); @@ -73,13 +75,14 @@ class RetryTest { return DOWN; } }; - nacosFactoryMockedStatic.when(() -> NacosFactory.createConfigService((Properties) any())).thenReturn(mock); - + nacosFactoryMockedStatic + .when(() -> NacosFactory.createConfigService((Properties) any())) + .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848") - .addParameter("nacos.retry", 5) - .addParameter("nacos.retry-wait", 10) - .addParameter("nacos.check", "false"); + .addParameter("nacos.retry", 5) + .addParameter("nacos.retry-wait", 10) + .addParameter("nacos.check", "false"); try { new NacosDynamicConfiguration(url, applicationModel); } catch (Throwable t) { @@ -107,13 +110,15 @@ class RetryTest { return UP; } }; - nacosFactoryMockedStatic.when(() -> NacosFactory.createConfigService((Properties) any())).thenReturn(mock); - + nacosFactoryMockedStatic + .when(() -> NacosFactory.createConfigService((Properties) any())) + .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848") - .addParameter("nacos.retry", 5) - .addParameter("nacos.retry-wait", 10); - Assertions.assertThrows(IllegalStateException.class, () -> new NacosDynamicConfiguration(url, applicationModel)); + .addParameter("nacos.retry", 5) + .addParameter("nacos.retry-wait", 10); + Assertions.assertThrows( + IllegalStateException.class, () -> new NacosDynamicConfiguration(url, applicationModel)); try { new NacosDynamicConfiguration(url, applicationModel); diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/pom.xml b/dubbo-configcenter/dubbo-configcenter-zookeeper/pom.xml index c0689824df..c1deb8c3e5 100644 --- a/dubbo-configcenter/dubbo-configcenter-zookeeper/pom.xml +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-configcenter - ${revision} - ../pom.xml - - dubbo-configcenter-zookeeper - jar - ${project.artifactId} - The zookeeper implementation of the config-center api + 4.0.0 + + org.apache.dubbo + dubbo-configcenter + ${revision} + ../pom.xml + + dubbo-configcenter-zookeeper + jar + ${project.artifactId} + The zookeeper implementation of the config-center api - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-zookeeper-curator5 - ${project.parent.version} - + + + org.apache.dubbo + dubbo-common + ${project.parent.version} + + + org.apache.dubbo + dubbo-remoting-zookeeper-curator5 + ${project.parent.version} + - - org.apache.dubbo - dubbo-test-common - ${project.parent.version} - test - + + org.apache.dubbo + dubbo-test-common + ${project.parent.version} + test + - - org.apache.curator - curator-framework - test - - - org.apache.curator - curator-recipes - test - - - org.apache.zookeeper - zookeeper - - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-prometheus - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-config-center - ${project.parent.version} - - + + org.apache.curator + curator-framework + test + + + org.apache.curator + curator-recipes + test + + + org.apache.zookeeper + zookeeper + + + org.apache.dubbo + dubbo-metrics-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-metrics-default + ${project.parent.version} + + + org.apache.dubbo + dubbo-metrics-prometheus + ${project.parent.version} + + + org.apache.dubbo + dubbo-metrics-config-center + ${project.parent.version} + + - - - curator5 - - [17,) - - - - org.apache.dubbo - dubbo-remoting-zookeeper-curator5 - ${project.parent.version} - - - - + + + curator5 + + [17,) + + + + org.apache.dubbo + dubbo-remoting-zookeeper-curator5 + ${project.parent.version} + + + + diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/CacheListener.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/CacheListener.java index df596926b7..ba3fc4a0b2 100644 --- a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/CacheListener.java +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/CacheListener.java @@ -32,12 +32,18 @@ public class CacheListener { private final ConcurrentMap pathKeyListeners = new ConcurrentHashMap<>(); - public CacheListener() { - } + public CacheListener() {} - public ZookeeperDataListener addListener(String pathKey, ConfigurationListener configurationListener, String key, String group, ApplicationModel applicationModel) { - ZookeeperDataListener zookeeperDataListener = ConcurrentHashMapUtils.computeIfAbsent(pathKeyListeners, pathKey, - _pathKey -> new ZookeeperDataListener(_pathKey, key, group, applicationModel)); + public ZookeeperDataListener addListener( + String pathKey, + ConfigurationListener configurationListener, + String key, + String group, + ApplicationModel applicationModel) { + ZookeeperDataListener zookeeperDataListener = ConcurrentHashMapUtils.computeIfAbsent( + pathKeyListeners, + pathKey, + _pathKey -> new ZookeeperDataListener(_pathKey, key, group, applicationModel)); zookeeperDataListener.addListener(configurationListener); return zookeeperDataListener; } @@ -65,4 +71,3 @@ public class CacheListener { pathKeyListeners.clear(); } } - diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDataListener.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDataListener.java index df22f5de0f..5ec5a3cd57 100644 --- a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDataListener.java +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDataListener.java @@ -80,8 +80,12 @@ public class ZookeeperDataListener implements DataListener { listeners.forEach(listener -> listener.process(configChangeEvent)); } - MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent(applicationModel, configChangeEvent.getKey(), configChangeEvent.getGroup(), - ConfigCenterEvent.ZK_PROTOCOL, ConfigChangeType.ADDED.name(), SELF_INCREMENT_SIZE)); + MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent( + applicationModel, + configChangeEvent.getKey(), + configChangeEvent.getGroup(), + ConfigCenterEvent.ZK_PROTOCOL, + ConfigChangeType.ADDED.name(), + SELF_INCREMENT_SIZE)); } - } diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java index e0bc325c4c..f29671f0c6 100644 --- a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java @@ -25,9 +25,7 @@ import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter; - import org.apache.dubbo.rpc.model.ApplicationModel; -import org.apache.zookeeper.data.Stat; import java.util.Collection; import java.util.Map; @@ -36,6 +34,8 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import org.apache.zookeeper.data.Stat; + import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_CONNECT_REGISTRY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION; @@ -50,29 +50,37 @@ public class ZookeeperDynamicConfiguration extends TreePathDynamicConfiguration private static final Long THREAD_KEEP_ALIVE_TIME = 0L; private final ApplicationModel applicationModel; - ZookeeperDynamicConfiguration(URL url, ZookeeperTransporter zookeeperTransporter, ApplicationModel applicationModel) { + ZookeeperDynamicConfiguration( + URL url, ZookeeperTransporter zookeeperTransporter, ApplicationModel applicationModel) { super(url); this.cacheListener = new CacheListener(); this.applicationModel = applicationModel; final String threadName = this.getClass().getSimpleName(); - this.executor = new ThreadPoolExecutor(DEFAULT_ZK_EXECUTOR_THREADS_NUM, DEFAULT_ZK_EXECUTOR_THREADS_NUM, - THREAD_KEEP_ALIVE_TIME, TimeUnit.MILLISECONDS, - new LinkedBlockingQueue<>(DEFAULT_QUEUE), - new NamedThreadFactory(threadName, true), - new AbortPolicyWithReport(threadName, url)); + this.executor = new ThreadPoolExecutor( + DEFAULT_ZK_EXECUTOR_THREADS_NUM, + DEFAULT_ZK_EXECUTOR_THREADS_NUM, + THREAD_KEEP_ALIVE_TIME, + TimeUnit.MILLISECONDS, + new LinkedBlockingQueue<>(DEFAULT_QUEUE), + new NamedThreadFactory(threadName, true), + new AbortPolicyWithReport(threadName, url)); zkClient = zookeeperTransporter.connect(url); boolean isConnected = zkClient.isConnected(); if (!isConnected) { - IllegalStateException illegalStateException = - new IllegalStateException("Failed to connect with zookeeper, pls check if url " + url + " is correct."); + IllegalStateException illegalStateException = new IllegalStateException( + "Failed to connect with zookeeper, pls check if url " + url + " is correct."); if (logger != null) { - logger.error(CONFIG_FAILED_CONNECT_REGISTRY, "configuration server offline", "", - "Failed to connect with zookeeper", illegalStateException); + logger.error( + CONFIG_FAILED_CONNECT_REGISTRY, + "configuration server offline", + "", + "Failed to connect with zookeeper", + illegalStateException); } throw illegalStateException; @@ -153,7 +161,8 @@ public class ZookeeperDynamicConfiguration extends TreePathDynamicConfiguration if (cachedListener != null) { cachedListener.addListener(listener); } else { - ZookeeperDataListener addedListener = cacheListener.addListener(pathKey, listener, key, group, applicationModel); + ZookeeperDataListener addedListener = + cacheListener.addListener(pathKey, listener, key, group, applicationModel); zkClient.addDataListener(pathKey, addedListener, executor); } } diff --git a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationTest.java index 99e7674ba1..dddd710d4b 100644 --- a/dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationTest.java +++ b/dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationTest.java @@ -24,6 +24,10 @@ import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory; import org.apache.dubbo.common.extension.ExtensionLoader; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.CountDownLatch; + import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; @@ -33,10 +37,6 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.CountDownLatch; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -56,10 +56,11 @@ class ZookeeperDynamicConfigurationTest { @BeforeAll public static void setUp() throws Exception { zookeeperConnectionAddress1 = System.getProperty("zookeeper.connection.address.1"); - zookeeperServerPort1 = Integer.parseInt(zookeeperConnectionAddress1.substring(zookeeperConnectionAddress1.lastIndexOf(":") + 1)); + zookeeperServerPort1 = Integer.parseInt( + zookeeperConnectionAddress1.substring(zookeeperConnectionAddress1.lastIndexOf(":") + 1)); - client = CuratorFrameworkFactory.newClient("127.0.0.1:" + zookeeperServerPort1, 60 * 1000, 60 * 1000, - new ExponentialBackoffRetry(1000, 3)); + client = CuratorFrameworkFactory.newClient( + "127.0.0.1:" + zookeeperServerPort1, 60 * 1000, 60 * 1000, new ExponentialBackoffRetry(1000, 3)); client.start(); try { @@ -67,14 +68,17 @@ class ZookeeperDynamicConfigurationTest { setData("/dubbo/config/dubbo/service:version:group.configurators", "The content from configurators"); setData("/dubbo/config/appname", "The content from higher level node"); setData("/dubbo/config/dubbo/appname.tag-router", "The content from appname tagrouters"); - setData("/dubbo/config/dubbo/never.change.DemoService.configurators", "Never change value from configurators"); + setData( + "/dubbo/config/dubbo/never.change.DemoService.configurators", + "Never change value from configurators"); } catch (Exception e) { e.printStackTrace(); } configUrl = URL.valueOf(zookeeperConnectionAddress1); - configuration = ExtensionLoader.getExtensionLoader(DynamicConfigurationFactory.class).getExtension(configUrl.getProtocol()) - .getDynamicConfiguration(configUrl); + configuration = ExtensionLoader.getExtensionLoader(DynamicConfigurationFactory.class) + .getExtension(configUrl.getProtocol()) + .getDynamicConfiguration(configUrl); } private static void setData(String path, String data) throws Exception { @@ -87,19 +91,22 @@ class ZookeeperDynamicConfigurationTest { private ConfigurationListener mockListener(CountDownLatch latch, String[] value, Map countMap) { ConfigurationListener listener = Mockito.mock(ConfigurationListener.class); Mockito.doAnswer(invoke -> { - ConfigChangedEvent event = invoke.getArgument(0); - Integer count = countMap.computeIfAbsent(event.getKey(), k -> 0); - countMap.put(event.getKey(), ++count); - value[0] = event.getContent(); - latch.countDown(); - return null; - }).when(listener).process(Mockito.any()); + ConfigChangedEvent event = invoke.getArgument(0); + Integer count = countMap.computeIfAbsent(event.getKey(), k -> 0); + countMap.put(event.getKey(), ++count); + value[0] = event.getContent(); + latch.countDown(); + return null; + }) + .when(listener) + .process(Mockito.any()); return listener; } @Test void testGetConfig() { - Assertions.assertEquals("The content from dubbo.properties", configuration.getConfig("dubbo.properties", "dubbo")); + Assertions.assertEquals( + "The content from dubbo.properties", configuration.getConfig("dubbo.properties", "dubbo")); } @Test @@ -107,7 +114,10 @@ class ZookeeperDynamicConfigurationTest { CountDownLatch latch = new CountDownLatch(4); String[] value1 = new String[1], value2 = new String[1], value3 = new String[1], value4 = new String[1]; - Map countMap1 = new HashMap<>(), countMap2 = new HashMap<>(), countMap3 = new HashMap<>(), countMap4 = new HashMap<>(); + Map countMap1 = new HashMap<>(), + countMap2 = new HashMap<>(), + countMap3 = new HashMap<>(), + countMap4 = new HashMap<>(); ConfigurationListener listener1 = mockListener(latch, value1, countMap1); ConfigurationListener listener2 = mockListener(latch, value2, countMap2); ConfigurationListener listener3 = mockListener(latch, value3, countMap3); @@ -163,22 +173,22 @@ class ZookeeperDynamicConfigurationTest { assertFalse(configuration.publishConfigCas(key, group, "newtest2", configItem.getTicket())); assertEquals("newtest", configuration.getConfigItem(key, group).getContent()); } -// -// @Test -// public void testGetConfigKeysAndContents() { -// -// String group = "mapping"; -// String key = "org.apache.dubbo.service.UserService"; -// String content = "app1"; -// -// String key2 = "org.apache.dubbo.service.UserService2"; -// -// assertTrue(configuration.publishConfig(key, group, content)); -// assertTrue(configuration.publishConfig(key2, group, content)); -// -// Set configKeys = configuration.getConfigKeys(group); -// -// assertEquals(new TreeSet(asList(key, key2)), configKeys); -// } + // + // @Test + // public void testGetConfigKeysAndContents() { + // + // String group = "mapping"; + // String key = "org.apache.dubbo.service.UserService"; + // String content = "app1"; + // + // String key2 = "org.apache.dubbo.service.UserService2"; + // + // assertTrue(configuration.publishConfig(key, group, content)); + // assertTrue(configuration.publishConfig(key2, group, content)); + // + // Set configKeys = configuration.getConfigKeys(group); + // + // assertEquals(new TreeSet(asList(key, key2)), configKeys); + // } -} \ No newline at end of file +} diff --git a/dubbo-configcenter/pom.xml b/dubbo-configcenter/pom.xml index 617f68a465..96a25b9d6e 100644 --- a/dubbo-configcenter/pom.xml +++ b/dubbo-configcenter/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-parent - ${revision} - ../pom.xml - - dubbo-configcenter - pom - ${project.artifactId} - The service config-center module of the Dubbo project - - false - + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + + dubbo-configcenter + pom + ${project.artifactId} + The service config-center module of the Dubbo project - - dubbo-configcenter-zookeeper - dubbo-configcenter-apollo - dubbo-configcenter-nacos - dubbo-configcenter-file - + + dubbo-configcenter-zookeeper + dubbo-configcenter-apollo + dubbo-configcenter-nacos + dubbo-configcenter-file + + + false + - - - org.apache.dubbo - dubbo-test-check - ${project.parent.version} - test - - + + + org.apache.dubbo + dubbo-test-check + ${project.parent.version} + test + + diff --git a/dubbo-container/dubbo-container-api/pom.xml b/dubbo-container/dubbo-container-api/pom.xml index 00e2fc3e45..709aa14dd4 100644 --- a/dubbo-container/dubbo-container-api/pom.xml +++ b/dubbo-container/dubbo-container-api/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-container - ${revision} - ../pom.xml - - dubbo-container-api - jar - ${project.artifactId} - The container module of dubbo project - - false - - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - true - - org.apache.dubbo.container.Main - - - - - - + 4.0.0 + + org.apache.dubbo + dubbo-container + ${revision} + ../pom.xml + + dubbo-container-api + jar + ${project.artifactId} + The container module of dubbo project + + false + + + + org.apache.dubbo + dubbo-common + ${project.parent.version} + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + true + + org.apache.dubbo.container.Main + + + + + + diff --git a/dubbo-container/dubbo-container-api/src/main/java/org/apache/dubbo/container/Container.java b/dubbo-container/dubbo-container-api/src/main/java/org/apache/dubbo/container/Container.java index 66b76b496e..00e3daee7d 100644 --- a/dubbo-container/dubbo-container-api/src/main/java/org/apache/dubbo/container/Container.java +++ b/dubbo-container/dubbo-container-api/src/main/java/org/apache/dubbo/container/Container.java @@ -33,5 +33,4 @@ public interface Container { * stop method to unload the container. */ void stop(); - } diff --git a/dubbo-container/dubbo-container-api/src/main/java/org/apache/dubbo/container/Main.java b/dubbo-container/dubbo-container-api/src/main/java/org/apache/dubbo/container/Main.java index da558f5f72..c9eca15c10 100644 --- a/dubbo-container/dubbo-container-api/src/main/java/org/apache/dubbo/container/Main.java +++ b/dubbo-container/dubbo-container-api/src/main/java/org/apache/dubbo/container/Main.java @@ -30,9 +30,9 @@ import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_THREAD_INTERRUPTED_EXCEPTION; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_START_DUBBO_ERROR; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_STOP_DUBBO_ERROR; -import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_THREAD_INTERRUPTED_EXCEPTION; /** * Main. (API, Static, ThreadSafe) @@ -92,7 +92,8 @@ public class Main { container.start(); logger.info("Dubbo " + container.getClass().getSimpleName() + " started!"); } - System.out.println(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss]").format(new Date()) + " Dubbo service server started!"); + System.out.println(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss]").format(new Date()) + + " Dubbo service server started!"); } catch (RuntimeException e) { logger.error(CONFIG_START_DUBBO_ERROR, "", "", e.getMessage(), e); System.exit(1); @@ -101,10 +102,14 @@ public class Main { LOCK.lock(); STOP.await(); } catch (InterruptedException e) { - logger.warn(COMMON_THREAD_INTERRUPTED_EXCEPTION, "", "", "Dubbo service server stopped, interrupted by other thread!", e); + logger.warn( + COMMON_THREAD_INTERRUPTED_EXCEPTION, + "", + "", + "Dubbo service server stopped, interrupted by other thread!", + e); } finally { LOCK.unlock(); } } - } diff --git a/dubbo-container/dubbo-container-spring/pom.xml b/dubbo-container/dubbo-container-spring/pom.xml index 7bf050a273..44fc43d51f 100644 --- a/dubbo-container/dubbo-container-spring/pom.xml +++ b/dubbo-container/dubbo-container-spring/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-container - ${revision} - ../pom.xml - - dubbo-container-spring - jar - ${project.artifactId} - The spring container module of dubbo project - - false - - - - org.apache.dubbo - dubbo-container-api - ${project.parent.version} - - - org.springframework - spring-context - - - org.slf4j - slf4j-log4j12 - test - - + 4.0.0 + + org.apache.dubbo + dubbo-container + ${revision} + ../pom.xml + + dubbo-container-spring + jar + ${project.artifactId} + The spring container module of dubbo project + + false + + + + org.apache.dubbo + dubbo-container-api + ${project.parent.version} + + + org.springframework + spring-context + + + org.slf4j + slf4j-log4j12 + test + + diff --git a/dubbo-container/dubbo-container-spring/src/main/java/org/apache/dubbo/container/spring/SpringContainer.java b/dubbo-container/dubbo-container-spring/src/main/java/org/apache/dubbo/container/spring/SpringContainer.java index 94e094e6a4..0adb798658 100644 --- a/dubbo-container/dubbo-container-spring/src/main/java/org/apache/dubbo/container/spring/SpringContainer.java +++ b/dubbo-container/dubbo-container-spring/src/main/java/org/apache/dubbo/container/spring/SpringContainer.java @@ -64,5 +64,4 @@ public class SpringContainer implements Container { logger.error(CONFIG_STOP_DUBBO_ERROR, "", "", e.getMessage(), e); } } - } diff --git a/dubbo-container/dubbo-container-spring/src/test/java/org/apache/dubbo/container/spring/SpringContainerTest.java b/dubbo-container/dubbo-container-spring/src/test/java/org/apache/dubbo/container/spring/SpringContainerTest.java index 9673770c84..b1ea0747c9 100644 --- a/dubbo-container/dubbo-container-spring/src/test/java/org/apache/dubbo/container/spring/SpringContainerTest.java +++ b/dubbo-container/dubbo-container-spring/src/test/java/org/apache/dubbo/container/spring/SpringContainerTest.java @@ -29,10 +29,11 @@ class SpringContainerTest { @Test void testContainer() { - SpringContainer container = (SpringContainer) ExtensionLoader.getExtensionLoader(Container.class).getExtension("spring"); + SpringContainer container = (SpringContainer) + ExtensionLoader.getExtensionLoader(Container.class).getExtension("spring"); container.start(); - Assertions.assertEquals(SpringContainer.class, container.context.getBean("container").getClass()); + Assertions.assertEquals( + SpringContainer.class, container.context.getBean("container").getClass()); container.stop(); } - -} \ No newline at end of file +} diff --git a/dubbo-container/pom.xml b/dubbo-container/pom.xml index ec2cab09c4..a104376e7f 100644 --- a/dubbo-container/pom.xml +++ b/dubbo-container/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-parent - ${revision} - ../pom.xml - - dubbo-container - pom - ${project.artifactId} - The container module of dubbo project - - false - - - dubbo-container-api - dubbo-container-spring - + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + + dubbo-container + pom + ${project.artifactId} + The container module of dubbo project + + dubbo-container-api + dubbo-container-spring + + + false + diff --git a/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/pom.xml b/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/pom.xml index 217f3edbc2..d8e0fe734d 100644 --- a/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/pom.xml @@ -17,92 +17,91 @@ ~ specific language governing permissions and limitations ~ under the License. --> - - - org.apache.dubbo - dubbo-demo-annotation - ${revision} - ../pom.xml - - 4.0.0 + 4.0.0 + + org.apache.dubbo + dubbo-demo-annotation + ${revision} + ../pom.xml + - dubbo-demo-annotation-consumer + dubbo-demo-annotation-consumer - - true - + + true + - - - org.apache.dubbo - dubbo-demo-interface - ${project.version} - - - org.apache.dubbo - dubbo-registry-multicast - ${project.version} - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-registry-nacos - ${project.version} - - - com.alibaba.nacos - nacos-client - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-nacos - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-nacos - ${project.version} - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - - - org.apache.dubbo - dubbo-config-spring - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.version} - - + + + org.apache.dubbo + dubbo-demo-interface + ${project.version} + + + org.apache.dubbo + dubbo-registry-multicast + ${project.version} + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-registry-nacos + ${project.version} + + + com.alibaba.nacos + nacos-client + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-nacos + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-nacos + ${project.version} + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + + + org.apache.dubbo + dubbo-config-spring + ${project.version} + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.version} + + diff --git a/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/src/main/java/org/apache/dubbo/demo/consumer/Application.java b/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/src/main/java/org/apache/dubbo/demo/consumer/Application.java index 718921c099..8f6d2e9c7d 100644 --- a/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/src/main/java/org/apache/dubbo/demo/consumer/Application.java +++ b/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/src/main/java/org/apache/dubbo/demo/consumer/Application.java @@ -31,7 +31,8 @@ public class Application { * launch the application */ public static void main(String[] args) { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfiguration.class); + AnnotationConfigApplicationContext context = + new AnnotationConfigApplicationContext(ConsumerConfiguration.class); context.start(); DemoService service = context.getBean("demoServiceComponent", DemoServiceComponent.class); String hello = service.sayHello("world"); @@ -42,7 +43,5 @@ public class Application { @EnableDubbo(scanBasePackages = "org.apache.dubbo.demo.consumer.comp") @PropertySource("classpath:/spring/dubbo-consumer.properties") @ComponentScan(value = {"org.apache.dubbo.demo.consumer.comp"}) - static class ConsumerConfiguration { - - } + static class ConsumerConfiguration {} } diff --git a/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/src/main/java/org/apache/dubbo/demo/consumer/comp/DemoServiceComponent.java b/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/src/main/java/org/apache/dubbo/demo/consumer/comp/DemoServiceComponent.java index fbfcd9ebd9..93d1eca356 100644 --- a/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/src/main/java/org/apache/dubbo/demo/consumer/comp/DemoServiceComponent.java +++ b/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-consumer/src/main/java/org/apache/dubbo/demo/consumer/comp/DemoServiceComponent.java @@ -19,10 +19,10 @@ package org.apache.dubbo.demo.consumer.comp; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.demo.DemoService; -import org.springframework.stereotype.Component; - import java.util.concurrent.CompletableFuture; +import org.springframework.stereotype.Component; + @Component("demoServiceComponent") public class DemoServiceComponent implements DemoService { @DubboReference diff --git a/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-provider/pom.xml b/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-provider/pom.xml index 74a7ac7b77..0b87bfe3a8 100644 --- a/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-provider/pom.xml @@ -17,92 +17,91 @@ ~ specific language governing permissions and limitations ~ under the License. --> - - - org.apache.dubbo - dubbo-demo-annotation - ${revision} - ../pom.xml - - 4.0.0 + 4.0.0 + + org.apache.dubbo + dubbo-demo-annotation + ${revision} + ../pom.xml + - dubbo-demo-annotation-provider + dubbo-demo-annotation-provider - - true - + + true + - - - org.apache.dubbo - dubbo-demo-interface - ${project.parent.version} - - - org.apache.dubbo - dubbo-registry-multicast - ${project.version} - - - org.apache.dubbo - dubbo-registry-nacos - ${project.version} - - - com.alibaba.nacos - nacos-client - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-nacos - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-nacos - ${project.version} - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - - - org.apache.dubbo - dubbo-config-spring - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.version} - - + + + org.apache.dubbo + dubbo-demo-interface + ${project.parent.version} + + + org.apache.dubbo + dubbo-registry-multicast + ${project.version} + + + org.apache.dubbo + dubbo-registry-nacos + ${project.version} + + + com.alibaba.nacos + nacos-client + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-nacos + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-nacos + ${project.version} + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + + + org.apache.dubbo + dubbo-config-spring + ${project.version} + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.version} + + diff --git a/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-provider/src/main/java/org/apache/dubbo/demo/provider/Application.java b/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-provider/src/main/java/org/apache/dubbo/demo/provider/Application.java index 3062d24727..56fe623cc9 100644 --- a/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-provider/src/main/java/org/apache/dubbo/demo/provider/Application.java +++ b/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-provider/src/main/java/org/apache/dubbo/demo/provider/Application.java @@ -26,7 +26,8 @@ import org.springframework.context.annotation.PropertySource; public class Application { public static void main(String[] args) throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ProviderConfiguration.class); + AnnotationConfigApplicationContext context = + new AnnotationConfigApplicationContext(ProviderConfiguration.class); context.start(); System.in.read(); } diff --git a/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-provider/src/main/java/org/apache/dubbo/demo/provider/DemoServiceImpl.java b/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-provider/src/main/java/org/apache/dubbo/demo/provider/DemoServiceImpl.java index 8983ed287b..8b4f944650 100644 --- a/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-provider/src/main/java/org/apache/dubbo/demo/provider/DemoServiceImpl.java +++ b/dubbo-demo/dubbo-demo-annotation/dubbo-demo-annotation-provider/src/main/java/org/apache/dubbo/demo/provider/DemoServiceImpl.java @@ -20,24 +20,25 @@ import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.demo.DemoService; import org.apache.dubbo.rpc.RpcContext; +import java.util.concurrent.CompletableFuture; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.concurrent.CompletableFuture; - @DubboService public class DemoServiceImpl implements DemoService { private static final Logger logger = LoggerFactory.getLogger(DemoServiceImpl.class); @Override public String sayHello(String name) { - logger.info("Hello " + name + ", request from consumer: " + RpcContext.getServiceContext().getRemoteAddress()); - return "Hello " + name + ", response from provider: " + RpcContext.getServiceContext().getLocalAddress(); + logger.info("Hello " + name + ", request from consumer: " + + RpcContext.getServiceContext().getRemoteAddress()); + return "Hello " + name + ", response from provider: " + + RpcContext.getServiceContext().getLocalAddress(); } @Override public CompletableFuture sayHelloAsync(String name) { return null; } - } diff --git a/dubbo-demo/dubbo-demo-annotation/pom.xml b/dubbo-demo/dubbo-demo-annotation/pom.xml index 54f08b5b40..891cfabbf8 100644 --- a/dubbo-demo/dubbo-demo-annotation/pom.xml +++ b/dubbo-demo/dubbo-demo-annotation/pom.xml @@ -17,41 +17,40 @@ ~ specific language governing permissions and limitations ~ under the License. --> - - - dubbo-demo - org.apache.dubbo - ${revision} - - 4.0.0 - pom - dubbo-demo-annotation + 4.0.0 + + org.apache.dubbo + dubbo-demo + ${revision} + + dubbo-demo-annotation + pom - - true - 2.7.17 - + + dubbo-demo-annotation-provider + dubbo-demo-annotation-consumer + - - dubbo-demo-annotation-provider - dubbo-demo-annotation-consumer - + + true + 2.7.17 + - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot-maven-plugin.version} - - - - repackage - - - - - - + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} + + + + repackage + + + + + + diff --git a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/pom.xml b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/pom.xml index 6e965d17ee..13d779b99f 100644 --- a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/pom.xml @@ -17,93 +17,92 @@ ~ specific language governing permissions and limitations ~ under the License. --> - - - org.apache.dubbo - dubbo-demo-api - ${revision} - ../pom.xml - - 4.0.0 + 4.0.0 + + org.apache.dubbo + dubbo-demo-api + ${revision} + ../pom.xml + - dubbo-demo-api-consumer + dubbo-demo-api-consumer - - true - + + true + - - - org.apache.dubbo - dubbo-demo-interface - ${project.parent.version} - - - org.apache.dubbo - dubbo-config-api - ${project.version} - - - org.apache.dubbo - dubbo-registry-multicast - ${project.version} - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-registry-nacos - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-nacos - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-nacos - ${project.version} - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.version} - - - org.apache.dubbo - dubbo-plugin-cluster-mergeable - ${project.version} - - + + + org.apache.dubbo + dubbo-demo-interface + ${project.parent.version} + + + org.apache.dubbo + dubbo-config-api + ${project.version} + + + org.apache.dubbo + dubbo-registry-multicast + ${project.version} + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-registry-nacos + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-nacos + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-nacos + ${project.version} + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.version} + + + org.apache.dubbo + dubbo-plugin-cluster-mergeable + ${project.version} + + diff --git a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/src/main/java/org/apache/dubbo/demo/consumer/Application.java b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/src/main/java/org/apache/dubbo/demo/consumer/Application.java index e655d4a637..07cbefed29 100644 --- a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/src/main/java/org/apache/dubbo/demo/consumer/Application.java +++ b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-consumer/src/main/java/org/apache/dubbo/demo/consumer/Application.java @@ -17,11 +17,10 @@ package org.apache.dubbo.demo.consumer; import org.apache.dubbo.common.constants.CommonConstants; - -import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ApplicationConfig; -import org.apache.dubbo.config.RegistryConfig; +import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ReferenceConfig; +import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.demo.DemoService; import org.apache.dubbo.rpc.service.GenericService; @@ -30,10 +29,8 @@ public class Application { private static final String REGISTRY_URL = "zookeeper://127.0.0.1:2181"; - - public static void main(String[] args) { - runWithBootstrap(); + runWithBootstrap(); } private static void runWithBootstrap() { @@ -42,11 +39,12 @@ public class Application { reference.setGeneric("true"); DubboBootstrap bootstrap = DubboBootstrap.getInstance(); - bootstrap.application(new ApplicationConfig("dubbo-demo-api-consumer")) - .registry(new RegistryConfig(REGISTRY_URL)) - .protocol(new ProtocolConfig(CommonConstants.DUBBO, -1)) - .reference(reference) - .start(); + bootstrap + .application(new ApplicationConfig("dubbo-demo-api-consumer")) + .registry(new RegistryConfig(REGISTRY_URL)) + .protocol(new ProtocolConfig(CommonConstants.DUBBO, -1)) + .reference(reference) + .start(); DemoService demoService = bootstrap.getCache().get(reference); String message = demoService.sayHello("dubbo"); @@ -54,9 +52,8 @@ public class Application { // generic invoke GenericService genericService = (GenericService) demoService; - Object genericInvokeResult = genericService.$invoke("sayHello", new String[]{String.class.getName()}, - new Object[]{"dubbo generic invoke"}); + Object genericInvokeResult = genericService.$invoke( + "sayHello", new String[] {String.class.getName()}, new Object[] {"dubbo generic invoke"}); System.out.println(genericInvokeResult.toString()); } - } diff --git a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/pom.xml b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/pom.xml index 85a5df1c7c..d29f723f70 100644 --- a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/pom.xml @@ -17,88 +17,86 @@ ~ specific language governing permissions and limitations ~ under the License. --> + + 4.0.0 + + org.apache.dubbo + dubbo-demo-api + ${revision} + ../pom.xml + - - - org.apache.dubbo - dubbo-demo-api - ${revision} - ../pom.xml - - 4.0.0 + dubbo-demo-api-provider - dubbo-demo-api-provider + + true + - - true - - - - - org.apache.dubbo - dubbo-demo-interface - ${project.parent.version} - - - org.apache.dubbo - dubbo-config-api - ${project.version} - - - org.apache.dubbo - dubbo-registry-multicast - ${project.version} - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-registry-nacos - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-nacos - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-nacos - ${project.version} - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.version} - - + + + org.apache.dubbo + dubbo-demo-interface + ${project.parent.version} + + + org.apache.dubbo + dubbo-config-api + ${project.version} + + + org.apache.dubbo + dubbo-registry-multicast + ${project.version} + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-registry-nacos + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-nacos + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-nacos + ${project.version} + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.version} + + diff --git a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo/provider/Application.java b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo/provider/Application.java index b80bfbfd3b..d6f70a57a1 100644 --- a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo/provider/Application.java +++ b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo/provider/Application.java @@ -38,12 +38,12 @@ public class Application { service.setRef(new DemoServiceImpl()); DubboBootstrap bootstrap = DubboBootstrap.getInstance(); - bootstrap.application(new ApplicationConfig("dubbo-demo-api-provider")) - .registry(new RegistryConfig(REGISTRY_URL)) - .protocol(new ProtocolConfig(CommonConstants.DUBBO, -1)) - .service(service) - .start() - .await(); + bootstrap + .application(new ApplicationConfig("dubbo-demo-api-provider")) + .registry(new RegistryConfig(REGISTRY_URL)) + .protocol(new ProtocolConfig(CommonConstants.DUBBO, -1)) + .service(service) + .start() + .await(); } - } diff --git a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo/provider/DemoServiceImpl.java b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo/provider/DemoServiceImpl.java index ae1faf86ab..e7760f53a7 100644 --- a/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo/provider/DemoServiceImpl.java +++ b/dubbo-demo/dubbo-demo-api/dubbo-demo-api-provider/src/main/java/org/apache/dubbo/demo/provider/DemoServiceImpl.java @@ -19,23 +19,24 @@ package org.apache.dubbo.demo.provider; import org.apache.dubbo.demo.DemoService; import org.apache.dubbo.rpc.RpcContext; +import java.util.concurrent.CompletableFuture; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.concurrent.CompletableFuture; - public class DemoServiceImpl implements DemoService { private static final Logger logger = LoggerFactory.getLogger(DemoServiceImpl.class); @Override public String sayHello(String name) { - logger.info("Hello " + name + ", request from consumer: " + RpcContext.getServiceContext().getRemoteAddress()); - return "Hello " + name + ", response from provider: " + RpcContext.getServiceContext().getLocalAddress(); + logger.info("Hello " + name + ", request from consumer: " + + RpcContext.getServiceContext().getRemoteAddress()); + return "Hello " + name + ", response from provider: " + + RpcContext.getServiceContext().getLocalAddress(); } @Override public CompletableFuture sayHelloAsync(String name) { return null; } - } diff --git a/dubbo-demo/dubbo-demo-api/pom.xml b/dubbo-demo/dubbo-demo-api/pom.xml index de47d5770f..c469ffdef5 100644 --- a/dubbo-demo/dubbo-demo-api/pom.xml +++ b/dubbo-demo/dubbo-demo-api/pom.xml @@ -17,45 +17,43 @@ ~ specific language governing permissions and limitations ~ under the License. --> + + 4.0.0 + + org.apache.dubbo + dubbo-demo + ${revision} + ../pom.xml + - - - org.apache.dubbo - dubbo-demo - ${revision} - ../pom.xml - - 4.0.0 - pom + dubbo-demo-api + pom - - dubbo-demo-api-provider - dubbo-demo-api-consumer - + + dubbo-demo-api-provider + dubbo-demo-api-consumer + - - true - 2.7.17 - + + true + 2.7.17 + - dubbo-demo-api - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot-maven-plugin.version} - - - - repackage - - - - - - + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} + + + + repackage + + + + + + diff --git a/dubbo-demo/dubbo-demo-generic-call/pom.xml b/dubbo-demo/dubbo-demo-generic-call/pom.xml index 4891a1e577..53925c9f36 100644 --- a/dubbo-demo/dubbo-demo-generic-call/pom.xml +++ b/dubbo-demo/dubbo-demo-generic-call/pom.xml @@ -17,87 +17,86 @@ ~ specific language governing permissions and limitations ~ under the License. --> - - - org.apache.dubbo - dubbo-demo - ${revision} - ../pom.xml - - 4.0.0 + 4.0.0 + + org.apache.dubbo + dubbo-demo + ${revision} + ../pom.xml + - dubbo-demo-generic-call + dubbo-demo-generic-call - - true - + + true + - - - org.apache.dubbo - dubbo-config-api - ${project.version} - - - org.apache.dubbo - dubbo-registry-multicast - ${project.version} - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-registry-nacos - ${project.version} - - - com.alibaba.nacos - nacos-client - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-nacos - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-nacos - ${project.version} - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.version} - - + + + org.apache.dubbo + dubbo-config-api + ${project.version} + + + org.apache.dubbo + dubbo-registry-multicast + ${project.version} + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-registry-nacos + ${project.version} + + + com.alibaba.nacos + nacos-client + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-nacos + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-nacos + ${project.version} + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.version} + + diff --git a/dubbo-demo/dubbo-demo-generic-call/src/main/java/org/apache/dubbo/demo/consumer/GenericApplication.java b/dubbo-demo/dubbo-demo-generic-call/src/main/java/org/apache/dubbo/demo/consumer/GenericApplication.java index 7aceba49a0..9b8a2210cb 100644 --- a/dubbo-demo/dubbo-demo-generic-call/src/main/java/org/apache/dubbo/demo/consumer/GenericApplication.java +++ b/dubbo-demo/dubbo-demo-generic-call/src/main/java/org/apache/dubbo/demo/consumer/GenericApplication.java @@ -32,7 +32,6 @@ public class GenericApplication { runWithBootstrap(args); } - private static void runWithBootstrap(String[] args) { ReferenceConfig reference = new ReferenceConfig<>(); reference.setInterface("org.apache.dubbo.demo.DemoService"); @@ -52,18 +51,19 @@ public class GenericApplication { metadataReportConfig.setAddress("zookeeper://127.0.0.1:2181"); DubboBootstrap bootstrap = DubboBootstrap.getInstance(); - bootstrap.application(applicationConfig) - .registry(new RegistryConfig("zookeeper://127.0.0.1:2181")) - .protocol(new ProtocolConfig(CommonConstants.DUBBO, -1)) - .reference(reference) - .start(); + bootstrap + .application(applicationConfig) + .registry(new RegistryConfig("zookeeper://127.0.0.1:2181")) + .protocol(new ProtocolConfig(CommonConstants.DUBBO, -1)) + .reference(reference) + .start(); // generic invoke GenericService genericService = bootstrap.getCache().get(reference); while (true) { try { - Object genericInvokeResult = genericService.$invoke("sayHello", new String[]{String.class.getName()}, - new Object[]{param}); + Object genericInvokeResult = + genericService.$invoke("sayHello", new String[] {String.class.getName()}, new Object[] {param}); System.out.println(genericInvokeResult); Thread.sleep(1000); } catch (Exception e) { @@ -71,5 +71,4 @@ public class GenericApplication { } } } - } diff --git a/dubbo-demo/dubbo-demo-interface/pom.xml b/dubbo-demo/dubbo-demo-interface/pom.xml index a328f3c46a..6641c3ce65 100644 --- a/dubbo-demo/dubbo-demo-interface/pom.xml +++ b/dubbo-demo/dubbo-demo-interface/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-demo - ${revision} - ../pom.xml - - dubbo-demo-interface - jar - ${project.artifactId} - The demo module of dubbo project + 4.0.0 + + org.apache.dubbo + dubbo-demo + ${revision} + ../pom.xml + + dubbo-demo-interface + jar + ${project.artifactId} + The demo module of dubbo project - - true - + + true + - - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - + + + org.apache.dubbo + dubbo-rpc-rest + ${project.version} + - - - org.springframework - spring-context - test - + + + org.springframework + spring-context + test + - - org.springframework - spring-web - - + + org.springframework + spring-web + + diff --git a/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/DemoService.java b/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/DemoService.java index 09bdafa1f6..26f1ac524a 100644 --- a/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/DemoService.java +++ b/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/DemoService.java @@ -25,5 +25,4 @@ public interface DemoService { default CompletableFuture sayHelloAsync(String name) { return CompletableFuture.completedFuture(sayHello(name)); } - } diff --git a/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/RestDemoService.java b/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/RestDemoService.java index 8caa8ccebc..f12536bfd1 100644 --- a/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/RestDemoService.java +++ b/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/RestDemoService.java @@ -16,19 +16,17 @@ */ package org.apache.dubbo.demo; - -import po.TestPO; - -import javax.ws.rs.Path; -import javax.ws.rs.GET; import javax.ws.rs.Consumes; +import javax.ws.rs.FormParam; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; -import javax.ws.rs.POST; -import javax.ws.rs.FormParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; +import po.TestPO; @Path("/demoService") public interface RestDemoService { @@ -71,7 +69,6 @@ public interface RestDemoService { @Consumes({MediaType.TEXT_PLAIN}) TestPO testBody2(TestPO b); - @POST @Path("/testBody5") @Consumes({MediaType.APPLICATION_JSON}) @@ -84,7 +81,6 @@ public interface RestDemoService { @Produces(MediaType.TEXT_PLAIN) String testForm1(@FormParam("name") String test); - @POST @Path("/testForm2") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) diff --git a/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/CurlService.java b/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/CurlService.java index 09a202ab58..b77cded2f5 100644 --- a/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/CurlService.java +++ b/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/CurlService.java @@ -16,19 +16,15 @@ */ package org.apache.dubbo.demo.rest.api; - - import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path("/curl") public interface CurlService { - // curl -X GET http://localhost:8888/services/curl - // http://localhost:8888/services/curl + // curl -X GET http://localhost:8888/services/curl + // http://localhost:8888/services/curl @GET @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) String curl(); - } - diff --git a/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/DubboServiceAnnotationService.java b/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/DubboServiceAnnotationService.java index 0ef70bf293..478b3e6dc2 100644 --- a/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/DubboServiceAnnotationService.java +++ b/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/DubboServiceAnnotationService.java @@ -16,8 +16,6 @@ */ package org.apache.dubbo.demo.rest.api; - - import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; @@ -27,6 +25,4 @@ public interface DubboServiceAnnotationService { @GET @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) String annotation(); - } - diff --git a/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/ExceptionMapperService.java b/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/ExceptionMapperService.java index 313159be0a..277693d915 100644 --- a/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/ExceptionMapperService.java +++ b/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/ExceptionMapperService.java @@ -16,8 +16,6 @@ */ package org.apache.dubbo.demo.rest.api; - - import javax.ws.rs.POST; import javax.ws.rs.Path; @@ -27,5 +25,4 @@ public interface ExceptionMapperService { @POST @Path("/exception") String exception(String message); - } diff --git a/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/HttpMethodService.java b/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/HttpMethodService.java index ebbc1b10f3..db1a815d46 100644 --- a/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/HttpMethodService.java +++ b/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/HttpMethodService.java @@ -16,9 +16,6 @@ */ package org.apache.dubbo.demo.rest.api; - -import io.swagger.jaxrs.PATCH; - import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; @@ -29,6 +26,8 @@ import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; +import io.swagger.jaxrs.PATCH; + @Path("/demoService") public interface HttpMethodService { @@ -66,6 +65,4 @@ public interface HttpMethodService { @Path("/sayOptions") @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) String sayHelloOptions(@QueryParam("name") String hello); - } - diff --git a/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/HttpRequestAndResponseRPCContextService.java b/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/HttpRequestAndResponseRPCContextService.java index e1df730e20..4e925b386d 100644 --- a/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/HttpRequestAndResponseRPCContextService.java +++ b/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/HttpRequestAndResponseRPCContextService.java @@ -16,12 +16,12 @@ */ package org.apache.dubbo.demo.rest.api; - import javax.ws.rs.Consumes; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; + import java.util.List; @Path("/demoService") @@ -41,7 +41,4 @@ public interface HttpRequestAndResponseRPCContextService { @Path("/httpResponseHeader") @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) List httpResponseHeader(@HeaderParam("response") String hello); - - } - diff --git a/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/JaxRsRestDemoService.java b/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/JaxRsRestDemoService.java index 368489f1cf..9b61aa5452 100644 --- a/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/JaxRsRestDemoService.java +++ b/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/JaxRsRestDemoService.java @@ -16,9 +16,6 @@ */ package org.apache.dubbo.demo.rest.api; - -import po.User; - import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.GET; @@ -29,9 +26,12 @@ import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; + import java.util.List; import java.util.Map; +import po.User; + /** * * @Consumers & @Produces can be not used ,we will make sure the content-type of request by arg type @@ -42,7 +42,6 @@ import java.util.Map; * * the path annotation must present in class & method */ - @Path("/jaxrs/demo/service") public interface JaxRsRestDemoService { @GET @@ -57,10 +56,6 @@ public interface JaxRsRestDemoService { @Path("/say") String sayHello(String name); - - - - @POST @Path("/testFormBody") Long testFormBody(@FormParam("number") Long number); @@ -70,8 +65,6 @@ public interface JaxRsRestDemoService { @Consumes({MediaType.APPLICATION_JSON}) User testJavaBeanBody(User user); - - @GET @Path("/primitive") int primitiveInt(@QueryParam("a") int a, @QueryParam("b") int b); @@ -115,6 +108,4 @@ public interface JaxRsRestDemoService { @Path("/headerInt") @Consumes({MediaType.TEXT_PLAIN}) int headerInt(@HeaderParam("header") int header); - - } diff --git a/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/SpringRestDemoService.java b/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/SpringRestDemoService.java index d5da64403e..ef726b5e2d 100644 --- a/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/SpringRestDemoService.java +++ b/dubbo-demo/dubbo-demo-interface/src/main/java/org/apache/dubbo/demo/rest/api/SpringRestDemoService.java @@ -16,6 +16,8 @@ */ package org.apache.dubbo.demo.rest.api; +import java.util.List; +import java.util.Map; import org.springframework.http.MediaType; import org.springframework.util.MultiValueMap; @@ -26,9 +28,6 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import po.User; -import java.util.List; -import java.util.Map; - @RequestMapping("/spring/demo/service") public interface SpringRestDemoService { @@ -41,13 +40,18 @@ public interface SpringRestDemoService { @RequestMapping(method = RequestMethod.POST, value = "/say") String sayHello(@RequestBody String name); - @RequestMapping(method = RequestMethod.POST, value = "/testFormBody", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) + @RequestMapping( + method = RequestMethod.POST, + value = "/testFormBody", + consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) Long testFormBody(@RequestBody Long number); - @RequestMapping(method = RequestMethod.POST, value = "/testJavaBeanBody", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) + @RequestMapping( + method = RequestMethod.POST, + value = "/testJavaBeanBody", + consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) User testJavaBeanBody(@RequestBody User user); - @RequestMapping(method = RequestMethod.GET, value = "/primitive") int primitiveInt(@RequestParam("a") int a, @RequestParam("b") int b); @@ -57,23 +61,21 @@ public interface SpringRestDemoService { @RequestMapping(method = RequestMethod.GET, value = "/primitiveByte") long primitiveByte(@RequestParam("a") byte a, @RequestParam("b") Long b); - @RequestMapping(method = RequestMethod.POST, value = "/primitiveShort") long primitiveShort(@RequestParam("a") short a, @RequestParam("b") Long b, @RequestBody int c); - @RequestMapping(method = RequestMethod.GET, value = "/testMapParam") String testMapParam(@RequestParam Map params); @RequestMapping(method = RequestMethod.GET, value = "/testMapHeader") String testMapHeader(@RequestHeader Map headers); - @RequestMapping(method = RequestMethod.POST, value = "/testMapForm", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) + @RequestMapping( + method = RequestMethod.POST, + value = "/testMapForm", + consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) List testMapForm(MultiValueMap params); - @RequestMapping(method = RequestMethod.GET, value = "/headerInt") int headerInt(@RequestHeader("header") int header); - - } diff --git a/dubbo-demo/dubbo-demo-interface/src/main/java/po/TestPO.java b/dubbo-demo/dubbo-demo-interface/src/main/java/po/TestPO.java index 4cd1df96d8..29a139f08a 100644 --- a/dubbo-demo/dubbo-demo-interface/src/main/java/po/TestPO.java +++ b/dubbo-demo/dubbo-demo-interface/src/main/java/po/TestPO.java @@ -27,8 +27,7 @@ public class TestPO { this.age = age; } - public TestPO() { - } + public TestPO() {} public String getName() { return name; @@ -60,10 +59,6 @@ public class TestPO { @Override public String toString() { - return "TestPO{" + - "name='" + name + '\'' + - ", address='" + address + '\'' + - ", age=" + age + - '}'; + return "TestPO{" + "name='" + name + '\'' + ", address='" + address + '\'' + ", age=" + age + '}'; } } diff --git a/dubbo-demo/dubbo-demo-interface/src/main/java/po/User.java b/dubbo-demo/dubbo-demo-interface/src/main/java/po/User.java index 2c58d9d3f2..d5a6326c90 100644 --- a/dubbo-demo/dubbo-demo-interface/src/main/java/po/User.java +++ b/dubbo-demo/dubbo-demo-interface/src/main/java/po/User.java @@ -19,16 +19,13 @@ package po; import java.io.Serializable; import java.util.Objects; - public class User implements Serializable { - private Long id; private String name; - public User() { - } + public User() {} public User(Long id, String name) { this.id = id; @@ -70,9 +67,6 @@ public class User implements Serializable { @Override public String toString() { - return "User (" + - "id=" + id + - ", name='" + name + '\'' + - ')'; + return "User (" + "id=" + id + ", name='" + name + '\'' + ')'; } } diff --git a/dubbo-demo/dubbo-demo-native/dubbo-demo-native-consumer/pom.xml b/dubbo-demo/dubbo-demo-native/dubbo-demo-native-consumer/pom.xml index 292c273958..6892e27714 100644 --- a/dubbo-demo/dubbo-demo-native/dubbo-demo-native-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-native/dubbo-demo-native-consumer/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-demo-native - ${revision} - ../pom.xml - + - 4.0.0 + 4.0.0 + + org.apache.dubbo + dubbo-demo-native + ${revision} + ../pom.xml + - dubbo-demo-native-consumer + dubbo-demo-native-consumer - - true - 5.1.0 - 3.8.3 - + + true + 5.1.0 + 3.8.3 + - - - org.apache.dubbo - dubbo-demo-native-interface - ${project.version} - - - org.apache.dubbo - dubbo-config-api - ${project.version} - - - org.apache.dubbo - dubbo-registry-multicast - ${project.version} - - - org.apache.curator - curator-x-discovery - ${curator5_version} - - - org.apache.curator - curator-recipes - ${curator5_version} - - - org.apache.curator - curator-framework - ${curator5_version} - - - org.apache.zookeeper - zookeeper - ${zookeeper_version} - - - io.netty - netty-handler - - - io.netty - netty-transport-native-epoll - - - + + + org.apache.dubbo + dubbo-demo-native-interface + ${project.version} + + + org.apache.dubbo + dubbo-config-api + ${project.version} + + + org.apache.dubbo + dubbo-registry-multicast + ${project.version} + + + org.apache.curator + curator-x-discovery + ${curator5_version} + + + org.apache.curator + curator-recipes + ${curator5_version} + + + org.apache.curator + curator-framework + ${curator5_version} + + + org.apache.zookeeper + zookeeper + ${zookeeper_version} + + + io.netty + netty-handler + + + io.netty + netty-transport-native-epoll + + + - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - - - curator-x-discovery - org.apache.curator - - - zookeeper - org.apache.zookeeper - - - org.apache.curator - curator-recipes - - - org.apache.curator - curator-framework - - - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.version} - + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.version} + + + org.apache.curator + curator-x-discovery + + + org.apache.zookeeper + zookeeper + + + org.apache.curator + curator-recipes + + + org.apache.curator + curator-framework + + + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.version} + - - org.apache.dubbo - dubbo-filter-cache - ${project.version} - - - org.apache.dubbo - dubbo-filter-validation - ${project.version} - - - org.apache.dubbo - dubbo-remoting-http - ${project.version} - + + org.apache.dubbo + dubbo-filter-cache + ${project.version} + + + org.apache.dubbo + dubbo-filter-validation + ${project.version} + + + org.apache.dubbo + dubbo-remoting-http + ${project.version} + - - com.alibaba - fastjson - + + com.alibaba + fastjson + - + + org.apache.dubbo + dubbo-native + ${project.version} + + + + + + native + + native + + + + org.apache.dubbo - dubbo-native + dubbo-maven-plugin ${project.version} - - + + org.apache.dubbo.demo.graalvm.consumer.Application + + + + + dubbo-process-aot + + process-sources + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.11.0 + + 1.8 + 1.8 + true + true + UTF-8 + + ${project.basedir}${file.separator}src${file.separator}main${file.separator}java + + + - - - native - - native - - - - - org.apache.dubbo - dubbo-maven-plugin - ${project.version} - - org.apache.dubbo.demo.graalvm.consumer.Application - - - - process-sources - - dubbo-process-aot - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.11.0 - - 1.8 - 1.8 - true - true - UTF-8 - - - ${project.basedir}${file.separator}src${file.separator}main${file.separator}java - - - - - - - org.graalvm.buildtools - native-maven-plugin - 0.9.28 - - ${project.build.outputDirectory} - - true - - 22.3 - org.apache.dubbo.demo.graalvm.consumer.Application - - - - - - + + org.graalvm.buildtools + native-maven-plugin + 0.9.28 + + ${project.build.outputDirectory} + + true + + 22.3 + org.apache.dubbo.demo.graalvm.consumer.Application + + + + + + diff --git a/dubbo-demo/dubbo-demo-native/dubbo-demo-native-consumer/src/main/java/org/apache/dubbo/demo/graalvm/consumer/Application.java b/dubbo-demo/dubbo-demo-native/dubbo-demo-native-consumer/src/main/java/org/apache/dubbo/demo/graalvm/consumer/Application.java index f430cfd7b9..77d77635f2 100644 --- a/dubbo-demo/dubbo-demo-native/dubbo-demo-native-consumer/src/main/java/org/apache/dubbo/demo/graalvm/consumer/Application.java +++ b/dubbo-demo/dubbo-demo-native/dubbo-demo-native-consumer/src/main/java/org/apache/dubbo/demo/graalvm/consumer/Application.java @@ -16,14 +16,13 @@ */ package org.apache.dubbo.demo.graalvm.consumer; -import org.apache.dubbo.graalvm.demo.DemoService; import org.apache.dubbo.common.constants.CommonConstants; +import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ReferenceConfig; -import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; - +import org.apache.dubbo.graalvm.demo.DemoService; import java.util.HashMap; import java.util.Map; @@ -32,7 +31,6 @@ public class Application { private static final String REGISTRY_URL = "zookeeper://127.0.0.1:2181"; - public static void main(String[] args) { System.setProperty("dubbo.application.logger", "log4j"); System.setProperty("native", "true"); @@ -56,15 +54,15 @@ public class Application { ProtocolConfig protocolConfig = new ProtocolConfig(CommonConstants.DUBBO, -1); protocolConfig.setSerialization("fastjson2"); - bootstrap.application(applicationConfig) - .registry(new RegistryConfig(REGISTRY_URL)) - .protocol(protocolConfig) - .reference(reference) - .start(); + bootstrap + .application(applicationConfig) + .registry(new RegistryConfig(REGISTRY_URL)) + .protocol(protocolConfig) + .reference(reference) + .start(); DemoService demoService = bootstrap.getCache().get(reference); String message = demoService.sayHello("Native"); System.out.println(message); } - } diff --git a/dubbo-demo/dubbo-demo-native/dubbo-demo-native-interface/pom.xml b/dubbo-demo/dubbo-demo-native/dubbo-demo-native-interface/pom.xml index f7476d2cb9..2184cc8e12 100644 --- a/dubbo-demo/dubbo-demo-native/dubbo-demo-native-interface/pom.xml +++ b/dubbo-demo/dubbo-demo-native/dubbo-demo-native-interface/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-demo-native - ${revision} - ../pom.xml - + - 4.0.0 + 4.0.0 + + org.apache.dubbo + dubbo-demo-native + ${revision} + ../pom.xml + - dubbo-demo-native-interface + dubbo-demo-native-interface - - true - + + true + diff --git a/dubbo-demo/dubbo-demo-native/dubbo-demo-native-interface/src/main/java/org/apache/dubbo/graalvm/demo/DemoService.java b/dubbo-demo/dubbo-demo-native/dubbo-demo-native-interface/src/main/java/org/apache/dubbo/graalvm/demo/DemoService.java index 06097a6c1f..8e338c4bac 100644 --- a/dubbo-demo/dubbo-demo-native/dubbo-demo-native-interface/src/main/java/org/apache/dubbo/graalvm/demo/DemoService.java +++ b/dubbo-demo/dubbo-demo-native/dubbo-demo-native-interface/src/main/java/org/apache/dubbo/graalvm/demo/DemoService.java @@ -19,5 +19,4 @@ package org.apache.dubbo.graalvm.demo; public interface DemoService { String sayHello(String name); - } diff --git a/dubbo-demo/dubbo-demo-native/dubbo-demo-native-provider/pom.xml b/dubbo-demo/dubbo-demo-native/dubbo-demo-native-provider/pom.xml index 9c132e812b..88a5d115ad 100644 --- a/dubbo-demo/dubbo-demo-native/dubbo-demo-native-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-native/dubbo-demo-native-provider/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-demo-native - ${revision} - ../pom.xml - + - 4.0.0 + 4.0.0 + + org.apache.dubbo + dubbo-demo-native + ${revision} + ../pom.xml + - dubbo-demo-native-provider + dubbo-demo-native-provider - - true - 5.1.0 - 3.8.3 - + + true + 5.1.0 + 3.8.3 + - - - org.apache.dubbo - dubbo-demo-native-interface - ${project.version} - - - org.apache.dubbo - dubbo-config-api - ${project.version} - - - org.apache.dubbo - dubbo-registry-multicast - ${project.version} - - - org.apache.curator - curator-x-discovery - ${curator5_version} - - - org.apache.curator - curator-recipes - ${curator5_version} - - - org.apache.curator - curator-framework - ${curator5_version} - - - org.apache.zookeeper - zookeeper - ${zookeeper_version} - - - io.netty - netty-handler - - - io.netty - netty-transport-native-epoll - - - + + + org.apache.dubbo + dubbo-demo-native-interface + ${project.version} + + + org.apache.dubbo + dubbo-config-api + ${project.version} + + + org.apache.dubbo + dubbo-registry-multicast + ${project.version} + + + org.apache.curator + curator-x-discovery + ${curator5_version} + + + org.apache.curator + curator-recipes + ${curator5_version} + + + org.apache.curator + curator-framework + ${curator5_version} + + + org.apache.zookeeper + zookeeper + ${zookeeper_version} + + + io.netty + netty-handler + + + io.netty + netty-transport-native-epoll + + + - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - - - curator-x-discovery - org.apache.curator - - - zookeeper - org.apache.zookeeper - - - org.apache.curator - curator-recipes - - - org.apache.curator - curator-framework - - - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.version} - - - org.apache.dubbo - dubbo-filter-cache - ${project.version} - - - org.apache.dubbo - dubbo-filter-validation - ${project.version} - - - org.apache.dubbo - dubbo-remoting-http - ${project.version} - - - com.alibaba - fastjson - - - org.apache.dubbo - dubbo-native - ${project.version} - - + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.version} + + + org.apache.curator + curator-x-discovery + + + org.apache.zookeeper + zookeeper + + + org.apache.curator + curator-recipes + + + org.apache.curator + curator-framework + + + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.version} + + + org.apache.dubbo + dubbo-filter-cache + ${project.version} + + + org.apache.dubbo + dubbo-filter-validation + ${project.version} + + + org.apache.dubbo + dubbo-remoting-http + ${project.version} + + + com.alibaba + fastjson + + + org.apache.dubbo + dubbo-native + ${project.version} + + - - - native - - native - + + + native + + native + - - - - org.apache.dubbo - dubbo-maven-plugin - ${project.version} - - org.apache.dubbo.demo.graalvm.provider.Application - - - - process-sources - - dubbo-process-aot - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.11.0 - - 1.8 - 1.8 - true - true - UTF-8 - - - ${project.basedir}${file.separator}src${file.separator}main${file.separator}java - - - - - - org.graalvm.buildtools - native-maven-plugin - 0.9.28 - - ${project.build.outputDirectory} - - true - - 22.3 - org.apache.dubbo.demo.graalvm.provider.Application - - - - - - + + + + org.apache.dubbo + dubbo-maven-plugin + ${project.version} + + org.apache.dubbo.demo.graalvm.provider.Application + + + + + dubbo-process-aot + + process-sources + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.11.0 + + 1.8 + 1.8 + true + true + UTF-8 + + ${project.basedir}${file.separator}src${file.separator}main${file.separator}java + + + + + org.graalvm.buildtools + native-maven-plugin + 0.9.28 + + ${project.build.outputDirectory} + + true + + 22.3 + org.apache.dubbo.demo.graalvm.provider.Application + + + + + + diff --git a/dubbo-demo/dubbo-demo-native/dubbo-demo-native-provider/src/main/java/org/apache/dubbo/demo/graalvm/provider/Application.java b/dubbo-demo/dubbo-demo-native/dubbo-demo-native-provider/src/main/java/org/apache/dubbo/demo/graalvm/provider/Application.java index f324635955..bfe638da2f 100644 --- a/dubbo-demo/dubbo-demo-native/dubbo-demo-native-provider/src/main/java/org/apache/dubbo/demo/graalvm/provider/Application.java +++ b/dubbo-demo/dubbo-demo-native/dubbo-demo-native-provider/src/main/java/org/apache/dubbo/demo/graalvm/provider/Application.java @@ -16,14 +16,13 @@ */ package org.apache.dubbo.demo.graalvm.provider; -import org.apache.dubbo.graalvm.demo.DemoService; import org.apache.dubbo.common.constants.CommonConstants; - -import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ApplicationConfig; -import org.apache.dubbo.config.ServiceConfig; +import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.RegistryConfig; +import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; +import org.apache.dubbo.graalvm.demo.DemoService; import java.util.HashMap; import java.util.Map; @@ -32,7 +31,6 @@ public class Application { private static final String REGISTRY_URL = "zookeeper://127.0.0.1:2181"; - public static void main(String[] args) throws Exception { System.setProperty("dubbo.application.logger", "log4j"); System.setProperty("native", "true"); @@ -61,14 +59,14 @@ public class Application { ProtocolConfig protocolConfig = new ProtocolConfig(CommonConstants.DUBBO, -1); protocolConfig.setSerialization("fastjson2"); - bootstrap.application(applicationConfig) - .registry(new RegistryConfig(REGISTRY_URL)) - .protocol(protocolConfig) - .service(service) - .start() - .await(); + bootstrap + .application(applicationConfig) + .registry(new RegistryConfig(REGISTRY_URL)) + .protocol(protocolConfig) + .service(service) + .start() + .await(); System.out.println("dubbo service started"); } - } diff --git a/dubbo-demo/dubbo-demo-native/dubbo-demo-native-provider/src/main/java/org/apache/dubbo/demo/graalvm/provider/DemoServiceImpl.java b/dubbo-demo/dubbo-demo-native/dubbo-demo-native-provider/src/main/java/org/apache/dubbo/demo/graalvm/provider/DemoServiceImpl.java index 38c9d1b45f..a360f6a5d9 100644 --- a/dubbo-demo/dubbo-demo-native/dubbo-demo-native-provider/src/main/java/org/apache/dubbo/demo/graalvm/provider/DemoServiceImpl.java +++ b/dubbo-demo/dubbo-demo-native/dubbo-demo-native-provider/src/main/java/org/apache/dubbo/demo/graalvm/provider/DemoServiceImpl.java @@ -16,18 +16,15 @@ */ package org.apache.dubbo.demo.graalvm.provider; -import org.apache.dubbo.rpc.RpcContext; - import org.apache.dubbo.graalvm.demo.DemoService; - +import org.apache.dubbo.rpc.RpcContext; public class DemoServiceImpl implements DemoService { @Override public String sayHello(String name) { - System.out.println("Hello " + name + ", request from consumer: " + RpcContext.getContext().getRemoteAddress()); - return "Hello " + name ; + System.out.println("Hello " + name + ", request from consumer: " + + RpcContext.getContext().getRemoteAddress()); + return "Hello " + name; } - - } diff --git a/dubbo-demo/dubbo-demo-native/pom.xml b/dubbo-demo/dubbo-demo-native/pom.xml index 0601a5dac1..4cf4a6654e 100644 --- a/dubbo-demo/dubbo-demo-native/pom.xml +++ b/dubbo-demo/dubbo-demo-native/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-demo - ${revision} - ../pom.xml - + - 4.0.0 + 4.0.0 + + org.apache.dubbo + dubbo-demo + ${revision} + ../pom.xml + - dubbo-demo-native - pom - - dubbo-demo-native-consumer - dubbo-demo-native-provider - dubbo-demo-native-interface - + dubbo-demo-native + pom + + dubbo-demo-native-consumer + dubbo-demo-native-provider + dubbo-demo-native-interface + - - true - + + true + diff --git a/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-consumer/pom.xml b/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-consumer/pom.xml index 6e414facec..a1771060af 100644 --- a/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-consumer/pom.xml @@ -1,3 +1,4 @@ + - - - dubbo-demo-spring-boot - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-demo-spring-boot + ${revision} + ../pom.xml + - dubbo-demo-spring-boot-consumer + dubbo-demo-spring-boot-consumer - - true - + + true + - - - org.apache.dubbo - dubbo-demo-spring-boot-interface - ${project.parent.version} - + + + org.apache.dubbo + dubbo-demo-spring-boot-interface + ${project.parent.version} + - - org.apache.dubbo - dubbo-spring-boot-starter - ${project.version} - + + org.apache.dubbo + dubbo-spring-boot-starter + ${project.version} + - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.version} + - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.version} - + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.version} + - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.version} - + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${project.version} + - - org.apache.dubbo - dubbo-config-spring - ${project.version} - + + org.apache.dubbo + dubbo-config-spring + ${project.version} + - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.version} + - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.version} - + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.version} + - - org.springframework.boot - spring-boot-starter - ${spring-boot.version} - + + org.springframework.boot + spring-boot-starter + ${spring-boot.version} + - - org.apache.dubbo - dubbo-tracing-otel-zipkin-spring-boot-starter - ${project.version} - + + org.apache.dubbo + dubbo-tracing-otel-zipkin-spring-boot-starter + ${project.version} + - - org.apache.dubbo - dubbo-qos - ${project.version} - - + + org.apache.dubbo + dubbo-qos + ${project.version} + + - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot-maven-plugin.version} - - - - repackage - - - - - - + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} + + + + repackage + + + + + + diff --git a/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-consumer/src/main/java/org/apache/dubbo/springboot/demo/consumer/ConsumerApplication.java b/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-consumer/src/main/java/org/apache/dubbo/springboot/demo/consumer/ConsumerApplication.java index 0b509c1003..61be9906e5 100644 --- a/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-consumer/src/main/java/org/apache/dubbo/springboot/demo/consumer/ConsumerApplication.java +++ b/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-consumer/src/main/java/org/apache/dubbo/springboot/demo/consumer/ConsumerApplication.java @@ -14,12 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.springboot.demo.consumer; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.springboot.demo.DemoService; + import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; diff --git a/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-interface/pom.xml b/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-interface/pom.xml index 75571006f0..831affea7e 100644 --- a/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-interface/pom.xml +++ b/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-interface/pom.xml @@ -1,3 +1,4 @@ + - - - dubbo-demo-spring-boot - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-demo-spring-boot + ${revision} + ../pom.xml + - dubbo-demo-spring-boot-interface + dubbo-demo-spring-boot-interface - - true - + + true + diff --git a/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-interface/src/main/java/org/apache/dubbo/springboot/demo/DemoService.java b/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-interface/src/main/java/org/apache/dubbo/springboot/demo/DemoService.java index 328be3a469..5a63840405 100644 --- a/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-interface/src/main/java/org/apache/dubbo/springboot/demo/DemoService.java +++ b/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-interface/src/main/java/org/apache/dubbo/springboot/demo/DemoService.java @@ -25,5 +25,4 @@ public interface DemoService { default CompletableFuture sayHelloAsync(String name) { return CompletableFuture.completedFuture(sayHello(name)); } - } diff --git a/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/pom.xml b/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/pom.xml index 9638f9e42c..6dd76b05c4 100644 --- a/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/pom.xml @@ -1,3 +1,4 @@ + - - - dubbo-demo-spring-boot - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-demo-spring-boot + ${revision} + ../pom.xml + - dubbo-demo-spring-boot-provider + dubbo-demo-spring-boot-provider - - true - + + true + - - - org.apache.dubbo - dubbo-demo-spring-boot-interface - ${project.parent.version} - + + + org.apache.dubbo + dubbo-demo-spring-boot-interface + ${project.parent.version} + - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.version} + - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.version} - + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.version} + - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.version} - + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${project.version} + - - org.apache.dubbo - dubbo-config-spring - ${project.version} - + + org.apache.dubbo + dubbo-config-spring + ${project.version} + - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.version} + - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.version} - + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.version} + - - - org.apache.dubbo - dubbo-tracing-otel-zipkin-spring-boot-starter - ${project.version} - + + + org.apache.dubbo + dubbo-tracing-otel-zipkin-spring-boot-starter + ${project.version} + - - org.apache.dubbo - dubbo-qos - ${project.version} - + + org.apache.dubbo + dubbo-qos + ${project.version} + - - org.springframework.boot - spring-boot-starter - - + + org.springframework.boot + spring-boot-starter + + - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot-maven-plugin.version} - - - - repackage - - - - - - + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} + + + + repackage + + + + + + diff --git a/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/src/main/java/org/apache/dubbo/springboot/demo/provider/DemoServiceImpl.java b/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/src/main/java/org/apache/dubbo/springboot/demo/provider/DemoServiceImpl.java index f0c1aecc3e..6468826fd0 100644 --- a/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/src/main/java/org/apache/dubbo/springboot/demo/provider/DemoServiceImpl.java +++ b/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/src/main/java/org/apache/dubbo/springboot/demo/provider/DemoServiceImpl.java @@ -16,10 +16,10 @@ */ package org.apache.dubbo.springboot.demo.provider; - import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.springboot.demo.DemoService; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -27,12 +27,11 @@ import org.slf4j.LoggerFactory; public class DemoServiceImpl implements DemoService { private static final Logger logger = LoggerFactory.getLogger(DemoServiceImpl.class); + @Override public String sayHello(String name) { - logger.info("Hello " + name + ", request from consumer: " + RpcContext.getContext().getRemoteAddress()); + logger.info("Hello " + name + ", request from consumer: " + + RpcContext.getContext().getRemoteAddress()); return "Hello " + name; - } - - } diff --git a/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/src/main/java/org/apache/dubbo/springboot/demo/provider/ProviderApplication.java b/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/src/main/java/org/apache/dubbo/springboot/demo/provider/ProviderApplication.java index 9406292086..db237d38ba 100644 --- a/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/src/main/java/org/apache/dubbo/springboot/demo/provider/ProviderApplication.java +++ b/dubbo-demo/dubbo-demo-spring-boot/dubbo-demo-spring-boot-provider/src/main/java/org/apache/dubbo/springboot/demo/provider/ProviderApplication.java @@ -14,16 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.springboot.demo.provider; - import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; import java.util.concurrent.CountDownLatch; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + @SpringBootApplication @EnableDubbo(scanBasePackages = {"org.apache.dubbo.springboot.demo.provider"}) public class ProviderApplication { diff --git a/dubbo-demo/dubbo-demo-spring-boot/pom.xml b/dubbo-demo/dubbo-demo-spring-boot/pom.xml index aa7ed6c1ef..086bf44d20 100644 --- a/dubbo-demo/dubbo-demo-spring-boot/pom.xml +++ b/dubbo-demo/dubbo-demo-spring-boot/pom.xml @@ -1,3 +1,4 @@ + - - - dubbo-demo - org.apache.dubbo - ${revision} - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-demo + ${revision} + - dubbo-demo-spring-boot - pom - - dubbo-demo-spring-boot-consumer - dubbo-demo-spring-boot-provider - dubbo-demo-spring-boot-interface - + dubbo-demo-spring-boot + pom + + dubbo-demo-spring-boot-consumer + dubbo-demo-spring-boot-provider + dubbo-demo-spring-boot-interface + - - true - 2.7.17 - 1.7.33 - 2.7.17 - 1.11.5 - + + true + 2.7.17 + 1.7.33 + 2.7.17 + 1.11.5 + - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - org.springframework.boot - spring-boot-starter-logging - ${spring-boot.version} - - - logback-classic - ch.qos.logback - - - log4j-to-slf4j - org.apache.logging.log4j - - - - - org.slf4j - slf4j-log4j12 - ${slf4j-log4j12_version} - - - io.micrometer - micrometer-core - ${micrometer-core.version} - - - + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + org.springframework.boot + spring-boot-starter-logging + ${spring-boot.version} + + + ch.qos.logback + logback-classic + + + org.apache.logging.log4j + log4j-to-slf4j + + + + + org.slf4j + slf4j-log4j12 + ${slf4j-log4j12_version} + + + io.micrometer + micrometer-core + ${micrometer-core.version} + + + diff --git a/dubbo-demo/dubbo-demo-triple/pom.xml b/dubbo-demo/dubbo-demo-triple/pom.xml index fb463ea86d..dc200cc784 100644 --- a/dubbo-demo/dubbo-demo-triple/pom.xml +++ b/dubbo-demo/dubbo-demo-triple/pom.xml @@ -17,158 +17,156 @@ ~ specific language governing permissions and limitations ~ under the License. --> - - - org.apache.dubbo - dubbo-demo - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-demo + ${revision} + ../pom.xml + - dubbo-demo-triple + dubbo-demo-triple - - true - + + true + - - - org.apache.dubbo - dubbo-filter-cache - ${project.version} - - - org.apache.dubbo - dubbo-config-api - ${project.version} - - - org.apache.dubbo - dubbo-config-spring - ${project.version} - - - org.apache.dubbo - dubbo-common - ${project.version} - - - org.apache.dubbo - dubbo-registry-api - ${project.version} - - - org.apache.dubbo - dubbo-registry-multicast - ${project.version} - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-registry-nacos - ${project.version} - - - com.alibaba.nacos - nacos-client - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-nacos - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-nacos - ${project.version} - - - org.apache.dubbo - dubbo-rpc-triple - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.version} - - - com.google.protobuf - protobuf-java - - + + + org.apache.dubbo + dubbo-filter-cache + ${project.version} + + + org.apache.dubbo + dubbo-config-api + ${project.version} + + + org.apache.dubbo + dubbo-config-spring + ${project.version} + + + org.apache.dubbo + dubbo-common + ${project.version} + + + org.apache.dubbo + dubbo-registry-api + ${project.version} + + + org.apache.dubbo + dubbo-registry-multicast + ${project.version} + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-registry-nacos + ${project.version} + + + com.alibaba.nacos + nacos-client + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-nacos + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-nacos + ${project.version} + + + org.apache.dubbo + dubbo-rpc-triple + ${project.parent.version} + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.version} + + + com.google.protobuf + protobuf-java + + - - - - kr.motd.maven - os-maven-plugin - ${maven_os_plugin_version} - - - initialize - - detect - - - - - - org.xolstice.maven.plugins - protobuf-maven-plugin - ${maven_protobuf_plugin_version} - - com.google.protobuf:protoc:${protobuf-protoc_version}:exe:${os.detected.classifier} - triple-java - - - - - compile - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - true - - - - + + + + kr.motd.maven + os-maven-plugin + ${maven_os_plugin_version} + + + + detect + + initialize + + + + + org.xolstice.maven.plugins + protobuf-maven-plugin + ${maven_protobuf_plugin_version} + + com.google.protobuf:protoc:${protobuf-protoc_version}:exe:${os.detected.classifier} + triple-java + + + + + compile + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + + true + + + + diff --git a/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/GreeterService.java b/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/GreeterService.java index 40492a31b2..2506a5da74 100644 --- a/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/GreeterService.java +++ b/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/GreeterService.java @@ -28,7 +28,5 @@ public interface GreeterService { */ HelloReply sayHello(HelloRequest request); - CompletableFuture sayHelloAsync(String request); - } diff --git a/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/GreeterServiceImpl.java b/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/GreeterServiceImpl.java index 284afef739..36cc07f3ee 100644 --- a/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/GreeterServiceImpl.java +++ b/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/GreeterServiceImpl.java @@ -25,9 +25,7 @@ public class GreeterServiceImpl implements GreeterService { @Override public HelloReply sayHello(HelloRequest request) { - return HelloReply.newBuilder() - .setMessage("Hello " + request.getName()) - .build(); + return HelloReply.newBuilder().setMessage("Hello " + request.getName()).build(); } @Override diff --git a/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/consumer/ApiConsumer.java b/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/consumer/ApiConsumer.java index 6f44f06f89..90cbfc49e3 100644 --- a/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/consumer/ApiConsumer.java +++ b/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/consumer/ApiConsumer.java @@ -40,23 +40,23 @@ public class ApiConsumer { referenceConfig.setTimeout(100000); DubboBootstrap bootstrap = DubboBootstrap.getInstance(); - bootstrap.application(new ApplicationConfig("dubbo-demo-triple-api-consumer")) - .registry(new RegistryConfig("zookeeper://127.0.0.1:2181")) - .protocol(new ProtocolConfig(CommonConstants.TRIPLE, -1)) - .reference(referenceConfig) - .start(); + bootstrap + .application(new ApplicationConfig("dubbo-demo-triple-api-consumer")) + .registry(new RegistryConfig("zookeeper://127.0.0.1:2181")) + .protocol(new ProtocolConfig(CommonConstants.TRIPLE, -1)) + .reference(referenceConfig) + .start(); GreeterService greeterService = referenceConfig.get(); System.out.println("dubbo referenceConfig started"); try { - final HelloReply reply = greeterService.sayHello(HelloRequest.newBuilder() - .setName("triple") - .build()); + final HelloReply reply = greeterService.sayHello( + HelloRequest.newBuilder().setName("triple").build()); TimeUnit.SECONDS.sleep(1); System.out.println("Reply: " + reply.getMessage()); CompletableFuture sayHelloAsync = greeterService.sayHelloAsync("triple"); - System.out.println("Async Reply: "+sayHelloAsync.get()); + System.out.println("Async Reply: " + sayHelloAsync.get()); } catch (Throwable t) { t.printStackTrace(); } diff --git a/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/consumer/ApiWrapperConsumer.java b/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/consumer/ApiWrapperConsumer.java index a67136b161..52bb640690 100644 --- a/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/consumer/ApiWrapperConsumer.java +++ b/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/consumer/ApiWrapperConsumer.java @@ -35,11 +35,12 @@ public class ApiWrapperConsumer { referenceConfig.setLazy(true); DubboBootstrap bootstrap = DubboBootstrap.getInstance(); - bootstrap.application(new ApplicationConfig("dubbo-demo-triple-api-wrapper-consumer")) - .registry(new RegistryConfig("zookeeper://127.0.0.1:2181")) - .protocol(new ProtocolConfig(CommonConstants.TRIPLE, -1)) - .reference(referenceConfig) - .start(); + bootstrap + .application(new ApplicationConfig("dubbo-demo-triple-api-wrapper-consumer")) + .registry(new RegistryConfig("zookeeper://127.0.0.1:2181")) + .protocol(new ProtocolConfig(CommonConstants.TRIPLE, -1)) + .reference(referenceConfig) + .start(); final GreeterWrapperService greeterWrapperService = referenceConfig.get(); System.out.println("dubbo referenceConfig started"); diff --git a/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/provider/ApiProvider.java b/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/provider/ApiProvider.java index fd422d7ac6..d2c680a87e 100644 --- a/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/provider/ApiProvider.java +++ b/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/provider/ApiProvider.java @@ -32,11 +32,12 @@ public class ApiProvider { serviceConfig.setRef(new GreeterServiceImpl()); DubboBootstrap bootstrap = DubboBootstrap.getInstance(); - bootstrap.application(new ApplicationConfig("dubbo-demo-triple-api-provider")) - .registry(new RegistryConfig("zookeeper://127.0.0.1:2181")) - .protocol(new ProtocolConfig(CommonConstants.TRIPLE, -1)) - .service(serviceConfig) - .start() - .await(); + bootstrap + .application(new ApplicationConfig("dubbo-demo-triple-api-provider")) + .registry(new RegistryConfig("zookeeper://127.0.0.1:2181")) + .protocol(new ProtocolConfig(CommonConstants.TRIPLE, -1)) + .service(serviceConfig) + .start() + .await(); } } diff --git a/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/provider/ApiWrapperProvider.java b/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/provider/ApiWrapperProvider.java index 3a78d7d56b..c874960d35 100644 --- a/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/provider/ApiWrapperProvider.java +++ b/dubbo-demo/dubbo-demo-triple/src/main/java/org/apache/dubbo/demo/provider/ApiWrapperProvider.java @@ -34,11 +34,12 @@ public class ApiWrapperProvider { serviceConfig.setRef(new GreeterWrapperServiceImpl()); DubboBootstrap bootstrap = DubboBootstrap.getInstance(); - bootstrap.application(new ApplicationConfig("dubbo-demo-triple-api-wrapper-provider")) - .registry(new RegistryConfig("zookeeper://127.0.0.1:2181")) - .protocol(new ProtocolConfig(CommonConstants.TRIPLE, -1)) - .service(serviceConfig) - .start() - .await(); + bootstrap + .application(new ApplicationConfig("dubbo-demo-triple-api-wrapper-provider")) + .registry(new RegistryConfig("zookeeper://127.0.0.1:2181")) + .protocol(new ProtocolConfig(CommonConstants.TRIPLE, -1)) + .service(serviceConfig) + .start() + .await(); } } diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/pom.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/pom.xml index 2f95fa7877..7f56bf8c84 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/pom.xml @@ -15,140 +15,138 @@ See the License for the specific language governing permissions and limitations under the License. --> - - 4.0.0 - - org.apache.dubbo - dubbo-demo-xml - ${revision} - ../pom.xml - + + 4.0.0 + + org.apache.dubbo + dubbo-demo-xml + ${revision} + ../pom.xml + - dubbo-demo-jaxrs-rest-consumer + dubbo-demo-jaxrs-rest-consumer - jar - Dubbo JAXRS Rest Consumer Demo - ${project.artifactId} + jar + ${project.artifactId} + Dubbo JAXRS Rest Consumer Demo - - true - + + true + - - - org.springframework - spring-context - - - org.springframework - spring-web - + + + org.springframework + spring-context + + + org.springframework + spring-web + - - org.apache.dubbo - dubbo-registry-multicast - ${project.version} - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-registry-nacos - ${project.version} - - - com.alibaba.nacos - nacos-client - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-nacos - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-nacos - ${project.version} - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - - - org.apache.dubbo - dubbo-config-spring - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-jdk - ${project.version} - + + org.apache.dubbo + dubbo-registry-multicast + ${project.version} + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-registry-nacos + ${project.version} + + + com.alibaba.nacos + nacos-client + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-nacos + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-nacos + ${project.version} + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + + + org.apache.dubbo + dubbo-rpc-rest + ${project.version} + + + org.apache.dubbo + dubbo-config-spring + ${project.version} + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-jdk + ${project.version} + - - org.springframework - spring-test - test - + + org.springframework + spring-test + test + - - org.apache.dubbo - dubbo-demo-interface - ${project.version} - - + + org.apache.dubbo + dubbo-demo-interface + ${project.version} + + - - - - javax.annotation - - [1.11,) - - - - javax.annotation - javax.annotation-api - 1.3.2 - - - - + + + + javax.annotation + + [1.11,) + + + + javax.annotation + javax.annotation-api + 1.3.2 + + + + diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/RestConsumer.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/RestConsumer.java index 1977f19efa..4b3b306d33 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/RestConsumer.java +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/RestConsumer.java @@ -17,12 +17,13 @@ package org.apache.dubbo.demo.rest.api; import org.apache.dubbo.demo.rest.api.annotation.DubboServiceAnnotationServiceConsumer; + +import java.util.Arrays; + import org.jboss.resteasy.specimpl.MultivaluedMapImpl; import org.springframework.context.support.ClassPathXmlApplicationContext; import po.User; -import java.util.Arrays; - public class RestConsumer { public static void main(String[] args) { @@ -30,7 +31,8 @@ public class RestConsumer { } public static void consumerService() { - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"spring/rest-consumer.xml"}); + ClassPathXmlApplicationContext context = + new ClassPathXmlApplicationContext(new String[] {"spring/rest-consumer.xml"}); context.start(); System.out.println("rest consumer start"); testExceptionMapperService(context); @@ -69,35 +71,37 @@ public class RestConsumer { assertEquals(User.getInstance(), jaxRsRestDemoService.testJavaBeanBody(User.getInstance())); } - private static void testExceptionMapperService(ClassPathXmlApplicationContext context) { String returnStr = "exception"; String paramStr = "exception"; - ExceptionMapperService exceptionMapperService = context.getBean("exceptionMapperService", ExceptionMapperService.class); + ExceptionMapperService exceptionMapperService = + context.getBean("exceptionMapperService", ExceptionMapperService.class); assertEquals(returnStr, exceptionMapperService.exception(paramStr)); } private static void httpRPCContextTest(ClassPathXmlApplicationContext context) { - HttpRequestAndResponseRPCContextService requestAndResponseRPCContextService = context.getBean("httpRequestAndResponseRPCContextService", HttpRequestAndResponseRPCContextService.class); + HttpRequestAndResponseRPCContextService requestAndResponseRPCContextService = context.getBean( + "httpRequestAndResponseRPCContextService", HttpRequestAndResponseRPCContextService.class); String returnStr = "hello"; String paramStr = "hello"; assertEquals(returnStr, requestAndResponseRPCContextService.httpRequestHeader(paramStr)); assertEquals(returnStr, requestAndResponseRPCContextService.httpRequestParam(paramStr)); - assertEquals(returnStr, requestAndResponseRPCContextService.httpResponseHeader(paramStr).get(0)); + assertEquals( + returnStr, + requestAndResponseRPCContextService.httpResponseHeader(paramStr).get(0)); } - private static void testHttpMethodService(ClassPathXmlApplicationContext context) { HttpMethodService httpMethodService = context.getBean("httpMethodService", HttpMethodService.class); String returnStr = "hello"; String paramStr = "hello"; -// assertEquals(null, httpMethodService.sayHelloHead(paramStr)); + // assertEquals(null, httpMethodService.sayHelloHead(paramStr)); assertEquals(returnStr, httpMethodService.sayHelloGet(paramStr)); assertEquals(returnStr, httpMethodService.sayHelloDelete(paramStr)); assertEquals(returnStr, httpMethodService.sayHelloPut(paramStr)); assertEquals(returnStr, httpMethodService.sayHelloOptions(paramStr)); -// Assert.assertEquals(returnStr, httpMethodService.sayHelloPatch(paramStr)); + // Assert.assertEquals(returnStr, httpMethodService.sayHelloPatch(paramStr)); assertEquals(returnStr, httpMethodService.sayHelloPost(paramStr)); } @@ -110,5 +114,4 @@ public class RestConsumer { throw new RuntimeException(); } } - } diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/annotation/DubboServiceAnnotationServiceConsumer.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/annotation/DubboServiceAnnotationServiceConsumer.java index bda5281231..dc8f6a5e69 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/annotation/DubboServiceAnnotationServiceConsumer.java +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/annotation/DubboServiceAnnotationServiceConsumer.java @@ -18,6 +18,7 @@ package org.apache.dubbo.demo.rest.api.annotation; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.demo.rest.api.DubboServiceAnnotationService; + import org.springframework.stereotype.Component; @Component diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java index a5d0edfacf..0d9eab4ecb 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java @@ -19,5 +19,4 @@ package org.apache.dubbo.demo.rest.api.config; import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan; @DubboComponentScan("org.apache.dubbo.demo.rest") -public class DubboConfig { -} +public class DubboConfig {} diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/pom.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/pom.xml index 154002ef7f..65b2e28d17 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/pom.xml @@ -15,140 +15,138 @@ See the License for the specific language governing permissions and limitations under the License. --> - - 4.0.0 - - org.apache.dubbo - dubbo-demo-xml - ${revision} - ../pom.xml - + + 4.0.0 + + org.apache.dubbo + dubbo-demo-xml + ${revision} + ../pom.xml + - dubbo-demo-jaxrs-rest-provider + dubbo-demo-jaxrs-rest-provider - jar - Dubbo JAXRS Rest Provider Demo - ${project.artifactId} + jar + ${project.artifactId} + Dubbo JAXRS Rest Provider Demo - - true - + + true + - - - org.springframework - spring-context - - - org.springframework - spring-web - + + + org.springframework + spring-context + + + org.springframework + spring-web + - - org.apache.dubbo - dubbo-registry-multicast - ${project.version} - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-registry-nacos - ${project.version} - - - com.alibaba.nacos - nacos-client - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-nacos - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-nacos - ${project.version} - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - - - org.apache.dubbo - dubbo-config-spring - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-jdk - ${project.version} - + + org.apache.dubbo + dubbo-registry-multicast + ${project.version} + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-registry-nacos + ${project.version} + + + com.alibaba.nacos + nacos-client + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-nacos + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-nacos + ${project.version} + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + + + org.apache.dubbo + dubbo-rpc-rest + ${project.version} + + + org.apache.dubbo + dubbo-config-spring + ${project.version} + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-jdk + ${project.version} + - - org.springframework - spring-test - test - + + org.springframework + spring-test + test + - - org.apache.dubbo - dubbo-demo-interface - ${project.version} - - + + org.apache.dubbo + dubbo-demo-interface + ${project.version} + + - - - - javax.annotation - - [1.11,) - - - - javax.annotation - javax.annotation-api - 1.3.2 - - - - + + + + javax.annotation + + [1.11,) + + + + javax.annotation + javax.annotation-api + 1.3.2 + + + + diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/RestProvider.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/RestProvider.java index ebc2ccfe73..d4cdbe038b 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/RestProvider.java +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/RestProvider.java @@ -18,26 +18,23 @@ package org.apache.dubbo.demo.rest.api; import org.springframework.context.support.ClassPathXmlApplicationContext; - public class RestProvider { public static void main(String[] args) throws Exception { - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"spring/rest-provider.xml"}); + ClassPathXmlApplicationContext context = + new ClassPathXmlApplicationContext(new String[] {"spring/rest-provider.xml"}); context.refresh(); -// SpringControllerService springControllerService = context.getBean(SpringControllerService.class); -// ServiceConfig serviceConfig = new ServiceConfig<>(); -// serviceConfig.setInterface(SpringControllerService.class); -// serviceConfig.setProtocol(new ProtocolConfig("rest", 8888)); -// serviceConfig.setRef(springControllerService); -// serviceConfig.export(); - + // SpringControllerService springControllerService = context.getBean(SpringControllerService.class); + // ServiceConfig serviceConfig = new ServiceConfig<>(); + // serviceConfig.setInterface(SpringControllerService.class); + // serviceConfig.setProtocol(new ProtocolConfig("rest", 8888)); + // serviceConfig.setRef(springControllerService); + // serviceConfig.export(); System.out.println("dubbo service started"); System.in.read(); } - - } diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java index a5d0edfacf..0d9eab4ecb 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java @@ -19,5 +19,4 @@ package org.apache.dubbo.demo.rest.api.config; import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan; @DubboComponentScan("org.apache.dubbo.demo.rest") -public class DubboConfig { -} +public class DubboConfig {} diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/extension/ExceptionMapperForTest.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/extension/ExceptionMapperForTest.java index 49099a606a..2fe7fe3641 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/extension/ExceptionMapperForTest.java +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/extension/ExceptionMapperForTest.java @@ -16,12 +16,10 @@ */ package org.apache.dubbo.demo.rest.api.extension; - import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionHandler; public class ExceptionMapperForTest implements ExceptionHandler { - @Override public Object result(RuntimeException exception) { return exception.getMessage(); diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/CurlServiceImpl.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/CurlServiceImpl.java index 64dacac29f..dcb3b53558 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/CurlServiceImpl.java +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/CurlServiceImpl.java @@ -19,11 +19,9 @@ package org.apache.dubbo.demo.rest.api.impl; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.demo.rest.api.CurlService; -@DubboService( interfaceClass = CurlService.class,protocol = "rest") +@DubboService(interfaceClass = CurlService.class, protocol = "rest") public class CurlServiceImpl implements CurlService { - - @Override public String curl() { return "hello,dubbo rest curl request"; diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/ExceptionMapperServiceImpl.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/ExceptionMapperServiceImpl.java index 26a69ff7fb..d8a84cc932 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/ExceptionMapperServiceImpl.java +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/ExceptionMapperServiceImpl.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.demo.rest.api.impl; - import org.apache.dubbo.demo.rest.api.ExceptionMapperService; + import org.springframework.stereotype.Service; @Service("exceptionMapperService") @@ -28,5 +28,4 @@ public class ExceptionMapperServiceImpl implements ExceptionMapperService { throw new RuntimeException(message); } - } diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/HttpMethodServiceImpl.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/HttpMethodServiceImpl.java index cc1e832ca1..24fc704bec 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/HttpMethodServiceImpl.java +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/HttpMethodServiceImpl.java @@ -17,6 +17,7 @@ package org.apache.dubbo.demo.rest.api.impl; import org.apache.dubbo.demo.rest.api.HttpMethodService; + import org.springframework.stereotype.Service; @Service("httpMethodService") @@ -57,4 +58,3 @@ public class HttpMethodServiceImpl implements HttpMethodService { return hello; } } - diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/HttpRequestAndResponseRPCContextServiceImpl.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/HttpRequestAndResponseRPCContextServiceImpl.java index 0aa6d69e6e..8c12038cf4 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/HttpRequestAndResponseRPCContextServiceImpl.java +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/HttpRequestAndResponseRPCContextServiceImpl.java @@ -16,16 +16,17 @@ */ package org.apache.dubbo.demo.rest.api.impl; +import org.apache.dubbo.demo.rest.api.HttpRequestAndResponseRPCContextService; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; -import org.apache.dubbo.demo.rest.api.HttpRequestAndResponseRPCContextService; -import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.List; import java.util.Map; +import org.springframework.stereotype.Service; + @Service("httpRequestAndResponseRPCContextService") public class HttpRequestAndResponseRPCContextServiceImpl implements HttpRequestAndResponseRPCContextService { @Override @@ -47,7 +48,6 @@ public class HttpRequestAndResponseRPCContextServiceImpl implements HttpRequestA String responseKey = "response"; outputHeaders.put(responseKey, Arrays.asList(hello)); - return outputHeaders.get(responseKey); } } diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/JaxRsRestDemoServiceImpl.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/JaxRsRestDemoServiceImpl.java index ad177d0940..06ec4fdbb9 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/JaxRsRestDemoServiceImpl.java +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-jaxrs-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/JaxRsRestDemoServiceImpl.java @@ -16,14 +16,16 @@ */ package org.apache.dubbo.demo.rest.api.impl; - import org.apache.dubbo.demo.rest.api.JaxRsRestDemoService; + +import javax.ws.rs.core.MultivaluedMap; + +import java.util.List; +import java.util.Map; + import org.springframework.stereotype.Service; import po.User; -import javax.ws.rs.core.MultivaluedMap; -import java.util.List; -import java.util.Map; @Service("jaxRsRestDemoService") public class JaxRsRestDemoServiceImpl implements JaxRsRestDemoService { @@ -42,7 +44,6 @@ public class JaxRsRestDemoServiceImpl implements JaxRsRestDemoService { return user; } - @Override public int primitiveInt(int a, int b) { return a + b; @@ -63,8 +64,6 @@ public class JaxRsRestDemoServiceImpl implements JaxRsRestDemoService { return a + b; } - - @Override public String testMapParam(Map params) { return params.get("param"); @@ -90,16 +89,13 @@ public class JaxRsRestDemoServiceImpl implements JaxRsRestDemoService { return header; } - @Override public Integer hello(Integer a, Integer b) { return a + b; } - @Override public String error() { throw new RuntimeException("test error"); } - } diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/pom.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/pom.xml index 91e117e724..d9ce547acb 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/pom.xml @@ -15,141 +15,138 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - dubbo-demo-xml - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-demo-xml + ${revision} + ../pom.xml + - dubbo-demo-spring-mvc-rest-consumer + dubbo-demo-spring-mvc-rest-consumer - jar - Dubbo Spring MVC Rest Consumer Demo - ${project.artifactId} + jar + ${project.artifactId} + Dubbo Spring MVC Rest Consumer Demo - - true - + + true + - - - org.springframework - spring-context - - - org.springframework - spring-web - + + + org.springframework + spring-context + + + org.springframework + spring-web + - - org.apache.dubbo - dubbo-registry-multicast - ${project.version} - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-registry-nacos - ${project.version} - - - com.alibaba.nacos - nacos-client - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-nacos - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-nacos - ${project.version} - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - - - org.apache.dubbo - dubbo-config-spring - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-jdk - ${project.version} - + + org.apache.dubbo + dubbo-registry-multicast + ${project.version} + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-registry-nacos + ${project.version} + + + com.alibaba.nacos + nacos-client + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-nacos + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-nacos + ${project.version} + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + + + org.apache.dubbo + dubbo-rpc-rest + ${project.version} + + + org.apache.dubbo + dubbo-config-spring + ${project.version} + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-jdk + ${project.version} + - - org.springframework - spring-test - test - + + org.springframework + spring-test + test + - - org.apache.dubbo - dubbo-demo-interface - ${project.version} - - + + org.apache.dubbo + dubbo-demo-interface + ${project.version} + + - - - - javax.annotation - - [1.11,) - - - - javax.annotation - javax.annotation-api - 1.3.2 - - - - + + + + javax.annotation + + [1.11,) + + + + javax.annotation + javax.annotation-api + 1.3.2 + + + + - diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/SpringMvcRestConsumer.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/SpringMvcRestConsumer.java index 43e1dc5854..e64117cce0 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/SpringMvcRestConsumer.java +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/SpringMvcRestConsumer.java @@ -16,13 +16,13 @@ */ package org.apache.dubbo.demo.rest.api; +import java.util.Arrays; + import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import po.User; -import java.util.Arrays; - public class SpringMvcRestConsumer { public static void main(String[] args) { @@ -30,7 +30,8 @@ public class SpringMvcRestConsumer { } public static void consumerService() { - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"spring/rest-consumer.xml"}); + ClassPathXmlApplicationContext context = + new ClassPathXmlApplicationContext(new String[] {"spring/rest-consumer.xml"}); context.start(); System.out.println("spring mvc rest consumer start"); springMvcRestDemoServiceTest(context); @@ -38,7 +39,8 @@ public class SpringMvcRestConsumer { } private static void springMvcRestDemoServiceTest(ClassPathXmlApplicationContext context) { - SpringRestDemoService springRestDemoService = context.getBean("springRestDemoService", SpringRestDemoService.class); + SpringRestDemoService springRestDemoService = + context.getBean("springRestDemoService", SpringRestDemoService.class); String hello = springRestDemoService.sayHello("hello"); assertEquals("Hello, hello", hello); Integer result = springRestDemoService.primitiveInt(1, 2); @@ -60,7 +62,6 @@ public class SpringMvcRestConsumer { assertEquals(User.getInstance(), springRestDemoService.testJavaBeanBody(User.getInstance())); } - private static void assertEquals(Object returnStr, Object exception) { boolean equal = returnStr != null && returnStr.equals(exception); @@ -70,5 +71,4 @@ public class SpringMvcRestConsumer { throw new RuntimeException(); } } - } diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java index 9710c76921..0d9eab4ecb 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java @@ -19,7 +19,4 @@ package org.apache.dubbo.demo.rest.api.config; import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan; @DubboComponentScan("org.apache.dubbo.demo.rest") -public class DubboConfig { - - -} +public class DubboConfig {} diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/consumer/SpringRestDemoServiceConsumer.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/consumer/SpringRestDemoServiceConsumer.java index 180947cd2d..fbedf5decd 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/consumer/SpringRestDemoServiceConsumer.java +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-consumer/src/main/java/org/apache/dubbo/demo/rest/api/consumer/SpringRestDemoServiceConsumer.java @@ -18,12 +18,11 @@ package org.apache.dubbo.demo.rest.api.consumer; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.demo.rest.api.SpringRestDemoService; + import org.springframework.stereotype.Component; @Component public class SpringRestDemoServiceConsumer { - @DubboReference(interfaceClass = SpringRestDemoService.class ) + @DubboReference(interfaceClass = SpringRestDemoService.class) SpringRestDemoService springRestDemoService; - - } diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/pom.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/pom.xml index 6220394435..4a4a98a216 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/pom.xml @@ -15,140 +15,138 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - dubbo-demo-xml - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-demo-xml + ${revision} + ../pom.xml + - dubbo-demo-spring-mvc-rest-provider + dubbo-demo-spring-mvc-rest-provider - jar - Dubbo Spring MVC Rest Provider Demo - ${project.artifactId} + jar + ${project.artifactId} + Dubbo Spring MVC Rest Provider Demo - - true - + + true + - - - org.springframework - spring-context - - - org.springframework - spring-web - + + + org.springframework + spring-context + + + org.springframework + spring-web + - - org.apache.dubbo - dubbo-registry-multicast - ${project.version} - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-registry-nacos - ${project.version} - - - com.alibaba.nacos - nacos-client - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-nacos - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-nacos - ${project.version} - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - - - org.apache.dubbo - dubbo-config-spring - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-jdk - ${project.version} - + + org.apache.dubbo + dubbo-registry-multicast + ${project.version} + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-registry-nacos + ${project.version} + + + com.alibaba.nacos + nacos-client + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-nacos + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-nacos + ${project.version} + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + + + org.apache.dubbo + dubbo-rpc-rest + ${project.version} + + + org.apache.dubbo + dubbo-config-spring + ${project.version} + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-jdk + ${project.version} + - - org.springframework - spring-test - test - + + org.springframework + spring-test + test + - - org.apache.dubbo - dubbo-demo-interface - ${project.version} - - + + org.apache.dubbo + dubbo-demo-interface + ${project.version} + + - - - - javax.annotation - - [1.11,) - - - - javax.annotation - javax.annotation-api - 1.3.2 - - - - + + + + javax.annotation + + [1.11,) + + + + javax.annotation + javax.annotation-api + 1.3.2 + + + + diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/SpringMvcRestProvider.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/SpringMvcRestProvider.java index 70b2fe9a41..81bc102481 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/SpringMvcRestProvider.java +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/SpringMvcRestProvider.java @@ -18,19 +18,16 @@ package org.apache.dubbo.demo.rest.api; import org.springframework.context.support.ClassPathXmlApplicationContext; - public class SpringMvcRestProvider { public static void main(String[] args) throws Exception { - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"spring/rest-provider.xml"}); + ClassPathXmlApplicationContext context = + new ClassPathXmlApplicationContext(new String[] {"spring/rest-provider.xml"}); context.refresh(); - System.out.println("spring mvc rest provider started"); System.in.read(); } - - } diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java index a5d0edfacf..0d9eab4ecb 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/config/DubboConfig.java @@ -19,5 +19,4 @@ package org.apache.dubbo.demo.rest.api.config; import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan; @DubboComponentScan("org.apache.dubbo.demo.rest") -public class DubboConfig { -} +public class DubboConfig {} diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/SpringRestDemoServiceImpl.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/SpringRestDemoServiceImpl.java index 2798e89aa3..6cdaede32f 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/SpringRestDemoServiceImpl.java +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-spring-mvc-rest-provider/src/main/java/org/apache/dubbo/demo/rest/api/impl/SpringRestDemoServiceImpl.java @@ -16,16 +16,16 @@ */ package org.apache.dubbo.demo.rest.api.impl; - import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.demo.rest.api.SpringRestDemoService; -import org.springframework.util.MultiValueMap; -import po.User; import java.util.List; import java.util.Map; -@DubboService(interfaceClass = SpringRestDemoService.class ,protocol = "rest") +import org.springframework.util.MultiValueMap; +import po.User; + +@DubboService(interfaceClass = SpringRestDemoService.class, protocol = "rest") public class SpringRestDemoServiceImpl implements SpringRestDemoService { @Override @@ -43,7 +43,6 @@ public class SpringRestDemoServiceImpl implements SpringRestDemoService { return user; } - @Override public int primitiveInt(int a, int b) { return a + b; @@ -64,7 +63,6 @@ public class SpringRestDemoServiceImpl implements SpringRestDemoService { return a + b; } - @Override public String testMapParam(Map params) { return params.get("param"); @@ -80,22 +78,18 @@ public class SpringRestDemoServiceImpl implements SpringRestDemoService { return params.get("form"); } - @Override public int headerInt(int header) { return header; } - @Override public Integer hello(Integer a, Integer b) { return a + b; } - @Override public String error() { throw new RuntimeException("test error"); } - } diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-consumer/pom.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-consumer/pom.xml index b614dd6675..4060ae76c5 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-consumer/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-demo-xml - ${revision} - ../pom.xml - - dubbo-demo-xml-consumer - jar - ${project.artifactId} - The demo consumer module of dubbo project - - true - - - - org.apache.dubbo - dubbo-demo-interface - ${project.parent.version} - - - org.apache.dubbo - dubbo-registry-multicast - ${project.version} - - - org.apache.dubbo - dubbo-registry-nacos - ${project.version} - - - com.alibaba.nacos - nacos-client - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-nacos - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-nacos - ${project.version} - - - org.apache.dubbo - dubbo-config-spring - ${project.version} - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-jdk - ${project.version} - - - org.apache.dubbo - dubbo-rpc-triple - ${project.version} - - + 4.0.0 + + org.apache.dubbo + dubbo-demo-xml + ${revision} + ../pom.xml + + dubbo-demo-xml-consumer + jar + ${project.artifactId} + The demo consumer module of dubbo project + + true + + + + org.apache.dubbo + dubbo-demo-interface + ${project.parent.version} + + + org.apache.dubbo + dubbo-registry-multicast + ${project.version} + + + org.apache.dubbo + dubbo-registry-nacos + ${project.version} + + + com.alibaba.nacos + nacos-client + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-nacos + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-nacos + ${project.version} + + + org.apache.dubbo + dubbo-config-spring + ${project.version} + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-jdk + ${project.version} + + + org.apache.dubbo + dubbo-rpc-triple + ${project.version} + + diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-consumer/src/main/java/org/apache/dubbo/demo/consumer/Application.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-consumer/src/main/java/org/apache/dubbo/demo/consumer/Application.java index b32502fcc3..2960b8d50e 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-consumer/src/main/java/org/apache/dubbo/demo/consumer/Application.java +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-consumer/src/main/java/org/apache/dubbo/demo/consumer/Application.java @@ -21,14 +21,15 @@ import org.apache.dubbo.demo.GreetingService; import org.apache.dubbo.demo.RestDemoService; import org.apache.dubbo.demo.TripleService; -import org.springframework.context.support.ClassPathXmlApplicationContext; -import po.TestPO; - import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; + import java.util.Arrays; import java.util.concurrent.CompletableFuture; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import po.TestPO; + public class Application { /** * In order to make sure multicast registry works, need to specify '-Djava.net.preferIPv4Stack=true' before @@ -43,48 +44,50 @@ public class Application { TripleService tripleService = context.getBean("tripleService", TripleService.class); new Thread(() -> { - while (true) { - try { - String greetings = greetingService.hello(); - System.out.println(greetings + " from separated thread."); - } catch (Exception e) { -// e.printStackTrace(); - } - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - } - } - }).start(); + while (true) { + try { + String greetings = greetingService.hello(); + System.out.println(greetings + " from separated thread."); + } catch (Exception e) { + // e.printStackTrace(); + } + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + } + } + }) + .start(); new Thread(() -> { - while (true) { - try { - Object restResult = restDemoService.sayHello("rest"); - System.out.println(restResult + " from separated thread."); - restResult = restDemoService.testBody5(TestPO.getInstance()); - System.out.println(restResult + " from separated thread."); + while (true) { + try { + Object restResult = restDemoService.sayHello("rest"); + System.out.println(restResult + " from separated thread."); + restResult = restDemoService.testBody5(TestPO.getInstance()); + System.out.println(restResult + " from separated thread."); - restResult = restDemoService.hello(1, 2); - System.out.println(restResult + " from separated thread."); + restResult = restDemoService.hello(1, 2); + System.out.println(restResult + " from separated thread."); - String form1 = restDemoService.testForm1("form1"); - System.out.println(form1); + String form1 = restDemoService.testForm1("form1"); + System.out.println(form1); - MultivaluedHashMap multivaluedHashMap = new MultivaluedHashMap(); - multivaluedHashMap.put("1", Arrays.asList("1")); - multivaluedHashMap.put("2", Arrays.asList("2")); - MultivaluedMap form2 = restDemoService.testForm2(multivaluedHashMap); - System.out.println(form2); - } catch (Exception e) { - e.printStackTrace(); - } - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - } - } - }).start(); + MultivaluedHashMap multivaluedHashMap = new MultivaluedHashMap(); + multivaluedHashMap.put("1", Arrays.asList("1")); + multivaluedHashMap.put("2", Arrays.asList("2")); + MultivaluedMap form2 = restDemoService.testForm2(multivaluedHashMap); + System.out.println(form2); + } catch (Exception e) { + e.printStackTrace(); + } + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + } + } + }) + .start(); while (true) { try { @@ -94,7 +97,7 @@ public class Application { String greetings = greetingService.hello(); System.out.println("result: " + greetings); } catch (Exception e) { -// e.printStackTrace(); + // e.printStackTrace(); } Thread.sleep(5000); diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/pom.xml b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/pom.xml index 0d1d8a85af..86fa7f498c 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - org.apache.dubbo - dubbo-demo-xml - ${revision} - ../pom.xml - - dubbo-demo-xml-provider - jar - ${project.artifactId} - The demo provider module of dubbo project + + 4.0.0 + + org.apache.dubbo + dubbo-demo-xml + ${revision} + ../pom.xml + + dubbo-demo-xml-provider + jar + ${project.artifactId} + The demo provider module of dubbo project - - true - + + true + - - - org.apache.dubbo - dubbo-demo-interface - ${project.parent.version} - - - org.apache.dubbo - dubbo-registry-multicast - ${project.version} - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-registry-nacos - ${project.version} - - - com.alibaba.nacos - nacos-client - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-nacos - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-nacos - ${project.version} - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - - - org.apache.dubbo - dubbo-config-spring - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-jdk - ${project.version} - - - org.apache.dubbo - dubbo-rpc-triple - ${project.version} - - - org.apache.dubbo - dubbo-qos - ${project.version} - - + + + org.apache.dubbo + dubbo-demo-interface + ${project.parent.version} + + + org.apache.dubbo + dubbo-registry-multicast + ${project.version} + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-registry-nacos + ${project.version} + + + com.alibaba.nacos + nacos-client + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-nacos + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-nacos + ${project.version} + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + + + org.apache.dubbo + dubbo-rpc-rest + ${project.version} + + + org.apache.dubbo + dubbo-config-spring + ${project.version} + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-jdk + ${project.version} + + + org.apache.dubbo + dubbo-rpc-triple + ${project.version} + + + org.apache.dubbo + dubbo-qos + ${project.version} + + diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo/provider/DemoServiceImpl.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo/provider/DemoServiceImpl.java index 8b36c98969..3467051454 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo/provider/DemoServiceImpl.java +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo/provider/DemoServiceImpl.java @@ -19,33 +19,35 @@ package org.apache.dubbo.demo.provider; import org.apache.dubbo.demo.DemoService; import org.apache.dubbo.rpc.RpcContext; +import java.util.concurrent.CompletableFuture; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.concurrent.CompletableFuture; - public class DemoServiceImpl implements DemoService { private static final Logger logger = LoggerFactory.getLogger(DemoServiceImpl.class); @Override public String sayHello(String name) { - logger.info("Hello " + name + ", request from consumer: " + RpcContext.getServiceContext().getRemoteAddress()); + logger.info("Hello " + name + ", request from consumer: " + + RpcContext.getServiceContext().getRemoteAddress()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } - return "Hello " + name + ", response from provider: " + RpcContext.getServiceContext().getLocalAddress(); + return "Hello " + name + ", response from provider: " + + RpcContext.getServiceContext().getLocalAddress(); } @Override public CompletableFuture sayHelloAsync(String name) { CompletableFuture cf = CompletableFuture.supplyAsync(() -> { -// try { -// Thread.sleep(1000); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } + // try { + // Thread.sleep(1000); + // } catch (InterruptedException e) { + // e.printStackTrace(); + // } return "async result"; }); return cf; diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo/provider/RestDemoServiceImpl.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo/provider/RestDemoServiceImpl.java index c0864c7a1b..37155fa436 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo/provider/RestDemoServiceImpl.java +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo/provider/RestDemoServiceImpl.java @@ -16,14 +16,15 @@ */ package org.apache.dubbo.demo.provider; - import org.apache.dubbo.demo.RestDemoService; import org.apache.dubbo.rpc.RpcContext; -import po.TestPO; import javax.ws.rs.core.MultivaluedMap; + import java.util.Map; +import po.TestPO; + public class RestDemoServiceImpl implements RestDemoService { private static Map context; private boolean called; @@ -33,7 +34,6 @@ public class RestDemoServiceImpl implements RestDemoService { return "Hello, " + name; } - public boolean isCalled() { return called; } @@ -83,12 +83,10 @@ public class RestDemoServiceImpl implements RestDemoService { return testPO; } - public String testForm1(String test) { return test; } - public MultivaluedMap testForm2(MultivaluedMap map) { return map; } diff --git a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo/provider/TripleServiceImpl.java b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo/provider/TripleServiceImpl.java index 75c27f8784..f1861454d1 100644 --- a/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo/provider/TripleServiceImpl.java +++ b/dubbo-demo/dubbo-demo-xml/dubbo-demo-xml-provider/src/main/java/org/apache/dubbo/demo/provider/TripleServiceImpl.java @@ -24,5 +24,4 @@ public class TripleServiceImpl implements TripleService { public String hello() { return "Triple!"; } - } diff --git a/dubbo-demo/dubbo-demo-xml/pom.xml b/dubbo-demo/dubbo-demo-xml/pom.xml index e491c67a12..f24ac41aa6 100644 --- a/dubbo-demo/dubbo-demo-xml/pom.xml +++ b/dubbo-demo/dubbo-demo-xml/pom.xml @@ -17,48 +17,47 @@ ~ specific language governing permissions and limitations ~ under the License. --> - - - org.apache.dubbo - dubbo-demo - ${revision} - ../pom.xml - - 4.0.0 - pom + 4.0.0 + + org.apache.dubbo + dubbo-demo + ${revision} + ../pom.xml + - dubbo-demo-xml + dubbo-demo-xml + pom - - true - 2.7.17 - + + dubbo-demo-xml-provider + dubbo-demo-xml-consumer + dubbo-demo-jaxrs-rest-consumer + dubbo-demo-jaxrs-rest-provider + dubbo-demo-spring-mvc-rest-consumer + dubbo-demo-spring-mvc-rest-provider + - - dubbo-demo-xml-provider - dubbo-demo-xml-consumer - dubbo-demo-jaxrs-rest-consumer - dubbo-demo-jaxrs-rest-provider - dubbo-demo-spring-mvc-rest-consumer - dubbo-demo-spring-mvc-rest-provider - + + true + 2.7.17 + - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot-maven-plugin.version} - - - - repackage - - - - - - + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} + + + + repackage + + + + + + diff --git a/dubbo-demo/pom.xml b/dubbo-demo/pom.xml index 59ada40918..fea5b042e7 100644 --- a/dubbo-demo/pom.xml +++ b/dubbo-demo/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-parent - ${revision} - ../pom.xml - - dubbo-demo - pom - ${project.artifactId} - The demo module of dubbo project + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + + dubbo-demo + pom + ${project.artifactId} + The demo module of dubbo project - - true - + + dubbo-demo-interface + dubbo-demo-xml + dubbo-demo-annotation + dubbo-demo-api + dubbo-demo-generic-call + dubbo-demo-triple + dubbo-demo-native + dubbo-demo-spring-boot + - - dubbo-demo-interface - dubbo-demo-xml - dubbo-demo-annotation - dubbo-demo-api - dubbo-demo-generic-call - dubbo-demo-triple - dubbo-demo-native - dubbo-demo-spring-boot - + + true + - - - org.slf4j - slf4j-log4j12 - - + + + org.slf4j + slf4j-log4j12 + + diff --git a/dubbo-dependencies-bom/pom.xml b/dubbo-dependencies-bom/pom.xml index 944a2ead34..4f1887314b 100644 --- a/dubbo-dependencies-bom/pom.xml +++ b/dubbo-dependencies-bom/pom.xml @@ -15,1155 +15,1157 @@ See the License for the specific language governing permissions and limitations under the License. --> - - 4.0.0 + + 4.0.0 - - org.apache - apache - 27 - - + + org.apache + apache + 27 + + - org.apache.dubbo - dubbo-dependencies-bom - ${revision} - pom + org.apache.dubbo + dubbo-dependencies-bom + ${revision} + pom - dubbo-dependencies-bom - Dubbo dependencies BOM + dubbo-dependencies-bom + Dubbo dependencies BOM + https://github.com/apache/dubbo + 2011 + + + The Apache Software Foundation + http://www.apache.org/ + + + + Apache License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0 + repo + + + + + dubbo.io + The Dubbo Project Contributors + dev-subscribe@dubbo.apache.org + http://dubbo.apache.org/ + + + + + Development List + dev-subscribe@dubbo.apache.org + dev-unsubscribe@dubbo.apache.org + dev@dubbo.apache.org + + + Commits List + commits-subscribe@dubbo.apache.org + commits-unsubscribe@dubbo.apache.org + commits@dubbo.apache.org + + + Issues List + issues-subscribe@dubbo.apache.org + issues-unsubscribe@dubbo.apache.org + issues@dubbo.apache.org + + + + + scm:git:https://github.com/apache/dubbo.git + scm:git:https://github.com/apache/dubbo.git + HEAD https://github.com/apache/dubbo - 2011 - - - Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0 - repo - - + - - https://github.com/apache/dubbo - scm:git:https://github.com/apache/dubbo.git - scm:git:https://github.com/apache/dubbo.git - HEAD - - - - Development List - dev-subscribe@dubbo.apache.org - dev-unsubscribe@dubbo.apache.org - dev@dubbo.apache.org - - - Commits List - commits-subscribe@dubbo.apache.org - commits-unsubscribe@dubbo.apache.org - commits@dubbo.apache.org - - - Issues List - issues-subscribe@dubbo.apache.org - issues-unsubscribe@dubbo.apache.org - issues@dubbo.apache.org - - - - - dubbo.io - The Dubbo Project Contributors - dev-subscribe@dubbo.apache.org - http://dubbo.apache.org/ - - + + Github Issues + https://github.com/apache/dubbo/issues + - - The Apache Software Foundation - http://www.apache.org/ - + + + + 5.3.25 + 5.8.8 + 3.29.2-GA + 1.14.9 + 3.2.10.Final + 4.1.100.Final + 2.2.1 + 2.4.4 + 4.5.14 + 4.4.16 + 1.2.83 + 2.0.42 + 3.7.0 + 5.1.0 + 2.12.0 + 3.10.0 + 1.4.5 + 2.2.1 + 1.5.3 + 1.4.3 + 3.5.5 + 0.19.0 + 4.0.66 + 3.25.0 + 1.3.2 + 3.1.0 + 9.4.53.v20231009 + 3.0.2 + 1.1.0.Final + 5.4.3.Final + 7.0.5.Final + 3.0.1-b12 + 1.1.1 + 4.0.3 + 0.45 + 2.57 + 1.11.1 + 2.1.0 + 2.2 + 3.12.0 + 1.8.0 + 0.1.35 + 1.11.5 + 1.26.0 + 2.16.4 + 1.1.6 + 3.3 + 0.16.0 + 1.0.4 + 3.5.11 + 2.2.21 + 3.14.9 - - Github Issues - https://github.com/apache/dubbo/issues - + 2.1.1 + 3.15.6.Final + 1.9.13 + 8.5.87 + 0.7.6 + 2.2.4 + 1.8.6 + 1.6.1 + 1.59.0 + 0.8.1 + 1.2.2 + 0.9.10 + + 1.7.36 + + 1.7.33 + 1.2 + 1.2.17 + 1.2.11 + + 2.20.0 + 2.11.0 + 1.16.0 - - - - 5.3.25 - 5.8.8 - 3.29.2-GA - 1.14.9 - 3.2.10.Final - 4.1.100.Final - 2.2.1 - 2.4.4 - 4.5.14 - 4.4.16 - 1.2.83 - 2.0.42 - 3.7.0 - 5.1.0 - 2.12.0 - 3.10.0 - 1.4.5 - 2.2.1 - 1.5.3 - 1.4.3 - 3.5.5 - 0.19.0 - 4.0.66 - 3.25.0 - 1.3.2 - 3.1.0 - 9.4.53.v20231009 - 3.0.2 - 1.1.0.Final - 5.4.3.Final - 7.0.5.Final - 3.0.1-b12 - 1.1.1 - 4.0.3 - 0.45 - 2.57 - 1.11.1 - 2.1.0 - 2.2 - 3.12.0 - 1.8.0 - 0.1.35 - 1.11.5 - 1.26.0 - 2.16.4 - 1.1.6 - 3.3 - 0.16.0 - 1.0.4 - 3.5.11 - 2.2.21 - 3.14.9 + 0.13.0 - 2.1.1 - 3.15.6.Final - 1.9.13 - 8.5.87 - 0.7.6 - 2.2.4 - 1.8.6 - 1.6.1 - 1.59.0 - 0.8.1 - 1.2.2 - 0.9.10 - - 1.7.36 - - 1.7.33 - 1.2 - 1.2.17 - 1.2.11 - - 2.20.0 - 2.11.0 - 1.16.0 + + 1.10.18 - 0.13.0 + + 6.9.1 - - 1.10.18 + + 1.0.11 - - 6.9.1 + + 5.9.3 + 4.2.0 + 2.2 + 2.2.2 + 4.11.0 - - 1.0.11 + 2.2.7 + 1.2.0 + 1.19.1 + 0.7.6 + 3.2.13 + 1.6.12 - - 5.9.3 - 4.2.0 - 2.2 - 2.2.2 - 4.11.0 + 1.1.10.5 + 1.70 + 2.0.6 + 5.4.3 + 2.10.1 + 2.15.3 + 6.1.26 + 2.0 + 1.5.0 + 1.23.0 + 2.40.0 + check + 1.0.0 + 2.38.0 + 3.3.0-beta.2-SNAPSHOT + 3.1.5 + - 2.2.7 - 1.2.0 - 1.19.1 - 0.7.6 - 3.2.13 - 1.6.12 + + + + + org.springframework + spring-framework-bom + ${spring_version} + pom + import + + + org.springframework.security + spring-security-bom + ${spring_security_version} + pom + import + + + io.netty + netty-bom + ${netty4_version} + pom + import + + + io.micrometer + micrometer-bom + ${micrometer.version} + pom + import + + + io.micrometer + micrometer-tracing-bom + ${micrometer-tracing.version} + pom + import + + + io.opentelemetry + opentelemetry-bom + ${opentelemetry.version} + pom + import + + + io.zipkin.reporter2 + zipkin-reporter-bom + ${zipkin-reporter.version} + pom + import + + + io.netty + netty-all + ${netty4_version} + + + org.javassist + javassist + ${javassist_version} + + + net.bytebuddy + byte-buddy + ${bytebuddy.version} + + + org.jboss.netty + netty + ${netty_version} + + + org.apache.mina + mina-core + ${mina_version} + + + org.glassfish.grizzly + grizzly-core + ${grizzly_version} + + + org.apache.httpcomponents + httpclient + ${httpclient_version} + + + org.apache.httpcomponents + httpcore + ${httpcore_version} + + + com.alibaba + fastjson + ${fastjson_version} + + + com.alibaba.fastjson2 + fastjson2 + ${fastjson2_version} + + + org.apache.zookeeper + zookeeper + ${zookeeper_version} + + + org.slf4j + slf4j-log4j12 + + + log4j + log4j + + + ch.qos.logback + logback-core + + + ch.qos.logback + logback-classic + + + org.apache.yetus + audience-annotations + + + io.netty + * + + + + + org.apache.curator + curator-framework + ${curator_version} + + + org.apache.zookeeper + zookeeper + + + + + org.apache.curator + curator-x-discovery + ${curator_version} + + + org.apache.zookeeper + zookeeper + + + + + redis.clients + jedis + ${jedis_version} + + + com.ecwid.consul + consul-api + ${consul_version} + + + com.pszymczyk.consul + embedded-consul + ${consul_process_version} + test + + + com.orbitz.consul + consul-client + ${consul_client_version} + + + + com.netflix.eureka + eureka-client + ${eureka.version} + + + com.netflix.eureka + eureka-core + ${eureka.version} + - 1.1.10.5 - 1.70 - 2.0.6 - 5.4.3 - 2.10.1 - 2.15.3 - 6.1.26 - 2.0 - 1.5.0 - 1.23.0 - 2.40.0 - check - 1.0.0 - 3.3.0-beta.2-SNAPSHOT - 3.1.5 - + + + com.alibaba.spring + spring-context-support + ${alibaba_spring_context_support_version} + - - - - - org.springframework - spring-framework-bom - ${spring_version} - pom - import - - - org.springframework.security - spring-security-bom - ${spring_security_version} - pom - import - - - io.netty - netty-bom - ${netty4_version} - pom - import - - - io.micrometer - micrometer-bom - ${micrometer.version} - pom - import - - - io.micrometer - micrometer-tracing-bom - ${micrometer-tracing.version} - pom - import - - - io.opentelemetry - opentelemetry-bom - ${opentelemetry.version} - pom - import - - - io.zipkin.reporter2 - zipkin-reporter-bom - ${zipkin-reporter.version} - pom - import - - - io.netty - netty-all - ${netty4_version} - - - org.javassist - javassist - ${javassist_version} - - - net.bytebuddy - byte-buddy - ${bytebuddy.version} - - - org.jboss.netty - netty - ${netty_version} - - - org.apache.mina - mina-core - ${mina_version} - - - org.glassfish.grizzly - grizzly-core - ${grizzly_version} - - - org.apache.httpcomponents - httpclient - ${httpclient_version} - - - org.apache.httpcomponents - httpcore - ${httpcore_version} - - - com.alibaba - fastjson - ${fastjson_version} - - - com.alibaba.fastjson2 - fastjson2 - ${fastjson2_version} - - - org.apache.zookeeper - zookeeper - ${zookeeper_version} - - - slf4j-log4j12 - org.slf4j - - - log4j - log4j - - - logback-core - ch.qos.logback - - - logback-classic - ch.qos.logback - - - audience-annotations - org.apache.yetus - - - * - io.netty - - - - - org.apache.curator - curator-framework - ${curator_version} - - - org.apache.zookeeper - zookeeper - - - - - org.apache.curator - curator-x-discovery - ${curator_version} - - - org.apache.zookeeper - zookeeper - - - - - redis.clients - jedis - ${jedis_version} - - - com.ecwid.consul - consul-api - ${consul_version} - - - com.pszymczyk.consul - embedded-consul - ${consul_process_version} - test - - - com.orbitz.consul - consul-client - ${consul_client_version} - - - - com.netflix.eureka - eureka-client - ${eureka.version} - - - com.netflix.eureka - eureka-core - ${eureka.version} - + + com.googlecode.xmemcached + xmemcached + ${xmemcached_version} + + + org.apache.cxf + cxf-rt-frontend-simple + ${cxf_version} + + + org.apache.cxf + cxf-rt-transports-http + ${cxf_version} + + + org.apache.thrift + libthrift + ${thrift_version} + + + com.caucho + hessian + ${hessian_version} + + + com.alibaba + hessian-lite + ${hessian_lite_version} + + + com.google.protobuf + protobuf-java + ${protobuf-java_version} + + + com.google.protobuf + protobuf-java-util + ${protobuf-java_version} + + + org.bouncycastle + bcprov-jdk15on + ${bouncycastle-bcprov_version} + + + org.bouncycastle + bcpkix-jdk15on + ${bouncycastle-bcprov_version} + + + org.bouncycastle + bcprov-ext-jdk15on + ${bouncycastle-bcprov_version} + - - - com.alibaba.spring - spring-context-support - ${alibaba_spring_context_support_version} - + + + javax.annotation + javax.annotation-api + ${javax_annotation-api_version} + + + + javax.servlet + javax.servlet-api + ${servlet_version} + - - com.googlecode.xmemcached - xmemcached - ${xmemcached_version} - - - org.apache.cxf - cxf-rt-frontend-simple - ${cxf_version} - - - org.apache.cxf - cxf-rt-transports-http - ${cxf_version} - - - org.apache.thrift - libthrift - ${thrift_version} - - - com.caucho - hessian - ${hessian_version} - - - com.alibaba - hessian-lite - ${hessian_lite_version} - - - com.google.protobuf - protobuf-java - ${protobuf-java_version} - - - com.google.protobuf - protobuf-java-util - ${protobuf-java_version} - - - org.bouncycastle - bcprov-jdk15on - ${bouncycastle-bcprov_version} - - - org.bouncycastle - bcpkix-jdk15on - ${bouncycastle-bcprov_version} - - - org.bouncycastle - bcprov-ext-jdk15on - ${bouncycastle-bcprov_version} - + + com.squareup.okhttp3 + okhttp + ${okhttp_version} + + + com.squareup.okhttp3 + mockwebserver + ${okhttp_version} + - - - javax.annotation - javax.annotation-api - ${javax_annotation-api_version} - - - - javax.servlet - javax.servlet-api - ${servlet_version} - + + org.eclipse.jetty + jetty-server + ${jetty_version} + + + org.eclipse.jetty + jetty-servlet + ${jetty_version} + + + org.mortbay.jetty + jetty + ${mortbay_jetty_version} + true + + + javax.validation + validation-api + ${validation_version} + + + org.hibernate + hibernate-validator + ${hibernate_validator_version} + + + org.glassfish + javax.el + ${jel_version} + + + jakarta.validation + jakarta.validation-api + ${validation_new_version} + + + org.hibernate.validator + hibernate-validator + ${hibernate_validator_new_version} + + + javax.cache + cache-api + ${jcache_version} + + + com.esotericsoftware + kryo + ${kryo_version} + + + de.javakaffee + kryo-serializers + ${kryo_serializers_version} + + + de.ruedigermoeller + fst + ${fst_version} + + + org.apache.avro + avro + ${avro_version} + + + io.protostuff + protostuff-core + ${protostuff_version} + + + io.protostuff + protostuff-runtime + ${protostuff_version} + + + javax.ws.rs + javax.ws.rs-api + ${rs_api_version} + + + org.jboss.resteasy + resteasy-jaxrs + ${resteasy_version} + + + org.jboss.resteasy + resteasy-client + ${resteasy_version} + + + org.jboss.resteasy + resteasy-netty4 + ${resteasy_version} + + + io.netty + netty-all + + + + + org.jboss.resteasy + resteasy-jdk-http + ${resteasy_version} + + + org.jboss.resteasy + resteasy-jackson-provider + ${resteasy_version} + + + org.codehaus.jackson + jackson-core-asl + ${codehaus-jackson_version} + + + org.codehaus.jackson + jackson-mapper-asl + ${codehaus-jackson_version} + + + org.codehaus.jackson + jackson-jaxrs + ${codehaus-jackson_version} + + + org.codehaus.jackson + jackson-xc + ${codehaus-jackson_version} + + + org.jboss.resteasy + resteasy-jaxb-provider + ${resteasy_version} + + + org.apache.tomcat.embed + tomcat-embed-core + ${tomcat_embed_version} + + + io.etcd + jetcd-core + ${jetcd_version} + + + io.netty + netty-codec-http2 + + + io.netty + netty-handler-proxy + + + + + + org.slf4j + slf4j-api + ${slf4j_version} + + + org.slf4j + slf4j-log4j12 + ${slf4j-log4j12_version} + + + commons-logging + commons-logging + ${jcl_version} + + + commons-io + commons-io + ${commons_io_version} + + + commons-codec + commons-codec + ${commons-codec_version} + + + log4j + log4j + ${log4j_version} + + + ch.qos.logback + logback-classic + ${logback_version} + + + org.apache.logging.log4j + log4j-api + ${log4j2_version} + + + org.apache.logging.log4j + log4j-core + ${log4j2_version} + + + com.ctrip.framework.apollo + apollo-client + ${apollo_client_version} + + + org.apache.curator + curator-recipes + ${curator_version} + + + org.apache.zookeeper + zookeeper + + + + + org.yaml + snakeyaml + ${snakeyaml_version} + + + org.apache.commons + commons-lang3 + ${commons_lang3_version} + + + io.envoyproxy.controlplane + api + ${envoy_api_version} + - - com.squareup.okhttp3 - okhttp - ${okhttp_version} - - - com.squareup.okhttp3 - mockwebserver - ${okhttp_version} - + + + javax.xml.bind + jaxb-api + ${jaxb_version} + + + com.sun.xml.bind + jaxb-impl + ${jaxb_version} + + + com.sun.xml.bind + jaxb-core + ${jaxb_version} + + + javax.activation + javax.activation-api + ${activation_version} + + + com.sun.activation + javax.activation + ${activation_version} + - - org.eclipse.jetty - jetty-server - ${jetty_version} - - - org.eclipse.jetty - jetty-servlet - ${jetty_version} - - - org.mortbay.jetty - jetty - ${mortbay_jetty_version} - true - - - javax.validation - validation-api - ${validation_version} - - - org.hibernate - hibernate-validator - ${hibernate_validator_version} - - - org.glassfish - javax.el - ${jel_version} - - - jakarta.validation - jakarta.validation-api - ${validation_new_version} - - - org.hibernate.validator - hibernate-validator - ${hibernate_validator_new_version} - - - javax.cache - cache-api - ${jcache_version} - - - com.esotericsoftware - kryo - ${kryo_version} - - - de.javakaffee - kryo-serializers - ${kryo_serializers_version} - - - de.ruedigermoeller - fst - ${fst_version} - - - org.apache.avro - avro - ${avro_version} - - - io.protostuff - protostuff-core - ${protostuff_version} - - - io.protostuff - protostuff-runtime - ${protostuff_version} - - - javax.ws.rs - javax.ws.rs-api - ${rs_api_version} - - - org.jboss.resteasy - resteasy-jaxrs - ${resteasy_version} - - - org.jboss.resteasy - resteasy-client - ${resteasy_version} - - - org.jboss.resteasy - resteasy-netty4 - ${resteasy_version} - - - io.netty - netty-all - - - - - org.jboss.resteasy - resteasy-jdk-http - ${resteasy_version} - - - org.jboss.resteasy - resteasy-jackson-provider - ${resteasy_version} - - - org.codehaus.jackson - jackson-core-asl - ${codehaus-jackson_version} - - - org.codehaus.jackson - jackson-mapper-asl - ${codehaus-jackson_version} - - - org.codehaus.jackson - jackson-jaxrs - ${codehaus-jackson_version} - - - org.codehaus.jackson - jackson-xc - ${codehaus-jackson_version} - - - org.jboss.resteasy - resteasy-jaxb-provider - ${resteasy_version} - - - org.apache.tomcat.embed - tomcat-embed-core - ${tomcat_embed_version} - - - io.etcd - jetcd-core - ${jetcd_version} - - - io.netty - netty-codec-http2 - - - io.netty - netty-handler-proxy - - - - - - org.slf4j - slf4j-api - ${slf4j_version} - - - org.slf4j - slf4j-log4j12 - ${slf4j-log4j12_version} - - - commons-logging - commons-logging - ${jcl_version} - - - commons-io - commons-io - ${commons_io_version} - - - commons-codec - commons-codec - ${commons-codec_version} - - - log4j - log4j - ${log4j_version} - - - ch.qos.logback - logback-classic - ${logback_version} - - - org.apache.logging.log4j - log4j-api - ${log4j2_version} - - - org.apache.logging.log4j - log4j-core - ${log4j2_version} - - - com.ctrip.framework.apollo - apollo-client - ${apollo_client_version} - - - org.apache.curator - curator-recipes - ${curator_version} - - - org.apache.zookeeper - zookeeper - - - - - org.yaml - snakeyaml - ${snakeyaml_version} - - - org.apache.commons - commons-lang3 - ${commons_lang3_version} - - - io.envoyproxy.controlplane - api - ${envoy_api_version} - + + + io.swagger + swagger-annotations + ${swagger_version} + + + io.swagger + swagger-jaxrs + ${swagger_version} + - - - javax.xml.bind - jaxb-api - ${jaxb_version} - - - com.sun.xml.bind - jaxb-impl - ${jaxb_version} - - - com.sun.xml.bind - jaxb-core - ${jaxb_version} - - - javax.activation - javax.activation-api - ${activation_version} - - - com.sun.activation - javax.activation - ${activation_version} - + + com.alibaba.middleware + metrics-core-api + ${metrics_version} + + + com.alibaba.middleware + metrics-core-impl + ${metrics_version} + + + com.alibaba.middleware + metrics-common + ${metrics_version} + - - - io.swagger - swagger-annotations - ${swagger_version} - - - io.swagger - swagger-jaxrs - ${swagger_version} - + + com.alibaba.middleware + metrics-rest + ${metrics_version} + - - com.alibaba.middleware - metrics-core-api - ${metrics_version} - - - com.alibaba.middleware - metrics-core-impl - ${metrics_version} - - - com.alibaba.middleware - metrics-common - ${metrics_version} - + + + com.alipay.sofa + registry-client-all + ${sofa_registry_version} + + + com.alipay.sofa + registry-test + ${sofa_registry_version} + test + - - com.alibaba.middleware - metrics-rest - ${metrics_version} - + + + org.junit.jupiter + junit-jupiter-engine + ${junit_jupiter_version} + test + + + org.junit.jupiter + junit-jupiter-api + ${junit_jupiter_version} + test + + + org.junit.jupiter + junit-jupiter-params + ${junit_jupiter_version} + test + + + org.junit.vintage + junit-vintage-engine + ${junit_jupiter_version} + test + + + org.awaitility + awaitility + ${awaitility_version} + test + + + org.hamcrest + hamcrest + ${hamcrest_version} + test + + + org.mockito + mockito-core + ${mockito_version} + test + + + org.mockito + mockito-inline + ${mockito_version} + test + + + cglib + cglib-nodep + ${cglib_version} + test + + + com.github.codemonstur + embedded-redis + ${embedded_redis_version} + test + + + org.springframework + spring-test + ${spring_version} + test + - - - com.alipay.sofa - registry-client-all - ${sofa_registry_version} - - - com.alipay.sofa - registry-test - ${sofa_registry_version} - test - + + com.google.code.gson + gson + ${gson_version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson_version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson_version} + + + com.fasterxml.jackson.core + jackson-core + ${jackson_version} + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson_version} + + + javax.portlet + portlet-api + ${portlet_version} + + + + io.etcd + jetcd-launcher + ${etcd_launcher_version} + + + com.github.spotbugs + spotbugs-annotations + + + + + org.testcontainers + testcontainers + ${test_container_version} + + + com.alibaba.nacos + nacos-client + ${nacos_version} + + + + com.alibaba.csp + sentinel-apache-dubbo3-adapter + ${sentinel.version} + + + com.alibaba.csp + sentinel-transport-simple-http + ${sentinel.version} + + + + io.seata + seata-spring-boot-starter + ${seata.version} + + + io.seata + seata-core + + + + + io.seata + seata-core + ${seata.version} + + + + io.grpc + grpc-core + ${grpc.version} + + + io.grpc + grpc-netty-shaded + ${grpc.version} + + + io.grpc + grpc-netty + ${grpc.version} + + + io.grpc + grpc-protobuf + ${grpc.version} + + + io.grpc + grpc-stub + ${grpc.version} + + + io.grpc + grpc-grpclb + ${grpc.version} + + + io.grpc + grpc-context + ${grpc.version} + + + com.salesforce.servicelibs + grpc-contrib + ${grpc_contrib_verdion} + + + com.salesforce.servicelibs + jprotoc + ${jprotoc_version} + + + com.github.spullara.mustache.java + compiler + ${mustache_version} + + + io.fabric8 + kubernetes-client + ${fabric8_kubernetes_version} + + + io.fabric8 + kubernetes-server-mock + ${fabric8_kubernetes_version} + test + + + + org.apache.commons + commons-compress + ${commons_compress_version} + + + org.xerial.snappy + snappy-java + ${snappy_java_version} + true + + + + com.tdunning + t-digest + ${t_digest.version} + + + io.prometheus + simpleclient + ${prometheus_client.version} + + + io.prometheus + simpleclient_pushgateway + ${prometheus_client.version} + + + + org.reactivestreams + reactive-streams + ${reactive.version} + + + io.projectreactor + reactor-core + ${reactor.version} + + + io.reactivex.rxjava2 + rxjava + ${rxjava.version} + + + org.springframework.cloud + spring-cloud-openfeign-core + ${open_feign_version} + + + - - - org.junit.jupiter - junit-jupiter-engine - ${junit_jupiter_version} - test - - - org.junit.jupiter - junit-jupiter-api - ${junit_jupiter_version} - test - - - org.junit.jupiter - junit-jupiter-params - ${junit_jupiter_version} - test - - - org.junit.vintage - junit-vintage-engine - ${junit_jupiter_version} - test - - - org.awaitility - awaitility - ${awaitility_version} - test - - - org.hamcrest - hamcrest - ${hamcrest_version} - test - - - org.mockito - mockito-core - ${mockito_version} - test - - - org.mockito - mockito-inline - ${mockito_version} - test - - - cglib - cglib-nodep - ${cglib_version} - test - - - com.github.codemonstur - embedded-redis - ${embedded_redis_version} - test - - - org.springframework - spring-test - ${spring_version} - test - + + + + org.codehaus.mojo + flatten-maven-plugin + ${maven_flatten_version} + + true + bom + + expand + remove + remove + remove + + + + + flatten + + flatten + + process-resources + + + flatten.clean + + clean + + clean + + + + + - - com.google.code.gson - gson - ${gson_version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson_version} - - - com.fasterxml.jackson.core - jackson-annotations - ${jackson_version} - - - com.fasterxml.jackson.core - jackson-core - ${jackson_version} - - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - ${jackson_version} - - - javax.portlet - portlet-api - ${portlet_version} - - - - io.etcd - jetcd-launcher - ${etcd_launcher_version} - - - com.github.spotbugs - spotbugs-annotations - - - - - org.testcontainers - testcontainers - ${test_container_version} - - - com.alibaba.nacos - nacos-client - ${nacos_version} - - - - com.alibaba.csp - sentinel-apache-dubbo3-adapter - ${sentinel.version} - - - com.alibaba.csp - sentinel-transport-simple-http - ${sentinel.version} - - - - io.seata - seata-spring-boot-starter - ${seata.version} - - - io.seata - seata-core - - - - - io.seata - seata-core - ${seata.version} - - - - io.grpc - grpc-core - ${grpc.version} - - - io.grpc - grpc-netty-shaded - ${grpc.version} - - - io.grpc - grpc-netty - ${grpc.version} - - - io.grpc - grpc-protobuf - ${grpc.version} - - - io.grpc - grpc-stub - ${grpc.version} - - - io.grpc - grpc-grpclb - ${grpc.version} - - - io.grpc - grpc-context - ${grpc.version} - - - com.salesforce.servicelibs - grpc-contrib - ${grpc_contrib_verdion} - - - com.salesforce.servicelibs - jprotoc - ${jprotoc_version} - - - com.github.spullara.mustache.java - compiler - ${mustache_version} - - - io.fabric8 - kubernetes-client - ${fabric8_kubernetes_version} - - - io.fabric8 - kubernetes-server-mock - test - ${fabric8_kubernetes_version} - - - - org.apache.commons - commons-compress - ${commons_compress_version} - - - org.xerial.snappy - snappy-java - ${snappy_java_version} - true - - - - com.tdunning - t-digest - ${t_digest.version} - - - io.prometheus - simpleclient - ${prometheus_client.version} - - - io.prometheus - simpleclient_pushgateway - ${prometheus_client.version} - - - - org.reactivestreams - reactive-streams - ${reactive.version} - - - io.projectreactor - reactor-core - ${reactor.version} - - - io.reactivex.rxjava2 - rxjava - ${rxjava.version} - - - org.springframework.cloud - spring-cloud-openfeign-core - ${open_feign_version} - - - - - + + + release + - - org.codehaus.mojo - flatten-maven-plugin - ${maven_flatten_version} - - true - bom - - expand - remove - remove - remove - - - - - flatten - process-resources - - flatten - - - - flatten.clean - clean - - clean - - - - + + org.apache.maven.plugins + maven-gpg-plugin + + + + sign + + verify + + + - - - - - release - - - - org.apache.maven.plugins - maven-gpg-plugin - - - verify - - sign - - - - - - - - - java11+ - - [11,) - - - - - - com.diffplug.spotless - spotless-maven-plugin - ${spotless-maven-plugin.version} - - - - - - dubbo-importorder.txt - - - checkstyle-header.txt - - - - - false - true - - - - true - - - - - com.alibaba - dubbo-shared-resources - ${dubbo-shared-resources.version} - - - - - - ${spotless.action} - - process-sources - - - - - - - + + + + java11+ + + [11,) + + + + + + com.diffplug.spotless + spotless-maven-plugin + ${spotless-maven-plugin.version} + + + + ${palantirJavaFormat.version} + + + + dubbo-importorder.txt + + + checkstyle-header.txt + + + + + false + true + + + + true + + + + + com.alibaba + dubbo-shared-resources + ${dubbo-shared-resources.version} + + + + + + ${spotless.action} + + process-sources + + + + + + + diff --git a/dubbo-dependencies/dubbo-dependencies-zookeeper-curator5/pom.xml b/dubbo-dependencies/dubbo-dependencies-zookeeper-curator5/pom.xml index 26a1f14b99..12e64cfaa8 100644 --- a/dubbo-dependencies/dubbo-dependencies-zookeeper-curator5/pom.xml +++ b/dubbo-dependencies/dubbo-dependencies-zookeeper-curator5/pom.xml @@ -15,204 +15,206 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - - 4.0.0 + 4.0.0 - - org.apache - apache - 27 - - + + org.apache + apache + 27 + + - org.apache.dubbo - dubbo-dependencies-zookeeper-curator5 - ${revision} - pom + org.apache.dubbo + dubbo-dependencies-zookeeper-curator5 + ${revision} + pom - - 3.3.0-beta.2-SNAPSHOT - 1.5.0 - 1.7.36 - 5.1.0 - 3.8.1 - 2.40.0 - check - 1.0.0 - - - - - - org.apache.zookeeper - parent - ${zookeeper_version} - pom - import - - - + + 3.3.0-beta.2-SNAPSHOT + 1.5.0 + 1.7.36 + 5.1.0 + 3.8.1 + 2.40.0 + check + 1.0.0 + 2.38.0 + + - - org.apache.curator - curator-x-discovery - ${curator5_version} - - - zookeeper - org.apache.zookeeper - - - slf4j-api - org.slf4j - - - listenablefuture - com.google.guava - - - - - org.apache.zookeeper - zookeeper - ${zookeeper_version} - - - logback-classic - ch.qos.logback - - - logback-core - ch.qos.logback - - - audience-annotations - org.apache.yetus - - - * - io.netty - - - slf4j-api - org.slf4j - - - commons-io - commons-io - - - - - org.slf4j - slf4j-api - ${slf4j_version} - + + org.apache.zookeeper + parent + ${zookeeper_version} + pom + import + + - + + + org.apache.curator + curator-x-discovery + ${curator5_version} + + + org.apache.zookeeper + zookeeper + + + org.slf4j + slf4j-api + + + com.google.guava + listenablefuture + + + + + org.apache.zookeeper + zookeeper + ${zookeeper_version} + + + ch.qos.logback + logback-classic + + + ch.qos.logback + logback-core + + + org.apache.yetus + audience-annotations + + + io.netty + * + + + org.slf4j + slf4j-api + + + commons-io + commons-io + + + + + org.slf4j + slf4j-api + ${slf4j_version} + + + + + + + org.codehaus.mojo + flatten-maven-plugin + ${maven_flatten_version} + + true + oss + + + + flatten + + flatten + + process-resources + + + flatten.clean + + clean + + clean + + + + + + + + + release + - - org.codehaus.mojo - flatten-maven-plugin - ${maven_flatten_version} - - true - oss - - - - flatten - process-resources - - flatten - - - - flatten.clean - clean - - clean - - - - + + org.apache.maven.plugins + maven-gpg-plugin + + + + sign + + verify + + + - - - - - release - - - - org.apache.maven.plugins - maven-gpg-plugin - - - verify - - sign - - - - - - - - - java11+ - - [11,) - - - - - - com.diffplug.spotless - spotless-maven-plugin - ${spotless-maven-plugin.version} - - - - - - dubbo-importorder.txt - - - checkstyle-header.txt - - - - - false - true - - - - true - - - - - com.alibaba - dubbo-shared-resources - ${dubbo-shared-resources.version} - - - - - - ${spotless.action} - - process-sources - - - - - - - + + + + java11+ + + [11,) + + + + + + com.diffplug.spotless + spotless-maven-plugin + ${spotless-maven-plugin.version} + + + + ${palantirJavaFormat.version} + + + + dubbo-importorder.txt + + + checkstyle-header.txt + + + + + false + true + + + + true + + + + + com.alibaba + dubbo-shared-resources + ${dubbo-shared-resources.version} + + + + + + ${spotless.action} + + process-sources + + + + + + + diff --git a/dubbo-dependencies/dubbo-dependencies-zookeeper/pom.xml b/dubbo-dependencies/dubbo-dependencies-zookeeper/pom.xml index 0098240f2a..cca065cfd5 100644 --- a/dubbo-dependencies/dubbo-dependencies-zookeeper/pom.xml +++ b/dubbo-dependencies/dubbo-dependencies-zookeeper/pom.xml @@ -15,196 +15,198 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - - 4.0.0 + 4.0.0 - - org.apache - apache - 27 - - + + org.apache + apache + 27 + + - org.apache.dubbo - dubbo-dependencies-zookeeper - ${revision} - pom + org.apache.dubbo + dubbo-dependencies-zookeeper + ${revision} + pom - - 3.3.0-beta.2-SNAPSHOT - 1.5.0 - 1.7.36 - 4.3.0 - 3.4.14 - 2.40.0 - check - 1.0.0 - + + 3.3.0-beta.2-SNAPSHOT + 1.5.0 + 1.7.36 + 4.3.0 + 3.4.14 + 2.40.0 + check + 1.0.0 + 2.38.0 + - - - org.apache.curator - curator-x-discovery - ${curator_version} - - - zookeeper - org.apache.zookeeper - - - slf4j-api - org.slf4j - - - listenablefuture - com.google.guava - - - - - org.apache.zookeeper - zookeeper - ${zookeeper_version} - - - slf4j-log4j12 - org.slf4j - - - log4j - log4j - - - spotbugs-annotations - com.github.spotbugs - - - audience-annotations - org.apache.yetus - - - jline - jline - - - * - io.netty - - - slf4j-api - org.slf4j - - - - - org.slf4j - slf4j-api - ${slf4j_version} - - + + + org.apache.curator + curator-x-discovery + ${curator_version} + + + org.apache.zookeeper + zookeeper + + + org.slf4j + slf4j-api + + + com.google.guava + listenablefuture + + + + + org.apache.zookeeper + zookeeper + ${zookeeper_version} + + + org.slf4j + slf4j-log4j12 + + + log4j + log4j + + + com.github.spotbugs + spotbugs-annotations + + + org.apache.yetus + audience-annotations + + + jline + jline + + + io.netty + * + + + org.slf4j + slf4j-api + + + + + org.slf4j + slf4j-api + ${slf4j_version} + + - + + + + org.codehaus.mojo + flatten-maven-plugin + ${maven_flatten_version} + + true + oss + + + + flatten + + flatten + + process-resources + + + flatten.clean + + clean + + clean + + + + + + + + + release + - - org.codehaus.mojo - flatten-maven-plugin - ${maven_flatten_version} - - true - oss - - - - flatten - process-resources - - flatten - - - - flatten.clean - clean - - clean - - - - + + org.apache.maven.plugins + maven-gpg-plugin + + + + sign + + verify + + + - - - - - release - - - - org.apache.maven.plugins - maven-gpg-plugin - - - verify - - sign - - - - - - - - - java11+ - - [11,) - - - - - - com.diffplug.spotless - spotless-maven-plugin - ${spotless-maven-plugin.version} - - - - - - dubbo-importorder.txt - - - checkstyle-header.txt - - - - - false - true - - - - true - - - - - com.alibaba - dubbo-shared-resources - ${dubbo-shared-resources.version} - - - - - - ${spotless.action} - - process-sources - - - - - - - + + + + java11+ + + [11,) + + + + + + com.diffplug.spotless + spotless-maven-plugin + ${spotless-maven-plugin.version} + + + + ${palantirJavaFormat.version} + + + + dubbo-importorder.txt + + + checkstyle-header.txt + + + + + false + true + + + + true + + + + + com.alibaba + dubbo-shared-resources + ${dubbo-shared-resources.version} + + + + + + ${spotless.action} + + process-sources + + + + + + + diff --git a/dubbo-dependencies/pom.xml b/dubbo-dependencies/pom.xml index 9aee5b19e7..441adfdb68 100644 --- a/dubbo-dependencies/pom.xml +++ b/dubbo-dependencies/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-parent - ${revision} - ../pom.xml - - 4.0.0 + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + - dubbo-dependencies - pom - - dubbo-dependencies-zookeeper - dubbo-dependencies-zookeeper-curator5 - + dubbo-dependencies + pom + + dubbo-dependencies-zookeeper + dubbo-dependencies-zookeeper-curator5 + - - 2.40.0 - check - 1.0.0 - + + 2.40.0 + check + 1.0.0 + 2.38.0 + - + + + + org.codehaus.mojo + flatten-maven-plugin + ${maven_flatten_version} + + true + bom + + + + flatten + + flatten + + process-resources + + + flatten.clean + + clean + + clean + + + + + + + + + java11+ + + [11,) + + + - - org.codehaus.mojo - flatten-maven-plugin - ${maven_flatten_version} - - true - bom - - - - flatten - process-resources - - flatten - - - - flatten.clean - clean - - clean - - - - + + com.diffplug.spotless + spotless-maven-plugin + ${spotless-maven-plugin.version} + + + + ${palantirJavaFormat.version} + + + + dubbo-importorder.txt + + + checkstyle-header.txt + + + + + false + true + + + + true + + + + + com.alibaba + dubbo-shared-resources + ${dubbo-shared-resources.version} + + + + + + ${spotless.action} + + process-sources + + + - - - - - java11+ - - [11,) - - - - - - com.diffplug.spotless - spotless-maven-plugin - ${spotless-maven-plugin.version} - - - - - - dubbo-importorder.txt - - - checkstyle-header.txt - - - - - false - true - - - - true - - - - - com.alibaba - dubbo-shared-resources - ${dubbo-shared-resources.version} - - - - - - ${spotless.action} - - process-sources - - - - - - - + + + diff --git a/dubbo-distribution/dubbo-all/pom.xml b/dubbo-distribution/dubbo-all/pom.xml index 744e115887..c22945a203 100644 --- a/dubbo-distribution/dubbo-all/pom.xml +++ b/dubbo-distribution/dubbo-all/pom.xml @@ -1,4 +1,5 @@ - - - 4.0.0 - - org.apache.dubbo - dubbo-parent - ${revision} - ../../pom.xml - - dubbo - jar - dubbo - The all in one project of dubbo - - false - - - - - org.apache.dubbo - dubbo-cluster - ${project.version} - compile - true - + + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../../pom.xml + + dubbo + jar + dubbo + The all in one project of dubbo + + false + + + + + org.apache.dubbo + dubbo-cluster + ${project.version} + compile + true + - - - org.apache.dubbo - dubbo-common - ${project.version} - compile - true - + + + org.apache.dubbo + dubbo-common + ${project.version} + compile + true + - - - org.apache.dubbo - dubbo-compatible - ${project.version} - compile - true - + + + org.apache.dubbo + dubbo-compatible + ${project.version} + compile + true + - - - org.apache.dubbo - dubbo-config-api - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-config-spring - ${project.version} - compile - true - + + + org.apache.dubbo + dubbo-config-api + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-config-spring + ${project.version} + compile + true + - - - org.apache.dubbo - dubbo-configcenter-file - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-configcenter-apollo - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-configcenter-nacos - ${project.version} - compile - true - + + + org.apache.dubbo + dubbo-configcenter-file + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-configcenter-apollo + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-configcenter-nacos + ${project.version} + compile + true + - - - org.apache.dubbo - dubbo-container-api - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-container-spring - ${project.version} - compile - true - + + + org.apache.dubbo + dubbo-container-api + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-container-spring + ${project.version} + compile + true + - - - org.apache.dubbo - dubbo-filter-cache - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-filter-validation - ${project.version} - compile - true - + + + org.apache.dubbo + dubbo-filter-cache + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-filter-validation + ${project.version} + compile + true + - - - org.apache.dubbo - dubbo-kubernetes - ${project.version} - compile - true - + + + org.apache.dubbo + dubbo-kubernetes + ${project.version} + compile + true + - - - org.apache.dubbo - dubbo-metadata-api - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-metadata-rest - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-metadata-report-nacos - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-metadata-report-redis - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-metadata-definition-protobuf - ${project.version} - compile - true - + + + org.apache.dubbo + dubbo-metadata-api + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-metadata-rest + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-metadata-report-nacos + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-metadata-report-redis + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-metadata-definition-protobuf + ${project.version} + compile + true + - - - org.apache.dubbo - dubbo-metrics-event - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-metrics-api - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-metrics-default - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-metrics-registry - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-metrics-prometheus - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-metrics-metadata - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-metrics-config-center - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-metrics-netty - ${project.version} - compile - true - + + + org.apache.dubbo + dubbo-metrics-event + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-metrics-api + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-metrics-default + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-metrics-registry + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-metrics-prometheus + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-metrics-metadata + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-metrics-config-center + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-metrics-netty + ${project.version} + compile + true + - - - org.apache.dubbo - dubbo-tracing - ${project.version} - compile - true - + + + org.apache.dubbo + dubbo-tracing + ${project.version} + compile + true + - - - org.apache.dubbo - dubbo-monitor-api - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-monitor-common - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-monitor-default - ${project.version} - compile - true - + + + org.apache.dubbo + dubbo-monitor-api + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-monitor-common + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-monitor-default + ${project.version} + compile + true + - - - org.apache.dubbo - dubbo-auth - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-qos-api - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-qos - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-security - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-reactive - ${project.version} - compile - true - + + + org.apache.dubbo + dubbo-auth + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-qos-api + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-qos + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-security + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-reactive + ${project.version} + compile + true + - - org.apache.dubbo - dubbo-spring-security - ${project.version} - compile - true - + + org.apache.dubbo + dubbo-spring-security + ${project.version} + compile + true + - - org.apache.dubbo - dubbo-plugin-cluster-mergeable - ${project.version} - compile - true - + + org.apache.dubbo + dubbo-plugin-cluster-mergeable + ${project.version} + compile + true + - - org.apache.dubbo - dubbo-plugin-mock - ${project.version} - compile - true - + + org.apache.dubbo + dubbo-plugin-mock + ${project.version} + compile + true + - - org.apache.dubbo - dubbo-plugin-router-script - ${project.version} - compile - true - + + org.apache.dubbo + dubbo-plugin-router-script + ${project.version} + compile + true + - - org.apache.dubbo - dubbo-plugin-router-mesh - ${project.version} - compile - true - + + org.apache.dubbo + dubbo-plugin-router-mesh + ${project.version} + compile + true + - - org.apache.dubbo - dubbo-plugin-router-condition - ${project.version} - compile - true - + + org.apache.dubbo + dubbo-plugin-router-condition + ${project.version} + compile + true + - - org.apache.dubbo - dubbo-plugin-router-tag - ${project.version} - compile - true - + + org.apache.dubbo + dubbo-plugin-router-tag + ${project.version} + compile + true + - - org.apache.dubbo - dubbo-plugin-loadbalance-adaptive - ${project.version} - compile - true - + + org.apache.dubbo + dubbo-plugin-loadbalance-adaptive + ${project.version} + compile + true + - - org.apache.dubbo - dubbo-plugin-access-log - ${project.version} - compile - true - + + org.apache.dubbo + dubbo-plugin-access-log + ${project.version} + compile + true + - - org.apache.dubbo - dubbo-plugin-tps - ${project.version} - compile - true - + + org.apache.dubbo + dubbo-plugin-tps + ${project.version} + compile + true + - - org.apache.dubbo - dubbo-plugin-token - ${project.version} - compile - true - + + org.apache.dubbo + dubbo-plugin-token + ${project.version} + compile + true + - - org.apache.dubbo - dubbo-plugin-generic-invoke - ${project.version} - compile - true - + + org.apache.dubbo + dubbo-plugin-generic-invoke + ${project.version} + compile + true + - - org.apache.dubbo - dubbo-plugin-context - ${project.version} - compile - true - + + org.apache.dubbo + dubbo-plugin-context + ${project.version} + compile + true + - - org.apache.dubbo - dubbo-plugin-classloader-filter - ${project.version} - compile - true - + + org.apache.dubbo + dubbo-plugin-classloader-filter + ${project.version} + compile + true + - - org.apache.dubbo - dubbo-plugin-proxy-bytebuddy - ${project.version} - compile - true - + + org.apache.dubbo + dubbo-plugin-proxy-bytebuddy + ${project.version} + compile + true + - - org.apache.dubbo - dubbo-plugin-qos-trace - ${project.version} - compile - true - + + org.apache.dubbo + dubbo-plugin-qos-trace + ${project.version} + compile + true + - - - org.apache.dubbo - dubbo-registry-api - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-registry-multicast - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-registry-multiple - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-registry-nacos - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - compile - true - + + + org.apache.dubbo + dubbo-registry-api + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-registry-multicast + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-registry-multiple + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-registry-nacos + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.version} + compile + true + - - - org.apache.dubbo - dubbo-remoting-api - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-remoting-http - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-remoting-http12 - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-remoting-netty - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-remoting-zookeeper-api - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-remoting-zookeeper - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-remoting-zookeeper-curator5 - ${project.version} - compile - true - + + + org.apache.dubbo + dubbo-remoting-api + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-remoting-http + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-remoting-http12 + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-remoting-netty + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-remoting-zookeeper-api + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-remoting-zookeeper + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-remoting-zookeeper-curator5 + ${project.version} + compile + true + - - - org.apache.dubbo - dubbo-rpc-api - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-rpc-injvm - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - compile - true - + + + org.apache.dubbo + dubbo-rpc-api + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-rpc-injvm + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-rpc-rest + ${project.version} + compile + true + - - org.apache.dubbo - dubbo-rpc-triple - ${project.version} - compile - true - + + org.apache.dubbo + dubbo-rpc-triple + ${project.version} + compile + true + - - - org.apache.dubbo - dubbo-serialization-api - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-serialization-jdk - ${project.version} - compile - true - + + + org.apache.dubbo + dubbo-serialization-api + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-serialization-jdk + ${project.version} + compile + true + - - - org.apache.dubbo - dubbo-xds - ${project.version} - compile - true - + + + org.apache.dubbo + dubbo-xds + ${project.version} + compile + true + - - - org.springframework - spring-context - - - com.alibaba.spring - spring-context-support - - - org.javassist - javassist - - - io.netty - netty-all - - - org.yaml - snakeyaml - - - com.alibaba - hessian-lite - - - com.alibaba.fastjson2 - fastjson2 - - - + + + org.springframework + spring-context + + + com.alibaba.spring + spring-context-support + + + org.javassist + javassist + + + io.netty + netty-all + + + org.yaml + snakeyaml + + + com.alibaba + hessian-lite + + + com.alibaba.fastjson2 + fastjson2 + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + + shade + + package + + true + false + + + org.apache.dubbo:dubbo-auth + org.apache.dubbo:dubbo-cluster + org.apache.dubbo:dubbo-common + org.apache.dubbo:dubbo-compatible + org.apache.dubbo:dubbo-config-api + org.apache.dubbo:dubbo-config-spring + org.apache.dubbo:dubbo-configcenter-file + org.apache.dubbo:dubbo-configcenter-apollo + org.apache.dubbo:dubbo-configcenter-nacos + org.apache.dubbo:dubbo-configcenter-zookeeper + org.apache.dubbo:dubbo-container-api + org.apache.dubbo:dubbo-container-spring + org.apache.dubbo:dubbo-filter-cache + org.apache.dubbo:dubbo-filter-validation + org.apache.dubbo:dubbo-metadata-api + org.apache.dubbo:dubbo-metadata-rest + org.apache.dubbo:dubbo-metadata-definition-protobuf + org.apache.dubbo:dubbo-metadata-report-nacos + org.apache.dubbo:dubbo-metadata-report-redis + org.apache.dubbo:dubbo-metadata-report-zookeeper + org.apache.dubbo:dubbo-metrics-event + org.apache.dubbo:dubbo-metrics-api + org.apache.dubbo:dubbo-metrics-default + org.apache.dubbo:dubbo-metrics-registry + org.apache.dubbo:dubbo-metrics-metadata + org.apache.dubbo:dubbo-metrics-config-center + org.apache.dubbo:dubbo-metrics-netty + org.apache.dubbo:dubbo-metrics-prometheus + org.apache.dubbo:dubbo-tracing + org.apache.dubbo:dubbo-monitor-api + org.apache.dubbo:dubbo-monitor-common + org.apache.dubbo:dubbo-monitor-default + org.apache.dubbo:dubbo-qos + org.apache.dubbo:dubbo-qos-api + org.apache.dubbo:dubbo-security + org.apache.dubbo:dubbo-reactive + org.apache.dubbo:dubbo-spring-security + org.apache.dubbo:dubbo-plugin-cluster-mergeable + org.apache.dubbo:dubbo-plugin-mock + org.apache.dubbo:dubbo-plugin-router-script + org.apache.dubbo:dubbo-plugin-router-mesh + org.apache.dubbo:dubbo-plugin-router-condition + org.apache.dubbo:dubbo-plugin-router-tag + org.apache.dubbo:dubbo-plugin-loadbalance-adaptive + org.apache.dubbo:dubbo-plugin-access-log + org.apache.dubbo:dubbo-plugin-tps + org.apache.dubbo:dubbo-plugin-token + org.apache.dubbo:dubbo-plugin-generic-invoke + org.apache.dubbo:dubbo-plugin-context + org.apache.dubbo:dubbo-plugin-classloader-filter + org.apache.dubbo:dubbo-plugin-proxy-bytebuddy + org.apache.dubbo:dubbo-plugin-qos-trace + org.apache.dubbo:dubbo-registry-api + org.apache.dubbo:dubbo-registry-multicast + org.apache.dubbo:dubbo-registry-multiple + org.apache.dubbo:dubbo-registry-nacos + org.apache.dubbo:dubbo-registry-zookeeper + org.apache.dubbo:dubbo-remoting-api + org.apache.dubbo:dubbo-remoting-http + org.apache.dubbo:dubbo-remoting-http12 + org.apache.dubbo:dubbo-remoting-netty4 + org.apache.dubbo:dubbo-remoting-netty + org.apache.dubbo:dubbo-remoting-zookeeper-api + org.apache.dubbo:dubbo-remoting-zookeeper + org.apache.dubbo:dubbo-remoting-zookeeper-curator5 + org.apache.dubbo:dubbo-rpc-api + org.apache.dubbo:dubbo-rpc-dubbo + org.apache.dubbo:dubbo-rpc-injvm + org.apache.dubbo:dubbo-rpc-rest + org.apache.dubbo:dubbo-rpc-triple + org.apache.dubbo:dubbo-serialization-api + org.apache.dubbo:dubbo-serialization-hessian2 + org.apache.dubbo:dubbo-serialization-fastjson2 + org.apache.dubbo:dubbo-serialization-jdk + org.apache.dubbo:dubbo-kubernetes + org.apache.dubbo:dubbo-xds + + + + + META-INF/dubbo/internal/com.alibaba.dubbo.common.extension.ExtensionFactory + + + META-INF/dubbo/internal/com.alibaba.dubbo.container.page.PageHandler + + + META-INF/dubbo/internal/org.apache.dubbo.auth.spi.AccessKeyStorage + + + META-INF/dubbo/internal/org.apache.dubbo.auth.spi.Authenticator + + + META-INF/dubbo/internal/org.apache.dubbo.cache.CacheFactory + + + META-INF/dubbo/internal/org.apache.dubbo.common.compiler.Compiler + + + META-INF/dubbo/internal/org.apache.dubbo.common.config.OrderedPropertiesProvider + + + META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory + + + META-INF/dubbo/internal/org.apache.dubbo.common.context.ApplicationExt + + + META-INF/dubbo/internal/org.apache.dubbo.common.context.ModuleExt + + + META-INF/dubbo/internal/org.apache.dubbo.common.convert.Converter + + + META-INF/dubbo/internal/org.apache.dubbo.common.convert.multiple.MultiValueConverter + + + META-INF/dubbo/internal/org.apache.dubbo.common.deploy.ApplicationDeployListener + + + META-INF/dubbo/internal/org.apache.dubbo.common.deploy.ModuleDeployListener + + + META-INF/dubbo/internal/org.apache.dubbo.common.extension.ExtensionFactory + + + META-INF/dubbo/internal/org.apache.dubbo.common.extension.ExtensionInjector + + + META-INF/dubbo/internal/org.apache.dubbo.common.extension.ExtensionLoader + + + META-INF/dubbo/internal/org.apache.dubbo.common.infra.InfraAdapter + + + META-INF/dubbo/internal/org.apache.dubbo.common.lang.ShutdownHookCallback + + + META-INF/dubbo/internal/org.apache.dubbo.common.logger.LoggerAdapter + + + META-INF/dubbo/internal/org.apache.dubbo.common.serialize.MultipleSerialization + + + META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization + + + META-INF/dubbo/internal/org.apache.dubbo.common.status.StatusChecker + + + META-INF/dubbo/internal/org.apache.dubbo.common.status.reporter.FrameworkStatusReporter + + + META-INF/dubbo/internal/org.apache.dubbo.common.store.DataStore + + + META-INF/dubbo/internal/org.apache.dubbo.common.threadpool.ThreadPool + + + META-INF/dubbo/internal/org.apache.dubbo.common.threadpool.manager.ExecutorRepository + + + META-INF/dubbo/internal/org.apache.dubbo.common.url.component.param.DynamicParamSource + + + META-INF/dubbo/internal/org.apache.dubbo.config.ConfigInitializer + + + META-INF/dubbo/internal/org.apache.dubbo.config.ConfigPostProcessor + + + META-INF/dubbo/internal/org.apache.dubbo.config.ServiceListener + + + META-INF/dubbo/internal/org.apache.dubbo.config.bootstrap.DubboBootstrapStartStopListener + + + META-INF/dubbo/internal/org.apache.dubbo.config.spring.context.DubboSpringInitCustomizer + + + META-INF/dubbo/internal/org.apache.dubbo.config.spring.extension.SpringExtensionInjector + + + META-INF/dubbo/internal/org.apache.dubbo.container.Container + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.MetadataParamsFilter + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.ServiceNameMapping + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.builder.TypeBuilder + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.rest.ServiceRestMetadataResolver + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.definition.builder.TypeBuilder + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.ServiceRestMetadataReader + + + META-INF/dubbo/internal/org.apache.dubbo.monitor.MonitorFactory + + + META-INF/dubbo/internal/org.apache.dubbo.qos.api.BaseCommand + + + META-INF/dubbo/internal/org.apache.dubbo.qos.probe.LivenessProbe + + + META-INF/dubbo/internal/org.apache.dubbo.qos.probe.ReadinessProbe + + + META-INF/dubbo/internal/org.apache.dubbo.qos.probe.StartupProbe + + + META-INF/dubbo/internal/org.apache.dubbo.qos.permission.PermissionChecker + + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.PenetrateAttachmentSelector + + + + META-INF/dubbo/internal/org.apache.dubbo.registry.AddressListener + + + META-INF/dubbo/internal/org.apache.dubbo.registry.ProviderFirstParams + + + META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory + + + META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryServiceListener + + + META-INF/dubbo/internal/org.apache.dubbo.registry.client.RegistryClusterIdentifier + + + META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscoveryFactory + + + META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceInstanceCustomizer + + + META-INF/dubbo/internal/org.apache.dubbo.registry.client.metadata.MetadataServiceURLBuilder + + + META-INF/dubbo/internal/org.apache.dubbo.common.ssl.CertProvider + + + META-INF/dubbo/internal/org.apache.dubbo.registry.client.migration.MigrationAddressComparator + + + META-INF/dubbo/internal/org.apache.dubbo.registry.client.migration.PreMigratingConditionChecker + + + META-INF/dubbo/internal/org.apache.dubbo.registry.integration.RegistryProtocolListener + + + META-INF/dubbo/internal/org.apache.dubbo.registry.xds.XdsCertificateSigner + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.filter.RestResponseInterceptor + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.filter.RestRequestFilter + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.filter.RestResponseFilter + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.NoAnnotatedParameterRequestTagProcessor + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodec + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer.BaseConsumerParamParser + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.http.factory.RestClientFactory + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.ChannelHandler + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.Codec + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.Codec2 + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.Dispatcher + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.Transporter + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.dubbo.ByteAccessor + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.api.pu.PortUnificationTransporter + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.api.connection.ConnectionManager + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.api.WireProtocol + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.exchange.Exchanger + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.http.HttpBinder + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.http12.message.HttpMessageCodec + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.http12.message.HttpMessageCodecFactory + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.http12.h2.Http2ServerTransportListenerFactory + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.http12.h1.Http1ServerTransportListenerFactory + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.telnet.TelnetHandler + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.ExporterListener + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.HeaderFilter + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.InvokerListener + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.PenetrateAttachmentSelector + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.ProxyFactory + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.ZoneDetector + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.Cluster + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.ConfiguratorFactory + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.LoadBalance + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.Merger + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.ProviderURLMergeProcessor + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.RouterFactory + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.RuleConverter + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.FilterChainBuilder + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.InvocationInterceptorBuilder + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.governance.GovernanceRuleRepository + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.interceptor.ClusterInterceptor + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.router.mesh.route.MeshEnvListenerFactory + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.router.condition.matcher.pattern.ValuePattern + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.router.condition.matcher.ConditionMatcherFactory + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ApplicationInitListener + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.model.BuiltinServiceDetector + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.injvm.ParamDeepCopyUtil + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.PathResolver + + + META-INF/dubbo/internal/org.apache.dubbo.validation.Validation + + + META-INF/dubbo/internal/org.apache.dubbo.registry.client.metadata.ServiceInstanceNotificationCustomizer + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.tri.compressor.Compressor + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.tri.compressor.DeCompressor + + + META-INF/dubbo/internal/org.apache.dubbo.metrics.service.MetricsService + + + META-INF/dubbo/internal/org.apache.dubbo.metrics.service.MetricsServiceExporter + + + META-INF/dubbo/internal/org.apache.dubbo.metrics.report.MetricsReporterFactory + + + META-INF/dubbo/internal/org.apache.dubbo.common.threadpool.event.ThreadPoolExhaustedListener + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.api.pu.PortUnificationTransporter + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.ServiceRestMetadataResolver + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.executor.IsolationExecutorSupportFactory + + + META-INF/dubbo/internal/org.apache.dubbo.metrics.collector.MetricsCollector + + + + META-INF/dubbo/internal/org.apache.dubbo.spring.security.jackson.ObjectMapperCodecCustomer + + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider.BaseProviderParamParser + + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.model.PackableMethodFactory + + + META-INF/dubbo/internal/org.apache.dubbo.aot.api.ReflectionTypeDescriberRegistrar + + + + META-INF/dubbo/internal/org.apache.dubbo.aot.api.ProxyDescriberRegistrar + + + + META-INF/dubbo/internal/org.apache.dubbo.aot.api.ResourceDescriberRegistrar + + + + META-INF/dubbo/internal/org.apache.dubbo.common.json.JsonUtil + + + + META-INF/dubbo/internal/org.apache.dubbo.config.CommonConfigPostProcessor + + + + + org.apache.dubbo:dubbo + + + com/** + org/** + + META-INF/dubbo/** + + + + + + + + + + + + + release + - - org.apache.maven.plugins - maven-shade-plugin - - - package - - shade - - - true - false - - - org.apache.dubbo:dubbo-auth - org.apache.dubbo:dubbo-cluster - org.apache.dubbo:dubbo-common - org.apache.dubbo:dubbo-compatible - org.apache.dubbo:dubbo-config-api - org.apache.dubbo:dubbo-config-spring - org.apache.dubbo:dubbo-configcenter-file - org.apache.dubbo:dubbo-configcenter-apollo - org.apache.dubbo:dubbo-configcenter-nacos - org.apache.dubbo:dubbo-configcenter-zookeeper - org.apache.dubbo:dubbo-container-api - org.apache.dubbo:dubbo-container-spring - org.apache.dubbo:dubbo-filter-cache - org.apache.dubbo:dubbo-filter-validation - org.apache.dubbo:dubbo-metadata-api - org.apache.dubbo:dubbo-metadata-rest - org.apache.dubbo:dubbo-metadata-definition-protobuf - org.apache.dubbo:dubbo-metadata-report-nacos - org.apache.dubbo:dubbo-metadata-report-redis - org.apache.dubbo:dubbo-metadata-report-zookeeper - org.apache.dubbo:dubbo-metrics-event - org.apache.dubbo:dubbo-metrics-api - org.apache.dubbo:dubbo-metrics-default - org.apache.dubbo:dubbo-metrics-registry - org.apache.dubbo:dubbo-metrics-metadata - org.apache.dubbo:dubbo-metrics-config-center - org.apache.dubbo:dubbo-metrics-netty - org.apache.dubbo:dubbo-metrics-prometheus - org.apache.dubbo:dubbo-tracing - org.apache.dubbo:dubbo-monitor-api - org.apache.dubbo:dubbo-monitor-common - org.apache.dubbo:dubbo-monitor-default - org.apache.dubbo:dubbo-qos - org.apache.dubbo:dubbo-qos-api - org.apache.dubbo:dubbo-security - org.apache.dubbo:dubbo-reactive - org.apache.dubbo:dubbo-spring-security - org.apache.dubbo:dubbo-plugin-cluster-mergeable - org.apache.dubbo:dubbo-plugin-mock - org.apache.dubbo:dubbo-plugin-router-script - org.apache.dubbo:dubbo-plugin-router-mesh - org.apache.dubbo:dubbo-plugin-router-condition - org.apache.dubbo:dubbo-plugin-router-tag - org.apache.dubbo:dubbo-plugin-loadbalance-adaptive - org.apache.dubbo:dubbo-plugin-access-log - org.apache.dubbo:dubbo-plugin-tps - org.apache.dubbo:dubbo-plugin-token - org.apache.dubbo:dubbo-plugin-generic-invoke - org.apache.dubbo:dubbo-plugin-context - org.apache.dubbo:dubbo-plugin-classloader-filter - org.apache.dubbo:dubbo-plugin-proxy-bytebuddy - org.apache.dubbo:dubbo-plugin-qos-trace - org.apache.dubbo:dubbo-registry-api - org.apache.dubbo:dubbo-registry-multicast - org.apache.dubbo:dubbo-registry-multiple - org.apache.dubbo:dubbo-registry-nacos - org.apache.dubbo:dubbo-registry-zookeeper - org.apache.dubbo:dubbo-remoting-api - org.apache.dubbo:dubbo-remoting-http - org.apache.dubbo:dubbo-remoting-http12 - org.apache.dubbo:dubbo-remoting-netty4 - org.apache.dubbo:dubbo-remoting-netty - org.apache.dubbo:dubbo-remoting-zookeeper-api - org.apache.dubbo:dubbo-remoting-zookeeper - org.apache.dubbo:dubbo-remoting-zookeeper-curator5 - org.apache.dubbo:dubbo-rpc-api - org.apache.dubbo:dubbo-rpc-dubbo - org.apache.dubbo:dubbo-rpc-injvm - org.apache.dubbo:dubbo-rpc-rest - org.apache.dubbo:dubbo-rpc-triple - org.apache.dubbo:dubbo-serialization-api - org.apache.dubbo:dubbo-serialization-hessian2 - org.apache.dubbo:dubbo-serialization-fastjson2 - org.apache.dubbo:dubbo-serialization-jdk - org.apache.dubbo:dubbo-kubernetes - org.apache.dubbo:dubbo-xds - - - - - - META-INF/dubbo/internal/com.alibaba.dubbo.common.extension.ExtensionFactory - - - - - META-INF/dubbo/internal/com.alibaba.dubbo.container.page.PageHandler - - - - - META-INF/dubbo/internal/org.apache.dubbo.auth.spi.AccessKeyStorage - - - - - META-INF/dubbo/internal/org.apache.dubbo.auth.spi.Authenticator - - - - - META-INF/dubbo/internal/org.apache.dubbo.cache.CacheFactory - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.compiler.Compiler - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.config.OrderedPropertiesProvider - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.context.ApplicationExt - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.context.ModuleExt - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.convert.Converter - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.convert.multiple.MultiValueConverter - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.deploy.ApplicationDeployListener - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.deploy.ModuleDeployListener - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.extension.ExtensionFactory - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.extension.ExtensionInjector - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.extension.ExtensionLoader - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.infra.InfraAdapter - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.lang.ShutdownHookCallback - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.logger.LoggerAdapter - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.serialize.MultipleSerialization - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.status.StatusChecker - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.status.reporter.FrameworkStatusReporter - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.store.DataStore - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.threadpool.ThreadPool - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.threadpool.manager.ExecutorRepository - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.url.component.param.DynamicParamSource - - - - - META-INF/dubbo/internal/org.apache.dubbo.config.ConfigInitializer - - - - - META-INF/dubbo/internal/org.apache.dubbo.config.ConfigPostProcessor - - - - - META-INF/dubbo/internal/org.apache.dubbo.config.ServiceListener - - - - - META-INF/dubbo/internal/org.apache.dubbo.config.bootstrap.DubboBootstrapStartStopListener - - - - - META-INF/dubbo/internal/org.apache.dubbo.config.spring.context.DubboSpringInitCustomizer - - - - - META-INF/dubbo/internal/org.apache.dubbo.config.spring.extension.SpringExtensionInjector - - - - - META-INF/dubbo/internal/org.apache.dubbo.container.Container - - - - - META-INF/dubbo/internal/org.apache.dubbo.metadata.MetadataParamsFilter - - - - - META-INF/dubbo/internal/org.apache.dubbo.metadata.ServiceNameMapping - - - - - META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.builder.TypeBuilder - - - - - META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor - - - - - META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.rest.ServiceRestMetadataResolver - - - - - META-INF/dubbo/internal/org.apache.dubbo.metadata.definition.builder.TypeBuilder - - - - - META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory - - - - - META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor - - - - - META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.ServiceRestMetadataReader - - - - - META-INF/dubbo/internal/org.apache.dubbo.monitor.MonitorFactory - - - - - META-INF/dubbo/internal/org.apache.dubbo.qos.api.BaseCommand - - - - - META-INF/dubbo/internal/org.apache.dubbo.qos.probe.LivenessProbe - - - - - META-INF/dubbo/internal/org.apache.dubbo.qos.probe.ReadinessProbe - - - - - META-INF/dubbo/internal/org.apache.dubbo.qos.probe.StartupProbe - - - - - META-INF/dubbo/internal/org.apache.dubbo.qos.permission.PermissionChecker - - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.PenetrateAttachmentSelector - - - - - - META-INF/dubbo/internal/org.apache.dubbo.registry.AddressListener - - - - - META-INF/dubbo/internal/org.apache.dubbo.registry.ProviderFirstParams - - - - - META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory - - - - - META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryServiceListener - - - - - META-INF/dubbo/internal/org.apache.dubbo.registry.client.RegistryClusterIdentifier - - - - - META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscoveryFactory - - - - - META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceInstanceCustomizer - - - - - META-INF/dubbo/internal/org.apache.dubbo.registry.client.metadata.MetadataServiceURLBuilder - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.ssl.CertProvider - - - - - META-INF/dubbo/internal/org.apache.dubbo.registry.client.migration.MigrationAddressComparator - - - - - META-INF/dubbo/internal/org.apache.dubbo.registry.client.migration.PreMigratingConditionChecker - - - - - META-INF/dubbo/internal/org.apache.dubbo.registry.integration.RegistryProtocolListener - - - - - META-INF/dubbo/internal/org.apache.dubbo.registry.xds.XdsCertificateSigner - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.filter.RestResponseInterceptor - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.filter.RestRequestFilter - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.filter.RestResponseFilter - - - - - META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.NoAnnotatedParameterRequestTagProcessor - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodec - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.annotation.consumer.HttpConnectionPreBuildIntercept - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer.BaseConsumerParamParser - - - - - META-INF/dubbo/internal/org.apache.dubbo.remoting.http.factory.RestClientFactory - - - - - META-INF/dubbo/internal/org.apache.dubbo.remoting.ChannelHandler - - - - - META-INF/dubbo/internal/org.apache.dubbo.remoting.Codec - - - - - META-INF/dubbo/internal/org.apache.dubbo.remoting.Codec2 - - - - - META-INF/dubbo/internal/org.apache.dubbo.remoting.Dispatcher - - - - - META-INF/dubbo/internal/org.apache.dubbo.remoting.Transporter - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.dubbo.ByteAccessor - - - - - META-INF/dubbo/internal/org.apache.dubbo.remoting.api.pu.PortUnificationTransporter - - - - - META-INF/dubbo/internal/org.apache.dubbo.remoting.api.connection.ConnectionManager - - - - - META-INF/dubbo/internal/org.apache.dubbo.remoting.api.WireProtocol - - - - - META-INF/dubbo/internal/org.apache.dubbo.remoting.exchange.Exchanger - - - - - META-INF/dubbo/internal/org.apache.dubbo.remoting.http.HttpBinder - - - - - META-INF/dubbo/internal/org.apache.dubbo.remoting.http12.message.HttpMessageCodec - - - - - META-INF/dubbo/internal/org.apache.dubbo.remoting.http12.message.HttpMessageCodecFactory - - - - - META-INF/dubbo/internal/org.apache.dubbo.remoting.http12.h2.Http2ServerTransportListenerFactory - - - - - META-INF/dubbo/internal/org.apache.dubbo.remoting.http12.h1.Http1ServerTransportListenerFactory - - - - - META-INF/dubbo/internal/org.apache.dubbo.remoting.telnet.TelnetHandler - - - - - META-INF/dubbo/internal/org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.ExporterListener - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.HeaderFilter - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.InvokerListener - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.PenetrateAttachmentSelector - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.ProxyFactory - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.ZoneDetector - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.Cluster - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.ConfiguratorFactory - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.LoadBalance - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.Merger - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.ProviderURLMergeProcessor - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.RouterFactory - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.RuleConverter - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.ClusterFilter - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.FilterChainBuilder - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.filter.InvocationInterceptorBuilder - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.governance.GovernanceRuleRepository - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.interceptor.ClusterInterceptor - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.router.mesh.route.MeshEnvListenerFactory - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.router.condition.matcher.pattern.ValuePattern - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.router.condition.matcher.ConditionMatcherFactory - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ApplicationInitListener - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.model.BuiltinServiceDetector - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.model.ScopeModelInitializer - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.injvm.ParamDeepCopyUtil - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.PathResolver - - - - - META-INF/dubbo/internal/org.apache.dubbo.validation.Validation - - - - - META-INF/dubbo/internal/org.apache.dubbo.registry.client.metadata.ServiceInstanceNotificationCustomizer - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.tri.compressor.Compressor - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.tri.compressor.DeCompressor - - - - - META-INF/dubbo/internal/org.apache.dubbo.metrics.service.MetricsService - - - - - META-INF/dubbo/internal/org.apache.dubbo.metrics.service.MetricsServiceExporter - - - - - META-INF/dubbo/internal/org.apache.dubbo.metrics.report.MetricsReporterFactory - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.threadpool.event.ThreadPoolExhaustedListener - - - - - META-INF/dubbo/internal/org.apache.dubbo.remoting.api.pu.PortUnificationTransporter - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider - - - - - META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.ServiceRestMetadataResolver - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.executor.IsolationExecutorSupportFactory - - - - - META-INF/dubbo/internal/org.apache.dubbo.metrics.collector.MetricsCollector - - - - - - META-INF/dubbo/internal/org.apache.dubbo.spring.security.jackson.ObjectMapperCodecCustomer - - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider.BaseProviderParamParser - - - - - - META-INF/dubbo/internal/org.apache.dubbo.rpc.model.PackableMethodFactory - - - - - META-INF/dubbo/internal/org.apache.dubbo.aot.api.ReflectionTypeDescriberRegistrar - - - - - - META-INF/dubbo/internal/org.apache.dubbo.aot.api.ProxyDescriberRegistrar - - - - - - META-INF/dubbo/internal/org.apache.dubbo.aot.api.ResourceDescriberRegistrar - - - - - - META-INF/dubbo/internal/org.apache.dubbo.common.json.JsonUtil - - - - - - META-INF/dubbo/internal/org.apache.dubbo.config.CommonConfigPostProcessor - - - - - - org.apache.dubbo:dubbo - - - com/** - org/** - - META-INF/dubbo/** - - - - - - - + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven_javadoc_version} + + true + + org.apache.dubbo:dubbo-* + + public + UTF-8 + UTF-8 + UTF-8 + + http://docs.oracle.com/javase/7/docs/api + + + + + attach-javadoc + + jar + + + none + + + + - - - - - release - - - - org.apache.maven.plugins - maven-javadoc-plugin - ${maven_javadoc_version} - - - attach-javadoc - - jar - - - none - - - - - true - - org.apache.dubbo:dubbo-* - - public - UTF-8 - UTF-8 - UTF-8 - - http://docs.oracle.com/javase/7/docs/api - - - - - - - + + + diff --git a/dubbo-distribution/dubbo-bom/pom.xml b/dubbo-distribution/dubbo-bom/pom.xml index fcb99025dc..f22cfcab9c 100644 --- a/dubbo-distribution/dubbo-bom/pom.xml +++ b/dubbo-distribution/dubbo-bom/pom.xml @@ -17,818 +17,818 @@ --> - 4.0.0 + 4.0.0 - + + org.apache.dubbo + dubbo-parent + ${revision} + ../../pom.xml + + + dubbo-bom + pom + + dubbo-bom + + + + + org.apache.dubbo - dubbo-parent - ${revision} - ../../pom.xml - + dubbo-cluster + ${project.version} + - dubbo-bom - pom + + + org.apache.dubbo + dubbo-common + ${project.version} + - dubbo-bom + + + org.apache.dubbo + dubbo-compatible + ${project.version} + - - - - - org.apache.dubbo - dubbo-cluster - ${project.version} - + + + org.apache.dubbo + dubbo-compiler + ${project.version} + - - - org.apache.dubbo - dubbo-common - ${project.version} - + + + org.apache.dubbo + dubbo-config + ${project.version} + pom + + + org.apache.dubbo + dubbo-config-api + ${project.version} + + + org.apache.dubbo + dubbo-config-spring + ${project.version} + - - - org.apache.dubbo - dubbo-compatible - ${project.version} - + + org.apache.dubbo + dubbo-config-spring6 + ${project.version} + - - - org.apache.dubbo - dubbo-compiler - ${project.version} - + + + org.apache.dubbo + dubbo-configcenter + ${project.version} + pom + + + org.apache.dubbo + dubbo-configcenter-file + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-apollo + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-nacos + ${project.version} + - - - org.apache.dubbo - dubbo-config - ${project.version} - pom - - - org.apache.dubbo - dubbo-config-api - ${project.version} - - - org.apache.dubbo - dubbo-config-spring - ${project.version} - + + + org.apache.dubbo + dubbo-container + ${project.version} + pom + + + org.apache.dubbo + dubbo-container-api + ${project.version} + + + org.apache.dubbo + dubbo-container-spring + ${project.version} + - - org.apache.dubbo - dubbo-config-spring6 - ${project.version} - + + + org.apache.dubbo + dubbo-dependencies + ${project.version} + + + org.apache.dubbo + dubbo-dependencies-zookeeper + ${project.version} + pom + + + org.apache.dubbo + dubbo-dependencies-zookeeper-curator5 + ${project.version} + pom + - - - org.apache.dubbo - dubbo-configcenter - ${project.version} - pom - - - org.apache.dubbo - dubbo-configcenter-file - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-apollo - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-nacos - ${project.version} - + + + org.apache.dubbo + dubbo-dependencies-bom + ${project.version} + - - - org.apache.dubbo - dubbo-container - ${project.version} - pom - - - org.apache.dubbo - dubbo-container-api - ${project.version} - - - org.apache.dubbo - dubbo-container-spring - ${project.version} - + + + org.apache.dubbo + dubbo-distribution + ${project.version} + pom + + + org.apache.dubbo + dubbo + ${project.version} + + + org.apache.dubbo + dubbo-bom + ${project.version} + + + org.apache.dubbo + dubbo-all-shaded + ${project.version} + - - - org.apache.dubbo - dubbo-dependencies - ${project.version} - - - org.apache.dubbo - dubbo-dependencies-zookeeper - ${project.version} - pom - - - org.apache.dubbo - dubbo-dependencies-zookeeper-curator5 - ${project.version} - pom - + + + org.apache.dubbo + dubbo-filter + ${project.version} + pom + + + org.apache.dubbo + dubbo-filter-cache + ${project.version} + + + org.apache.dubbo + dubbo-filter-validation + ${project.version} + - - - org.apache.dubbo - dubbo-dependencies-bom - ${project.version} - + + + org.apache.dubbo + dubbo-kubernetes + ${project.version} + - - - org.apache.dubbo - dubbo-distribution - ${project.version} - pom - - - org.apache.dubbo - dubbo - ${project.version} - - - org.apache.dubbo - dubbo-bom - ${project.version} - - - org.apache.dubbo - dubbo-all-shaded - ${project.version} - + + + org.apache.dubbo + dubbo-metadata + ${project.version} + pom + + + org.apache.dubbo + dubbo-metadata-api + ${project.version} + + + org.apache.dubbo + dubbo-metadata-rest + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-nacos + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-redis + ${project.version} + + + org.apache.dubbo + dubbo-metadata-processor + ${project.version} + + + org.apache.dubbo + dubbo-metadata-definition-protobuf + ${project.version} + - - - org.apache.dubbo - dubbo-filter - ${project.version} - pom - - - org.apache.dubbo - dubbo-filter-cache - ${project.version} - - - org.apache.dubbo - dubbo-filter-validation - ${project.version} - + + + org.apache.dubbo + dubbo-metrics + ${project.version} + pom + + + org.apache.dubbo + dubbo-metrics-api + ${project.version} + + + org.apache.dubbo + dubbo-metrics-event + ${project.version} + + + org.apache.dubbo + dubbo-metrics-default + ${project.version} + + + org.apache.dubbo + dubbo-metrics-registry + ${project.version} + + + org.apache.dubbo + dubbo-metrics-prometheus + ${project.version} + + + org.apache.dubbo + dubbo-metrics-metadata + ${project.version} + + + org.apache.dubbo + dubbo-metrics-config-center + ${project.version} + + + org.apache.dubbo + dubbo-metrics-netty + ${project.version} + - - - org.apache.dubbo - dubbo-kubernetes - ${project.version} - + + + org.apache.dubbo + dubbo-tracing + ${project.version} + - - - org.apache.dubbo - dubbo-metadata - ${project.version} - pom - - - org.apache.dubbo - dubbo-metadata-api - ${project.version} - - - org.apache.dubbo - dubbo-metadata-rest - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-nacos - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-redis - ${project.version} - - - org.apache.dubbo - dubbo-metadata-processor - ${project.version} - - - org.apache.dubbo - dubbo-metadata-definition-protobuf - ${project.version} - + + + org.apache.dubbo + dubbo-monitor + ${project.version} + pom + + + org.apache.dubbo + dubbo-monitor-api + ${project.version} + + + org.apache.dubbo + dubbo-monitor-common + ${project.version} + + + org.apache.dubbo + dubbo-monitor-default + ${project.version} + - - - org.apache.dubbo - dubbo-metrics - ${project.version} - pom - - - org.apache.dubbo - dubbo-metrics-api - ${project.version} - - - org.apache.dubbo - dubbo-metrics-event - ${project.version} - - - org.apache.dubbo - dubbo-metrics-default - ${project.version} - - - org.apache.dubbo - dubbo-metrics-registry - ${project.version} - - - org.apache.dubbo - dubbo-metrics-prometheus - ${project.version} - - - org.apache.dubbo - dubbo-metrics-metadata - ${project.version} - - - org.apache.dubbo - dubbo-metrics-config-center - ${project.version} - - - org.apache.dubbo - dubbo-metrics-netty - ${project.version} - + + + org.apache.dubbo + dubbo-native + ${project.version} + - - - org.apache.dubbo - dubbo-tracing - ${project.version} - + + org.apache.dubbo + dubbo-maven-plugin + ${project.version} + - - - org.apache.dubbo - dubbo-monitor - ${project.version} - pom - - - org.apache.dubbo - dubbo-monitor-api - ${project.version} - - - org.apache.dubbo - dubbo-monitor-common - ${project.version} - - - org.apache.dubbo - dubbo-monitor-default - ${project.version} - + + + org.apache.dubbo + dubbo-plugin + ${project.version} + + + org.apache.dubbo + dubbo-auth + ${project.version} + + + org.apache.dubbo + dubbo-security + ${project.version} + + + org.apache.dubbo + dubbo-qos-api + ${project.version} + + + org.apache.dubbo + dubbo-qos + ${project.version} + + + org.apache.dubbo + dubbo-reactive + ${project.version} + - - - org.apache.dubbo - dubbo-native - ${project.version} - + + org.apache.dubbo + dubbo-spring-security + ${project.version} + - - org.apache.dubbo - dubbo-maven-plugin - ${project.version} - + + org.apache.dubbo + dubbo-plugin-cluster-mergeable + ${project.version} + - - - org.apache.dubbo - dubbo-plugin - ${project.version} - - - org.apache.dubbo - dubbo-auth - ${project.version} - - - org.apache.dubbo - dubbo-security - ${project.version} - - - org.apache.dubbo - dubbo-qos-api - ${project.version} - - - org.apache.dubbo - dubbo-qos - ${project.version} - - - org.apache.dubbo - dubbo-reactive - ${project.version} - + + org.apache.dubbo + dubbo-plugin-mock + ${project.version} + - - org.apache.dubbo - dubbo-spring-security - ${project.version} - + + org.apache.dubbo + dubbo-plugin-router-script + ${project.version} + - - org.apache.dubbo - dubbo-plugin-cluster-mergeable - ${project.version} - + + org.apache.dubbo + dubbo-plugin-router-mesh + ${project.version} + - - org.apache.dubbo - dubbo-plugin-mock - ${project.version} - + + org.apache.dubbo + dubbo-plugin-router-condition + ${project.version} + - - org.apache.dubbo - dubbo-plugin-router-script - ${project.version} - + + org.apache.dubbo + dubbo-plugin-router-tag + ${project.version} + - - org.apache.dubbo - dubbo-plugin-router-mesh - ${project.version} - + + org.apache.dubbo + dubbo-plugin-loadbalance-adaptive + ${project.version} + - - org.apache.dubbo - dubbo-plugin-router-condition - ${project.version} - + + org.apache.dubbo + dubbo-plugin-access-log + ${project.version} + - - org.apache.dubbo - dubbo-plugin-router-tag - ${project.version} - + + org.apache.dubbo + dubbo-plugin-tps + ${project.version} + - - org.apache.dubbo - dubbo-plugin-loadbalance-adaptive - ${project.version} - + + org.apache.dubbo + dubbo-plugin-token + ${project.version} + - - org.apache.dubbo - dubbo-plugin-access-log - ${project.version} - + + org.apache.dubbo + dubbo-plugin-generic-invoke + ${project.version} + - - org.apache.dubbo - dubbo-plugin-tps - ${project.version} - + + org.apache.dubbo + dubbo-plugin-context + ${project.version} + - - org.apache.dubbo - dubbo-plugin-token - ${project.version} - + + org.apache.dubbo + dubbo-plugin-classloader-filter + ${project.version} + - - org.apache.dubbo - dubbo-plugin-generic-invoke - ${project.version} - + + org.apache.dubbo + dubbo-plugin-proxy-bytebuddy + ${project.version} + - - org.apache.dubbo - dubbo-plugin-context - ${project.version} - + + org.apache.dubbo + dubbo-plugin-qos-trace + ${project.version} + - - org.apache.dubbo - dubbo-plugin-classloader-filter - ${project.version} - + + + org.apache.dubbo + dubbo-registry + ${project.version} + pom + + + org.apache.dubbo + dubbo-registry-api + ${project.version} + + + org.apache.dubbo + dubbo-registry-multicast + ${project.version} + + + org.apache.dubbo + dubbo-registry-multiple + ${project.version} + + + org.apache.dubbo + dubbo-registry-nacos + ${project.version} + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.version} + - - org.apache.dubbo - dubbo-plugin-proxy-bytebuddy - ${project.version} - + + + org.apache.dubbo + dubbo-remoting + ${project.version} + pom + + + org.apache.dubbo + dubbo-remoting-api + ${project.version} + + + org.apache.dubbo + dubbo-remoting-http + ${project.version} + + + org.apache.dubbo + dubbo-remoting-http12 + ${project.version} + + + org.apache.dubbo + dubbo-remoting-netty + ${project.version} + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + + + org.apache.dubbo + dubbo-remoting-zookeeper-api + ${project.version} + + + org.apache.dubbo + dubbo-remoting-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-remoting-zookeeper-curator5 + ${project.version} + - - org.apache.dubbo - dubbo-plugin-qos-trace - ${project.version} - + + + org.apache.dubbo + dubbo-rpc + ${project.version} + pom + + + org.apache.dubbo + dubbo-rpc-api + ${project.version} + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + + + org.apache.dubbo + dubbo-rpc-injvm + ${project.version} + + + org.apache.dubbo + dubbo-rpc-rest + ${project.version} + - - - org.apache.dubbo - dubbo-registry - ${project.version} - pom - - - org.apache.dubbo - dubbo-registry-api - ${project.version} - - - org.apache.dubbo - dubbo-registry-multicast - ${project.version} - - - org.apache.dubbo - dubbo-registry-multiple - ${project.version} - - - org.apache.dubbo - dubbo-registry-nacos - ${project.version} - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - + + org.apache.dubbo + dubbo-rpc-triple + ${project.version} + - - - org.apache.dubbo - dubbo-remoting - ${project.version} - pom - - - org.apache.dubbo - dubbo-remoting-api - ${project.version} - - - org.apache.dubbo - dubbo-remoting-http - ${project.version} - - - org.apache.dubbo - dubbo-remoting-http12 - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - - - org.apache.dubbo - dubbo-remoting-zookeeper-api - ${project.version} - - - org.apache.dubbo - dubbo-remoting-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-remoting-zookeeper-curator5 - ${project.version} - + + + org.apache.dubbo + dubbo-serialization + ${project.version} + pom + + + org.apache.dubbo + dubbo-serialization-api + ${project.version} + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-jdk + ${project.version} + - - - org.apache.dubbo - dubbo-rpc - ${project.version} - pom - - - org.apache.dubbo - dubbo-rpc-api - ${project.version} - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - - - org.apache.dubbo - dubbo-rpc-injvm - ${project.version} - - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - + + + org.apache.dubbo + dubbo-spring-boot + ${project.version} + pom + + + org.apache.dubbo + dubbo-spring-boot-actuator + ${project.version} + + + org.apache.dubbo + dubbo-spring-boot-autoconfigure + ${project.version} + + + org.apache.dubbo + dubbo-spring-boot-compatible + ${project.version} + pom + + + org.apache.dubbo + dubbo-spring-boot-actuator-compatible + ${project.version} + + + org.apache.dubbo + dubbo-spring-boot-autoconfigure-compatible + ${project.version} + + + org.apache.dubbo + dubbo-spring-boot-configuration-metadata-compatible + ${project.version} + + + org.apache.dubbo + dubbo-spring-boot-starter + ${project.version} + + + org.apache.dubbo + dubbo-spring-boot-interceptor + ${project.version} + + + org.apache.dubbo + dubbo-spring-boot-starters + ${project.version} + pom + + + org.apache.dubbo + dubbo-observability-spring-boot-starters + ${project.version} + pom + + + org.apache.dubbo + dubbo-observability-spring-boot-autoconfigure + ${project.version} + + + org.apache.dubbo + dubbo-tracing-otel-zipkin-spring-boot-starter + ${project.version} + + + org.apache.dubbo + dubbo-tracing-otel-otlp-spring-boot-starter + ${project.version} + + + org.apache.dubbo + dubbo-tracing-brave-zipkin-spring-boot-starter + ${project.version} + + + org.apache.dubbo + dubbo-observability-spring-boot-starter + ${project.version} + + + org.apache.dubbo + dubbo-nacos-spring-boot-starter + ${project.version} + + + org.apache.dubbo + dubbo-zookeeper-spring-boot-starter + ${project.version} + + + org.apache.dubbo + dubbo-zookeeper-curator5-spring-boot-starter + ${project.version} + + + org.apache.dubbo + dubbo-sentinel-spring-boot-starter + ${project.version} + + + org.apache.dubbo + dubbo-seata-spring-boot-starter + ${project.version} + - - org.apache.dubbo - dubbo-rpc-triple - ${project.version} - + + + org.apache.dubbo + dubbo-test + ${project.version} + pom + + + org.apache.dubbo + dubbo-test-check + ${project.version} + + + org.apache.dubbo + dubbo-test-common + ${project.version} + + + org.apache.dubbo + dubbo-test-modules + ${project.version} + + + org.apache.dubbo + dubbo-test-spring + ${project.version} + + + org.apache.dubbo + dubbo-test-spring3.2 + ${project.version} + + + org.apache.dubbo + dubbo-test-spring4.1 + ${project.version} + + + org.apache.dubbo + dubbo-test-spring4.2 + ${project.version} + - - - org.apache.dubbo - dubbo-serialization - ${project.version} - pom - - - org.apache.dubbo - dubbo-serialization-api - ${project.version} - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-jdk - ${project.version} - + + + org.apache.dubbo + dubbo-xds + ${project.version} + + + - - - org.apache.dubbo - dubbo-spring-boot - ${project.version} - pom - - - org.apache.dubbo - dubbo-spring-boot-actuator - ${project.version} - - - org.apache.dubbo - dubbo-spring-boot-autoconfigure - ${project.version} - - - org.apache.dubbo - dubbo-spring-boot-compatible - ${project.version} - pom - - - org.apache.dubbo - dubbo-spring-boot-actuator-compatible - ${project.version} - - - org.apache.dubbo - dubbo-spring-boot-autoconfigure-compatible - ${project.version} - - - org.apache.dubbo - dubbo-spring-boot-configuration-metadata-compatible - ${project.version} - - - org.apache.dubbo - dubbo-spring-boot-starter - ${project.version} - - - org.apache.dubbo - dubbo-spring-boot-interceptor - ${project.version} - - - org.apache.dubbo - dubbo-spring-boot-starters - ${project.version} - pom - - - org.apache.dubbo - dubbo-observability-spring-boot-starters - ${project.version} - pom - - - org.apache.dubbo - dubbo-observability-spring-boot-autoconfigure - ${project.version} - - - org.apache.dubbo - dubbo-tracing-otel-zipkin-spring-boot-starter - ${project.version} - - - org.apache.dubbo - dubbo-tracing-otel-otlp-spring-boot-starter - ${project.version} - - - org.apache.dubbo - dubbo-tracing-brave-zipkin-spring-boot-starter - ${project.version} - - - org.apache.dubbo - dubbo-observability-spring-boot-starter - ${project.version} - - - org.apache.dubbo - dubbo-nacos-spring-boot-starter - ${project.version} - - - org.apache.dubbo - dubbo-zookeeper-spring-boot-starter - ${project.version} - - - org.apache.dubbo - dubbo-zookeeper-curator5-spring-boot-starter - ${project.version} - - - org.apache.dubbo - dubbo-sentinel-spring-boot-starter - ${project.version} - - - org.apache.dubbo - dubbo-seata-spring-boot-starter - ${project.version} - + + + + org.codehaus.mojo + flatten-maven-plugin + ${maven_flatten_version} + + true + bom + + expand + remove + remove + remove + + + + + flatten + + flatten + + process-resources + + + flatten.clean + + clean + + clean + + + + + - - - org.apache.dubbo - dubbo-test - ${project.version} - pom - - - org.apache.dubbo - dubbo-test-check - ${project.version} - - - org.apache.dubbo - dubbo-test-common - ${project.version} - - - org.apache.dubbo - dubbo-test-modules - ${project.version} - - - org.apache.dubbo - dubbo-test-spring - ${project.version} - - - org.apache.dubbo - dubbo-test-spring3.2 - ${project.version} - - - org.apache.dubbo - dubbo-test-spring4.1 - ${project.version} - - - org.apache.dubbo - dubbo-test-spring4.2 - ${project.version} - - - - - org.apache.dubbo - dubbo-xds - ${project.version} - - - - - + + + release + - - org.codehaus.mojo - flatten-maven-plugin - ${maven_flatten_version} - - true - bom - - expand - remove - remove - remove - - - - - flatten - process-resources - - flatten - - - - flatten.clean - clean - - clean - - - - + + org.apache.maven.plugins + maven-gpg-plugin + + + + sign + + verify + + + - - - - - release - - - - org.apache.maven.plugins - maven-gpg-plugin - - - verify - - sign - - - - - - - - + + + diff --git a/dubbo-distribution/pom.xml b/dubbo-distribution/pom.xml index 2327eb98e3..cb85215347 100644 --- a/dubbo-distribution/pom.xml +++ b/dubbo-distribution/pom.xml @@ -1,3 +1,4 @@ + + + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + - - - org.apache.dubbo - dubbo-parent - ${revision} - ../pom.xml - - 4.0.0 + dubbo-distribution + pom - dubbo-distribution - pom - - - 2.40.0 - check - 1.0.0 - - - - - release - - dubbo-all - dubbo-all-shaded - dubbo-apache-release - dubbo-bom - dubbo-core-spi - - - - dubbo-all - - true - - - dubbo-all - dubbo-bom - - - - dubbo-core-spi - - dubbo-core-spi - - - - dubbo-all-shaded - - dubbo-all-shaded - dubbo-bom - - - - java11+ - - [11,) - - - - - - com.diffplug.spotless - spotless-maven-plugin - ${spotless-maven-plugin.version} - - - - - - dubbo-importorder.txt - - - checkstyle-header.txt - - - - - false - true - - - - true - - - - - com.alibaba - dubbo-shared-resources - ${dubbo-shared-resources.version} - - - - - - ${spotless.action} - - process-sources - - - - - - - + + + release + + dubbo-all + dubbo-all-shaded + dubbo-apache-release + dubbo-bom + dubbo-core-spi + + + + dubbo-all + + true + + + dubbo-all + dubbo-bom + + + + dubbo-core-spi + + dubbo-core-spi + + + + dubbo-all-shaded + + dubbo-all-shaded + dubbo-bom + + + diff --git a/dubbo-kubernetes/pom.xml b/dubbo-kubernetes/pom.xml index 7b35219234..c8a99a6c42 100644 --- a/dubbo-kubernetes/pom.xml +++ b/dubbo-kubernetes/pom.xml @@ -15,66 +15,64 @@ See the License for the specific language governing permissions and limitations under the License. --> - - 4.0.0 - - org.apache.dubbo - dubbo-parent - ${revision} - ../pom.xml - + + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + - dubbo-kubernetes - ${project.artifactId} - The Kubernetes Integration - - false - + dubbo-kubernetes + ${project.artifactId} + The Kubernetes Integration + + false + - - - org.apache.dubbo - dubbo-registry-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - org.apache.dubbo - dubbo-metadata-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-plugin-router-mesh - ${project.parent.version} - - - io.fabric8 - kubernetes-client - - - io.fabric8 - kubernetes-server-mock - test - - - org.mockito - mockito-junit-jupiter - 3.12.4 - test - - - org.junit.jupiter - junit-jupiter-api - - - - + + + org.apache.dubbo + dubbo-registry-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-common + ${project.parent.version} + + + org.apache.dubbo + dubbo-metadata-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-plugin-router-mesh + ${project.parent.version} + + + io.fabric8 + kubernetes-client + + + io.fabric8 + kubernetes-server-mock + test + + + org.mockito + mockito-junit-jupiter + 3.12.4 + test + + + org.junit.jupiter + junit-jupiter-api + + + + diff --git a/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesMeshEnvListener.java b/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesMeshEnvListener.java index e35419f8c7..43e79862fe 100644 --- a/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesMeshEnvListener.java +++ b/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesMeshEnvListener.java @@ -21,6 +21,9 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.cluster.router.mesh.route.MeshAppRuleListener; import org.apache.dubbo.rpc.cluster.router.mesh.route.MeshEnvListener; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + import io.fabric8.kubernetes.api.model.GenericKubernetesResource; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.Watch; @@ -30,13 +33,11 @@ import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.SafeConstructor; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_LISTEN_KUBERNETES; public class KubernetesMeshEnvListener implements MeshEnvListener { - public static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(KubernetesMeshEnvListener.class); + public static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(KubernetesMeshEnvListener.class); private static volatile boolean usingApiServer = false; private static volatile KubernetesClient kubernetesClient; private static volatile String namespace; @@ -82,15 +83,15 @@ public class KubernetesMeshEnvListener implements MeshEnvListener { try { Watch watch = kubernetesClient - .genericKubernetesResources( - MeshConstant.getVsDefinition()) + .genericKubernetesResources(MeshConstant.getVsDefinition()) .inNamespace(namespace) .withName(appName) .watch(new Watcher() { @Override public void eventReceived(Action action, GenericKubernetesResource resource) { if (logger.isInfoEnabled()) { - logger.info("Received VS Rule notification. AppName: " + appName + " Action:" + action + " Resource:" + resource); + logger.info("Received VS Rule notification. AppName: " + appName + " Action:" + action + + " Resource:" + resource); } if (action == Action.ADDED || action == Action.MODIFIED) { @@ -112,8 +113,7 @@ public class KubernetesMeshEnvListener implements MeshEnvListener { vsAppWatch.put(appName, watch); try { GenericKubernetesResource vsRule = kubernetesClient - .genericKubernetesResources( - MeshConstant.getVsDefinition()) + .genericKubernetesResources(MeshConstant.getVsDefinition()) .inNamespace(namespace) .withName(appName) .get(); @@ -140,15 +140,15 @@ public class KubernetesMeshEnvListener implements MeshEnvListener { try { Watch watch = kubernetesClient - .genericKubernetesResources( - MeshConstant.getDrDefinition()) + .genericKubernetesResources(MeshConstant.getDrDefinition()) .inNamespace(namespace) .withName(appName) .watch(new Watcher() { @Override public void eventReceived(Action action, GenericKubernetesResource resource) { if (logger.isInfoEnabled()) { - logger.info("Received VS Rule notification. AppName: " + appName + " Action:" + action + " Resource:" + resource); + logger.info("Received VS Rule notification. AppName: " + appName + " Action:" + action + + " Resource:" + resource); } if (action == Action.ADDED || action == Action.MODIFIED) { @@ -171,8 +171,7 @@ public class KubernetesMeshEnvListener implements MeshEnvListener { drAppWatch.put(appName, watch); try { GenericKubernetesResource drRule = kubernetesClient - .genericKubernetesResources( - MeshConstant.getDrDefinition()) + .genericKubernetesResources(MeshConstant.getDrDefinition()) .inNamespace(namespace) .withName(appName) .get(); diff --git a/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesRegistry.java b/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesRegistry.java index b221c89c2b..2d51c1bfa2 100644 --- a/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesRegistry.java +++ b/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesRegistry.java @@ -37,22 +37,14 @@ public class KubernetesRegistry extends FailbackRegistry { } @Override - public void doRegister(URL url) { - - } + public void doRegister(URL url) {} @Override - public void doUnregister(URL url) { - - } + public void doUnregister(URL url) {} @Override - public void doSubscribe(URL url, NotifyListener listener) { - - } + public void doSubscribe(URL url, NotifyListener listener) {} @Override - public void doUnsubscribe(URL url, NotifyListener listener) { - - } + public void doUnsubscribe(URL url, NotifyListener listener) {} } diff --git a/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesServiceDiscovery.java b/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesServiceDiscovery.java index 739a5e0584..7792abdd2b 100644 --- a/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesServiceDiscovery.java +++ b/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesServiceDiscovery.java @@ -16,15 +16,6 @@ */ package org.apache.dubbo.registry.kubernetes; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicLong; -import java.util.stream.Collectors; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -40,6 +31,15 @@ import org.apache.dubbo.registry.kubernetes.util.KubernetesConfigUtils; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ScopeModelUtil; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicLong; +import java.util.stream.Collectors; + import io.fabric8.kubernetes.api.model.EndpointAddress; import io.fabric8.kubernetes.api.model.EndpointPort; import io.fabric8.kubernetes.api.model.EndpointSubset; @@ -70,15 +70,18 @@ public class KubernetesServiceDiscovery extends AbstractServiceDiscovery { private final boolean enableRegister; - public final static String KUBERNETES_PROPERTIES_KEY = "io.dubbo/metadata"; + public static final String KUBERNETES_PROPERTIES_KEY = "io.dubbo/metadata"; - private final static ConcurrentHashMap SERVICE_UPDATE_TIME = new ConcurrentHashMap<>(64); + private static final ConcurrentHashMap SERVICE_UPDATE_TIME = new ConcurrentHashMap<>(64); - private final static ConcurrentHashMap> SERVICE_INFORMER = new ConcurrentHashMap<>(64); + private static final ConcurrentHashMap> SERVICE_INFORMER = + new ConcurrentHashMap<>(64); - private final static ConcurrentHashMap> PODS_INFORMER = new ConcurrentHashMap<>(64); + private static final ConcurrentHashMap> PODS_INFORMER = + new ConcurrentHashMap<>(64); - private final static ConcurrentHashMap> ENDPOINTS_INFORMER = new ConcurrentHashMap<>(64); + private static final ConcurrentHashMap> ENDPOINTS_INFORMER = + new ConcurrentHashMap<>(64); public KubernetesServiceDiscovery(ApplicationModel applicationModel, URL registryURL) { super(applicationModel, registryURL); @@ -96,11 +99,11 @@ public class KubernetesServiceDiscovery extends AbstractServiceDiscovery { availableAccess = false; } if (!availableAccess) { - String message = "Unable to access api server. " + - "Please check your url config." + - " Master URL: " + config.getMasterUrl() + - " Hostname: " + currentHostname; - logger.error(REGISTRY_UNABLE_ACCESS_KUBERNETES,"","",message); + String message = "Unable to access api server. " + "Please check your url config." + + " Master URL: " + + config.getMasterUrl() + " Hostname: " + + currentHostname; + logger.error(REGISTRY_UNABLE_ACCESS_KUBERNETES, "", "", message); } else { KubernetesMeshEnvListener.injectKubernetesEnv(kubernetesClient, namespace); } @@ -127,15 +130,15 @@ public class KubernetesServiceDiscovery extends AbstractServiceDiscovery { .pods() .inNamespace(namespace) .withName(currentHostname) - .edit(pod -> - new PodBuilder(pod) - .editOrNewMetadata() - .addToAnnotations(KUBERNETES_PROPERTIES_KEY, JsonUtils.toJson(serviceInstance.getMetadata())) - .endMetadata() - .build()); + .edit(pod -> new PodBuilder(pod) + .editOrNewMetadata() + .addToAnnotations( + KUBERNETES_PROPERTIES_KEY, JsonUtils.toJson(serviceInstance.getMetadata())) + .endMetadata() + .build()); if (logger.isInfoEnabled()) { - logger.info("Write Current Service Instance Metadata to Kubernetes pod. " + - "Current pod name: " + currentHostname); + logger.info("Write Current Service Instance Metadata to Kubernetes pod. " + "Current pod name: " + + currentHostname); } } } @@ -144,7 +147,8 @@ public class KubernetesServiceDiscovery extends AbstractServiceDiscovery { * Comparing to {@link AbstractServiceDiscovery#doUpdate(ServiceInstance, ServiceInstance)}, unregister() is unnecessary here. */ @Override - public void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance) throws RuntimeException { + public void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance) + throws RuntimeException { reportMetadata(newServiceInstance.getServiceMetadata()); this.doRegister(newServiceInstance); } @@ -156,26 +160,21 @@ public class KubernetesServiceDiscovery extends AbstractServiceDiscovery { .pods() .inNamespace(namespace) .withName(currentHostname) - .edit(pod -> - new PodBuilder(pod) - .editOrNewMetadata() - .removeFromAnnotations(KUBERNETES_PROPERTIES_KEY) - .endMetadata() - .build()); + .edit(pod -> new PodBuilder(pod) + .editOrNewMetadata() + .removeFromAnnotations(KUBERNETES_PROPERTIES_KEY) + .endMetadata() + .build()); if (logger.isInfoEnabled()) { - logger.info("Remove Current Service Instance from Kubernetes pod. Current pod name: " + currentHostname); + logger.info( + "Remove Current Service Instance from Kubernetes pod. Current pod name: " + currentHostname); } } } @Override public Set getServices() { - return kubernetesClient - .services() - .inNamespace(namespace) - .list() - .getItems() - .stream() + return kubernetesClient.services().inNamespace(namespace).list().getItems().stream() .map(service -> service.getMetadata().getName()) .collect(Collectors.toSet()); } @@ -203,7 +202,8 @@ public class KubernetesServiceDiscovery extends AbstractServiceDiscovery { } @Override - public void addServiceInstancesChangedListener(ServiceInstancesChangedListener listener) throws NullPointerException, IllegalArgumentException { + public void addServiceInstancesChangedListener(ServiceInstancesChangedListener listener) + throws NullPointerException, IllegalArgumentException { listener.getServiceNames().forEach(serviceName -> { SERVICE_UPDATE_TIME.put(serviceName, new AtomicLong(0L)); @@ -227,8 +227,8 @@ public class KubernetesServiceDiscovery extends AbstractServiceDiscovery { @Override public void onAdd(Endpoints endpoints) { if (logger.isDebugEnabled()) { - logger.debug("Received Endpoint Event. Event type: added. Current pod name: " + currentHostname + - ". Endpoints is: " + endpoints); + logger.debug("Received Endpoint Event. Event type: added. Current pod name: " + + currentHostname + ". Endpoints is: " + endpoints); } notifyServiceChanged(serviceName, listener, toServiceInstance(endpoints, serviceName)); } @@ -236,8 +236,8 @@ public class KubernetesServiceDiscovery extends AbstractServiceDiscovery { @Override public void onUpdate(Endpoints oldEndpoints, Endpoints newEndpoints) { if (logger.isDebugEnabled()) { - logger.debug("Received Endpoint Event. Event type: updated. Current pod name: " + currentHostname + - ". The new Endpoints is: " + newEndpoints); + logger.debug("Received Endpoint Event. Event type: updated. Current pod name: " + + currentHostname + ". The new Endpoints is: " + newEndpoints); } notifyServiceChanged(serviceName, listener, toServiceInstance(newEndpoints, serviceName)); } @@ -245,8 +245,8 @@ public class KubernetesServiceDiscovery extends AbstractServiceDiscovery { @Override public void onDelete(Endpoints endpoints, boolean deletedFinalStateUnknown) { if (logger.isDebugEnabled()) { - logger.debug("Received Endpoint Event. Event type: deleted. Current pod name: " + currentHostname + - ". Endpoints is: " + endpoints); + logger.debug("Received Endpoint Event. Event type: deleted. Current pod name: " + + currentHostname + ". Endpoints is: " + endpoints); } notifyServiceChanged(serviceName, listener, toServiceInstance(endpoints, serviceName)); } @@ -269,16 +269,16 @@ public class KubernetesServiceDiscovery extends AbstractServiceDiscovery { @Override public void onAdd(Pod pod) { if (logger.isDebugEnabled()) { - logger.debug("Received Pods Event. Event type: added. Current pod name: " + currentHostname + - ". Pod is: " + pod); + logger.debug("Received Pods Event. Event type: added. Current pod name: " + currentHostname + + ". Pod is: " + pod); } } @Override public void onUpdate(Pod oldPod, Pod newPod) { if (logger.isDebugEnabled()) { - logger.debug("Received Pods Event. Event type: updated. Current pod name: " + currentHostname + - ". new Pod is: " + newPod); + logger.debug("Received Pods Event. Event type: updated. Current pod name: " + + currentHostname + ". new Pod is: " + newPod); } notifyServiceChanged(serviceName, listener, getInstances(serviceName)); @@ -287,8 +287,8 @@ public class KubernetesServiceDiscovery extends AbstractServiceDiscovery { @Override public void onDelete(Pod pod, boolean deletedFinalStateUnknown) { if (logger.isDebugEnabled()) { - logger.debug("Received Pods Event. Event type: deleted. Current pod name: " + currentHostname + - ". Pod is: " + pod); + logger.debug("Received Pods Event. Event type: deleted. Current pod name: " + + currentHostname + ". Pod is: " + pod); } } }); @@ -301,43 +301,40 @@ public class KubernetesServiceDiscovery extends AbstractServiceDiscovery { .services() .inNamespace(namespace) .withName(serviceName) - .inform( - new ResourceEventHandler() { - @Override - public void onAdd(Service service) { - if (logger.isDebugEnabled()) { - logger.debug("Received Service Added Event. " + - "Current pod name: " + currentHostname); - } - } - - @Override - public void onUpdate(Service oldService, Service newService) { - if (logger.isDebugEnabled()) { - logger.debug("Received Service Update Event. Update Pods Watcher. Current pod name: " + currentHostname + - ". The new Service is: " + newService); - } - if (PODS_INFORMER.containsKey(serviceName)) { - PODS_INFORMER.get(serviceName).close(); - PODS_INFORMER.remove(serviceName); - } - watchPods(listener, serviceName); - } - - @Override - public void onDelete(Service service, boolean deletedFinalStateUnknown) { - if (logger.isDebugEnabled()) { - logger.debug("Received Service Delete Event. " + - "Current pod name: " + currentHostname); - } - } + .inform(new ResourceEventHandler() { + @Override + public void onAdd(Service service) { + if (logger.isDebugEnabled()) { + logger.debug("Received Service Added Event. " + "Current pod name: " + currentHostname); } - ); + } + + @Override + public void onUpdate(Service oldService, Service newService) { + if (logger.isDebugEnabled()) { + logger.debug("Received Service Update Event. Update Pods Watcher. Current pod name: " + + currentHostname + ". The new Service is: " + newService); + } + if (PODS_INFORMER.containsKey(serviceName)) { + PODS_INFORMER.get(serviceName).close(); + PODS_INFORMER.remove(serviceName); + } + watchPods(listener, serviceName); + } + + @Override + public void onDelete(Service service, boolean deletedFinalStateUnknown) { + if (logger.isDebugEnabled()) { + logger.debug("Received Service Delete Event. " + "Current pod name: " + currentHostname); + } + } + }); SERVICE_INFORMER.put(serviceName, serviceInformer); } - private void notifyServiceChanged(String serviceName, ServiceInstancesChangedListener listener, List serviceInstanceList) { + private void notifyServiceChanged( + String serviceName, ServiceInstancesChangedListener listener, List serviceInstanceList) { long receivedTime = System.nanoTime(); ServiceInstancesChangedEvent event; @@ -355,10 +352,11 @@ public class KubernetesServiceDiscovery extends AbstractServiceDiscovery { } if (logger.isInfoEnabled()) { - logger.info("Discard Service Instance Data. " + - "Possible Cause: Newer message has been processed or Failed to update time record by CAS. " + - "Current Data received time: " + receivedTime + ". " + - "Newer Data received time: " + lastUpdateTime + "."); + logger.info("Discard Service Instance Data. " + + "Possible Cause: Newer message has been processed or Failed to update time record by CAS. " + + "Current Data received time: " + + receivedTime + ". " + "Newer Data received time: " + + lastUpdateTime + "."); } } @@ -368,7 +366,11 @@ public class KubernetesServiceDiscovery extends AbstractServiceDiscovery { } private Map getServiceSelector(String serviceName) { - Service service = kubernetesClient.services().inNamespace(namespace).withName(serviceName).get(); + Service service = kubernetesClient + .services() + .inNamespace(namespace) + .withName(serviceName) + .get(); if (service == null) { return null; } @@ -380,26 +382,17 @@ public class KubernetesServiceDiscovery extends AbstractServiceDiscovery { if (serviceSelector == null) { return new LinkedList<>(); } - Map pods = kubernetesClient - .pods() - .inNamespace(namespace) - .withLabels(serviceSelector) - .list() - .getItems() - .stream() - .collect( - Collectors.toMap( - pod -> pod.getMetadata().getName(), - pod -> pod)); + Map pods = + kubernetesClient.pods().inNamespace(namespace).withLabels(serviceSelector).list().getItems().stream() + .collect(Collectors.toMap(pod -> pod.getMetadata().getName(), pod -> pod)); List instances = new LinkedList<>(); Set instancePorts = new HashSet<>(); for (EndpointSubset endpointSubset : endpoints.getSubsets()) { - instancePorts.addAll( - endpointSubset.getPorts() - .stream().map(EndpointPort::getPort) - .collect(Collectors.toSet())); + instancePorts.addAll(endpointSubset.getPorts().stream() + .map(EndpointPort::getPort) + .collect(Collectors.toSet())); } for (EndpointSubset endpointSubset : endpoints.getSubsets()) { @@ -407,21 +400,31 @@ public class KubernetesServiceDiscovery extends AbstractServiceDiscovery { Pod pod = pods.get(address.getTargetRef().getName()); String ip = address.getIp(); if (pod == null) { - logger.warn(REGISTRY_UNABLE_MATCH_KUBERNETES, "", "", "Unable to match Kubernetes Endpoint address with Pod. " + - "EndpointAddress Hostname: " + address.getTargetRef().getName()); + logger.warn( + REGISTRY_UNABLE_MATCH_KUBERNETES, + "", + "", + "Unable to match Kubernetes Endpoint address with Pod. " + "EndpointAddress Hostname: " + + address.getTargetRef().getName()); continue; } instancePorts.forEach(port -> { - ServiceInstance serviceInstance = new DefaultServiceInstance(serviceName, ip, port, ScopeModelUtil.getApplicationModel(getUrl().getScopeModel())); + ServiceInstance serviceInstance = new DefaultServiceInstance( + serviceName, ip, port, ScopeModelUtil.getApplicationModel(getUrl().getScopeModel())); String properties = pod.getMetadata().getAnnotations().get(KUBERNETES_PROPERTIES_KEY); if (StringUtils.isNotEmpty(properties)) { serviceInstance.getMetadata().putAll(JsonUtils.toJavaObject(properties, Map.class)); instances.add(serviceInstance); } else { - logger.warn(REGISTRY_UNABLE_FIND_SERVICE_KUBERNETES, "", "", "Unable to find Service Instance metadata in Pod Annotations. " + - "Possibly cause: provider has not been initialized successfully. " + - "EndpointAddress Hostname: " + address.getTargetRef().getName()); + logger.warn( + REGISTRY_UNABLE_FIND_SERVICE_KUBERNETES, + "", + "", + "Unable to find Service Instance metadata in Pod Annotations. " + + "Possibly cause: provider has not been initialized successfully. " + + "EndpointAddress Hostname: " + + address.getTargetRef().getName()); } }); } diff --git a/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/MeshConstant.java b/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/MeshConstant.java index 813bdd8259..e8b8f8407f 100644 --- a/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/MeshConstant.java +++ b/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/MeshConstant.java @@ -22,22 +22,24 @@ public class MeshConstant { public static CustomResourceDefinitionContext getVsDefinition() { // TODO cache return new CustomResourceDefinitionContext.Builder() - .withGroup("service.dubbo.apache.org") - .withVersion("v1alpha1") - .withScope("Namespaced") - .withName("virtualservices.service.dubbo.apache.org") - .withPlural("virtualservices") - .withKind("VirtualService").build(); + .withGroup("service.dubbo.apache.org") + .withVersion("v1alpha1") + .withScope("Namespaced") + .withName("virtualservices.service.dubbo.apache.org") + .withPlural("virtualservices") + .withKind("VirtualService") + .build(); } public static CustomResourceDefinitionContext getDrDefinition() { // TODO cache return new CustomResourceDefinitionContext.Builder() - .withGroup("service.dubbo.apache.org") - .withVersion("v1alpha1") - .withScope("Namespaced") - .withName("destinationrules.service.dubbo.apache.org") - .withPlural("destinationrules") - .withKind("DestinationRule").build(); + .withGroup("service.dubbo.apache.org") + .withVersion("v1alpha1") + .withScope("Namespaced") + .withName("destinationrules.service.dubbo.apache.org") + .withPlural("destinationrules") + .withKind("DestinationRule") + .build(); } } diff --git a/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/NopKubernetesMeshEnvListener.java b/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/NopKubernetesMeshEnvListener.java index 1238efb579..818b8df64d 100644 --- a/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/NopKubernetesMeshEnvListener.java +++ b/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/NopKubernetesMeshEnvListener.java @@ -27,12 +27,8 @@ public class NopKubernetesMeshEnvListener implements MeshEnvListener { } @Override - public void onSubscribe(String appName, MeshAppRuleListener listener) { - - } + public void onSubscribe(String appName, MeshAppRuleListener listener) {} @Override - public void onUnSubscribe(String appName) { - - } + public void onUnSubscribe(String appName) {} } diff --git a/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/util/KubernetesClientConst.java b/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/util/KubernetesClientConst.java index d4591a249e..b7ace53894 100644 --- a/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/util/KubernetesClientConst.java +++ b/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/util/KubernetesClientConst.java @@ -20,59 +20,59 @@ public class KubernetesClientConst { public static final String DEFAULT_MASTER_PLACEHOLDER = "DEFAULT_MASTER_HOST"; public static final String DEFAULT_MASTER_URL = "https://kubernetes.default.svc"; - public final static String ENABLE_REGISTER = "enableRegister"; + public static final String ENABLE_REGISTER = "enableRegister"; - public final static String TRUST_CERTS = "trustCerts"; + public static final String TRUST_CERTS = "trustCerts"; - public final static String USE_HTTPS = "useHttps"; + public static final String USE_HTTPS = "useHttps"; public static final String HTTP2_DISABLE = "http2Disable"; - public final static String NAMESPACE = "namespace"; + public static final String NAMESPACE = "namespace"; - public final static String API_VERSION = "apiVersion"; + public static final String API_VERSION = "apiVersion"; - public final static String CA_CERT_FILE = "caCertFile"; + public static final String CA_CERT_FILE = "caCertFile"; - public final static String CA_CERT_DATA = "caCertData"; + public static final String CA_CERT_DATA = "caCertData"; - public final static String CLIENT_CERT_FILE = "clientCertFile"; + public static final String CLIENT_CERT_FILE = "clientCertFile"; - public final static String CLIENT_CERT_DATA = "clientCertData"; + public static final String CLIENT_CERT_DATA = "clientCertData"; - public final static String CLIENT_KEY_FILE = "clientKeyFile"; + public static final String CLIENT_KEY_FILE = "clientKeyFile"; - public final static String CLIENT_KEY_DATA = "clientKeyData"; + public static final String CLIENT_KEY_DATA = "clientKeyData"; - public final static String CLIENT_KEY_ALGO = "clientKeyAlgo"; + public static final String CLIENT_KEY_ALGO = "clientKeyAlgo"; - public final static String CLIENT_KEY_PASSPHRASE = "clientKeyPassphrase"; + public static final String CLIENT_KEY_PASSPHRASE = "clientKeyPassphrase"; - public final static String OAUTH_TOKEN = "oauthToken"; + public static final String OAUTH_TOKEN = "oauthToken"; - public final static String USERNAME = "username"; + public static final String USERNAME = "username"; - public final static String PASSWORD = "password"; + public static final String PASSWORD = "password"; - public final static String WATCH_RECONNECT_INTERVAL = "watchReconnectInterval"; + public static final String WATCH_RECONNECT_INTERVAL = "watchReconnectInterval"; - public final static String WATCH_RECONNECT_LIMIT = "watchReconnectLimit"; + public static final String WATCH_RECONNECT_LIMIT = "watchReconnectLimit"; - public final static String CONNECTION_TIMEOUT = "connectionTimeout"; + public static final String CONNECTION_TIMEOUT = "connectionTimeout"; - public final static String REQUEST_TIMEOUT = "requestTimeout"; + public static final String REQUEST_TIMEOUT = "requestTimeout"; - public final static String ROLLING_TIMEOUT = "rollingTimeout"; + public static final String ROLLING_TIMEOUT = "rollingTimeout"; - public final static String LOGGING_INTERVAL = "loggingInterval"; + public static final String LOGGING_INTERVAL = "loggingInterval"; - public final static String HTTP_PROXY = "httpProxy"; + public static final String HTTP_PROXY = "httpProxy"; - public final static String HTTPS_PROXY = "httpsProxy"; + public static final String HTTPS_PROXY = "httpsProxy"; - public final static String PROXY_USERNAME = "proxyUsername"; + public static final String PROXY_USERNAME = "proxyUsername"; - public final static String PROXY_PASSWORD = "proxyPassword"; + public static final String PROXY_PASSWORD = "proxyPassword"; - public final static String NO_PROXY = "noProxy"; + public static final String NO_PROXY = "noProxy"; } diff --git a/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/util/KubernetesConfigUtils.java b/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/util/KubernetesConfigUtils.java index 4b54b4c6b0..332bb6e733 100644 --- a/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/util/KubernetesConfigUtils.java +++ b/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/util/KubernetesConfigUtils.java @@ -19,11 +19,11 @@ package org.apache.dubbo.registry.kubernetes.util; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; +import java.util.Base64; + import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.ConfigBuilder; -import java.util.Base64; - import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.API_VERSION; import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.CA_CERT_DATA; import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.CA_CERT_FILE; @@ -66,31 +66,23 @@ public class KubernetesConfigUtils { .withNamespace(url.getParameter(NAMESPACE, base.getNamespace())) // .withUsername(url.getParameter(USERNAME, base.getUsername())) // .withPassword(url.getParameter(PASSWORD, base.getPassword())) // - .withOauthToken(url.getParameter(OAUTH_TOKEN, base.getOauthToken())) // - .withCaCertFile(url.getParameter(CA_CERT_FILE, base.getCaCertFile())) // .withCaCertData(url.getParameter(CA_CERT_DATA, decodeBase64(base.getCaCertData()))) // - .withClientKeyFile(url.getParameter(CLIENT_KEY_FILE, base.getClientKeyFile())) // .withClientKeyData(url.getParameter(CLIENT_KEY_DATA, decodeBase64(base.getClientKeyData()))) // - .withClientCertFile(url.getParameter(CLIENT_CERT_FILE, base.getClientCertFile())) // .withClientCertData(url.getParameter(CLIENT_CERT_DATA, decodeBase64(base.getClientCertData()))) // - .withClientKeyAlgo(url.getParameter(CLIENT_KEY_ALGO, base.getClientKeyAlgo())) // .withClientKeyPassphrase(url.getParameter(CLIENT_KEY_PASSPHRASE, base.getClientKeyPassphrase())) // - .withConnectionTimeout(url.getParameter(CONNECTION_TIMEOUT, base.getConnectionTimeout())) // .withRequestTimeout(url.getParameter(REQUEST_TIMEOUT, base.getRequestTimeout())) // - - .withWatchReconnectInterval(url.getParameter(WATCH_RECONNECT_INTERVAL, base.getWatchReconnectInterval())) // + .withWatchReconnectInterval( + url.getParameter(WATCH_RECONNECT_INTERVAL, base.getWatchReconnectInterval())) // .withWatchReconnectLimit(url.getParameter(WATCH_RECONNECT_LIMIT, base.getWatchReconnectLimit())) // .withLoggingInterval(url.getParameter(LOGGING_INTERVAL, base.getLoggingInterval())) // - .withTrustCerts(url.getParameter(TRUST_CERTS, base.isTrustCerts())) // .withHttp2Disable(url.getParameter(HTTP2_DISABLE, base.isHttp2Disable())) // - .withHttpProxy(url.getParameter(HTTP_PROXY, base.getHttpProxy())) // .withHttpsProxy(url.getParameter(HTTPS_PROXY, base.getHttpsProxy())) // .withProxyUsername(url.getParameter(PROXY_USERNAME, base.getProxyUsername())) // @@ -103,14 +95,10 @@ public class KubernetesConfigUtils { if (DEFAULT_MASTER_PLACEHOLDER.equalsIgnoreCase(url.getHost())) { return DEFAULT_MASTER_URL; } - return (url.getParameter(USE_HTTPS, true) ? - "https://" : "http://") - + url.getHost() + ":" + url.getPort(); + return (url.getParameter(USE_HTTPS, true) ? "https://" : "http://") + url.getHost() + ":" + url.getPort(); } private static String decodeBase64(String str) { - return StringUtils.isNotEmpty(str) ? - new String(Base64.getDecoder().decode(str)) : - null; + return StringUtils.isNotEmpty(str) ? new String(Base64.getDecoder().decode(str)) : null; } } diff --git a/dubbo-kubernetes/src/test/java/org/apache/dubbo/registry/kubernetes/KubernetesServiceDiscoveryTest.java b/dubbo-kubernetes/src/test/java/org/apache/dubbo/registry/kubernetes/KubernetesServiceDiscoveryTest.java index 5341c0cb74..6f47be6015 100644 --- a/dubbo-kubernetes/src/test/java/org/apache/dubbo/registry/kubernetes/KubernetesServiceDiscoveryTest.java +++ b/dubbo-kubernetes/src/test/java/org/apache/dubbo/registry/kubernetes/KubernetesServiceDiscoveryTest.java @@ -16,15 +16,6 @@ */ package org.apache.dubbo.registry.kubernetes; -import io.fabric8.kubernetes.api.model.Endpoints; -import io.fabric8.kubernetes.api.model.EndpointsBuilder; -import io.fabric8.kubernetes.api.model.Pod; -import io.fabric8.kubernetes.api.model.PodBuilder; -import io.fabric8.kubernetes.api.model.Service; -import io.fabric8.kubernetes.api.model.ServiceBuilder; -import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.NamespacedKubernetesClient; -import io.fabric8.kubernetes.client.server.mock.KubernetesServer; import org.apache.dubbo.common.URL; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.registry.client.DefaultServiceInstance; @@ -34,6 +25,20 @@ import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedLi import org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ScopeModelUtil; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; + +import io.fabric8.kubernetes.api.model.Endpoints; +import io.fabric8.kubernetes.api.model.EndpointsBuilder; +import io.fabric8.kubernetes.api.model.Pod; +import io.fabric8.kubernetes.api.model.PodBuilder; +import io.fabric8.kubernetes.api.model.Service; +import io.fabric8.kubernetes.api.model.ServiceBuilder; +import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.NamespacedKubernetesClient; +import io.fabric8.kubernetes.client.server.mock.KubernetesServer; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -43,10 +48,6 @@ import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; - import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.NAMESPACE; import static org.awaitility.Awaitility.await; @@ -69,7 +70,6 @@ class KubernetesServiceDiscoveryTest { private KubernetesServiceDiscovery serviceDiscovery; - @BeforeEach public void setUp() { mockServer.before(); @@ -93,19 +93,35 @@ class KubernetesServiceDiscoveryTest { selector = new HashMap<>(4); selector.put("l", "v"); Pod pod = new PodBuilder() - .withNewMetadata().withName(POD_NAME).withLabels(selector).endMetadata() + .withNewMetadata() + .withName(POD_NAME) + .withLabels(selector) + .endMetadata() .build(); Service service = new ServiceBuilder() - .withNewMetadata().withName(SERVICE_NAME).endMetadata() - .withNewSpec().withSelector(selector).endSpec().build(); + .withNewMetadata() + .withName(SERVICE_NAME) + .endMetadata() + .withNewSpec() + .withSelector(selector) + .endSpec() + .build(); Endpoints endPoints = new EndpointsBuilder() - .withNewMetadata().withName(SERVICE_NAME).endMetadata() + .withNewMetadata() + .withName(SERVICE_NAME) + .endMetadata() .addNewSubset() - .addNewAddress().withIp("ip1") - .withNewTargetRef().withUid("uid1").withName(POD_NAME).endTargetRef().endAddress() - .addNewPort("Test", "Test", 12345, "TCP").endSubset() + .addNewAddress() + .withIp("ip1") + .withNewTargetRef() + .withUid("uid1") + .withName(POD_NAME) + .endTargetRef() + .endAddress() + .addNewPort("Test", "Test", 12345, "TCP") + .endSubset() .build(); mockClient.pods().resource(pod).create(); @@ -125,7 +141,11 @@ class KubernetesServiceDiscoveryTest { serviceDiscovery.setCurrentHostname(POD_NAME); serviceDiscovery.setKubernetesClient(mockClient); - ServiceInstance serviceInstance = new DefaultServiceInstance(SERVICE_NAME, "Test", 12345, ScopeModelUtil.getApplicationModel(serviceDiscovery.getUrl().getScopeModel())); + ServiceInstance serviceInstance = new DefaultServiceInstance( + SERVICE_NAME, + "Test", + 12345, + ScopeModelUtil.getApplicationModel(serviceDiscovery.getUrl().getScopeModel())); serviceDiscovery.doRegister(serviceInstance); @@ -135,25 +155,29 @@ class KubernetesServiceDiscoveryTest { Mockito.doNothing().when(mockListener).onEvent(Mockito.any()); serviceDiscovery.addServiceInstancesChangedListener(mockListener); - mockClient.endpoints().withName(SERVICE_NAME) - .edit(endpoints -> - new EndpointsBuilder(endpoints) - .editFirstSubset() - .addNewAddress() - .withIp("ip2") - .withNewTargetRef().withUid("uid2").withName(POD_NAME).endTargetRef() - .endAddress().endSubset() - .build()); + mockClient.endpoints().withName(SERVICE_NAME).edit(endpoints -> new EndpointsBuilder(endpoints) + .editFirstSubset() + .addNewAddress() + .withIp("ip2") + .withNewTargetRef() + .withUid("uid2") + .withName(POD_NAME) + .endTargetRef() + .endAddress() + .endSubset() + .build()); await().until(() -> { - ArgumentCaptor captor = ArgumentCaptor.forClass(ServiceInstancesChangedEvent.class); + ArgumentCaptor captor = + ArgumentCaptor.forClass(ServiceInstancesChangedEvent.class); Mockito.verify(mockListener, Mockito.atLeast(0)).onEvent(captor.capture()); return captor.getValue().getServiceInstances().size() == 2; }); ArgumentCaptor eventArgumentCaptor = ArgumentCaptor.forClass(ServiceInstancesChangedEvent.class); Mockito.verify(mockListener, Mockito.times(2)).onEvent(eventArgumentCaptor.capture()); - Assertions.assertEquals(2, eventArgumentCaptor.getValue().getServiceInstances().size()); + Assertions.assertEquals( + 2, eventArgumentCaptor.getValue().getServiceInstances().size()); serviceDiscovery.doUnregister(serviceInstance); } @@ -163,7 +187,11 @@ class KubernetesServiceDiscoveryTest { serviceDiscovery.setCurrentHostname(POD_NAME); serviceDiscovery.setKubernetesClient(mockClient); - ServiceInstance serviceInstance = new DefaultServiceInstance(SERVICE_NAME, "Test", 12345, ScopeModelUtil.getApplicationModel(serviceDiscovery.getUrl().getScopeModel())); + ServiceInstance serviceInstance = new DefaultServiceInstance( + SERVICE_NAME, + "Test", + 12345, + ScopeModelUtil.getApplicationModel(serviceDiscovery.getUrl().getScopeModel())); serviceDiscovery.doRegister(serviceInstance); @@ -174,18 +202,24 @@ class KubernetesServiceDiscoveryTest { serviceDiscovery.addServiceInstancesChangedListener(mockListener); - serviceInstance = new DefaultServiceInstance(SERVICE_NAME, "Test12345", 12345, ScopeModelUtil.getApplicationModel(serviceDiscovery.getUrl().getScopeModel())); + serviceInstance = new DefaultServiceInstance( + SERVICE_NAME, + "Test12345", + 12345, + ScopeModelUtil.getApplicationModel(serviceDiscovery.getUrl().getScopeModel())); serviceDiscovery.doUpdate(serviceInstance, serviceInstance); await().until(() -> { - ArgumentCaptor captor = ArgumentCaptor.forClass(ServiceInstancesChangedEvent.class); + ArgumentCaptor captor = + ArgumentCaptor.forClass(ServiceInstancesChangedEvent.class); Mockito.verify(mockListener, Mockito.atLeast(0)).onEvent(captor.capture()); return captor.getValue().getServiceInstances().size() == 1; }); ArgumentCaptor eventArgumentCaptor = ArgumentCaptor.forClass(ServiceInstancesChangedEvent.class); Mockito.verify(mockListener, Mockito.times(1)).onEvent(eventArgumentCaptor.capture()); - Assertions.assertEquals(1, eventArgumentCaptor.getValue().getServiceInstances().size()); + Assertions.assertEquals( + 1, eventArgumentCaptor.getValue().getServiceInstances().size()); serviceDiscovery.doUnregister(serviceInstance); } @@ -195,7 +229,11 @@ class KubernetesServiceDiscoveryTest { serviceDiscovery.setCurrentHostname(POD_NAME); serviceDiscovery.setKubernetesClient(mockClient); - ServiceInstance serviceInstance = new DefaultServiceInstance(SERVICE_NAME, "Test", 12345, ScopeModelUtil.getApplicationModel(serviceDiscovery.getUrl().getScopeModel())); + ServiceInstance serviceInstance = new DefaultServiceInstance( + SERVICE_NAME, + "Test", + 12345, + ScopeModelUtil.getApplicationModel(serviceDiscovery.getUrl().getScopeModel())); serviceDiscovery.doRegister(serviceInstance); @@ -207,22 +245,23 @@ class KubernetesServiceDiscoveryTest { serviceDiscovery.addServiceInstancesChangedListener(mockListener); selector.put("app", "test"); - mockClient.services().withName(SERVICE_NAME) - .edit(service -> new ServiceBuilder(service) - .editSpec() - .addToSelector(selector) - .endSpec() - .build()); + mockClient.services().withName(SERVICE_NAME).edit(service -> new ServiceBuilder(service) + .editSpec() + .addToSelector(selector) + .endSpec() + .build()); await().until(() -> { - ArgumentCaptor captor = ArgumentCaptor.forClass(ServiceInstancesChangedEvent.class); + ArgumentCaptor captor = + ArgumentCaptor.forClass(ServiceInstancesChangedEvent.class); Mockito.verify(mockListener, Mockito.atLeast(0)).onEvent(captor.capture()); return captor.getValue().getServiceInstances().size() == 1; }); ArgumentCaptor eventArgumentCaptor = ArgumentCaptor.forClass(ServiceInstancesChangedEvent.class); Mockito.verify(mockListener, Mockito.times(1)).onEvent(eventArgumentCaptor.capture()); - Assertions.assertEquals(1, eventArgumentCaptor.getValue().getServiceInstances().size()); + Assertions.assertEquals( + 1, eventArgumentCaptor.getValue().getServiceInstances().size()); serviceDiscovery.doUnregister(serviceInstance); } @@ -232,7 +271,11 @@ class KubernetesServiceDiscoveryTest { serviceDiscovery.setCurrentHostname(POD_NAME); serviceDiscovery.setKubernetesClient(mockClient); - ServiceInstance serviceInstance = new DefaultServiceInstance(SERVICE_NAME, "Test", 12345, ScopeModelUtil.getApplicationModel(serviceDiscovery.getUrl().getScopeModel())); + ServiceInstance serviceInstance = new DefaultServiceInstance( + SERVICE_NAME, + "Test", + 12345, + ScopeModelUtil.getApplicationModel(serviceDiscovery.getUrl().getScopeModel())); serviceDiscovery.doRegister(serviceInstance); diff --git a/dubbo-maven-plugin/pom.xml b/dubbo-maven-plugin/pom.xml index 6be4d359ad..254e9f0324 100644 --- a/dubbo-maven-plugin/pom.xml +++ b/dubbo-maven-plugin/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - dubbo-parent - org.apache.dubbo - ${revision} - + + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + - dubbo-maven-plugin - Dubbo Maven Plugin - maven-plugin + dubbo-maven-plugin + maven-plugin + Dubbo Maven Plugin - - - org.apache.maven - maven-plugin-api - 3.9.1 - + + + org.apache.maven + maven-plugin-api + 3.9.1 + - - org.apache.maven - maven-core - 3.9.1 - provided - + + org.apache.maven + maven-core + 3.9.1 + provided + - - org.apache.maven.plugin-tools - maven-plugin-annotations - 3.8.1 - provided - + + org.apache.maven.plugin-tools + maven-plugin-annotations + 3.8.1 + provided + - - org.apache.maven.shared - maven-common-artifact-filters - 3.3.2 - + + org.apache.maven.shared + maven-common-artifact-filters + 3.3.2 + - - org.apache.dubbo - dubbo-common - ${project.version} - + + org.apache.dubbo + dubbo-common + ${project.version} + - - commons-io - commons-io - 2.11.0 - + + commons-io + commons-io + 2.11.0 + - - org.sonatype.plexus - plexus-build-api - 0.0.7 - - - org.codehaus.plexus - plexus-utils - - - - + + org.sonatype.plexus + plexus-build-api + 0.0.7 + + + org.codehaus.plexus + plexus-utils + + + + - - - - maven-plugin-plugin - 3.8.1 - - - default-addPluginArtifactMetadata - package - - addPluginArtifactMetadata - - - - default-descriptor - process-classes - - descriptor - - - - - - + + + + maven-plugin-plugin + 3.8.1 + + + default-addPluginArtifactMetadata + + addPluginArtifactMetadata + + package + + + default-descriptor + + descriptor + + process-classes + + + + + diff --git a/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/DubboProcessAotMojo.java b/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/DubboProcessAotMojo.java index fbcc05a466..c871e3f19a 100644 --- a/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/DubboProcessAotMojo.java +++ b/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/DubboProcessAotMojo.java @@ -16,20 +16,22 @@ */ package org.apache.dubbo.maven.plugin.aot; +import java.io.File; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; -import java.io.File; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; - -@Mojo(name = "dubbo-process-aot", defaultPhase = LifecyclePhase.PREPARE_PACKAGE, threadSafe = true, - requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME, - requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME) +@Mojo( + name = "dubbo-process-aot", + defaultPhase = LifecyclePhase.PREPARE_PACKAGE, + threadSafe = true, + requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME, + requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME) public class DubboProcessAotMojo extends AbstractAotMojo { private static final String AOT_PROCESSOR_CLASS_NAME = "org.apache.dubbo.aot.generate.AotProcessor"; @@ -66,14 +68,12 @@ public class DubboProcessAotMojo extends AbstractAotMojo { @Parameter(property = "dubbo.aot.main-class") private String mainClass; - /** * Application arguments that should be taken into account for AOT processing. */ @Parameter private String[] arguments; - @Override protected void executeAot() throws Exception { URL[] classPath = getClassPath().toArray(new URL[0]); @@ -96,7 +96,7 @@ public class DubboProcessAotMojo extends AbstractAotMojo { } private List getClassPath() throws Exception { - File[] directories = new File[]{this.classesDirectory, this.generatedClasses}; + File[] directories = new File[] {this.classesDirectory, this.generatedClasses}; return getClassPath(directories, new ExcludeTestScopeArtifactFilter()); } } diff --git a/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/DubboProtocPlugin.java b/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/DubboProtocPlugin.java index 630390bc18..dcb1b820a1 100644 --- a/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/DubboProtocPlugin.java +++ b/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/DubboProtocPlugin.java @@ -32,8 +32,7 @@ public class DubboProtocPlugin { private List jvmArgs = new ArrayList<>(); private File protocPlugin = null; - public DubboProtocPlugin() { - } + public DubboProtocPlugin() {} public String getId() { return id; @@ -125,16 +124,15 @@ public class DubboProtocPlugin { @Override public String toString() { - return "DubboProtocPlugin{" + - "id='" + id + '\'' + - ", mainClass='" + mainClass + '\'' + - ", dubboVersion='" + dubboVersion + '\'' + - ", javaHome='" + javaHome + '\'' + - ", pluginDirectory=" + pluginDirectory + - ", resolvedJars=" + resolvedJars + - ", args=" + args + - ", jvmArgs=" + jvmArgs + - ", protocPlugin=" + protocPlugin + - '}'; + return "DubboProtocPlugin{" + "id='" + + id + '\'' + ", mainClass='" + + mainClass + '\'' + ", dubboVersion='" + + dubboVersion + '\'' + ", javaHome='" + + javaHome + '\'' + ", pluginDirectory=" + + pluginDirectory + ", resolvedJars=" + + resolvedJars + ", args=" + + args + ", jvmArgs=" + + jvmArgs + ", protocPlugin=" + + protocPlugin + '}'; } } diff --git a/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/DubboProtocPluginWrapper.java b/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/DubboProtocPluginWrapper.java index 0124f9e4fa..00eb1a6040 100644 --- a/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/DubboProtocPluginWrapper.java +++ b/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/DubboProtocPluginWrapper.java @@ -16,10 +16,10 @@ */ package org.apache.dubbo.maven.plugin.protoc; -import org.apache.maven.plugin.logging.Log; - import java.io.File; +import org.apache.maven.plugin.logging.Log; + public interface DubboProtocPluginWrapper { File createProtocPlugin(DubboProtocPlugin dubboProtocPlugin, Log log); diff --git a/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/DubboProtocPluginWrapperFactory.java b/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/DubboProtocPluginWrapperFactory.java index 3a60034b63..42d83530ed 100644 --- a/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/DubboProtocPluginWrapperFactory.java +++ b/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/DubboProtocPluginWrapperFactory.java @@ -16,27 +16,23 @@ */ package org.apache.dubbo.maven.plugin.protoc; - -import org.codehaus.plexus.util.Os; - import java.util.HashMap; import java.util.Map; +import org.codehaus.plexus.util.Os; + public class DubboProtocPluginWrapperFactory { private final LinuxDubboProtocPluginWrapper linuxProtocCommandBuilder = new LinuxDubboProtocPluginWrapper(); private final WinDubboProtocPluginWrapper winDubboProtocPluginWrapper = new WinDubboProtocPluginWrapper(); - private final Map dubboProtocPluginWrappers = new HashMap<>(); - public DubboProtocPluginWrapperFactory() { dubboProtocPluginWrappers.put("linux", linuxProtocCommandBuilder); dubboProtocPluginWrappers.put("windows", winDubboProtocPluginWrapper); } - public DubboProtocPluginWrapper findByOs() { if (Os.isFamily(Os.FAMILY_WINDOWS)) { return dubboProtocPluginWrappers.get("windows"); diff --git a/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/LinuxDubboProtocPluginWrapper.java b/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/LinuxDubboProtocPluginWrapper.java index 639300eb33..4ece88359f 100644 --- a/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/LinuxDubboProtocPluginWrapper.java +++ b/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/LinuxDubboProtocPluginWrapper.java @@ -16,16 +16,15 @@ */ package org.apache.dubbo.maven.plugin.protoc; -import org.apache.maven.plugin.logging.Log; - import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.List; -public class LinuxDubboProtocPluginWrapper implements DubboProtocPluginWrapper { +import org.apache.maven.plugin.logging.Log; +public class LinuxDubboProtocPluginWrapper implements DubboProtocPluginWrapper { @Override public File createProtocPlugin(DubboProtocPlugin dubboProtocPlugin, Log log) { @@ -60,7 +59,7 @@ public class LinuxDubboProtocPluginWrapper implements DubboProtocPluginWrapper { out.println("\""); out.println(); out.println("\"" + javaLocation.getAbsolutePath() + "\" $JVMARGS -cp $CP " - + dubboProtocPlugin.getMainClass() + " $ARGS"); + + dubboProtocPlugin.getMainClass() + " $ARGS"); out.println(); boolean b = pluginExecutableFile.setExecutable(true); if (!b) { @@ -70,15 +69,13 @@ public class LinuxDubboProtocPluginWrapper implements DubboProtocPluginWrapper { } catch (IOException e) { throw new RuntimeException("Could not write plugin script file: " + pluginExecutableFile, e); } - } - private void createPluginDirectory(File pluginDirectory) { pluginDirectory.mkdirs(); if (!pluginDirectory.isDirectory()) { - throw new RuntimeException("Could not create protoc plugin directory: " - + pluginDirectory.getAbsolutePath()); + throw new RuntimeException( + "Could not create protoc plugin directory: " + pluginDirectory.getAbsolutePath()); } } } diff --git a/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/ProtocMetaData.java b/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/ProtocMetaData.java index 277d53b481..0efb81c271 100644 --- a/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/ProtocMetaData.java +++ b/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/ProtocMetaData.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.maven.plugin.protoc; - import java.io.File; import java.util.List; @@ -28,11 +27,14 @@ public class ProtocMetaData { private File outputDir; private DubboProtocPlugin dubboProtocPlugin; - public ProtocMetaData() { + public ProtocMetaData() {} - } - - public ProtocMetaData(String protocExecutable, File protoSourceDir, List protoFiles, File outputDir, DubboProtocPlugin dubboProtocPlugin) { + public ProtocMetaData( + String protocExecutable, + File protoSourceDir, + List protoFiles, + File outputDir, + DubboProtocPlugin dubboProtocPlugin) { this.protocExecutable = protocExecutable; this.protoSourceDir = protoSourceDir; this.protoFiles = protoFiles; @@ -40,7 +42,6 @@ public class ProtocMetaData { this.dubboProtocPlugin = dubboProtocPlugin; } - public String getProtocExecutable() { return protocExecutable; } @@ -80,6 +81,4 @@ public class ProtocMetaData { public void setDubboProtocPlugin(DubboProtocPlugin dubboProtocPlugin) { this.dubboProtocPlugin = dubboProtocPlugin; } - - } diff --git a/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/WinDubboProtocPluginWrapper.java b/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/WinDubboProtocPluginWrapper.java index f28a8c5c9f..eff281c3e8 100644 --- a/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/WinDubboProtocPluginWrapper.java +++ b/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/WinDubboProtocPluginWrapper.java @@ -16,15 +16,15 @@ */ package org.apache.dubbo.maven.plugin.protoc; -import org.apache.maven.plugin.logging.Log; -import org.codehaus.plexus.util.FileUtils; - import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.net.URL; +import org.apache.maven.plugin.logging.Log; +import org.codehaus.plexus.util.FileUtils; + public class WinDubboProtocPluginWrapper implements DubboProtocPluginWrapper { private static final String DATA_MODEL_SYSPROP = "sun.arch.data.model"; @@ -49,12 +49,14 @@ public class WinDubboProtocPluginWrapper implements DubboProtocPluginWrapper { public File createProtocPlugin(DubboProtocPlugin dubboProtocPlugin, Log log) { createPluginDirectory(dubboProtocPlugin.getPluginDirectory()); final File javaHome = new File(dubboProtocPlugin.getJavaHome()); - final File jvmLocation = findJvmLocation(javaHome, - "jre/bin/server/jvm.dll", - "bin/server/jvm.dll", - "jre/bin/client/jvm.dll", - "bin/client/jvm.dll"); - final File winRun4JIniFile = new File(dubboProtocPlugin.getPluginDirectory(), dubboProtocPlugin.getId() + ".ini"); + final File jvmLocation = findJvmLocation( + javaHome, + "jre/bin/server/jvm.dll", + "bin/server/jvm.dll", + "jre/bin/client/jvm.dll", + "bin/client/jvm.dll"); + final File winRun4JIniFile = + new File(dubboProtocPlugin.getPluginDirectory(), dubboProtocPlugin.getId() + ".ini"); if (winJvmDataModel != null) { if (!(winJvmDataModel.equals(WIN_JVM_DATA_MODEL_32) || winJvmDataModel.equals(WIN_JVM_DATA_MODEL_64))) { @@ -109,14 +111,12 @@ public class WinDubboProtocPluginWrapper implements DubboProtocPluginWrapper { out.println("[ErrorMessages]"); out.println("show.popup=false"); } catch (IOException e) { - throw new RuntimeException( - "Could not write WinRun4J ini file: " + winRun4JIniFile.getAbsolutePath(), e); + throw new RuntimeException("Could not write WinRun4J ini file: " + winRun4JIniFile.getAbsolutePath(), e); } final String executablePath = getWinrun4jExecutablePath(); final URL url = Thread.currentThread().getContextClassLoader().getResource(executablePath); if (url == null) { - throw new RuntimeException( - "Could not locate WinRun4J executable at path: " + executablePath); + throw new RuntimeException("Could not locate WinRun4J executable at path: " + executablePath); } File pluginExecutableFile = getPluginExecutableFile(dubboProtocPlugin); try { @@ -124,22 +124,22 @@ public class WinDubboProtocPluginWrapper implements DubboProtocPluginWrapper { return pluginExecutableFile; } catch (IOException e) { throw new RuntimeException( - "Could not copy WinRun4J executable to: " + pluginExecutableFile.getAbsolutePath(), e); + "Could not copy WinRun4J executable to: " + pluginExecutableFile.getAbsolutePath(), e); } } private void createPluginDirectory(File pluginDirectory) { pluginDirectory.mkdirs(); if (!pluginDirectory.isDirectory()) { - throw new RuntimeException("Could not create protoc plugin directory: " - + pluginDirectory.getAbsolutePath()); + throw new RuntimeException( + "Could not create protoc plugin directory: " + pluginDirectory.getAbsolutePath()); } } private boolean archDirectoryExists(String arch, String javaHome) { return javaHome != null - && (new File(javaHome, "jre/lib/" + arch).isDirectory() - || new File(javaHome, "lib/" + arch).isDirectory()); + && (new File(javaHome, "jre/lib/" + arch).isDirectory() + || new File(javaHome, "lib/" + arch).isDirectory()); } private String getWinrun4jExecutablePath() { @@ -149,5 +149,4 @@ public class WinDubboProtocPluginWrapper implements DubboProtocPluginWrapper { public File getPluginExecutableFile(DubboProtocPlugin dubboProtocPlugin) { return new File(dubboProtocPlugin.getPluginDirectory(), "protoc-gen-" + dubboProtocPlugin.getId() + ".exe"); } - } diff --git a/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/enums/DubboGenerateTypeEnum.java b/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/enums/DubboGenerateTypeEnum.java index 2157e6eee1..f66bb21b5b 100644 --- a/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/enums/DubboGenerateTypeEnum.java +++ b/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/enums/DubboGenerateTypeEnum.java @@ -17,16 +17,17 @@ package org.apache.dubbo.maven.plugin.protoc.enums; public enum DubboGenerateTypeEnum { - Dubbo("dubbo","org.apache.dubbo.gen.dubbo.DubboGenerator"), - Dubbo3("dubbo3","org.apache.dubbo.gen.dubbo.Dubbo3Generator"), - Tri("tri","org.apache.dubbo.gen.tri.Dubbo3TripleGenerator"), - Tri_reactor("tri_reactor","org.apache.dubbo.gen.tri.reactive.ReactorDubbo3TripleGenerator"), - Grpc("grpc","org.apache.dubbo.gen.grpc.DubboGrpcGenerator"), - Grpc_reactor("grpc_reactor","org.apache.dubbo.gen.grpc.reactive.ReactorDubboGrpcGenerator"), - Grpc_rx("grpc_rx","org.apache.dubbo.gen.grpc.reactive.RxDubboGrpcGenerator"), + Dubbo("dubbo", "org.apache.dubbo.gen.dubbo.DubboGenerator"), + Dubbo3("dubbo3", "org.apache.dubbo.gen.dubbo.Dubbo3Generator"), + Tri("tri", "org.apache.dubbo.gen.tri.Dubbo3TripleGenerator"), + Tri_reactor("tri_reactor", "org.apache.dubbo.gen.tri.reactive.ReactorDubbo3TripleGenerator"), + Grpc("grpc", "org.apache.dubbo.gen.grpc.DubboGrpcGenerator"), + Grpc_reactor("grpc_reactor", "org.apache.dubbo.gen.grpc.reactive.ReactorDubboGrpcGenerator"), + Grpc_rx("grpc_rx", "org.apache.dubbo.gen.grpc.reactive.RxDubboGrpcGenerator"), ; private String id; private String mainClass; + DubboGenerateTypeEnum(String id, String mainClass) { this.id = id; this.mainClass = mainClass; diff --git a/dubbo-metadata/dubbo-metadata-api/pom.xml b/dubbo-metadata/dubbo-metadata-api/pom.xml index 4190008795..abe5dd3752 100644 --- a/dubbo-metadata/dubbo-metadata-api/pom.xml +++ b/dubbo-metadata/dubbo-metadata-api/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-metadata - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-metadata + ${revision} + ../pom.xml + - dubbo-metadata-api - jar + dubbo-metadata-api + jar - dubbo-metadata-api - The metadata module of Dubbo project + dubbo-metadata-api + The metadata module of Dubbo project - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - true - + + + org.apache.dubbo + dubbo-rpc-api + ${project.parent.version} + true + - - org.apache.dubbo - dubbo-cluster - ${project.parent.version} - + + org.apache.dubbo + dubbo-cluster + ${project.parent.version} + - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - compile - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - compile - - - org.apache.dubbo - dubbo-metrics-metadata - ${project.parent.version} - compile - + + org.apache.dubbo + dubbo-metrics-api + ${project.parent.version} + compile + + + org.apache.dubbo + dubbo-metrics-default + ${project.parent.version} + compile + + + org.apache.dubbo + dubbo-metrics-metadata + ${project.parent.version} + compile + - - org.apache.dubbo - dubbo-native - ${project.parent.version} - + + org.apache.dubbo + dubbo-native + ${project.parent.version} + - + diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/AbstractCacheManager.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/AbstractCacheManager.java index 4a367c812a..3344115751 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/AbstractCacheManager.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/AbstractCacheManager.java @@ -45,14 +45,22 @@ public abstract class AbstractCacheManager implements Disposable { protected FileCacheStore cacheStore; protected LRUCache cache; - protected void init(boolean enableFileCache, String filePath, String fileName, int entrySize, long fileSize, int interval, ScheduledExecutorService executorService) { + protected void init( + boolean enableFileCache, + String filePath, + String fileName, + int entrySize, + long fileSize, + int interval, + ScheduledExecutorService executorService) { this.cache = new LRUCache<>(entrySize); try { cacheStore = FileCacheStoreFactory.getInstance(filePath, fileName, enableFileCache); Map properties = cacheStore.loadCache(entrySize); if (logger.isDebugEnabled()) { - logger.debug("Successfully loaded " + getName() + " cache from file " + fileName + ", entries " + properties.size()); + logger.debug("Successfully loaded " + getName() + " cache from file " + fileName + ", entries " + + properties.size()); } for (Map.Entry entry : properties.entrySet()) { String key = entry.getKey(); @@ -61,12 +69,17 @@ public abstract class AbstractCacheManager implements Disposable { } // executorService can be empty if FileCacheStore fails if (executorService == null) { - this.executorService = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-cache-refreshing-scheduler", true)); + this.executorService = Executors.newSingleThreadScheduledExecutor( + new NamedThreadFactory("Dubbo-cache-refreshing-scheduler", true)); } else { this.executorService = executorService; } - this.executorService.scheduleWithFixedDelay(new CacheRefreshTask<>(this.cacheStore, this.cache, this, fileSize), 10, interval, TimeUnit.MINUTES); + this.executorService.scheduleWithFixedDelay( + new CacheRefreshTask<>(this.cacheStore, this.cache, this, fileSize), + 10, + interval, + TimeUnit.MINUTES); } catch (Exception e) { logger.error(COMMON_FAILED_LOAD_MAPPING_CACHE, "", "", "Load mapping from local cache file error ", e); } @@ -116,10 +129,9 @@ public abstract class AbstractCacheManager implements Disposable { executorService.shutdownNow(); try { if (!executorService.awaitTermination( - ConfigurationUtils.reCalShutdownTime(DEFAULT_SERVER_SHUTDOWN_TIMEOUT), - TimeUnit.MILLISECONDS)) { - logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", - "Wait global executor service terminated timeout."); + ConfigurationUtils.reCalShutdownTime(DEFAULT_SERVER_SHUTDOWN_TIMEOUT), TimeUnit.MILLISECONDS)) { + logger.warn( + COMMON_UNEXPECTED_EXCEPTION, "", "", "Wait global executor service terminated timeout."); } } catch (InterruptedException e) { logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "destroy resources failed: " + e.getMessage(), e); @@ -141,7 +153,11 @@ public abstract class AbstractCacheManager implements Disposable { private final AbstractCacheManager cacheManager; private final long maxFileSize; - public CacheRefreshTask(FileCacheStore cacheStore, LRUCache cache, AbstractCacheManager cacheManager, long maxFileSize) { + public CacheRefreshTask( + FileCacheStore cacheStore, + LRUCache cache, + AbstractCacheManager cacheManager, + long maxFileSize) { this.cacheStore = cacheStore; this.cache = cache; this.cacheManager = cacheManager; diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/AbstractServiceNameMapping.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/AbstractServiceNameMapping.java index 6ed85622ee..d26684a512 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/AbstractServiceNameMapping.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/AbstractServiceNameMapping.java @@ -57,14 +57,19 @@ public abstract class AbstractServiceNameMapping implements ServiceNameMapping { public AbstractServiceNameMapping(ApplicationModel applicationModel) { this.applicationModel = applicationModel; boolean enableFileCache = true; - Optional application = applicationModel.getApplicationConfigManager().getApplication(); + Optional application = + applicationModel.getApplicationConfigManager().getApplication(); if (application.isPresent()) { enableFileCache = Boolean.TRUE.equals(application.get().getEnableFileCache()) ? true : false; } - this.mappingCacheManager = new MappingCacheManager(enableFileCache, - applicationModel.tryGetApplicationName(), - applicationModel.getFrameworkModel().getBeanFactory() - .getBean(FrameworkExecutorRepository.class).getCacheRefreshingScheduledExecutor()); + this.mappingCacheManager = new MappingCacheManager( + enableFileCache, + applicationModel.tryGetApplicationName(), + applicationModel + .getFrameworkModel() + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class) + .getCacheRefreshingScheduledExecutor()); } // just for test @@ -77,16 +82,16 @@ public abstract class AbstractServiceNameMapping implements ServiceNameMapping { * * @return */ - abstract public Set get(URL url); + public abstract Set get(URL url); /** * Get the service names from the specified Dubbo service interface, group, version and protocol * * @return */ - abstract public Set getAndListen(URL url, MappingListener mappingListener); + public abstract Set getAndListen(URL url, MappingListener mappingListener); - abstract protected void removeListener(URL url, MappingListener mappingListener); + protected abstract void removeListener(URL url, MappingListener mappingListener); @Override public Set getAndListen(URL registryURL, URL subscribedURL, MappingListener listener) { @@ -105,7 +110,8 @@ public abstract class AbstractServiceNameMapping implements ServiceNameMapping { if (CollectionUtils.isEmpty(mappingServices)) { String registryServices = registryURL.getParameter(SUBSCRIBED_SERVICE_NAMES_KEY); if (StringUtils.isNotEmpty(registryServices)) { - logger.info(subscribedURL.getServiceInterface() + " mapping to " + registryServices + " instructed by registry subscribed-services."); + logger.info(subscribedURL.getServiceInterface() + " mapping to " + registryServices + + " instructed by registry subscribed-services."); mappingServices = parseServices(registryServices); } } @@ -113,8 +119,11 @@ public abstract class AbstractServiceNameMapping implements ServiceNameMapping { this.putCachedMapping(ServiceNameMapping.buildMappingKey(subscribedURL), mappingServices); } } else { - ExecutorService executorService = applicationModel.getFrameworkModel().getBeanFactory() - .getBean(FrameworkExecutorRepository.class).getMappingRefreshingExecutor(); + ExecutorService executorService = applicationModel + .getFrameworkModel() + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class) + .getMappingRefreshingExecutor(); executorService.submit(new AsyncMappingTask(listener, subscribedURL, true)); } @@ -127,7 +136,7 @@ public abstract class AbstractServiceNameMapping implements ServiceNameMapping { if (listener != null) { String mappingKey = ServiceNameMapping.buildMappingKey(subscribeURL); Set listeners = mappingListeners.get(mappingKey); - //todo, remove listener from remote metadata center + // todo, remove listener from remote metadata center if (CollectionUtils.isNotEmpty(listeners)) { listeners.remove(listener); listener.stop(); @@ -144,11 +153,12 @@ public abstract class AbstractServiceNameMapping implements ServiceNameMapping { } static Set parseServices(String literalServices) { - return isBlank(literalServices) ? emptySet() : - unmodifiableSet(new TreeSet<>(of(literalServices.split(",")) - .map(String::trim) - .filter(StringUtils::isNotEmpty) - .collect(toSet()))); + return isBlank(literalServices) + ? emptySet() + : unmodifiableSet(new TreeSet<>(of(literalServices.split(",")) + .map(String::trim) + .filter(StringUtils::isNotEmpty) + .collect(toSet()))); } @Override @@ -171,7 +181,7 @@ public abstract class AbstractServiceNameMapping implements ServiceNameMapping { @Override public Set getMapping(URL consumerURL) { Set mappingByUrl = ServiceNameMapping.getMappingByUrl(consumerURL); - if(mappingByUrl != null) { + if (mappingByUrl != null) { return mappingByUrl; } return mappingCacheManager.get(ServiceNameMapping.buildMappingKey(consumerURL)); @@ -229,11 +239,13 @@ public abstract class AbstractServiceNameMapping implements ServiceNameMapping { String mappingKey = ServiceNameMapping.buildMappingKey(subscribedURL); if (listener != null) { mappedServices = toTreeSet(getAndListen(subscribedURL, listener)); - Set listeners = mappingListeners.computeIfAbsent(mappingKey, _k -> new HashSet<>()); + Set listeners = + mappingListeners.computeIfAbsent(mappingKey, _k -> new HashSet<>()); listeners.add(listener); if (CollectionUtils.isNotEmpty(mappedServices)) { if (notifyAtFirstTime) { - // guarantee at-least-once notification no matter what kind of underlying meta server is used. + // guarantee at-least-once notification no matter what kind of underlying meta server is + // used. // listener notification will also cause updating of mapping cache. listener.onEvent(new MappingChangedEvent(mappingKey, mappedServices)); } @@ -245,7 +257,12 @@ public abstract class AbstractServiceNameMapping implements ServiceNameMapping { } } } catch (Exception e) { - logger.error(COMMON_FAILED_LOAD_MAPPING_CACHE, "", "", "Failed getting mapping info from remote center. ", e); + logger.error( + COMMON_FAILED_LOAD_MAPPING_CACHE, + "", + "", + "Failed getting mapping info from remote center. ", + e); } return mappedServices; } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/DefaultMetadataParamsFilter.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/DefaultMetadataParamsFilter.java index 241ba8c839..7f6aab282b 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/DefaultMetadataParamsFilter.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/DefaultMetadataParamsFilter.java @@ -38,10 +38,22 @@ public class DefaultMetadataParamsFilter implements MetadataParamsFilter { private final String[] includedInstanceParams; public DefaultMetadataParamsFilter() { - this.includedInstanceParams = new String[]{HEARTBEAT_TIMEOUT_KEY, TIMESTAMP_KEY, IPV6_KEY}; - this.excludedServiceParams = new String[]{MONITOR_KEY, BIND_IP_KEY, BIND_PORT_KEY, QOS_ENABLE, - QOS_HOST, QOS_PORT, ACCEPT_FOREIGN_IP, VALIDATION_KEY, INTERFACES, PID_KEY, TIMESTAMP_KEY, HEARTBEAT_TIMEOUT_KEY, - IPV6_KEY}; + this.includedInstanceParams = new String[] {HEARTBEAT_TIMEOUT_KEY, TIMESTAMP_KEY, IPV6_KEY}; + this.excludedServiceParams = new String[] { + MONITOR_KEY, + BIND_IP_KEY, + BIND_PORT_KEY, + QOS_ENABLE, + QOS_HOST, + QOS_PORT, + ACCEPT_FOREIGN_IP, + VALIDATION_KEY, + INTERFACES, + PID_KEY, + TIMESTAMP_KEY, + HEARTBEAT_TIMEOUT_KEY, + IPV6_KEY + }; } @Override diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MappingCacheManager.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MappingCacheManager.java index 4af42d4a3f..ca23dbf178 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MappingCacheManager.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MappingCacheManager.java @@ -53,7 +53,7 @@ public class MappingCacheManager extends AbstractCacheManager> { String rawMaxFileSize = System.getProperty("dubbo.mapping.cache.maxFileSize"); long maxFileSize = StringUtils.parseLong(rawMaxFileSize); - init(enableFileCache, filePath, fileName, entrySize, maxFileSize, 50, executorService); + init(enableFileCache, filePath, fileName, entrySize, maxFileSize, 50, executorService); } @Override diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MappingChangedEvent.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MappingChangedEvent.java index a1c40f0f91..3a81cd7bf1 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MappingChangedEvent.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MappingChangedEvent.java @@ -38,7 +38,6 @@ public class MappingChangedEvent { @Override public String toString() { - return "{serviceKey: " + serviceKey + ", apps: " + - apps.toString() + "}"; + return "{serviceKey: " + serviceKey + ", apps: " + apps.toString() + "}"; } } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataConstants.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataConstants.java index 0ec12681ab..8b808d7b24 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataConstants.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataConstants.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata; - public interface MetadataConstants { String KEY_SEPARATOR = ":"; String DEFAULT_PATH_TAG = "metadata"; diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataInfo.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataInfo.java index 26665790d4..0a2f8c698b 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataInfo.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataInfo.java @@ -60,19 +60,21 @@ public class MetadataInfo implements Serializable { private static final Logger logger = LoggerFactory.getLogger(MetadataInfo.class); private String app; - // revision that will report to registry or remote meta center, must always update together with rawMetadataInfo, check {@link this#calAndGetRevision} + // revision that will report to registry or remote meta center, must always update together with rawMetadataInfo, + // check {@link this#calAndGetRevision} private volatile String revision; // key format is '{group}/{interface name}:{version}:{protocol}' private final Map services; /* used at runtime */ private transient AtomicBoolean initiated = new AtomicBoolean(false); - // Json formatted metadata that will report to remote meta center, must always update together with revision, check {@link this#calAndGetRevision} + // Json formatted metadata that will report to remote meta center, must always update together with revision, check + // {@link this#calAndGetRevision} private transient volatile String rawMetadataInfo; // key format is '{group}/{interface name}:{version}' private transient Map> subscribedServices; - private transient final Map extendParams; - private transient final Map instanceParams; + private final transient Map extendParams; + private final transient Map instanceParams; protected transient volatile boolean updated = false; private transient ConcurrentNavigableMap> subscribedServiceURLs; private transient ConcurrentNavigableMap> exportedServiceURLs; @@ -94,11 +96,17 @@ public class MetadataInfo implements Serializable { this.instanceParams = new ConcurrentHashMap<>(); } - private MetadataInfo(String app, String revision, Map services, AtomicBoolean initiated, - Map extendParams, Map instanceParams, boolean updated, - ConcurrentNavigableMap> subscribedServiceURLs, - ConcurrentNavigableMap> exportedServiceURLs, - ExtensionLoader loader) { + private MetadataInfo( + String app, + String revision, + Map services, + AtomicBoolean initiated, + Map extendParams, + Map instanceParams, + boolean updated, + ConcurrentNavigableMap> subscribedServiceURLs, + ConcurrentNavigableMap> exportedServiceURLs, + ExtensionLoader loader) { this.app = app; this.revision = revision; this.services = new ConcurrentHashMap<>(services); @@ -106,8 +114,10 @@ public class MetadataInfo implements Serializable { this.extendParams = new ConcurrentHashMap<>(extendParams); this.instanceParams = new ConcurrentHashMap<>(instanceParams); this.updated = updated; - this.subscribedServiceURLs = subscribedServiceURLs == null ? null : new ConcurrentSkipListMap<>(subscribedServiceURLs); - this.exportedServiceURLs = exportedServiceURLs == null ? null : new ConcurrentSkipListMap<>(exportedServiceURLs); + this.subscribedServiceURLs = + subscribedServiceURLs == null ? null : new ConcurrentSkipListMap<>(subscribedServiceURLs); + this.exportedServiceURLs = + exportedServiceURLs == null ? null : new ConcurrentSkipListMap<>(exportedServiceURLs); this.loader = loader; } @@ -121,11 +131,13 @@ public class MetadataInfo implements Serializable { if (CollectionUtils.isNotEmptyMap(services)) { services.forEach((_k, serviceInfo) -> { serviceInfo.init(); - // create duplicate serviceKey(without protocol)->serviceInfo mapping to support metadata search when protocol is not specified on consumer side. + // create duplicate serviceKey(without protocol)->serviceInfo mapping to support metadata search when + // protocol is not specified on consumer side. if (subscribedServices == null) { subscribedServices = new HashMap<>(); } - Set serviceInfos = subscribedServices.computeIfAbsent(serviceInfo.getServiceKey(), _key -> new HashSet<>()); + Set serviceInfos = + subscribedServices.computeIfAbsent(serviceInfo.getServiceKey(), _key -> new HashSet<>()); serviceInfos.add(serviceInfo); }); } @@ -189,7 +201,9 @@ public class MetadataInfo implements Serializable { String tempRevision = RevisionResolver.calRevision(sb.toString()); if (!StringUtils.isEquals(this.revision, tempRevision)) { if (logger.isInfoEnabled()) { - logger.info(String.format("metadata revision changed: %s -> %s, app: %s, services: %d", this.revision, tempRevision, this.app, this.services.size())); + logger.info(String.format( + "metadata revision changed: %s -> %s, app: %s, services: %d", + this.revision, tempRevision, this.app, this.services.size())); } this.revision = tempRevision; this.rawMetadataInfo = JsonUtils.toJson(this); @@ -241,7 +255,9 @@ public class MetadataInfo implements Serializable { } Set subServices = subscribedServices.get(serviceKeyWithoutProtocol); if (CollectionUtils.isNotEmpty(subServices)) { - List validServices = subServices.stream().filter(serviceInfo -> StringUtils.isEmpty(serviceInfo.getParameter(IS_EXTRA))).collect(Collectors.toList()); + List validServices = subServices.stream() + .filter(serviceInfo -> StringUtils.isEmpty(serviceInfo.getParameter(IS_EXTRA))) + .collect(Collectors.toList()); if (CollectionUtils.isNotEmpty(validServices)) { return validServices.iterator().next(); } else { @@ -263,10 +279,9 @@ public class MetadataInfo implements Serializable { } public List getMatchedServiceInfos(ProtocolServiceKey consumerProtocolServiceKey) { - return getServices().values() - .stream() - .filter(serviceInfo -> serviceInfo.matchProtocolServiceKey(consumerProtocolServiceKey)) - .collect(Collectors.toList()); + return getServices().values().stream() + .filter(serviceInfo -> serviceInfo.matchProtocolServiceKey(consumerProtocolServiceKey)) + .collect(Collectors.toList()); } public Map getExtendParams() { @@ -330,9 +345,9 @@ public class MetadataInfo implements Serializable { return Collections.emptySet(); } return exportedServiceURLs.values().stream() - .filter(CollectionUtils::isNotEmpty) - .flatMap(Collection::stream) - .collect(Collectors.toSet()); + .filter(CollectionUtils::isNotEmpty) + .flatMap(Collection::stream) + .collect(Collectors.toSet()); } private boolean addURL(Map> serviceURLs, URL url) { @@ -374,11 +389,11 @@ public class MetadataInfo implements Serializable { return false; } - MetadataInfo other = (MetadataInfo)obj; + MetadataInfo other = (MetadataInfo) obj; return Objects.equals(app, other.getApp()) - && ((services == null && other.services == null) - || (services != null && services.equals(other.services))); + && ((services == null && other.services == null) + || (services != null && services.equals(other.services))); } private void extractInstanceParams(URL url, List filters) { @@ -424,27 +439,23 @@ public class MetadataInfo implements Serializable { tmpInstanceParams.forEach((key, value) -> { String oldValue = instanceParams.put(key, value); if (!TIMESTAMP_KEY.equals(key) && oldValue != null && !oldValue.equals(value)) { - throw new IllegalStateException(String.format("Inconsistent instance metadata found in different services: %s, %s", oldValue, value)); + throw new IllegalStateException(String.format( + "Inconsistent instance metadata found in different services: %s, %s", oldValue, value)); } }); } @Override public String toString() { - return "metadata{" + - "app='" + app + "'," + - "revision='" + revision + "'," + - "size=" + (services == null ? 0 : services.size()) + "," + - "services=" + getSimplifiedServices(services) + - "}"; + return "metadata{" + "app='" + + app + "'," + "revision='" + + revision + "'," + "size=" + + (services == null ? 0 : services.size()) + "," + "services=" + + getSimplifiedServices(services) + "}"; } public String toFullString() { - return "metadata{" + - "app='" + app + "'," + - "revision='" + revision + "'," + - "services=" + services + - "}"; + return "metadata{" + "app='" + app + "'," + "revision='" + revision + "'," + "services=" + services + "}"; } private String getSimplifiedServices(Map services) { @@ -457,7 +468,17 @@ public class MetadataInfo implements Serializable { @Override public synchronized MetadataInfo clone() { - return new MetadataInfo(app, revision, services, initiated, extendParams, instanceParams, updated, subscribedServiceURLs, exportedServiceURLs, loader); + return new MetadataInfo( + app, + revision, + services, + initiated, + extendParams, + instanceParams, + updated, + subscribedServiceURLs, + exportedServiceURLs, + loader); } private Object readResolve() { @@ -475,26 +496,33 @@ public class MetadataInfo implements Serializable { private Map params; // params configured on consumer side, - private volatile transient Map consumerParams; + private transient volatile Map consumerParams; // cached method params - private volatile transient Map> methodParams; - private volatile transient Map> consumerMethodParams; + private transient volatile Map> methodParams; + private transient volatile Map> consumerMethodParams; // cached numbers - private volatile transient Map numbers; - private volatile transient Map> methodNumbers; + private transient volatile Map numbers; + private transient volatile Map> methodNumbers; // service + group + version - private volatile transient String serviceKey; + private transient volatile String serviceKey; // service + group + version + protocol - private volatile transient String matchKey; + private transient volatile String matchKey; - private volatile transient ProtocolServiceKey protocolServiceKey; + private transient volatile ProtocolServiceKey protocolServiceKey; private transient URL url; public ServiceInfo() {} public ServiceInfo(URL url, List filters) { - this(url.getServiceInterface(), url.getGroup(), url.getVersion(), url.getProtocol(), url.getPort(), url.getPath(), null); + this( + url.getServiceInterface(), + url.getGroup(), + url.getVersion(), + url.getProtocol(), + url.getPort(), + url.getPath(), + null); this.url = url; Map params = extractServiceParams(url, filters); // initialize method params caches. @@ -502,7 +530,14 @@ public class MetadataInfo implements Serializable { this.consumerMethodParams = URLParam.initMethodParameters(consumerParams); } - public ServiceInfo(String name, String group, String version, String protocol, int port, String path, Map params) { + public ServiceInfo( + String name, + String group, + String version, + String protocol, + int port, + String path, + Map params) { this.name = name; this.group = group; this.version = version; @@ -594,7 +629,7 @@ public class MetadataInfo implements Serializable { this.methodParams = URLParam.initMethodParameters(params); // Actually, consumer params is empty after deserialized on the consumer side, so no need to initialize. // Check how InstanceAddressURL operates on consumer url for more detail. -// this.consumerMethodParams = URLParam.initMethodParameters(consumerParams); + // this.consumerMethodParams = URLParam.initMethodParameters(consumerParams); // no need to init numbers for it's only for cache purpose } @@ -622,7 +657,7 @@ public class MetadataInfo implements Serializable { if (protocolServiceKey != null) { return protocolServiceKey; } - protocolServiceKey = new ProtocolServiceKey(name, version, group, protocol); + protocolServiceKey = new ProtocolServiceKey(name, version, group, protocol); return protocolServiceKey; } @@ -701,7 +736,8 @@ public class MetadataInfo implements Serializable { @Transient public Map getAllParams() { if (consumerParams != null) { - Map allParams = new HashMap<>((int) ((params.size() + consumerParams.size()) / 0.75f + 1)); + Map allParams = + new HashMap<>((int) ((params.size() + consumerParams.size()) / 0.75f + 1)); allParams.putAll(params); allParams.putAll(consumerParams); return allParams; @@ -748,7 +784,7 @@ public class MetadataInfo implements Serializable { public boolean hasMethodParameter(String method) { return (consumerMethodParams != null && consumerMethodParams.containsKey(method)) - || (methodParams != null && methodParams.containsKey(method)); + || (methodParams != null && methodParams.containsKey(method)); } public String toDescString() { @@ -814,11 +850,11 @@ public class MetadataInfo implements Serializable { * on json deserialization. */ return Objects.equals(this.getVersion(), serviceInfo.getVersion()) - && Objects.equals(this.getGroup(), serviceInfo.getGroup()) - && Objects.equals(this.getName(), serviceInfo.getName()) - && Objects.equals(this.getProtocol(), serviceInfo.getProtocol()) - && Objects.equals(this.getPort(), serviceInfo.getPort()) - && this.getParams().equals(serviceInfo.getParams()); + && Objects.equals(this.getGroup(), serviceInfo.getGroup()) + && Objects.equals(this.getName(), serviceInfo.getName()) + && Objects.equals(this.getProtocol(), serviceInfo.getProtocol()) + && Objects.equals(this.getPort(), serviceInfo.getPort()) + && this.getParams().equals(serviceInfo.getParams()); } @Override @@ -832,14 +868,13 @@ public class MetadataInfo implements Serializable { } public String toFullString() { - return "service{" + - "name='" + name + "'," + - "group='" + group + "'," + - "version='" + version + "'," + - "protocol='" + protocol + "'," + - "port='" + port + "'," + - "params=" + params + "," + - "}"; + return "service{" + "name='" + + name + "'," + "group='" + + group + "'," + "version='" + + version + "'," + "protocol='" + + protocol + "'," + "port='" + + port + "'," + "params=" + + params + "," + "}"; } } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataParamsFilter.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataParamsFilter.java index 18e7105715..6bd42d386c 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataParamsFilter.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataParamsFilter.java @@ -32,14 +32,14 @@ import org.apache.dubbo.common.extension.SPI; @SPI public interface MetadataParamsFilter { - /** - * params that need to be sent to metadata center - * - * @return arrays of keys - */ - default String[] serviceParamsIncluded() { - return new String[0]; - } + /** + * params that need to be sent to metadata center + * + * @return arrays of keys + */ + default String[] serviceParamsIncluded() { + return new String[0]; + } /** * params that need to be excluded before sending to metadata center diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataServiceDetector.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataServiceDetector.java index a992cdc586..ff9b016701 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataServiceDetector.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataServiceDetector.java @@ -24,5 +24,4 @@ public class MetadataServiceDetector implements BuiltinServiceDetector { public Class getService() { return MetadataService.class; } - } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ParameterTypesComparator.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ParameterTypesComparator.java index 35527d0356..ecc4d29618 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ParameterTypesComparator.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ParameterTypesComparator.java @@ -22,7 +22,6 @@ public class ParameterTypesComparator { private Class[] parameterTypes; - public ParameterTypesComparator(Class[] parameterTypes) { this.parameterTypes = parameterTypes; } @@ -40,10 +39,7 @@ public class ParameterTypesComparator { return Arrays.hashCode(parameterTypes); } - public static ParameterTypesComparator getInstance(Class[] parameterTypes) { return new ParameterTypesComparator(parameterTypes); } - - } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/RevisionResolver.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/RevisionResolver.java index a1c9e19169..9284289f59 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/RevisionResolver.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/RevisionResolver.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata; - import org.apache.dubbo.common.utils.MD5Utils; public class RevisionResolver { @@ -28,5 +27,4 @@ public class RevisionResolver { public static String calRevision(String metadata) { return md5Utils.getMd5(metadata); } - } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java index 8987249053..e2c58e69eb 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java @@ -64,8 +64,8 @@ public interface ServiceNameMapping extends Destroyable { } static String buildGroup(String serviceInterface) { - //the issue : https://github.com/apache/dubbo/issues/4671 -// return DEFAULT_MAPPING_GROUP + SLASH + serviceInterface; + // the issue : https://github.com/apache/dubbo/issues/4671 + // return DEFAULT_MAPPING_GROUP + SLASH + serviceInterface; return serviceInterface; } @@ -93,7 +93,7 @@ public interface ServiceNameMapping extends Destroyable { static Set getMappingByUrl(URL consumerURL) { String providedBy = consumerURL.getParameter(RegistryConstants.PROVIDED_BY); - if(StringUtils.isBlank(providedBy)) { + if (StringUtils.isBlank(providedBy)) { return null; } return AbstractServiceNameMapping.parseServices(providedBy); diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/aot/MetadataReflectionTypeDescriberRegistrar.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/aot/MetadataReflectionTypeDescriberRegistrar.java index 46ba6b2e04..52450d866e 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/aot/MetadataReflectionTypeDescriberRegistrar.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/aot/MetadataReflectionTypeDescriberRegistrar.java @@ -27,7 +27,6 @@ import java.util.HashSet; import java.util.List; import java.util.Set; - public class MetadataReflectionTypeDescriberRegistrar implements ReflectionTypeDescriberRegistrar { @Override @@ -41,12 +40,14 @@ public class MetadataReflectionTypeDescriberRegistrar implements ReflectionTypeD private TypeDescriber buildTypeDescriberWithPublicMethod(Class cl) { Set memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.INVOKE_PUBLIC_METHODS); - return new TypeDescriber(cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); + return new TypeDescriber( + cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } private TypeDescriber buildTypeDescriberWithDeclaredConstructors(Class cl) { Set memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); - return new TypeDescriber(cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); + return new TypeDescriber( + cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReport.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReport.java index b871dc7424..b4668948d2 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReport.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.report; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigItem; import org.apache.dubbo.metadata.MappingListener; @@ -42,11 +41,9 @@ public interface MetadataReport { /** * Application Metadata -- START **/ - default void publishAppMetadata(SubscriberMetadataIdentifier identifier, MetadataInfo metadataInfo) { - } + default void publishAppMetadata(SubscriberMetadataIdentifier identifier, MetadataInfo metadataInfo) {} - default void unPublishAppMetadata(SubscriberMetadataIdentifier identifier, MetadataInfo metadataInfo) { - } + default void unPublishAppMetadata(SubscriberMetadataIdentifier identifier, MetadataInfo metadataInfo) {} default MetadataInfo getAppMetadata(SubscriberMetadataIdentifier identifier, Map instanceMetadata) { return null; @@ -73,7 +70,8 @@ public interface MetadataReport { return new ConfigItem(); } - default boolean registerServiceAppMapping(String serviceInterface, String defaultMappingGroup, String newConfigContent, Object ticket) { + default boolean registerServiceAppMapping( + String serviceInterface, String defaultMappingGroup, String newConfigContent, Object ticket) { return false; } @@ -81,9 +79,7 @@ public interface MetadataReport { return false; } - default void removeServiceAppMappingListener(String serviceKey, MappingListener listener) { - - } + default void removeServiceAppMappingListener(String serviceKey, MappingListener listener) {} /** * Service<-->Application Mapping -- START @@ -99,5 +95,4 @@ public interface MetadataReport { boolean shouldReportDefinition(); boolean shouldReportMetadata(); - } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportFactory.java index a0e1bb2e2a..44340244e0 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportFactory.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportFactory.java @@ -33,6 +33,5 @@ public interface MetadataReportFactory { @Adaptive({PROTOCOL_KEY}) MetadataReport getMetadataReport(URL url); - default void destroy() { - } + default void destroy() {} } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportInstance.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportInstance.java index 264d6a18f9..3fd14dff0b 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportInstance.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportInstance.java @@ -55,7 +55,8 @@ public class MetadataReportInstance implements Disposable { private AtomicBoolean init = new AtomicBoolean(false); private String metadataType; - // mapping of registry id to metadata report instance, registry instances will use this mapping to find related metadata reports + // mapping of registry id to metadata report instance, registry instances will use this mapping to find related + // metadata reports private final Map metadataReports = new HashMap<>(); private final ApplicationModel applicationModel; private final NopMetadataReport nopMetadataReport; @@ -70,12 +71,16 @@ public class MetadataReportInstance implements Disposable { return; } - this.metadataType = applicationModel.getApplicationConfigManager().getApplicationOrElseThrow().getMetadataType(); + this.metadataType = applicationModel + .getApplicationConfigManager() + .getApplicationOrElseThrow() + .getMetadataType(); if (metadataType == null) { this.metadataType = DEFAULT_METADATA_STORAGE_TYPE; } - MetadataReportFactory metadataReportFactory = applicationModel.getExtensionLoader(MetadataReportFactory.class).getAdaptiveExtension(); + MetadataReportFactory metadataReportFactory = + applicationModel.getExtensionLoader(MetadataReportFactory.class).getAdaptiveExtension(); for (MetadataReportConfig metadataReportConfig : metadataReportConfigs) { init(metadataReportConfig, metadataReportFactory); } @@ -92,11 +97,17 @@ public class MetadataReportInstance implements Disposable { .removeParameter(METADATA_REPORT_KEY) .build(); } - url = url.addParameterIfAbsent(APPLICATION_KEY, applicationModel.getCurrentConfig().getName()); - url = url.addParameterIfAbsent(REGISTRY_LOCAL_FILE_CACHE_ENABLED, String.valueOf(applicationModel.getCurrentConfig().getEnableFileCache())); - String relatedRegistryId = isEmpty(config.getRegistry()) ? (isEmpty(config.getId()) ? DEFAULT_KEY : config.getId()) : config.getRegistry(); -// RegistryConfig registryConfig = applicationModel.getConfigManager().getRegistry(relatedRegistryId) -// .orElseThrow(() -> new IllegalStateException("Registry id " + relatedRegistryId + " does not exist.")); + url = url.addParameterIfAbsent( + APPLICATION_KEY, applicationModel.getCurrentConfig().getName()); + url = url.addParameterIfAbsent( + REGISTRY_LOCAL_FILE_CACHE_ENABLED, + String.valueOf(applicationModel.getCurrentConfig().getEnableFileCache())); + String relatedRegistryId = isEmpty(config.getRegistry()) + ? (isEmpty(config.getId()) ? DEFAULT_KEY : config.getId()) + : config.getRegistry(); + // RegistryConfig registryConfig = applicationModel.getConfigManager().getRegistry(relatedRegistryId) + // .orElseThrow(() -> new IllegalStateException("Registry id " + relatedRegistryId + " does not + // exist.")); MetadataReport metadataReport = metadataReportFactory.getMetadataReport(url); if (metadataReport != null) { metadataReports.put(relatedRegistryId, metadataReport); diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataScopeModelInitializer.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataScopeModelInitializer.java index c88eaf774a..ce16b2b95f 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataScopeModelInitializer.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataScopeModelInitializer.java @@ -24,9 +24,7 @@ import org.apache.dubbo.rpc.model.ScopeModelInitializer; public class MetadataScopeModelInitializer implements ScopeModelInitializer { @Override - public void initializeFrameworkModel(FrameworkModel frameworkModel) { - - } + public void initializeFrameworkModel(FrameworkModel frameworkModel) {} @Override public void initializeApplicationModel(ApplicationModel applicationModel) { @@ -35,7 +33,5 @@ public class MetadataScopeModelInitializer implements ScopeModelInitializer { } @Override - public void initializeModuleModel(ModuleModel moduleModel) { - - } + public void initializeModuleModel(ModuleModel moduleModel) {} } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/BaseApplicationMetadataIdentifier.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/BaseApplicationMetadataIdentifier.java index 591a1a70b9..3838e43926 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/BaseApplicationMetadataIdentifier.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/BaseApplicationMetadataIdentifier.java @@ -34,7 +34,7 @@ public class BaseApplicationMetadataIdentifier { } protected String getIdentifierKey(String... params) { - return KeyTypeEnum.UNIQUE_KEY.build(application,params); + return KeyTypeEnum.UNIQUE_KEY.build(application, params); } private String getFilePathKey(String... params) { @@ -45,5 +45,4 @@ public class BaseApplicationMetadataIdentifier { String prefix = KeyTypeEnum.PATH.build(pathTag, application); return KeyTypeEnum.PATH.build(prefix, params); } - } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/BaseMetadataIdentifier.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/BaseMetadataIdentifier.java index dded259cdd..496d69fb60 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/BaseMetadataIdentifier.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/BaseMetadataIdentifier.java @@ -21,5 +21,4 @@ public interface BaseMetadataIdentifier { String getUniqueKey(KeyTypeEnum keyType); String getIdentifierKey(); - } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/KeyTypeEnum.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/KeyTypeEnum.java index 3253f85a73..cb9c0aa463 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/KeyTypeEnum.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/KeyTypeEnum.java @@ -26,7 +26,6 @@ import static org.apache.dubbo.metadata.MetadataConstants.KEY_SEPARATOR; * 2019-08-15 */ public enum KeyTypeEnum { - PATH(PATH_SEPARATOR) { public String build(String one, String... others) { return buildPath(one, others); @@ -58,5 +57,4 @@ public enum KeyTypeEnum { * @since 2.7.8 */ public abstract String build(String one, String... others); - } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/MetadataIdentifier.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/MetadataIdentifier.java index 1e5b8919f0..b5501ae6a3 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/MetadataIdentifier.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/MetadataIdentifier.java @@ -29,8 +29,7 @@ public class MetadataIdentifier extends BaseServiceMetadataIdentifier implements private String application; - public MetadataIdentifier() { - } + public MetadataIdentifier() {} public MetadataIdentifier(String serviceInterface, String version, String group, String side, String application) { this.serviceInterface = serviceInterface; @@ -40,7 +39,6 @@ public class MetadataIdentifier extends BaseServiceMetadataIdentifier implements this.application = application; } - public MetadataIdentifier(URL url) { this.serviceInterface = url.getServiceInterface(); this.version = url.getVersion(); @@ -103,12 +101,11 @@ public class MetadataIdentifier extends BaseServiceMetadataIdentifier implements @Override public String toString() { - return "MetadataIdentifier{" + - "application='" + application + '\'' + - ", serviceInterface='" + serviceInterface + '\'' + - ", version='" + version + '\'' + - ", group='" + group + '\'' + - ", side='" + side + '\'' + - '}'; + return "MetadataIdentifier{" + "application='" + + application + '\'' + ", serviceInterface='" + + serviceInterface + '\'' + ", version='" + + version + '\'' + ", group='" + + group + '\'' + ", side='" + + side + '\'' + '}'; } } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/ServiceMetadataIdentifier.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/ServiceMetadataIdentifier.java index 100d844219..4fd036b97c 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/ServiceMetadataIdentifier.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/ServiceMetadataIdentifier.java @@ -31,10 +31,10 @@ public class ServiceMetadataIdentifier extends BaseServiceMetadataIdentifier imp private String revision; private String protocol; - public ServiceMetadataIdentifier() { - } + public ServiceMetadataIdentifier() {} - public ServiceMetadataIdentifier(String serviceInterface, String version, String group, String side, String revision, String protocol) { + public ServiceMetadataIdentifier( + String serviceInterface, String version, String group, String side, String revision, String protocol) { this.serviceInterface = serviceInterface; this.version = version; this.group = group; @@ -43,7 +43,6 @@ public class ServiceMetadataIdentifier extends BaseServiceMetadataIdentifier imp this.protocol = protocol; } - public ServiceMetadataIdentifier(URL url) { this.serviceInterface = url.getServiceInterface(); this.version = url.getVersion(); @@ -70,13 +69,13 @@ public class ServiceMetadataIdentifier extends BaseServiceMetadataIdentifier imp @Override public String toString() { - return "ServiceMetadataIdentifier{" + - "revision='" + revision + '\'' + - ", protocol='" + protocol + '\'' + - ", serviceInterface='" + serviceInterface + '\'' + - ", version='" + version + '\'' + - ", group='" + group + '\'' + - ", side='" + side + '\'' + - "} " + super.toString(); + return "ServiceMetadataIdentifier{" + "revision='" + + revision + '\'' + ", protocol='" + + protocol + '\'' + ", serviceInterface='" + + serviceInterface + '\'' + ", version='" + + version + '\'' + ", group='" + + group + '\'' + ", side='" + + side + '\'' + "} " + + super.toString(); } } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/SubscriberMetadataIdentifier.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/SubscriberMetadataIdentifier.java index e375593047..12993f66f1 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/SubscriberMetadataIdentifier.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/SubscriberMetadataIdentifier.java @@ -27,15 +27,13 @@ public class SubscriberMetadataIdentifier extends BaseApplicationMetadataIdentif private String revision; - public SubscriberMetadataIdentifier() { - } + public SubscriberMetadataIdentifier() {} public SubscriberMetadataIdentifier(String application, String revision) { this.application = application; this.revision = revision; } - public SubscriberMetadataIdentifier(URL url) { this.application = url.getApplication(""); this.revision = url.getParameter(REVISION_KEY, ""); @@ -64,6 +62,4 @@ public class SubscriberMetadataIdentifier extends BaseApplicationMetadataIdentif public void setRevision(String revision) { this.revision = revision; } - - } diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java index 1c26581a95..a1575f00f1 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java @@ -82,16 +82,18 @@ import static org.apache.dubbo.metadata.report.support.Constants.USER_HOME; public abstract class AbstractMetadataReport implements MetadataReport { - protected final static String DEFAULT_ROOT = "dubbo"; + protected static final String DEFAULT_ROOT = "dubbo"; private static final int ONE_DAY_IN_MILLISECONDS = 60 * 24 * 60 * 1000; private static final int FOUR_HOURS_IN_MILLISECONDS = 60 * 4 * 60 * 1000; // Log output protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); - // Local disk cache, where the special key value.registries records the list of metadata centers, and the others are the list of notified service providers + // Local disk cache, where the special key value.registries records the list of metadata centers, and the others are + // the list of notified service providers final Properties properties = new Properties(); - private final ExecutorService reportCacheExecutor = Executors.newFixedThreadPool(1, new NamedThreadFactory("DubboSaveMetadataReport", true)); + private final ExecutorService reportCacheExecutor = + Executors.newFixedThreadPool(1, new NamedThreadFactory("DubboSaveMetadataReport", true)); final Map allMetadataReports = new ConcurrentHashMap<>(4); private final AtomicLong lastCacheChanged = new AtomicLong(); @@ -114,16 +116,19 @@ public abstract class AbstractMetadataReport implements MetadataReport { boolean localCacheEnabled = reportServerURL.getParameter(REGISTRY_LOCAL_FILE_CACHE_ENABLED, true); // Start file save timer - String defaultFilename = System.getProperty(USER_HOME) + DUBBO_METADATA + - reportServerURL.getApplication() + "-" + - replace(reportServerURL.getAddress(), ":", "-") + CACHE; + String defaultFilename = System.getProperty(USER_HOME) + DUBBO_METADATA + reportServerURL.getApplication() + + "-" + replace(reportServerURL.getAddress(), ":", "-") + + CACHE; String filename = reportServerURL.getParameter(FILE_KEY, defaultFilename); File file = null; if (localCacheEnabled && ConfigUtils.isNotEmpty(filename)) { file = new File(filename); - if (!file.exists() && file.getParentFile() != null && !file.getParentFile().exists()) { + if (!file.exists() + && file.getParentFile() != null + && !file.getParentFile().exists()) { if (!file.getParentFile().mkdirs()) { - throw new IllegalArgumentException("Invalid service store file " + file + ", cause: Failed to create directory " + file.getParentFile() + "!"); + throw new IllegalArgumentException("Invalid service store file " + file + + ", cause: Failed to create directory " + file.getParentFile() + "!"); } } // if this file exists, firstly delete it. @@ -134,12 +139,15 @@ public abstract class AbstractMetadataReport implements MetadataReport { this.file = file; loadProperties(); syncReport = reportServerURL.getParameter(SYNC_REPORT_KEY, false); - metadataReportRetry = new MetadataReportRetry(reportServerURL.getParameter(RETRY_TIMES_KEY, DEFAULT_METADATA_REPORT_RETRY_TIMES), - reportServerURL.getParameter(RETRY_PERIOD_KEY, DEFAULT_METADATA_REPORT_RETRY_PERIOD)); + metadataReportRetry = new MetadataReportRetry( + reportServerURL.getParameter(RETRY_TIMES_KEY, DEFAULT_METADATA_REPORT_RETRY_TIMES), + reportServerURL.getParameter(RETRY_PERIOD_KEY, DEFAULT_METADATA_REPORT_RETRY_PERIOD)); // cycle report the data switch if (reportServerURL.getParameter(CYCLE_REPORT_KEY, DEFAULT_METADATA_REPORT_CYCLE_REPORT)) { - reportTimerScheduler = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("DubboMetadataReportTimer", true)); - reportTimerScheduler.scheduleAtFixedRate(this::publishAll, calculateStartTime(), ONE_DAY_IN_MILLISECONDS, TimeUnit.MILLISECONDS); + reportTimerScheduler = Executors.newSingleThreadScheduledExecutor( + new NamedThreadFactory("DubboMetadataReportTimer", true)); + reportTimerScheduler.scheduleAtFixedRate( + this::publishAll, calculateStartTime(), ONE_DAY_IN_MILLISECONDS, TimeUnit.MILLISECONDS); } this.reportMetadata = reportServerURL.getParameter(REPORT_METADATA_KEY, false); @@ -171,10 +179,12 @@ public abstract class AbstractMetadataReport implements MetadataReport { lockfile.createNewFile(); } try (RandomAccessFile raf = new RandomAccessFile(lockfile, "rw"); - FileChannel channel = raf.getChannel()) { + FileChannel channel = raf.getChannel()) { FileLock lock = channel.tryLock(); if (lock == null) { - throw new IOException("Can not lock the metadataReport cache file " + file.getAbsolutePath() + ", ignore and retry later, maybe multi java process use the file, please config: dubbo.metadata.file=xxx.properties"); + throw new IOException( + "Can not lock the metadataReport cache file " + file.getAbsolutePath() + + ", ignore and retry later, maybe multi java process use the file, please config: dubbo.metadata.file=xxx.properties"); } // Save try { @@ -210,7 +220,12 @@ public abstract class AbstractMetadataReport implements MetadataReport { } else { reportCacheExecutor.execute(new SaveProperties(lastCacheChanged.incrementAndGet())); } - logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "Failed to save service store file, cause: " + e.getMessage(), e); + logger.warn( + COMMON_UNEXPECTED_EXCEPTION, + "", + "", + "Failed to save service store file, cause: " + e.getMessage(), + e); } } @@ -269,7 +284,8 @@ public abstract class AbstractMetadataReport implements MetadataReport { } @Override - public void storeProviderMetadata(MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) { + public void storeProviderMetadata( + MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) { if (syncReport) { storeProviderMetadataTask(providerMetadataIdentifier, serviceDefinition); } else { @@ -277,47 +293,60 @@ public abstract class AbstractMetadataReport implements MetadataReport { } } - private void storeProviderMetadataTask(MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) { + private void storeProviderMetadataTask( + MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) { - MetadataEvent metadataEvent = MetadataEvent.toServiceSubscribeEvent(applicationModel, providerMetadataIdentifier.getUniqueServiceName()); - MetricsEventBus.post(metadataEvent, () -> - { - boolean result = true; - try { - if (logger.isInfoEnabled()) { - logger.info("store provider metadata. Identifier : " + providerMetadataIdentifier + "; definition: " + serviceDefinition); + MetadataEvent metadataEvent = MetadataEvent.toServiceSubscribeEvent( + applicationModel, providerMetadataIdentifier.getUniqueServiceName()); + MetricsEventBus.post( + metadataEvent, + () -> { + boolean result = true; + try { + if (logger.isInfoEnabled()) { + logger.info("store provider metadata. Identifier : " + providerMetadataIdentifier + + "; definition: " + serviceDefinition); + } + allMetadataReports.put(providerMetadataIdentifier, serviceDefinition); + failedReports.remove(providerMetadataIdentifier); + String data = JsonUtils.toJson(serviceDefinition); + doStoreProviderMetadata(providerMetadataIdentifier, data); + saveProperties(providerMetadataIdentifier, data, true, !syncReport); + } catch (Exception e) { + // retry again. If failed again, throw exception. + failedReports.put(providerMetadataIdentifier, serviceDefinition); + metadataReportRetry.startRetryTask(); + logger.error( + PROXY_FAILED_EXPORT_SERVICE, + "", + "", + "Failed to put provider metadata " + providerMetadataIdentifier + " in " + + serviceDefinition + ", cause: " + e.getMessage(), + e); + result = false; } - allMetadataReports.put(providerMetadataIdentifier, serviceDefinition); - failedReports.remove(providerMetadataIdentifier); - String data = JsonUtils.toJson(serviceDefinition); - doStoreProviderMetadata(providerMetadataIdentifier, data); - saveProperties(providerMetadataIdentifier, data, true, !syncReport); - } catch (Exception e) { - // retry again. If failed again, throw exception. - failedReports.put(providerMetadataIdentifier, serviceDefinition); - metadataReportRetry.startRetryTask(); - logger.error(PROXY_FAILED_EXPORT_SERVICE, "", "", "Failed to put provider metadata " + providerMetadataIdentifier + " in " + serviceDefinition + ", cause: " + e.getMessage(), e); - result = false; - } - return result; - }, aBoolean -> aBoolean - ); - + return result; + }, + aBoolean -> aBoolean); } @Override - public void storeConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, Map serviceParameterMap) { + public void storeConsumerMetadata( + MetadataIdentifier consumerMetadataIdentifier, Map serviceParameterMap) { if (syncReport) { storeConsumerMetadataTask(consumerMetadataIdentifier, serviceParameterMap); } else { - reportCacheExecutor.execute(() -> storeConsumerMetadataTask(consumerMetadataIdentifier, serviceParameterMap)); + reportCacheExecutor.execute( + () -> storeConsumerMetadataTask(consumerMetadataIdentifier, serviceParameterMap)); } } - protected void storeConsumerMetadataTask(MetadataIdentifier consumerMetadataIdentifier, Map serviceParameterMap) { + protected void storeConsumerMetadataTask( + MetadataIdentifier consumerMetadataIdentifier, Map serviceParameterMap) { try { if (logger.isInfoEnabled()) { - logger.info("store consumer metadata. Identifier : " + consumerMetadataIdentifier + "; definition: " + serviceParameterMap); + logger.info("store consumer metadata. Identifier : " + consumerMetadataIdentifier + "; definition: " + + serviceParameterMap); } allMetadataReports.put(consumerMetadataIdentifier, serviceParameterMap); failedReports.remove(consumerMetadataIdentifier); @@ -329,7 +358,13 @@ public abstract class AbstractMetadataReport implements MetadataReport { // retry again. If failed again, throw exception. failedReports.put(consumerMetadataIdentifier, serviceParameterMap); metadataReportRetry.startRetryTask(); - logger.error(PROXY_FAILED_EXPORT_SERVICE, "", "", "Failed to put consumer metadata " + consumerMetadataIdentifier + "; " + serviceParameterMap + ", cause: " + e.getMessage(), e); + logger.error( + PROXY_FAILED_EXPORT_SERVICE, + "", + "", + "Failed to put consumer metadata " + consumerMetadataIdentifier + "; " + serviceParameterMap + + ", cause: " + e.getMessage(), + e); } } @@ -376,11 +411,11 @@ public abstract class AbstractMetadataReport implements MetadataReport { if (syncReport) { doSaveSubscriberData(subscriberMetadataIdentifier, JsonUtils.toJson(urls)); } else { - reportCacheExecutor.execute(() -> doSaveSubscriberData(subscriberMetadataIdentifier, JsonUtils.toJson(urls))); + reportCacheExecutor.execute( + () -> doSaveSubscriberData(subscriberMetadataIdentifier, JsonUtils.toJson(urls))); } } - @Override public List getSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) { String content = doGetSubscribedURLs(subscriberMetadataIdentifier); @@ -414,7 +449,8 @@ public abstract class AbstractMetadataReport implements MetadataReport { if (metadataMap.isEmpty()) { return true; } - Iterator> iterable = metadataMap.entrySet().iterator(); + Iterator> iterable = + metadataMap.entrySet().iterator(); while (iterable.hasNext()) { Map.Entry item = iterable.next(); if (PROVIDER_SIDE.equals(item.getKey().getSide())) { @@ -422,7 +458,6 @@ public abstract class AbstractMetadataReport implements MetadataReport { } else if (CONSUMER_SIDE.equals(item.getKey().getSide())) { this.storeConsumerMetadata(item.getKey(), (Map) item.getValue()); } - } return false; } @@ -448,13 +483,16 @@ public abstract class AbstractMetadataReport implements MetadataReport { calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); long subtract = calendar.getTimeInMillis() + ONE_DAY_IN_MILLISECONDS - nowMill; - return subtract + (FOUR_HOURS_IN_MILLISECONDS / 2) + ThreadLocalRandom.current().nextInt(FOUR_HOURS_IN_MILLISECONDS); + return subtract + + (FOUR_HOURS_IN_MILLISECONDS / 2) + + ThreadLocalRandom.current().nextInt(FOUR_HOURS_IN_MILLISECONDS); } class MetadataReportRetry { protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); - final ScheduledExecutorService retryExecutor = Executors.newScheduledThreadPool(0, new NamedThreadFactory("DubboMetadataReportRetryTimer", true)); + final ScheduledExecutorService retryExecutor = + Executors.newScheduledThreadPool(0, new NamedThreadFactory("DubboMetadataReportRetryTimer", true)); volatile ScheduledFuture retryScheduledFuture; final AtomicInteger retryCounter = new AtomicInteger(0); // retry task schedule period @@ -473,21 +511,30 @@ public abstract class AbstractMetadataReport implements MetadataReport { if (retryScheduledFuture == null) { synchronized (retryCounter) { if (retryScheduledFuture == null) { - retryScheduledFuture = retryExecutor.scheduleWithFixedDelay(() -> { - // Check and connect to the metadata - try { - int times = retryCounter.incrementAndGet(); - logger.info("start to retry task for metadata report. retry times:" + times); - if (retry() && times > retryTimesIfNonFail) { - cancelRetryTask(); - } - if (times > retryLimit) { - cancelRetryTask(); - } - } catch (Throwable t) { // Defensive fault tolerance - logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", "Unexpected error occur at failed retry, cause: " + t.getMessage(), t); - } - }, 500, retryPeriod, TimeUnit.MILLISECONDS); + retryScheduledFuture = retryExecutor.scheduleWithFixedDelay( + () -> { + // Check and connect to the metadata + try { + int times = retryCounter.incrementAndGet(); + logger.info("start to retry task for metadata report. retry times:" + times); + if (retry() && times > retryTimesIfNonFail) { + cancelRetryTask(); + } + if (times > retryLimit) { + cancelRetryTask(); + } + } catch (Throwable t) { // Defensive fault tolerance + logger.error( + COMMON_UNEXPECTED_EXCEPTION, + "", + "", + "Unexpected error occur at failed retry, cause: " + t.getMessage(), + t); + } + }, + 500, + retryPeriod, + TimeUnit.MILLISECONDS); } } } @@ -524,9 +571,11 @@ public abstract class AbstractMetadataReport implements MetadataReport { doSaveSubscriberData(subscriberMetadataIdentifier, encodedUrlList); } - protected abstract void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions); + protected abstract void doStoreProviderMetadata( + MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions); - protected abstract void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String serviceParameterString); + protected abstract void doStoreConsumerMetadata( + MetadataIdentifier consumerMetadataIdentifier, String serviceParameterString); protected abstract void doSaveMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url); @@ -534,7 +583,8 @@ public abstract class AbstractMetadataReport implements MetadataReport { protected abstract List doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier); - protected abstract void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urlListStr); + protected abstract void doSaveSubscriberData( + SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urlListStr); protected abstract String doGetSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier); diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactory.java index 7ac9aabdca..e0d156773d 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactory.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactory.java @@ -32,7 +32,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED public abstract class AbstractMetadataReportFactory implements MetadataReportFactory { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractMetadataReportFactory.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(AbstractMetadataReportFactory.class); private static final String EXPORT_KEY = "export"; private static final String REFER_KEY = "refer"; @@ -48,8 +49,7 @@ public abstract class AbstractMetadataReportFactory implements MetadataReportFac @Override public MetadataReport getMetadataReport(URL url) { - url = url.setPath(MetadataReport.class.getName()) - .removeParameters(EXPORT_KEY, REFER_KEY); + url = url.setPath(MetadataReport.class.getName()).removeParameters(EXPORT_KEY, REFER_KEY); String key = url.toServiceString(); MetadataReport metadataReport = serviceStoreMap.get(key); diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/Constants.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/Constants.java index 406df6c418..4c1fa597ec 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/Constants.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/Constants.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metadata.report.support; public interface Constants { diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/NopMetadataReport.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/NopMetadataReport.java index e42ae2744f..ef900bd793 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/NopMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/NopMetadataReport.java @@ -28,13 +28,11 @@ import java.util.Map; import java.util.Set; public class NopMetadataReport implements MetadataReport { - public NopMetadataReport() { - } + public NopMetadataReport() {} @Override - public void storeProviderMetadata(MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) { - - } + public void storeProviderMetadata( + MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) {} @Override public String getServiceDefinition(MetadataIdentifier metadataIdentifier) { @@ -42,9 +40,8 @@ public class NopMetadataReport implements MetadataReport { } @Override - public void storeConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, Map serviceParameterMap) { - - } + public void storeConsumerMetadata( + MetadataIdentifier consumerMetadataIdentifier, Map serviceParameterMap) {} @Override public List getExportedURLs(ServiceMetadataIdentifier metadataIdentifier) { @@ -52,24 +49,16 @@ public class NopMetadataReport implements MetadataReport { } @Override - public void destroy() { - - } + public void destroy() {} @Override - public void saveServiceMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) { - - } + public void saveServiceMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) {} @Override - public void removeServiceMetadata(ServiceMetadataIdentifier metadataIdentifier) { - - } + public void removeServiceMetadata(ServiceMetadataIdentifier metadataIdentifier) {} @Override - public void saveSubscribedData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, Set urls) { - - } + public void saveSubscribedData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, Set urls) {} @Override public List getSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) { diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/AbstractServiceNameMappingTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/AbstractServiceNameMappingTest.java index 14432ee0a1..3cd01884d8 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/AbstractServiceNameMappingTest.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/AbstractServiceNameMappingTest.java @@ -19,16 +19,16 @@ package org.apache.dubbo.metadata; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDED_BY; import static org.apache.dubbo.common.constants.RegistryConstants.SUBSCRIBED_SERVICE_NAMES_KEY; @@ -43,8 +43,7 @@ class AbstractServiceNameMappingTest { URL url = URL.valueOf("dubbo://127.0.0.1:21880/" + AbstractServiceNameMappingTest.class.getName()); @BeforeEach - public void setUp() throws Exception { - } + public void setUp() throws Exception {} @AfterEach public void clearup() { @@ -58,15 +57,14 @@ class AbstractServiceNameMappingTest { Assertions.assertTrue(services.contains("app1")); Assertions.assertTrue(services.contains("app2")); -// // remove mapping cache, check get() works. -// mapping.removeCachedMapping(ServiceNameMapping.buildMappingKey(url)); -// services = mapping.initInterfaceAppMapping(url); -// Assertions.assertTrue(services.contains("remote-app1")); -// Assertions.assertTrue(services.contains("remote-app2")); + // // remove mapping cache, check get() works. + // mapping.removeCachedMapping(ServiceNameMapping.buildMappingKey(url)); + // services = mapping.initInterfaceAppMapping(url); + // Assertions.assertTrue(services.contains("remote-app1")); + // Assertions.assertTrue(services.contains("remote-app2")); - -// Assertions.assertNotNull(mapping.getCachedMapping(url)); -// Assertions.assertIterableEquals(mapping.getCachedMapping(url), services); + // Assertions.assertNotNull(mapping.getCachedMapping(url)); + // Assertions.assertIterableEquals(mapping.getCachedMapping(url), services); } @Test @@ -82,17 +80,12 @@ class AbstractServiceNameMappingTest { mapping2.enabled = true; services = mapping2.getAndListen(registryURL, url, new MappingListener() { @Override - public void onEvent(MappingChangedEvent event) { - - } + public void onEvent(MappingChangedEvent event) {} @Override - public void stop() { - - } + public void stop() {} }); Assertions.assertTrue(services.contains("remote-app3")); - } private class MockServiceNameMapping extends AbstractServiceNameMapping { @@ -117,9 +110,7 @@ class AbstractServiceNameMappingTest { } @Override - protected void removeListener(URL url, MappingListener mappingListener) { - - } + protected void removeListener(URL url, MappingListener mappingListener) {} @Override public boolean map(URL url) { @@ -154,9 +145,7 @@ class AbstractServiceNameMappingTest { } @Override - protected void removeListener(URL url, MappingListener mappingListener) { - - } + protected void removeListener(URL url, MappingListener mappingListener) {} @Override public boolean map(URL url) { @@ -168,5 +157,4 @@ class AbstractServiceNameMappingTest { return false; } } - } diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/DemoService.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/DemoService.java deleted file mode 100644 index e30b40a9dd..0000000000 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/DemoService.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.dubbo.metadata; -// -//import org.apache.dubbo.metadata.rest.User; -// -//import java.util.List; -// -// -///** -// * DemoService -// */ -//public interface DemoService { -// -// String sayName(String name); -// -// void throwRuntimeException() throws RuntimeException; -// -// List getUsers(List users); -// -// int echo(int i); -// -//} diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/MetadataInfoTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/MetadataInfoTest.java index d9f3f82b9d..8c483739fc 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/MetadataInfoTest.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/MetadataInfoTest.java @@ -19,9 +19,6 @@ package org.apache.dubbo.metadata; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.JsonUtils; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -31,12 +28,15 @@ import java.lang.reflect.Field; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.PAYLOAD; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.PAYLOAD; import static org.apache.dubbo.metadata.RevisionResolver.EMPTY_REVISION; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -49,29 +49,30 @@ import static org.junit.jupiter.api.Assertions.assertTrue; * Some construction and filter cases are covered in InMemoryMetadataServiceTest */ class MetadataInfoTest { - private static URL url = URL.valueOf("dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService2?" + - "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2" + - "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService2" + - "&metadata-type=remote&methods=sayHello&sayHello.timeout=7000&pid=36621&release=&revision=1.0.0&service-name-mapping=true" + - "&side=provider&timeout=5000×tamp=1629970068002&version=1.0.0¶ms-filter=customized,-excluded"); + private static URL url = URL.valueOf("dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService2?" + + "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2" + + "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService2" + + "&metadata-type=remote&methods=sayHello&sayHello.timeout=7000&pid=36621&release=&revision=1.0.0&service-name-mapping=true" + + "&side=provider&timeout=5000×tamp=1629970068002&version=1.0.0¶ms-filter=customized,-excluded"); - private static URL url2 = URL.valueOf("dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService?" + - "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2" + - "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService" + - "&metadata-type=remote&methods=sayHello&pid=36621&release=&revision=1.0.0&service-name-mapping=true" + - "&side=provider&timeout=5000×tamp=1629970068002&version=1.0.0¶ms-filter=customized,-excluded"); + private static URL url2 = URL.valueOf("dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService?" + + "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2" + + "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService" + + "&metadata-type=remote&methods=sayHello&pid=36621&release=&revision=1.0.0&service-name-mapping=true" + + "&side=provider&timeout=5000×tamp=1629970068002&version=1.0.0¶ms-filter=customized,-excluded"); - private static URL url3 = URL.valueOf("dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService?" + - "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2" + - "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService" + - "&metadata-type=remote&methods=sayHello&sayHello.timeout=7000&pid=36621&release=&revision=1.0.0&service-name-mapping=true" + - "&side=provider&timeout=5000×tamp=1629970068002&version=1.0.0¶ms-filter=-customized,excluded"); + private static URL url3 = URL.valueOf("dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService?" + + "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2" + + "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService" + + "&metadata-type=remote&methods=sayHello&sayHello.timeout=7000&pid=36621&release=&revision=1.0.0&service-name-mapping=true" + + "&side=provider&timeout=5000×tamp=1629970068002&version=1.0.0¶ms-filter=-customized,excluded"); - private static URL url4 = URL.valueOf("dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService?" + - "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2" + - "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService" + - "&metadata-type=remote&methods=sayHello&sayHello.timeout=7000&pid=36621&release=&revision=1.0.0&service-name-mapping=true" + - "&side=provider&timeout=5000×tamp=1629970068002&version=1.0.0¶ms-filter=-customized,excluded&payload=1024"); + private static URL url4 = URL.valueOf( + "dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService?" + + "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2" + + "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService" + + "&metadata-type=remote&methods=sayHello&sayHello.timeout=7000&pid=36621&release=&revision=1.0.0&service-name-mapping=true" + + "&side=provider&timeout=5000×tamp=1629970068002&version=1.0.0¶ms-filter=-customized,excluded&payload=1024"); @Test void testEmptyRevision() { @@ -175,7 +176,6 @@ class MetadataInfoTest { metadataInfo2.addService(url); metadataInfo2.addService(url2); System.out.println(JsonUtils.toJson(metadataInfo2)); - } @Test @@ -198,7 +198,7 @@ class MetadataInfoTest { Field initiatedField = MetadataInfo.class.getDeclaredField("initiated"); initiatedField.setAccessible(true); Assertions.assertInstanceOf(AtomicBoolean.class, initiatedField.get(metadataInfo2)); - Assertions.assertFalse(((AtomicBoolean)initiatedField.get(metadataInfo2)).get()); + Assertions.assertFalse(((AtomicBoolean) initiatedField.get(metadataInfo2)).get()); } @Test @@ -218,7 +218,7 @@ class MetadataInfoTest { metadataInfo.calAndGetRevision(); - Map ret = JsonUtils.toJavaObject(metadataInfo.getContent(), Map.class); + Map ret = JsonUtils.toJavaObject(metadataInfo.getContent(), Map.class); assertNull(ret.get("content")); assertNull(ret.get("rawMetadataInfo")); } diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/ServiceNameMappingTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/ServiceNameMappingTest.java deleted file mode 100644 index 322359fa00..0000000000 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/ServiceNameMappingTest.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.dubbo.metadata; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.config.configcenter.file.FileSystemDynamicConfiguration; -import org.apache.dubbo.config.ApplicationConfig; -import org.apache.dubbo.rpc.model.ApplicationModel; - -import org.apache.commons.io.FileUtils; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.LinkedHashSet; -import java.util.Set; - -import static java.util.Arrays.asList; -import static java.util.Collections.singleton; -import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.SUBSCRIBED_SERVICE_NAMES_KEY; -import static org.apache.dubbo.common.config.configcenter.DynamicConfigurationServiceNameMapping.buildGroup; -import static org.apache.dubbo.metadata.ServiceNameMapping.getDefaultExtension; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - -*/ -/** - * {@link org.apache.dubbo.metadata.ServiceNameMapping} Test - * - * @since 2.7.8 - *//* - -class ServiceNameMappingTest { - - private static final URL BASE_URL = URL.valueOf("dubbo://127.0.0.1:20880"); - - private FileSystemDynamicConfiguration configuration; - - private ServiceNameMapping serviceNameMapping; - - private String applicationName; - - @BeforeEach - public void init() { - - ApplicationModel.reset(); - - applicationName = getClass().getSimpleName(); - - ApplicationModel.defaultModel().getConfigManager().setApplication(new ApplicationConfig(applicationName)); - - configuration = new FileSystemDynamicConfiguration(); - - FileUtils.deleteQuietly(configuration.getRootDirectory()); - - ApplicationModel.defaultModel().getEnvironment().setDynamicConfiguration(configuration); - - serviceNameMapping = getDefaultExtension(); - } - - @AfterEach - public void reset() throws Exception { - FileUtils.deleteQuietly(configuration.getRootDirectory()); - configuration.close(); - ApplicationModel.reset(); - } - - @Test - void testDeprecatedMethods() { - assertThrows(UnsupportedOperationException.class, () -> { - serviceNameMapping.map(null, null, null, null); - }); - - assertThrows(UnsupportedOperationException.class, () -> { - serviceNameMapping.get(null, null, null, null); - }); - } - - @Test - void testMap() { - String serviceInterface = ServiceNameMapping.class.getName(); - String key = applicationName; - String group = buildGroup(serviceInterface, null, null, null); - URL url = BASE_URL.setServiceInterface(serviceInterface); - serviceNameMapping.map(url); - assertNotNull(configuration.getConfig(key, group)); - } - - @Test - void testGet() { - String serviceInterface = ServiceNameMapping.class.getName(); - URL url = BASE_URL.setServiceInterface(serviceInterface); - serviceNameMapping.map(url); - Set serviceNames = serviceNameMapping.get(url); - assertEquals(singleton(applicationName), serviceNames); - - url = url.setServiceInterface("com.acme.Interface1").addParameter(GROUP_KEY, "default"); - serviceNames = serviceNameMapping.get(url); - assertEquals(singleton("Service1"), serviceNames); - - - url = url.addParameter(SUBSCRIBED_SERVICE_NAMES_KEY, "A , B , C "); - serviceNames = serviceNameMapping.get(url); - assertEquals(new LinkedHashSet<>(asList("A", "B", "C")), serviceNames); - - } -} -*/ diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/filter/CustomizedParamsFilter.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/filter/CustomizedParamsFilter.java index ac1b22d7f1..d6fe8a2feb 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/filter/CustomizedParamsFilter.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/filter/CustomizedParamsFilter.java @@ -29,7 +29,7 @@ public class CustomizedParamsFilter implements MetadataParamsFilter { @Override public String[] serviceParamsIncluded() { - return new String[]{APPLICATION_KEY, TIMEOUT_KEY, GROUP_KEY, VERSION_KEY}; + return new String[] {APPLICATION_KEY, TIMEOUT_KEY, GROUP_KEY, VERSION_KEY}; } @Override diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/filter/ExcludedParamsFilter.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/filter/ExcludedParamsFilter.java index d0e0de43d6..14075ffeed 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/filter/ExcludedParamsFilter.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/filter/ExcludedParamsFilter.java @@ -32,7 +32,7 @@ public class ExcludedParamsFilter implements MetadataParamsFilter { @Override public String[] serviceParamsExcluded() { - return new String[]{TIMEOUT_KEY, GROUP_KEY, "anyhost"}; + return new String[] {TIMEOUT_KEY, GROUP_KEY, "anyhost"}; } /** diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/filter/ExcludedParamsFilter2.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/filter/ExcludedParamsFilter2.java index ac347fd5f7..8fe4c177f4 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/filter/ExcludedParamsFilter2.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/filter/ExcludedParamsFilter2.java @@ -32,7 +32,7 @@ public class ExcludedParamsFilter2 implements MetadataParamsFilter { @Override public String[] serviceParamsExcluded() { - return new String[]{DEPRECATED_KEY, SIDE_KEY}; + return new String[] {DEPRECATED_KEY, SIDE_KEY}; } /** diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/MetadataReportInstanceTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/MetadataReportInstanceTest.java index 0f2d3cb4b6..226bd62f3a 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/MetadataReportInstanceTest.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/MetadataReportInstanceTest.java @@ -22,14 +22,14 @@ import org.apache.dubbo.config.MetadataReportConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.Collections; +import java.util.Map; + import org.hamcrest.Matchers; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Collections; -import java.util.Map; - import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -48,7 +48,6 @@ class MetadataReportInstanceTest { ApplicationModel applicationModel = spy(ApplicationModel.defaultModel()); metadataReportInstance = new MetadataReportInstance(applicationModel); - URL url = URL.valueOf("metadata://127.0.0.1:20880/TestService?version=1.0.0&metadata=JTest"); metadataReportConfig = mock(MetadataReportConfig.class); when(metadataReportConfig.getUsername()).thenReturn("username"); @@ -61,14 +60,15 @@ class MetadataReportInstanceTest { when(configManager.getMetadataConfigs()).thenReturn(Collections.emptyList()); when(applicationModel.getApplicationConfigManager()).thenReturn(configManager); - when(applicationModel.getApplicationConfigManager().getApplicationOrElseThrow()).thenReturn(new ApplicationConfig("test")); + when(applicationModel.getApplicationConfigManager().getApplicationOrElseThrow()) + .thenReturn(new ApplicationConfig("test")); when(applicationModel.getCurrentConfig()).thenReturn(new ApplicationConfig("test")); - } @Test void test() { - Assertions.assertNull(metadataReportInstance.getMetadataReport(registryId), "the metadata report was not initialized."); + Assertions.assertNull( + metadataReportInstance.getMetadataReport(registryId), "the metadata report was not initialized."); assertThat(metadataReportInstance.getMetadataReports(true), Matchers.anEmptyMap()); metadataReportInstance.init(Collections.singletonList(metadataReportConfig)); @@ -85,5 +85,4 @@ class MetadataReportInstanceTest { Assertions.assertEquals(metadataReportConfig.getUsername(), "username"); Assertions.assertEquals(metadataReportConfig.getPassword(), "password"); } - } diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/BaseApplicationMetadataIdentifierTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/BaseApplicationMetadataIdentifierTest.java index 90950b50e8..6e9743431b 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/BaseApplicationMetadataIdentifierTest.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/BaseApplicationMetadataIdentifierTest.java @@ -38,7 +38,7 @@ class BaseApplicationMetadataIdentifierTest { @Test void getIdentifierKey() { - String identifierKey = baseApplicationMetadataIdentifier.getIdentifierKey( "reversion"); + String identifierKey = baseApplicationMetadataIdentifier.getIdentifierKey("reversion"); Assertions.assertEquals(identifierKey, "app:reversion"); } } diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/BaseServiceMetadataIdentifierTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/BaseServiceMetadataIdentifierTest.java index 3b6ce9103c..c21dd934b1 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/BaseServiceMetadataIdentifierTest.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/BaseServiceMetadataIdentifierTest.java @@ -42,7 +42,7 @@ class BaseServiceMetadataIdentifierTest { @Test void getIdentifierKey() { - String identifierKey = baseServiceMetadataIdentifier.getIdentifierKey( "appName"); + String identifierKey = baseServiceMetadataIdentifier.getIdentifierKey("appName"); Assertions.assertEquals(identifierKey, "BaseServiceMetadataIdentifierTest:1.0.0:test:provider:appName"); } } diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/MetadataIdentifierTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/MetadataIdentifierTest.java index 810c668a62..476623e4ea 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/MetadataIdentifierTest.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/MetadataIdentifierTest.java @@ -35,16 +35,24 @@ class MetadataIdentifierTest { String version = "1.0.0.zk.md"; String group = null; String application = "vic.zk.md"; - MetadataIdentifier providerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application); - Assertions.assertEquals(providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.PATH), - "metadata" + PATH_SEPARATOR + interfaceName + PATH_SEPARATOR + - (version == null ? "" : (version + PATH_SEPARATOR)) + MetadataIdentifier providerMetadataIdentifier = + new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application); + Assertions.assertEquals( + providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.PATH), + "metadata" + PATH_SEPARATOR + interfaceName + PATH_SEPARATOR + + (version == null ? "" : (version + PATH_SEPARATOR)) + (group == null ? "" : (group + PATH_SEPARATOR)) + PROVIDER_SIDE + PATH_SEPARATOR + application); - Assertions.assertEquals(providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), - interfaceName + MetadataConstants.KEY_SEPARATOR + - (version == null ? "" : version) + MetadataConstants.KEY_SEPARATOR - + (group == null ? "" : group) + MetadataConstants.KEY_SEPARATOR - + PROVIDER_SIDE + MetadataConstants.KEY_SEPARATOR + application); + Assertions.assertEquals( + providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), + interfaceName + + MetadataConstants.KEY_SEPARATOR + + (version == null ? "" : version) + + MetadataConstants.KEY_SEPARATOR + + (group == null ? "" : group) + + MetadataConstants.KEY_SEPARATOR + + PROVIDER_SIDE + + MetadataConstants.KEY_SEPARATOR + + application); } } diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactoryTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactoryTest.java index 7172703448..f8c3dae0d9 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactoryTest.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactoryTest.java @@ -26,14 +26,14 @@ import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier; import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + /** * 2018/9/14 */ @@ -45,24 +45,20 @@ class AbstractMetadataReportFactoryTest { return new MetadataReport() { @Override - public void storeProviderMetadata(MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) { + public void storeProviderMetadata( + MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) { store.put(providerMetadataIdentifier.getIdentifierKey(), JsonUtils.toJson(serviceDefinition)); } @Override - public void saveServiceMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) { - - } + public void saveServiceMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) {} @Override - public void removeServiceMetadata(ServiceMetadataIdentifier metadataIdentifier) { - - } + public void removeServiceMetadata(ServiceMetadataIdentifier metadataIdentifier) {} @Override - public void saveSubscribedData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, Set urls) { - - } + public void saveSubscribedData( + SubscriberMetadataIdentifier subscriberMetadataIdentifier, Set urls) {} @Override public List getExportedURLs(ServiceMetadataIdentifier metadataIdentifier) { @@ -70,9 +66,7 @@ class AbstractMetadataReportFactoryTest { } @Override - public void destroy() { - - } + public void destroy() {} @Override public List getSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) { @@ -80,9 +74,7 @@ class AbstractMetadataReportFactoryTest { } @Override - public void removeServiceAppMappingListener(String serviceKey, MappingListener listener) { - - } + public void removeServiceAppMappingListener(String serviceKey, MappingListener listener) {} @Override public boolean shouldReportDefinition() { @@ -100,20 +92,20 @@ class AbstractMetadataReportFactoryTest { } @Override - public void storeConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, Map serviceParameterMap) { + public void storeConsumerMetadata( + MetadataIdentifier consumerMetadataIdentifier, Map serviceParameterMap) { store.put(consumerMetadataIdentifier.getIdentifierKey(), JsonUtils.toJson(serviceParameterMap)); } Map store = new ConcurrentHashMap<>(); - - }; } }; @Test void testGetOneMetadataReport() { - URL url = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic"); + URL url = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic"); MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url); MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url); Assertions.assertEquals(metadataReport1, metadataReport2); @@ -123,8 +115,10 @@ class AbstractMetadataReportFactoryTest { void testGetOneMetadataReportForIpFormat() { String hostName = NetUtils.getLocalAddress().getHostName(); String ip = NetUtils.getIpByHost(hostName); - URL url1 = URL.valueOf("zookeeper://" + hostName + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic"); - URL url2 = URL.valueOf("zookeeper://" + ip + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic"); + URL url1 = URL.valueOf( + "zookeeper://" + hostName + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic"); + URL url2 = + URL.valueOf("zookeeper://" + ip + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic"); MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url1); MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url2); Assertions.assertEquals(metadataReport1, metadataReport2); @@ -132,8 +126,10 @@ class AbstractMetadataReportFactoryTest { @Test void testGetForDiffService() { - URL url1 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService1?version=1.0.0&application=vic"); - URL url2 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService2?version=1.0.0&application=vic"); + URL url1 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + + ":4444/org.apache.dubbo.TestService1?version=1.0.0&application=vic"); + URL url2 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + + ":4444/org.apache.dubbo.TestService2?version=1.0.0&application=vic"); MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url1); MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url2); Assertions.assertEquals(metadataReport1, metadataReport2); @@ -141,8 +137,10 @@ class AbstractMetadataReportFactoryTest { @Test void testGetForDiffGroup() { - URL url1 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&group=aaa"); - URL url2 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&group=bbb"); + URL url1 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&group=aaa"); + URL url2 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&group=bbb"); MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url1); MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url2); Assertions.assertNotEquals(metadataReport1, metadataReport2); diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportTest.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportTest.java index a64ab817a7..66bbf79646 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportTest.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metadata.report.support; import org.apache.dubbo.common.URL; @@ -31,11 +30,6 @@ import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.Calendar; import java.util.HashMap; import java.util.List; @@ -45,6 +39,11 @@ import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadPoolExecutor; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.awaitility.Awaitility.await; @@ -64,11 +63,13 @@ class AbstractMetadataReportTest { // set the simple name of current class as the application name FrameworkModel frameworkModel = FrameworkModel.defaultModel(); applicationModel = frameworkModel.newApplication(); - applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig(getClass().getSimpleName())); + applicationModel + .getApplicationConfigManager() + .setApplication(new ApplicationConfig(getClass().getSimpleName())); - URL url = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic"); + URL url = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName() + + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic"); abstractMetadataReport = new NewMetadataReport(url, applicationModel); - } @AfterEach @@ -79,11 +80,13 @@ class AbstractMetadataReportTest { @Test void testGetProtocol() { - URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&side=provider"); + URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&side=provider"); String protocol = abstractMetadataReport.getProtocol(url); assertEquals("provider", protocol); - URL url2 = URL.valueOf("consumer://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic"); + URL url2 = URL.valueOf("consumer://" + NetUtils.getLocalAddress().getHostName() + + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic"); String protocol2 = abstractMetadataReport.getProtocol(url2); assertEquals("consumer", protocol2); } @@ -97,9 +100,11 @@ class AbstractMetadataReportTest { ThreadPoolExecutor reportCacheExecutor = (ThreadPoolExecutor) abstractMetadataReport.getReportCacheExecutor(); long completedTaskCount1 = reportCacheExecutor.getCompletedTaskCount(); - MetadataIdentifier providerMetadataIdentifier = storeProvider(abstractMetadataReport, interfaceName, version, group, application); + MetadataIdentifier providerMetadataIdentifier = + storeProvider(abstractMetadataReport, interfaceName, version, group, application); await().until(() -> reportCacheExecutor.getCompletedTaskCount() > completedTaskCount1); - Assertions.assertNotNull(abstractMetadataReport.store.get(providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY))); + Assertions.assertNotNull( + abstractMetadataReport.store.get(providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY))); } @Test @@ -109,14 +114,18 @@ class AbstractMetadataReportTest { String group = null; String application = "vic"; abstractMetadataReport.syncReport = true; - MetadataIdentifier providerMetadataIdentifier = storeProvider(abstractMetadataReport, interfaceName, version, group, application); - Assertions.assertNotNull(abstractMetadataReport.store.get(providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY))); + MetadataIdentifier providerMetadataIdentifier = + storeProvider(abstractMetadataReport, interfaceName, version, group, application); + Assertions.assertNotNull( + abstractMetadataReport.store.get(providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY))); } @Test void testFileExistAfterPut() throws ClassNotFoundException { - //just for one method - URL singleUrl = URL.valueOf("redis://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.metadata.store.InterfaceNameTestService?version=1.0.0&application=singleTest"); + // just for one method + URL singleUrl = URL.valueOf( + "redis://" + NetUtils.getLocalAddress().getHostName() + + ":4444/org.apache.dubbo.metadata.store.InterfaceNameTestService?version=1.0.0&application=singleTest"); NewMetadataReport singleMetadataReport = new NewMetadataReport(singleUrl, applicationModel); assertFalse(singleMetadataReport.file.exists()); @@ -128,11 +137,13 @@ class AbstractMetadataReportTest { ThreadPoolExecutor reportCacheExecutor = (ThreadPoolExecutor) singleMetadataReport.getReportCacheExecutor(); long completedTaskCount1 = reportCacheExecutor.getCompletedTaskCount(); - MetadataIdentifier providerMetadataIdentifier = storeProvider(singleMetadataReport, interfaceName, version, group, application); + MetadataIdentifier providerMetadataIdentifier = + storeProvider(singleMetadataReport, interfaceName, version, group, application); await().until(() -> reportCacheExecutor.getCompletedTaskCount() > completedTaskCount1); assertTrue(singleMetadataReport.file.exists()); - assertTrue(singleMetadataReport.properties.containsKey(providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY))); + assertTrue(singleMetadataReport.properties.containsKey( + providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY))); } @Test @@ -141,18 +152,20 @@ class AbstractMetadataReportTest { String version = "1.0.0.retry"; String group = null; String application = "vic.retry"; - URL storeUrl = URL.valueOf("retryReport://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestServiceForRetry?version=1.0.0.retry&application=vic.retry"); + URL storeUrl = URL.valueOf("retryReport://" + NetUtils.getLocalAddress().getHostName() + + ":4444/org.apache.dubbo.TestServiceForRetry?version=1.0.0.retry&application=vic.retry"); RetryMetadataReport retryReport = new RetryMetadataReport(storeUrl, 2, applicationModel); retryReport.metadataReportRetry.retryPeriod = 400L; - URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic"); + URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic"); Assertions.assertNull(retryReport.metadataReportRetry.retryScheduledFuture); assertEquals(0, retryReport.metadataReportRetry.retryCounter.get()); assertTrue(retryReport.store.isEmpty()); assertTrue(retryReport.failedReports.isEmpty()); - ThreadPoolExecutor reportCacheExecutor = (ThreadPoolExecutor) retryReport.getReportCacheExecutor(); - ScheduledThreadPoolExecutor retryExecutor = (ScheduledThreadPoolExecutor) retryReport.getMetadataReportRetry().getRetryExecutor(); + ScheduledThreadPoolExecutor retryExecutor = (ScheduledThreadPoolExecutor) + retryReport.getMetadataReportRetry().getRetryExecutor(); long completedTaskCount1 = reportCacheExecutor.getCompletedTaskCount(); long completedTaskCount2 = retryExecutor.getCompletedTaskCount(); @@ -176,13 +189,15 @@ class AbstractMetadataReportTest { String version = "1.0.0.retrycancel"; String group = null; String application = "vic.retry"; - URL storeUrl = URL.valueOf("retryReport://" + NetUtils.getLocalAddress().getHostName() + ":4444/org.apache.dubbo.TestServiceForRetryCancel?version=1.0.0.retrycancel&application=vic.retry"); + URL storeUrl = URL.valueOf("retryReport://" + NetUtils.getLocalAddress().getHostName() + + ":4444/org.apache.dubbo.TestServiceForRetryCancel?version=1.0.0.retrycancel&application=vic.retry"); RetryMetadataReport retryReport = new RetryMetadataReport(storeUrl, 2, applicationModel); retryReport.metadataReportRetry.retryPeriod = 150L; retryReport.metadataReportRetry.retryTimesIfNonFail = 2; retryReport.semaphore = new Semaphore(1); - ScheduledThreadPoolExecutor retryExecutor = (ScheduledThreadPoolExecutor) retryReport.getMetadataReportRetry().getRetryExecutor(); + ScheduledThreadPoolExecutor retryExecutor = (ScheduledThreadPoolExecutor) + retryReport.getMetadataReportRetry().getRetryExecutor(); long completedTaskCount = retryExecutor.getCompletedTaskCount(); storeProvider(retryReport, interfaceName, version, group, application); @@ -196,25 +211,42 @@ class AbstractMetadataReportTest { await().untilAsserted(() -> assertTrue(retryReport.metadataReportRetry.retryExecutor.isShutdown())); } - private MetadataIdentifier storeProvider(AbstractMetadataReport abstractMetadataReport, String interfaceName, String version, String group, String application) throws ClassNotFoundException { - URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + "?version=" + version + "&application=" - + application + (group == null ? "" : "&group=" + group) + "&testPKey=8989"); + private MetadataIdentifier storeProvider( + AbstractMetadataReport abstractMetadataReport, + String interfaceName, + String version, + String group, + String application) + throws ClassNotFoundException { + URL url = URL.valueOf( + "xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + "?version=" + version + + "&application=" + application + (group == null ? "" : "&group=" + group) + "&testPKey=8989"); - MetadataIdentifier providerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application); + MetadataIdentifier providerMetadataIdentifier = + new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application); Class interfaceClass = Class.forName(interfaceName); - FullServiceDefinition fullServiceDefinition = ServiceDefinitionBuilder.buildFullDefinition(interfaceClass, url.getParameters()); + FullServiceDefinition fullServiceDefinition = + ServiceDefinitionBuilder.buildFullDefinition(interfaceClass, url.getParameters()); abstractMetadataReport.storeProviderMetadata(providerMetadataIdentifier, fullServiceDefinition); return providerMetadataIdentifier; } - private MetadataIdentifier storeConsumer(AbstractMetadataReport abstractMetadataReport, String interfaceName, String version, String group, String application, Map tmp) { - URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + "?version=" + version + "&application=" - + application + (group == null ? "" : "&group=" + group) + "&testPKey=9090"); + private MetadataIdentifier storeConsumer( + AbstractMetadataReport abstractMetadataReport, + String interfaceName, + String version, + String group, + String application, + Map tmp) { + URL url = URL.valueOf( + "xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + "?version=" + version + + "&application=" + application + (group == null ? "" : "&group=" + group) + "&testPKey=9090"); tmp.putAll(url.getParameters()); - MetadataIdentifier consumerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, CONSUMER_SIDE, application); + MetadataIdentifier consumerMetadataIdentifier = + new MetadataIdentifier(interfaceName, version, group, CONSUMER_SIDE, application); abstractMetadataReport.storeConsumerMetadata(consumerMetadataIdentifier, tmp); @@ -232,22 +264,33 @@ class AbstractMetadataReportTest { String group = null; String application = "vic"; long completedTaskCount1 = reportCacheExecutor.getCompletedTaskCount(); - MetadataIdentifier providerMetadataIdentifier1 = storeProvider(abstractMetadataReport, interfaceName, version, group, application); + MetadataIdentifier providerMetadataIdentifier1 = + storeProvider(abstractMetadataReport, interfaceName, version, group, application); await().until(() -> reportCacheExecutor.getCompletedTaskCount() > completedTaskCount1); assertEquals(1, abstractMetadataReport.allMetadataReports.size()); - assertTrue(((FullServiceDefinition) abstractMetadataReport.allMetadataReports.get(providerMetadataIdentifier1)).getParameters().containsKey("testPKey")); + assertTrue(((FullServiceDefinition) abstractMetadataReport.allMetadataReports.get(providerMetadataIdentifier1)) + .getParameters() + .containsKey("testPKey")); long completedTaskCount2 = reportCacheExecutor.getCompletedTaskCount(); - MetadataIdentifier providerMetadataIdentifier2 = storeProvider(abstractMetadataReport, interfaceName, version + "_2", group + "_2", application); + MetadataIdentifier providerMetadataIdentifier2 = + storeProvider(abstractMetadataReport, interfaceName, version + "_2", group + "_2", application); await().until(() -> reportCacheExecutor.getCompletedTaskCount() > completedTaskCount2); assertEquals(2, abstractMetadataReport.allMetadataReports.size()); - assertTrue(((FullServiceDefinition) abstractMetadataReport.allMetadataReports.get(providerMetadataIdentifier2)).getParameters().containsKey("testPKey")); - assertEquals(((FullServiceDefinition) abstractMetadataReport.allMetadataReports.get(providerMetadataIdentifier2)).getParameters().get("version"), version + "_2"); + assertTrue(((FullServiceDefinition) abstractMetadataReport.allMetadataReports.get(providerMetadataIdentifier2)) + .getParameters() + .containsKey("testPKey")); + assertEquals( + ((FullServiceDefinition) abstractMetadataReport.allMetadataReports.get(providerMetadataIdentifier2)) + .getParameters() + .get("version"), + version + "_2"); Map tmpMap = new HashMap<>(); tmpMap.put("testKey", "value"); long completedTaskCount3 = reportCacheExecutor.getCompletedTaskCount(); - MetadataIdentifier consumerMetadataIdentifier = storeConsumer(abstractMetadataReport, interfaceName, version + "_3", group + "_3", application, tmpMap); + MetadataIdentifier consumerMetadataIdentifier = + storeConsumer(abstractMetadataReport, interfaceName, version + "_3", group + "_3", application, tmpMap); await().until(() -> reportCacheExecutor.getCompletedTaskCount() > completedTaskCount3); assertEquals(3, abstractMetadataReport.allMetadataReports.size()); @@ -290,7 +333,6 @@ class AbstractMetadataReportTest { } } - private void checkParam(Map map, String application, String version) { assertEquals(map.get("application"), application); assertEquals(map.get("version"), version); @@ -306,48 +348,54 @@ class AbstractMetadataReportTest { } @Override - protected void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) { + protected void doStoreProviderMetadata( + MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) { store.put(providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), serviceDefinitions); } @Override - protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String serviceParameterString) { + protected void doStoreConsumerMetadata( + MetadataIdentifier consumerMetadataIdentifier, String serviceParameterString) { store.put(consumerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), serviceParameterString); } @Override protected void doSaveMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) { - throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + throw new UnsupportedOperationException( + "This extension does not support working as a remote metadata center."); } @Override protected void doRemoveMetadata(ServiceMetadataIdentifier metadataIdentifier) { - throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + throw new UnsupportedOperationException( + "This extension does not support working as a remote metadata center."); } @Override protected List doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier) { - throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + throw new UnsupportedOperationException( + "This extension does not support working as a remote metadata center."); } @Override - protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urls) { - - } + protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urls) {} @Override protected String doGetSubscribedURLs(SubscriberMetadataIdentifier metadataIdentifier) { - throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + throw new UnsupportedOperationException( + "This extension does not support working as a remote metadata center."); } @Override public String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier) { - throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + throw new UnsupportedOperationException( + "This extension does not support working as a remote metadata center."); } @Override public void removeServiceAppMappingListener(String serviceKey, MappingListener listener) { - throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + throw new UnsupportedOperationException( + "This extension does not support working as a remote metadata center."); } } @@ -365,7 +413,8 @@ class AbstractMetadataReportTest { } @Override - protected void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) { + protected void doStoreProviderMetadata( + MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) { ++executeTimes; System.out.println("***" + executeTimes + ";" + System.currentTimeMillis()); semaphore.acquireUninterruptibly(); @@ -376,7 +425,8 @@ class AbstractMetadataReportTest { } @Override - protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String serviceParameterString) { + protected void doStoreConsumerMetadata( + MetadataIdentifier consumerMetadataIdentifier, String serviceParameterString) { ++executeTimes; if (executeTimes <= needRetryTimes) { throw new RuntimeException("must retry:" + executeTimes); @@ -386,40 +436,41 @@ class AbstractMetadataReportTest { @Override protected void doSaveMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) { - throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + throw new UnsupportedOperationException( + "This extension does not support working as a remote metadata center."); } @Override protected void doRemoveMetadata(ServiceMetadataIdentifier metadataIdentifier) { - throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + throw new UnsupportedOperationException( + "This extension does not support working as a remote metadata center."); } @Override protected List doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier) { - throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + throw new UnsupportedOperationException( + "This extension does not support working as a remote metadata center."); } @Override - protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urls) { - - } + protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urls) {} @Override protected String doGetSubscribedURLs(SubscriberMetadataIdentifier metadataIdentifier) { - throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + throw new UnsupportedOperationException( + "This extension does not support working as a remote metadata center."); } @Override public String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier) { - throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + throw new UnsupportedOperationException( + "This extension does not support working as a remote metadata center."); } @Override public void removeServiceAppMappingListener(String serviceKey, MappingListener listener) { - throw new UnsupportedOperationException("This extension does not support working as a remote metadata center."); + throw new UnsupportedOperationException( + "This extension does not support working as a remote metadata center."); } - } - - } diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/test/JTestMetadataReport4Test.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/test/JTestMetadataReport4Test.java index ad4f052954..fc26020f2a 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/test/JTestMetadataReport4Test.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/test/JTestMetadataReport4Test.java @@ -36,8 +36,7 @@ import java.util.concurrent.ConcurrentHashMap; */ class JTestMetadataReport4Test extends AbstractMetadataReport { - private final static Logger logger = LoggerFactory.getLogger(JTestMetadataReport4Test.class); - + private static final Logger logger = LoggerFactory.getLogger(JTestMetadataReport4Test.class); public JTestMetadataReport4Test(URL url) { super(url); @@ -45,7 +44,6 @@ class JTestMetadataReport4Test extends AbstractMetadataReport { public volatile Map store = new ConcurrentHashMap<>(); - private static String getProtocol(URL url) { String protocol = url.getSide(); protocol = protocol == null ? url.getProtocol() : protocol; @@ -58,7 +56,8 @@ class JTestMetadataReport4Test extends AbstractMetadataReport { } @Override - protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String serviceParameterString) { + protected void doStoreConsumerMetadata( + MetadataIdentifier consumerMetadataIdentifier, String serviceParameterString) { store.put(consumerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), serviceParameterString); } @@ -101,7 +100,5 @@ class JTestMetadataReport4Test extends AbstractMetadataReport { } @Override - public void removeServiceAppMappingListener(String serviceKey, MappingListener listener) { - - } + public void removeServiceAppMappingListener(String serviceKey, MappingListener listener) {} } diff --git a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/test/JTestMetadataReportFactory4Test.java b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/test/JTestMetadataReportFactory4Test.java index 6e26408300..cf29a35031 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/test/JTestMetadataReportFactory4Test.java +++ b/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/test/JTestMetadataReportFactory4Test.java @@ -29,5 +29,4 @@ public class JTestMetadataReportFactory4Test extends AbstractMetadataReportFacto public MetadataReport createMetadataReport(URL url) { return new JTestMetadataReport4Test(url); } - } diff --git a/dubbo-metadata/dubbo-metadata-definition-protobuf/pom.xml b/dubbo-metadata/dubbo-metadata-definition-protobuf/pom.xml index 44a969de0c..486601be2b 100644 --- a/dubbo-metadata/dubbo-metadata-definition-protobuf/pom.xml +++ b/dubbo-metadata/dubbo-metadata-definition-protobuf/pom.xml @@ -1,3 +1,4 @@ + - - org.apache.dubbo - dubbo-metadata - ${revision} - ../pom.xml - - 4.0.0 - dubbo-metadata-definition-protobuf + 4.0.0 + + org.apache.dubbo + dubbo-metadata + ${revision} + ../pom.xml + + dubbo-metadata-definition-protobuf - - - com.google.protobuf - protobuf-java - - - com.google.protobuf - protobuf-java-util - - - org.apache.dubbo - dubbo-metadata-api - ${project.parent.version} - - + + + com.google.protobuf + protobuf-java + + + com.google.protobuf + protobuf-java-util + + + org.apache.dubbo + dubbo-metadata-api + ${project.parent.version} + + diff --git a/dubbo-metadata/dubbo-metadata-definition-protobuf/src/main/java/org/apache/dubbo/metadata/definition/protobuf/ProtobufTypeBuilder.java b/dubbo-metadata/dubbo-metadata-definition-protobuf/src/main/java/org/apache/dubbo/metadata/definition/protobuf/ProtobufTypeBuilder.java index a6b4850ad6..18ba0a37a3 100644 --- a/dubbo-metadata/dubbo-metadata-definition-protobuf/src/main/java/org/apache/dubbo/metadata/definition/protobuf/ProtobufTypeBuilder.java +++ b/dubbo-metadata/dubbo-metadata-definition-protobuf/src/main/java/org/apache/dubbo/metadata/definition/protobuf/ProtobufTypeBuilder.java @@ -24,12 +24,6 @@ import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder; import org.apache.dubbo.metadata.definition.builder.TypeBuilder; import org.apache.dubbo.metadata.definition.model.TypeDefinition; -import com.google.protobuf.ByteString; -import com.google.protobuf.Descriptors; -import com.google.protobuf.GeneratedMessageV3; -import com.google.protobuf.ProtocolStringList; -import com.google.protobuf.UnknownFieldSet; - import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.HashMap; @@ -38,6 +32,12 @@ import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; +import com.google.protobuf.ByteString; +import com.google.protobuf.Descriptors; +import com.google.protobuf.GeneratedMessageV3; +import com.google.protobuf.ProtocolStringList; +import com.google.protobuf.UnknownFieldSet; + @Activate(onClass = "com.google.protobuf.GeneratedMessageV3") public class ProtobufTypeBuilder implements TypeBuilder, Prioritized { private final Logger logger = LoggerFactory.getLogger(getClass()); @@ -54,7 +54,8 @@ public class ProtobufTypeBuilder implements TypeBuilder, Prioritized { static { try { - STRING_LIST_TYPE = ProtobufTypeBuilder.class.getDeclaredField("LIST").getGenericType(); + STRING_LIST_TYPE = + ProtobufTypeBuilder.class.getDeclaredField("LIST").getGenericType(); } catch (NoSuchFieldException e) { // do nothing } @@ -114,7 +115,8 @@ public class ProtobufTypeBuilder implements TypeBuilder, Prioritized { return (GeneratedMessageV3.Builder) method.invoke(null, null); } - private TypeDefinition buildProtobufTypeDefinition(Class clazz, GeneratedMessageV3.Builder builder, Map typeCache) { + private TypeDefinition buildProtobufTypeDefinition( + Class clazz, GeneratedMessageV3.Builder builder, Map typeCache) { String canonicalName = clazz.getCanonicalName(); TypeDefinition td = new TypeDefinition(canonicalName); if (builder == null) { @@ -128,7 +130,8 @@ public class ProtobufTypeBuilder implements TypeBuilder, Prioritized { if (isSimplePropertySettingMethod(method)) { // property of custom type or primitive type - TypeDefinition fieldTd = TypeDefinitionBuilder.build(method.getGenericParameterTypes()[0], method.getParameterTypes()[0], typeCache); + TypeDefinition fieldTd = TypeDefinitionBuilder.build( + method.getGenericParameterTypes()[0], method.getParameterTypes()[0], typeCache); properties.put(generateSimpleFiledName(methodName), fieldTd.getType()); } else if (isMapPropertySettingMethod(method)) { // property of map @@ -171,8 +174,8 @@ public class ProtobufTypeBuilder implements TypeBuilder, Prioritized { private void validateMapType(String fieldName, String typeName) { Matcher matcher = MAP_PATTERN.matcher(typeName); if (!matcher.matches()) { - throw new IllegalArgumentException("Map protobuf property " + fieldName + "of Type " + - typeName + " can't be parsed.The type name should mathch[" + MAP_PATTERN.toString() + "]."); + throw new IllegalArgumentException("Map protobuf property " + fieldName + "of Type " + typeName + + " can't be parsed.The type name should mathch[" + MAP_PATTERN.toString() + "]."); } } @@ -209,7 +212,6 @@ public class ProtobufTypeBuilder implements TypeBuilder, Prioritized { return toCamelCase(methodName.substring(3, methodName.length() - 4)); } - private String toCamelCase(String nameString) { char[] chars = nameString.toCharArray(); chars[0] = Character.toLowerCase(chars[0]); @@ -263,7 +265,6 @@ public class ProtobufTypeBuilder implements TypeBuilder, Prioritized { return !methodName.endsWith("Value") || types[0] != int.class; } - /** * judge List property
* proto3 grammar ex: repeated string names;
@@ -276,7 +277,6 @@ public class ProtobufTypeBuilder implements TypeBuilder, Prioritized { String methodName = method.getName(); Class type = method.getReturnType(); - if (!methodName.startsWith("get") || !methodName.endsWith("List")) { return false; } diff --git a/dubbo-metadata/dubbo-metadata-definition-protobuf/src/test/java/org/apache/dubbo/metadata/definition/protobuf/ProtobufTypeBuilderTest.java b/dubbo-metadata/dubbo-metadata-definition-protobuf/src/test/java/org/apache/dubbo/metadata/definition/protobuf/ProtobufTypeBuilderTest.java index 559d313f46..f3d1921efa 100644 --- a/dubbo-metadata/dubbo-metadata-definition-protobuf/src/test/java/org/apache/dubbo/metadata/definition/protobuf/ProtobufTypeBuilderTest.java +++ b/dubbo-metadata/dubbo-metadata-definition-protobuf/src/test/java/org/apache/dubbo/metadata/definition/protobuf/ProtobufTypeBuilderTest.java @@ -24,11 +24,11 @@ import org.apache.dubbo.metadata.definition.model.TypeDefinition; import org.apache.dubbo.metadata.definition.protobuf.model.ServiceInterface; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.junit.jupiter.api.Test; - import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Test; + import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -68,17 +68,21 @@ class ProtobufTypeBuilderTest { assertThat(propertiesMap.containsKey("name"), is(true)); assertThat(getTypeName(propertiesMap.get("name"), types), equalTo("java.lang.String")); assertThat(propertiesMap.containsKey("msg"), is(true)); - assertThat(getTypeName(propertiesMap.get("msg"), types), - equalTo("com.google.protobuf.ByteString")); + assertThat(getTypeName(propertiesMap.get("msg"), types), equalTo("com.google.protobuf.ByteString")); assertThat(propertiesMap.containsKey("phone"), is(true)); - assertThat(getTypeName(propertiesMap.get("phone"), types), + assertThat( + getTypeName(propertiesMap.get("phone"), types), equalTo("java.util.List")); assertThat(propertiesMap.containsKey("doubleMap"), is(true)); - assertThat(getTypeName(propertiesMap.get("doubleMap"), types), - equalTo("java.util.Map")); - assertThat(getTypeName(propertiesMap.get("bytesList"), types), + assertThat( + getTypeName(propertiesMap.get("doubleMap"), types), + equalTo( + "java.util.Map")); + assertThat( + getTypeName(propertiesMap.get("bytesList"), types), equalTo("java.util.List")); - assertThat(getTypeName(propertiesMap.get("bytesMap"), types), + assertThat( + getTypeName(propertiesMap.get("bytesMap"), types), equalTo("java.util.Map")); } diff --git a/dubbo-metadata/dubbo-metadata-definition-protobuf/src/test/java/org/apache/dubbo/metadata/definition/protobuf/model/GooglePB.java b/dubbo-metadata/dubbo-metadata-definition-protobuf/src/test/java/org/apache/dubbo/metadata/definition/protobuf/model/GooglePB.java index 22a45ad5ae..a70d0aff24 100644 --- a/dubbo-metadata/dubbo-metadata-definition-protobuf/src/test/java/org/apache/dubbo/metadata/definition/protobuf/model/GooglePB.java +++ b/dubbo-metadata/dubbo-metadata-definition-protobuf/src/test/java/org/apache/dubbo/metadata/definition/protobuf/model/GooglePB.java @@ -14,3867 +14,3872 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: GooglePB.proto - package org.apache.dubbo.metadata.definition.protobuf.model; public final class GooglePB { - private GooglePB() {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistryLite registry) { - } + private GooglePB() {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - registerAllExtensions( - (com.google.protobuf.ExtensionRegistryLite) registry); - } - /** - * Protobuf enum {@code org.apache.dubbo.metadata.definition.protobuf.model.PhoneType} - */ - public enum PhoneType - implements com.google.protobuf.ProtocolMessageEnum { - /** - * MOBILE = 0; - */ - MOBILE(0), - /** - * HOME = 1; - */ - HOME(1), - /** - * WORK = 2; - */ - WORK(2), - ; + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} - /** - * MOBILE = 0; - */ - public static final int MOBILE_VALUE = 0; - /** - * HOME = 1; - */ - public static final int HOME_VALUE = 1; - /** - * WORK = 2; - */ - public static final int WORK_VALUE = 2; - - - public final int getNumber() { - return value; + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { + registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); } + /** + * Protobuf enum {@code org.apache.dubbo.metadata.definition.protobuf.model.PhoneType} + */ + public enum PhoneType implements com.google.protobuf.ProtocolMessageEnum { + /** + * MOBILE = 0; + */ + MOBILE(0), + /** + * HOME = 1; + */ + HOME(1), + /** + * WORK = 2; + */ + WORK(2), + ; - /** - * @deprecated Use {@link #forNumber(int)} instead. - */ - @java.lang.Deprecated - public static PhoneType valueOf(int value) { - return forNumber(value); - } + /** + * MOBILE = 0; + */ + public static final int MOBILE_VALUE = 0; + /** + * HOME = 1; + */ + public static final int HOME_VALUE = 1; + /** + * WORK = 2; + */ + public static final int WORK_VALUE = 2; - public static PhoneType forNumber(int value) { - switch (value) { - case 0: return MOBILE; - case 1: return HOME; - case 2: return WORK; - default: return null; - } - } - - public static com.google.protobuf.Internal.EnumLiteMap - internalGetValueMap() { - return internalValueMap; - } - private static final com.google.protobuf.Internal.EnumLiteMap< - PhoneType> internalValueMap = - new com.google.protobuf.Internal.EnumLiteMap() { - public PhoneType findValueByNumber(int number) { - return PhoneType.forNumber(number); - } - }; - - public final com.google.protobuf.Descriptors.EnumValueDescriptor - getValueDescriptor() { - return getDescriptor().getValues().get(ordinal()); - } - public final com.google.protobuf.Descriptors.EnumDescriptor - getDescriptorForType() { - return getDescriptor(); - } - public static final com.google.protobuf.Descriptors.EnumDescriptor - getDescriptor() { - return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.getDescriptor().getEnumTypes().get(0); - } - - private static final PhoneType[] VALUES = values(); - - public static PhoneType valueOf( - com.google.protobuf.Descriptors.EnumValueDescriptor desc) { - if (desc.getType() != getDescriptor()) { - throw new java.lang.IllegalArgumentException( - "EnumValueDescriptor is not for this type."); - } - return VALUES[desc.getIndex()]; - } - - private final int value; - - private PhoneType(int value) { - this.value = value; - } - - // @@protoc_insertion_point(enum_scope:org.apache.dubbo.metadata.definition.protobuf.model.PhoneType) - } - - public interface PBRequestTypeOrBuilder extends - // @@protoc_insertion_point(interface_extends:org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType) - com.google.protobuf.MessageOrBuilder { - - /** - * optional double money = 1; - */ - boolean hasMoney(); - /** - * optional double money = 1; - */ - double getMoney(); - - /** - * optional float cash = 2; - */ - boolean hasCash(); - /** - * optional float cash = 2; - */ - float getCash(); - - /** - * optional int32 age = 3; - */ - boolean hasAge(); - /** - * optional int32 age = 3; - */ - int getAge(); - - /** - * optional int64 num = 4; - */ - boolean hasNum(); - /** - * optional int64 num = 4; - */ - long getNum(); - - /** - * optional bool sex = 5; - */ - boolean hasSex(); - /** - * optional bool sex = 5; - */ - boolean getSex(); - - /** - * optional string name = 6; - */ - boolean hasName(); - /** - * optional string name = 6; - */ - java.lang.String getName(); - /** - * optional string name = 6; - */ - com.google.protobuf.ByteString - getNameBytes(); - - /** - * optional bytes msg = 7; - */ - boolean hasMsg(); - /** - * optional bytes msg = 7; - */ - com.google.protobuf.ByteString getMsg(); - - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - java.util.List - getPhoneList(); - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getPhone(int index); - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - int getPhoneCount(); - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - java.util.List - getPhoneOrBuilderList(); - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumberOrBuilder getPhoneOrBuilder( - int index); - - /** - * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; - */ - int getDoubleMapCount(); - /** - * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; - */ - boolean containsDoubleMap( - java.lang.String key); - /** - * Use {@link #getDoubleMapMap()} instead. - */ - @java.lang.Deprecated - java.util.Map - getDoubleMap(); - /** - * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; - */ - java.util.Map - getDoubleMapMap(); - /** - * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; - */ - - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDoubleMapOrDefault( - java.lang.String key, - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber defaultValue); - /** - * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; - */ - - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDoubleMapOrThrow( - java.lang.String key); - - /** - * repeated bytes bytesList = 10; - */ - java.util.List getBytesListList(); - /** - * repeated bytes bytesList = 10; - */ - int getBytesListCount(); - /** - * repeated bytes bytesList = 10; - */ - com.google.protobuf.ByteString getBytesList(int index); - - /** - * map<string, bytes> bytesMap = 11; - */ - int getBytesMapCount(); - /** - * map<string, bytes> bytesMap = 11; - */ - boolean containsBytesMap( - java.lang.String key); - /** - * Use {@link #getBytesMapMap()} instead. - */ - @java.lang.Deprecated - java.util.Map - getBytesMap(); - /** - * map<string, bytes> bytesMap = 11; - */ - java.util.Map - getBytesMapMap(); - /** - * map<string, bytes> bytesMap = 11; - */ - - com.google.protobuf.ByteString getBytesMapOrDefault( - java.lang.String key, - com.google.protobuf.ByteString defaultValue); - /** - * map<string, bytes> bytesMap = 11; - */ - - com.google.protobuf.ByteString getBytesMapOrThrow( - java.lang.String key); - } - /** - * Protobuf type {@code org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType} - */ - public static final class PBRequestType extends - com.google.protobuf.GeneratedMessageV3 implements - // @@protoc_insertion_point(message_implements:org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType) - PBRequestTypeOrBuilder { - private static final long serialVersionUID = 0L; - // Use PBRequestType.newBuilder() to construct. - private PBRequestType(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - private PBRequestType() { - money_ = 0D; - cash_ = 0F; - age_ = 0; - num_ = 0L; - sex_ = false; - name_ = ""; - msg_ = com.google.protobuf.ByteString.EMPTY; - phone_ = java.util.Collections.emptyList(); - bytesList_ = java.util.Collections.emptyList(); - } - - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet - getUnknownFields() { - return this.unknownFields; - } - private PBRequestType( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownField( - input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - case 9: { - bitField0_ |= 0x00000001; - money_ = input.readDouble(); - break; - } - case 21: { - bitField0_ |= 0x00000002; - cash_ = input.readFloat(); - break; - } - case 24: { - bitField0_ |= 0x00000004; - age_ = input.readInt32(); - break; - } - case 32: { - bitField0_ |= 0x00000008; - num_ = input.readInt64(); - break; - } - case 40: { - bitField0_ |= 0x00000010; - sex_ = input.readBool(); - break; - } - case 50: { - com.google.protobuf.ByteString bs = input.readBytes(); - bitField0_ |= 0x00000020; - name_ = bs; - break; - } - case 58: { - bitField0_ |= 0x00000040; - msg_ = input.readBytes(); - break; - } - case 66: { - if (!((mutable_bitField0_ & 0x00000080) == 0x00000080)) { - phone_ = new java.util.ArrayList(); - mutable_bitField0_ |= 0x00000080; - } - phone_.add( - input.readMessage(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.PARSER, extensionRegistry)); - break; - } - case 74: { - if (!((mutable_bitField0_ & 0x00000100) == 0x00000100)) { - doubleMap_ = com.google.protobuf.MapField.newMapField( - DoubleMapDefaultEntryHolder.defaultEntry); - mutable_bitField0_ |= 0x00000100; - } - com.google.protobuf.MapEntry - doubleMap__ = input.readMessage( - DoubleMapDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); - doubleMap_.getMutableMap().put( - doubleMap__.getKey(), doubleMap__.getValue()); - break; - } - case 82: { - if (!((mutable_bitField0_ & 0x00000200) == 0x00000200)) { - bytesList_ = new java.util.ArrayList(); - mutable_bitField0_ |= 0x00000200; - } - bytesList_.add(input.readBytes()); - break; - } - case 90: { - if (!((mutable_bitField0_ & 0x00000400) == 0x00000400)) { - bytesMap_ = com.google.protobuf.MapField.newMapField( - BytesMapDefaultEntryHolder.defaultEntry); - mutable_bitField0_ |= 0x00000400; - } - com.google.protobuf.MapEntry - bytesMap__ = input.readMessage( - BytesMapDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); - bytesMap_.getMutableMap().put( - bytesMap__.getKey(), bytesMap__.getValue()); - break; - } - } + public final int getNumber() { + return value; } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException( - e).setUnfinishedMessage(this); - } finally { - if (((mutable_bitField0_ & 0x00000080) == 0x00000080)) { - phone_ = java.util.Collections.unmodifiableList(phone_); + + /** + * @deprecated Use {@link #forNumber(int)} instead. + */ + @java.lang.Deprecated + public static PhoneType valueOf(int value) { + return forNumber(value); } - if (((mutable_bitField0_ & 0x00000200) == 0x00000200)) { - bytesList_ = java.util.Collections.unmodifiableList(bytesList_); + + public static PhoneType forNumber(int value) { + switch (value) { + case 0: + return MOBILE; + case 1: + return HOME; + case 2: + return WORK; + default: + return null; + } } - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); - } - } - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor; - } - @SuppressWarnings({"rawtypes"}) - protected com.google.protobuf.MapField internalGetMapField( - int number) { - switch (number) { - case 9: - return internalGetDoubleMap(); - case 11: - return internalGetBytesMap(); - default: - throw new RuntimeException( - "Invalid map field number: " + number); - } - } - protected FieldAccessorTable - internalGetFieldAccessorTable() { - return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_fieldAccessorTable - .ensureFieldAccessorsInitialized( - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.class, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.Builder.class); - } - - private int bitField0_; - public static final int MONEY_FIELD_NUMBER = 1; - private double money_; - /** - * optional double money = 1; - */ - public boolean hasMoney() { - return ((bitField0_ & 0x00000001) == 0x00000001); - } - /** - * optional double money = 1; - */ - public double getMoney() { - return money_; - } - - public static final int CASH_FIELD_NUMBER = 2; - private float cash_; - /** - * optional float cash = 2; - */ - public boolean hasCash() { - return ((bitField0_ & 0x00000002) == 0x00000002); - } - /** - * optional float cash = 2; - */ - public float getCash() { - return cash_; - } - - public static final int AGE_FIELD_NUMBER = 3; - private int age_; - /** - * optional int32 age = 3; - */ - public boolean hasAge() { - return ((bitField0_ & 0x00000004) == 0x00000004); - } - /** - * optional int32 age = 3; - */ - public int getAge() { - return age_; - } - - public static final int NUM_FIELD_NUMBER = 4; - private long num_; - /** - * optional int64 num = 4; - */ - public boolean hasNum() { - return ((bitField0_ & 0x00000008) == 0x00000008); - } - /** - * optional int64 num = 4; - */ - public long getNum() { - return num_; - } - - public static final int SEX_FIELD_NUMBER = 5; - private boolean sex_; - /** - * optional bool sex = 5; - */ - public boolean hasSex() { - return ((bitField0_ & 0x00000010) == 0x00000010); - } - /** - * optional bool sex = 5; - */ - public boolean getSex() { - return sex_; - } - - public static final int NAME_FIELD_NUMBER = 6; - private volatile java.lang.Object name_; - /** - * optional string name = 6; - */ - public boolean hasName() { - return ((bitField0_ & 0x00000020) == 0x00000020); - } - /** - * optional string name = 6; - */ - public java.lang.String getName() { - java.lang.Object ref = name_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - if (bs.isValidUtf8()) { - name_ = s; + public static com.google.protobuf.Internal.EnumLiteMap internalGetValueMap() { + return internalValueMap; } - return s; - } - } - /** - * optional string name = 6; - */ - public com.google.protobuf.ByteString - getNameBytes() { - java.lang.Object ref = name_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); - name_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - public static final int MSG_FIELD_NUMBER = 7; - private com.google.protobuf.ByteString msg_; - /** - * optional bytes msg = 7; - */ - public boolean hasMsg() { - return ((bitField0_ & 0x00000040) == 0x00000040); - } - /** - * optional bytes msg = 7; - */ - public com.google.protobuf.ByteString getMsg() { - return msg_; - } + private static final com.google.protobuf.Internal.EnumLiteMap internalValueMap = + new com.google.protobuf.Internal.EnumLiteMap() { + public PhoneType findValueByNumber(int number) { + return PhoneType.forNumber(number); + } + }; - public static final int PHONE_FIELD_NUMBER = 8; - private java.util.List phone_; - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - public java.util.List getPhoneList() { - return phone_; - } - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - public java.util.List - getPhoneOrBuilderList() { - return phone_; - } - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - public int getPhoneCount() { - return phone_.size(); - } - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getPhone(int index) { - return phone_.get(index); - } - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumberOrBuilder getPhoneOrBuilder( - int index) { - return phone_.get(index); - } - - public static final int DOUBLEMAP_FIELD_NUMBER = 9; - private static final class DoubleMapDefaultEntryHolder { - static final com.google.protobuf.MapEntry< - String, PhoneNumber> defaultEntry = - com.google.protobuf.MapEntry - .newDefaultInstance( - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_DoubleMapEntry_descriptor, - com.google.protobuf.WireFormat.FieldType.STRING, - "", - com.google.protobuf.WireFormat.FieldType.MESSAGE, - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.getDefaultInstance()); - } - private com.google.protobuf.MapField< - String, PhoneNumber> doubleMap_; - private com.google.protobuf.MapField - internalGetDoubleMap() { - if (doubleMap_ == null) { - return com.google.protobuf.MapField.emptyMapField( - DoubleMapDefaultEntryHolder.defaultEntry); - } - return doubleMap_; - } - - public int getDoubleMapCount() { - return internalGetDoubleMap().getMap().size(); - } - /** - * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; - */ - - public boolean containsDoubleMap( - java.lang.String key) { - if (key == null) { throw new java.lang.NullPointerException(); } - return internalGetDoubleMap().getMap().containsKey(key); - } - /** - * Use {@link #getDoubleMapMap()} instead. - */ - @java.lang.Deprecated - public java.util.Map getDoubleMap() { - return getDoubleMapMap(); - } - /** - * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; - */ - - public java.util.Map getDoubleMapMap() { - return internalGetDoubleMap().getMap(); - } - /** - * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; - */ - - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDoubleMapOrDefault( - java.lang.String key, - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber defaultValue) { - if (key == null) { throw new java.lang.NullPointerException(); } - java.util.Map map = - internalGetDoubleMap().getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; - } - /** - * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; - */ - - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDoubleMapOrThrow( - java.lang.String key) { - if (key == null) { throw new java.lang.NullPointerException(); } - java.util.Map map = - internalGetDoubleMap().getMap(); - if (!map.containsKey(key)) { - throw new java.lang.IllegalArgumentException(); - } - return map.get(key); - } - - public static final int BYTESLIST_FIELD_NUMBER = 10; - private java.util.List bytesList_; - /** - * repeated bytes bytesList = 10; - */ - public java.util.List - getBytesListList() { - return bytesList_; - } - /** - * repeated bytes bytesList = 10; - */ - public int getBytesListCount() { - return bytesList_.size(); - } - /** - * repeated bytes bytesList = 10; - */ - public com.google.protobuf.ByteString getBytesList(int index) { - return bytesList_.get(index); - } - - public static final int BYTESMAP_FIELD_NUMBER = 11; - private static final class BytesMapDefaultEntryHolder { - static final com.google.protobuf.MapEntry< - String, com.google.protobuf.ByteString> defaultEntry = - com.google.protobuf.MapEntry - .newDefaultInstance( - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_BytesMapEntry_descriptor, - com.google.protobuf.WireFormat.FieldType.STRING, - "", - com.google.protobuf.WireFormat.FieldType.BYTES, - com.google.protobuf.ByteString.EMPTY); - } - private com.google.protobuf.MapField< - String, com.google.protobuf.ByteString> bytesMap_; - private com.google.protobuf.MapField - internalGetBytesMap() { - if (bytesMap_ == null) { - return com.google.protobuf.MapField.emptyMapField( - BytesMapDefaultEntryHolder.defaultEntry); - } - return bytesMap_; - } - - public int getBytesMapCount() { - return internalGetBytesMap().getMap().size(); - } - /** - * map<string, bytes> bytesMap = 11; - */ - - public boolean containsBytesMap( - java.lang.String key) { - if (key == null) { throw new java.lang.NullPointerException(); } - return internalGetBytesMap().getMap().containsKey(key); - } - /** - * Use {@link #getBytesMapMap()} instead. - */ - @java.lang.Deprecated - public java.util.Map getBytesMap() { - return getBytesMapMap(); - } - /** - * map<string, bytes> bytesMap = 11; - */ - - public java.util.Map getBytesMapMap() { - return internalGetBytesMap().getMap(); - } - /** - * map<string, bytes> bytesMap = 11; - */ - - public com.google.protobuf.ByteString getBytesMapOrDefault( - java.lang.String key, - com.google.protobuf.ByteString defaultValue) { - if (key == null) { throw new java.lang.NullPointerException(); } - java.util.Map map = - internalGetBytesMap().getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; - } - /** - * map<string, bytes> bytesMap = 11; - */ - - public com.google.protobuf.ByteString getBytesMapOrThrow( - java.lang.String key) { - if (key == null) { throw new java.lang.NullPointerException(); } - java.util.Map map = - internalGetBytesMap().getMap(); - if (!map.containsKey(key)) { - throw new java.lang.IllegalArgumentException(); - } - return map.get(key); - } - - private byte memoizedIsInitialized = -1; - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) return true; - if (isInitialized == 0) return false; - - for (int i = 0; i < getPhoneCount(); i++) { - if (!getPhone(i).isInitialized()) { - memoizedIsInitialized = 0; - return false; + public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { + return getDescriptor().getValues().get(ordinal()); } - } - for (org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber item : getDoubleMapMap().values()) { - if (!item.isInitialized()) { - memoizedIsInitialized = 0; - return false; + + public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { + return getDescriptor(); } - } - memoizedIsInitialized = 1; - return true; - } - public void writeTo(com.google.protobuf.CodedOutputStream output) - throws java.io.IOException { - if (((bitField0_ & 0x00000001) == 0x00000001)) { - output.writeDouble(1, money_); - } - if (((bitField0_ & 0x00000002) == 0x00000002)) { - output.writeFloat(2, cash_); - } - if (((bitField0_ & 0x00000004) == 0x00000004)) { - output.writeInt32(3, age_); - } - if (((bitField0_ & 0x00000008) == 0x00000008)) { - output.writeInt64(4, num_); - } - if (((bitField0_ & 0x00000010) == 0x00000010)) { - output.writeBool(5, sex_); - } - if (((bitField0_ & 0x00000020) == 0x00000020)) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 6, name_); - } - if (((bitField0_ & 0x00000040) == 0x00000040)) { - output.writeBytes(7, msg_); - } - for (int i = 0; i < phone_.size(); i++) { - output.writeMessage(8, phone_.get(i)); - } - com.google.protobuf.GeneratedMessageV3 - .serializeStringMapTo( - output, - internalGetDoubleMap(), - DoubleMapDefaultEntryHolder.defaultEntry, - 9); - for (int i = 0; i < bytesList_.size(); i++) { - output.writeBytes(10, bytesList_.get(i)); - } - com.google.protobuf.GeneratedMessageV3 - .serializeStringMapTo( - output, - internalGetBytesMap(), - BytesMapDefaultEntryHolder.defaultEntry, - 11); - unknownFields.writeTo(output); - } - - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) return size; - - size = 0; - if (((bitField0_ & 0x00000001) == 0x00000001)) { - size += com.google.protobuf.CodedOutputStream - .computeDoubleSize(1, money_); - } - if (((bitField0_ & 0x00000002) == 0x00000002)) { - size += com.google.protobuf.CodedOutputStream - .computeFloatSize(2, cash_); - } - if (((bitField0_ & 0x00000004) == 0x00000004)) { - size += com.google.protobuf.CodedOutputStream - .computeInt32Size(3, age_); - } - if (((bitField0_ & 0x00000008) == 0x00000008)) { - size += com.google.protobuf.CodedOutputStream - .computeInt64Size(4, num_); - } - if (((bitField0_ & 0x00000010) == 0x00000010)) { - size += com.google.protobuf.CodedOutputStream - .computeBoolSize(5, sex_); - } - if (((bitField0_ & 0x00000020) == 0x00000020)) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, name_); - } - if (((bitField0_ & 0x00000040) == 0x00000040)) { - size += com.google.protobuf.CodedOutputStream - .computeBytesSize(7, msg_); - } - for (int i = 0; i < phone_.size(); i++) { - size += com.google.protobuf.CodedOutputStream - .computeMessageSize(8, phone_.get(i)); - } - for (java.util.Map.Entry entry - : internalGetDoubleMap().getMap().entrySet()) { - com.google.protobuf.MapEntry - doubleMap__ = DoubleMapDefaultEntryHolder.defaultEntry.newBuilderForType() - .setKey(entry.getKey()) - .setValue(entry.getValue()) - .build(); - size += com.google.protobuf.CodedOutputStream - .computeMessageSize(9, doubleMap__); - } - { - int dataSize = 0; - for (int i = 0; i < bytesList_.size(); i++) { - dataSize += com.google.protobuf.CodedOutputStream - .computeBytesSizeNoTag(bytesList_.get(i)); + public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { + return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.getDescriptor() + .getEnumTypes() + .get(0); } - size += dataSize; - size += 1 * getBytesListList().size(); - } - for (java.util.Map.Entry entry - : internalGetBytesMap().getMap().entrySet()) { - com.google.protobuf.MapEntry - bytesMap__ = BytesMapDefaultEntryHolder.defaultEntry.newBuilderForType() - .setKey(entry.getKey()) - .setValue(entry.getValue()) - .build(); - size += com.google.protobuf.CodedOutputStream - .computeMessageSize(11, bytesMap__); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; + + private static final PhoneType[] VALUES = values(); + + public static PhoneType valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) { + if (desc.getType() != getDescriptor()) { + throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type."); + } + return VALUES[desc.getIndex()]; + } + + private final int value; + + private PhoneType(int value) { + this.value = value; + } + + // @@protoc_insertion_point(enum_scope:org.apache.dubbo.metadata.definition.protobuf.model.PhoneType) } - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType)) { - return super.equals(obj); - } - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType other = (org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType) obj; + public interface PBRequestTypeOrBuilder + extends + // @@protoc_insertion_point(interface_extends:org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType) + com.google.protobuf.MessageOrBuilder { - boolean result = true; - result = result && (hasMoney() == other.hasMoney()); - if (hasMoney()) { - result = result && ( - java.lang.Double.doubleToLongBits(getMoney()) - == java.lang.Double.doubleToLongBits( - other.getMoney())); - } - result = result && (hasCash() == other.hasCash()); - if (hasCash()) { - result = result && ( - java.lang.Float.floatToIntBits(getCash()) - == java.lang.Float.floatToIntBits( - other.getCash())); - } - result = result && (hasAge() == other.hasAge()); - if (hasAge()) { - result = result && (getAge() - == other.getAge()); - } - result = result && (hasNum() == other.hasNum()); - if (hasNum()) { - result = result && (getNum() - == other.getNum()); - } - result = result && (hasSex() == other.hasSex()); - if (hasSex()) { - result = result && (getSex() - == other.getSex()); - } - result = result && (hasName() == other.hasName()); - if (hasName()) { - result = result && getName() - .equals(other.getName()); - } - result = result && (hasMsg() == other.hasMsg()); - if (hasMsg()) { - result = result && getMsg() - .equals(other.getMsg()); - } - result = result && getPhoneList() - .equals(other.getPhoneList()); - result = result && internalGetDoubleMap().equals( - other.internalGetDoubleMap()); - result = result && getBytesListList() - .equals(other.getBytesListList()); - result = result && internalGetBytesMap().equals( - other.internalGetBytesMap()); - result = result && unknownFields.equals(other.unknownFields); - return result; - } + /** + * optional double money = 1; + */ + boolean hasMoney(); + /** + * optional double money = 1; + */ + double getMoney(); - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - if (hasMoney()) { - hash = (37 * hash) + MONEY_FIELD_NUMBER; - hash = (53 * hash) + com.google.protobuf.Internal.hashLong( - java.lang.Double.doubleToLongBits(getMoney())); - } - if (hasCash()) { - hash = (37 * hash) + CASH_FIELD_NUMBER; - hash = (53 * hash) + java.lang.Float.floatToIntBits( - getCash()); - } - if (hasAge()) { - hash = (37 * hash) + AGE_FIELD_NUMBER; - hash = (53 * hash) + getAge(); - } - if (hasNum()) { - hash = (37 * hash) + NUM_FIELD_NUMBER; - hash = (53 * hash) + com.google.protobuf.Internal.hashLong( - getNum()); - } - if (hasSex()) { - hash = (37 * hash) + SEX_FIELD_NUMBER; - hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( - getSex()); - } - if (hasName()) { - hash = (37 * hash) + NAME_FIELD_NUMBER; - hash = (53 * hash) + getName().hashCode(); - } - if (hasMsg()) { - hash = (37 * hash) + MSG_FIELD_NUMBER; - hash = (53 * hash) + getMsg().hashCode(); - } - if (getPhoneCount() > 0) { - hash = (37 * hash) + PHONE_FIELD_NUMBER; - hash = (53 * hash) + getPhoneList().hashCode(); - } - if (!internalGetDoubleMap().getMap().isEmpty()) { - hash = (37 * hash) + DOUBLEMAP_FIELD_NUMBER; - hash = (53 * hash) + internalGetDoubleMap().hashCode(); - } - if (getBytesListCount() > 0) { - hash = (37 * hash) + BYTESLIST_FIELD_NUMBER; - hash = (53 * hash) + getBytesListList().hashCode(); - } - if (!internalGetBytesMap().getMap().isEmpty()) { - hash = (37 * hash) + BYTESMAP_FIELD_NUMBER; - hash = (53 * hash) + internalGetBytesMap().hashCode(); - } - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; - } + /** + * optional float cash = 2; + */ + boolean hasCash(); + /** + * optional float cash = 2; + */ + float getCash(); - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom( - java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom( - java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input, extensionRegistry); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } + /** + * optional int32 age = 3; + */ + boolean hasAge(); + /** + * optional int32 age = 3; + */ + int getAge(); - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } - public static Builder newBuilder(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); - } - public Builder toBuilder() { - return this == DEFAULT_INSTANCE - ? new Builder() : new Builder().mergeFrom(this); - } + /** + * optional int64 num = 4; + */ + boolean hasNum(); + /** + * optional int64 num = 4; + */ + long getNum(); - @java.lang.Override - protected Builder newBuilderForType( - BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; + /** + * optional bool sex = 5; + */ + boolean hasSex(); + /** + * optional bool sex = 5; + */ + boolean getSex(); + + /** + * optional string name = 6; + */ + boolean hasName(); + /** + * optional string name = 6; + */ + java.lang.String getName(); + /** + * optional string name = 6; + */ + com.google.protobuf.ByteString getNameBytes(); + + /** + * optional bytes msg = 7; + */ + boolean hasMsg(); + /** + * optional bytes msg = 7; + */ + com.google.protobuf.ByteString getMsg(); + + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + java.util.List getPhoneList(); + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getPhone(int index); + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + int getPhoneCount(); + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + java.util.List + getPhoneOrBuilderList(); + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumberOrBuilder getPhoneOrBuilder(int index); + + /** + * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; + */ + int getDoubleMapCount(); + /** + * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; + */ + boolean containsDoubleMap(java.lang.String key); + /** + * Use {@link #getDoubleMapMap()} instead. + */ + @java.lang.Deprecated + java.util.Map + getDoubleMap(); + /** + * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; + */ + java.util.Map + getDoubleMapMap(); + /** + * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; + */ + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDoubleMapOrDefault( + java.lang.String key, + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber defaultValue); + /** + * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; + */ + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDoubleMapOrThrow( + java.lang.String key); + + /** + * repeated bytes bytesList = 10; + */ + java.util.List getBytesListList(); + /** + * repeated bytes bytesList = 10; + */ + int getBytesListCount(); + /** + * repeated bytes bytesList = 10; + */ + com.google.protobuf.ByteString getBytesList(int index); + + /** + * map<string, bytes> bytesMap = 11; + */ + int getBytesMapCount(); + /** + * map<string, bytes> bytesMap = 11; + */ + boolean containsBytesMap(java.lang.String key); + /** + * Use {@link #getBytesMapMap()} instead. + */ + @java.lang.Deprecated + java.util.Map getBytesMap(); + /** + * map<string, bytes> bytesMap = 11; + */ + java.util.Map getBytesMapMap(); + /** + * map<string, bytes> bytesMap = 11; + */ + com.google.protobuf.ByteString getBytesMapOrDefault( + java.lang.String key, com.google.protobuf.ByteString defaultValue); + /** + * map<string, bytes> bytesMap = 11; + */ + com.google.protobuf.ByteString getBytesMapOrThrow(java.lang.String key); } /** * Protobuf type {@code org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType} */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder implements - // @@protoc_insertion_point(builder_implements:org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType) - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestTypeOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor; - } + public static final class PBRequestType extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType) + PBRequestTypeOrBuilder { + private static final long serialVersionUID = 0L; + // Use PBRequestType.newBuilder() to construct. + private PBRequestType(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } - @SuppressWarnings({"rawtypes"}) - protected com.google.protobuf.MapField internalGetMapField( - int number) { - switch (number) { - case 9: - return internalGetDoubleMap(); - case 11: - return internalGetBytesMap(); - default: - throw new RuntimeException( - "Invalid map field number: " + number); + private PBRequestType() { + money_ = 0D; + cash_ = 0F; + age_ = 0; + num_ = 0L; + sex_ = false; + name_ = ""; + msg_ = com.google.protobuf.ByteString.EMPTY; + phone_ = java.util.Collections.emptyList(); + bytesList_ = java.util.Collections.emptyList(); } - } - @SuppressWarnings({"rawtypes"}) - protected com.google.protobuf.MapField internalGetMutableMapField( - int number) { - switch (number) { - case 9: - return internalGetMutableDoubleMap(); - case 11: - return internalGetMutableBytesMap(); - default: - throw new RuntimeException( - "Invalid map field number: " + number); - } - } - protected FieldAccessorTable - internalGetFieldAccessorTable() { - return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_fieldAccessorTable - .ensureFieldAccessorsInitialized( - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.class, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.Builder.class); - } - // Construct using org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } - private Builder( - BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3 - .alwaysUseFieldBuilders) { - getPhoneFieldBuilder(); + private PBRequestType( + com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 9: { + bitField0_ |= 0x00000001; + money_ = input.readDouble(); + break; + } + case 21: { + bitField0_ |= 0x00000002; + cash_ = input.readFloat(); + break; + } + case 24: { + bitField0_ |= 0x00000004; + age_ = input.readInt32(); + break; + } + case 32: { + bitField0_ |= 0x00000008; + num_ = input.readInt64(); + break; + } + case 40: { + bitField0_ |= 0x00000010; + sex_ = input.readBool(); + break; + } + case 50: { + com.google.protobuf.ByteString bs = input.readBytes(); + bitField0_ |= 0x00000020; + name_ = bs; + break; + } + case 58: { + bitField0_ |= 0x00000040; + msg_ = input.readBytes(); + break; + } + case 66: { + if (!((mutable_bitField0_ & 0x00000080) == 0x00000080)) { + phone_ = new java.util.ArrayList< + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber>(); + mutable_bitField0_ |= 0x00000080; + } + phone_.add(input.readMessage( + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.PARSER, + extensionRegistry)); + break; + } + case 74: { + if (!((mutable_bitField0_ & 0x00000100) == 0x00000100)) { + doubleMap_ = com.google.protobuf.MapField.newMapField( + DoubleMapDefaultEntryHolder.defaultEntry); + mutable_bitField0_ |= 0x00000100; + } + com.google.protobuf.MapEntry doubleMap__ = input.readMessage( + DoubleMapDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); + doubleMap_.getMutableMap().put(doubleMap__.getKey(), doubleMap__.getValue()); + break; + } + case 82: { + if (!((mutable_bitField0_ & 0x00000200) == 0x00000200)) { + bytesList_ = new java.util.ArrayList(); + mutable_bitField0_ |= 0x00000200; + } + bytesList_.add(input.readBytes()); + break; + } + case 90: { + if (!((mutable_bitField0_ & 0x00000400) == 0x00000400)) { + bytesMap_ = com.google.protobuf.MapField.newMapField( + BytesMapDefaultEntryHolder.defaultEntry); + mutable_bitField0_ |= 0x00000400; + } + com.google.protobuf.MapEntry bytesMap__ = + input.readMessage( + BytesMapDefaultEntryHolder.defaultEntry.getParserForType(), + extensionRegistry); + bytesMap_.getMutableMap().put(bytesMap__.getKey(), bytesMap__.getValue()); + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000080) == 0x00000080)) { + phone_ = java.util.Collections.unmodifiableList(phone_); + } + if (((mutable_bitField0_ & 0x00000200) == 0x00000200)) { + bytesList_ = java.util.Collections.unmodifiableList(bytesList_); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } } - } - public Builder clear() { - super.clear(); - money_ = 0D; - bitField0_ = (bitField0_ & ~0x00000001); - cash_ = 0F; - bitField0_ = (bitField0_ & ~0x00000002); - age_ = 0; - bitField0_ = (bitField0_ & ~0x00000004); - num_ = 0L; - bitField0_ = (bitField0_ & ~0x00000008); - sex_ = false; - bitField0_ = (bitField0_ & ~0x00000010); - name_ = ""; - bitField0_ = (bitField0_ & ~0x00000020); - msg_ = com.google.protobuf.ByteString.EMPTY; - bitField0_ = (bitField0_ & ~0x00000040); - if (phoneBuilder_ == null) { - phone_ = java.util.Collections.emptyList(); - bitField0_ = (bitField0_ & ~0x00000080); - } else { - phoneBuilder_.clear(); - } - internalGetMutableDoubleMap().clear(); - bytesList_ = java.util.Collections.emptyList(); - bitField0_ = (bitField0_ & ~0x00000200); - internalGetMutableBytesMap().clear(); - return this; - } - public com.google.protobuf.Descriptors.Descriptor - getDescriptorForType() { - return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor; - } + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB + .internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor; + } - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType getDefaultInstanceForType() { - return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.getDefaultInstance(); - } + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMapField(int number) { + switch (number) { + case 9: + return internalGetDoubleMap(); + case 11: + return internalGetBytesMap(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } + } - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType build() { - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); + protected FieldAccessorTable internalGetFieldAccessorTable() { + return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB + .internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.class, + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.Builder.class); } - return result; - } - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType buildPartial() { - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType result = new org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType(this); - int from_bitField0_ = bitField0_; - int to_bitField0_ = 0; - if (((from_bitField0_ & 0x00000001) == 0x00000001)) { - to_bitField0_ |= 0x00000001; + private int bitField0_; + public static final int MONEY_FIELD_NUMBER = 1; + private double money_; + /** + * optional double money = 1; + */ + public boolean hasMoney() { + return ((bitField0_ & 0x00000001) == 0x00000001); } - result.money_ = money_; - if (((from_bitField0_ & 0x00000002) == 0x00000002)) { - to_bitField0_ |= 0x00000002; + /** + * optional double money = 1; + */ + public double getMoney() { + return money_; } - result.cash_ = cash_; - if (((from_bitField0_ & 0x00000004) == 0x00000004)) { - to_bitField0_ |= 0x00000004; - } - result.age_ = age_; - if (((from_bitField0_ & 0x00000008) == 0x00000008)) { - to_bitField0_ |= 0x00000008; - } - result.num_ = num_; - if (((from_bitField0_ & 0x00000010) == 0x00000010)) { - to_bitField0_ |= 0x00000010; - } - result.sex_ = sex_; - if (((from_bitField0_ & 0x00000020) == 0x00000020)) { - to_bitField0_ |= 0x00000020; - } - result.name_ = name_; - if (((from_bitField0_ & 0x00000040) == 0x00000040)) { - to_bitField0_ |= 0x00000040; - } - result.msg_ = msg_; - if (phoneBuilder_ == null) { - if (((bitField0_ & 0x00000080) == 0x00000080)) { - phone_ = java.util.Collections.unmodifiableList(phone_); - bitField0_ = (bitField0_ & ~0x00000080); - } - result.phone_ = phone_; - } else { - result.phone_ = phoneBuilder_.build(); - } - result.doubleMap_ = internalGetDoubleMap(); - result.doubleMap_.makeImmutable(); - if (((bitField0_ & 0x00000200) == 0x00000200)) { - bytesList_ = java.util.Collections.unmodifiableList(bytesList_); - bitField0_ = (bitField0_ & ~0x00000200); - } - result.bytesList_ = bytesList_; - result.bytesMap_ = internalGetBytesMap(); - result.bytesMap_.makeImmutable(); - result.bitField0_ = to_bitField0_; - onBuilt(); - return result; - } - public Builder clone() { - return (Builder) super.clone(); - } - public Builder setField( - com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } - public Builder clearField( - com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - public Builder clearOneof( - com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - public Builder setRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } - public Builder addRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType) { - return mergeFrom((org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType)other); - } else { - super.mergeFrom(other); - return this; + public static final int CASH_FIELD_NUMBER = 2; + private float cash_; + /** + * optional float cash = 2; + */ + public boolean hasCash() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * optional float cash = 2; + */ + public float getCash() { + return cash_; } - } - public Builder mergeFrom(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType other) { - if (other == org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.getDefaultInstance()) return this; - if (other.hasMoney()) { - setMoney(other.getMoney()); + public static final int AGE_FIELD_NUMBER = 3; + private int age_; + /** + * optional int32 age = 3; + */ + public boolean hasAge() { + return ((bitField0_ & 0x00000004) == 0x00000004); } - if (other.hasCash()) { - setCash(other.getCash()); + /** + * optional int32 age = 3; + */ + public int getAge() { + return age_; } - if (other.hasAge()) { - setAge(other.getAge()); + + public static final int NUM_FIELD_NUMBER = 4; + private long num_; + /** + * optional int64 num = 4; + */ + public boolean hasNum() { + return ((bitField0_ & 0x00000008) == 0x00000008); } - if (other.hasNum()) { - setNum(other.getNum()); + /** + * optional int64 num = 4; + */ + public long getNum() { + return num_; } - if (other.hasSex()) { - setSex(other.getSex()); + + public static final int SEX_FIELD_NUMBER = 5; + private boolean sex_; + /** + * optional bool sex = 5; + */ + public boolean hasSex() { + return ((bitField0_ & 0x00000010) == 0x00000010); } - if (other.hasName()) { - bitField0_ |= 0x00000020; - name_ = other.name_; - onChanged(); + /** + * optional bool sex = 5; + */ + public boolean getSex() { + return sex_; } - if (other.hasMsg()) { - setMsg(other.getMsg()); + + public static final int NAME_FIELD_NUMBER = 6; + private volatile java.lang.Object name_; + /** + * optional string name = 6; + */ + public boolean hasName() { + return ((bitField0_ & 0x00000020) == 0x00000020); } - if (phoneBuilder_ == null) { - if (!other.phone_.isEmpty()) { - if (phone_.isEmpty()) { - phone_ = other.phone_; - bitField0_ = (bitField0_ & ~0x00000080); + /** + * optional string name = 6; + */ + public java.lang.String getName() { + java.lang.Object ref = name_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; } else { - ensurePhoneIsMutable(); - phone_.addAll(other.phone_); + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + name_ = s; + } + return s; } - onChanged(); - } - } else { - if (!other.phone_.isEmpty()) { - if (phoneBuilder_.isEmpty()) { - phoneBuilder_.dispose(); - phoneBuilder_ = null; - phone_ = other.phone_; - bitField0_ = (bitField0_ & ~0x00000080); - phoneBuilder_ = - com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? - getPhoneFieldBuilder() : null; + } + /** + * optional string name = 6; + */ + public com.google.protobuf.ByteString getNameBytes() { + java.lang.Object ref = name_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + name_ = b; + return b; } else { - phoneBuilder_.addAllMessages(other.phone_); + return (com.google.protobuf.ByteString) ref; } - } } - internalGetMutableDoubleMap().mergeFrom( - other.internalGetDoubleMap()); - if (!other.bytesList_.isEmpty()) { - if (bytesList_.isEmpty()) { - bytesList_ = other.bytesList_; - bitField0_ = (bitField0_ & ~0x00000200); - } else { - ensureBytesListIsMutable(); - bytesList_.addAll(other.bytesList_); - } - onChanged(); + + public static final int MSG_FIELD_NUMBER = 7; + private com.google.protobuf.ByteString msg_; + /** + * optional bytes msg = 7; + */ + public boolean hasMsg() { + return ((bitField0_ & 0x00000040) == 0x00000040); } - internalGetMutableBytesMap().mergeFrom( - other.internalGetBytesMap()); - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - public final boolean isInitialized() { - for (int i = 0; i < getPhoneCount(); i++) { - if (!getPhone(i).isInitialized()) { - return false; - } + /** + * optional bytes msg = 7; + */ + public com.google.protobuf.ByteString getMsg() { + return msg_; } - for (org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber item : getDoubleMapMap().values()) { - if (!item.isInitialized()) { - return false; - } + + public static final int PHONE_FIELD_NUMBER = 8; + private java.util.List phone_; + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + public java.util.List getPhoneList() { + return phone_; } - return true; - } - - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType) e.getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + public java.util.List< + ? extends org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumberOrBuilder> + getPhoneOrBuilderList() { + return phone_; } - return this; - } - private int bitField0_; - - private double money_ ; - /** - * optional double money = 1; - */ - public boolean hasMoney() { - return ((bitField0_ & 0x00000001) == 0x00000001); - } - /** - * optional double money = 1; - */ - public double getMoney() { - return money_; - } - /** - * optional double money = 1; - */ - public Builder setMoney(double value) { - bitField0_ |= 0x00000001; - money_ = value; - onChanged(); - return this; - } - /** - * optional double money = 1; - */ - public Builder clearMoney() { - bitField0_ = (bitField0_ & ~0x00000001); - money_ = 0D; - onChanged(); - return this; - } - - private float cash_ ; - /** - * optional float cash = 2; - */ - public boolean hasCash() { - return ((bitField0_ & 0x00000002) == 0x00000002); - } - /** - * optional float cash = 2; - */ - public float getCash() { - return cash_; - } - /** - * optional float cash = 2; - */ - public Builder setCash(float value) { - bitField0_ |= 0x00000002; - cash_ = value; - onChanged(); - return this; - } - /** - * optional float cash = 2; - */ - public Builder clearCash() { - bitField0_ = (bitField0_ & ~0x00000002); - cash_ = 0F; - onChanged(); - return this; - } - - private int age_ ; - /** - * optional int32 age = 3; - */ - public boolean hasAge() { - return ((bitField0_ & 0x00000004) == 0x00000004); - } - /** - * optional int32 age = 3; - */ - public int getAge() { - return age_; - } - /** - * optional int32 age = 3; - */ - public Builder setAge(int value) { - bitField0_ |= 0x00000004; - age_ = value; - onChanged(); - return this; - } - /** - * optional int32 age = 3; - */ - public Builder clearAge() { - bitField0_ = (bitField0_ & ~0x00000004); - age_ = 0; - onChanged(); - return this; - } - - private long num_ ; - /** - * optional int64 num = 4; - */ - public boolean hasNum() { - return ((bitField0_ & 0x00000008) == 0x00000008); - } - /** - * optional int64 num = 4; - */ - public long getNum() { - return num_; - } - /** - * optional int64 num = 4; - */ - public Builder setNum(long value) { - bitField0_ |= 0x00000008; - num_ = value; - onChanged(); - return this; - } - /** - * optional int64 num = 4; - */ - public Builder clearNum() { - bitField0_ = (bitField0_ & ~0x00000008); - num_ = 0L; - onChanged(); - return this; - } - - private boolean sex_ ; - /** - * optional bool sex = 5; - */ - public boolean hasSex() { - return ((bitField0_ & 0x00000010) == 0x00000010); - } - /** - * optional bool sex = 5; - */ - public boolean getSex() { - return sex_; - } - /** - * optional bool sex = 5; - */ - public Builder setSex(boolean value) { - bitField0_ |= 0x00000010; - sex_ = value; - onChanged(); - return this; - } - /** - * optional bool sex = 5; - */ - public Builder clearSex() { - bitField0_ = (bitField0_ & ~0x00000010); - sex_ = false; - onChanged(); - return this; - } - - private java.lang.Object name_ = ""; - /** - * optional string name = 6; - */ - public boolean hasName() { - return ((bitField0_ & 0x00000020) == 0x00000020); - } - /** - * optional string name = 6; - */ - public java.lang.String getName() { - java.lang.Object ref = name_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - if (bs.isValidUtf8()) { - name_ = s; - } - return s; - } else { - return (java.lang.String) ref; + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + public int getPhoneCount() { + return phone_.size(); } - } - /** - * optional string name = 6; - */ - public com.google.protobuf.ByteString - getNameBytes() { - java.lang.Object ref = name_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); - name_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getPhone(int index) { + return phone_.get(index); } - } - /** - * optional string name = 6; - */ - public Builder setName( - java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000020; - name_ = value; - onChanged(); - return this; - } - /** - * optional string name = 6; - */ - public Builder clearName() { - bitField0_ = (bitField0_ & ~0x00000020); - name_ = getDefaultInstance().getName(); - onChanged(); - return this; - } - /** - * optional string name = 6; - */ - public Builder setNameBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000020; - name_ = value; - onChanged(); - return this; - } - - private com.google.protobuf.ByteString msg_ = com.google.protobuf.ByteString.EMPTY; - /** - * optional bytes msg = 7; - */ - public boolean hasMsg() { - return ((bitField0_ & 0x00000040) == 0x00000040); - } - /** - * optional bytes msg = 7; - */ - public com.google.protobuf.ByteString getMsg() { - return msg_; - } - /** - * optional bytes msg = 7; - */ - public Builder setMsg(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000040; - msg_ = value; - onChanged(); - return this; - } - /** - * optional bytes msg = 7; - */ - public Builder clearMsg() { - bitField0_ = (bitField0_ & ~0x00000040); - msg_ = getDefaultInstance().getMsg(); - onChanged(); - return this; - } - - private java.util.List phone_ = - java.util.Collections.emptyList(); - private void ensurePhoneIsMutable() { - if (!((bitField0_ & 0x00000080) == 0x00000080)) { - phone_ = new java.util.ArrayList(phone_); - bitField0_ |= 0x00000080; - } - } - - private com.google.protobuf.RepeatedFieldBuilderV3< - PhoneNumber, PhoneNumber.Builder, PhoneNumberOrBuilder> phoneBuilder_; - - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - public java.util.List getPhoneList() { - if (phoneBuilder_ == null) { - return java.util.Collections.unmodifiableList(phone_); - } else { - return phoneBuilder_.getMessageList(); + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumberOrBuilder getPhoneOrBuilder( + int index) { + return phone_.get(index); } - } - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - public int getPhoneCount() { - if (phoneBuilder_ == null) { - return phone_.size(); - } else { - return phoneBuilder_.getCount(); + + public static final int DOUBLEMAP_FIELD_NUMBER = 9; + + private static final class DoubleMapDefaultEntryHolder { + static final com.google.protobuf.MapEntry defaultEntry = com.google.protobuf.MapEntry + . + newDefaultInstance( + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB + .internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_DoubleMapEntry_descriptor, + com.google.protobuf.WireFormat.FieldType.STRING, + "", + com.google.protobuf.WireFormat.FieldType.MESSAGE, + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber + .getDefaultInstance()); } - } - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getPhone(int index) { - if (phoneBuilder_ == null) { - return phone_.get(index); - } else { - return phoneBuilder_.getMessage(index); - } - } - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - public Builder setPhone( - int index, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber value) { - if (phoneBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - ensurePhoneIsMutable(); - phone_.set(index, value); - onChanged(); - } else { - phoneBuilder_.setMessage(index, value); - } - return this; - } - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - public Builder setPhone( - int index, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder builderForValue) { - if (phoneBuilder_ == null) { - ensurePhoneIsMutable(); - phone_.set(index, builderForValue.build()); - onChanged(); - } else { - phoneBuilder_.setMessage(index, builderForValue.build()); - } - return this; - } - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - public Builder addPhone(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber value) { - if (phoneBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - ensurePhoneIsMutable(); - phone_.add(value); - onChanged(); - } else { - phoneBuilder_.addMessage(value); - } - return this; - } - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - public Builder addPhone( - int index, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber value) { - if (phoneBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - ensurePhoneIsMutable(); - phone_.add(index, value); - onChanged(); - } else { - phoneBuilder_.addMessage(index, value); - } - return this; - } - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - public Builder addPhone( - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder builderForValue) { - if (phoneBuilder_ == null) { - ensurePhoneIsMutable(); - phone_.add(builderForValue.build()); - onChanged(); - } else { - phoneBuilder_.addMessage(builderForValue.build()); - } - return this; - } - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - public Builder addPhone( - int index, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder builderForValue) { - if (phoneBuilder_ == null) { - ensurePhoneIsMutable(); - phone_.add(index, builderForValue.build()); - onChanged(); - } else { - phoneBuilder_.addMessage(index, builderForValue.build()); - } - return this; - } - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - public Builder addAllPhone( - java.lang.Iterable values) { - if (phoneBuilder_ == null) { - ensurePhoneIsMutable(); - com.google.protobuf.AbstractMessageLite.Builder.addAll( - values, phone_); - onChanged(); - } else { - phoneBuilder_.addAllMessages(values); - } - return this; - } - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - public Builder clearPhone() { - if (phoneBuilder_ == null) { - phone_ = java.util.Collections.emptyList(); - bitField0_ = (bitField0_ & ~0x00000080); - onChanged(); - } else { - phoneBuilder_.clear(); - } - return this; - } - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - public Builder removePhone(int index) { - if (phoneBuilder_ == null) { - ensurePhoneIsMutable(); - phone_.remove(index); - onChanged(); - } else { - phoneBuilder_.remove(index); - } - return this; - } - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder getPhoneBuilder( - int index) { - return getPhoneFieldBuilder().getBuilder(index); - } - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumberOrBuilder getPhoneOrBuilder( - int index) { - if (phoneBuilder_ == null) { - return phone_.get(index); } else { - return phoneBuilder_.getMessageOrBuilder(index); - } - } - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - public java.util.List - getPhoneOrBuilderList() { - if (phoneBuilder_ != null) { - return phoneBuilder_.getMessageOrBuilderList(); - } else { - return java.util.Collections.unmodifiableList(phone_); - } - } - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder addPhoneBuilder() { - return getPhoneFieldBuilder().addBuilder( - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.getDefaultInstance()); - } - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder addPhoneBuilder( - int index) { - return getPhoneFieldBuilder().addBuilder( - index, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.getDefaultInstance()); - } - /** - * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; - */ - public java.util.List - getPhoneBuilderList() { - return getPhoneFieldBuilder().getBuilderList(); - } - private com.google.protobuf.RepeatedFieldBuilderV3< - PhoneNumber, PhoneNumber.Builder, PhoneNumberOrBuilder> - getPhoneFieldBuilder() { - if (phoneBuilder_ == null) { - phoneBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< - PhoneNumber, PhoneNumber.Builder, PhoneNumberOrBuilder>( - phone_, - ((bitField0_ & 0x00000080) == 0x00000080), - getParentForChildren(), - isClean()); - phone_ = null; - } - return phoneBuilder_; - } - private com.google.protobuf.MapField< - String, PhoneNumber> doubleMap_; - private com.google.protobuf.MapField - internalGetDoubleMap() { - if (doubleMap_ == null) { - return com.google.protobuf.MapField.emptyMapField( - DoubleMapDefaultEntryHolder.defaultEntry); - } - return doubleMap_; - } - private com.google.protobuf.MapField - internalGetMutableDoubleMap() { - onChanged();; - if (doubleMap_ == null) { - doubleMap_ = com.google.protobuf.MapField.newMapField( - DoubleMapDefaultEntryHolder.defaultEntry); - } - if (!doubleMap_.isMutable()) { - doubleMap_ = doubleMap_.copy(); - } - return doubleMap_; - } + private com.google.protobuf.MapField doubleMap_; - public int getDoubleMapCount() { - return internalGetDoubleMap().getMap().size(); - } - /** - * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; - */ - - public boolean containsDoubleMap( - java.lang.String key) { - if (key == null) { throw new java.lang.NullPointerException(); } - return internalGetDoubleMap().getMap().containsKey(key); - } - /** - * Use {@link #getDoubleMapMap()} instead. - */ - @java.lang.Deprecated - public java.util.Map getDoubleMap() { - return getDoubleMapMap(); - } - /** - * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; - */ - - public java.util.Map getDoubleMapMap() { - return internalGetDoubleMap().getMap(); - } - /** - * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; - */ - - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDoubleMapOrDefault( - java.lang.String key, - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber defaultValue) { - if (key == null) { throw new java.lang.NullPointerException(); } - java.util.Map map = - internalGetDoubleMap().getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; - } - /** - * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; - */ - - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDoubleMapOrThrow( - java.lang.String key) { - if (key == null) { throw new java.lang.NullPointerException(); } - java.util.Map map = - internalGetDoubleMap().getMap(); - if (!map.containsKey(key)) { - throw new java.lang.IllegalArgumentException(); - } - return map.get(key); - } - - public Builder clearDoubleMap() { - internalGetMutableDoubleMap().getMutableMap() - .clear(); - return this; - } - /** - * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; - */ - - public Builder removeDoubleMap( - java.lang.String key) { - if (key == null) { throw new java.lang.NullPointerException(); } - internalGetMutableDoubleMap().getMutableMap() - .remove(key); - return this; - } - /** - * Use alternate mutation accessors instead. - */ - @java.lang.Deprecated - public java.util.Map - getMutableDoubleMap() { - return internalGetMutableDoubleMap().getMutableMap(); - } - /** - * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; - */ - public Builder putDoubleMap( - java.lang.String key, - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber value) { - if (key == null) { throw new java.lang.NullPointerException(); } - if (value == null) { throw new java.lang.NullPointerException(); } - internalGetMutableDoubleMap().getMutableMap() - .put(key, value); - return this; - } - /** - * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; - */ - - public Builder putAllDoubleMap( - java.util.Map values) { - internalGetMutableDoubleMap().getMutableMap() - .putAll(values); - return this; - } - - private java.util.List bytesList_ = java.util.Collections.emptyList(); - private void ensureBytesListIsMutable() { - if (!((bitField0_ & 0x00000200) == 0x00000200)) { - bytesList_ = new java.util.ArrayList(bytesList_); - bitField0_ |= 0x00000200; - } - } - /** - * repeated bytes bytesList = 10; - */ - public java.util.List - getBytesListList() { - return java.util.Collections.unmodifiableList(bytesList_); - } - /** - * repeated bytes bytesList = 10; - */ - public int getBytesListCount() { - return bytesList_.size(); - } - /** - * repeated bytes bytesList = 10; - */ - public com.google.protobuf.ByteString getBytesList(int index) { - return bytesList_.get(index); - } - /** - * repeated bytes bytesList = 10; - */ - public Builder setBytesList( - int index, com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - ensureBytesListIsMutable(); - bytesList_.set(index, value); - onChanged(); - return this; - } - /** - * repeated bytes bytesList = 10; - */ - public Builder addBytesList(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - ensureBytesListIsMutable(); - bytesList_.add(value); - onChanged(); - return this; - } - /** - * repeated bytes bytesList = 10; - */ - public Builder addAllBytesList( - java.lang.Iterable values) { - ensureBytesListIsMutable(); - com.google.protobuf.AbstractMessageLite.Builder.addAll( - values, bytesList_); - onChanged(); - return this; - } - /** - * repeated bytes bytesList = 10; - */ - public Builder clearBytesList() { - bytesList_ = java.util.Collections.emptyList(); - bitField0_ = (bitField0_ & ~0x00000200); - onChanged(); - return this; - } - - private com.google.protobuf.MapField< - String, com.google.protobuf.ByteString> bytesMap_; - private com.google.protobuf.MapField - internalGetBytesMap() { - if (bytesMap_ == null) { - return com.google.protobuf.MapField.emptyMapField( - BytesMapDefaultEntryHolder.defaultEntry); - } - return bytesMap_; - } - private com.google.protobuf.MapField - internalGetMutableBytesMap() { - onChanged();; - if (bytesMap_ == null) { - bytesMap_ = com.google.protobuf.MapField.newMapField( - BytesMapDefaultEntryHolder.defaultEntry); - } - if (!bytesMap_.isMutable()) { - bytesMap_ = bytesMap_.copy(); - } - return bytesMap_; - } - - public int getBytesMapCount() { - return internalGetBytesMap().getMap().size(); - } - /** - * map<string, bytes> bytesMap = 11; - */ - - public boolean containsBytesMap( - java.lang.String key) { - if (key == null) { throw new java.lang.NullPointerException(); } - return internalGetBytesMap().getMap().containsKey(key); - } - /** - * Use {@link #getBytesMapMap()} instead. - */ - @java.lang.Deprecated - public java.util.Map getBytesMap() { - return getBytesMapMap(); - } - /** - * map<string, bytes> bytesMap = 11; - */ - - public java.util.Map getBytesMapMap() { - return internalGetBytesMap().getMap(); - } - /** - * map<string, bytes> bytesMap = 11; - */ - - public com.google.protobuf.ByteString getBytesMapOrDefault( - java.lang.String key, - com.google.protobuf.ByteString defaultValue) { - if (key == null) { throw new java.lang.NullPointerException(); } - java.util.Map map = - internalGetBytesMap().getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; - } - /** - * map<string, bytes> bytesMap = 11; - */ - - public com.google.protobuf.ByteString getBytesMapOrThrow( - java.lang.String key) { - if (key == null) { throw new java.lang.NullPointerException(); } - java.util.Map map = - internalGetBytesMap().getMap(); - if (!map.containsKey(key)) { - throw new java.lang.IllegalArgumentException(); - } - return map.get(key); - } - - public Builder clearBytesMap() { - internalGetMutableBytesMap().getMutableMap() - .clear(); - return this; - } - /** - * map<string, bytes> bytesMap = 11; - */ - - public Builder removeBytesMap( - java.lang.String key) { - if (key == null) { throw new java.lang.NullPointerException(); } - internalGetMutableBytesMap().getMutableMap() - .remove(key); - return this; - } - /** - * Use alternate mutation accessors instead. - */ - @java.lang.Deprecated - public java.util.Map - getMutableBytesMap() { - return internalGetMutableBytesMap().getMutableMap(); - } - /** - * map<string, bytes> bytesMap = 11; - */ - public Builder putBytesMap( - java.lang.String key, - com.google.protobuf.ByteString value) { - if (key == null) { throw new java.lang.NullPointerException(); } - if (value == null) { throw new java.lang.NullPointerException(); } - internalGetMutableBytesMap().getMutableMap() - .put(key, value); - return this; - } - /** - * map<string, bytes> bytesMap = 11; - */ - - public Builder putAllBytesMap( - java.util.Map values) { - internalGetMutableBytesMap().getMutableMap() - .putAll(values); - return this; - } - public final Builder setUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFields(unknownFields); - } - - public final Builder mergeUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); - } - - - // @@protoc_insertion_point(builder_scope:org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType) - } - - // @@protoc_insertion_point(class_scope:org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType) - private static final org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType(); - } - - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - @java.lang.Deprecated public static final com.google.protobuf.Parser - PARSER = new com.google.protobuf.AbstractParser() { - public PBRequestType parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new PBRequestType(input, extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } - - } - - public interface PBResponseTypeOrBuilder extends - // @@protoc_insertion_point(interface_extends:org.apache.dubbo.metadata.definition.protobuf.model.PBResponseType) - com.google.protobuf.MessageOrBuilder { - - /** - * optional string msg = 1; - */ - boolean hasMsg(); - /** - * optional string msg = 1; - */ - java.lang.String getMsg(); - /** - * optional string msg = 1; - */ - com.google.protobuf.ByteString - getMsgBytes(); - - /** - * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; - */ - boolean hasCDubboPBRequestType(); - /** - * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; - */ - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType getCDubboPBRequestType(); - /** - * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; - */ - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestTypeOrBuilder getCDubboPBRequestTypeOrBuilder(); - } - /** - * Protobuf type {@code org.apache.dubbo.metadata.definition.protobuf.model.PBResponseType} - */ - public static final class PBResponseType extends - com.google.protobuf.GeneratedMessageV3 implements - // @@protoc_insertion_point(message_implements:org.apache.dubbo.metadata.definition.protobuf.model.PBResponseType) - PBResponseTypeOrBuilder { - private static final long serialVersionUID = 0L; - // Use PBResponseType.newBuilder() to construct. - private PBResponseType(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - private PBResponseType() { - msg_ = ""; - } - - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet - getUnknownFields() { - return this.unknownFields; - } - private PBResponseType( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownField( - input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; + private com.google.protobuf.MapField internalGetDoubleMap() { + if (doubleMap_ == null) { + return com.google.protobuf.MapField.emptyMapField(DoubleMapDefaultEntryHolder.defaultEntry); } - case 10: { - com.google.protobuf.ByteString bs = input.readBytes(); - bitField0_ |= 0x00000001; - msg_ = bs; - break; + return doubleMap_; + } + + public int getDoubleMapCount() { + return internalGetDoubleMap().getMap().size(); + } + /** + * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; + */ + public boolean containsDoubleMap(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); } - case 26: { - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.Builder subBuilder = null; - if (((bitField0_ & 0x00000002) == 0x00000002)) { - subBuilder = cDubboPBRequestType_.toBuilder(); - } - cDubboPBRequestType_ = input.readMessage(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.PARSER, extensionRegistry); - if (subBuilder != null) { - subBuilder.mergeFrom(cDubboPBRequestType_); - cDubboPBRequestType_ = subBuilder.buildPartial(); - } - bitField0_ |= 0x00000002; - break; + return internalGetDoubleMap().getMap().containsKey(key); + } + /** + * Use {@link #getDoubleMapMap()} instead. + */ + @java.lang.Deprecated + public java.util.Map + getDoubleMap() { + return getDoubleMapMap(); + } + /** + * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; + */ + public java.util.Map + getDoubleMapMap() { + return internalGetDoubleMap().getMap(); + } + /** + * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; + */ + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDoubleMapOrDefault( + java.lang.String key, + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber defaultValue) { + if (key == null) { + throw new java.lang.NullPointerException(); } - } + java.util.Map + map = internalGetDoubleMap().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException( - e).setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); - } - } - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_descriptor; - } - - protected FieldAccessorTable - internalGetFieldAccessorTable() { - return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_fieldAccessorTable - .ensureFieldAccessorsInitialized( - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType.class, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType.Builder.class); - } - - private int bitField0_; - public static final int MSG_FIELD_NUMBER = 1; - private volatile java.lang.Object msg_; - /** - * optional string msg = 1; - */ - public boolean hasMsg() { - return ((bitField0_ & 0x00000001) == 0x00000001); - } - /** - * optional string msg = 1; - */ - public java.lang.String getMsg() { - java.lang.Object ref = msg_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - if (bs.isValidUtf8()) { - msg_ = s; + /** + * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; + */ + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDoubleMapOrThrow( + java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map + map = internalGetDoubleMap().getMap(); + if (!map.containsKey(key)) { + throw new java.lang.IllegalArgumentException(); + } + return map.get(key); } - return s; - } - } - /** - * optional string msg = 1; - */ - public com.google.protobuf.ByteString - getMsgBytes() { - java.lang.Object ref = msg_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); - msg_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - public static final int CDUBBOPBREQUESTTYPE_FIELD_NUMBER = 3; - private org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType cDubboPBRequestType_; - /** - * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; - */ - public boolean hasCDubboPBRequestType() { - return ((bitField0_ & 0x00000002) == 0x00000002); - } - /** - * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; - */ - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType getCDubboPBRequestType() { - return cDubboPBRequestType_ == null ? org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.getDefaultInstance() : cDubboPBRequestType_; - } - /** - * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; - */ - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestTypeOrBuilder getCDubboPBRequestTypeOrBuilder() { - return cDubboPBRequestType_ == null ? org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.getDefaultInstance() : cDubboPBRequestType_; - } - - private byte memoizedIsInitialized = -1; - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) return true; - if (isInitialized == 0) return false; - - if (hasCDubboPBRequestType()) { - if (!getCDubboPBRequestType().isInitialized()) { - memoizedIsInitialized = 0; - return false; + public static final int BYTESLIST_FIELD_NUMBER = 10; + private java.util.List bytesList_; + /** + * repeated bytes bytesList = 10; + */ + public java.util.List getBytesListList() { + return bytesList_; + } + /** + * repeated bytes bytesList = 10; + */ + public int getBytesListCount() { + return bytesList_.size(); + } + /** + * repeated bytes bytesList = 10; + */ + public com.google.protobuf.ByteString getBytesList(int index) { + return bytesList_.get(index); + } + + public static final int BYTESMAP_FIELD_NUMBER = 11; + + private static final class BytesMapDefaultEntryHolder { + static final com.google.protobuf.MapEntry defaultEntry = + com.google.protobuf.MapEntry.newDefaultInstance( + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB + .internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_BytesMapEntry_descriptor, + com.google.protobuf.WireFormat.FieldType.STRING, + "", + com.google.protobuf.WireFormat.FieldType.BYTES, + com.google.protobuf.ByteString.EMPTY); + } + + private com.google.protobuf.MapField bytesMap_; + + private com.google.protobuf.MapField internalGetBytesMap() { + if (bytesMap_ == null) { + return com.google.protobuf.MapField.emptyMapField(BytesMapDefaultEntryHolder.defaultEntry); + } + return bytesMap_; + } + + public int getBytesMapCount() { + return internalGetBytesMap().getMap().size(); + } + /** + * map<string, bytes> bytesMap = 11; + */ + public boolean containsBytesMap(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + return internalGetBytesMap().getMap().containsKey(key); + } + /** + * Use {@link #getBytesMapMap()} instead. + */ + @java.lang.Deprecated + public java.util.Map getBytesMap() { + return getBytesMapMap(); + } + /** + * map<string, bytes> bytesMap = 11; + */ + public java.util.Map getBytesMapMap() { + return internalGetBytesMap().getMap(); + } + /** + * map<string, bytes> bytesMap = 11; + */ + public com.google.protobuf.ByteString getBytesMapOrDefault( + java.lang.String key, com.google.protobuf.ByteString defaultValue) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map map = + internalGetBytesMap().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + /** + * map<string, bytes> bytesMap = 11; + */ + public com.google.protobuf.ByteString getBytesMapOrThrow(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map map = + internalGetBytesMap().getMap(); + if (!map.containsKey(key)) { + throw new java.lang.IllegalArgumentException(); + } + return map.get(key); + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + for (int i = 0; i < getPhoneCount(); i++) { + if (!getPhone(i).isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + for (org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber item : + getDoubleMapMap().values()) { + if (!item.isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeDouble(1, money_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeFloat(2, cash_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeInt32(3, age_); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + output.writeInt64(4, num_); + } + if (((bitField0_ & 0x00000010) == 0x00000010)) { + output.writeBool(5, sex_); + } + if (((bitField0_ & 0x00000020) == 0x00000020)) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 6, name_); + } + if (((bitField0_ & 0x00000040) == 0x00000040)) { + output.writeBytes(7, msg_); + } + for (int i = 0; i < phone_.size(); i++) { + output.writeMessage(8, phone_.get(i)); + } + com.google.protobuf.GeneratedMessageV3.serializeStringMapTo( + output, internalGetDoubleMap(), DoubleMapDefaultEntryHolder.defaultEntry, 9); + for (int i = 0; i < bytesList_.size(); i++) { + output.writeBytes(10, bytesList_.get(i)); + } + com.google.protobuf.GeneratedMessageV3.serializeStringMapTo( + output, internalGetBytesMap(), BytesMapDefaultEntryHolder.defaultEntry, 11); + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream.computeDoubleSize(1, money_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream.computeFloatSize(2, cash_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + size += com.google.protobuf.CodedOutputStream.computeInt32Size(3, age_); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + size += com.google.protobuf.CodedOutputStream.computeInt64Size(4, num_); + } + if (((bitField0_ & 0x00000010) == 0x00000010)) { + size += com.google.protobuf.CodedOutputStream.computeBoolSize(5, sex_); + } + if (((bitField0_ & 0x00000020) == 0x00000020)) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, name_); + } + if (((bitField0_ & 0x00000040) == 0x00000040)) { + size += com.google.protobuf.CodedOutputStream.computeBytesSize(7, msg_); + } + for (int i = 0; i < phone_.size(); i++) { + size += com.google.protobuf.CodedOutputStream.computeMessageSize(8, phone_.get(i)); + } + for (java.util.Map.Entry< + java.lang.String, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber> + entry : internalGetDoubleMap().getMap().entrySet()) { + com.google.protobuf.MapEntry doubleMap__ = DoubleMapDefaultEntryHolder.defaultEntry + .newBuilderForType() + .setKey(entry.getKey()) + .setValue(entry.getValue()) + .build(); + size += com.google.protobuf.CodedOutputStream.computeMessageSize(9, doubleMap__); + } + { + int dataSize = 0; + for (int i = 0; i < bytesList_.size(); i++) { + dataSize += com.google.protobuf.CodedOutputStream.computeBytesSizeNoTag(bytesList_.get(i)); + } + size += dataSize; + size += 1 * getBytesListList().size(); + } + for (java.util.Map.Entry entry : + internalGetBytesMap().getMap().entrySet()) { + com.google.protobuf.MapEntry bytesMap__ = + BytesMapDefaultEntryHolder.defaultEntry + .newBuilderForType() + .setKey(entry.getKey()) + .setValue(entry.getValue()) + .build(); + size += com.google.protobuf.CodedOutputStream.computeMessageSize(11, bytesMap__); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType)) { + return super.equals(obj); + } + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType other = + (org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType) obj; + + boolean result = true; + result = result && (hasMoney() == other.hasMoney()); + if (hasMoney()) { + result = result + && (java.lang.Double.doubleToLongBits(getMoney()) + == java.lang.Double.doubleToLongBits(other.getMoney())); + } + result = result && (hasCash() == other.hasCash()); + if (hasCash()) { + result = result + && (java.lang.Float.floatToIntBits(getCash()) + == java.lang.Float.floatToIntBits(other.getCash())); + } + result = result && (hasAge() == other.hasAge()); + if (hasAge()) { + result = result && (getAge() == other.getAge()); + } + result = result && (hasNum() == other.hasNum()); + if (hasNum()) { + result = result && (getNum() == other.getNum()); + } + result = result && (hasSex() == other.hasSex()); + if (hasSex()) { + result = result && (getSex() == other.getSex()); + } + result = result && (hasName() == other.hasName()); + if (hasName()) { + result = result && getName().equals(other.getName()); + } + result = result && (hasMsg() == other.hasMsg()); + if (hasMsg()) { + result = result && getMsg().equals(other.getMsg()); + } + result = result && getPhoneList().equals(other.getPhoneList()); + result = result && internalGetDoubleMap().equals(other.internalGetDoubleMap()); + result = result && getBytesListList().equals(other.getBytesListList()); + result = result && internalGetBytesMap().equals(other.internalGetBytesMap()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + if (hasMoney()) { + hash = (37 * hash) + MONEY_FIELD_NUMBER; + hash = (53 * hash) + + com.google.protobuf.Internal.hashLong(java.lang.Double.doubleToLongBits(getMoney())); + } + if (hasCash()) { + hash = (37 * hash) + CASH_FIELD_NUMBER; + hash = (53 * hash) + java.lang.Float.floatToIntBits(getCash()); + } + if (hasAge()) { + hash = (37 * hash) + AGE_FIELD_NUMBER; + hash = (53 * hash) + getAge(); + } + if (hasNum()) { + hash = (37 * hash) + NUM_FIELD_NUMBER; + hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getNum()); + } + if (hasSex()) { + hash = (37 * hash) + SEX_FIELD_NUMBER; + hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getSex()); + } + if (hasName()) { + hash = (37 * hash) + NAME_FIELD_NUMBER; + hash = (53 * hash) + getName().hashCode(); + } + if (hasMsg()) { + hash = (37 * hash) + MSG_FIELD_NUMBER; + hash = (53 * hash) + getMsg().hashCode(); + } + if (getPhoneCount() > 0) { + hash = (37 * hash) + PHONE_FIELD_NUMBER; + hash = (53 * hash) + getPhoneList().hashCode(); + } + if (!internalGetDoubleMap().getMap().isEmpty()) { + hash = (37 * hash) + DOUBLEMAP_FIELD_NUMBER; + hash = (53 * hash) + internalGetDoubleMap().hashCode(); + } + if (getBytesListCount() > 0) { + hash = (37 * hash) + BYTESLIST_FIELD_NUMBER; + hash = (53 * hash) + getBytesListList().hashCode(); + } + if (!internalGetBytesMap().getMap().isEmpty()) { + hash = (37 * hash) + BYTESMAP_FIELD_NUMBER; + hash = (53 * hash) + internalGetBytesMap().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom( + com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom( + com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseDelimitedFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom( + com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType} + */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType) + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestTypeOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB + .internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor; + } + + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMapField(int number) { + switch (number) { + case 9: + return internalGetDoubleMap(); + case 11: + return internalGetBytesMap(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } + } + + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMutableMapField(int number) { + switch (number) { + case 9: + return internalGetMutableDoubleMap(); + case 11: + return internalGetMutableBytesMap(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } + } + + protected FieldAccessorTable internalGetFieldAccessorTable() { + return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB + .internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.class, + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.Builder + .class); + } + + // Construct using org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { + getPhoneFieldBuilder(); + } + } + + public Builder clear() { + super.clear(); + money_ = 0D; + bitField0_ = (bitField0_ & ~0x00000001); + cash_ = 0F; + bitField0_ = (bitField0_ & ~0x00000002); + age_ = 0; + bitField0_ = (bitField0_ & ~0x00000004); + num_ = 0L; + bitField0_ = (bitField0_ & ~0x00000008); + sex_ = false; + bitField0_ = (bitField0_ & ~0x00000010); + name_ = ""; + bitField0_ = (bitField0_ & ~0x00000020); + msg_ = com.google.protobuf.ByteString.EMPTY; + bitField0_ = (bitField0_ & ~0x00000040); + if (phoneBuilder_ == null) { + phone_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000080); + } else { + phoneBuilder_.clear(); + } + internalGetMutableDoubleMap().clear(); + bytesList_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000200); + internalGetMutableBytesMap().clear(); + return this; + } + + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB + .internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor; + } + + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType + getDefaultInstanceForType() { + return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.getDefaultInstance(); + } + + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType build() { + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType buildPartial() { + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType result = + new org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.money_ = money_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.cash_ = cash_; + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + result.age_ = age_; + if (((from_bitField0_ & 0x00000008) == 0x00000008)) { + to_bitField0_ |= 0x00000008; + } + result.num_ = num_; + if (((from_bitField0_ & 0x00000010) == 0x00000010)) { + to_bitField0_ |= 0x00000010; + } + result.sex_ = sex_; + if (((from_bitField0_ & 0x00000020) == 0x00000020)) { + to_bitField0_ |= 0x00000020; + } + result.name_ = name_; + if (((from_bitField0_ & 0x00000040) == 0x00000040)) { + to_bitField0_ |= 0x00000040; + } + result.msg_ = msg_; + if (phoneBuilder_ == null) { + if (((bitField0_ & 0x00000080) == 0x00000080)) { + phone_ = java.util.Collections.unmodifiableList(phone_); + bitField0_ = (bitField0_ & ~0x00000080); + } + result.phone_ = phone_; + } else { + result.phone_ = phoneBuilder_.build(); + } + result.doubleMap_ = internalGetDoubleMap(); + result.doubleMap_.makeImmutable(); + if (((bitField0_ & 0x00000200) == 0x00000200)) { + bytesList_ = java.util.Collections.unmodifiableList(bytesList_); + bitField0_ = (bitField0_ & ~0x00000200); + } + result.bytesList_ = bytesList_; + result.bytesMap_ = internalGetBytesMap(); + result.bytesMap_.makeImmutable(); + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder clone() { + return (Builder) super.clone(); + } + + public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); + } + + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } + + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } + + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } + + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType) { + return mergeFrom( + (org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType) other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType other) { + if (other + == org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType + .getDefaultInstance()) return this; + if (other.hasMoney()) { + setMoney(other.getMoney()); + } + if (other.hasCash()) { + setCash(other.getCash()); + } + if (other.hasAge()) { + setAge(other.getAge()); + } + if (other.hasNum()) { + setNum(other.getNum()); + } + if (other.hasSex()) { + setSex(other.getSex()); + } + if (other.hasName()) { + bitField0_ |= 0x00000020; + name_ = other.name_; + onChanged(); + } + if (other.hasMsg()) { + setMsg(other.getMsg()); + } + if (phoneBuilder_ == null) { + if (!other.phone_.isEmpty()) { + if (phone_.isEmpty()) { + phone_ = other.phone_; + bitField0_ = (bitField0_ & ~0x00000080); + } else { + ensurePhoneIsMutable(); + phone_.addAll(other.phone_); + } + onChanged(); + } + } else { + if (!other.phone_.isEmpty()) { + if (phoneBuilder_.isEmpty()) { + phoneBuilder_.dispose(); + phoneBuilder_ = null; + phone_ = other.phone_; + bitField0_ = (bitField0_ & ~0x00000080); + phoneBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders + ? getPhoneFieldBuilder() + : null; + } else { + phoneBuilder_.addAllMessages(other.phone_); + } + } + } + internalGetMutableDoubleMap().mergeFrom(other.internalGetDoubleMap()); + if (!other.bytesList_.isEmpty()) { + if (bytesList_.isEmpty()) { + bytesList_ = other.bytesList_; + bitField0_ = (bitField0_ & ~0x00000200); + } else { + ensureBytesListIsMutable(); + bytesList_.addAll(other.bytesList_); + } + onChanged(); + } + internalGetMutableBytesMap().mergeFrom(other.internalGetBytesMap()); + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + public final boolean isInitialized() { + for (int i = 0; i < getPhoneCount(); i++) { + if (!getPhone(i).isInitialized()) { + return false; + } + } + for (org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber item : + getDoubleMapMap().values()) { + if (!item.isInitialized()) { + return false; + } + } + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType) + e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private int bitField0_; + + private double money_; + /** + * optional double money = 1; + */ + public boolean hasMoney() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * optional double money = 1; + */ + public double getMoney() { + return money_; + } + /** + * optional double money = 1; + */ + public Builder setMoney(double value) { + bitField0_ |= 0x00000001; + money_ = value; + onChanged(); + return this; + } + /** + * optional double money = 1; + */ + public Builder clearMoney() { + bitField0_ = (bitField0_ & ~0x00000001); + money_ = 0D; + onChanged(); + return this; + } + + private float cash_; + /** + * optional float cash = 2; + */ + public boolean hasCash() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * optional float cash = 2; + */ + public float getCash() { + return cash_; + } + /** + * optional float cash = 2; + */ + public Builder setCash(float value) { + bitField0_ |= 0x00000002; + cash_ = value; + onChanged(); + return this; + } + /** + * optional float cash = 2; + */ + public Builder clearCash() { + bitField0_ = (bitField0_ & ~0x00000002); + cash_ = 0F; + onChanged(); + return this; + } + + private int age_; + /** + * optional int32 age = 3; + */ + public boolean hasAge() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + /** + * optional int32 age = 3; + */ + public int getAge() { + return age_; + } + /** + * optional int32 age = 3; + */ + public Builder setAge(int value) { + bitField0_ |= 0x00000004; + age_ = value; + onChanged(); + return this; + } + /** + * optional int32 age = 3; + */ + public Builder clearAge() { + bitField0_ = (bitField0_ & ~0x00000004); + age_ = 0; + onChanged(); + return this; + } + + private long num_; + /** + * optional int64 num = 4; + */ + public boolean hasNum() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + /** + * optional int64 num = 4; + */ + public long getNum() { + return num_; + } + /** + * optional int64 num = 4; + */ + public Builder setNum(long value) { + bitField0_ |= 0x00000008; + num_ = value; + onChanged(); + return this; + } + /** + * optional int64 num = 4; + */ + public Builder clearNum() { + bitField0_ = (bitField0_ & ~0x00000008); + num_ = 0L; + onChanged(); + return this; + } + + private boolean sex_; + /** + * optional bool sex = 5; + */ + public boolean hasSex() { + return ((bitField0_ & 0x00000010) == 0x00000010); + } + /** + * optional bool sex = 5; + */ + public boolean getSex() { + return sex_; + } + /** + * optional bool sex = 5; + */ + public Builder setSex(boolean value) { + bitField0_ |= 0x00000010; + sex_ = value; + onChanged(); + return this; + } + /** + * optional bool sex = 5; + */ + public Builder clearSex() { + bitField0_ = (bitField0_ & ~0x00000010); + sex_ = false; + onChanged(); + return this; + } + + private java.lang.Object name_ = ""; + /** + * optional string name = 6; + */ + public boolean hasName() { + return ((bitField0_ & 0x00000020) == 0x00000020); + } + /** + * optional string name = 6; + */ + public java.lang.String getName() { + java.lang.Object ref = name_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + name_ = s; + } + return s; + } else { + return (java.lang.String) ref; + } + } + /** + * optional string name = 6; + */ + public com.google.protobuf.ByteString getNameBytes() { + java.lang.Object ref = name_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + name_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + * optional string name = 6; + */ + public Builder setName(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000020; + name_ = value; + onChanged(); + return this; + } + /** + * optional string name = 6; + */ + public Builder clearName() { + bitField0_ = (bitField0_ & ~0x00000020); + name_ = getDefaultInstance().getName(); + onChanged(); + return this; + } + /** + * optional string name = 6; + */ + public Builder setNameBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000020; + name_ = value; + onChanged(); + return this; + } + + private com.google.protobuf.ByteString msg_ = com.google.protobuf.ByteString.EMPTY; + /** + * optional bytes msg = 7; + */ + public boolean hasMsg() { + return ((bitField0_ & 0x00000040) == 0x00000040); + } + /** + * optional bytes msg = 7; + */ + public com.google.protobuf.ByteString getMsg() { + return msg_; + } + /** + * optional bytes msg = 7; + */ + public Builder setMsg(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000040; + msg_ = value; + onChanged(); + return this; + } + /** + * optional bytes msg = 7; + */ + public Builder clearMsg() { + bitField0_ = (bitField0_ & ~0x00000040); + msg_ = getDefaultInstance().getMsg(); + onChanged(); + return this; + } + + private java.util.List phone_ = + java.util.Collections.emptyList(); + + private void ensurePhoneIsMutable() { + if (!((bitField0_ & 0x00000080) == 0x00000080)) { + phone_ = new java.util.ArrayList< + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber>(phone_); + bitField0_ |= 0x00000080; + } + } + + private com.google.protobuf.RepeatedFieldBuilderV3 + phoneBuilder_; + + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + public java.util.List + getPhoneList() { + if (phoneBuilder_ == null) { + return java.util.Collections.unmodifiableList(phone_); + } else { + return phoneBuilder_.getMessageList(); + } + } + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + public int getPhoneCount() { + if (phoneBuilder_ == null) { + return phone_.size(); + } else { + return phoneBuilder_.getCount(); + } + } + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getPhone(int index) { + if (phoneBuilder_ == null) { + return phone_.get(index); + } else { + return phoneBuilder_.getMessage(index); + } + } + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + public Builder setPhone( + int index, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber value) { + if (phoneBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensurePhoneIsMutable(); + phone_.set(index, value); + onChanged(); + } else { + phoneBuilder_.setMessage(index, value); + } + return this; + } + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + public Builder setPhone( + int index, + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder builderForValue) { + if (phoneBuilder_ == null) { + ensurePhoneIsMutable(); + phone_.set(index, builderForValue.build()); + onChanged(); + } else { + phoneBuilder_.setMessage(index, builderForValue.build()); + } + return this; + } + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + public Builder addPhone(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber value) { + if (phoneBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensurePhoneIsMutable(); + phone_.add(value); + onChanged(); + } else { + phoneBuilder_.addMessage(value); + } + return this; + } + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + public Builder addPhone( + int index, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber value) { + if (phoneBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensurePhoneIsMutable(); + phone_.add(index, value); + onChanged(); + } else { + phoneBuilder_.addMessage(index, value); + } + return this; + } + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + public Builder addPhone( + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder builderForValue) { + if (phoneBuilder_ == null) { + ensurePhoneIsMutable(); + phone_.add(builderForValue.build()); + onChanged(); + } else { + phoneBuilder_.addMessage(builderForValue.build()); + } + return this; + } + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + public Builder addPhone( + int index, + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder builderForValue) { + if (phoneBuilder_ == null) { + ensurePhoneIsMutable(); + phone_.add(index, builderForValue.build()); + onChanged(); + } else { + phoneBuilder_.addMessage(index, builderForValue.build()); + } + return this; + } + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + public Builder addAllPhone( + java.lang.Iterable< + ? extends org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber> + values) { + if (phoneBuilder_ == null) { + ensurePhoneIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll(values, phone_); + onChanged(); + } else { + phoneBuilder_.addAllMessages(values); + } + return this; + } + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + public Builder clearPhone() { + if (phoneBuilder_ == null) { + phone_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000080); + onChanged(); + } else { + phoneBuilder_.clear(); + } + return this; + } + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + public Builder removePhone(int index) { + if (phoneBuilder_ == null) { + ensurePhoneIsMutable(); + phone_.remove(index); + onChanged(); + } else { + phoneBuilder_.remove(index); + } + return this; + } + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder getPhoneBuilder( + int index) { + return getPhoneFieldBuilder().getBuilder(index); + } + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumberOrBuilder getPhoneOrBuilder( + int index) { + if (phoneBuilder_ == null) { + return phone_.get(index); + } else { + return phoneBuilder_.getMessageOrBuilder(index); + } + } + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + public java.util.List< + ? extends org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumberOrBuilder> + getPhoneOrBuilderList() { + if (phoneBuilder_ != null) { + return phoneBuilder_.getMessageOrBuilderList(); + } else { + return java.util.Collections.unmodifiableList(phone_); + } + } + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder addPhoneBuilder() { + return getPhoneFieldBuilder() + .addBuilder( + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber + .getDefaultInstance()); + } + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder addPhoneBuilder( + int index) { + return getPhoneFieldBuilder() + .addBuilder( + index, + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber + .getDefaultInstance()); + } + /** + * repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8; + */ + public java.util.List + getPhoneBuilderList() { + return getPhoneFieldBuilder().getBuilderList(); + } + + private com.google.protobuf.RepeatedFieldBuilderV3 + getPhoneFieldBuilder() { + if (phoneBuilder_ == null) { + phoneBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< + PhoneNumber, PhoneNumber.Builder, PhoneNumberOrBuilder>( + phone_, ((bitField0_ & 0x00000080) == 0x00000080), getParentForChildren(), isClean()); + phone_ = null; + } + return phoneBuilder_; + } + + private com.google.protobuf.MapField doubleMap_; + + private com.google.protobuf.MapField internalGetDoubleMap() { + if (doubleMap_ == null) { + return com.google.protobuf.MapField.emptyMapField(DoubleMapDefaultEntryHolder.defaultEntry); + } + return doubleMap_; + } + + private com.google.protobuf.MapField internalGetMutableDoubleMap() { + onChanged(); + ; + if (doubleMap_ == null) { + doubleMap_ = com.google.protobuf.MapField.newMapField(DoubleMapDefaultEntryHolder.defaultEntry); + } + if (!doubleMap_.isMutable()) { + doubleMap_ = doubleMap_.copy(); + } + return doubleMap_; + } + + public int getDoubleMapCount() { + return internalGetDoubleMap().getMap().size(); + } + /** + * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; + */ + public boolean containsDoubleMap(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + return internalGetDoubleMap().getMap().containsKey(key); + } + /** + * Use {@link #getDoubleMapMap()} instead. + */ + @java.lang.Deprecated + public java.util.Map< + java.lang.String, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber> + getDoubleMap() { + return getDoubleMapMap(); + } + /** + * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; + */ + public java.util.Map< + java.lang.String, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber> + getDoubleMapMap() { + return internalGetDoubleMap().getMap(); + } + /** + * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; + */ + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDoubleMapOrDefault( + java.lang.String key, + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber defaultValue) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map< + java.lang.String, + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber> + map = internalGetDoubleMap().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + /** + * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; + */ + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDoubleMapOrThrow( + java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map< + java.lang.String, + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber> + map = internalGetDoubleMap().getMap(); + if (!map.containsKey(key)) { + throw new java.lang.IllegalArgumentException(); + } + return map.get(key); + } + + public Builder clearDoubleMap() { + internalGetMutableDoubleMap().getMutableMap().clear(); + return this; + } + /** + * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; + */ + public Builder removeDoubleMap(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + internalGetMutableDoubleMap().getMutableMap().remove(key); + return this; + } + /** + * Use alternate mutation accessors instead. + */ + @java.lang.Deprecated + public java.util.Map< + java.lang.String, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber> + getMutableDoubleMap() { + return internalGetMutableDoubleMap().getMutableMap(); + } + /** + * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; + */ + public Builder putDoubleMap( + java.lang.String key, + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber value) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + if (value == null) { + throw new java.lang.NullPointerException(); + } + internalGetMutableDoubleMap().getMutableMap().put(key, value); + return this; + } + /** + * map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9; + */ + public Builder putAllDoubleMap( + java.util.Map< + java.lang.String, + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber> + values) { + internalGetMutableDoubleMap().getMutableMap().putAll(values); + return this; + } + + private java.util.List bytesList_ = java.util.Collections.emptyList(); + + private void ensureBytesListIsMutable() { + if (!((bitField0_ & 0x00000200) == 0x00000200)) { + bytesList_ = new java.util.ArrayList(bytesList_); + bitField0_ |= 0x00000200; + } + } + /** + * repeated bytes bytesList = 10; + */ + public java.util.List getBytesListList() { + return java.util.Collections.unmodifiableList(bytesList_); + } + /** + * repeated bytes bytesList = 10; + */ + public int getBytesListCount() { + return bytesList_.size(); + } + /** + * repeated bytes bytesList = 10; + */ + public com.google.protobuf.ByteString getBytesList(int index) { + return bytesList_.get(index); + } + /** + * repeated bytes bytesList = 10; + */ + public Builder setBytesList(int index, com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + ensureBytesListIsMutable(); + bytesList_.set(index, value); + onChanged(); + return this; + } + /** + * repeated bytes bytesList = 10; + */ + public Builder addBytesList(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + ensureBytesListIsMutable(); + bytesList_.add(value); + onChanged(); + return this; + } + /** + * repeated bytes bytesList = 10; + */ + public Builder addAllBytesList(java.lang.Iterable values) { + ensureBytesListIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll(values, bytesList_); + onChanged(); + return this; + } + /** + * repeated bytes bytesList = 10; + */ + public Builder clearBytesList() { + bytesList_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000200); + onChanged(); + return this; + } + + private com.google.protobuf.MapField bytesMap_; + + private com.google.protobuf.MapField internalGetBytesMap() { + if (bytesMap_ == null) { + return com.google.protobuf.MapField.emptyMapField(BytesMapDefaultEntryHolder.defaultEntry); + } + return bytesMap_; + } + + private com.google.protobuf.MapField internalGetMutableBytesMap() { + onChanged(); + ; + if (bytesMap_ == null) { + bytesMap_ = com.google.protobuf.MapField.newMapField(BytesMapDefaultEntryHolder.defaultEntry); + } + if (!bytesMap_.isMutable()) { + bytesMap_ = bytesMap_.copy(); + } + return bytesMap_; + } + + public int getBytesMapCount() { + return internalGetBytesMap().getMap().size(); + } + /** + * map<string, bytes> bytesMap = 11; + */ + public boolean containsBytesMap(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + return internalGetBytesMap().getMap().containsKey(key); + } + /** + * Use {@link #getBytesMapMap()} instead. + */ + @java.lang.Deprecated + public java.util.Map getBytesMap() { + return getBytesMapMap(); + } + /** + * map<string, bytes> bytesMap = 11; + */ + public java.util.Map getBytesMapMap() { + return internalGetBytesMap().getMap(); + } + /** + * map<string, bytes> bytesMap = 11; + */ + public com.google.protobuf.ByteString getBytesMapOrDefault( + java.lang.String key, com.google.protobuf.ByteString defaultValue) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map map = + internalGetBytesMap().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + /** + * map<string, bytes> bytesMap = 11; + */ + public com.google.protobuf.ByteString getBytesMapOrThrow(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map map = + internalGetBytesMap().getMap(); + if (!map.containsKey(key)) { + throw new java.lang.IllegalArgumentException(); + } + return map.get(key); + } + + public Builder clearBytesMap() { + internalGetMutableBytesMap().getMutableMap().clear(); + return this; + } + /** + * map<string, bytes> bytesMap = 11; + */ + public Builder removeBytesMap(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + internalGetMutableBytesMap().getMutableMap().remove(key); + return this; + } + /** + * Use alternate mutation accessors instead. + */ + @java.lang.Deprecated + public java.util.Map getMutableBytesMap() { + return internalGetMutableBytesMap().getMutableMap(); + } + /** + * map<string, bytes> bytesMap = 11; + */ + public Builder putBytesMap(java.lang.String key, com.google.protobuf.ByteString value) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + if (value == null) { + throw new java.lang.NullPointerException(); + } + internalGetMutableBytesMap().getMutableMap().put(key, value); + return this; + } + /** + * map<string, bytes> bytesMap = 11; + */ + public Builder putAllBytesMap(java.util.Map values) { + internalGetMutableBytesMap().getMutableMap().putAll(values); + return this; + } + + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFields(unknownFields); + } + + public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + // @@protoc_insertion_point(builder_scope:org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType) + } + + // @@protoc_insertion_point(class_scope:org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType) + private static final org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType + DEFAULT_INSTANCE; + + static { + DEFAULT_INSTANCE = new org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType(); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + @java.lang.Deprecated + public static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public PBRequestType parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new PBRequestType(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType getDefaultInstanceForType() { + return DEFAULT_INSTANCE; } - } - memoizedIsInitialized = 1; - return true; } - public void writeTo(com.google.protobuf.CodedOutputStream output) - throws java.io.IOException { - if (((bitField0_ & 0x00000001) == 0x00000001)) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 1, msg_); - } - if (((bitField0_ & 0x00000002) == 0x00000002)) { - output.writeMessage(3, getCDubboPBRequestType()); - } - unknownFields.writeTo(output); - } + public interface PBResponseTypeOrBuilder + extends + // @@protoc_insertion_point(interface_extends:org.apache.dubbo.metadata.definition.protobuf.model.PBResponseType) + com.google.protobuf.MessageOrBuilder { - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) return size; + /** + * optional string msg = 1; + */ + boolean hasMsg(); + /** + * optional string msg = 1; + */ + java.lang.String getMsg(); + /** + * optional string msg = 1; + */ + com.google.protobuf.ByteString getMsgBytes(); - size = 0; - if (((bitField0_ & 0x00000001) == 0x00000001)) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, msg_); - } - if (((bitField0_ & 0x00000002) == 0x00000002)) { - size += com.google.protobuf.CodedOutputStream - .computeMessageSize(3, getCDubboPBRequestType()); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; - } - - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType)) { - return super.equals(obj); - } - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType other = (org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType) obj; - - boolean result = true; - result = result && (hasMsg() == other.hasMsg()); - if (hasMsg()) { - result = result && getMsg() - .equals(other.getMsg()); - } - result = result && (hasCDubboPBRequestType() == other.hasCDubboPBRequestType()); - if (hasCDubboPBRequestType()) { - result = result && getCDubboPBRequestType() - .equals(other.getCDubboPBRequestType()); - } - result = result && unknownFields.equals(other.unknownFields); - return result; - } - - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - if (hasMsg()) { - hash = (37 * hash) + MSG_FIELD_NUMBER; - hash = (53 * hash) + getMsg().hashCode(); - } - if (hasCDubboPBRequestType()) { - hash = (37 * hash) + CDUBBOPBREQUESTTYPE_FIELD_NUMBER; - hash = (53 * hash) + getCDubboPBRequestType().hashCode(); - } - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; - } - - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom( - java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom( - java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input, extensionRegistry); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } - public static Builder newBuilder(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); - } - public Builder toBuilder() { - return this == DEFAULT_INSTANCE - ? new Builder() : new Builder().mergeFrom(this); - } - - @java.lang.Override - protected Builder newBuilderForType( - BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; + /** + * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + boolean hasCDubboPBRequestType(); + /** + * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType getCDubboPBRequestType(); + /** + * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestTypeOrBuilder + getCDubboPBRequestTypeOrBuilder(); } /** * Protobuf type {@code org.apache.dubbo.metadata.definition.protobuf.model.PBResponseType} */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder implements - // @@protoc_insertion_point(builder_implements:org.apache.dubbo.metadata.definition.protobuf.model.PBResponseType) - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseTypeOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_descriptor; - } - - protected FieldAccessorTable - internalGetFieldAccessorTable() { - return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_fieldAccessorTable - .ensureFieldAccessorsInitialized( - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType.class, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType.Builder.class); - } - - // Construct using org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder( - BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3 - .alwaysUseFieldBuilders) { - getCDubboPBRequestTypeFieldBuilder(); + public static final class PBResponseType extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:org.apache.dubbo.metadata.definition.protobuf.model.PBResponseType) + PBResponseTypeOrBuilder { + private static final long serialVersionUID = 0L; + // Use PBResponseType.newBuilder() to construct. + private PBResponseType(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); } - } - public Builder clear() { - super.clear(); - msg_ = ""; - bitField0_ = (bitField0_ & ~0x00000001); - if (cDubboPBRequestTypeBuilder_ == null) { - cDubboPBRequestType_ = null; - } else { - cDubboPBRequestTypeBuilder_.clear(); + + private PBResponseType() { + msg_ = ""; } - bitField0_ = (bitField0_ & ~0x00000002); - return this; - } - public com.google.protobuf.Descriptors.Descriptor - getDescriptorForType() { - return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_descriptor; - } - - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType getDefaultInstanceForType() { - return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType.getDefaultInstance(); - } - - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType build() { - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; } - return result; - } - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType buildPartial() { - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType result = new org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType(this); - int from_bitField0_ = bitField0_; - int to_bitField0_ = 0; - if (((from_bitField0_ & 0x00000001) == 0x00000001)) { - to_bitField0_ |= 0x00000001; - } - result.msg_ = msg_; - if (((from_bitField0_ & 0x00000002) == 0x00000002)) { - to_bitField0_ |= 0x00000002; - } - if (cDubboPBRequestTypeBuilder_ == null) { - result.cDubboPBRequestType_ = cDubboPBRequestType_; - } else { - result.cDubboPBRequestType_ = cDubboPBRequestTypeBuilder_.build(); - } - result.bitField0_ = to_bitField0_; - onBuilt(); - return result; - } - - public Builder clone() { - return (Builder) super.clone(); - } - public Builder setField( - com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } - public Builder clearField( - com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - public Builder clearOneof( - com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - public Builder setRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } - public Builder addRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType) { - return mergeFrom((org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType)other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType other) { - if (other == org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType.getDefaultInstance()) return this; - if (other.hasMsg()) { - bitField0_ |= 0x00000001; - msg_ = other.msg_; - onChanged(); - } - if (other.hasCDubboPBRequestType()) { - mergeCDubboPBRequestType(other.getCDubboPBRequestType()); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - public final boolean isInitialized() { - if (hasCDubboPBRequestType()) { - if (!getCDubboPBRequestType().isInitialized()) { - return false; - } - } - return true; - } - - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType) e.getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - private int bitField0_; - - private java.lang.Object msg_ = ""; - /** - * optional string msg = 1; - */ - public boolean hasMsg() { - return ((bitField0_ & 0x00000001) == 0x00000001); - } - /** - * optional string msg = 1; - */ - public java.lang.String getMsg() { - java.lang.Object ref = msg_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - if (bs.isValidUtf8()) { - msg_ = s; - } - return s; - } else { - return (java.lang.String) ref; - } - } - /** - * optional string msg = 1; - */ - public com.google.protobuf.ByteString - getMsgBytes() { - java.lang.Object ref = msg_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); - msg_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - /** - * optional string msg = 1; - */ - public Builder setMsg( - java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000001; - msg_ = value; - onChanged(); - return this; - } - /** - * optional string msg = 1; - */ - public Builder clearMsg() { - bitField0_ = (bitField0_ & ~0x00000001); - msg_ = getDefaultInstance().getMsg(); - onChanged(); - return this; - } - /** - * optional string msg = 1; - */ - public Builder setMsgBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000001; - msg_ = value; - onChanged(); - return this; - } - - private org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType cDubboPBRequestType_ = null; - private com.google.protobuf.SingleFieldBuilderV3< - PBRequestType, PBRequestType.Builder, PBRequestTypeOrBuilder> cDubboPBRequestTypeBuilder_; - /** - * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; - */ - public boolean hasCDubboPBRequestType() { - return ((bitField0_ & 0x00000002) == 0x00000002); - } - /** - * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; - */ - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType getCDubboPBRequestType() { - if (cDubboPBRequestTypeBuilder_ == null) { - return cDubboPBRequestType_ == null ? org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.getDefaultInstance() : cDubboPBRequestType_; - } else { - return cDubboPBRequestTypeBuilder_.getMessage(); - } - } - /** - * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; - */ - public Builder setCDubboPBRequestType(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType value) { - if (cDubboPBRequestTypeBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - cDubboPBRequestType_ = value; - onChanged(); - } else { - cDubboPBRequestTypeBuilder_.setMessage(value); - } - bitField0_ |= 0x00000002; - return this; - } - /** - * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; - */ - public Builder setCDubboPBRequestType( - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.Builder builderForValue) { - if (cDubboPBRequestTypeBuilder_ == null) { - cDubboPBRequestType_ = builderForValue.build(); - onChanged(); - } else { - cDubboPBRequestTypeBuilder_.setMessage(builderForValue.build()); - } - bitField0_ |= 0x00000002; - return this; - } - /** - * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; - */ - public Builder mergeCDubboPBRequestType(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType value) { - if (cDubboPBRequestTypeBuilder_ == null) { - if (((bitField0_ & 0x00000002) == 0x00000002) && - cDubboPBRequestType_ != null && - cDubboPBRequestType_ != org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.getDefaultInstance()) { - cDubboPBRequestType_ = - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.newBuilder(cDubboPBRequestType_).mergeFrom(value).buildPartial(); - } else { - cDubboPBRequestType_ = value; - } - onChanged(); - } else { - cDubboPBRequestTypeBuilder_.mergeFrom(value); - } - bitField0_ |= 0x00000002; - return this; - } - /** - * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; - */ - public Builder clearCDubboPBRequestType() { - if (cDubboPBRequestTypeBuilder_ == null) { - cDubboPBRequestType_ = null; - onChanged(); - } else { - cDubboPBRequestTypeBuilder_.clear(); - } - bitField0_ = (bitField0_ & ~0x00000002); - return this; - } - /** - * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; - */ - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.Builder getCDubboPBRequestTypeBuilder() { - bitField0_ |= 0x00000002; - onChanged(); - return getCDubboPBRequestTypeFieldBuilder().getBuilder(); - } - /** - * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; - */ - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestTypeOrBuilder getCDubboPBRequestTypeOrBuilder() { - if (cDubboPBRequestTypeBuilder_ != null) { - return cDubboPBRequestTypeBuilder_.getMessageOrBuilder(); - } else { - return cDubboPBRequestType_ == null ? - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.getDefaultInstance() : cDubboPBRequestType_; - } - } - /** - * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; - */ - private com.google.protobuf.SingleFieldBuilderV3< - PBRequestType, PBRequestType.Builder, PBRequestTypeOrBuilder> - getCDubboPBRequestTypeFieldBuilder() { - if (cDubboPBRequestTypeBuilder_ == null) { - cDubboPBRequestTypeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< - PBRequestType, PBRequestType.Builder, PBRequestTypeOrBuilder>( - getCDubboPBRequestType(), - getParentForChildren(), - isClean()); - cDubboPBRequestType_ = null; - } - return cDubboPBRequestTypeBuilder_; - } - public final Builder setUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFields(unknownFields); - } - - public final Builder mergeUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); - } - - - // @@protoc_insertion_point(builder_scope:org.apache.dubbo.metadata.definition.protobuf.model.PBResponseType) - } - - // @@protoc_insertion_point(class_scope:org.apache.dubbo.metadata.definition.protobuf.model.PBResponseType) - private static final org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType(); - } - - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - @java.lang.Deprecated public static final com.google.protobuf.Parser - PARSER = new com.google.protobuf.AbstractParser() { - public PBResponseType parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new PBResponseType(input, extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } - - } - - public interface PhoneNumberOrBuilder extends - // @@protoc_insertion_point(interface_extends:org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber) - com.google.protobuf.MessageOrBuilder { - - /** - * required string number = 1; - */ - boolean hasNumber(); - /** - * required string number = 1; - */ - java.lang.String getNumber(); - /** - * required string number = 1; - */ - com.google.protobuf.ByteString - getNumberBytes(); - - /** - * optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME]; - */ - boolean hasType(); - /** - * optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME]; - */ - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType getType(); - } - /** - * Protobuf type {@code org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber} - */ - public static final class PhoneNumber extends - com.google.protobuf.GeneratedMessageV3 implements - // @@protoc_insertion_point(message_implements:org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber) - PhoneNumberOrBuilder { - private static final long serialVersionUID = 0L; - // Use PhoneNumber.newBuilder() to construct. - private PhoneNumber(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - private PhoneNumber() { - number_ = ""; - type_ = 1; - } - - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet - getUnknownFields() { - return this.unknownFields; - } - private PhoneNumber( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownField( - input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; + private PBResponseType( + com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: { + com.google.protobuf.ByteString bs = input.readBytes(); + bitField0_ |= 0x00000001; + msg_ = bs; + break; + } + case 26: { + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.Builder + subBuilder = null; + if (((bitField0_ & 0x00000002) == 0x00000002)) { + subBuilder = cDubboPBRequestType_.toBuilder(); + } + cDubboPBRequestType_ = input.readMessage( + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.PARSER, + extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(cDubboPBRequestType_); + cDubboPBRequestType_ = subBuilder.buildPartial(); + } + bitField0_ |= 0x00000002; + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); } - case 10: { - com.google.protobuf.ByteString bs = input.readBytes(); - bitField0_ |= 0x00000001; - number_ = bs; - break; + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB + .internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_descriptor; + } + + protected FieldAccessorTable internalGetFieldAccessorTable() { + return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB + .internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType.class, + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType.Builder.class); + } + + private int bitField0_; + public static final int MSG_FIELD_NUMBER = 1; + private volatile java.lang.Object msg_; + /** + * optional string msg = 1; + */ + public boolean hasMsg() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * optional string msg = 1; + */ + public java.lang.String getMsg() { + java.lang.Object ref = msg_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + msg_ = s; + } + return s; } - case 16: { - int rawValue = input.readEnum(); - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType value = org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType.valueOf(rawValue); - if (value == null) { - unknownFields.mergeVarintField(2, rawValue); - } else { + } + /** + * optional string msg = 1; + */ + public com.google.protobuf.ByteString getMsgBytes() { + java.lang.Object ref = msg_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + msg_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int CDUBBOPBREQUESTTYPE_FIELD_NUMBER = 3; + private org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType cDubboPBRequestType_; + /** + * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + public boolean hasCDubboPBRequestType() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType getCDubboPBRequestType() { + return cDubboPBRequestType_ == null + ? org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.getDefaultInstance() + : cDubboPBRequestType_; + } + /** + * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestTypeOrBuilder + getCDubboPBRequestTypeOrBuilder() { + return cDubboPBRequestType_ == null + ? org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.getDefaultInstance() + : cDubboPBRequestType_; + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + if (hasCDubboPBRequestType()) { + if (!getCDubboPBRequestType().isInitialized()) { + memoizedIsInitialized = 0; + return false; + } + } + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + if (((bitField0_ & 0x00000001) == 0x00000001)) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, msg_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeMessage(3, getCDubboPBRequestType()); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, msg_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getCDubboPBRequestType()); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType)) { + return super.equals(obj); + } + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType other = + (org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType) obj; + + boolean result = true; + result = result && (hasMsg() == other.hasMsg()); + if (hasMsg()) { + result = result && getMsg().equals(other.getMsg()); + } + result = result && (hasCDubboPBRequestType() == other.hasCDubboPBRequestType()); + if (hasCDubboPBRequestType()) { + result = result && getCDubboPBRequestType().equals(other.getCDubboPBRequestType()); + } + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + if (hasMsg()) { + hash = (37 * hash) + MSG_FIELD_NUMBER; + hash = (53 * hash) + getMsg().hashCode(); + } + if (hasCDubboPBRequestType()) { + hash = (37 * hash) + CDUBBOPBREQUESTTYPE_FIELD_NUMBER; + hash = (53 * hash) + getCDubboPBRequestType().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom( + com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom( + com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseDelimitedFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom( + com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code org.apache.dubbo.metadata.definition.protobuf.model.PBResponseType} + */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:org.apache.dubbo.metadata.definition.protobuf.model.PBResponseType) + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseTypeOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB + .internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_descriptor; + } + + protected FieldAccessorTable internalGetFieldAccessorTable() { + return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB + .internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType.class, + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType.Builder + .class); + } + + // Construct using org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { + getCDubboPBRequestTypeFieldBuilder(); + } + } + + public Builder clear() { + super.clear(); + msg_ = ""; + bitField0_ = (bitField0_ & ~0x00000001); + if (cDubboPBRequestTypeBuilder_ == null) { + cDubboPBRequestType_ = null; + } else { + cDubboPBRequestTypeBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000002); + return this; + } + + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB + .internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_descriptor; + } + + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType + getDefaultInstanceForType() { + return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType.getDefaultInstance(); + } + + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType build() { + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType buildPartial() { + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType result = + new org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.msg_ = msg_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + if (cDubboPBRequestTypeBuilder_ == null) { + result.cDubboPBRequestType_ = cDubboPBRequestType_; + } else { + result.cDubboPBRequestType_ = cDubboPBRequestTypeBuilder_.build(); + } + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder clone() { + return (Builder) super.clone(); + } + + public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); + } + + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } + + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } + + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } + + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType) { + return mergeFrom( + (org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType) other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom( + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType other) { + if (other + == org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType + .getDefaultInstance()) return this; + if (other.hasMsg()) { + bitField0_ |= 0x00000001; + msg_ = other.msg_; + onChanged(); + } + if (other.hasCDubboPBRequestType()) { + mergeCDubboPBRequestType(other.getCDubboPBRequestType()); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + public final boolean isInitialized() { + if (hasCDubboPBRequestType()) { + if (!getCDubboPBRequestType().isInitialized()) { + return false; + } + } + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType) + e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private int bitField0_; + + private java.lang.Object msg_ = ""; + /** + * optional string msg = 1; + */ + public boolean hasMsg() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * optional string msg = 1; + */ + public java.lang.String getMsg() { + java.lang.Object ref = msg_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + msg_ = s; + } + return s; + } else { + return (java.lang.String) ref; + } + } + /** + * optional string msg = 1; + */ + public com.google.protobuf.ByteString getMsgBytes() { + java.lang.Object ref = msg_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + msg_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + * optional string msg = 1; + */ + public Builder setMsg(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000001; + msg_ = value; + onChanged(); + return this; + } + /** + * optional string msg = 1; + */ + public Builder clearMsg() { + bitField0_ = (bitField0_ & ~0x00000001); + msg_ = getDefaultInstance().getMsg(); + onChanged(); + return this; + } + /** + * optional string msg = 1; + */ + public Builder setMsgBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000001; + msg_ = value; + onChanged(); + return this; + } + + private org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType cDubboPBRequestType_ = + null; + private com.google.protobuf.SingleFieldBuilderV3< + PBRequestType, PBRequestType.Builder, PBRequestTypeOrBuilder> + cDubboPBRequestTypeBuilder_; + /** + * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + public boolean hasCDubboPBRequestType() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType getCDubboPBRequestType() { + if (cDubboPBRequestTypeBuilder_ == null) { + return cDubboPBRequestType_ == null + ? org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType + .getDefaultInstance() + : cDubboPBRequestType_; + } else { + return cDubboPBRequestTypeBuilder_.getMessage(); + } + } + /** + * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + public Builder setCDubboPBRequestType( + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType value) { + if (cDubboPBRequestTypeBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + cDubboPBRequestType_ = value; + onChanged(); + } else { + cDubboPBRequestTypeBuilder_.setMessage(value); + } bitField0_ |= 0x00000002; - type_ = rawValue; - } - break; + return this; } - } + /** + * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + public Builder setCDubboPBRequestType( + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.Builder + builderForValue) { + if (cDubboPBRequestTypeBuilder_ == null) { + cDubboPBRequestType_ = builderForValue.build(); + onChanged(); + } else { + cDubboPBRequestTypeBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000002; + return this; + } + /** + * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + public Builder mergeCDubboPBRequestType( + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType value) { + if (cDubboPBRequestTypeBuilder_ == null) { + if (((bitField0_ & 0x00000002) == 0x00000002) + && cDubboPBRequestType_ != null + && cDubboPBRequestType_ + != org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType + .getDefaultInstance()) { + cDubboPBRequestType_ = + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.newBuilder( + cDubboPBRequestType_) + .mergeFrom(value) + .buildPartial(); + } else { + cDubboPBRequestType_ = value; + } + onChanged(); + } else { + cDubboPBRequestTypeBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000002; + return this; + } + /** + * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + public Builder clearCDubboPBRequestType() { + if (cDubboPBRequestTypeBuilder_ == null) { + cDubboPBRequestType_ = null; + onChanged(); + } else { + cDubboPBRequestTypeBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000002); + return this; + } + /** + * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.Builder + getCDubboPBRequestTypeBuilder() { + bitField0_ |= 0x00000002; + onChanged(); + return getCDubboPBRequestTypeFieldBuilder().getBuilder(); + } + /** + * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestTypeOrBuilder + getCDubboPBRequestTypeOrBuilder() { + if (cDubboPBRequestTypeBuilder_ != null) { + return cDubboPBRequestTypeBuilder_.getMessageOrBuilder(); + } else { + return cDubboPBRequestType_ == null + ? org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType + .getDefaultInstance() + : cDubboPBRequestType_; + } + } + /** + * optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3; + */ + private com.google.protobuf.SingleFieldBuilderV3< + PBRequestType, PBRequestType.Builder, PBRequestTypeOrBuilder> + getCDubboPBRequestTypeFieldBuilder() { + if (cDubboPBRequestTypeBuilder_ == null) { + cDubboPBRequestTypeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + PBRequestType, PBRequestType.Builder, PBRequestTypeOrBuilder>( + getCDubboPBRequestType(), getParentForChildren(), isClean()); + cDubboPBRequestType_ = null; + } + return cDubboPBRequestTypeBuilder_; + } + + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFields(unknownFields); + } + + public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + // @@protoc_insertion_point(builder_scope:org.apache.dubbo.metadata.definition.protobuf.model.PBResponseType) } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException( - e).setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); - } - } - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_descriptor; - } - protected FieldAccessorTable - internalGetFieldAccessorTable() { - return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_fieldAccessorTable - .ensureFieldAccessorsInitialized( - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.class, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder.class); - } + // @@protoc_insertion_point(class_scope:org.apache.dubbo.metadata.definition.protobuf.model.PBResponseType) + private static final org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType + DEFAULT_INSTANCE; - private int bitField0_; - public static final int NUMBER_FIELD_NUMBER = 1; - private volatile java.lang.Object number_; - /** - * required string number = 1; - */ - public boolean hasNumber() { - return ((bitField0_ & 0x00000001) == 0x00000001); - } - /** - * required string number = 1; - */ - public java.lang.String getNumber() { - java.lang.Object ref = number_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - if (bs.isValidUtf8()) { - number_ = s; + static { + DEFAULT_INSTANCE = new org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType(); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + @java.lang.Deprecated + public static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public PBResponseType parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new PBResponseType(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType getDefaultInstanceForType() { + return DEFAULT_INSTANCE; } - return s; - } - } - /** - * required string number = 1; - */ - public com.google.protobuf.ByteString - getNumberBytes() { - java.lang.Object ref = number_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); - number_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } } - public static final int TYPE_FIELD_NUMBER = 2; - private int type_; - /** - * optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME]; - */ - public boolean hasType() { - return ((bitField0_ & 0x00000002) == 0x00000002); - } - /** - * optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME]; - */ - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType getType() { - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType result = org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType.valueOf(type_); - return result == null ? org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType.HOME : result; - } + public interface PhoneNumberOrBuilder + extends + // @@protoc_insertion_point(interface_extends:org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber) + com.google.protobuf.MessageOrBuilder { - private byte memoizedIsInitialized = -1; - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) return true; - if (isInitialized == 0) return false; + /** + * required string number = 1; + */ + boolean hasNumber(); + /** + * required string number = 1; + */ + java.lang.String getNumber(); + /** + * required string number = 1; + */ + com.google.protobuf.ByteString getNumberBytes(); - if (!hasNumber()) { - memoizedIsInitialized = 0; - return false; - } - memoizedIsInitialized = 1; - return true; - } - - public void writeTo(com.google.protobuf.CodedOutputStream output) - throws java.io.IOException { - if (((bitField0_ & 0x00000001) == 0x00000001)) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 1, number_); - } - if (((bitField0_ & 0x00000002) == 0x00000002)) { - output.writeEnum(2, type_); - } - unknownFields.writeTo(output); - } - - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) return size; - - size = 0; - if (((bitField0_ & 0x00000001) == 0x00000001)) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, number_); - } - if (((bitField0_ & 0x00000002) == 0x00000002)) { - size += com.google.protobuf.CodedOutputStream - .computeEnumSize(2, type_); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; - } - - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber)) { - return super.equals(obj); - } - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber other = (org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber) obj; - - boolean result = true; - result = result && (hasNumber() == other.hasNumber()); - if (hasNumber()) { - result = result && getNumber() - .equals(other.getNumber()); - } - result = result && (hasType() == other.hasType()); - if (hasType()) { - result = result && type_ == other.type_; - } - result = result && unknownFields.equals(other.unknownFields); - return result; - } - - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - if (hasNumber()) { - hash = (37 * hash) + NUMBER_FIELD_NUMBER; - hash = (53 * hash) + getNumber().hashCode(); - } - if (hasType()) { - hash = (37 * hash) + TYPE_FIELD_NUMBER; - hash = (53 * hash) + type_; - } - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; - } - - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom( - java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom( - java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input, extensionRegistry); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } - public static Builder newBuilder(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); - } - public Builder toBuilder() { - return this == DEFAULT_INSTANCE - ? new Builder() : new Builder().mergeFrom(this); - } - - @java.lang.Override - protected Builder newBuilderForType( - BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; + /** + * optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME]; + */ + boolean hasType(); + /** + * optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME]; + */ + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType getType(); } /** * Protobuf type {@code org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber} */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder implements - // @@protoc_insertion_point(builder_implements:org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber) - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumberOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_descriptor; - } - - protected FieldAccessorTable - internalGetFieldAccessorTable() { - return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_fieldAccessorTable - .ensureFieldAccessorsInitialized( - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.class, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder.class); - } - - // Construct using org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder( - BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3 - .alwaysUseFieldBuilders) { + public static final class PhoneNumber extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber) + PhoneNumberOrBuilder { + private static final long serialVersionUID = 0L; + // Use PhoneNumber.newBuilder() to construct. + private PhoneNumber(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); } - } - public Builder clear() { - super.clear(); - number_ = ""; - bitField0_ = (bitField0_ & ~0x00000001); - type_ = 1; - bitField0_ = (bitField0_ & ~0x00000002); - return this; - } - public com.google.protobuf.Descriptors.Descriptor - getDescriptorForType() { - return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_descriptor; - } - - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDefaultInstanceForType() { - return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.getDefaultInstance(); - } - - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber build() { - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); + private PhoneNumber() { + number_ = ""; + type_ = 1; } - return result; - } - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber buildPartial() { - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber result = new org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber(this); - int from_bitField0_ = bitField0_; - int to_bitField0_ = 0; - if (((from_bitField0_ & 0x00000001) == 0x00000001)) { - to_bitField0_ |= 0x00000001; + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; } - result.number_ = number_; - if (((from_bitField0_ & 0x00000002) == 0x00000002)) { - to_bitField0_ |= 0x00000002; - } - result.type_ = type_; - result.bitField0_ = to_bitField0_; - onBuilt(); - return result; - } - public Builder clone() { - return (Builder) super.clone(); - } - public Builder setField( - com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } - public Builder clearField( - com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - public Builder clearOneof( - com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - public Builder setRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } - public Builder addRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber) { - return mergeFrom((org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber)other); - } else { - super.mergeFrom(other); - return this; + private PhoneNumber( + com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: { + com.google.protobuf.ByteString bs = input.readBytes(); + bitField0_ |= 0x00000001; + number_ = bs; + break; + } + case 16: { + int rawValue = input.readEnum(); + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType value = + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType.valueOf( + rawValue); + if (value == null) { + unknownFields.mergeVarintField(2, rawValue); + } else { + bitField0_ |= 0x00000002; + type_ = rawValue; + } + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } } - } - public Builder mergeFrom(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber other) { - if (other == org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.getDefaultInstance()) return this; - if (other.hasNumber()) { - bitField0_ |= 0x00000001; - number_ = other.number_; - onChanged(); + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB + .internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_descriptor; } - if (other.hasType()) { - setType(other.getType()); + + protected FieldAccessorTable internalGetFieldAccessorTable() { + return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB + .internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.class, + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder.class); } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - public final boolean isInitialized() { - if (!hasNumber()) { - return false; + private int bitField0_; + public static final int NUMBER_FIELD_NUMBER = 1; + private volatile java.lang.Object number_; + /** + * required string number = 1; + */ + public boolean hasNumber() { + return ((bitField0_ & 0x00000001) == 0x00000001); } - return true; - } - - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber) e.getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } + /** + * required string number = 1; + */ + public java.lang.String getNumber() { + java.lang.Object ref = number_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + number_ = s; + } + return s; + } } - return this; - } - private int bitField0_; - - private java.lang.Object number_ = ""; - /** - * required string number = 1; - */ - public boolean hasNumber() { - return ((bitField0_ & 0x00000001) == 0x00000001); - } - /** - * required string number = 1; - */ - public java.lang.String getNumber() { - java.lang.Object ref = number_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - if (bs.isValidUtf8()) { - number_ = s; - } - return s; - } else { - return (java.lang.String) ref; + /** + * required string number = 1; + */ + public com.google.protobuf.ByteString getNumberBytes() { + java.lang.Object ref = number_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + number_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } } - } - /** - * required string number = 1; - */ - public com.google.protobuf.ByteString - getNumberBytes() { - java.lang.Object ref = number_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); - number_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; + + public static final int TYPE_FIELD_NUMBER = 2; + private int type_; + /** + * optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME]; + */ + public boolean hasType() { + return ((bitField0_ & 0x00000002) == 0x00000002); } - } - /** - * required string number = 1; - */ - public Builder setNumber( - java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000001; - number_ = value; - onChanged(); - return this; - } - /** - * required string number = 1; - */ - public Builder clearNumber() { - bitField0_ = (bitField0_ & ~0x00000001); - number_ = getDefaultInstance().getNumber(); - onChanged(); - return this; - } - /** - * required string number = 1; - */ - public Builder setNumberBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000001; - number_ = value; - onChanged(); - return this; - } - - private int type_ = 1; - /** - * optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME]; - */ - public boolean hasType() { - return ((bitField0_ & 0x00000002) == 0x00000002); - } - /** - * optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME]; - */ - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType getType() { - org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType result = org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType.valueOf(type_); - return result == null ? org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType.HOME : result; - } - /** - * optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME]; - */ - public Builder setType(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType value) { - if (value == null) { - throw new NullPointerException(); + /** + * optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME]; + */ + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType getType() { + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType result = + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType.valueOf(type_); + return result == null + ? org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType.HOME + : result; } - bitField0_ |= 0x00000002; - type_ = value.getNumber(); - onChanged(); - return this; - } - /** - * optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME]; - */ - public Builder clearType() { - bitField0_ = (bitField0_ & ~0x00000002); - type_ = 1; - onChanged(); - return this; - } - public final Builder setUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFields(unknownFields); - } - public final Builder mergeUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); - } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; - // @@protoc_insertion_point(builder_scope:org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber) + if (!hasNumber()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + if (((bitField0_ & 0x00000001) == 0x00000001)) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, number_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeEnum(2, type_); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, number_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream.computeEnumSize(2, type_); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber)) { + return super.equals(obj); + } + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber other = + (org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber) obj; + + boolean result = true; + result = result && (hasNumber() == other.hasNumber()); + if (hasNumber()) { + result = result && getNumber().equals(other.getNumber()); + } + result = result && (hasType() == other.hasType()); + if (hasType()) { + result = result && type_ == other.type_; + } + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + if (hasNumber()) { + hash = (37 * hash) + NUMBER_FIELD_NUMBER; + hash = (53 * hash) + getNumber().hashCode(); + } + if (hasType()) { + hash = (37 * hash) + TYPE_FIELD_NUMBER; + hash = (53 * hash) + type_; + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom( + com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom( + com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseDelimitedFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom( + com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber} + */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber) + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumberOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB + .internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_descriptor; + } + + protected FieldAccessorTable internalGetFieldAccessorTable() { + return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB + .internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.class, + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder.class); + } + + // Construct using org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} + } + + public Builder clear() { + super.clear(); + number_ = ""; + bitField0_ = (bitField0_ & ~0x00000001); + type_ = 1; + bitField0_ = (bitField0_ & ~0x00000002); + return this; + } + + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB + .internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_descriptor; + } + + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber + getDefaultInstanceForType() { + return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.getDefaultInstance(); + } + + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber build() { + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber buildPartial() { + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber result = + new org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.number_ = number_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.type_ = type_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder clone() { + return (Builder) super.clone(); + } + + public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); + } + + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } + + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } + + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } + + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber) { + return mergeFrom((org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber) other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber other) { + if (other + == org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber + .getDefaultInstance()) return this; + if (other.hasNumber()) { + bitField0_ |= 0x00000001; + number_ = other.number_; + onChanged(); + } + if (other.hasType()) { + setType(other.getType()); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + public final boolean isInitialized() { + if (!hasNumber()) { + return false; + } + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber) + e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private int bitField0_; + + private java.lang.Object number_ = ""; + /** + * required string number = 1; + */ + public boolean hasNumber() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * required string number = 1; + */ + public java.lang.String getNumber() { + java.lang.Object ref = number_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + number_ = s; + } + return s; + } else { + return (java.lang.String) ref; + } + } + /** + * required string number = 1; + */ + public com.google.protobuf.ByteString getNumberBytes() { + java.lang.Object ref = number_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + number_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + * required string number = 1; + */ + public Builder setNumber(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000001; + number_ = value; + onChanged(); + return this; + } + /** + * required string number = 1; + */ + public Builder clearNumber() { + bitField0_ = (bitField0_ & ~0x00000001); + number_ = getDefaultInstance().getNumber(); + onChanged(); + return this; + } + /** + * required string number = 1; + */ + public Builder setNumberBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000001; + number_ = value; + onChanged(); + return this; + } + + private int type_ = 1; + /** + * optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME]; + */ + public boolean hasType() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME]; + */ + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType getType() { + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType result = + org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType.valueOf(type_); + return result == null + ? org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType.HOME + : result; + } + /** + * optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME]; + */ + public Builder setType(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000002; + type_ = value.getNumber(); + onChanged(); + return this; + } + /** + * optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME]; + */ + public Builder clearType() { + bitField0_ = (bitField0_ & ~0x00000002); + type_ = 1; + onChanged(); + return this; + } + + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFields(unknownFields); + } + + public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + // @@protoc_insertion_point(builder_scope:org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber) + } + + // @@protoc_insertion_point(class_scope:org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber) + private static final org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber DEFAULT_INSTANCE; + + static { + DEFAULT_INSTANCE = new org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber(); + } + + public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + @java.lang.Deprecated + public static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public PhoneNumber parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new PhoneNumber(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } } - // @@protoc_insertion_point(class_scope:org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber) - private static final org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber DEFAULT_INSTANCE; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor; + private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_DoubleMapEntry_descriptor; + private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_DoubleMapEntry_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_BytesMapEntry_descriptor; + private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_BytesMapEntry_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_descriptor; + private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_descriptor; + private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_fieldAccessorTable; + + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } + + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; + static { - DEFAULT_INSTANCE = new org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber(); - } - - public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - @java.lang.Deprecated public static final com.google.protobuf.Parser - PARSER = new com.google.protobuf.AbstractParser() { - public PhoneNumber parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new PhoneNumber(input, extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } - - } - - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor; - private static final - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_fieldAccessorTable; - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_DoubleMapEntry_descriptor; - private static final - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_DoubleMapEntry_fieldAccessorTable; - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_BytesMapEntry_descriptor; - private static final - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_BytesMapEntry_fieldAccessorTable; - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_descriptor; - private static final - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_fieldAccessorTable; - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_descriptor; - private static final - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_fieldAccessorTable; - - public static com.google.protobuf.Descriptors.FileDescriptor - getDescriptor() { - return descriptor; - } - private static com.google.protobuf.Descriptors.FileDescriptor - descriptor; - static { - java.lang.String[] descriptorData = { - "\n\016GooglePB.proto\0223org.apache.dubbo.metad" + - "ata.definition.protobuf.model\"\301\004\n\rPBRequ" + - "estType\022\r\n\005money\030\001 \001(\001\022\014\n\004cash\030\002 \001(\002\022\013\n\003" + - "age\030\003 \001(\005\022\013\n\003num\030\004 \001(\003\022\013\n\003sex\030\005 \001(\010\022\014\n\004n" + - "ame\030\006 \001(\t\022\013\n\003msg\030\007 \001(\014\022O\n\005phone\030\010 \003(\0132@." + - "org.apache.dubbo.metadata.definition.pro" + - "tobuf.model.PhoneNumber\022d\n\tdoubleMap\030\t \003" + - "(\0132Q.org.apache.dubbo.metadata.definitio" + - "n.protobuf.model.PBRequestType.DoubleMap" + - "Entry\022\021\n\tbytesList\030\n \003(\014\022b\n\010bytesMap\030\013 \003", - "(\0132P.org.apache.dubbo.metadata.definitio" + - "n.protobuf.model.PBRequestType.BytesMapE" + - "ntry\032r\n\016DoubleMapEntry\022\013\n\003key\030\001 \001(\t\022O\n\005v" + - "alue\030\002 \001(\0132@.org.apache.dubbo.metadata.d" + - "efinition.protobuf.model.PhoneNumber:\0028\001" + - "\032/\n\rBytesMapEntry\022\013\n\003key\030\001 \001(\t\022\r\n\005value\030" + - "\002 \001(\014:\0028\001\"~\n\016PBResponseType\022\013\n\003msg\030\001 \001(\t" + - "\022_\n\023CDubboPBRequestType\030\003 \001(\0132B.org.apac" + - "he.dubbo.metadata.definition.protobuf.mo" + - "del.PBRequestType\"q\n\013PhoneNumber\022\016\n\006numb", - "er\030\001 \002(\t\022R\n\004type\030\002 \001(\0162>.org.apache.dubb" + - "o.metadata.definition.protobuf.model.Pho" + - "neType:\004HOME*+\n\tPhoneType\022\n\n\006MOBILE\020\000\022\010\n" + - "\004HOME\020\001\022\010\n\004WORK\020\0022\247\001\n\017CDubboPBService\022\223\001" + - "\n\010sayHello\022B.org.apache.dubbo.metadata.d" + - "efinition.protobuf.model.PBRequestType\032C" + - ".org.apache.dubbo.metadata.definition.pr" + - "otobuf.model.PBResponseType" - }; - com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = - new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { - public com.google.protobuf.ExtensionRegistry assignDescriptors( - com.google.protobuf.Descriptors.FileDescriptor root) { - descriptor = root; - return null; - } + java.lang.String[] descriptorData = { + "\n\016GooglePB.proto\0223org.apache.dubbo.metad" + "ata.definition.protobuf.model\"\301\004\n\rPBRequ" + + "estType\022\r\n\005money\030\001 \001(\001\022\014\n\004cash\030\002 \001(\002\022\013\n\003" + + "age\030\003 \001(\005\022\013\n\003num\030\004 \001(\003\022\013\n\003sex\030\005 \001(\010\022\014\n\004n" + + "ame\030\006 \001(\t\022\013\n\003msg\030\007 \001(\014\022O\n\005phone\030\010 \003(\0132@." + + "org.apache.dubbo.metadata.definition.pro" + + "tobuf.model.PhoneNumber\022d\n\tdoubleMap\030\t \003" + + "(\0132Q.org.apache.dubbo.metadata.definitio" + + "n.protobuf.model.PBRequestType.DoubleMap" + + "Entry\022\021\n\tbytesList\030\n \003(\014\022b\n\010bytesMap\030\013 \003", + "(\0132P.org.apache.dubbo.metadata.definitio" + "n.protobuf.model.PBRequestType.BytesMapE" + + "ntry\032r\n\016DoubleMapEntry\022\013\n\003key\030\001 \001(\t\022O\n\005v" + + "alue\030\002 \001(\0132@.org.apache.dubbo.metadata.d" + + "efinition.protobuf.model.PhoneNumber:\0028\001" + + "\032/\n\rBytesMapEntry\022\013\n\003key\030\001 \001(\t\022\r\n\005value\030" + + "\002 \001(\014:\0028\001\"~\n\016PBResponseType\022\013\n\003msg\030\001 \001(\t" + + "\022_\n\023CDubboPBRequestType\030\003 \001(\0132B.org.apac" + + "he.dubbo.metadata.definition.protobuf.mo" + + "del.PBRequestType\"q\n\013PhoneNumber\022\016\n\006numb", + "er\030\001 \002(\t\022R\n\004type\030\002 \001(\0162>.org.apache.dubb" + + "o.metadata.definition.protobuf.model.Pho" + + "neType:\004HOME*+\n\tPhoneType\022\n\n\006MOBILE\020\000\022\010\n" + + "\004HOME\020\001\022\010\n\004WORK\020\0022\247\001\n\017CDubboPBService\022\223\001" + + "\n\010sayHello\022B.org.apache.dubbo.metadata.d" + + "efinition.protobuf.model.PBRequestType\032C" + + ".org.apache.dubbo.metadata.definition.pr" + + "otobuf.model.PBResponseType" }; - com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom(descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[] { - }, assigner); - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor = - getDescriptor().getMessageTypes().get(0); - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_fieldAccessorTable = new - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor, - new java.lang.String[] { "Money", "Cash", "Age", "Num", "Sex", "Name", "Msg", "Phone", "DoubleMap", "BytesList", "BytesMap", }); - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_DoubleMapEntry_descriptor = - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor.getNestedTypes().get(0); - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_DoubleMapEntry_fieldAccessorTable = new - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_DoubleMapEntry_descriptor, - new java.lang.String[] { "Key", "Value", }); - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_BytesMapEntry_descriptor = - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor.getNestedTypes().get(1); - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_BytesMapEntry_fieldAccessorTable = new - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_BytesMapEntry_descriptor, - new java.lang.String[] { "Key", "Value", }); - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_descriptor = - getDescriptor().getMessageTypes().get(1); - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_fieldAccessorTable = new - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_descriptor, - new java.lang.String[] { "Msg", "CDubboPBRequestType", }); - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_descriptor = - getDescriptor().getMessageTypes().get(2); - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_fieldAccessorTable = new - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_descriptor, - new java.lang.String[] { "Number", "Type", }); - } + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( + descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner); + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor = + getDescriptor().getMessageTypes().get(0); + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor, + new java.lang.String[] { + "Money", + "Cash", + "Age", + "Num", + "Sex", + "Name", + "Msg", + "Phone", + "DoubleMap", + "BytesList", + "BytesMap", + }); + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_DoubleMapEntry_descriptor = + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor + .getNestedTypes() + .get(0); + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_DoubleMapEntry_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_DoubleMapEntry_descriptor, + new java.lang.String[] { + "Key", "Value", + }); + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_BytesMapEntry_descriptor = + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor + .getNestedTypes() + .get(1); + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_BytesMapEntry_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_BytesMapEntry_descriptor, + new java.lang.String[] { + "Key", "Value", + }); + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_descriptor = + getDescriptor().getMessageTypes().get(1); + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_descriptor, + new java.lang.String[] { + "Msg", "CDubboPBRequestType", + }); + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_descriptor = + getDescriptor().getMessageTypes().get(2); + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_descriptor, + new java.lang.String[] { + "Number", "Type", + }); + } - // @@protoc_insertion_point(outer_class_scope) + // @@protoc_insertion_point(outer_class_scope) } diff --git a/dubbo-metadata/dubbo-metadata-processor/pom.xml b/dubbo-metadata/dubbo-metadata-processor/pom.xml index 87ec734449..7e1a50d684 100644 --- a/dubbo-metadata/dubbo-metadata-processor/pom.xml +++ b/dubbo-metadata/dubbo-metadata-processor/pom.xml @@ -15,110 +15,108 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - - - org.apache.dubbo - dubbo-metadata - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-metadata + ${revision} + ../pom.xml + - dubbo-metadata-processor - jar - dubbo-metadata-processor - The metadata processor module of Dubbo project + dubbo-metadata-processor + jar + dubbo-metadata-processor + The metadata processor module of Dubbo project - - - org.apache.dubbo - dubbo-metadata-rest - ${project.parent.version} - - - org.apache.dubbo - dubbo-rpc-api - - - org.apache.dubbo - dubbo-cluster - - - + + + org.apache.dubbo + dubbo-metadata-rest + ${project.parent.version} + + + org.apache.dubbo + dubbo-rpc-api + + + org.apache.dubbo + dubbo-cluster + + + - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - commons-io - commons-io - - - javassist - org.javassist - - - javax.annotation-api - javax.annotation - - - + + org.apache.dubbo + dubbo-common + ${project.parent.version} + + + commons-io + commons-io + + + org.javassist + javassist + + + javax.annotation + javax.annotation-api + + + - - - org.apache.dubbo - dubbo-config-api - ${project.parent.version} - test - - - - - - - org.apache.dubbo - dubbo-metadata-api - - - org.apache.dubbo - dubbo-monitor-api - - - org.apache.dubbo - dubbo-remoting-api - - - org.apache.dubbo - dubbo-rpc-injvm - - - org.apache.dubbo - dubbo-filter-validation - - - org.apache.dubbo - dubbo-filter-cache - - - + + + org.apache.dubbo + dubbo-config-api + ${project.parent.version} + test + + + + + + + org.apache.dubbo + dubbo-metadata-api + + + org.apache.dubbo + dubbo-monitor-api + + + org.apache.dubbo + dubbo-remoting-api + + + org.apache.dubbo + dubbo-rpc-injvm + + + org.apache.dubbo + dubbo-filter-validation + + + org.apache.dubbo + dubbo-filter-cache + + + - - - javax.ws.rs - javax.ws.rs-api - test - + + + javax.ws.rs + javax.ws.rs-api + test + - - - org.springframework - spring-web - test - - + + + org.springframework + spring-web + test + + diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/AbstractServiceAnnotationProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/AbstractServiceAnnotationProcessor.java index d65c6ba7e8..c5c64e8e47 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/AbstractServiceAnnotationProcessor.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/AbstractServiceAnnotationProcessor.java @@ -26,6 +26,7 @@ import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Elements; + import java.util.HashMap; import java.util.LinkedList; import java.util.List; @@ -81,9 +82,7 @@ public abstract class AbstractServiceAnnotationProcessor extends AbstractProcess methodSignatureBuilder.append(member).append(' '); }); - methodSignatureBuilder.append(method.getReturnType()) - .append(' ') - .append(method.toString()); + methodSignatureBuilder.append(method.getReturnType()).append(' ').append(method.toString()); return methodSignatureBuilder.toString(); } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/ClassPathMetadataStorage.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/ClassPathMetadataStorage.java index 9e1032c590..a40a340439 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/ClassPathMetadataStorage.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/ClassPathMetadataStorage.java @@ -16,10 +16,10 @@ */ package org.apache.dubbo.metadata.annotation.processing; - import javax.annotation.processing.Filer; import javax.annotation.processing.ProcessingEnvironment; import javax.tools.FileObject; + import java.io.File; import java.io.IOException; import java.io.Reader; @@ -74,13 +74,15 @@ public class ClassPathMetadataStorage { } private Reader getReader(String resourceName) { - return getResource(resourceName).map(fileObject -> { - try { - return fileObject.openReader(false); - } catch (IOException e) { - } - return null; - }).orElse(null); + return getResource(resourceName) + .map(fileObject -> { + try { + return fileObject.openReader(false); + } catch (IOException e) { + } + return null; + }) + .orElse(null); } private FileObject createResource(String resourceName) throws IOException { @@ -99,7 +101,9 @@ public class ClassPathMetadataStorage { private Writer getWriter(String resourceName) throws IOException { FileObject fileObject = createResource(resourceName); - info("The resource[path : %s , deleted : %s] will be written", fileObject.toUri().getPath(), fileObject.delete()); + info( + "The resource[path : %s , deleted : %s] will be written", + fileObject.toUri().getPath(), fileObject.delete()); return fileObject.openWriter(); } } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/ServiceDefinitionMetadataAnnotationProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/ServiceDefinitionMetadataAnnotationProcessor.java index cf8b45695e..244cde36af 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/ServiceDefinitionMetadataAnnotationProcessor.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/ServiceDefinitionMetadataAnnotationProcessor.java @@ -23,6 +23,7 @@ import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.TypeElement; + import java.util.LinkedList; import java.util.List; import java.util.Set; @@ -53,7 +54,8 @@ public class ServiceDefinitionMetadataAnnotationProcessor extends AbstractServic return false; } - private void process(ProcessingEnvironment processingEnv, TypeElement serviceType, Set annotations) { + private void process( + ProcessingEnvironment processingEnv, TypeElement serviceType, Set annotations) { serviceDefinitions.add(build(processingEnv, serviceType)); } } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilder.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilder.java index 26aa10dfcc..e1ed3677d6 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilder.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilder.java @@ -21,6 +21,7 @@ import org.apache.dubbo.metadata.definition.model.TypeDefinition; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.type.ArrayType; import javax.lang.model.type.TypeMirror; + import java.lang.reflect.Array; import java.util.Map; @@ -39,12 +40,12 @@ public class ArrayTypeDefinitionBuilder implements TypeBuilder { } @Override - public TypeDefinition build(ProcessingEnvironment processingEnv, ArrayType type, Map typeCache) { + public TypeDefinition build( + ProcessingEnvironment processingEnv, ArrayType type, Map typeCache) { TypeDefinition typeDefinition = new TypeDefinition(type.toString()); TypeMirror componentType = type.getComponentType(); TypeDefinition subTypeDefinition = TypeDefinitionBuilder.build(processingEnv, componentType, typeCache); - typeDefinition.getItems() - .add(subTypeDefinition.getType()); + typeDefinition.getItems().add(subTypeDefinition.getType()); return typeDefinition; } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilder.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilder.java index 7f7be24185..21c3e927fd 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilder.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilder.java @@ -24,6 +24,7 @@ import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; + import java.util.Collection; import java.util.Map; import java.util.Objects; @@ -46,16 +47,17 @@ public class CollectionTypeDefinitionBuilder implements DeclaredTypeDefinitionBu } @Override - public TypeDefinition build(ProcessingEnvironment processingEnv, DeclaredType type, Map typeCache) { + public TypeDefinition build( + ProcessingEnvironment processingEnv, DeclaredType type, Map typeCache) { String typeName = type.toString(); TypeDefinition typeDefinition = new TypeDefinition(typeName); // Generic Type arguments - type.getTypeArguments() - .stream() - .map(typeArgument -> TypeDefinitionBuilder.build(processingEnv, typeArgument, typeCache)) // build the TypeDefinition from typeArgument + type.getTypeArguments().stream() + .map(typeArgument -> TypeDefinitionBuilder.build( + processingEnv, typeArgument, typeCache)) // build the TypeDefinition from typeArgument .filter(Objects::nonNull) .map(TypeDefinition::getType) - .forEach(typeDefinition.getItems()::add); // Add into the declared TypeDefinition + .forEach(typeDefinition.getItems()::add); // Add into the declared TypeDefinition return typeDefinition; } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilder.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilder.java index bc3b05cbba..51bf9c8d84 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilder.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilder.java @@ -23,6 +23,7 @@ import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Element; import javax.lang.model.element.Name; import javax.lang.model.type.DeclaredType; + import java.util.Map; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getDeclaredFields; @@ -41,10 +42,10 @@ public class EnumTypeDefinitionBuilder implements DeclaredTypeDefinitionBuilder } @Override - public TypeDefinition build(ProcessingEnvironment processingEnv, DeclaredType type, Map typeCache) { + public TypeDefinition build( + ProcessingEnvironment processingEnv, DeclaredType type, Map typeCache) { TypeDefinition typeDefinition = new TypeDefinition(type.toString()); - getDeclaredFields(type, FieldUtils::isEnumMemberField) - .stream() + getDeclaredFields(type, FieldUtils::isEnumMemberField).stream() .map(Element::getSimpleName) .map(Name::toString) .forEach(typeDefinition.getEnums()::add); diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilder.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilder.java index 1e907e7245..c64d800508 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilder.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilder.java @@ -21,6 +21,7 @@ import org.apache.dubbo.metadata.definition.model.TypeDefinition; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; + import java.util.Map; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getNonStaticFields; @@ -40,7 +41,8 @@ public class GeneralTypeDefinitionBuilder implements DeclaredTypeDefinitionBuild } @Override - public TypeDefinition build(ProcessingEnvironment processingEnv, DeclaredType type, Map typeCache) { + public TypeDefinition build( + ProcessingEnvironment processingEnv, DeclaredType type, Map typeCache) { String typeName = type.toString(); @@ -49,7 +51,8 @@ public class GeneralTypeDefinitionBuilder implements DeclaredTypeDefinitionBuild return buildProperties(processingEnv, typeElement, typeCache); } - protected TypeDefinition buildProperties(ProcessingEnvironment processingEnv, TypeElement type, Map typeCache) { + protected TypeDefinition buildProperties( + ProcessingEnvironment processingEnv, TypeElement type, Map typeCache) { TypeDefinition definition = new TypeDefinition(type.toString()); getNonStaticFields(type).forEach(field -> { String fieldName = field.getSimpleName().toString(); diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilder.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilder.java index 1045fcb27d..e58a43f988 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilder.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilder.java @@ -24,6 +24,7 @@ import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; + import java.util.Map; import java.util.Objects; @@ -45,15 +46,16 @@ public class MapTypeDefinitionBuilder implements DeclaredTypeDefinitionBuilder { } @Override - public TypeDefinition build(ProcessingEnvironment processingEnv, DeclaredType type, Map typeCache) { + public TypeDefinition build( + ProcessingEnvironment processingEnv, DeclaredType type, Map typeCache) { TypeDefinition typeDefinition = new TypeDefinition(type.toString()); // Generic Type arguments - type.getTypeArguments() - .stream() - .map(typeArgument -> TypeDefinitionBuilder.build(processingEnv, typeArgument, typeCache)) // build the TypeDefinition from typeArgument + type.getTypeArguments().stream() + .map(typeArgument -> TypeDefinitionBuilder.build( + processingEnv, typeArgument, typeCache)) // build the TypeDefinition from typeArgument .filter(Objects::nonNull) .map(TypeDefinition::getType) - .forEach(typeDefinition.getItems()::add); // Add into the declared TypeDefinition + .forEach(typeDefinition.getItems()::add); // Add into the declared TypeDefinition return typeDefinition; } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/MethodDefinitionBuilder.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/MethodDefinitionBuilder.java index c91f96f208..0fa96c3ffe 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/MethodDefinitionBuilder.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/MethodDefinitionBuilder.java @@ -21,6 +21,7 @@ import org.apache.dubbo.metadata.definition.model.TypeDefinition; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.ExecutableElement; + import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -37,7 +38,8 @@ import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.g */ public interface MethodDefinitionBuilder { - static MethodDefinition build(ProcessingEnvironment processingEnv, ExecutableElement method, Map typeCache) { + static MethodDefinition build( + ProcessingEnvironment processingEnv, ExecutableElement method, Map typeCache) { MethodDefinition methodDefinition = new MethodDefinition(); methodDefinition.setName(getMethodName(method)); methodDefinition.setReturnType(getReturnType(method)); @@ -46,7 +48,8 @@ public interface MethodDefinitionBuilder { return methodDefinition; } - static List getMethodParameters(ProcessingEnvironment processingEnv, ExecutableElement method, Map typeCache) { + static List getMethodParameters( + ProcessingEnvironment processingEnv, ExecutableElement method, Map typeCache) { return method.getParameters().stream() .map(element -> TypeDefinitionBuilder.build(processingEnv, element, typeCache)) .collect(Collectors.toList()); diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilder.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilder.java index 6153917f84..e8577723dd 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilder.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilder.java @@ -21,6 +21,7 @@ import org.apache.dubbo.metadata.definition.model.TypeDefinition; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.type.PrimitiveType; import javax.lang.model.type.TypeMirror; + import java.util.Map; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isPrimitiveType; @@ -38,7 +39,8 @@ public class PrimitiveTypeDefinitionBuilder implements TypeBuilder typeCache) { + public TypeDefinition build( + ProcessingEnvironment processingEnv, PrimitiveType type, Map typeCache) { TypeDefinition typeDefinition = new TypeDefinition(type.toString()); return typeDefinition; } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilder.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilder.java index 4fe27b5ce8..669945a56d 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilder.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilder.java @@ -21,6 +21,7 @@ import org.apache.dubbo.metadata.definition.model.TypeDefinition; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement; + import java.util.ArrayList; import java.util.HashMap; import java.util.Map; @@ -50,8 +51,7 @@ public interface ServiceDefinitionBuilder { .forEach(t -> TypeDefinitionBuilder.build(processingEnv, t, types)); // Get all declared methods that will be added into ServiceDefinition#getMethods() - getPublicNonStaticMethods(type, Object.class) - .stream() + getPublicNonStaticMethods(type, Object.class).stream() .map(method -> MethodDefinitionBuilder.build(processingEnv, method, types)) .forEach(serviceDefinition.getMethods()::add); diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilder.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilder.java index 172d8aa3ab..d133fe2aee 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilder.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilder.java @@ -21,11 +21,11 @@ import org.apache.dubbo.metadata.definition.model.TypeDefinition; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.type.DeclaredType; + import java.util.Map; import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isSimpleType; - /** * {@link TypeBuilder} for {@link TypeUtils#SIMPLE_TYPES Java Simple Type} * @@ -39,7 +39,8 @@ public class SimpleTypeDefinitionBuilder implements DeclaredTypeDefinitionBuilde } @Override - public TypeDefinition build(ProcessingEnvironment processingEnv, DeclaredType type, Map typeCache) { + public TypeDefinition build( + ProcessingEnvironment processingEnv, DeclaredType type, Map typeCache) { TypeDefinition td = new TypeDefinition(type.toString()); return td; } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/TypeBuilder.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/TypeBuilder.java index 1df9dcd2f1..6feefaf6c3 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/TypeBuilder.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/TypeBuilder.java @@ -22,6 +22,7 @@ import org.apache.dubbo.metadata.definition.model.TypeDefinition; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.type.TypeMirror; + import java.util.Map; @SPI diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/TypeDefinitionBuilder.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/TypeDefinitionBuilder.java index b717037145..f7dcf08035 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/TypeDefinitionBuilder.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/TypeDefinitionBuilder.java @@ -23,6 +23,7 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Element; import javax.lang.model.type.TypeMirror; + import java.util.Map; /** @@ -39,7 +40,8 @@ public interface TypeDefinitionBuilder extends Prioritized * @param element {@link Element source element} * @return non-null */ - static TypeDefinition build(ProcessingEnvironment processingEnv, Element element, Map typeCache) { + static TypeDefinition build( + ProcessingEnvironment processingEnv, Element element, Map typeCache) { TypeDefinition typeDefinition = build(processingEnv, element.asType(), typeCache); // Comment this code for the compatibility // typeDefinition.set$ref(element.toString()); @@ -53,20 +55,23 @@ public interface TypeDefinitionBuilder extends Prioritized * @param type {@link TypeMirror type} * @return non-null */ - static TypeDefinition build(ProcessingEnvironment processingEnv, TypeMirror type, Map typeCache) { + static TypeDefinition build( + ProcessingEnvironment processingEnv, TypeMirror type, Map typeCache) { // Build by all instances of TypeDefinitionBuilder that were loaded By Java SPI - TypeDefinition typeDefinition = ApplicationModel.defaultModel() - .getExtensionLoader(TypeBuilder.class) - .getSupportedExtensionInstances() - .stream() -// load(TypeDefinitionBuilder.class, TypeDefinitionBuilder.class.getClassLoader()) - .filter(builder -> builder.accept(processingEnv, type)) - .findFirst() - .map(builder -> { - return builder.build(processingEnv, type, typeCache); - // typeDefinition.setTypeBuilderName(builder.getClass().getName()); - }).orElse(null); + TypeDefinition typeDefinition = + ApplicationModel.defaultModel() + .getExtensionLoader(TypeBuilder.class) + .getSupportedExtensionInstances() + .stream() + // load(TypeDefinitionBuilder.class, TypeDefinitionBuilder.class.getClassLoader()) + .filter(builder -> builder.accept(processingEnv, type)) + .findFirst() + .map(builder -> { + return builder.build(processingEnv, type, typeCache); + // typeDefinition.setTypeBuilderName(builder.getClass().getName()); + }) + .orElse(null); if (typeDefinition != null) { typeCache.put(typeDefinition.getType(), typeDefinition); diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AbstractAnnotatedMethodParameterProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AbstractAnnotatedMethodParameterProcessor.java index df79c4fbdb..142429e0f3 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AbstractAnnotatedMethodParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AbstractAnnotatedMethodParameterProcessor.java @@ -33,14 +33,25 @@ import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUti public abstract class AbstractAnnotatedMethodParameterProcessor implements AnnotatedMethodParameterProcessor { @Override - public final void process(AnnotationMirror annotation, VariableElement parameter, int parameterIndex, ExecutableElement method, RestMethodMetadata restMethodMetadata) { + public final void process( + AnnotationMirror annotation, + VariableElement parameter, + int parameterIndex, + ExecutableElement method, + RestMethodMetadata restMethodMetadata) { String annotationValue = getAnnotationValue(annotation, parameter, parameterIndex); String defaultValue = getDefaultValue(annotation, parameter, parameterIndex); process(annotationValue, defaultValue, annotation, parameter, parameterIndex, method, restMethodMetadata); } - protected abstract void process(String annotationValue, String defaultValue, AnnotationMirror annotation, VariableElement parameter, int parameterIndex, - ExecutableElement method, RestMethodMetadata restMethodMetadata); + protected abstract void process( + String annotationValue, + String defaultValue, + AnnotationMirror annotation, + VariableElement parameter, + int parameterIndex, + ExecutableElement method, + RestMethodMetadata restMethodMetadata); protected String getAnnotationValue(AnnotationMirror annotation, VariableElement parameter, int parameterIndex) { return getValue(annotation); diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AbstractServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AbstractServiceRestMetadataResolver.java index a52bd25710..a2a388d34d 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AbstractServiceRestMetadataResolver.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AbstractServiceRestMetadataResolver.java @@ -29,6 +29,7 @@ import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.util.Elements; + import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -61,18 +62,21 @@ import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnota */ public abstract class AbstractServiceRestMetadataResolver implements ServiceRestMetadataResolver { - private final static ThreadLocal> threadLocalCache = withInitial(HashMap::new); + private static final ThreadLocal> threadLocalCache = withInitial(HashMap::new); - private final static Map> parameterProcessorsMap = loadAnnotatedMethodParameterProcessors(); + private static final Map> parameterProcessorsMap = + loadAnnotatedMethodParameterProcessors(); private final String processorName = getClass().getSimpleName(); @Override - public final ServiceRestMetadata resolve(ProcessingEnvironment processingEnv, - TypeElement serviceType, - Set annotations) { + public final ServiceRestMetadata resolve( + ProcessingEnvironment processingEnv, TypeElement serviceType, Set annotations) { - info("%s is processing the service type[%s] with annotations[%s]", processorName, serviceType, + info( + "%s is processing the service type[%s] with annotations[%s]", + processorName, + serviceType, annotations.stream().map(t -> "@" + t.toString()).collect(Collectors.joining(","))); ServiceRestMetadata serviceRestMetadata = new ServiceRestMetadata(); @@ -88,14 +92,16 @@ public abstract class AbstractServiceRestMetadataResolver implements ServiceRest TypeElement serviceInterfaceType = elements.getTypeElement(serviceInterfaceName); - List serviceMethods = new LinkedList<>(getPublicNonStaticMethods(serviceInterfaceType, Object.class)); + List serviceMethods = + new LinkedList<>(getPublicNonStaticMethods(serviceInterfaceType, Object.class)); // Sorts sort(serviceMethods, ExecutableElementComparator.INSTANCE); serviceMethods.forEach(serviceMethod -> { - resolveRestMethodMetadata(processingEnv, serviceType, serviceInterfaceType, serviceMethod, serviceRestMetadata) - .ifPresent(serviceRestMetadata.getMeta()::add); + resolveRestMethodMetadata( + processingEnv, serviceType, serviceInterfaceType, serviceMethod, serviceRestMetadata) + .ifPresent(serviceRestMetadata.getMeta()::add); }); } finally { @@ -107,25 +113,29 @@ public abstract class AbstractServiceRestMetadataResolver implements ServiceRest return serviceRestMetadata; } - protected Optional resolveRestMethodMetadata(ProcessingEnvironment processingEnv, - TypeElement serviceType, - TypeElement serviceInterfaceType, - ExecutableElement serviceMethod, - ServiceRestMetadata serviceRestMetadata) { + protected Optional resolveRestMethodMetadata( + ProcessingEnvironment processingEnv, + TypeElement serviceType, + TypeElement serviceInterfaceType, + ExecutableElement serviceMethod, + ServiceRestMetadata serviceRestMetadata) { - ExecutableElement restCapableMethod = findRestCapableMethod(processingEnv, serviceType, serviceInterfaceType, serviceMethod); + ExecutableElement restCapableMethod = + findRestCapableMethod(processingEnv, serviceType, serviceInterfaceType, serviceMethod); if (restCapableMethod == null) { // if can't be found return empty(); } - String requestPath = resolveRequestPath(processingEnv, serviceType, restCapableMethod); // requestPath is required + String requestPath = + resolveRequestPath(processingEnv, serviceType, restCapableMethod); // requestPath is required if (requestPath == null) { return empty(); } - String requestMethod = resolveRequestMethod(processingEnv, serviceType, restCapableMethod); // requestMethod is required + String requestMethod = + resolveRequestMethod(processingEnv, serviceType, restCapableMethod); // requestMethod is required if (requestMethod == null) { return empty(); @@ -172,10 +182,11 @@ public abstract class AbstractServiceRestMetadataResolver implements ServiceRest * @param serviceMethod * @return null if can't be found */ - private ExecutableElement findRestCapableMethod(ProcessingEnvironment processingEnv, - TypeElement serviceType, - TypeElement serviceInterfaceType, - ExecutableElement serviceMethod) { + private ExecutableElement findRestCapableMethod( + ProcessingEnvironment processingEnv, + TypeElement serviceType, + TypeElement serviceInterfaceType, + ExecutableElement serviceMethod) { // try to judge the override first ExecutableElement overrideMethod = getOverrideMethod(processingEnv, serviceType, serviceMethod); if (supports(processingEnv, serviceType, serviceInterfaceType, overrideMethod)) { @@ -192,11 +203,11 @@ public abstract class AbstractServiceRestMetadataResolver implements ServiceRest * @param method the method may be declared on the interface or class * @return if supports, return true, or false */ - protected abstract boolean supports(ProcessingEnvironment processingEnv, - TypeElement serviceType, - TypeElement serviceInterfaceType, - ExecutableElement method); - + protected abstract boolean supports( + ProcessingEnvironment processingEnv, + TypeElement serviceType, + TypeElement serviceInterfaceType, + ExecutableElement method); /** * Post-Process for {@link RestMethodMetadata}, sub-type could override this method for further works @@ -206,23 +217,25 @@ public abstract class AbstractServiceRestMetadataResolver implements ServiceRest * @param method The public method of serviceType * @param metadata {@link RestMethodMetadata} maybe updated */ - protected void postProcessRestMethodMetadata(ProcessingEnvironment processingEnv, TypeElement serviceType, - ExecutableElement method, RestMethodMetadata metadata) { - } + protected void postProcessRestMethodMetadata( + ProcessingEnvironment processingEnv, + TypeElement serviceType, + ExecutableElement method, + RestMethodMetadata metadata) {} - protected abstract String resolveRequestPath(ProcessingEnvironment processingEnv, TypeElement serviceType, - ExecutableElement method); + protected abstract String resolveRequestPath( + ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method); - protected abstract String resolveRequestMethod(ProcessingEnvironment processingEnv, TypeElement serviceType, - ExecutableElement method); + protected abstract String resolveRequestMethod( + ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method); - protected MethodDefinition resolveMethodDefinition(ProcessingEnvironment processingEnv, TypeElement serviceType, - ExecutableElement method) { + protected MethodDefinition resolveMethodDefinition( + ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method) { return build(processingEnv, method, new HashMap<>()); } - protected void processAnnotatedMethodParameters(ExecutableElement method, TypeElement type, - RestMethodMetadata metadata) { + protected void processAnnotatedMethodParameters( + ExecutableElement method, TypeElement type, RestMethodMetadata metadata) { List methodParameters = method.getParameters(); int size = methodParameters.size(); for (int i = 0; i < size; i++) { @@ -233,24 +246,32 @@ public abstract class AbstractServiceRestMetadataResolver implements ServiceRest } } - protected void processAnnotatedMethodParameter(VariableElement parameter, int parameterIndex, - ExecutableElement method, TypeElement serviceType, - RestMethodMetadata metadata) { + protected void processAnnotatedMethodParameter( + VariableElement parameter, + int parameterIndex, + ExecutableElement method, + TypeElement serviceType, + RestMethodMetadata metadata) { parameter.getAnnotationMirrors().forEach(annotation -> { String annotationType = annotation.getAnnotationType().toString(); - parameterProcessorsMap.getOrDefault(annotationType, emptyList()) - .forEach(parameterProcessor -> { - parameterProcessor.process(annotation, parameter, parameterIndex, method, metadata); - }); + parameterProcessorsMap.getOrDefault(annotationType, emptyList()).forEach(parameterProcessor -> { + parameterProcessor.process(annotation, parameter, parameterIndex, method, metadata); + }); }); } - protected abstract void processProduces(ProcessingEnvironment processingEnv, TypeElement serviceType, - ExecutableElement method, Set produces); + protected abstract void processProduces( + ProcessingEnvironment processingEnv, + TypeElement serviceType, + ExecutableElement method, + Set produces); - protected abstract void processConsumes(ProcessingEnvironment processingEnv, TypeElement serviceType, - ExecutableElement method, Set consumes); + protected abstract void processConsumes( + ProcessingEnvironment processingEnv, + TypeElement serviceType, + ExecutableElement method, + Set consumes); protected static final void put(String name, Object value) { Map cache = getCache(); @@ -269,14 +290,15 @@ public abstract class AbstractServiceRestMetadataResolver implements ServiceRest private static Map> loadAnnotatedMethodParameterProcessors() { Map> parameterProcessorsMap = new LinkedHashMap<>(); -// load(AnnotatedMethodParameterProcessor.class, AnnotatedMethodParameterProcessor.class.getClassLoader()) + // load(AnnotatedMethodParameterProcessor.class, + // AnnotatedMethodParameterProcessor.class.getClassLoader()) ApplicationModel.defaultModel() .getExtensionLoader(AnnotatedMethodParameterProcessor.class) .getSupportedExtensionInstances() .forEach(processor -> { - List processors = - parameterProcessorsMap.computeIfAbsent(processor.getAnnotationType(), k -> new LinkedList<>()); + List processors = parameterProcessorsMap.computeIfAbsent( + processor.getAnnotationType(), k -> new LinkedList<>()); processors.add(processor); }); diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AnnotatedMethodParameterProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AnnotatedMethodParameterProcessor.java index 85f0f8a87d..dd97c2dbd3 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AnnotatedMethodParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/AnnotatedMethodParameterProcessor.java @@ -48,9 +48,12 @@ public interface AnnotatedMethodParameterProcessor extends Prioritized { * @param method {@link ExecutableElement method that parameter belongs to} * @param restMethodMetadata {@link RestMethodMetadata the metadata is used to update} */ - void process(AnnotationMirror annotation, VariableElement parameter, int parameterIndex, ExecutableElement method, - RestMethodMetadata restMethodMetadata); - + void process( + AnnotationMirror annotation, + VariableElement parameter, + int parameterIndex, + ExecutableElement method, + RestMethodMetadata restMethodMetadata); /** * Build the default value diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/DefaultServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/DefaultServiceRestMetadataResolver.java index 2128967878..2487572682 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/DefaultServiceRestMetadataResolver.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/DefaultServiceRestMetadataResolver.java @@ -28,6 +28,7 @@ import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; + import java.util.HashSet; import java.util.List; import java.util.Set; @@ -59,27 +60,29 @@ public class DefaultServiceRestMetadataResolver extends AbstractServiceRestMetad "application/*+json", "application/xml;charset=UTF-8", "text/xml;charset=UTF-8", - "application/*+xml;charset=UTF-8" - ); + "application/*+xml;charset=UTF-8"); private final Set hasComplexParameterTypeMethods = new HashSet<>(); @Override public boolean supports(ProcessingEnvironment processingEnvironment, TypeElement serviceType) { - return !JAXRSServiceRestMetadataResolver.supports(serviceType) && - !SpringMvcServiceRestMetadataResolver.supports(serviceType); + return !JAXRSServiceRestMetadataResolver.supports(serviceType) + && !SpringMvcServiceRestMetadataResolver.supports(serviceType); } @Override - protected boolean supports(ProcessingEnvironment processingEnv, TypeElement serviceType, - TypeElement serviceInterfaceType, ExecutableElement method) { + protected boolean supports( + ProcessingEnvironment processingEnv, + TypeElement serviceType, + TypeElement serviceInterfaceType, + ExecutableElement method) { // TODO add some criterion return true; } @Override - protected String resolveRequestPath(ProcessingEnvironment processingEnv, TypeElement serviceType, - ExecutableElement method) { + protected String resolveRequestPath( + ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method) { AnnotationMirror serviceAnnotation = getAnnotation(serviceType); @@ -105,15 +108,21 @@ public class DefaultServiceRestMetadataResolver extends AbstractServiceRestMetad continue; } else { // The count of complex types must be only one, or return immediately - warn("The method[%s] contains more than one complex parameter type, " + - "thus it will not be chosen as the REST service", method.toString()); + warn( + "The method[%s] contains more than one complex parameter type, " + + "thus it will not be chosen as the REST service", + method.toString()); } } String parameterName = parameter.getSimpleName().toString(); // If "-parameters" option is enabled, take the parameter name as the path variable name, // or use the index of parameter String pathVariableName = isEnabledParametersCompilerOption(parameterName) ? parameterName : valueOf(i); - requestPathBuilder.append(PATH_SEPARATOR).append('{').append(pathVariableName).append('}'); + requestPathBuilder + .append(PATH_SEPARATOR) + .append('{') + .append(pathVariableName) + .append('}'); } return requestPathBuilder.toString(); @@ -147,7 +156,11 @@ public class DefaultServiceRestMetadataResolver extends AbstractServiceRestMetad boolean supported; try { Class targetType = forName(className, classLoader); - supported = FrameworkModel.defaultModel().getBeanFactory().getBean(ConverterUtil.class).getConverter(String.class, targetType) != null; + supported = FrameworkModel.defaultModel() + .getBeanFactory() + .getBean(ConverterUtil.class) + .getConverter(String.class, targetType) + != null; } catch (ClassNotFoundException e) { supported = false; } @@ -155,14 +168,17 @@ public class DefaultServiceRestMetadataResolver extends AbstractServiceRestMetad } @Override - protected String resolveRequestMethod(ProcessingEnvironment processingEnv, TypeElement serviceType, - ExecutableElement method) { + protected String resolveRequestMethod( + ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method) { return HTTP_REQUEST_METHOD; } @Override - protected void processProduces(ProcessingEnvironment processingEnv, TypeElement serviceType, - ExecutableElement method, Set produces) { + protected void processProduces( + ProcessingEnvironment processingEnv, + TypeElement serviceType, + ExecutableElement method, + Set produces) { TypeMirror returnType = method.getReturnType(); if (isComplexType(returnType)) { produces.addAll(MEDIA_TYPES); @@ -170,8 +186,11 @@ public class DefaultServiceRestMetadataResolver extends AbstractServiceRestMetad } @Override - protected void processConsumes(ProcessingEnvironment processingEnv, TypeElement serviceType, - ExecutableElement method, Set consumes) { + protected void processConsumes( + ProcessingEnvironment processingEnv, + TypeElement serviceType, + ExecutableElement method, + Set consumes) { if (hasComplexParameterType(method)) { consumes.addAll(MEDIA_TYPES); } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataAnnotationProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataAnnotationProcessor.java index e4d904a1cb..e9f0c8bed5 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataAnnotationProcessor.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataAnnotationProcessor.java @@ -24,6 +24,7 @@ import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.TypeElement; + import java.io.IOException; import java.util.LinkedHashSet; import java.util.Set; @@ -50,8 +51,8 @@ public class ServiceRestMetadataAnnotationProcessor extends AbstractServiceAnnot public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); this.metadataProcessors = ApplicationModel.defaultModel() - .getExtensionLoader(ServiceRestMetadataResolver.class) - .getSupportedExtensionInstances(); + .getExtensionLoader(ServiceRestMetadataResolver.class) + .getSupportedExtensionInstances(); this.serviceRestMetadataWriter = new ServiceRestMetadataStorage(processingEnv); } @@ -71,17 +72,16 @@ public class ServiceRestMetadataAnnotationProcessor extends AbstractServiceAnnot return false; } - private void process(ProcessingEnvironment processingEnv, TypeElement serviceType, - Set annotations) { - metadataProcessors - .stream() + private void process( + ProcessingEnvironment processingEnv, TypeElement serviceType, Set annotations) { + metadataProcessors.stream() .filter(processor -> supports(processor, processingEnv, serviceType)) .map(processor -> processor.resolve(processingEnv, serviceType, annotations)) .forEach(serviceRestMetadata::add); } - private boolean supports(ServiceRestMetadataResolver processor, ProcessingEnvironment processingEnv, - TypeElement serviceType) { + private boolean supports( + ServiceRestMetadataResolver processor, ProcessingEnvironment processingEnv, TypeElement serviceType) { // @Service must be present in service type return isServiceAnnotationPresent(serviceType) && processor.supports(processingEnv, serviceType); } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataResolver.java index 9e431f1f16..ed29a2d909 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataResolver.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataResolver.java @@ -22,6 +22,7 @@ import org.apache.dubbo.metadata.rest.ServiceRestMetadata; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement; + import java.util.Set; /** @@ -49,7 +50,8 @@ public interface ServiceRestMetadataResolver extends Prioritized { * @param annotations * @return non-null */ - ServiceRestMetadata resolve(ProcessingEnvironment processingEnvironment, - TypeElement serviceType, - Set annotations); + ServiceRestMetadata resolve( + ProcessingEnvironment processingEnvironment, + TypeElement serviceType, + Set annotations); } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataStorage.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataStorage.java index a24f6b789f..14a14c24eb 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataStorage.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/ServiceRestMetadataStorage.java @@ -21,6 +21,7 @@ import org.apache.dubbo.metadata.annotation.processing.ClassPathMetadataStorage; import org.apache.dubbo.metadata.rest.ServiceRestMetadata; import javax.annotation.processing.ProcessingEnvironment; + import java.io.IOException; import java.util.Set; @@ -40,18 +41,19 @@ public class ServiceRestMetadataStorage { public void append(Set serviceRestMetadata) throws IOException { // Add all existed ServiceRestMetadata storage.read(SERVICE_REST_METADATA_RESOURCE_PATH, reader -> { - try { - StringBuilder stringBuilder = new StringBuilder(); - char[] buf = new char[1024]; - int len; - while ((len = reader.read(buf)) != -1) { - stringBuilder.append(buf, 0, len); - } - return JsonUtils.toJavaList(stringBuilder.toString(), ServiceRestMetadata.class); - } catch (IOException e) { - return null; - } - }).ifPresent(serviceRestMetadata::addAll); + try { + StringBuilder stringBuilder = new StringBuilder(); + char[] buf = new char[1024]; + int len; + while ((len = reader.read(buf)) != -1) { + stringBuilder.append(buf, 0, len); + } + return JsonUtils.toJavaList(stringBuilder.toString(), ServiceRestMetadata.class); + } catch (IOException e) { + return null; + } + }) + .ifPresent(serviceRestMetadata::addAll); write(serviceRestMetadata); } @@ -61,5 +63,4 @@ public class ServiceRestMetadataStorage { } storage.write(() -> JsonUtils.toJson(serviceRestMetadata), SERVICE_REST_METADATA_RESOURCE_PATH); } - } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/DefaultValueParameterProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/DefaultValueParameterProcessor.java index f5c5a6235c..213d2647b4 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/DefaultValueParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/DefaultValueParameterProcessor.java @@ -24,12 +24,12 @@ import org.apache.dubbo.metadata.rest.RestMethodMetadata; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.VariableElement; + import java.util.List; import java.util.Map; import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.DEFAULT_VALUE_ANNOTATION_CLASS_NAME; - /** * The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @DefaultValue * * @@ -44,14 +44,20 @@ public class DefaultValueParameterProcessor extends AbstractAnnotatedMethodParam } @Override - protected void process(String annotationValue, String defaultValue, AnnotationMirror annotation, VariableElement parameter, int parameterIndex, ExecutableElement method, RestMethodMetadata restMethodMetadata) { + protected void process( + String annotationValue, + String defaultValue, + AnnotationMirror annotation, + VariableElement parameter, + int parameterIndex, + ExecutableElement method, + RestMethodMetadata restMethodMetadata) { RequestMetadata requestMetadata = restMethodMetadata.getRequest(); // process the request parameters setDefaultValue(requestMetadata.getParams(), defaultValue, annotationValue); // process the request headers setDefaultValue(requestMetadata.getHeaders(), defaultValue, annotationValue); - } private void setDefaultValue(Map> source, String placeholderValue, String defaultValue) { diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/HeaderParamParameterProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/HeaderParamParameterProcessor.java index f4ccddf2d6..5579904e70 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/HeaderParamParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/HeaderParamParameterProcessor.java @@ -41,9 +41,14 @@ public class HeaderParamParameterProcessor extends AbstractAnnotatedMethodParame } @Override - protected void process(String headerName, String defaultValue, AnnotationMirror annotation, - VariableElement parameter, int parameterIndex, - ExecutableElement method, RestMethodMetadata restMethodMetadata) { + protected void process( + String headerName, + String defaultValue, + AnnotationMirror annotation, + VariableElement parameter, + int parameterIndex, + ExecutableElement method, + RestMethodMetadata restMethodMetadata) { RequestMetadata requestMetadata = restMethodMetadata.getRequest(); // Add the placeholder as header value requestMetadata.addHeader(headerName, buildDefaultValue(parameterIndex)); diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/JAXRSServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/JAXRSServiceRestMetadataResolver.java index 02e52a2f64..fcfc9f341f 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/JAXRSServiceRestMetadataResolver.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/JAXRSServiceRestMetadataResolver.java @@ -25,6 +25,7 @@ import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; + import java.util.Set; import java.util.stream.Stream; @@ -56,38 +57,48 @@ public class JAXRSServiceRestMetadataResolver extends AbstractServiceRestMetadat } @Override - protected boolean supports(ProcessingEnvironment processingEnv, TypeElement serviceType, - TypeElement serviceInterfaceType, ExecutableElement method) { - return isAnnotationPresent(method, PATH_ANNOTATION_CLASS_NAME) || - isAnnotationPresent(method, HTTP_METHOD_ANNOTATION_CLASS_NAME); + protected boolean supports( + ProcessingEnvironment processingEnv, + TypeElement serviceType, + TypeElement serviceInterfaceType, + ExecutableElement method) { + return isAnnotationPresent(method, PATH_ANNOTATION_CLASS_NAME) + || isAnnotationPresent(method, HTTP_METHOD_ANNOTATION_CLASS_NAME); } @Override - protected String resolveRequestPath(ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method) { + protected String resolveRequestPath( + ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method) { String pathFromType = getPathValue(processingEnv, serviceType); String pathFromMethod = getPathValue(method); return buildPath(pathFromType, pathFromMethod); } @Override - protected String resolveRequestMethod(ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method) { + protected String resolveRequestMethod( + ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method) { AnnotationMirror annotation = findMetaAnnotation(method, HTTP_METHOD_ANNOTATION_CLASS_NAME); return getValue(annotation); } @Override - protected void processProduces(ProcessingEnvironment processingEnv, TypeElement serviceType, - ExecutableElement method, Set produces) { + protected void processProduces( + ProcessingEnvironment processingEnv, + TypeElement serviceType, + ExecutableElement method, + Set produces) { addAnnotationValues(method, PRODUCES_ANNOTATION_CLASS_NAME, produces); } @Override - protected void processConsumes(ProcessingEnvironment processingEnv, TypeElement serviceType, - ExecutableElement method, Set consumes) { + protected void processConsumes( + ProcessingEnvironment processingEnv, + TypeElement serviceType, + ExecutableElement method, + Set consumes) { addAnnotationValues(method, CONSUMES_ANNOTATION_CLASS_NAME, consumes); } - private void addAnnotationValues(Element element, String annotationAttributeName, Set result) { AnnotationMirror annotation = findAnnotation(element, annotationAttributeName); String[] value = getValue(annotation); diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/ParamAnnotationParameterProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/ParamAnnotationParameterProcessor.java index d615cdcb33..8052fc9123 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/ParamAnnotationParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/jaxrs/ParamAnnotationParameterProcessor.java @@ -30,8 +30,14 @@ import javax.lang.model.element.VariableElement; */ public abstract class ParamAnnotationParameterProcessor extends AbstractAnnotatedMethodParameterProcessor { - protected void process(String name, String defaultValue, AnnotationMirror annotation, VariableElement parameter, int parameterIndex, - ExecutableElement method, RestMethodMetadata restMethodMetadata) { + protected void process( + String name, + String defaultValue, + AnnotationMirror annotation, + VariableElement parameter, + int parameterIndex, + ExecutableElement method, + RestMethodMetadata restMethodMetadata) { RequestMetadata requestMetadata = restMethodMetadata.getRequest(); requestMetadata.addParam(name, defaultValue); } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/AbstractRequestAnnotationParameterProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/AbstractRequestAnnotationParameterProcessor.java index 1fa5285ef2..2d9cf8dfb5 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/AbstractRequestAnnotationParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/AbstractRequestAnnotationParameterProcessor.java @@ -31,11 +31,14 @@ import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUti */ public abstract class AbstractRequestAnnotationParameterProcessor extends AbstractAnnotatedMethodParameterProcessor { - - protected abstract void process(String name, String defaultValue, AnnotationMirror annotation, - VariableElement parameter, int parameterIndex, - ExecutableElement method, - RestMethodMetadata restMethodMetadata); + protected abstract void process( + String name, + String defaultValue, + AnnotationMirror annotation, + VariableElement parameter, + int parameterIndex, + ExecutableElement method, + RestMethodMetadata restMethodMetadata); @Override protected String getAnnotationValue(AnnotationMirror annotation, VariableElement parameter, int parameterIndex) { diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/RequestHeaderParameterProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/RequestHeaderParameterProcessor.java index c28b88083e..49a5f747e8 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/RequestHeaderParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/RequestHeaderParameterProcessor.java @@ -36,8 +36,14 @@ public class RequestHeaderParameterProcessor extends AbstractRequestAnnotationPa } @Override - protected void process(String name, String defaultValue, AnnotationMirror annotation, VariableElement parameter, int parameterIndex, ExecutableElement method, RestMethodMetadata restMethodMetadata) { + protected void process( + String name, + String defaultValue, + AnnotationMirror annotation, + VariableElement parameter, + int parameterIndex, + ExecutableElement method, + RestMethodMetadata restMethodMetadata) { restMethodMetadata.getRequest().addHeader(name, defaultValue); } - } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/RequestParamParameterProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/RequestParamParameterProcessor.java index e589c0d7db..f881f1ca12 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/RequestParamParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/RequestParamParameterProcessor.java @@ -36,9 +36,14 @@ public class RequestParamParameterProcessor extends AbstractRequestAnnotationPar } @Override - protected void process(String name, String defaultValue, AnnotationMirror annotation, - VariableElement parameter, int parameterIndex, - ExecutableElement method, RestMethodMetadata restMethodMetadata) { + protected void process( + String name, + String defaultValue, + AnnotationMirror annotation, + VariableElement parameter, + int parameterIndex, + ExecutableElement method, + RestMethodMetadata restMethodMetadata) { restMethodMetadata.getRequest().addParam(name, defaultValue); } } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/SpringMvcServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/SpringMvcServiceRestMetadataResolver.java index e33fdb3f1d..bcf1d6edd7 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/SpringMvcServiceRestMetadataResolver.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/rest/springmvc/SpringMvcServiceRestMetadataResolver.java @@ -25,6 +25,7 @@ import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; + import java.lang.reflect.Array; import java.util.Set; @@ -58,19 +59,23 @@ public class SpringMvcServiceRestMetadataResolver extends AbstractServiceRestMet } @Override - protected boolean supports(ProcessingEnvironment processingEnv, TypeElement serviceType, - TypeElement serviceInterfaceType, ExecutableElement method) { + protected boolean supports( + ProcessingEnvironment processingEnv, + TypeElement serviceType, + TypeElement serviceInterfaceType, + ExecutableElement method) { return isAnnotationPresent(method, REQUEST_MAPPING_ANNOTATION_CLASS_NAME); } public static boolean supports(TypeElement serviceType) { // class @Controller or @RequestMapping - return isAnnotationPresent(serviceType, CONTROLLER_ANNOTATION_CLASS_NAME) || isAnnotationPresent(serviceType, REQUEST_MAPPING_ANNOTATION_CLASS_NAME); + return isAnnotationPresent(serviceType, CONTROLLER_ANNOTATION_CLASS_NAME) + || isAnnotationPresent(serviceType, REQUEST_MAPPING_ANNOTATION_CLASS_NAME); } @Override - protected String resolveRequestPath(ProcessingEnvironment processingEnv, TypeElement serviceType, - ExecutableElement method) { + protected String resolveRequestPath( + ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method) { String requestPathFromType = getRequestPath(serviceType); @@ -79,10 +84,9 @@ public class SpringMvcServiceRestMetadataResolver extends AbstractServiceRestMet return buildPath(requestPathFromType, requestPathFromMethod); } - @Override - protected String resolveRequestMethod(ProcessingEnvironment processingEnv, TypeElement serviceType, - ExecutableElement method) { + protected String resolveRequestMethod( + ProcessingEnvironment processingEnv, TypeElement serviceType, ExecutableElement method) { AnnotationMirror requestMapping = getRequestMapping(method); @@ -108,14 +112,20 @@ public class SpringMvcServiceRestMetadataResolver extends AbstractServiceRestMet } @Override - protected void processProduces(ProcessingEnvironment processingEnv, TypeElement serviceType, - ExecutableElement method, Set produces) { + protected void processProduces( + ProcessingEnvironment processingEnv, + TypeElement serviceType, + ExecutableElement method, + Set produces) { addMediaTypes(method, "produces", produces); } @Override - protected void processConsumes(ProcessingEnvironment processingEnv, TypeElement serviceType, - ExecutableElement method, Set consumes) { + protected void processConsumes( + ProcessingEnvironment processingEnv, + TypeElement serviceType, + ExecutableElement method, + Set consumes) { addMediaTypes(method, "consumes", consumes); } @@ -131,17 +141,17 @@ public class SpringMvcServiceRestMetadataResolver extends AbstractServiceRestMet } private AnnotationMirror getMappingAnnotation(Element element) { - return computeIfAbsent(valueOf(element), key -> - filterFirst(getAllAnnotations(element), annotation -> { - DeclaredType annotationType = annotation.getAnnotationType(); - // try "@RequestMapping" first - if (REQUEST_MAPPING_ANNOTATION_CLASS_NAME.equals(annotationType.toString())) { - return true; - } - // try meta annotation - return isAnnotationPresent(annotationType.asElement(), REQUEST_MAPPING_ANNOTATION_CLASS_NAME); - }) - ); + return computeIfAbsent( + valueOf(element), + key -> filterFirst(getAllAnnotations(element), annotation -> { + DeclaredType annotationType = annotation.getAnnotationType(); + // try "@RequestMapping" first + if (REQUEST_MAPPING_ANNOTATION_CLASS_NAME.equals(annotationType.toString())) { + return true; + } + // try meta annotation + return isAnnotationPresent(annotationType.asElement(), REQUEST_MAPPING_ANNOTATION_CLASS_NAME); + })); } private String getRequestPath(Element element) { diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtils.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtils.java index 176043be90..5a8f025407 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtils.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtils.java @@ -24,6 +24,7 @@ import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.type.ArrayType; import javax.lang.model.type.TypeMirror; + import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.Type; @@ -52,11 +53,9 @@ import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.ofT */ public interface AnnotationUtils { - static AnnotationMirror getAnnotation(AnnotatedConstruct annotatedConstruct, - Class annotationClass) { - return annotationClass == null ? - null : - getAnnotation(annotatedConstruct, annotationClass.getTypeName()); + static AnnotationMirror getAnnotation( + AnnotatedConstruct annotatedConstruct, Class annotationClass) { + return annotationClass == null ? null : getAnnotation(annotatedConstruct, annotationClass.getTypeName()); } static AnnotationMirror getAnnotation(AnnotatedConstruct annotatedConstruct, CharSequence annotationClassName) { @@ -64,24 +63,25 @@ public interface AnnotationUtils { return annotations.isEmpty() ? null : annotations.get(0); } - static List getAnnotations(AnnotatedConstruct annotatedConstruct, Class annotationClass) { - return annotationClass == null ? - emptyList() : - getAnnotations(annotatedConstruct, annotationClass.getTypeName()); + static List getAnnotations( + AnnotatedConstruct annotatedConstruct, Class annotationClass) { + return annotationClass == null + ? emptyList() + : getAnnotations(annotatedConstruct, annotationClass.getTypeName()); } - static List getAnnotations(AnnotatedConstruct annotatedConstruct, - CharSequence annotationClassName) { - return getAnnotations(annotatedConstruct, - annotation -> isSameType(annotation.getAnnotationType(), annotationClassName)); + static List getAnnotations( + AnnotatedConstruct annotatedConstruct, CharSequence annotationClassName) { + return getAnnotations( + annotatedConstruct, annotation -> isSameType(annotation.getAnnotationType(), annotationClassName)); } static List getAnnotations(AnnotatedConstruct annotatedConstruct) { return getAnnotations(annotatedConstruct, EMPTY_ARRAY); } - static List getAnnotations(AnnotatedConstruct annotatedConstruct, - Predicate... annotationFilters) { + static List getAnnotations( + AnnotatedConstruct annotatedConstruct, Predicate... annotationFilters) { AnnotatedConstruct actualAnnotatedConstruct = annotatedConstruct; @@ -89,9 +89,10 @@ public interface AnnotationUtils { actualAnnotatedConstruct = ofTypeElement((TypeMirror) actualAnnotatedConstruct); } - return actualAnnotatedConstruct == null ? - emptyList() : - filterAll((List) actualAnnotatedConstruct.getAnnotationMirrors(), annotationFilters); + return actualAnnotatedConstruct == null + ? emptyList() + : filterAll( + (List) actualAnnotatedConstruct.getAnnotationMirrors(), annotationFilters); } static List getAllAnnotations(TypeMirror type) { @@ -107,9 +108,9 @@ public interface AnnotationUtils { } static List getAllAnnotations(Element element, Class annotationClass) { - return element == null || annotationClass == null ? - emptyList() : - getAllAnnotations(element, annotationClass.getTypeName()); + return element == null || annotationClass == null + ? emptyList() + : getAllAnnotations(element, annotationClass.getTypeName()); } static List getAllAnnotations(TypeMirror type, CharSequence annotationClassName) { @@ -117,7 +118,8 @@ public interface AnnotationUtils { } static List getAllAnnotations(Element element, CharSequence annotationClassName) { - return getAllAnnotations(element, annotation -> isSameType(annotation.getAnnotationType(), annotationClassName)); + return getAllAnnotations( + element, annotation -> isSameType(annotation.getAnnotationType(), annotationClassName)); } static List getAllAnnotations(TypeMirror type, Predicate... annotationFilters) { @@ -126,13 +128,12 @@ public interface AnnotationUtils { static List getAllAnnotations(Element element, Predicate... annotationFilters) { - List allAnnotations = isTypeElement(element) ? - getHierarchicalTypes(ofTypeElement(element)) - .stream() + List allAnnotations = isTypeElement(element) + ? getHierarchicalTypes(ofTypeElement(element)).stream() .map(AnnotationUtils::getAnnotations) .flatMap(Collection::stream) - .collect(Collectors.toList()) : - element == null ? emptyList() : (List) element.getAnnotationMirrors(); + .collect(Collectors.toList()) + : element == null ? emptyList() : (List) element.getAnnotationMirrors(); return filterAll(allAnnotations, annotationFilters); } @@ -141,15 +142,17 @@ public interface AnnotationUtils { return getAllAnnotations(processingEnv, annotatedType, EMPTY_ARRAY); } - static List getAllAnnotations(ProcessingEnvironment processingEnv, Type annotatedType, - Predicate... annotationFilters) { - return annotatedType == null ? - emptyList() : - getAllAnnotations(processingEnv, annotatedType.getTypeName(), annotationFilters); + static List getAllAnnotations( + ProcessingEnvironment processingEnv, Type annotatedType, Predicate... annotationFilters) { + return annotatedType == null + ? emptyList() + : getAllAnnotations(processingEnv, annotatedType.getTypeName(), annotationFilters); } - static List getAllAnnotations(ProcessingEnvironment processingEnv, CharSequence annotatedTypeName, - Predicate... annotationFilters) { + static List getAllAnnotations( + ProcessingEnvironment processingEnv, + CharSequence annotatedTypeName, + Predicate... annotationFilters) { return getAllAnnotations(getType(processingEnv, annotatedTypeName), annotationFilters); } @@ -166,14 +169,14 @@ public interface AnnotationUtils { } static AnnotationMirror findAnnotation(Element element, CharSequence annotationClassName) { - return filterFirst(getAllAnnotations(element, annotation -> isSameType(annotation.getAnnotationType(), annotationClassName))); + return filterFirst(getAllAnnotations( + element, annotation -> isSameType(annotation.getAnnotationType(), annotationClassName))); } static AnnotationMirror findMetaAnnotation(Element annotatedConstruct, CharSequence metaAnnotationClassName) { - return annotatedConstruct == null ? - null : - getAnnotations(annotatedConstruct) - .stream() + return annotatedConstruct == null + ? null + : getAnnotations(annotatedConstruct).stream() .map(annotation -> findAnnotation(annotation.getAnnotationType(), metaAnnotationClassName)) .filter(Objects::nonNull) .findFirst() @@ -181,16 +184,16 @@ public interface AnnotationUtils { } static boolean isAnnotationPresent(Element element, CharSequence annotationClassName) { - return findAnnotation(element, annotationClassName) != null || - findMetaAnnotation(element, annotationClassName) != null; + return findAnnotation(element, annotationClassName) != null + || findMetaAnnotation(element, annotationClassName) != null; } static T getAttribute(AnnotationMirror annotation, String attributeName) { return annotation == null ? null : getAttribute(annotation.getElementValues(), attributeName); } - static T getAttribute(Map attributesMap, - String attributeName) { + static T getAttribute( + Map attributesMap, String attributeName) { T annotationValue = null; for (Map.Entry entry : attributesMap.entrySet()) { ExecutableElement attributeMethod = entry.getKey(); diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/ExecutableElementComparator.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/ExecutableElementComparator.java index 31603faabe..362c572bf9 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/ExecutableElementComparator.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/ExecutableElementComparator.java @@ -20,6 +20,7 @@ import org.apache.dubbo.common.utils.CharSequenceComparator; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.VariableElement; + import java.util.Comparator; import java.util.List; @@ -36,10 +37,9 @@ import java.util.List; */ public class ExecutableElementComparator implements Comparator { - public final static ExecutableElementComparator INSTANCE = new ExecutableElementComparator(); + public static final ExecutableElementComparator INSTANCE = new ExecutableElementComparator(); - private ExecutableElementComparator() { - } + private ExecutableElementComparator() {} @Override public int compare(ExecutableElement e1, ExecutableElement e2) { @@ -60,7 +60,8 @@ public class ExecutableElementComparator implements Comparator getAllDeclaredFields(TypeMirror type, Predicate... fieldFilters) { - return getHierarchicalTypes(type) - .stream() + return getHierarchicalTypes(type).stream() .map(t -> getDeclaredFields(t, fieldFilters)) .flatMap(Collection::stream) .collect(Collectors.toList()); @@ -87,7 +87,8 @@ public interface FieldUtils { } static VariableElement getDeclaredField(TypeMirror type, String fieldName) { - return filterFirst(getDeclaredFields(type, field -> fieldName.equals(field.getSimpleName().toString()))); + return filterFirst(getDeclaredFields( + type, field -> fieldName.equals(field.getSimpleName().toString()))); } static VariableElement findField(Element element, String fieldName) { @@ -140,7 +141,8 @@ public interface FieldUtils { } static boolean equals(VariableElement field, CharSequence fieldName) { - return field != null && fieldName != null && field.getSimpleName().toString().equals(fieldName.toString()); + return field != null + && fieldName != null + && field.getSimpleName().toString().equals(fieldName.toString()); } - } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/LoggerUtils.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/LoggerUtils.java index 9bac9d65dc..b8a6b44051 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/LoggerUtils.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/LoggerUtils.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.annotation.processing.util; - import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtils.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtils.java index 800b4ba1fd..5b5cbdf2a3 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtils.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtils.java @@ -22,6 +22,7 @@ import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; + import java.util.Collection; import java.util.List; import java.util.Objects; @@ -68,8 +69,7 @@ public interface MemberUtils { } static List getAllDeclaredMembers(TypeMirror type) { - return getHierarchicalTypes(type) - .stream() + return getHierarchicalTypes(type).stream() .map(MemberUtils::getDeclaredMembers) .flatMap(Collection::stream) .collect(Collectors.toList()); diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtils.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtils.java index 0bd2ae900e..6aa5c9b180 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtils.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtils.java @@ -16,13 +16,13 @@ */ package org.apache.dubbo.metadata.annotation.processing.util; - import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; + import java.lang.reflect.Type; import java.util.Collection; import java.util.LinkedList; @@ -59,7 +59,8 @@ public interface MethodUtils { return filterAll(methodsIn(getDeclaredMembers(type)), methodFilters); } - static List getAllDeclaredMethods(TypeElement type, Predicate... methodFilters) { + static List getAllDeclaredMethods( + TypeElement type, Predicate... methodFilters) { return type == null ? emptyList() : getAllDeclaredMethods(type.asType(), methodFilters); } @@ -67,9 +68,9 @@ public interface MethodUtils { return getAllDeclaredMethods(type, EMPTY_ARRAY); } - static List getAllDeclaredMethods(TypeMirror type, Predicate... methodFilters) { - return getHierarchicalTypes(type) - .stream() + static List getAllDeclaredMethods( + TypeMirror type, Predicate... methodFilters) { + return getHierarchicalTypes(type).stream() .map(t -> getDeclaredMethods(t, methodFilters)) .flatMap(Collection::stream) .collect(Collectors.toList()); @@ -84,8 +85,7 @@ public interface MethodUtils { } static List getAllDeclaredMethods(TypeMirror type, Type... excludedTypes) { - return getHierarchicalTypes(type, excludedTypes) - .stream() + return getHierarchicalTypes(type, excludedTypes).stream() .map(t -> getDeclaredMethods(t)) .flatMap(Collection::stream) .collect(Collectors.toList()); @@ -107,15 +107,18 @@ public interface MethodUtils { return isMethod(method) && isPublicNonStatic(method); } - static ExecutableElement findMethod(TypeElement type, String methodName, Type oneParameterType, Type... otherParameterTypes) { + static ExecutableElement findMethod( + TypeElement type, String methodName, Type oneParameterType, Type... otherParameterTypes) { return type == null ? null : findMethod(type.asType(), methodName, oneParameterType, otherParameterTypes); } - static ExecutableElement findMethod(TypeMirror type, String methodName, Type oneParameterType, Type... otherParameterTypes) { + static ExecutableElement findMethod( + TypeMirror type, String methodName, Type oneParameterType, Type... otherParameterTypes) { List parameterTypes = new LinkedList<>(); parameterTypes.add(oneParameterType); parameterTypes.addAll(asList(otherParameterTypes)); - return findMethod(type, methodName, parameterTypes.stream().map(Type::getTypeName).toArray(String[]::new)); + return findMethod( + type, methodName, parameterTypes.stream().map(Type::getTypeName).toArray(String[]::new)); } static ExecutableElement findMethod(TypeElement type, String methodName, CharSequence... parameterTypes) { @@ -123,19 +126,18 @@ public interface MethodUtils { } static ExecutableElement findMethod(TypeMirror type, String methodName, CharSequence... parameterTypes) { - return filterFirst(getAllDeclaredMethods(type), + return filterFirst( + getAllDeclaredMethods(type), method -> methodName.equals(method.getSimpleName().toString()), - method -> matchParameterTypes(method.getParameters(), parameterTypes) - ); + method -> matchParameterTypes(method.getParameters(), parameterTypes)); } - static ExecutableElement getOverrideMethod(ProcessingEnvironment processingEnv, TypeElement type, - ExecutableElement declaringMethod) { + static ExecutableElement getOverrideMethod( + ProcessingEnvironment processingEnv, TypeElement type, ExecutableElement declaringMethod) { Elements elements = processingEnv.getElementUtils(); return filterFirst(getAllDeclaredMethods(type), method -> elements.overrides(method, declaringMethod, type)); } - static String getMethodName(ExecutableElement method) { return method == null ? null : method.getSimpleName().toString(); } @@ -145,10 +147,9 @@ public interface MethodUtils { } static String[] getMethodParameterTypes(ExecutableElement method) { - return method == null ? - new String[0] : - method.getParameters() - .stream() + return method == null + ? new String[0] + : method.getParameters().stream() .map(VariableElement::asType) .map(TypeUtils::toString) .toArray(String[]::new); diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtils.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtils.java index 6f0010b550..ffda6e42b2 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtils.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtils.java @@ -18,6 +18,7 @@ package org.apache.dubbo.metadata.annotation.processing.util; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.TypeElement; + import java.util.LinkedHashSet; import java.util.Objects; import java.util.Set; @@ -78,7 +79,8 @@ public interface ServiceAnnotationUtils { */ String VERSION_ATTRIBUTE_NAME = "version"; - Set SUPPORTED_ANNOTATION_TYPES = unmodifiableSet(new LinkedHashSet<>(asList(DUBBO_SERVICE_ANNOTATION_TYPE, SERVICE_ANNOTATION_TYPE, LEGACY_SERVICE_ANNOTATION_TYPE))); + Set SUPPORTED_ANNOTATION_TYPES = unmodifiableSet(new LinkedHashSet<>( + asList(DUBBO_SERVICE_ANNOTATION_TYPE, SERVICE_ANNOTATION_TYPE, LEGACY_SERVICE_ANNOTATION_TYPE))); static boolean isServiceAnnotationPresent(TypeElement annotatedType) { return SUPPORTED_ANNOTATION_TYPES.stream() @@ -106,7 +108,8 @@ public interface ServiceAnnotationUtils { } if (matchedAnnotationMirror == null) { - throw new IllegalArgumentException("The annotated element must be annotated any of " + SUPPORTED_ANNOTATION_TYPES); + throw new IllegalArgumentException( + "The annotated element must be annotated any of " + SUPPORTED_ANNOTATION_TYPES); } return matchedAnnotationMirror; diff --git a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtils.java b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtils.java index 2f877e6bc5..0e85171fda 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtils.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtils.java @@ -28,6 +28,7 @@ import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.tools.FileObject; import javax.tools.StandardLocation; + import java.io.IOException; import java.lang.reflect.Type; import java.net.URL; @@ -61,12 +62,8 @@ import static org.apache.dubbo.common.utils.MethodUtils.invokeMethod; */ public interface TypeUtils { - List SIMPLE_TYPES = asList( - ClassUtils.SIMPLE_TYPES - .stream() - .map(Class::getName) - .toArray(String[]::new) - ); + List SIMPLE_TYPES = + asList(ClassUtils.SIMPLE_TYPES.stream().map(Class::getName).toArray(String[]::new)); static boolean isSimpleType(Element element) { return element != null && isSimpleType(element.asType()); @@ -152,19 +149,22 @@ public interface TypeUtils { } static Set getHierarchicalTypes(TypeMirror type, Type... excludedTypes) { - return getHierarchicalTypes(type, of(excludedTypes).map(Type::getTypeName).toArray(String[]::new)); + return getHierarchicalTypes( + type, of(excludedTypes).map(Type::getTypeName).toArray(String[]::new)); } static Set getHierarchicalTypes(TypeMirror type, CharSequence... excludedTypeNames) { - Set typeNames = of(excludedTypeNames).map(CharSequence::toString).collect(toSet()); + Set typeNames = + of(excludedTypeNames).map(CharSequence::toString).collect(toSet()); return getHierarchicalTypes(type, t -> !typeNames.contains(t.toString())); } - static Set getHierarchicalTypes(TypeElement type, - boolean includeSelf, - boolean includeSuperTypes, - boolean includeSuperInterfaces, - Predicate... typeFilters) { + static Set getHierarchicalTypes( + TypeElement type, + boolean includeSelf, + boolean includeSuperTypes, + boolean includeSuperInterfaces, + Predicate... typeFilters) { if (type == null) { return emptySet(); @@ -187,18 +187,16 @@ public interface TypeUtils { return filterAll(hierarchicalTypes, typeFilters); } - static Set getHierarchicalTypes(TypeMirror type, - boolean includeSelf, - boolean includeSuperTypes, - boolean includeSuperInterfaces) { - return ofDeclaredTypes(getHierarchicalTypes(ofTypeElement(type), - includeSelf, - includeSuperTypes, - includeSuperInterfaces)); + static Set getHierarchicalTypes( + TypeMirror type, boolean includeSelf, boolean includeSuperTypes, boolean includeSuperInterfaces) { + return ofDeclaredTypes( + getHierarchicalTypes(ofTypeElement(type), includeSelf, includeSuperTypes, includeSuperInterfaces)); } static List getInterfaces(TypeElement type, Predicate... interfaceFilters) { - return type == null ? emptyList() : filterAll((List) ofTypeElement(type).getInterfaces(), interfaceFilters); + return type == null + ? emptyList() + : filterAll((List) ofTypeElement(type).getInterfaces(), interfaceFilters); } static List getInterfaces(TypeMirror type, Predicate... interfaceFilters) { @@ -320,9 +318,9 @@ public interface TypeUtils { } static Set ofDeclaredTypes(Iterable elements) { - return elements == null ? - emptySet() : - stream(elements.spliterator(), false) + return elements == null + ? emptySet() + : stream(elements.spliterator(), false) .map(TypeUtils::ofTypeElement) .filter(Objects::nonNull) .map(Element::asType) @@ -332,9 +330,9 @@ public interface TypeUtils { } static Set ofTypeElements(Iterable types) { - return types == null ? - emptySet() : - stream(types.spliterator(), false) + return types == null + ? emptySet() + : stream(types.spliterator(), false) .map(TypeUtils::ofTypeElement) .filter(Objects::nonNull) .collect(LinkedHashSet::new, Set::add, Set::addAll); @@ -361,7 +359,8 @@ public interface TypeUtils { URL resource = null; try { if (relativeName != null) { - FileObject fileObject = processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", relativeName); + FileObject fileObject = + processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", relativeName); resource = fileObject.toUri().toURL(); // try to open it resource.getContent(); diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/AbstractAnnotationProcessingTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/AbstractAnnotationProcessingTest.java index fb0421eb91..cbb0a5da77 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/AbstractAnnotationProcessingTest.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/AbstractAnnotationProcessingTest.java @@ -18,18 +18,18 @@ package org.apache.dubbo.metadata.annotation.processing; import org.apache.dubbo.metadata.annotation.processing.util.TypeUtils; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.extension.ExtendWith; - import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; -import java.io.IOException; + import java.lang.annotation.Annotation; import java.util.Set; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; + /** * Abstract {@link Annotation} Processing Test case * diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/AnnotationProcessingTestProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/AnnotationProcessingTestProcessor.java index a02432711b..4b21c6437f 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/AnnotationProcessingTestProcessor.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/AnnotationProcessingTestProcessor.java @@ -16,18 +16,19 @@ */ package org.apache.dubbo.metadata.annotation.processing; -import org.junit.jupiter.api.extension.ExtensionContext; -import org.junit.jupiter.api.extension.InvocationInterceptor; -import org.junit.jupiter.api.extension.ReflectiveInvocationContext; - import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.SourceVersion; import javax.lang.model.element.TypeElement; + import java.lang.reflect.Method; import java.util.Set; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.InvocationInterceptor; +import org.junit.jupiter.api.extension.ReflectiveInvocationContext; + import static javax.lang.model.SourceVersion.latestSupported; @SupportedAnnotationTypes("*") @@ -40,9 +41,11 @@ public class AnnotationProcessingTestProcessor extends AbstractProcessor { private final ExtensionContext extensionContext; - public AnnotationProcessingTestProcessor(AbstractAnnotationProcessingTest abstractAnnotationProcessingTest, InvocationInterceptor.Invocation invocation, - ReflectiveInvocationContext invocationContext, - ExtensionContext extensionContext) { + public AnnotationProcessingTestProcessor( + AbstractAnnotationProcessingTest abstractAnnotationProcessingTest, + InvocationInterceptor.Invocation invocation, + ReflectiveInvocationContext invocationContext, + ExtensionContext extensionContext) { this.abstractAnnotationProcessingTest = abstractAnnotationProcessingTest; this.invocation = invocation; this.invocationContext = invocationContext; diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/CompilerInvocationInterceptor.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/CompilerInvocationInterceptor.java index fe97b4b4b8..44689fe64e 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/CompilerInvocationInterceptor.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/CompilerInvocationInterceptor.java @@ -18,28 +18,31 @@ package org.apache.dubbo.metadata.annotation.processing; import org.apache.dubbo.metadata.tools.Compiler; -import org.junit.jupiter.api.extension.ExtensionContext; -import org.junit.jupiter.api.extension.InvocationInterceptor; -import org.junit.jupiter.api.extension.ReflectiveInvocationContext; - import java.lang.reflect.Method; import java.util.LinkedHashSet; import java.util.Set; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.InvocationInterceptor; +import org.junit.jupiter.api.extension.ReflectiveInvocationContext; + import static org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest.testInstanceHolder; public class CompilerInvocationInterceptor implements InvocationInterceptor { @Override - public void interceptTestMethod(Invocation invocation, - ReflectiveInvocationContext invocationContext, - ExtensionContext extensionContext) throws Throwable { + public void interceptTestMethod( + Invocation invocation, + ReflectiveInvocationContext invocationContext, + ExtensionContext extensionContext) + throws Throwable { Set> classesToBeCompiled = new LinkedHashSet<>(); AbstractAnnotationProcessingTest abstractAnnotationProcessingTest = testInstanceHolder.get(); classesToBeCompiled.add(getClass()); abstractAnnotationProcessingTest.addCompiledClasses(classesToBeCompiled); Compiler compiler = new Compiler(); - compiler.processors(new AnnotationProcessingTestProcessor(abstractAnnotationProcessingTest, invocation, invocationContext, extensionContext)); + compiler.processors(new AnnotationProcessingTestProcessor( + abstractAnnotationProcessingTest, invocation, invocationContext, extensionContext)); compiler.compile(classesToBeCompiled.toArray(new Class[0])); } } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilderTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilderTest.java index cd84396e6d..779cbd08b8 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilderTest.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilderTest.java @@ -20,18 +20,19 @@ import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcess import org.apache.dubbo.metadata.annotation.processing.model.ArrayTypeModel; import org.apache.dubbo.metadata.definition.model.TypeDefinition; -import org.junit.jupiter.api.Test; - import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.ElementKind; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; + import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; import java.util.stream.Stream; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -89,37 +90,51 @@ class ArrayTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { buildAndAssertTypeDefinition(processingEnv, stringsField, "java.lang.String[]", "java.lang.String", builder); - buildAndAssertTypeDefinition(processingEnv, primitiveTypeModelsField, + buildAndAssertTypeDefinition( + processingEnv, + primitiveTypeModelsField, "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel[]", - "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel", builder); + "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel", + builder); - buildAndAssertTypeDefinition(processingEnv, modelsField, + buildAndAssertTypeDefinition( + processingEnv, + modelsField, "org.apache.dubbo.metadata.annotation.processing.model.Model[]", - "org.apache.dubbo.metadata.annotation.processing.model.Model", builder, (def, subDef) -> { + "org.apache.dubbo.metadata.annotation.processing.model.Model", + builder, + (def, subDef) -> { TypeElement subType = elements.getTypeElement(subDef.getType()); assertEquals(ElementKind.CLASS, subType.getKind()); }); - buildAndAssertTypeDefinition(processingEnv, colorsField, + buildAndAssertTypeDefinition( + processingEnv, + colorsField, "org.apache.dubbo.metadata.annotation.processing.model.Color[]", - "org.apache.dubbo.metadata.annotation.processing.model.Color", builder, (def, subDef) -> { + "org.apache.dubbo.metadata.annotation.processing.model.Color", + builder, + (def, subDef) -> { TypeElement subType = elements.getTypeElement(subDef.getType()); assertEquals(ElementKind.ENUM, subType.getKind()); }); - } - static void buildAndAssertTypeDefinition(ProcessingEnvironment processingEnv, VariableElement field, - String expectedType, String compositeType, TypeBuilder builder, - BiConsumer... assertions) { + static void buildAndAssertTypeDefinition( + ProcessingEnvironment processingEnv, + VariableElement field, + String expectedType, + String compositeType, + TypeBuilder builder, + BiConsumer... assertions) { Map typeCache = new HashMap<>(); TypeDefinition typeDefinition = TypeDefinitionBuilder.build(processingEnv, field, typeCache); String subTypeName = typeDefinition.getItems().get(0); TypeDefinition subTypeDefinition = typeCache.get(subTypeName); assertEquals(expectedType, typeDefinition.getType()); -// assertEquals(field.getSimpleName().toString(), typeDefinition.get$ref()); + // assertEquals(field.getSimpleName().toString(), typeDefinition.get$ref()); assertEquals(compositeType, subTypeDefinition.getType()); -// assertEquals(builder.getClass().getName(), typeDefinition.getTypeBuilderName()); + // assertEquals(builder.getClass().getName(), typeDefinition.getTypeBuilderName()); Stream.of(assertions).forEach(assertion -> assertion.accept(typeDefinition, subTypeDefinition)); } } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilderTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilderTest.java index e99d417784..865613a496 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilderTest.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilderTest.java @@ -19,12 +19,13 @@ package org.apache.dubbo.metadata.annotation.processing.builder; import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; import org.apache.dubbo.metadata.annotation.processing.model.CollectionTypeModel; -import org.junit.jupiter.api.Test; - import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; + import java.util.Set; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.metadata.annotation.processing.builder.ArrayTypeDefinitionBuilderTest.buildAndAssertTypeDefinition; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -58,15 +59,16 @@ class CollectionTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTe protected void beforeEach() { builder = new CollectionTypeDefinitionBuilder(); TypeElement testType = getType(CollectionTypeModel.class); - stringsField = findField( testType, "strings"); - colorsField = findField( testType, "colors"); - primitiveTypeModelsField = findField( testType, "primitiveTypeModels"); - modelsField = findField( testType, "models"); - modelArraysField = findField( testType, "modelArrays"); + stringsField = findField(testType, "strings"); + colorsField = findField(testType, "colors"); + primitiveTypeModelsField = findField(testType, "primitiveTypeModels"); + modelsField = findField(testType, "models"); + modelArraysField = findField(testType, "modelArrays"); assertEquals("strings", stringsField.getSimpleName().toString()); assertEquals("colors", colorsField.getSimpleName().toString()); - assertEquals("primitiveTypeModels", primitiveTypeModelsField.getSimpleName().toString()); + assertEquals( + "primitiveTypeModels", primitiveTypeModelsField.getSimpleName().toString()); assertEquals("models", modelsField.getSimpleName().toString()); assertEquals("modelArrays", modelArraysField.getSimpleName().toString()); } @@ -83,23 +85,35 @@ class CollectionTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTe @Test void testBuild() { - buildAndAssertTypeDefinition(processingEnv, stringsField, "java.util.Collection", "java.lang.String", builder); + buildAndAssertTypeDefinition( + processingEnv, stringsField, "java.util.Collection", "java.lang.String", builder); - buildAndAssertTypeDefinition(processingEnv, colorsField, "java.util.List", - "org.apache.dubbo.metadata.annotation.processing.model.Color", builder); + buildAndAssertTypeDefinition( + processingEnv, + colorsField, + "java.util.List", + "org.apache.dubbo.metadata.annotation.processing.model.Color", + builder); - buildAndAssertTypeDefinition(processingEnv, primitiveTypeModelsField, + buildAndAssertTypeDefinition( + processingEnv, + primitiveTypeModelsField, "java.util.Queue", - "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel", builder); + "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel", + builder); - buildAndAssertTypeDefinition(processingEnv, modelsField, + buildAndAssertTypeDefinition( + processingEnv, + modelsField, "java.util.Deque", - "org.apache.dubbo.metadata.annotation.processing.model.Model", builder); + "org.apache.dubbo.metadata.annotation.processing.model.Model", + builder); - buildAndAssertTypeDefinition(processingEnv, modelArraysField, + buildAndAssertTypeDefinition( + processingEnv, + modelArraysField, "java.util.Set", - "org.apache.dubbo.metadata.annotation.processing.model.Model[]", builder); - - + "org.apache.dubbo.metadata.annotation.processing.model.Model[]", + builder); } } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilderTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilderTest.java index 49572e708e..d3a7261f57 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilderTest.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilderTest.java @@ -20,13 +20,14 @@ import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcess import org.apache.dubbo.metadata.annotation.processing.model.Color; import org.apache.dubbo.metadata.definition.model.TypeDefinition; -import org.junit.jupiter.api.Test; - import javax.lang.model.element.TypeElement; + import java.util.HashMap; import java.util.Map; import java.util.Set; +import org.junit.jupiter.api.Test; + import static java.util.Arrays.asList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -63,7 +64,6 @@ class EnumTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { TypeDefinition typeDefinition = TypeDefinitionBuilder.build(processingEnv, typeElement, typeCache); assertEquals(Color.class.getName(), typeDefinition.getType()); assertEquals(asList("RED", "YELLOW", "BLUE"), typeDefinition.getEnums()); -// assertEquals(typeDefinition.getTypeBuilderName(), builder.getClass().getName()); + // assertEquals(typeDefinition.getTypeBuilderName(), builder.getClass().getName()); } - } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilderTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilderTest.java index 8ca703aa32..7a930e5924 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilderTest.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilderTest.java @@ -24,10 +24,10 @@ import org.apache.dubbo.metadata.annotation.processing.model.Model; import org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel; import org.apache.dubbo.metadata.annotation.processing.model.SimpleTypeModel; -import org.junit.jupiter.api.Test; - import java.util.Set; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -53,15 +53,15 @@ class GeneralTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest @Test void testAccept() { assertTrue(builder.accept(processingEnv, getType(Model.class).asType())); - assertTrue(builder.accept(processingEnv, getType(PrimitiveTypeModel.class).asType())); + assertTrue( + builder.accept(processingEnv, getType(PrimitiveTypeModel.class).asType())); assertTrue(builder.accept(processingEnv, getType(SimpleTypeModel.class).asType())); assertTrue(builder.accept(processingEnv, getType(ArrayTypeModel.class).asType())); - assertTrue(builder.accept(processingEnv, getType(CollectionTypeModel.class).asType())); + assertTrue( + builder.accept(processingEnv, getType(CollectionTypeModel.class).asType())); assertFalse(builder.accept(processingEnv, getType(Color.class).asType())); } @Test - void testBuild() { - - } + void testBuild() {} } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilderTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilderTest.java index 4f48684606..dd7944c66e 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilderTest.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilderTest.java @@ -20,17 +20,18 @@ import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcess import org.apache.dubbo.metadata.annotation.processing.model.MapTypeModel; import org.apache.dubbo.metadata.definition.model.TypeDefinition; -import org.junit.jupiter.api.Test; - import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; + import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; import java.util.stream.Stream; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -71,7 +72,8 @@ class MapTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { assertEquals("strings", stringsField.getSimpleName().toString()); assertEquals("colors", colorsField.getSimpleName().toString()); - assertEquals("primitiveTypeModels", primitiveTypeModelsField.getSimpleName().toString()); + assertEquals( + "primitiveTypeModels", primitiveTypeModelsField.getSimpleName().toString()); assertEquals("models", modelsField.getSimpleName().toString()); assertEquals("modelArrays", modelArraysField.getSimpleName().toString()); } @@ -88,41 +90,55 @@ class MapTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { @Test void testBuild() { - buildAndAssertTypeDefinition(processingEnv, stringsField, + buildAndAssertTypeDefinition( + processingEnv, + stringsField, "java.util.Map", "java.lang.String", "java.lang.String", builder); - buildAndAssertTypeDefinition(processingEnv, colorsField, + buildAndAssertTypeDefinition( + processingEnv, + colorsField, "java.util.SortedMap", "java.lang.String", "org.apache.dubbo.metadata.annotation.processing.model.Color", builder); - buildAndAssertTypeDefinition(processingEnv, primitiveTypeModelsField, + buildAndAssertTypeDefinition( + processingEnv, + primitiveTypeModelsField, "java.util.NavigableMap", "org.apache.dubbo.metadata.annotation.processing.model.Color", "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel", builder); - buildAndAssertTypeDefinition(processingEnv, modelsField, + buildAndAssertTypeDefinition( + processingEnv, + modelsField, "java.util.HashMap", "java.lang.String", "org.apache.dubbo.metadata.annotation.processing.model.Model", builder); - buildAndAssertTypeDefinition(processingEnv, modelArraysField, + buildAndAssertTypeDefinition( + processingEnv, + modelArraysField, "java.util.TreeMap", "org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel", "org.apache.dubbo.metadata.annotation.processing.model.Model[]", builder); } - static void buildAndAssertTypeDefinition(ProcessingEnvironment processingEnv, VariableElement field, - String expectedType, String keyType, String valueType, - TypeBuilder builder, - BiConsumer... assertions) { + static void buildAndAssertTypeDefinition( + ProcessingEnvironment processingEnv, + VariableElement field, + String expectedType, + String keyType, + String valueType, + TypeBuilder builder, + BiConsumer... assertions) { Map typeCache = new HashMap<>(); TypeDefinition typeDefinition = TypeDefinitionBuilder.build(processingEnv, field, typeCache); String keyTypeName = typeDefinition.getItems().get(0); @@ -130,10 +146,10 @@ class MapTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { String valueTypeName = typeDefinition.getItems().get(1); TypeDefinition valueTypeDefinition = typeCache.get(valueTypeName); assertEquals(expectedType, typeDefinition.getType()); -// assertEquals(field.getSimpleName().toString(), typeDefinition.get$ref()); + // assertEquals(field.getSimpleName().toString(), typeDefinition.get$ref()); assertEquals(keyType, keyTypeDefinition.getType()); assertEquals(valueType, valueTypeDefinition.getType()); -// assertEquals(builder.getClass().getName(), typeDefinition.getTypeBuilderName()); + // assertEquals(builder.getClass().getName(), typeDefinition.getTypeBuilderName()); Stream.of(assertions).forEach(assertion -> assertion.accept(typeDefinition, keyTypeDefinition)); } } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilderTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilderTest.java index 3c9774cf6c..db714bde3f 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilderTest.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilderTest.java @@ -20,15 +20,16 @@ import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcess import org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel; import org.apache.dubbo.metadata.definition.model.TypeDefinition; -import org.junit.jupiter.api.Test; - import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; + import java.util.HashMap; import java.util.Map; import java.util.Set; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -70,14 +71,14 @@ class PrimitiveTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTes TypeElement testType = getType(PrimitiveTypeModel.class); - zField = findField( testType, "z"); - bField = findField( testType, "b"); - cField = findField( testType, "c"); - sField = findField( testType, "s"); - iField = findField( testType, "i"); - lField = findField( testType, "l"); - fField = findField( testType, "f"); - dField = findField( testType, "d"); + zField = findField(testType, "z"); + bField = findField(testType, "b"); + cField = findField(testType, "c"); + sField = findField(testType, "s"); + iField = findField(testType, "i"); + lField = findField(testType, "l"); + fField = findField(testType, "f"); + dField = findField(testType, "d"); assertEquals("boolean", zField.asType().toString()); assertEquals("byte", bField.asType().toString()); @@ -114,16 +115,17 @@ class PrimitiveTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTes buildAndAssertTypeDefinition(processingEnv, dField, builder); } - static void buildAndAssertTypeDefinition(ProcessingEnvironment processingEnv, VariableElement field, TypeBuilder builder) { + static void buildAndAssertTypeDefinition( + ProcessingEnvironment processingEnv, VariableElement field, TypeBuilder builder) { Map typeCache = new HashMap<>(); TypeDefinition typeDefinition = TypeDefinitionBuilder.build(processingEnv, field, typeCache); assertBasicTypeDefinition(typeDefinition, field.asType().toString(), builder); -// assertEquals(field.getSimpleName().toString(), typeDefinition.get$ref()); + // assertEquals(field.getSimpleName().toString(), typeDefinition.get$ref()); } static void assertBasicTypeDefinition(TypeDefinition typeDefinition, String type, TypeBuilder builder) { assertEquals(type, typeDefinition.getType()); -// assertEquals(builder.getClass().getName(), typeDefinition.getTypeBuilderName()); + // assertEquals(builder.getClass().getName(), typeDefinition.getTypeBuilderName()); assertTrue(typeDefinition.getProperties().isEmpty()); assertTrue(typeDefinition.getItems().isEmpty()); assertTrue(typeDefinition.getEnums().isEmpty()); diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilderTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilderTest.java index 9906f12975..0f57ba3778 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilderTest.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilderTest.java @@ -21,12 +21,12 @@ import org.apache.dubbo.metadata.definition.model.ServiceDefinition; import org.apache.dubbo.metadata.definition.model.TypeDefinition; import org.apache.dubbo.metadata.tools.TestServiceImpl; -import org.junit.jupiter.api.Test; - import java.util.Arrays; import java.util.List; import java.util.Set; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.metadata.annotation.processing.builder.ServiceDefinitionBuilder.build; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -37,15 +37,13 @@ import static org.junit.jupiter.api.Assertions.assertEquals; */ class ServiceDefinitionBuilderTest extends AbstractAnnotationProcessingTest { - @Override protected void addCompiledClasses(Set> classesToBeCompiled) { classesToBeCompiled.add(TestServiceImpl.class); } @Override - protected void beforeEach() { - } + protected void beforeEach() {} @Test void testBuild() { @@ -61,8 +59,7 @@ class ServiceDefinitionBuilderTest extends AbstractAnnotationProcessingTest { "org.apache.dubbo.metadata.tools.TestService", "java.lang.AutoCloseable", "java.io.Serializable", - "java.util.EventListener" - ); + "java.util.EventListener"); for (String typeName : typeNames) { String gotTypeName = getTypeName(typeName, serviceDefinition.getTypes()); assertEquals(typeName, gotTypeName); diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilderTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilderTest.java index 08f008d394..10118ee8bd 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilderTest.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/SimpleTypeDefinitionBuilderTest.java @@ -19,12 +19,13 @@ package org.apache.dubbo.metadata.annotation.processing.builder; import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcessingTest; import org.apache.dubbo.metadata.annotation.processing.model.SimpleTypeModel; -import org.junit.jupiter.api.Test; - import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; + import java.util.Set; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.metadata.annotation.processing.builder.PrimitiveTypeDefinitionBuilderTest.buildAndAssertTypeDefinition; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -68,7 +69,6 @@ class SimpleTypeDefinitionBuilderTest extends AbstractAnnotationProcessingTest { private VariableElement invalidField; - @Override protected void addCompiledClasses(Set> classesToBeCompiled) { classesToBeCompiled.add(SimpleTypeModel.class); diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/ArrayTypeModel.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/ArrayTypeModel.java index 28bf4f3111..8c8a63a8f5 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/ArrayTypeModel.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/ArrayTypeModel.java @@ -23,14 +23,13 @@ package org.apache.dubbo.metadata.annotation.processing.model; */ public class ArrayTypeModel { - private int[] integers; // Primitive type array + private int[] integers; // Primitive type array - private String[] strings; // Simple type array + private String[] strings; // Simple type array private PrimitiveTypeModel[] primitiveTypeModels; // Complex type array - private Model[] models; // Hierarchical Complex type array - - private Color[] colors; // Enum type array + private Model[] models; // Hierarchical Complex type array + private Color[] colors; // Enum type array } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/CollectionTypeModel.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/CollectionTypeModel.java index e90f1c8926..f370432203 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/CollectionTypeModel.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/CollectionTypeModel.java @@ -31,12 +31,11 @@ public class CollectionTypeModel { private Collection strings; // The composite element is simple type - private List colors; // The composite element is Enum type + private List colors; // The composite element is Enum type - private Queue primitiveTypeModels; // The composite element is POJO type + private Queue primitiveTypeModels; // The composite element is POJO type - private Deque models; // The composite element is hierarchical POJO type + private Deque models; // The composite element is hierarchical POJO type private Set modelArrays; // The composite element is hierarchical POJO type - } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Color.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Color.java index 9fab9df62d..e1fc517bee 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Color.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/Color.java @@ -22,7 +22,6 @@ package org.apache.dubbo.metadata.annotation.processing.model; * @since 2.7.6 */ public enum Color { - RED(1), YELLOW(2), BLUE(3); @@ -35,9 +34,7 @@ public enum Color { @Override public String toString() { - return "Color{" + - "value=" + value + - "} " + super.toString(); + return "Color{" + "value=" + value + "} " + super.toString(); } public int getValue() { diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/MapTypeModel.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/MapTypeModel.java index 087aa932ed..fb58296034 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/MapTypeModel.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/model/MapTypeModel.java @@ -31,11 +31,11 @@ public class MapTypeModel { private Map strings; // The composite element is simple type - private SortedMap colors; // The composite element is Enum type + private SortedMap colors; // The composite element is Enum type - private NavigableMap primitiveTypeModels; // The composite element is POJO type + private NavigableMap primitiveTypeModels; // The composite element is POJO type - private HashMap models; // The composite element is hierarchical POJO type + private HashMap models; // The composite element is hierarchical POJO type private TreeMap modelArrays; // The composite element is hierarchical POJO type } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtilsTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtilsTest.java index 79a50e304c..1bb202d91d 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtilsTest.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/AnnotationUtilsTest.java @@ -22,9 +22,6 @@ import org.apache.dubbo.metadata.rest.SpringRestService; import org.apache.dubbo.metadata.tools.TestService; import org.apache.dubbo.metadata.tools.TestServiceImpl; -import org.junit.jupiter.api.Test; -import org.springframework.web.bind.annotation.GetMapping; - import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; @@ -32,10 +29,14 @@ import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; import javax.ws.rs.Path; + import java.util.Iterator; import java.util.List; import java.util.Set; +import org.junit.jupiter.api.Test; +import org.springframework.web.bind.annotation.GetMapping; + import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.findAnnotation; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.findMetaAnnotation; import static org.apache.dubbo.metadata.annotation.processing.util.AnnotationUtils.getAllAnnotations; @@ -61,8 +62,7 @@ class AnnotationUtilsTest extends AbstractAnnotationProcessingTest { private TypeElement testType; @Override - protected void addCompiledClasses(Set> classesToBeCompiled) { - } + protected void addCompiledClasses(Set> classesToBeCompiled) {} @Override protected void beforeEach() { @@ -95,29 +95,38 @@ class AnnotationUtilsTest extends AbstractAnnotationProcessingTest { Iterator iterator = annotations.iterator(); assertEquals(1, annotations.size()); -// assertEquals("com.alibaba.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); - assertEquals("org.apache.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); + // assertEquals("com.alibaba.dubbo.config.annotation.Service", + // iterator.next().getAnnotationType().toString()); + assertEquals( + "org.apache.dubbo.config.annotation.Service", + iterator.next().getAnnotationType().toString()); annotations = getAnnotations(testType, Service.class); iterator = annotations.iterator(); assertEquals(1, annotations.size()); - assertEquals("org.apache.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); + assertEquals( + "org.apache.dubbo.config.annotation.Service", + iterator.next().getAnnotationType().toString()); annotations = getAnnotations(testType.asType(), Service.class); iterator = annotations.iterator(); assertEquals(1, annotations.size()); - assertEquals("org.apache.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); + assertEquals( + "org.apache.dubbo.config.annotation.Service", + iterator.next().getAnnotationType().toString()); annotations = getAnnotations(testType.asType(), Service.class.getTypeName()); iterator = annotations.iterator(); assertEquals(1, annotations.size()); - assertEquals("org.apache.dubbo.config.annotation.Service", iterator.next().getAnnotationType().toString()); + assertEquals( + "org.apache.dubbo.config.annotation.Service", + iterator.next().getAnnotationType().toString()); annotations = getAnnotations(testType, Override.class); assertEquals(0, annotations.size()); -// annotations = getAnnotations(testType, com.alibaba.dubbo.config.annotation.Service.class); -// assertEquals(1, annotations.size()); + // annotations = getAnnotations(testType, com.alibaba.dubbo.config.annotation.Service.class); + // assertEquals(1, annotations.size()); assertTrue(getAnnotations(null, (Class) null).isEmpty()); assertTrue(getAnnotations(null, (String) null).isEmpty()); @@ -146,20 +155,20 @@ class AnnotationUtilsTest extends AbstractAnnotationProcessingTest { annotations = getAllAnnotations(testType, Override.class); assertEquals(0, annotations.size()); -// annotations = getAllAnnotations(testType.asType(), com.alibaba.dubbo.config.annotation.Service.class); -// assertEquals(2, annotations.size()); + // annotations = getAllAnnotations(testType.asType(), com.alibaba.dubbo.config.annotation.Service.class); + // assertEquals(2, annotations.size()); assertTrue(getAllAnnotations((Element) null, (Class) null).isEmpty()); assertTrue(getAllAnnotations((TypeMirror) null, (String) null).isEmpty()); assertTrue(getAllAnnotations((ProcessingEnvironment) null, (Class) null).isEmpty()); - assertTrue(getAllAnnotations((ProcessingEnvironment) null, (String) null).isEmpty()); + assertTrue( + getAllAnnotations((ProcessingEnvironment) null, (String) null).isEmpty()); assertTrue(getAllAnnotations((Element) null).isEmpty()); assertTrue(getAllAnnotations((TypeMirror) null).isEmpty()); assertTrue(getAllAnnotations(processingEnv, (Class) null).isEmpty()); assertTrue(getAllAnnotations(processingEnv, (String) null).isEmpty()); - assertTrue(getAllAnnotations(testType, (Class) null).isEmpty()); assertTrue(getAllAnnotations(testType.asType(), (Class) null).isEmpty()); @@ -167,18 +176,31 @@ class AnnotationUtilsTest extends AbstractAnnotationProcessingTest { assertTrue(getAllAnnotations(testType.asType(), (String) null).isEmpty()); assertTrue(getAllAnnotations((Element) null, Service.class).isEmpty()); - assertTrue(getAllAnnotations((TypeMirror) null, Service.class.getTypeName()).isEmpty()); + assertTrue(getAllAnnotations((TypeMirror) null, Service.class.getTypeName()) + .isEmpty()); } - @Test void testFindAnnotation() { - assertEquals("org.apache.dubbo.config.annotation.Service", findAnnotation(testType, Service.class).getAnnotationType().toString()); -// assertEquals("com.alibaba.dubbo.config.annotation.Service", findAnnotation(testType, com.alibaba.dubbo.config.annotation.Service.class).getAnnotationType().toString()); - assertEquals("javax.ws.rs.Path", findAnnotation(testType, Path.class).getAnnotationType().toString()); - assertEquals("javax.ws.rs.Path", findAnnotation(testType.asType(), Path.class).getAnnotationType().toString()); - assertEquals("javax.ws.rs.Path", findAnnotation(testType.asType(), Path.class.getTypeName()).getAnnotationType().toString()); + assertEquals( + "org.apache.dubbo.config.annotation.Service", + findAnnotation(testType, Service.class).getAnnotationType().toString()); + // assertEquals("com.alibaba.dubbo.config.annotation.Service", findAnnotation(testType, + // com.alibaba.dubbo.config.annotation.Service.class).getAnnotationType().toString()); + assertEquals( + "javax.ws.rs.Path", + findAnnotation(testType, Path.class).getAnnotationType().toString()); + assertEquals( + "javax.ws.rs.Path", + findAnnotation(testType.asType(), Path.class) + .getAnnotationType() + .toString()); + assertEquals( + "javax.ws.rs.Path", + findAnnotation(testType.asType(), Path.class.getTypeName()) + .getAnnotationType() + .toString()); assertNull(findAnnotation(testType, Override.class)); assertNull(findAnnotation((Element) null, (Class) null)); @@ -195,14 +217,22 @@ class AnnotationUtilsTest extends AbstractAnnotationProcessingTest { @Test void testFindMetaAnnotation() { getAllDeclaredMethods(getType(TestService.class)).forEach(method -> { - assertEquals("javax.ws.rs.HttpMethod", findMetaAnnotation(method, "javax.ws.rs.HttpMethod").getAnnotationType().toString()); + assertEquals( + "javax.ws.rs.HttpMethod", + findMetaAnnotation(method, "javax.ws.rs.HttpMethod") + .getAnnotationType() + .toString()); }); } @Test void testGetAttribute() { - assertEquals("org.apache.dubbo.metadata.tools.TestService", getAttribute(findAnnotation(testType, Service.class), "interfaceName")); - assertEquals("org.apache.dubbo.metadata.tools.TestService", getAttribute(findAnnotation(testType, Service.class).getElementValues(), "interfaceName")); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", + getAttribute(findAnnotation(testType, Service.class), "interfaceName")); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", + getAttribute(findAnnotation(testType, Service.class).getElementValues(), "interfaceName")); assertEquals("/echo", getAttribute(findAnnotation(testType, Path.class), "value")); assertNull(getAttribute(findAnnotation(testType, Path.class), null)); @@ -212,7 +242,7 @@ class AnnotationUtilsTest extends AbstractAnnotationProcessingTest { AnnotationMirror annotation = findAnnotation(method, GetMapping.class); - assertArrayEquals(new String[]{"/param"}, (String[]) getAttribute(annotation, "value")); + assertArrayEquals(new String[] {"/param"}, (String[]) getAttribute(annotation, "value")); assertNull(getAttribute(annotation, "path")); } @@ -225,7 +255,7 @@ class AnnotationUtilsTest extends AbstractAnnotationProcessingTest { @Test void testIsAnnotationPresent() { assertTrue(isAnnotationPresent(testType, "org.apache.dubbo.config.annotation.Service")); -// assertTrue(isAnnotationPresent(testType, "com.alibaba.dubbo.config.annotation.Service")); + // assertTrue(isAnnotationPresent(testType, "com.alibaba.dubbo.config.annotation.Service")); assertTrue(isAnnotationPresent(testType, "javax.ws.rs.Path")); } } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtilsTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtilsTest.java index 74b69cc72d..d2e5f72e2a 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtilsTest.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/FieldUtilsTest.java @@ -21,12 +21,11 @@ import org.apache.dubbo.metadata.annotation.processing.model.Color; import org.apache.dubbo.metadata.annotation.processing.model.Model; import org.apache.dubbo.metadata.tools.TestServiceImpl; -import org.junit.jupiter.api.Test; - import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; + import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger; @@ -34,6 +33,8 @@ import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; + import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; @@ -62,8 +63,7 @@ class FieldUtilsTest extends AbstractAnnotationProcessingTest { private TypeElement testType; @Override - protected void addCompiledClasses(Set> classesToBeCompiled) { - } + protected void addCompiledClasses(Set> classesToBeCompiled) {} @Override protected void beforeEach() { @@ -185,7 +185,6 @@ class FieldUtilsTest extends AbstractAnnotationProcessingTest { type = getType(Color.class); assertTrue(isField(findField(type, "BLUE"), PUBLIC, STATIC, FINAL)); - assertFalse(isField(null)); assertFalse(isField(null, PUBLIC, STATIC, FINAL)); } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtilsTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtilsTest.java index 59a1b4545a..7b43a1210e 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtilsTest.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MemberUtilsTest.java @@ -20,15 +20,16 @@ import org.apache.dubbo.metadata.annotation.processing.AbstractAnnotationProcess import org.apache.dubbo.metadata.annotation.processing.model.Model; import org.apache.dubbo.metadata.tools.TestServiceImpl; -import org.junit.jupiter.api.Test; - import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; + import java.util.List; import java.util.Set; +import org.junit.jupiter.api.Test; + import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.util.ElementFilter.fieldsIn; import static javax.lang.model.util.ElementFilter.methodsIn; @@ -52,8 +53,7 @@ class MemberUtilsTest extends AbstractAnnotationProcessingTest { private TypeElement testType; @Override - protected void addCompiledClasses(Set> classesToBeCompiled) { - } + protected void addCompiledClasses(Set> classesToBeCompiled) {} @Override protected void beforeEach() { diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtilsTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtilsTest.java index dca4090df5..ee3ecc4eac 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtilsTest.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/MethodUtilsTest.java @@ -21,14 +21,15 @@ import org.apache.dubbo.metadata.annotation.processing.model.Model; import org.apache.dubbo.metadata.tools.TestService; import org.apache.dubbo.metadata.tools.TestServiceImpl; -import org.junit.jupiter.api.Test; - import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; + import java.util.List; import java.util.Set; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.findMethod; import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getAllDeclaredMethods; import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getDeclaredMethods; @@ -52,8 +53,7 @@ class MethodUtilsTest extends AbstractAnnotationProcessingTest { private TypeElement testType; @Override - protected void addCompiledClasses(Set> classesToBeCompiled) { - } + protected void addCompiledClasses(Set> classesToBeCompiled) {} @Override protected void beforeEach() { @@ -102,7 +102,8 @@ class MethodUtilsTest extends AbstractAnnotationProcessingTest { @Test void testIsPublicNonStaticMethod() { List methods = getPublicNonStaticMethods(testType, Object.class); - assertEquals(14, methods.stream().map(MethodUtils::isPublicNonStaticMethod).count()); + assertEquals( + 14, methods.stream().map(MethodUtils::isPublicNonStaticMethod).count()); } @Test @@ -190,7 +191,7 @@ class MethodUtilsTest extends AbstractAnnotationProcessingTest { @Test void testMatchParameterTypes() { ExecutableElement method = findMethod(testType, "echo", "java.lang.String"); - assertArrayEquals(new String[]{"java.lang.String"}, getMethodParameterTypes(method)); + assertArrayEquals(new String[] {"java.lang.String"}, getMethodParameterTypes(method)); assertTrue(getMethodParameterTypes(null).length == 0); } } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtilsTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtilsTest.java index 309956ba50..4cab1c49c9 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtilsTest.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/ServiceAnnotationUtilsTest.java @@ -22,12 +22,13 @@ import org.apache.dubbo.metadata.tools.GenericTestService; import org.apache.dubbo.metadata.tools.TestService; import org.apache.dubbo.metadata.tools.TestServiceImpl; -import org.junit.jupiter.api.Test; - import javax.lang.model.element.TypeElement; + import java.util.LinkedHashSet; import java.util.Set; +import org.junit.jupiter.api.Test; + import static java.util.Arrays.asList; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.DUBBO_SERVICE_ANNOTATION_TYPE; import static org.apache.dubbo.metadata.annotation.processing.util.ServiceAnnotationUtils.GROUP_ATTRIBUTE_NAME; @@ -55,14 +56,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue; class ServiceAnnotationUtilsTest extends AbstractAnnotationProcessingTest { @Override - protected void addCompiledClasses(Set> classesToBeCompiled) { - - } + protected void addCompiledClasses(Set> classesToBeCompiled) {} @Override - protected void beforeEach() { - - } + protected void beforeEach() {} @Test void testConstants() { @@ -73,7 +70,12 @@ class ServiceAnnotationUtilsTest extends AbstractAnnotationProcessingTest { assertEquals("interfaceName", INTERFACE_NAME_ATTRIBUTE_NAME); assertEquals("group", GROUP_ATTRIBUTE_NAME); assertEquals("version", VERSION_ATTRIBUTE_NAME); - assertEquals(new LinkedHashSet<>(asList("org.apache.dubbo.config.annotation.DubboService", "org.apache.dubbo.config.annotation.Service", "com.alibaba.dubbo.config.annotation.Service")), SUPPORTED_ANNOTATION_TYPES); + assertEquals( + new LinkedHashSet<>(asList( + "org.apache.dubbo.config.annotation.DubboService", + "org.apache.dubbo.config.annotation.Service", + "com.alibaba.dubbo.config.annotation.Service")), + SUPPORTED_ANNOTATION_TYPES); } @Test @@ -89,13 +91,18 @@ class ServiceAnnotationUtilsTest extends AbstractAnnotationProcessingTest { @Test void testGetAnnotation() { TypeElement type = getType(TestServiceImpl.class); - assertEquals("org.apache.dubbo.config.annotation.Service", getAnnotation(type).getAnnotationType().toString()); + assertEquals( + "org.apache.dubbo.config.annotation.Service", + getAnnotation(type).getAnnotationType().toString()); -// type = getType(GenericTestService.class); -// assertEquals("com.alibaba.dubbo.config.annotation.Service", getAnnotation(type).getAnnotationType().toString()); + // type = getType(GenericTestService.class); + // assertEquals("com.alibaba.dubbo.config.annotation.Service", + // getAnnotation(type).getAnnotationType().toString()); type = getType(DefaultTestService.class); - assertEquals("org.apache.dubbo.config.annotation.Service", getAnnotation(type).getAnnotationType().toString()); + assertEquals( + "org.apache.dubbo.config.annotation.Service", + getAnnotation(type).getAnnotationType().toString()); assertThrows(IllegalArgumentException.class, () -> getAnnotation(getType(TestService.class))); } @@ -103,13 +110,16 @@ class ServiceAnnotationUtilsTest extends AbstractAnnotationProcessingTest { @Test void testResolveServiceInterfaceName() { TypeElement type = getType(TestServiceImpl.class); - assertEquals("org.apache.dubbo.metadata.tools.TestService", resolveServiceInterfaceName(type, getAnnotation(type))); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", resolveServiceInterfaceName(type, getAnnotation(type))); type = getType(GenericTestService.class); - assertEquals("org.apache.dubbo.metadata.tools.TestService", resolveServiceInterfaceName(type, getAnnotation(type))); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", resolveServiceInterfaceName(type, getAnnotation(type))); type = getType(DefaultTestService.class); - assertEquals("org.apache.dubbo.metadata.tools.TestService", resolveServiceInterfaceName(type, getAnnotation(type))); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", resolveServiceInterfaceName(type, getAnnotation(type))); } @Test diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtilsTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtilsTest.java index 04e86e77ff..282c5c470c 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtilsTest.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/annotation/processing/util/TypeUtilsTest.java @@ -25,15 +25,13 @@ import org.apache.dubbo.metadata.tools.DefaultTestService; import org.apache.dubbo.metadata.tools.GenericTestService; import org.apache.dubbo.metadata.tools.TestServiceImpl; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; + import java.io.File; import java.lang.reflect.Type; import java.math.BigDecimal; @@ -45,6 +43,9 @@ import java.util.Iterator; import java.util.List; import java.util.Set; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + import static java.util.Arrays.asList; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.findField; import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getDeclaredFields; @@ -172,8 +173,7 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { @Test void testIsPrimitiveType() { TypeElement type = getType(PrimitiveTypeModel.class); - getDeclaredFields(type.asType()) - .stream() + getDeclaredFields(type.asType()).stream() .map(VariableElement::asType) .forEach(t -> assertTrue(isPrimitiveType(t))); @@ -217,11 +217,18 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { Set hierarchicalTypes = getHierarchicalTypes(testType.asType(), true, true, true); Iterator iterator = hierarchicalTypes.iterator(); assertEquals(8, hierarchicalTypes.size()); - assertEquals("org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.GenericTestService", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.DefaultTestService", iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestServiceImpl", + iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.GenericTestService", + iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.DefaultTestService", + iterator.next().toString()); assertEquals("java.lang.Object", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); assertEquals("java.lang.AutoCloseable", iterator.next().toString()); assertEquals("java.io.Serializable", iterator.next().toString()); assertEquals("java.util.EventListener", iterator.next().toString()); @@ -229,11 +236,18 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { hierarchicalTypes = getHierarchicalTypes(testType); iterator = hierarchicalTypes.iterator(); assertEquals(8, hierarchicalTypes.size()); - assertEquals("org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.GenericTestService", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.DefaultTestService", iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestServiceImpl", + iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.GenericTestService", + iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.DefaultTestService", + iterator.next().toString()); assertEquals("java.lang.Object", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); assertEquals("java.lang.AutoCloseable", iterator.next().toString()); assertEquals("java.io.Serializable", iterator.next().toString()); assertEquals("java.util.EventListener", iterator.next().toString()); @@ -241,10 +255,17 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { hierarchicalTypes = getHierarchicalTypes(testType.asType(), Object.class); iterator = hierarchicalTypes.iterator(); assertEquals(7, hierarchicalTypes.size()); - assertEquals("org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.GenericTestService", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.DefaultTestService", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestServiceImpl", + iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.GenericTestService", + iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.DefaultTestService", + iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); assertEquals("java.lang.AutoCloseable", iterator.next().toString()); assertEquals("java.io.Serializable", iterator.next().toString()); assertEquals("java.util.EventListener", iterator.next().toString()); @@ -252,16 +273,25 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { hierarchicalTypes = getHierarchicalTypes(testType.asType(), true, true, false); iterator = hierarchicalTypes.iterator(); assertEquals(4, hierarchicalTypes.size()); - assertEquals("org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.GenericTestService", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.DefaultTestService", iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestServiceImpl", + iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.GenericTestService", + iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.DefaultTestService", + iterator.next().toString()); assertEquals("java.lang.Object", iterator.next().toString()); hierarchicalTypes = getHierarchicalTypes(testType.asType(), true, false, true); iterator = hierarchicalTypes.iterator(); assertEquals(5, hierarchicalTypes.size()); - assertEquals("org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); - assertEquals("org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestServiceImpl", + iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); assertEquals("java.lang.AutoCloseable", iterator.next().toString()); assertEquals("java.io.Serializable", iterator.next().toString()); assertEquals("java.util.EventListener", iterator.next().toString()); @@ -269,7 +299,8 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { hierarchicalTypes = getHierarchicalTypes(testType.asType(), false, false, true); iterator = hierarchicalTypes.iterator(); assertEquals(4, hierarchicalTypes.size()); - assertEquals("org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); assertEquals("java.lang.AutoCloseable", iterator.next().toString()); assertEquals("java.io.Serializable", iterator.next().toString()); assertEquals("java.util.EventListener", iterator.next().toString()); @@ -277,7 +308,9 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { hierarchicalTypes = getHierarchicalTypes(testType.asType(), true, false, false); iterator = hierarchicalTypes.iterator(); assertEquals(1, hierarchicalTypes.size()); - assertEquals("org.apache.dubbo.metadata.tools.TestServiceImpl", iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestServiceImpl", + iterator.next().toString()); hierarchicalTypes = getHierarchicalTypes(testType.asType(), false, false, false); assertEquals(0, hierarchicalTypes.size()); @@ -286,7 +319,6 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { assertTrue(getHierarchicalTypes((TypeMirror) null).isEmpty()); } - @Test void testGetInterfaces() { TypeElement type = getType(Model.class); @@ -296,7 +328,8 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { interfaces = getInterfaces(testType.asType()); assertEquals(3, interfaces.size()); - assertEquals("org.apache.dubbo.metadata.tools.TestService", interfaces.get(0).toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", interfaces.get(0).toString()); assertEquals("java.lang.AutoCloseable", interfaces.get(1).toString()); assertEquals("java.io.Serializable", interfaces.get(2).toString()); @@ -309,7 +342,8 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { Set interfaces = getAllInterfaces(testType.asType()); assertEquals(4, interfaces.size()); Iterator iterator = interfaces.iterator(); - assertEquals("org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", iterator.next().toString()); assertEquals("java.lang.AutoCloseable", iterator.next().toString()); assertEquals("java.io.Serializable", iterator.next().toString()); assertEquals("java.util.EventListener", iterator.next().toString()); @@ -318,7 +352,9 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { assertEquals(4, interfaces.size()); Iterator allIterator = allInterfaces.iterator(); - assertEquals("org.apache.dubbo.metadata.tools.TestService", allIterator.next().toString()); + assertEquals( + "org.apache.dubbo.metadata.tools.TestService", + allIterator.next().toString()); assertEquals("java.lang.AutoCloseable", allIterator.next().toString()); assertEquals("java.io.Serializable", allIterator.next().toString()); assertEquals("java.util.EventListener", allIterator.next().toString()); @@ -416,7 +452,8 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { @Test void testOfDeclaredTypes() { - Set declaredTypes = ofDeclaredTypes(asList(getType(String.class), getType(TestServiceImpl.class), getType(Color.class))); + Set declaredTypes = + ofDeclaredTypes(asList(getType(String.class), getType(TestServiceImpl.class), getType(Color.class))); assertTrue(declaredTypes.contains(getType(String.class).asType())); assertTrue(declaredTypes.contains(getType(TestServiceImpl.class).asType())); assertTrue(declaredTypes.contains(getType(Color.class).asType())); @@ -430,7 +467,7 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { assertEquals(1, types.size()); assertEquals(ofDeclaredType(testType), types.get(0)); - types = listDeclaredTypes(asList(new Element[]{null})); + types = listDeclaredTypes(asList(new Element[] {null})); assertTrue(types.isEmpty()); } @@ -440,10 +477,11 @@ class TypeUtilsTest extends AbstractAnnotationProcessingTest { assertEquals(1, typeElements.size()); assertEquals(testType, typeElements.get(0)); - typeElements = listTypeElements(asList(types.getPrimitiveType(TypeKind.BYTE), types.getNullType(), types.getNoType(TypeKind.NONE))); + typeElements = listTypeElements( + asList(types.getPrimitiveType(TypeKind.BYTE), types.getNullType(), types.getNoType(TypeKind.NONE))); assertTrue(typeElements.isEmpty()); - typeElements = listTypeElements(asList(new TypeMirror[]{null})); + typeElements = listTypeElements(asList(new TypeMirror[] {null})); assertTrue(typeElements.isEmpty()); typeElements = listTypeElements(null); diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/RestService.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/RestService.java index 65d67ab475..7b6883780d 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/RestService.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/RestService.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.rest; - import java.util.Map; /** diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java index c2daf9b104..b475bd53da 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java @@ -18,6 +18,9 @@ package org.apache.dubbo.metadata.rest; import org.apache.dubbo.config.annotation.DubboService; +import java.util.HashMap; +import java.util.Map; + import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -27,9 +30,6 @@ import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import java.util.HashMap; -import java.util.Map; - /** * Spring MVC {@link RestService} * @@ -47,22 +47,24 @@ public class SpringRestService implements RestService { @Override @PostMapping("/params") - public String params(@RequestParam(defaultValue = "value-a") int a, @RequestParam(defaultValue = "value-b") String b) { + public String params( + @RequestParam(defaultValue = "value-a") int a, @RequestParam(defaultValue = "value-b") String b) { return null; } @Override @GetMapping("/headers") - public String headers(@RequestHeader(name = "h", defaultValue = "value-h") String header, - @RequestHeader(name = "h2", defaultValue = "value-h2") String header2, - @RequestParam(value = "v", defaultValue = "1") Integer param) { + public String headers( + @RequestHeader(name = "h", defaultValue = "value-h") String header, + @RequestHeader(name = "h2", defaultValue = "value-h2") String header2, + @RequestParam(value = "v", defaultValue = "1") Integer param) { return null; } @Override @GetMapping("/path-variables/{p1}/{p2}") - public String pathVariables(@PathVariable("p1") String path1, - @PathVariable("p2") String path2, @RequestParam("v") String param) { + public String pathVariables( + @PathVariable("p1") String path1, @PathVariable("p2") String path2, @RequestParam("v") String param) { return null; } @@ -74,8 +76,7 @@ public class SpringRestService implements RestService { @Override @PostMapping(value = "/request/body/map", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - public User requestBodyMap(@RequestBody Map data, - @RequestParam("param") String param) { + public User requestBodyMap(@RequestBody Map data, @RequestParam("param") String param) { User user = new User(); user.setId(((Integer) data.get("id")).longValue()); user.setName((String) data.get("name")); diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java index 684d76fd3b..2f7d57e557 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java @@ -27,14 +27,17 @@ import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; + import java.util.HashMap; import java.util.Map; - /** * JAX-RS {@link RestService} */ -@DubboService(version = "3.0.0", protocol = {"dubbo", "rest"}, group = "standard") +@DubboService( + version = "3.0.0", + protocol = {"dubbo", "rest"}, + group = "standard") @Path("/") public class StandardRestService implements RestService { @@ -55,8 +58,8 @@ public class StandardRestService implements RestService { @Override @Path("headers") @GET - public String headers(@HeaderParam("h") String header, - @HeaderParam("h2") String header2, @QueryParam("v") Integer param) { + public String headers( + @HeaderParam("h") String header, @HeaderParam("h2") String header2, @QueryParam("v") Integer param) { String result = header + " , " + header2 + " , " + param; return result; } @@ -64,8 +67,8 @@ public class StandardRestService implements RestService { @Override @Path("path-variables/{p1}/{p2}") @GET - public String pathVariables(@PathParam("p1") String path1, - @PathParam("p2") String path2, @QueryParam("v") String param) { + public String pathVariables( + @PathParam("p1") String path1, @PathParam("p2") String path2, @QueryParam("v") String param) { String result = path1 + " , " + path2 + " , " + param; return result; } @@ -84,8 +87,7 @@ public class StandardRestService implements RestService { @Path("request/body/map") @POST @Produces("application/json;charset=UTF-8") - public User requestBodyMap(Map data, - @QueryParam("param") String param) { + public User requestBodyMap(Map data, @QueryParam("param") String param) { User user = new User(); user.setId(((Integer) data.get("id")).longValue()); user.setName((String) data.get("name")); diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/Compiler.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/Compiler.java index e2f27dd306..5874ad0562 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/Compiler.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/Compiler.java @@ -22,6 +22,7 @@ import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.StandardLocation; import javax.tools.ToolProvider; + import java.io.File; import java.io.IOException; import java.net.URL; @@ -104,10 +105,14 @@ public class Compiler { } public boolean compile(Class... sourceClasses) { - JavaCompiler.CompilationTask task = javaCompiler.getTask(null, this.javaFileManager, null, + JavaCompiler.CompilationTask task = javaCompiler.getTask( + null, + this.javaFileManager, + null, asList("-parameters", "-Xlint:unchecked", "-nowarn", "-Xlint:deprecation"), -// null, - null, getJavaFileObjects(sourceClasses)); + // null, + null, + getJavaFileObjects(sourceClasses)); if (!processors.isEmpty()) { task.setProcessors(processors); } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/CompilerTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/CompilerTest.java index 071e1b26c8..762e297d36 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/CompilerTest.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/CompilerTest.java @@ -16,10 +16,10 @@ */ package org.apache.dubbo.metadata.tools; -import org.junit.jupiter.api.Test; - import java.io.IOException; +import org.junit.jupiter.api.Test; + /** * The Compiler test case */ @@ -28,10 +28,6 @@ class CompilerTest { @Test void testCompile() throws IOException { Compiler compiler = new Compiler(); - compiler.compile( - TestServiceImpl.class, - DefaultTestService.class, - GenericTestService.class); + compiler.compile(TestServiceImpl.class, DefaultTestService.class, GenericTestService.class); } } - diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/DefaultRestServiceTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/DefaultRestServiceTest.java index d7b73c4abc..9b020d2ca4 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/DefaultRestServiceTest.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/DefaultRestServiceTest.java @@ -22,10 +22,10 @@ import org.apache.dubbo.metadata.rest.SpringRestService; import org.apache.dubbo.metadata.rest.StandardRestService; import org.apache.dubbo.metadata.rest.User; -import org.junit.jupiter.api.Test; - import java.io.IOException; +import org.junit.jupiter.api.Test; + /** * The test case for {@link DefaultRestService} * @@ -36,7 +36,8 @@ class DefaultRestServiceTest { @Test void test() throws IOException { Compiler compiler = new Compiler(); - compiler.compile(User.class, + compiler.compile( + User.class, RestService.class, DefaultRestService.class, SpringRestService.class, diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/DefaultTestService.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/DefaultTestService.java index 85bce6924d..bb2bc21b63 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/DefaultTestService.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/DefaultTestService.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.tools; - import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.metadata.annotation.processing.model.Model; @@ -27,11 +26,7 @@ import java.util.concurrent.TimeUnit; * * @since 2.7.6 */ -@Service( - interfaceName = "org.apache.dubbo.metadata.tools.TestService", - version = "1.0.0", - group = "default" -) +@Service(interfaceName = "org.apache.dubbo.metadata.tools.TestService", version = "1.0.0", group = "default") public class DefaultTestService implements TestService { private String name; diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/GenericTestService.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/GenericTestService.java index c6f540347b..40187adfc3 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/GenericTestService.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/GenericTestService.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.tools; - import org.apache.dubbo.config.annotation.Service; import java.util.EventListener; @@ -26,10 +25,7 @@ import java.util.EventListener; * * @since 2.7.6 */ -@Service( - version = "2.0.0", - group = "generic" -) +@Service(version = "2.0.0", group = "generic") public class GenericTestService extends DefaultTestService implements TestService, EventListener { @Override public String echo(String message) { diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/RestServiceTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/RestServiceTest.java index 5f0ed6e093..b8ea68c957 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/RestServiceTest.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/RestServiceTest.java @@ -21,10 +21,10 @@ import org.apache.dubbo.metadata.rest.SpringRestService; import org.apache.dubbo.metadata.rest.StandardRestService; import org.apache.dubbo.metadata.rest.User; -import org.junit.jupiter.api.Test; - import java.io.IOException; +import org.junit.jupiter.api.Test; + /** * {@link RestService} Test * @@ -35,8 +35,6 @@ class RestServiceTest { @Test void test() throws IOException { Compiler compiler = new Compiler(); - compiler.compile(User.class, RestService.class, - StandardRestService.class, - SpringRestService.class); + compiler.compile(User.class, RestService.class, StandardRestService.class, SpringRestService.class); } } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/SpringRestServiceTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/SpringRestServiceTest.java index ce17abd592..5871c21fef 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/SpringRestServiceTest.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/SpringRestServiceTest.java @@ -20,10 +20,10 @@ import org.apache.dubbo.metadata.rest.RestService; import org.apache.dubbo.metadata.rest.SpringRestService; import org.apache.dubbo.metadata.rest.User; -import org.junit.jupiter.api.Test; - import java.io.IOException; +import org.junit.jupiter.api.Test; + /** * {@link SpringRestService} Test * diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/StandardRestServiceTest.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/StandardRestServiceTest.java index e55fdf3da4..84c8199dc7 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/StandardRestServiceTest.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/StandardRestServiceTest.java @@ -20,10 +20,10 @@ import org.apache.dubbo.metadata.rest.RestService; import org.apache.dubbo.metadata.rest.StandardRestService; import org.apache.dubbo.metadata.rest.User; -import org.junit.jupiter.api.Test; - import java.io.IOException; +import org.junit.jupiter.api.Test; + /** * The test case for {@link StandardRestService} * diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestProcessor.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestProcessor.java index cb8ae82354..42cdaa1811 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestProcessor.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestProcessor.java @@ -23,6 +23,7 @@ import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.SourceVersion; import javax.lang.model.element.TypeElement; + import java.util.Set; import static javax.lang.model.SourceVersion.latestSupported; @@ -44,7 +45,7 @@ public class TestProcessor extends AbstractProcessor { return super.processingEnv; } - public SourceVersion getSupportedSourceVersion(){ + public SourceVersion getSupportedSourceVersion() { return latestSupported(); } } diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestService.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestService.java index 83c0ef6aff..83fdf165e8 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestService.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestService.java @@ -24,6 +24,7 @@ import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; + import java.util.concurrent.TimeUnit; /** diff --git a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestServiceImpl.java b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestServiceImpl.java index 7bb1bf0c06..f9745473e5 100644 --- a/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestServiceImpl.java +++ b/dubbo-metadata/dubbo-metadata-processor/src/test/java/org/apache/dubbo/metadata/tools/TestServiceImpl.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.tools; - import org.apache.dubbo.config.annotation.Service; import java.io.Serializable; @@ -30,8 +29,7 @@ import java.io.Serializable; interfaceName = "org.apache.dubbo.metadata.tools.TestService", interfaceClass = TestService.class, version = "3.0.0", - group = "test" -) + group = "test") public class TestServiceImpl extends GenericTestService implements TestService, AutoCloseable, Serializable { @Override @@ -40,6 +38,5 @@ public class TestServiceImpl extends GenericTestService implements TestService, } @Override - public void close() throws Exception { - } + public void close() throws Exception {} } diff --git a/dubbo-metadata/dubbo-metadata-report-nacos/pom.xml b/dubbo-metadata/dubbo-metadata-report-nacos/pom.xml index 2c07e58543..9b716b33ad 100644 --- a/dubbo-metadata/dubbo-metadata-report-nacos/pom.xml +++ b/dubbo-metadata/dubbo-metadata-report-nacos/pom.xml @@ -15,29 +15,27 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - - - org.apache.dubbo - dubbo-metadata - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-metadata + ${revision} + ../pom.xml + - dubbo-metadata-report-nacos + dubbo-metadata-report-nacos - - - org.apache.dubbo - dubbo-metadata-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-configcenter-nacos - ${project.parent.version} - - + + + org.apache.dubbo + dubbo-metadata-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-configcenter-nacos + ${project.parent.version} + + diff --git a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosConfigServiceWrapper.java b/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosConfigServiceWrapper.java index 3fb52fbc70..a712526012 100644 --- a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosConfigServiceWrapper.java +++ b/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosConfigServiceWrapper.java @@ -78,5 +78,4 @@ public class NacosConfigServiceWrapper { } return data.replace(INNERCLASS_SYMBOL, INNERCLASS_COMPATIBLE_SYMBOL).replace(SLASH_CHAR, HYPHEN_CHAR); } - } diff --git a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java b/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java index c3a16d4c43..bdd5e83006 100644 --- a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java @@ -14,21 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metadata.store.nacos; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CopyOnWriteArraySet; -import java.util.concurrent.Executor; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; @@ -49,6 +36,18 @@ import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier; import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; import org.apache.dubbo.metadata.report.support.AbstractMetadataReport; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArraySet; +import java.util.concurrent.Executor; + import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.api.config.ConfigService; @@ -107,13 +106,20 @@ public class NacosMetadataReport extends AbstractMetadataReport { try { for (int i = 0; i < retryTimes + 1; i++) { tmpConfigServices = NacosFactory.createConfigService(nacosProperties); - if (!check || (UP.equals(tmpConfigServices.getServerStatus()) && testConfigService(tmpConfigServices))) { + if (!check + || (UP.equals(tmpConfigServices.getServerStatus()) && testConfigService(tmpConfigServices))) { break; } else { - logger.warn(LoggerCodeConstants.CONFIG_ERROR_NACOS, "", "", - "Failed to connect to nacos config server. " + - (i < retryTimes ? "Dubbo will try to retry in " + sleepMsBetweenRetries + ". " : "Exceed retry max times.") + - "Try times: " + (i + 1)); + logger.warn( + LoggerCodeConstants.CONFIG_ERROR_NACOS, + "", + "", + "Failed to connect to nacos config server. " + + (i < retryTimes + ? "Dubbo will try to retry in " + sleepMsBetweenRetries + ". " + : "Exceed retry max times.") + + "Try times: " + + (i + 1)); } tmpConfigServices.shutDown(); tmpConfigServices = null; @@ -129,8 +135,13 @@ public class NacosMetadataReport extends AbstractMetadataReport { } if (tmpConfigServices == null) { - logger.error(CONFIG_ERROR_NACOS, "", "", "Failed to create nacos config service client. Reason: server status check failed."); - throw new IllegalStateException("Failed to create nacos config service client. Reason: server status check failed."); + logger.error( + CONFIG_ERROR_NACOS, + "", + "", + "Failed to create nacos config service client. Reason: server status check failed."); + throw new IllegalStateException( + "Failed to create nacos config service client. Reason: server status check failed."); } return new NacosConfigServiceWrapper(tmpConfigServices); @@ -153,8 +164,7 @@ public class NacosMetadataReport extends AbstractMetadataReport { } private void setServerAddr(URL url, Properties properties) { - StringBuilder serverAddrBuilder = - new StringBuilder(url.getHost()) // Host + StringBuilder serverAddrBuilder = new StringBuilder(url.getHost()) // Host .append(':') .append(url.getPort()); // Port // Append backup parameter as other servers @@ -193,7 +203,8 @@ public class NacosMetadataReport extends AbstractMetadataReport { public void publishAppMetadata(SubscriberMetadataIdentifier identifier, MetadataInfo metadataInfo) { try { if (metadataInfo.getContent() != null) { - configService.publishConfig(identifier.getApplication(), identifier.getRevision(), metadataInfo.getContent()); + configService.publishConfig( + identifier.getApplication(), identifier.getRevision(), metadataInfo.getContent()); } } catch (NacosException e) { throw new IllegalStateException(e.getMessage(), e); @@ -325,7 +336,8 @@ public class NacosMetadataReport extends AbstractMetadataReport { } private void addCasServiceMappingListener(String serviceKey, String group, MappingListener listener) { - MappingDataListener mappingDataListener = casListenerMap.computeIfAbsent(buildListenerKey(serviceKey, group), k -> new MappingDataListener(serviceKey, group)); + MappingDataListener mappingDataListener = casListenerMap.computeIfAbsent( + buildListenerKey(serviceKey, group), k -> new MappingDataListener(serviceKey, group)); mappingDataListener.addListeners(listener); addListener(serviceKey, DEFAULT_MAPPING_GROUP, mappingDataListener); } @@ -344,7 +356,7 @@ public class NacosMetadataReport extends AbstractMetadataReport { public void addListener(String key, String group, ConfigurationListener listener) { String listenerKey = buildListenerKey(key, group); NacosConfigListener nacosConfigListener = - watchListenerMap.computeIfAbsent(listenerKey, k -> createTargetListener(key, group)); + watchListenerMap.computeIfAbsent(listenerKey, k -> createTargetListener(key, group)); nacosConfigListener.addListener(listener); try { configService.addListener(key, group, nacosConfigListener); @@ -379,16 +391,22 @@ public class NacosMetadataReport extends AbstractMetadataReport { return key + HYPHEN_CHAR + group; } - private void storeMetadata(BaseMetadataIdentifier identifier, String value) { try { - boolean publishResult = configService.publishConfig(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), group, value); + boolean publishResult = + configService.publishConfig(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), group, value); if (!publishResult) { throw new RuntimeException("publish nacos metadata failed"); } } catch (Throwable t) { - logger.error(REGISTRY_NACOS_EXCEPTION, "", "", "Failed to put " + identifier + " to nacos " + value + ", cause: " + t.getMessage(), t); - throw new RuntimeException("Failed to put " + identifier + " to nacos " + value + ", cause: " + t.getMessage(), t); + logger.error( + REGISTRY_NACOS_EXCEPTION, + "", + "", + "Failed to put " + identifier + " to nacos " + value + ", cause: " + t.getMessage(), + t); + throw new RuntimeException( + "Failed to put " + identifier + " to nacos " + value + ", cause: " + t.getMessage(), t); } } @@ -399,7 +417,12 @@ public class NacosMetadataReport extends AbstractMetadataReport { throw new RuntimeException("remove nacos metadata failed"); } } catch (Throwable t) { - logger.error(REGISTRY_NACOS_EXCEPTION, "", "", "Failed to remove " + identifier + " from nacos , cause: " + t.getMessage(), t); + logger.error( + REGISTRY_NACOS_EXCEPTION, + "", + "", + "Failed to remove " + identifier + " from nacos , cause: " + t.getMessage(), + t); throw new RuntimeException("Failed to remove " + identifier + " from nacos , cause: " + t.getMessage(), t); } } @@ -408,7 +431,12 @@ public class NacosMetadataReport extends AbstractMetadataReport { try { return configService.getConfig(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), group, 3000L); } catch (Throwable t) { - logger.error(REGISTRY_NACOS_EXCEPTION, "", "", "Failed to get " + identifier + " from nacos , cause: " + t.getMessage(), t); + logger.error( + REGISTRY_NACOS_EXCEPTION, + "", + "", + "Failed to get " + identifier + " from nacos , cause: " + t.getMessage(), + t); throw new RuntimeException("Failed to get " + identifier + " from nacos , cause: " + t.getMessage(), t); } } @@ -436,7 +464,8 @@ public class NacosMetadataReport extends AbstractMetadataReport { @Override public void innerReceive(String dataId, String group, String configInfo) { String oldValue = cacheData.get(dataId); - ConfigChangedEvent event = new ConfigChangedEvent(dataId, group, configInfo, getChangeType(configInfo, oldValue)); + ConfigChangedEvent event = + new ConfigChangedEvent(dataId, group, configInfo, getChangeType(configInfo, oldValue)); if (configInfo == null) { cacheData.remove(dataId); } else { diff --git a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java index 2cff74c9a1..a858a0a1b1 100644 --- a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java +++ b/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metadata.store.nacos; import org.apache.dubbo.common.URL; diff --git a/dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/MockConfigService.java b/dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/MockConfigService.java index a2970e282e..e362a88a5f 100644 --- a/dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/MockConfigService.java +++ b/dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/MockConfigService.java @@ -32,9 +32,7 @@ public class MockConfigService implements ConfigService { } @Override - public void addListener(String dataId, String group, Listener listener) { - - } + public void addListener(String dataId, String group, Listener listener) {} @Override public boolean publishConfig(String dataId, String group, String content) { @@ -62,9 +60,7 @@ public class MockConfigService implements ConfigService { } @Override - public void removeListener(String dataId, String group, Listener listener) { - - } + public void removeListener(String dataId, String group, Listener listener) {} @Override public String getServerStatus() { @@ -72,7 +68,5 @@ public class MockConfigService implements ConfigService { } @Override - public void shutDown() { - - } + public void shutDown() {} } diff --git a/dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/RetryTest.java b/dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/RetryTest.java index 8ff2d826f3..ce4a6b514a 100644 --- a/dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/RetryTest.java +++ b/dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/RetryTest.java @@ -16,18 +16,18 @@ */ package org.apache.dubbo.metadata.store.nacos; +import org.apache.dubbo.common.URL; + import java.util.Properties; import java.util.concurrent.atomic.AtomicInteger; -import org.apache.dubbo.common.URL; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.mockito.MockedStatic; -import org.mockito.Mockito; - import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.exception.NacosException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; import static com.alibaba.nacos.client.constant.Constants.HealthCheck.DOWN; import static com.alibaba.nacos.client.constant.Constants.HealthCheck.UP; @@ -45,12 +45,13 @@ class RetryTest { return atomicInteger.incrementAndGet() > 10 ? UP : DOWN; } }; - nacosFactoryMockedStatic.when(() -> NacosFactory.createConfigService((Properties) any())).thenReturn(mock); - + nacosFactoryMockedStatic + .when(() -> NacosFactory.createConfigService((Properties) any())) + .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848") - .addParameter("nacos.retry", 5) - .addParameter("nacos.retry-wait", 10); + .addParameter("nacos.retry", 5) + .addParameter("nacos.retry-wait", 10); Assertions.assertThrows(IllegalStateException.class, () -> new NacosMetadataReport(url)); try { @@ -60,6 +61,7 @@ class RetryTest { } } } + @Test void testDisable() { try (MockedStatic nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { @@ -69,13 +71,14 @@ class RetryTest { return DOWN; } }; - nacosFactoryMockedStatic.when(() -> NacosFactory.createConfigService((Properties) any())).thenReturn(mock); - + nacosFactoryMockedStatic + .when(() -> NacosFactory.createConfigService((Properties) any())) + .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848") - .addParameter("nacos.retry", 5) - .addParameter("nacos.retry-wait", 10) - .addParameter("nacos.check", "false"); + .addParameter("nacos.retry", 5) + .addParameter("nacos.retry-wait", 10) + .addParameter("nacos.check", "false"); try { new NacosMetadataReport(url); } catch (Throwable t) { @@ -103,12 +106,13 @@ class RetryTest { return UP; } }; - nacosFactoryMockedStatic.when(() -> NacosFactory.createConfigService((Properties) any())).thenReturn(mock); - + nacosFactoryMockedStatic + .when(() -> NacosFactory.createConfigService((Properties) any())) + .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848") - .addParameter("nacos.retry", 5) - .addParameter("nacos.retry-wait", 10); + .addParameter("nacos.retry", 5) + .addParameter("nacos.retry-wait", 10); Assertions.assertThrows(IllegalStateException.class, () -> new NacosMetadataReport(url)); try { diff --git a/dubbo-metadata/dubbo-metadata-report-redis/pom.xml b/dubbo-metadata/dubbo-metadata-report-redis/pom.xml index 708178b432..e35b79374a 100644 --- a/dubbo-metadata/dubbo-metadata-report-redis/pom.xml +++ b/dubbo-metadata/dubbo-metadata-report-redis/pom.xml @@ -1,3 +1,4 @@ + - - org.apache.dubbo - dubbo-metadata - ${revision} - - 4.0.0 + 4.0.0 + + org.apache.dubbo + dubbo-metadata + ${revision} + - dubbo-metadata-report-redis - - 3.10.0 - + dubbo-metadata-report-redis + + 3.10.0 + - - - org.apache.dubbo - dubbo-metadata-api - ${project.parent.version} - - - redis.clients - jedis - ${jedis.version} - - - com.github.codemonstur - embedded-redis - test - - - org.apache.commons - commons-lang3 - test - - + + + org.apache.dubbo + dubbo-metadata-api + ${project.parent.version} + + + redis.clients + jedis + ${jedis.version} + + + com.github.codemonstur + embedded-redis + test + + + org.apache.commons + commons-lang3 + test + + diff --git a/dubbo-metadata/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java b/dubbo-metadata/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java index 47097f2214..453aee6f48 100644 --- a/dubbo-metadata/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReport.java @@ -28,13 +28,6 @@ import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; import org.apache.dubbo.metadata.report.support.AbstractMetadataReport; import org.apache.dubbo.rpc.RpcException; -import org.apache.commons.pool2.impl.GenericObjectPoolConfig; -import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisCluster; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.JedisPoolConfig; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -42,6 +35,13 @@ import java.util.HashSet; import java.util.List; import java.util.Set; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisCluster; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; @@ -62,7 +62,6 @@ public class RedisMetadataReport extends AbstractMetadataReport { private int timeout; private String password; - public RedisMetadataReport(URL url) { super(url); timeout = url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); @@ -132,10 +131,12 @@ public class RedisMetadataReport extends AbstractMetadataReport { } private void storeMetadataInCluster(BaseMetadataIdentifier metadataIdentifier, String v) { - try (JedisCluster jedisCluster = new JedisCluster(jedisClusterNodes, timeout, timeout, 2, password, new GenericObjectPoolConfig<>())) { + try (JedisCluster jedisCluster = + new JedisCluster(jedisClusterNodes, timeout, timeout, 2, password, new GenericObjectPoolConfig<>())) { jedisCluster.set(metadataIdentifier.getIdentifierKey() + META_DATA_STORE_TAG, v); } catch (Throwable e) { - String msg = "Failed to put " + metadataIdentifier + " to redis cluster " + v + ", cause: " + e.getMessage(); + String msg = + "Failed to put " + metadataIdentifier + " to redis cluster " + v + ", cause: " + e.getMessage(); logger.error(TRANSPORT_FAILED_RESPONSE, "", "", msg, e); throw new RpcException(msg, e); } @@ -160,7 +161,8 @@ public class RedisMetadataReport extends AbstractMetadataReport { } private void deleteMetadataInCluster(BaseMetadataIdentifier metadataIdentifier) { - try (JedisCluster jedisCluster = new JedisCluster(jedisClusterNodes, timeout, timeout, 2, password, new GenericObjectPoolConfig<>())) { + try (JedisCluster jedisCluster = + new JedisCluster(jedisClusterNodes, timeout, timeout, 2, password, new GenericObjectPoolConfig<>())) { jedisCluster.del(metadataIdentifier.getIdentifierKey() + META_DATA_STORE_TAG); } catch (Throwable e) { String msg = "Failed to delete " + metadataIdentifier + " from redis cluster , cause: " + e.getMessage(); @@ -188,7 +190,8 @@ public class RedisMetadataReport extends AbstractMetadataReport { } private String getMetadataInCluster(BaseMetadataIdentifier metadataIdentifier) { - try (JedisCluster jedisCluster = new JedisCluster(jedisClusterNodes, timeout, timeout, 2, password, new GenericObjectPoolConfig<>())) { + try (JedisCluster jedisCluster = + new JedisCluster(jedisClusterNodes, timeout, timeout, 2, password, new GenericObjectPoolConfig<>())) { return jedisCluster.get(metadataIdentifier.getIdentifierKey() + META_DATA_STORE_TAG); } catch (Throwable e) { String msg = "Failed to get " + metadataIdentifier + " from redis cluster , cause: " + e.getMessage(); @@ -206,5 +209,4 @@ public class RedisMetadataReport extends AbstractMetadataReport { throw new RpcException(msg, e); } } - } diff --git a/dubbo-metadata/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportFactory.java index bd0887753f..d871877f6b 100644 --- a/dubbo-metadata/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportFactory.java +++ b/dubbo-metadata/dubbo-metadata-report-redis/src/main/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportFactory.java @@ -25,10 +25,8 @@ import org.apache.dubbo.metadata.report.support.AbstractMetadataReportFactory; */ public class RedisMetadataReportFactory extends AbstractMetadataReportFactory { - @Override public MetadataReport createMetadataReport(URL url) { return new RedisMetadataReport(url); } - } diff --git a/dubbo-metadata/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadata4TstService.java b/dubbo-metadata/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadata4TstService.java index 0a8d51ba6a..357b217545 100644 --- a/dubbo-metadata/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadata4TstService.java +++ b/dubbo-metadata/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadata4TstService.java @@ -21,7 +21,6 @@ package org.apache.dubbo.metadata.store.redis; */ public interface RedisMetadata4TstService { - int getCounter(); void printResult(String var); diff --git a/dubbo-metadata/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java b/dubbo-metadata/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java index 0306e96050..ebfce5de95 100644 --- a/dubbo-metadata/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java +++ b/dubbo-metadata/dubbo-metadata-report-redis/src/test/java/org/apache/dubbo/metadata/store/redis/RedisMetadataReportTest.java @@ -25,6 +25,11 @@ import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum; import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; import org.apache.dubbo.rpc.RpcException; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + import org.apache.commons.lang3.SystemUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; @@ -36,11 +41,6 @@ import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisDataException; import redis.embedded.RedisServer; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Random; - import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.SYNC_REPORT_KEY; @@ -48,10 +48,9 @@ import static redis.embedded.RedisServer.newRedisServer; class RedisMetadataReportTest { - private static final String - REDIS_URL_TEMPLATE = "redis://%slocalhost:%d", - REDIS_PASSWORD = "チェリー", - REDIS_URL_AUTH_SECTION = "username:" + REDIS_PASSWORD + "@"; + private static final String REDIS_URL_TEMPLATE = "redis://%slocalhost:%d", + REDIS_PASSWORD = "チェリー", + REDIS_URL_AUTH_SECTION = "username:" + REDIS_PASSWORD + "@"; RedisMetadataReport redisMetadataReport; RedisMetadataReport syncRedisMetadataReport; @@ -68,11 +67,11 @@ class RedisMetadataReportTest { try { redisPort = NetUtils.getAvailablePort(30000 + new Random().nextInt(10000)); redisServer = newRedisServer() - .port(redisPort) - // set maxheap to fix Windows error 0x70 while starting redis - .settingIf(SystemUtils.IS_OS_WINDOWS, "maxheap 128mb") - .settingIf(usesAuthentication, "requirepass " + REDIS_PASSWORD) - .build(); + .port(redisPort) + // set maxheap to fix Windows error 0x70 while starting redis + .settingIf(SystemUtils.IS_OS_WINDOWS, "maxheap 128mb") + .settingIf(usesAuthentication, "requirepass " + REDIS_PASSWORD) + .build(); this.redisServer.start(); exception = null; } catch (IOException e) { @@ -88,7 +87,8 @@ class RedisMetadataReportTest { registryUrl = newRedisUrl(usesAuthentication, redisPort); redisMetadataReport = (RedisMetadataReport) new RedisMetadataReportFactory().createMetadataReport(registryUrl); URL syncRegistryUrl = registryUrl.addParameter(SYNC_REPORT_KEY, "true"); - syncRedisMetadataReport = (RedisMetadataReport) new RedisMetadataReportFactory().createMetadataReport(syncRegistryUrl); + syncRedisMetadataReport = + (RedisMetadataReport) new RedisMetadataReportFactory().createMetadataReport(syncRegistryUrl); } private static boolean usesAuthentication(final TestInfo testInfo) { @@ -116,11 +116,13 @@ class RedisMetadataReportTest { testStoreProvider(syncRedisMetadataReport, "1.0.0.redis.md.p2", 3); } - private void testStoreProvider(RedisMetadataReport redisMetadataReport, String version, long moreTime) throws ClassNotFoundException { + private void testStoreProvider(RedisMetadataReport redisMetadataReport, String version, long moreTime) + throws ClassNotFoundException { String interfaceName = "org.apache.dubbo.metadata.store.redis.RedisMetadata4TstService"; String group = null; String application = "vic.redis.md"; - MetadataIdentifier providerMetadataIdentifier = storePrivider(redisMetadataReport, interfaceName, version, group, application); + MetadataIdentifier providerMetadataIdentifier = + storePrivider(redisMetadataReport, interfaceName, version, group, application); Jedis jedis = null; try { jedis = redisMetadataReport.pool.getResource(); @@ -155,11 +157,13 @@ class RedisMetadataReportTest { testStoreConsumer(syncRedisMetadataReport, "1.0.0.redis.md.c2", 3); } - private void testStoreConsumer(RedisMetadataReport redisMetadataReport, String version, long moreTime) throws ClassNotFoundException { + private void testStoreConsumer(RedisMetadataReport redisMetadataReport, String version, long moreTime) + throws ClassNotFoundException { String interfaceName = "org.apache.dubbo.metadata.store.redis.RedisMetadata4TstService"; String group = null; String application = "vic.redis.md"; - MetadataIdentifier consumerMetadataIdentifier = storeConsumer(redisMetadataReport, interfaceName, version, group, application); + MetadataIdentifier consumerMetadataIdentifier = + storeConsumer(redisMetadataReport, interfaceName, version, group, application); Jedis jedis = null; try { jedis = redisMetadataReport.pool.getResource(); @@ -180,13 +184,22 @@ class RedisMetadataReportTest { } } - private MetadataIdentifier storePrivider(RedisMetadataReport redisMetadataReport, String interfaceName, String version, String group, String application) throws ClassNotFoundException { - URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + "?paramTest=redisTest&version=" + version + "&application=" - + application + (group == null ? "" : "&group=" + group)); + private MetadataIdentifier storePrivider( + RedisMetadataReport redisMetadataReport, + String interfaceName, + String version, + String group, + String application) + throws ClassNotFoundException { + URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + + "?paramTest=redisTest&version=" + version + "&application=" + application + + (group == null ? "" : "&group=" + group)); - MetadataIdentifier providerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application); + MetadataIdentifier providerMetadataIdentifier = + new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application); Class interfaceClass = Class.forName(interfaceName); - FullServiceDefinition fullServiceDefinition = ServiceDefinitionBuilder.buildFullDefinition(interfaceClass, url.getParameters()); + FullServiceDefinition fullServiceDefinition = + ServiceDefinitionBuilder.buildFullDefinition(interfaceClass, url.getParameters()); redisMetadataReport.storeProviderMetadata(providerMetadataIdentifier, fullServiceDefinition); try { @@ -197,11 +210,18 @@ class RedisMetadataReportTest { return providerMetadataIdentifier; } - private MetadataIdentifier storeConsumer(RedisMetadataReport redisMetadataReport, String interfaceName, String version, String group, String application) throws ClassNotFoundException { - URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + "?version=" + version + "&application=" - + application + (group == null ? "" : "&group=" + group)); + private MetadataIdentifier storeConsumer( + RedisMetadataReport redisMetadataReport, + String interfaceName, + String version, + String group, + String application) + throws ClassNotFoundException { + URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + + "?version=" + version + "&application=" + application + (group == null ? "" : "&group=" + group)); - MetadataIdentifier consumerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, CONSUMER_SIDE, application); + MetadataIdentifier consumerMetadataIdentifier = + new MetadataIdentifier(interfaceName, version, group, CONSUMER_SIDE, application); Class interfaceClass = Class.forName(interfaceName); Map tmp = new HashMap<>(); @@ -227,8 +247,10 @@ class RedisMetadataReportTest { try { testStoreProvider(redisMetadataReport, "1.0.0.redis.md.p1", 3000); } catch (RpcException e) { - if (e.getCause() instanceof JedisConnectionException && e.getCause().getCause() instanceof JedisDataException) { - Assertions.assertEquals("ERR invalid password", e.getCause().getCause().getMessage()); + if (e.getCause() instanceof JedisConnectionException + && e.getCause().getCause() instanceof JedisDataException) { + Assertions.assertEquals( + "ERR invalid password", e.getCause().getCause().getMessage()); } else { Assertions.fail("no invalid password exception!"); } diff --git a/dubbo-metadata/dubbo-metadata-report-zookeeper/pom.xml b/dubbo-metadata/dubbo-metadata-report-zookeeper/pom.xml index 6df0fc86cc..7a344bdfdd 100644 --- a/dubbo-metadata/dubbo-metadata-report-zookeeper/pom.xml +++ b/dubbo-metadata/dubbo-metadata-report-zookeeper/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-metadata - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-metadata + ${revision} + ../pom.xml + - dubbo-metadata-report-zookeeper + dubbo-metadata-report-zookeeper - - - org.apache.dubbo - dubbo-metadata-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.parent.version} - + + + org.apache.dubbo + dubbo-metadata-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.parent.version} + - - org.apache.dubbo - dubbo-test-common - ${project.parent.version} - test - + + org.apache.dubbo + dubbo-test-common + ${project.parent.version} + test + - - org.apache.curator - curator-framework - test - - - org.apache.curator - curator-recipes - test - - - org.apache.zookeeper - zookeeper - - + + org.apache.curator + curator-framework + test + + + org.apache.curator + curator-recipes + test + + + org.apache.zookeeper + zookeeper + + - - - curator5 - - [17,) - - - - org.apache.dubbo - dubbo-remoting-zookeeper-curator5 - ${project.parent.version} - - - - + + + curator5 + + [17,) + + + + org.apache.dubbo + dubbo-remoting-zookeeper-curator5 + ${project.parent.version} + + + + diff --git a/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java b/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java index a7cfa56dbe..ce01bf0d7c 100644 --- a/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java @@ -37,8 +37,6 @@ import org.apache.dubbo.remoting.zookeeper.EventType; import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter; -import org.apache.zookeeper.data.Stat; - import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; @@ -48,6 +46,8 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import org.apache.zookeeper.data.Stat; + import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION; import static org.apache.dubbo.metadata.ServiceNameMapping.DEFAULT_MAPPING_GROUP; @@ -58,7 +58,8 @@ import static org.apache.dubbo.metadata.ServiceNameMapping.getAppNames; */ public class ZookeeperMetadataReport extends AbstractMetadataReport { - private final static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ZookeeperMetadataReport.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ZookeeperMetadataReport.class); private final String root; @@ -66,7 +67,6 @@ public class ZookeeperMetadataReport extends AbstractMetadataReport { private ConcurrentMap casListenerMap = new ConcurrentHashMap<>(); - public ZookeeperMetadataReport(URL url, ZookeeperTransporter zookeeperTransporter) { super(url); if (url.isAnyHost()) { diff --git a/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportFactory.java index c628fc858d..42270d863e 100644 --- a/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportFactory.java +++ b/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportFactory.java @@ -46,5 +46,4 @@ public class ZookeeperMetadataReportFactory extends AbstractMetadataReportFactor public MetadataReport createMetadataReport(URL url) { return new ZookeeperMetadataReport(url, zookeeperTransporter); } - } diff --git a/dubbo-metadata/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java b/dubbo-metadata/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java index 388f32d81f..cfa83a9ff0 100644 --- a/dubbo-metadata/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java +++ b/dubbo-metadata/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java @@ -32,11 +32,6 @@ import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier; import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.Arrays; import java.util.Collections; import java.util.HashMap; @@ -46,6 +41,11 @@ import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; import static org.apache.dubbo.metadata.ServiceNameMapping.DEFAULT_MAPPING_GROUP; @@ -69,7 +69,8 @@ class ZookeeperMetadataReportTest { this.registryUrl = URL.valueOf(zookeeperConnectionAddress1); zookeeperMetadataReportFactory = new ZookeeperMetadataReportFactory(ApplicationModel.defaultModel()); - this.zookeeperMetadataReport = (ZookeeperMetadataReport) zookeeperMetadataReportFactory.getMetadataReport(registryUrl); + this.zookeeperMetadataReport = + (ZookeeperMetadataReport) zookeeperMetadataReportFactory.getMetadataReport(registryUrl); } private void deletePath(MetadataIdentifier metadataIdentifier, ZookeeperMetadataReport zookeeperMetadataReport) { @@ -83,20 +84,23 @@ class ZookeeperMetadataReportTest { String version = "1.0.0.zk.md"; String group = null; String application = "vic.zk.md"; - MetadataIdentifier providerMetadataIdentifier = storePrivider(zookeeperMetadataReport, interfaceName, version, group, application); + MetadataIdentifier providerMetadataIdentifier = + storePrivider(zookeeperMetadataReport, interfaceName, version, group, application); - String fileContent = zookeeperMetadataReport.zkClient.getContent(zookeeperMetadataReport.getNodePath(providerMetadataIdentifier)); + String fileContent = zookeeperMetadataReport.zkClient.getContent( + zookeeperMetadataReport.getNodePath(providerMetadataIdentifier)); fileContent = waitSeconds(fileContent, 3500, zookeeperMetadataReport.getNodePath(providerMetadataIdentifier)); Assertions.assertNotNull(fileContent); deletePath(providerMetadataIdentifier, zookeeperMetadataReport); - fileContent = zookeeperMetadataReport.zkClient.getContent(zookeeperMetadataReport.getNodePath(providerMetadataIdentifier)); + fileContent = zookeeperMetadataReport.zkClient.getContent( + zookeeperMetadataReport.getNodePath(providerMetadataIdentifier)); fileContent = waitSeconds(fileContent, 1000, zookeeperMetadataReport.getNodePath(providerMetadataIdentifier)); Assertions.assertNull(fileContent); - providerMetadataIdentifier = storePrivider(zookeeperMetadataReport, interfaceName, version, group, application); - fileContent = zookeeperMetadataReport.zkClient.getContent(zookeeperMetadataReport.getNodePath(providerMetadataIdentifier)); + fileContent = zookeeperMetadataReport.zkClient.getContent( + zookeeperMetadataReport.getNodePath(providerMetadataIdentifier)); fileContent = waitSeconds(fileContent, 3500, zookeeperMetadataReport.getNodePath(providerMetadataIdentifier)); Assertions.assertNotNull(fileContent); @@ -104,26 +108,29 @@ class ZookeeperMetadataReportTest { Assertions.assertEquals(fullServiceDefinition.getParameters().get("paramTest"), "zkTest"); } - @Test void testConsumer() throws ClassNotFoundException, InterruptedException { String interfaceName = "org.apache.dubbo.metadata.store.zookeeper.ZookeeperMetadataReport4TstService"; String version = "1.0.0.zk.md"; String group = null; String application = "vic.zk.md"; - MetadataIdentifier consumerMetadataIdentifier = storeConsumer(zookeeperMetadataReport, interfaceName, version, group, application); + MetadataIdentifier consumerMetadataIdentifier = + storeConsumer(zookeeperMetadataReport, interfaceName, version, group, application); - String fileContent = zookeeperMetadataReport.zkClient.getContent(zookeeperMetadataReport.getNodePath(consumerMetadataIdentifier)); + String fileContent = zookeeperMetadataReport.zkClient.getContent( + zookeeperMetadataReport.getNodePath(consumerMetadataIdentifier)); fileContent = waitSeconds(fileContent, 3500, zookeeperMetadataReport.getNodePath(consumerMetadataIdentifier)); Assertions.assertNotNull(fileContent); deletePath(consumerMetadataIdentifier, zookeeperMetadataReport); - fileContent = zookeeperMetadataReport.zkClient.getContent(zookeeperMetadataReport.getNodePath(consumerMetadataIdentifier)); + fileContent = zookeeperMetadataReport.zkClient.getContent( + zookeeperMetadataReport.getNodePath(consumerMetadataIdentifier)); fileContent = waitSeconds(fileContent, 1000, zookeeperMetadataReport.getNodePath(consumerMetadataIdentifier)); Assertions.assertNull(fileContent); consumerMetadataIdentifier = storeConsumer(zookeeperMetadataReport, interfaceName, version, group, application); - fileContent = zookeeperMetadataReport.zkClient.getContent(zookeeperMetadataReport.getNodePath(consumerMetadataIdentifier)); + fileContent = zookeeperMetadataReport.zkClient.getContent( + zookeeperMetadataReport.getNodePath(consumerMetadataIdentifier)); fileContent = waitSeconds(fileContent, 3000, zookeeperMetadataReport.getNodePath(consumerMetadataIdentifier)); Assertions.assertNotNull(fileContent); Assertions.assertEquals(fileContent, "{\"paramConsumerTest\":\"zkCm\"}"); @@ -138,11 +145,12 @@ class ZookeeperMetadataReportTest { String revision = "90980"; String protocol = "xxx"; URL url = generateURL(interfaceName, version, group, application); - ServiceMetadataIdentifier serviceMetadataIdentifier = new ServiceMetadataIdentifier(interfaceName, version, - group, "provider", revision, protocol); + ServiceMetadataIdentifier serviceMetadataIdentifier = + new ServiceMetadataIdentifier(interfaceName, version, group, "provider", revision, protocol); zookeeperMetadataReport.doSaveMetadata(serviceMetadataIdentifier, url); - String fileContent = zookeeperMetadataReport.zkClient.getContent(zookeeperMetadataReport.getNodePath(serviceMetadataIdentifier)); + String fileContent = zookeeperMetadataReport.zkClient.getContent( + zookeeperMetadataReport.getNodePath(serviceMetadataIdentifier)); Assertions.assertNotNull(fileContent); Assertions.assertEquals(fileContent, URL.encode(url.toFullString())); @@ -157,17 +165,18 @@ class ZookeeperMetadataReportTest { String revision = "90980"; String protocol = "xxx"; URL url = generateURL(interfaceName, version, group, application); - ServiceMetadataIdentifier serviceMetadataIdentifier = new ServiceMetadataIdentifier(interfaceName, version, - group, "provider", revision, protocol); + ServiceMetadataIdentifier serviceMetadataIdentifier = + new ServiceMetadataIdentifier(interfaceName, version, group, "provider", revision, protocol); zookeeperMetadataReport.doSaveMetadata(serviceMetadataIdentifier, url); - String fileContent = zookeeperMetadataReport.zkClient.getContent(zookeeperMetadataReport.getNodePath(serviceMetadataIdentifier)); + String fileContent = zookeeperMetadataReport.zkClient.getContent( + zookeeperMetadataReport.getNodePath(serviceMetadataIdentifier)); Assertions.assertNotNull(fileContent); - zookeeperMetadataReport.doRemoveMetadata(serviceMetadataIdentifier); - fileContent = zookeeperMetadataReport.zkClient.getContent(zookeeperMetadataReport.getNodePath(serviceMetadataIdentifier)); + fileContent = zookeeperMetadataReport.zkClient.getContent( + zookeeperMetadataReport.getNodePath(serviceMetadataIdentifier)); Assertions.assertNull(fileContent); } @@ -180,8 +189,8 @@ class ZookeeperMetadataReportTest { String revision = "90980"; String protocol = "xxx"; URL url = generateURL(interfaceName, version, group, application); - ServiceMetadataIdentifier serviceMetadataIdentifier = new ServiceMetadataIdentifier(interfaceName, version, - group, "provider", revision, protocol); + ServiceMetadataIdentifier serviceMetadataIdentifier = + new ServiceMetadataIdentifier(interfaceName, version, group, "provider", revision, protocol); zookeeperMetadataReport.doSaveMetadata(serviceMetadataIdentifier, url); List r = zookeeperMetadataReport.doGetExportedURLs(serviceMetadataIdentifier); @@ -202,11 +211,13 @@ class ZookeeperMetadataReportTest { String revision = "90980"; String protocol = "xxx"; URL url = generateURL(interfaceName, version, group, application); - SubscriberMetadataIdentifier subscriberMetadataIdentifier = new SubscriberMetadataIdentifier(application, revision); + SubscriberMetadataIdentifier subscriberMetadataIdentifier = + new SubscriberMetadataIdentifier(application, revision); String r = JsonUtils.toJson(Arrays.asList(url.toString())); zookeeperMetadataReport.doSaveSubscriberData(subscriberMetadataIdentifier, r); - String fileContent = zookeeperMetadataReport.zkClient.getContent(zookeeperMetadataReport.getNodePath(subscriberMetadataIdentifier)); + String fileContent = zookeeperMetadataReport.zkClient.getContent( + zookeeperMetadataReport.getNodePath(subscriberMetadataIdentifier)); Assertions.assertNotNull(fileContent); @@ -222,36 +233,53 @@ class ZookeeperMetadataReportTest { String revision = "90980"; String protocol = "xxx"; URL url = generateURL(interfaceName, version, group, application); - SubscriberMetadataIdentifier subscriberMetadataIdentifier = new SubscriberMetadataIdentifier(application, revision); + SubscriberMetadataIdentifier subscriberMetadataIdentifier = + new SubscriberMetadataIdentifier(application, revision); String r = JsonUtils.toJson(Arrays.asList(url.toString())); zookeeperMetadataReport.doSaveSubscriberData(subscriberMetadataIdentifier, r); - String fileContent = zookeeperMetadataReport.zkClient.getContent(zookeeperMetadataReport.getNodePath(subscriberMetadataIdentifier)); + String fileContent = zookeeperMetadataReport.zkClient.getContent( + zookeeperMetadataReport.getNodePath(subscriberMetadataIdentifier)); Assertions.assertNotNull(fileContent); Assertions.assertEquals(fileContent, r); } + private MetadataIdentifier storePrivider( + MetadataReport zookeeperMetadataReport, + String interfaceName, + String version, + String group, + String application) + throws ClassNotFoundException, InterruptedException { + URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + + "?paramTest=zkTest&version=" + version + "&application=" + application + + (group == null ? "" : "&group=" + group)); - private MetadataIdentifier storePrivider(MetadataReport zookeeperMetadataReport, String interfaceName, String version, String group, String application) throws ClassNotFoundException, InterruptedException { - URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + "?paramTest=zkTest&version=" + version + "&application=" - + application + (group == null ? "" : "&group=" + group)); - - MetadataIdentifier providerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application); + MetadataIdentifier providerMetadataIdentifier = + new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application); Class interfaceClass = Class.forName(interfaceName); - FullServiceDefinition fullServiceDefinition = ServiceDefinitionBuilder.buildFullDefinition(interfaceClass, url.getParameters()); + FullServiceDefinition fullServiceDefinition = + ServiceDefinitionBuilder.buildFullDefinition(interfaceClass, url.getParameters()); zookeeperMetadataReport.storeProviderMetadata(providerMetadataIdentifier, fullServiceDefinition); Thread.sleep(2000); return providerMetadataIdentifier; } - private MetadataIdentifier storeConsumer(MetadataReport zookeeperMetadataReport, String interfaceName, String version, String group, String application) throws ClassNotFoundException, InterruptedException { - URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + "?version=" + version + "&application=" - + application + (group == null ? "" : "&group=" + group)); + private MetadataIdentifier storeConsumer( + MetadataReport zookeeperMetadataReport, + String interfaceName, + String version, + String group, + String application) + throws ClassNotFoundException, InterruptedException { + URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + + "?version=" + version + "&application=" + application + (group == null ? "" : "&group=" + group)); - MetadataIdentifier consumerMetadataIdentifier = new MetadataIdentifier(interfaceName, version, group, CONSUMER_SIDE, application); + MetadataIdentifier consumerMetadataIdentifier = + new MetadataIdentifier(interfaceName, version, group, CONSUMER_SIDE, application); Class interfaceClass = Class.forName(interfaceName); Map tmp = new HashMap<>(); @@ -271,13 +299,13 @@ class ZookeeperMetadataReportTest { } private URL generateURL(String interfaceName, String version, String group, String application) { - URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":8989/" + interfaceName + - "?paramTest=etcdTest&version=" + version + "&application=" - + application + (group == null ? "" : "&group=" + group)); + URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":8989/" + interfaceName + + "?paramTest=etcdTest&version=" + + version + "&application=" + + application + (group == null ? "" : "&group=" + group)); return url; } - @Test void testMapping() throws InterruptedException { String serviceKey = ZookeeperMetadataReportTest.class.getName(); @@ -285,25 +313,27 @@ class ZookeeperMetadataReportTest { String appNames = "demo1,demo2"; CountDownLatch latch = new CountDownLatch(1); - Set serviceAppMapping = zookeeperMetadataReport.getServiceAppMapping(serviceKey, new MappingListener() { - @Override - public void onEvent(MappingChangedEvent event) { - Set apps = event.getApps(); - Assertions.assertEquals(apps.size(), 2); - Assertions.assertTrue(apps.contains("demo1")); - Assertions.assertTrue(apps.contains("demo2")); - latch.countDown(); - } + Set serviceAppMapping = zookeeperMetadataReport.getServiceAppMapping( + serviceKey, + new MappingListener() { + @Override + public void onEvent(MappingChangedEvent event) { + Set apps = event.getApps(); + Assertions.assertEquals(apps.size(), 2); + Assertions.assertTrue(apps.contains("demo1")); + Assertions.assertTrue(apps.contains("demo2")); + latch.countDown(); + } - @Override - public void stop() { - - } - }, url); + @Override + public void stop() {} + }, + url); Assertions.assertTrue(serviceAppMapping.isEmpty()); ConfigItem configItem = zookeeperMetadataReport.getConfigItem(serviceKey, DEFAULT_MAPPING_GROUP); - zookeeperMetadataReport.registerServiceAppMapping(serviceKey, DEFAULT_MAPPING_GROUP, appNames, configItem.getTicket()); + zookeeperMetadataReport.registerServiceAppMapping( + serviceKey, DEFAULT_MAPPING_GROUP, appNames, configItem.getTicket()); latch.await(); } @@ -315,7 +345,8 @@ class ZookeeperMetadataReportTest { MetadataInfo metadataInfo = new MetadataInfo(appName); metadataInfo.addService(url); - SubscriberMetadataIdentifier identifier = new SubscriberMetadataIdentifier(appName, metadataInfo.calAndGetRevision()); + SubscriberMetadataIdentifier identifier = + new SubscriberMetadataIdentifier(appName, metadataInfo.calAndGetRevision()); MetadataInfo appMetadata = zookeeperMetadataReport.getAppMetadata(identifier, Collections.emptyMap()); Assertions.assertNull(appMetadata); @@ -323,6 +354,5 @@ class ZookeeperMetadataReportTest { appMetadata = zookeeperMetadataReport.getAppMetadata(identifier, Collections.emptyMap()); Assertions.assertNotNull(appMetadata); Assertions.assertEquals(appMetadata.calAndGetRevision(), metadataInfo.calAndGetRevision()); - } } diff --git a/dubbo-metadata/dubbo-metadata-rest/pom.xml b/dubbo-metadata/dubbo-metadata-rest/pom.xml index 3179070537..dfb0b3cffc 100644 --- a/dubbo-metadata/dubbo-metadata-rest/pom.xml +++ b/dubbo-metadata/dubbo-metadata-rest/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-metadata - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-metadata + ${revision} + ../pom.xml + - dubbo-metadata-rest - jar + dubbo-metadata-rest + jar - dubbo-metadata-rest - The rest metadata module of Dubbo project + dubbo-metadata-rest + The rest metadata module of Dubbo project - - - org.apache.dubbo - dubbo-metadata-api - ${project.parent.version} - + + + org.apache.dubbo + dubbo-metadata-api + ${project.parent.version} + - - - javax.ws.rs - javax.ws.rs-api - test - + + + javax.ws.rs + javax.ws.rs-api + test + - - - org.springframework - spring-web - test - + + + org.springframework + spring-web + test + - - - org.springframework - spring-context - test - + + + org.springframework + spring-context + test + - - org.springframework.cloud - spring-cloud-openfeign-core - test - - + + org.springframework.cloud + spring-cloud-openfeign-core + test + + diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AbstractAnnotatedMethodParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AbstractAnnotatedMethodParameterProcessor.java index 71d47cfda6..d7f9a32bc3 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AbstractAnnotatedMethodParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AbstractAnnotatedMethodParameterProcessor.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.rest; - import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Parameter; @@ -33,8 +32,14 @@ import static org.apache.dubbo.common.utils.ClassUtils.resolveClass; public abstract class AbstractAnnotatedMethodParameterProcessor implements AnnotatedMethodParameterProcessor { @Override - public void process(Annotation annotation, Parameter parameter, int parameterIndex, Method method, - Class serviceType, Class serviceInterfaceClass, RestMethodMetadata restMethodMetadata) { + public void process( + Annotation annotation, + Parameter parameter, + int parameterIndex, + Method method, + Class serviceType, + Class serviceInterfaceClass, + RestMethodMetadata restMethodMetadata) { String annotationValue = getAnnotationValue(annotation, parameter, parameterIndex); String defaultValue = getDefaultValue(annotation, parameter, parameterIndex); @@ -42,23 +47,30 @@ public abstract class AbstractAnnotatedMethodParameterProcessor implements Annot process(annotationValue, defaultValue, annotation, parameter, parameterIndex, method, restMethodMetadata); } - - protected void process(String annotationValue, String defaultValue, Annotation annotation, Parameter parameter, - int parameterIndex, Method method, RestMethodMetadata restMethodMetadata) { - - } - + protected void process( + String annotationValue, + String defaultValue, + Annotation annotation, + Parameter parameter, + int parameterIndex, + Method method, + RestMethodMetadata restMethodMetadata) {} @Override public Class getAnnotationClass() { return resolveClass(getAnnotationName(), getClassLoader()); } - protected void addArgInfo(Parameter parameter, int parameterIndex, - RestMethodMetadata restMethodMetadata, String annotationValue, Object defaultValue) { + protected void addArgInfo( + Parameter parameter, + int parameterIndex, + RestMethodMetadata restMethodMetadata, + String annotationValue, + Object defaultValue) { ArgInfo argInfo = ArgInfo.build(parameterIndex, parameter) - .setParamAnnotationType(getAnnotationClass()) - .setAnnotationNameAttribute(annotationValue).setDefaultValue(defaultValue); + .setParamAnnotationType(getAnnotationClass()) + .setAnnotationNameAttribute(annotationValue) + .setDefaultValue(defaultValue); restMethodMetadata.addArgInfo(argInfo); } @@ -69,5 +81,4 @@ public abstract class AbstractAnnotatedMethodParameterProcessor implements Annot protected String getDefaultValue(Annotation annotation, Parameter parameter, int parameterIndex) { return AnnotatedMethodParameterProcessor.buildDefaultValue(parameterIndex); } - } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AbstractNoAnnotatedParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AbstractNoAnnotatedParameterProcessor.java index b4975dc0c6..23cdd4cbf3 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AbstractNoAnnotatedParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AbstractNoAnnotatedParameterProcessor.java @@ -41,7 +41,7 @@ public abstract class AbstractNoAnnotatedParameterProcessor implements NoAnnotat // @RequestParam String,number param if (mediaType.equals(MediaType.ALL_VALUE)) { - // jaxrs no annotation param is from http body + // jaxrs no annotation param is from http body if (JAXRSServiceRestMetadataResolver.class.equals(restMethodMetadata.getCodeStyle())) { return true; } @@ -67,12 +67,12 @@ public abstract class AbstractNoAnnotatedParameterProcessor implements NoAnnotat return false; } - - protected void addArgInfo(Parameter parameter, int parameterIndex, - RestMethodMetadata restMethodMetadata, boolean isFormBody) { + protected void addArgInfo( + Parameter parameter, int parameterIndex, RestMethodMetadata restMethodMetadata, boolean isFormBody) { ArgInfo argInfo = ArgInfo.build(parameterIndex, parameter) - .setParamAnnotationType(resolveClass(defaultAnnotationClassName(restMethodMetadata), getClassLoader())) - .setAnnotationNameAttribute(parameter.getName()).setFormContentType(isFormBody); + .setParamAnnotationType(resolveClass(defaultAnnotationClassName(restMethodMetadata), getClassLoader())) + .setAnnotationNameAttribute(parameter.getName()) + .setFormContentType(isFormBody); restMethodMetadata.addArgInfo(argInfo); } } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AbstractServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AbstractServiceRestMetadataResolver.java index a520005e3c..8544ba564e 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AbstractServiceRestMetadataResolver.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AbstractServiceRestMetadataResolver.java @@ -93,8 +93,8 @@ public abstract class AbstractServiceRestMetadataResolver implements ServiceRest protected final boolean isServiceAnnotationPresent(Class serviceType) { if (Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isServiceClassLoaded()) { - return isAnyAnnotationPresent(serviceType, DubboService.class, Service.class, - Dubbo2CompactUtils.getServiceClass()); + return isAnyAnnotationPresent( + serviceType, DubboService.class, Service.class, Dubbo2CompactUtils.getServiceClass()); } else { return isAnyAnnotationPresent(serviceType, DubboService.class, Service.class); } @@ -118,7 +118,6 @@ public abstract class AbstractServiceRestMetadataResolver implements ServiceRest return resolve(serviceType, serviceRestMetadata); } - @Override public final ServiceRestMetadata resolve(Class serviceType, ServiceRestMetadata serviceRestMetadata) { serviceRestMetadata.setCodeStyle(this.getClass()); @@ -159,10 +158,19 @@ public abstract class AbstractServiceRestMetadataResolver implements ServiceRest // try the overrider method first Method serviceMethod = entry.getKey(); // If failed, it indicates the overrider method does not contain metadata , then try the declared method - if (!processRestMethodMetadata(serviceMethod, serviceType, serviceInterfaceClass, serviceRestMetadata::addRestMethodMetadata, serviceRestMetadata)) { + if (!processRestMethodMetadata( + serviceMethod, + serviceType, + serviceInterfaceClass, + serviceRestMetadata::addRestMethodMetadata, + serviceRestMetadata)) { Method declaredServiceMethod = entry.getValue(); - processRestMethodMetadata(declaredServiceMethod, serviceType, serviceInterfaceClass, - serviceRestMetadata::addRestMethodMetadata, serviceRestMetadata); + processRestMethodMetadata( + declaredServiceMethod, + serviceType, + serviceInterfaceClass, + serviceRestMetadata::addRestMethodMetadata, + serviceRestMetadata); } } } @@ -178,7 +186,8 @@ public abstract class AbstractServiceRestMetadataResolver implements ServiceRest protected Map resolveServiceMethodsMap(Class serviceType, Class serviceInterfaceClass) { Map serviceMethodsMap = new LinkedHashMap<>(); // exclude the public methods declared in java.lang.Object.class - List declaredServiceMethods = new ArrayList<>(getAllMethods(serviceInterfaceClass, excludedDeclaredClass(Object.class))); + List declaredServiceMethods = + new ArrayList<>(getAllMethods(serviceInterfaceClass, excludedDeclaredClass(Object.class))); // controller class if (serviceType.equals(serviceInterfaceClass)) { @@ -194,7 +203,6 @@ public abstract class AbstractServiceRestMetadataResolver implements ServiceRest List serviceMethods = new ArrayList<>(getAllMethods(serviceType, excludedDeclaredClass(Object.class))); - // sort methods sort(declaredServiceMethods, MethodComparator.INSTANCE); sort(serviceMethods, MethodComparator.INSTANCE); @@ -204,8 +212,8 @@ public abstract class AbstractServiceRestMetadataResolver implements ServiceRest if (overrides(serviceMethod, declaredServiceMethod)) { serviceMethodsMap.put(serviceMethod, declaredServiceMethod); // override method count > 1 -// // once method match ,break for decrease loop times -// break; + // // once method match ,break for decrease loop times + // break; } } } @@ -248,22 +256,26 @@ public abstract class AbstractServiceRestMetadataResolver implements ServiceRest * @param metadataToProcess {@link RestMethodMetadata} to process if present * @return if processed successfully, return true, or false */ - protected boolean processRestMethodMetadata(Method serviceMethod, Class serviceType, - Class serviceInterfaceClass, - Consumer metadataToProcess, - ServiceRestMetadata serviceRestMetadata) { + protected boolean processRestMethodMetadata( + Method serviceMethod, + Class serviceType, + Class serviceInterfaceClass, + Consumer metadataToProcess, + ServiceRestMetadata serviceRestMetadata) { if (!isRestCapableMethod(serviceMethod, serviceType, serviceInterfaceClass)) { return false; } - String requestPath = resolveRequestPath(serviceMethod, serviceType, serviceInterfaceClass); // requestPath is required + String requestPath = + resolveRequestPath(serviceMethod, serviceType, serviceInterfaceClass); // requestPath is required if (requestPath == null) { return false; } - String requestMethod = resolveRequestMethod(serviceMethod, serviceType, serviceInterfaceClass); // requestMethod is required + String requestMethod = + resolveRequestMethod(serviceMethod, serviceType, serviceInterfaceClass); // requestMethod is required if (requestMethod == null) { return false; @@ -299,7 +311,6 @@ public abstract class AbstractServiceRestMetadataResolver implements ServiceRest // process the annotated method parameters processAnnotatedMethodParameters(serviceMethod, serviceType, serviceInterfaceClass, metadata); - // Post-Process postResolveRestMethodMetadata(serviceMethod, serviceType, serviceInterfaceClass, metadata); @@ -317,8 +328,8 @@ public abstract class AbstractServiceRestMetadataResolver implements ServiceRest * @param serviceInterfaceClass The type of Dubbo Service interface * @return If capable, return true */ - protected abstract boolean isRestCapableMethod(Method serviceMethod, Class serviceType, Class - serviceInterfaceClass); + protected abstract boolean isRestCapableMethod( + Method serviceMethod, Class serviceType, Class serviceInterfaceClass); /** * Resolve the request method @@ -328,8 +339,8 @@ public abstract class AbstractServiceRestMetadataResolver implements ServiceRest * @param serviceInterfaceClass The type of Dubbo Service interface * @return if can't be resolve, return null */ - protected abstract String resolveRequestMethod(Method serviceMethod, Class serviceType, Class - serviceInterfaceClass); + protected abstract String resolveRequestMethod( + Method serviceMethod, Class serviceType, Class serviceInterfaceClass); /** * Resolve the request path @@ -339,8 +350,8 @@ public abstract class AbstractServiceRestMetadataResolver implements ServiceRest * @param serviceInterfaceClass The type of Dubbo Service interface * @return if can't be resolve, return null */ - protected abstract String resolveRequestPath(Method serviceMethod, Class serviceType, Class - serviceInterfaceClass); + protected abstract String resolveRequestPath( + Method serviceMethod, Class serviceType, Class serviceInterfaceClass); /** * Resolve the {@link MethodDefinition} @@ -351,14 +362,14 @@ public abstract class AbstractServiceRestMetadataResolver implements ServiceRest * @return if can't be resolve, return null * @see MethodDefinitionBuilder */ - protected MethodDefinition resolveMethodDefinition(Method serviceMethod, Class serviceType, - Class serviceInterfaceClass) { + protected MethodDefinition resolveMethodDefinition( + Method serviceMethod, Class serviceType, Class serviceInterfaceClass) { MethodDefinitionBuilder builder = new MethodDefinitionBuilder(); return builder.build(serviceMethod); } - private void processAnnotatedMethodParameters(Method serviceMethod, Class serviceType, - Class serviceInterfaceClass, RestMethodMetadata metadata) { + private void processAnnotatedMethodParameters( + Method serviceMethod, Class serviceType, Class serviceInterfaceClass, RestMethodMetadata metadata) { int paramCount = serviceMethod.getParameterCount(); Parameter[] parameters = serviceMethod.getParameters(); for (int i = 0; i < paramCount; i++) { @@ -369,9 +380,13 @@ public abstract class AbstractServiceRestMetadataResolver implements ServiceRest } } - protected void processAnnotatedMethodParameter(Parameter parameter, int parameterIndex, Method serviceMethod, - Class serviceType, Class serviceInterfaceClass, - RestMethodMetadata metadata) { + protected void processAnnotatedMethodParameter( + Parameter parameter, + int parameterIndex, + Method serviceMethod, + Class serviceType, + Class serviceInterfaceClass, + RestMethodMetadata metadata) { Annotation[] annotations = parameter.getAnnotations(); if (annotations == null || annotations.length == 0) { @@ -382,49 +397,55 @@ public abstract class AbstractServiceRestMetadataResolver implements ServiceRest return; } } - } for (Annotation annotation : annotations) { String annotationType = annotation.annotationType().getName(); - parameterProcessorsMap.getOrDefault(annotationType, emptyList()) - .forEach(processor -> { - processor.process(annotation, parameter, parameterIndex, serviceMethod, serviceType, - serviceInterfaceClass, metadata); - }); + parameterProcessorsMap.getOrDefault(annotationType, emptyList()).forEach(processor -> { + processor.process( + annotation, + parameter, + parameterIndex, + serviceMethod, + serviceType, + serviceInterfaceClass, + metadata); + }); } } - protected abstract void processProduces(Method serviceMethod, Class serviceType, Class - serviceInterfaceClass, - Set produces); + protected abstract void processProduces( + Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set produces); - protected abstract void processConsumes(Method serviceMethod, Class serviceType, Class - serviceInterfaceClass, - Set consumes); + protected abstract void processConsumes( + Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set consumes); - protected void postResolveRestMethodMetadata(Method serviceMethod, Class serviceType, - Class serviceInterfaceClass, RestMethodMetadata metadata) { + protected void postResolveRestMethodMetadata( + Method serviceMethod, Class serviceType, Class serviceInterfaceClass, RestMethodMetadata metadata) { // parse pathVariable index from url by annotation info PathUtil.setArgInfoSplitIndex(metadata.getRequest().getPath(), metadata.getArgInfos()); } - private static Map> loadAnnotatedMethodParameterProcessors(ApplicationModel applicationModel) { + private static Map> loadAnnotatedMethodParameterProcessors( + ApplicationModel applicationModel) { Map> parameterProcessorsMap = new LinkedHashMap<>(); - applicationModel.getExtensionLoader(AnnotatedMethodParameterProcessor.class) - .getSupportedExtensionInstances() - .forEach(processor -> { - List processors = - parameterProcessorsMap.computeIfAbsent(processor.getAnnotationName(), k -> new LinkedList<>()); - processors.add(processor); - }); + applicationModel + .getExtensionLoader(AnnotatedMethodParameterProcessor.class) + .getSupportedExtensionInstances() + .forEach(processor -> { + List processors = parameterProcessorsMap.computeIfAbsent( + processor.getAnnotationName(), k -> new LinkedList<>()); + processors.add(processor); + }); return parameterProcessorsMap; } - private static Set loadNoAnnotatedMethodParameterProcessors(ApplicationModel applicationModel) { - Set supportedExtensionInstances = applicationModel.getExtensionLoader(NoAnnotatedParameterRequestTagProcessor.class) - .getSupportedExtensionInstances(); + private static Set loadNoAnnotatedMethodParameterProcessors( + ApplicationModel applicationModel) { + Set supportedExtensionInstances = applicationModel + .getExtensionLoader(NoAnnotatedParameterRequestTagProcessor.class) + .getSupportedExtensionInstances(); return supportedExtensionInstances; } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AnnotatedMethodParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AnnotatedMethodParameterProcessor.java index 506b6cf665..b05bd4b48e 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AnnotatedMethodParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/AnnotatedMethodParameterProcessor.java @@ -21,6 +21,7 @@ import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.common.lang.Prioritized; import javax.lang.model.element.VariableElement; + import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Parameter; @@ -40,7 +41,6 @@ public interface AnnotatedMethodParameterProcessor extends Prioritized { */ String getAnnotationName(); - /** * The string presenting the annotation type * @@ -59,8 +59,14 @@ public interface AnnotatedMethodParameterProcessor extends Prioritized { * @param serviceInterfaceClass The type of Dubbo Service interface * @param restMethodMetadata {@link RestMethodMetadata the metadata is used to update} */ - void process(Annotation annotation, Parameter parameter, int parameterIndex, Method method, - Class serviceType, Class serviceInterfaceClass, RestMethodMetadata restMethodMetadata); + void process( + Annotation annotation, + Parameter parameter, + int parameterIndex, + Method method, + Class serviceType, + Class serviceInterfaceClass, + RestMethodMetadata restMethodMetadata); /** * Build the default value @@ -71,5 +77,4 @@ public interface AnnotatedMethodParameterProcessor extends Prioritized { static String buildDefaultValue(int parameterIndex) { return "{" + parameterIndex + "}"; } - } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ArgInfo.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ArgInfo.java index 9c8a96550c..dc2f7001f8 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ArgInfo.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ArgInfo.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.rest; - import java.lang.reflect.Parameter; import java.lang.reflect.Type; @@ -73,8 +72,7 @@ public class ArgInfo { this.actualType = parameter.getParameterizedType(); } - public ArgInfo() { - } + public ArgInfo() {} public int getIndex() { return index; @@ -115,7 +113,6 @@ public class ArgInfo { this.paramType = paramType; } - public int getUrlSplitIndex() { return urlSplitIndex; } @@ -165,15 +162,14 @@ public class ArgInfo { @Override public String toString() { - return "ArgInfo{" + - "index=" + index + - ", annotationNameAttribute='" + annotationNameAttribute + '\'' + - ", paramAnnotationType=" + paramAnnotationType + - ", paramType=" + paramType + - ", paramName='" + paramName + '\'' + - ", urlSplitIndex=" + urlSplitIndex + - ", defaultValue=" + defaultValue + - ", formContentType=" + formContentType + - '}'; + return "ArgInfo{" + "index=" + + index + ", annotationNameAttribute='" + + annotationNameAttribute + '\'' + ", paramAnnotationType=" + + paramAnnotationType + ", paramType=" + + paramType + ", paramName='" + + paramName + '\'' + ", urlSplitIndex=" + + urlSplitIndex + ", defaultValue=" + + defaultValue + ", formContentType=" + + formContentType + '}'; } } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/DefaultServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/DefaultServiceRestMetadataResolver.java index 926fc64d4c..41a4e1bec9 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/DefaultServiceRestMetadataResolver.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/DefaultServiceRestMetadataResolver.java @@ -21,7 +21,6 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import java.lang.reflect.Method; import java.util.Set; - /** * The default implementation {@link ServiceRestMetadataResolver} * @@ -53,12 +52,10 @@ public class DefaultServiceRestMetadataResolver extends AbstractServiceRestMetad } @Override - protected void processProduces(Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set produces) { - - } + protected void processProduces( + Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set produces) {} @Override - protected void processConsumes(Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set consumes) { - - } + protected void processConsumes( + Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set consumes) {} } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/JAXRSClassConstants.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/JAXRSClassConstants.java index 0c78eec52a..47c9149ff4 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/JAXRSClassConstants.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/JAXRSClassConstants.java @@ -25,7 +25,6 @@ public interface JAXRSClassConstants extends RestMetadataConstants.JAX_RS { */ Class PATH_ANNOTATION_CLASS = resolveClass(PATH_ANNOTATION_CLASS_NAME, getClassLoader()); - /** * The annotation class of @FormParam */ @@ -41,13 +40,11 @@ public interface JAXRSClassConstants extends RestMetadataConstants.JAX_RS { */ Class HEADER_PARAM_ANNOTATION_CLASS = resolveClass(HEADER_PARAM_ANNOTATION_CLASS_NAME, getClassLoader()); - /** * The annotation class of @MatrixParam */ Class MATRIX_PARAM_ANNOTATION_CLASS = resolveClass(MATRIX_PARAM_ANNOTATION_CLASS_NAME, getClassLoader()); - /** * The annotation class of @QueryParam */ @@ -62,6 +59,4 @@ public interface JAXRSClassConstants extends RestMetadataConstants.JAX_RS { * The annotation class of @PathParam */ Class PATH_PARAM_ANNOTATION_CLASS = resolveClass(PATH_PARAM_ANNOTATION_CLASS_NAME, getClassLoader()); - - } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ParamType.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ParamType.java index df59bf1da0..23ac6a840e 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ParamType.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ParamType.java @@ -24,37 +24,44 @@ import java.util.ArrayList; import java.util.List; public enum ParamType { - HEADER(addSupportTypes(JAXRSClassConstants.HEADER_PARAM_ANNOTATION_CLASS, - SpringMvcClassConstants.REQUEST_HEADER_ANNOTATION_CLASS)), + HEADER(addSupportTypes( + JAXRSClassConstants.HEADER_PARAM_ANNOTATION_CLASS, + SpringMvcClassConstants.REQUEST_HEADER_ANNOTATION_CLASS)), - PARAM(addSupportTypes(JAXRSClassConstants.QUERY_PARAM_ANNOTATION_CLASS, - SpringMvcClassConstants.REQUEST_PARAM_ANNOTATION_CLASS, ParamTag.class)), + PARAM(addSupportTypes( + JAXRSClassConstants.QUERY_PARAM_ANNOTATION_CLASS, + SpringMvcClassConstants.REQUEST_PARAM_ANNOTATION_CLASS, + ParamTag.class)), BODY(addSupportTypes( - JAXRSClassConstants.REST_EASY_BODY_ANNOTATION_CLASS, - SpringMvcClassConstants.REQUEST_BODY_ANNOTATION_CLASS, BodyTag.class)), + JAXRSClassConstants.REST_EASY_BODY_ANNOTATION_CLASS, + SpringMvcClassConstants.REQUEST_BODY_ANNOTATION_CLASS, + BodyTag.class)), - PATH(addSupportTypes(JAXRSClassConstants.PATH_PARAM_ANNOTATION_CLASS, - SpringMvcClassConstants.PATH_VARIABLE_ANNOTATION_CLASS)), + PATH(addSupportTypes( + JAXRSClassConstants.PATH_PARAM_ANNOTATION_CLASS, SpringMvcClassConstants.PATH_VARIABLE_ANNOTATION_CLASS)), - FORM(addSupportTypes(JAXRSClassConstants.FORM_PARAM_ANNOTATION_CLASS, JAXRSClassConstants.FORM_BODY_ANNOTATION_CLASS, - SpringMvcClassConstants.REQUEST_BODY_ANNOTATION_CLASS)), + FORM(addSupportTypes( + JAXRSClassConstants.FORM_PARAM_ANNOTATION_CLASS, + JAXRSClassConstants.FORM_BODY_ANNOTATION_CLASS, + SpringMvcClassConstants.REQUEST_BODY_ANNOTATION_CLASS)), PROVIDER_BODY(addSupportTypes( - JAXRSClassConstants.REST_EASY_BODY_ANNOTATION_CLASS, JAXRSClassConstants.FORM_PARAM_ANNOTATION_CLASS, - SpringMvcClassConstants.REQUEST_BODY_ANNOTATION_CLASS, BodyTag.class, JAXRSClassConstants.FORM_BODY_ANNOTATION_CLASS)), + JAXRSClassConstants.REST_EASY_BODY_ANNOTATION_CLASS, + JAXRSClassConstants.FORM_PARAM_ANNOTATION_CLASS, + SpringMvcClassConstants.REQUEST_BODY_ANNOTATION_CLASS, + BodyTag.class, + JAXRSClassConstants.FORM_BODY_ANNOTATION_CLASS)), PROVIDER_NO_ANNOTATION(addSupportTypes(NoAnnotationTag.class)), EMPTY(addSupportTypes()); private List annotationClasses; - ParamType(List annotationClasses) { this.annotationClasses = annotationClasses; } - public boolean supportAnno(Class anno) { if (anno == null) { return false; @@ -82,9 +89,5 @@ public enum ParamType { } return types; - - } - - } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/PathMatcher.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/PathMatcher.java index e08e0733b2..2e526d19a6 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/PathMatcher.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/PathMatcher.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.rest; - import java.lang.reflect.Method; import java.util.Arrays; import java.util.Objects; @@ -27,9 +26,9 @@ import java.util.Objects; public class PathMatcher { private static final String SEPARATOR = "/"; private String path; - private String version;// service version - private String group;// service group - private Integer port;// service port + private String version; // service version + private String group; // service group + private Integer port; // service port private String[] pathSplits; private boolean hasPathVariable; private String contextPath; @@ -42,7 +41,6 @@ public class PathMatcher { // service method private Method method; - public PathMatcher(String path) { this(path, null, null, null); } @@ -97,19 +95,17 @@ public class PathMatcher { public void setContextPath(String contextPath) { - contextPath = contextPathFormat(contextPath); - this.contextPath = contextPath; setPath(contextPath + path); dealPathVariable(path); - } - public static PathMatcher getInvokeCreatePathMatcher(String path, String version, String group, Integer port, String method) { + public static PathMatcher getInvokeCreatePathMatcher( + String path, String version, String group, Integer port, String method) { return new PathMatcher(path, version, group, port, method).compareHttpMethod(false); } @@ -118,7 +114,8 @@ public class PathMatcher { } public static PathMatcher convertPathMatcher(PathMatcher pathMatcher) { - return getInvokeCreatePathMatcher(pathMatcher.path, pathMatcher.version, pathMatcher.group, pathMatcher.port, pathMatcher.httpMethod); + return getInvokeCreatePathMatcher( + pathMatcher.path, pathMatcher.version, pathMatcher.group, pathMatcher.port, pathMatcher.httpMethod); } public boolean hasPathVariable() { @@ -161,16 +158,16 @@ public class PathMatcher { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PathMatcher that = (PathMatcher) o; - return serviceMethodEqual(that, this) - || pathMatch(that); + return serviceMethodEqual(that, this) || pathMatch(that); } private boolean pathMatch(PathMatcher that) { return (!that.needCompareServiceMethod && !needCompareServiceMethod) // no need service method compare - && pathEqual(that) // path compare - && Objects.equals(version, that.version) // service version compare - && httpMethodMatch(that) // http method compare - && Objects.equals(group, that.group) && Objects.equals(port, that.port); + && pathEqual(that) // path compare + && Objects.equals(version, that.version) // service version compare + && httpMethodMatch(that) // http method compare + && Objects.equals(group, that.group) + && Objects.equals(port, that.port); } /** @@ -180,17 +177,19 @@ public class PathMatcher { * @return */ private boolean httpMethodMatch(PathMatcher that) { - return !that.needCompareHttpMethod || !this.needCompareHttpMethod ? true : Objects.equals(this.httpMethod, that.httpMethod); + return !that.needCompareHttpMethod || !this.needCompareHttpMethod + ? true + : Objects.equals(this.httpMethod, that.httpMethod); } private boolean serviceMethodEqual(PathMatcher thatPathMatcher, PathMatcher thisPathMatcher) { Method thatMethod = thatPathMatcher.method; Method thisMethod = thisPathMatcher.method; return thatMethod != null - && thisMethod != null - && (thatPathMatcher.needCompareServiceMethod || thisPathMatcher.needCompareServiceMethod) - && thisMethod.getName().equals(thatMethod.getName()) - && Arrays.equals(thisMethod.getParameterTypes(), thatMethod.getParameterTypes()); + && thisMethod != null + && (thatPathMatcher.needCompareServiceMethod || thisPathMatcher.needCompareServiceMethod) + && thisMethod.getName().equals(thatMethod.getName()) + && Arrays.equals(thisMethod.getParameterTypes(), thatMethod.getParameterTypes()); } @Override @@ -204,7 +203,6 @@ public class PathMatcher { return false; } - // no place hold if (!pathMatcher.hasPathVariable) { return this.path.equals(pathMatcher.path); @@ -213,7 +211,6 @@ public class PathMatcher { String[] pathSplits = pathMatcher.pathSplits; String[] thisPathSplits = this.pathSplits; - if (thisPathSplits.length != pathSplits.length) { return false; } @@ -232,7 +229,6 @@ public class PathMatcher { } return true; - } private boolean placeHoldCompare(String pathSplit, String pathToCompare) { @@ -257,15 +253,12 @@ public class PathMatcher { return pathSplit.startsWith("{") && pathSplit.endsWith("}"); } - private String contextPathFormat(String contextPath) { - if (contextPath == null || contextPath.equals(SEPARATOR) || contextPath.length() == 0) { return ""; } - return pathFormat(contextPath); } @@ -277,17 +270,15 @@ public class PathMatcher { } } - @Override public String toString() { - return "PathMatcher{" + - "path='" + path + '\'' + - ", version='" + version + '\'' + - ", group='" + group + '\'' + - ", port=" + port + - ", hasPathVariable=" + hasPathVariable + - ", contextPath='" + contextPath + '\'' + - ", httpMethod='" + httpMethod + '\'' + - '}'; + return "PathMatcher{" + "path='" + + path + '\'' + ", version='" + + version + '\'' + ", group='" + + group + '\'' + ", port=" + + port + ", hasPathVariable=" + + hasPathVariable + ", contextPath='" + + contextPath + '\'' + ", httpMethod='" + + httpMethod + '\'' + '}'; } } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/PathUtil.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/PathUtil.java index f105461268..90cc7cd8fa 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/PathUtil.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/PathUtil.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.rest; - import org.apache.dubbo.metadata.MetadataConstants; import java.util.ArrayList; @@ -55,12 +54,10 @@ public class PathUtil { } } - for (ArgInfo pathArgInfo : pathArgInfos) { strings.set(pathArgInfo.getUrlSplitIndex(), String.valueOf(args.get(pathArgInfo.getIndex()))); } - String pat = SEPARATOR; for (String string : strings) { @@ -77,10 +74,8 @@ public class PathUtil { } return pat; - } - /** * parse pathVariable index from url by annotation info * @@ -107,7 +102,6 @@ public class PathUtil { } } } - } public static class PathPair { @@ -116,7 +110,6 @@ public class PathUtil { ArgInfo argInfo; - public PathPair(ArgInfo argInfo) { this.argInfo = argInfo; this.value = argInfo.getAnnotationNameAttribute(); @@ -135,11 +128,10 @@ public class PathUtil { } public boolean match(String value) { - return getPatten().equals(value)// for : {id} - || (value.startsWith(getLeftPatten()) && value.endsWith(getRightPatten()));// for : {id: \d+} + return getPatten().equals(value) // for : {id} + || (value.startsWith(getLeftPatten()) && value.endsWith(getRightPatten())); // for : {id: \d+} } - public String getValue() { return value; } @@ -153,5 +145,3 @@ public class PathUtil { } } } - - diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/RequestMetadata.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/RequestMetadata.java index e7f825d26a..bdac2575e4 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/RequestMetadata.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/RequestMetadata.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.rest; - import org.apache.dubbo.common.utils.CollectionUtils; import java.io.Serializable; @@ -56,12 +55,10 @@ public class RequestMetadata implements Serializable { private Set produces = new LinkedHashSet<>(); - /** * Default Constructor */ - public RequestMetadata() { - } + public RequestMetadata() {} public String getMethod() { return method; @@ -81,7 +78,6 @@ public class RequestMetadata implements Serializable { if (!path.startsWith(SLASH)) { this.path = SLASH + path; } - } public Map> getParams() { @@ -100,8 +96,8 @@ public class RequestMetadata implements Serializable { values.add(value); } - private static > void addAll(Map> multiValueMap, - Map source) { + private static > void addAll( + Map> multiValueMap, Map source) { for (Map.Entry entry : source.entrySet()) { String key = entry.getKey(); for (String value : entry.getValue()) { @@ -155,13 +151,13 @@ public class RequestMetadata implements Serializable { return new HashSet<>(headers.keySet()); } -// public List getConsumeMediaTypes() { -// return toMediaTypes(consumes); -// } -// -// public List getProduceMediaTypes() { -// return toMediaTypes(produces); -// } + // public List getConsumeMediaTypes() { + // return toMediaTypes(consumes); + // } + // + // public List getProduceMediaTypes() { + // return toMediaTypes(produces); + // } public String getParameter(String name) { return getFirst(params, name); @@ -192,8 +188,8 @@ public class RequestMetadata implements Serializable { // Add all headers addAll(httpHeaders, headers); // Handles "Content-Type" and "Accept" headers if present -// mediaTypes(httpHeaders, HttpHeaders.CONTENT_TYPE, this.consumes); -// mediaTypes(httpHeaders, HttpHeaders.ACCEPT, this.produces); + // mediaTypes(httpHeaders, HttpHeaders.CONTENT_TYPE, this.consumes); + // mediaTypes(httpHeaders, HttpHeaders.ACCEPT, this.produces); this.headers.putAll(httpHeaders); } return this; @@ -220,26 +216,25 @@ public class RequestMetadata implements Serializable { } RequestMetadata that = (RequestMetadata) o; return Objects.equals(method, that.method) - && Objects.equals(path, that.path) - && Objects.equals(consumes, that.consumes) - && Objects.equals(produces, that.produces) && - // Metadata should not compare the values - Objects.equals(getParamNames(), that.getParamNames()) - && Objects.equals(getHeaderNames(), that.getHeaderNames()); - + && Objects.equals(path, that.path) + && Objects.equals(consumes, that.consumes) + && Objects.equals(produces, that.produces) + && + // Metadata should not compare the values + Objects.equals(getParamNames(), that.getParamNames()) + && Objects.equals(getHeaderNames(), that.getHeaderNames()); } @Override public int hashCode() { // The values of metadata should not use for the hashCode() method - return Objects.hash(method, path, consumes, produces, getParamNames(), - getHeaderNames()); + return Objects.hash(method, path, consumes, produces, getParamNames(), getHeaderNames()); } @Override public String toString() { return "RequestMetadata{" + "method='" + method + '\'' + ", path='" + path + '\'' - + ", params=" + params + ", headers=" + headers + ", consumes=" + consumes - + ", produces=" + produces + '}'; + + ", params=" + params + ", headers=" + headers + ", consumes=" + consumes + + ", produces=" + produces + '}'; } } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/RestMetadataConstants.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/RestMetadataConstants.java index 7e2f51f781..97bca97595 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/RestMetadataConstants.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/RestMetadataConstants.java @@ -149,14 +149,16 @@ public interface RestMetadataConstants { * * @since 2.7.9 */ - Class CONTROLLER_ANNOTATION_CLASS = (Class) resolveClass(CONTROLLER_ANNOTATION_CLASS_NAME, getClassLoader()); + Class CONTROLLER_ANNOTATION_CLASS = + (Class) resolveClass(CONTROLLER_ANNOTATION_CLASS_NAME, getClassLoader()); /** * The class of @RequestMapping * * @since 2.7.9 */ - Class REQUEST_MAPPING_ANNOTATION_CLASS = (Class) resolveClass(REQUEST_MAPPING_ANNOTATION_CLASS_NAME, getClassLoader()); + Class REQUEST_MAPPING_ANNOTATION_CLASS = + (Class) resolveClass(REQUEST_MAPPING_ANNOTATION_CLASS_NAME, getClassLoader()); /** * The annotation class name of AnnotatedElementUtils @@ -172,7 +174,7 @@ public interface RestMetadataConstants { */ Class ANNOTATED_ELEMENT_UTILS_CLASS = resolveClass(ANNOTATED_ELEMENT_UTILS_CLASS_NAME, getClassLoader()); - Class FEIGN_CLIENT_CLASS = (Class) resolveClass(FEIGN_CLIENT_CLASS_NAME, getClassLoader()); - + Class FEIGN_CLIENT_CLASS = + (Class) resolveClass(FEIGN_CLIENT_CLASS_NAME, getClassLoader()); } } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/RestMethodMetadata.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/RestMethodMetadata.java index 59ebdec63f..e820b5fa75 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/RestMethodMetadata.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/RestMethodMetadata.java @@ -183,7 +183,6 @@ public class RestMethodMetadata implements Serializable { getArgInfos().add(argInfo); } - public Method getReflectMethod() { return reflectMethod; } @@ -213,36 +212,43 @@ public class RestMethodMetadata implements Serializable { return false; } RestMethodMetadata that = (RestMethodMetadata) o; - return Objects.equals(getMethod(), that.getMethod()) && - Objects.equals(getRequest(), that.getRequest()) && - Objects.equals(getUrlIndex(), that.getUrlIndex()) && - Objects.equals(getBodyIndex(), that.getBodyIndex()) && - Objects.equals(getHeaderMapIndex(), that.getHeaderMapIndex()) && - Objects.equals(getBodyType(), that.getBodyType()) && - Objects.equals(getFormParams(), that.getFormParams()) && - Objects.equals(getIndexToEncoded(), that.getIndexToEncoded()); + return Objects.equals(getMethod(), that.getMethod()) + && Objects.equals(getRequest(), that.getRequest()) + && Objects.equals(getUrlIndex(), that.getUrlIndex()) + && Objects.equals(getBodyIndex(), that.getBodyIndex()) + && Objects.equals(getHeaderMapIndex(), that.getHeaderMapIndex()) + && Objects.equals(getBodyType(), that.getBodyType()) + && Objects.equals(getFormParams(), that.getFormParams()) + && Objects.equals(getIndexToEncoded(), that.getIndexToEncoded()); } @Override public int hashCode() { - return Objects.hash(getMethod(), getRequest(), getUrlIndex(), getBodyIndex(), getHeaderMapIndex(), getBodyType(), getFormParams(), getIndexToEncoded()); + return Objects.hash( + getMethod(), + getRequest(), + getUrlIndex(), + getBodyIndex(), + getHeaderMapIndex(), + getBodyType(), + getFormParams(), + getIndexToEncoded()); } @Override public String toString() { - return "RestMethodMetadata{" + - "method=" + method + - ", request=" + request + - ", urlIndex=" + urlIndex + - ", bodyIndex=" + bodyIndex + - ", headerMapIndex=" + headerMapIndex + - ", bodyType='" + bodyType + '\'' + - ", indexToName=" + indexToName + - ", formParams=" + formParams + - ", indexToEncoded=" + indexToEncoded + - ", argInfos=" + argInfos + - ", reflectMethod=" + reflectMethod + - ", codeStyle=" + codeStyle + - '}'; + return "RestMethodMetadata{" + "method=" + + method + ", request=" + + request + ", urlIndex=" + + urlIndex + ", bodyIndex=" + + bodyIndex + ", headerMapIndex=" + + headerMapIndex + ", bodyType='" + + bodyType + '\'' + ", indexToName=" + + indexToName + ", formParams=" + + formParams + ", indexToEncoded=" + + indexToEncoded + ", argInfos=" + + argInfos + ", reflectMethod=" + + reflectMethod + ", codeStyle=" + + codeStyle + '}'; } } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadata.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadata.java index b384bbd7d5..f18da31097 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadata.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadata.java @@ -66,8 +66,7 @@ public class ServiceRestMetadata implements Serializable { this.consumer = consumer; } - public ServiceRestMetadata() { - } + public ServiceRestMetadata() {} public ServiceRestMetadata(String serviceInterface, String version, String group) { this(serviceInterface, version, group, false); @@ -109,15 +108,18 @@ public class ServiceRestMetadata implements Serializable { } public void addRestMethodMetadata(RestMethodMetadata restMethodMetadata) { - PathMatcher pathMather = new PathMatcher(restMethodMetadata.getRequest().getPath(), - this.getVersion(), this.getGroup(), this.getPort(),restMethodMetadata.getRequest().getMethod()); + PathMatcher pathMather = new PathMatcher( + restMethodMetadata.getRequest().getPath(), + this.getVersion(), + this.getGroup(), + this.getPort(), + restMethodMetadata.getRequest().getMethod()); pathMather.setMethod(restMethodMetadata.getReflectMethod()); addPathToServiceMap(pathMather, restMethodMetadata); addMethodToServiceMap(restMethodMetadata); getMeta().add(restMethodMetadata); } - public Map getPathContainPathVariableToServiceMap() { return pathToServiceMapContainPathVariable; } @@ -133,29 +135,29 @@ public class ServiceRestMetadata implements Serializable { } else { doublePathCheck(pathToServiceMapUnContainPathVariable, pathMather, restMethodMetadata, false); } - - } - private void doublePathCheck(Map pathMatcherRestMethodMetadataMap, - PathMatcher pathMather, - RestMethodMetadata restMethodMetadata, boolean containPathVariable) { + private void doublePathCheck( + Map pathMatcherRestMethodMetadataMap, + PathMatcher pathMather, + RestMethodMetadata restMethodMetadata, + boolean containPathVariable) { if (pathMatcherRestMethodMetadataMap.containsKey(pathMather)) { if (containPathVariable) { - throw new IllegalArgumentException("dubbo rest metadata resolve double path error,and contain path variable is: " - + pathMather + ", rest method metadata is: " + restMethodMetadata); + throw new IllegalArgumentException( + "dubbo rest metadata resolve double path error,and contain path variable is: " + pathMather + + ", rest method metadata is: " + restMethodMetadata); } else { - throw new IllegalArgumentException("dubbo rest metadata resolve double path error,and do not contain path variable is: " - + pathMather + ", rest method metadata is: " + restMethodMetadata); + throw new IllegalArgumentException( + "dubbo rest metadata resolve double path error,and do not contain path variable is: " + + pathMather + ", rest method metadata is: " + restMethodMetadata); } } pathMatcherRestMethodMetadataMap.put(pathMather, restMethodMetadata); - } - public Integer getPort() { return port; } @@ -189,8 +191,12 @@ public class ServiceRestMetadata implements Serializable { this.methodToServiceMap = new HashMap<>(); } - this.methodToServiceMap.computeIfAbsent(restMethodMetadata.getReflectMethod().getName(), k -> new HashMap<>()) - .put(ParameterTypesComparator.getInstance(restMethodMetadata.getReflectMethod().getParameterTypes()), restMethodMetadata); + this.methodToServiceMap + .computeIfAbsent(restMethodMetadata.getReflectMethod().getName(), k -> new HashMap<>()) + .put( + ParameterTypesComparator.getInstance( + restMethodMetadata.getReflectMethod().getParameterTypes()), + restMethodMetadata); } public Class getCodeStyle() { @@ -218,11 +224,11 @@ public class ServiceRestMetadata implements Serializable { return false; } ServiceRestMetadata that = (ServiceRestMetadata) o; - return Objects.equals(getServiceInterface(), that.getServiceInterface()) && - Objects.equals(getVersion(), that.getVersion()) && - Objects.equals(getGroup(), that.getGroup()) && - Objects.equals(getMeta(), that.getMeta()) && - Objects.equals(getPort(), that.getPort()); + return Objects.equals(getServiceInterface(), that.getServiceInterface()) + && Objects.equals(getVersion(), that.getVersion()) + && Objects.equals(getGroup(), that.getGroup()) + && Objects.equals(getMeta(), that.getMeta()) + && Objects.equals(getPort(), that.getPort()); } @Override diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadataReader.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadataReader.java index de5207a9dd..6a590260c3 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadataReader.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadataReader.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.rest; - import org.apache.dubbo.common.extension.SPI; import java.util.List; diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadataResolver.java index 492dc942fb..b36ba51dec 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadataResolver.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/ServiceRestMetadataResolver.java @@ -36,7 +36,7 @@ public interface ServiceRestMetadataResolver { */ boolean supports(Class serviceType); - boolean supports(Class serviceType,boolean consumer); + boolean supports(Class serviceType, boolean consumer); /** * Resolve the {@link ServiceRestMetadata REST metadata} from the specified diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/SpringMvcClassConstants.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/SpringMvcClassConstants.java index bd3cabf4db..d16ba21523 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/SpringMvcClassConstants.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/SpringMvcClassConstants.java @@ -25,27 +25,23 @@ public interface SpringMvcClassConstants extends RestMetadataConstants.SPRING_MV */ Class REQUEST_MAPPING_ANNOTATION_CLASS = resolveClass(REQUEST_MAPPING_ANNOTATION_CLASS_NAME, getClassLoader()); - /** * The annotation class of @RequestHeader */ Class REQUEST_HEADER_ANNOTATION_CLASS = resolveClass(REQUEST_HEADER_ANNOTATION_CLASS_NAME, getClassLoader()); - /** * The annotation class of @RequestParam */ Class REQUEST_PARAM_ANNOTATION_CLASS = resolveClass(REQUEST_PARAM_ANNOTATION_CLASS_NAME, getClassLoader()); - /** * The annotation class of @RequestBody */ Class REQUEST_BODY_ANNOTATION_CLASS = resolveClass(REQUEST_BODY_ANNOTATION_CLASS_NAME, getClassLoader()); - /** * The annotation class of @RequestBody */ - Class PATH_VARIABLE_ANNOTATION_CLASS= resolveClass(PATH_VARIABLE_ANNOTATION_CLASS_NAME, getClassLoader()); + Class PATH_VARIABLE_ANNOTATION_CLASS = resolveClass(PATH_VARIABLE_ANNOTATION_CLASS_NAME, getClassLoader()); } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/BodyParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/BodyParameterProcessor.java index 9889553470..2ee067091b 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/BodyParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/BodyParameterProcessor.java @@ -40,13 +40,15 @@ public class BodyParameterProcessor extends AbstractAnnotatedMethodParameterProc } @Override - public void process(Annotation annotation, Parameter parameter, int parameterIndex, Method method, Class serviceType, Class serviceInterfaceClass, RestMethodMetadata restMethodMetadata) { - ArgInfo argInfo = ArgInfo. - build(parameterIndex, parameter). - setParamAnnotationType(getAnnotationClass()); + public void process( + Annotation annotation, + Parameter parameter, + int parameterIndex, + Method method, + Class serviceType, + Class serviceInterfaceClass, + RestMethodMetadata restMethodMetadata) { + ArgInfo argInfo = ArgInfo.build(parameterIndex, parameter).setParamAnnotationType(getAnnotationClass()); restMethodMetadata.addArgInfo(argInfo); - } - - } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/DefaultValueParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/DefaultValueParameterProcessor.java index 475fbe9cd1..5b3a4ee2a2 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/DefaultValueParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/DefaultValueParameterProcessor.java @@ -29,7 +29,6 @@ import java.util.Map; import static org.apache.dubbo.metadata.rest.RestMetadataConstants.JAX_RS.DEFAULT_VALUE_ANNOTATION_CLASS_NAME; - /** * The {@link AnnotatedMethodParameterProcessor} implementation for JAX-RS's @DefaultValue * * @@ -44,8 +43,14 @@ public class DefaultValueParameterProcessor extends AbstractAnnotatedMethodParam } @Override - protected void process(String annotationValue, String defaultValue, Annotation annotation, Parameter parameter, - int parameterIndex, Method method, RestMethodMetadata restMethodMetadata) { + protected void process( + String annotationValue, + String defaultValue, + Annotation annotation, + Parameter parameter, + int parameterIndex, + Method method, + RestMethodMetadata restMethodMetadata) { RequestMetadata requestMetadata = restMethodMetadata.getRequest(); // process the request parameters diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/FormBodyParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/FormBodyParameterProcessor.java index 057623acf2..26483885bf 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/FormBodyParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/FormBodyParameterProcessor.java @@ -40,15 +40,21 @@ public class FormBodyParameterProcessor extends AbstractAnnotatedMethodParameter } @Override - public void process(Annotation annotation, Parameter parameter, int parameterIndex, Method method, Class serviceType, Class serviceInterfaceClass, RestMethodMetadata restMethodMetadata) { - super.process(annotation, parameter, parameterIndex, method, serviceType, serviceInterfaceClass, restMethodMetadata); + public void process( + Annotation annotation, + Parameter parameter, + int parameterIndex, + Method method, + Class serviceType, + Class serviceInterfaceClass, + RestMethodMetadata restMethodMetadata) { + super.process( + annotation, parameter, parameterIndex, method, serviceType, serviceInterfaceClass, restMethodMetadata); restMethodMetadata.getRequest().getConsumes().add(APPLICATION_FORM_URLENCODED_VALUE.value); - } @Override protected String getAnnotationValue(Annotation annotation, Parameter parameter, int parameterIndex) { return null; } - } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/HeaderParamParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/HeaderParamParameterProcessor.java index 216f1091f2..9fc5299e83 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/HeaderParamParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/HeaderParamParameterProcessor.java @@ -41,8 +41,14 @@ public class HeaderParamParameterProcessor extends AbstractAnnotatedMethodParame } @Override - protected void process(String headerName, String defaultValue, Annotation annotation, Parameter parameter, - int parameterIndex, Method method, RestMethodMetadata restMethodMetadata) { + protected void process( + String headerName, + String defaultValue, + Annotation annotation, + Parameter parameter, + int parameterIndex, + Method method, + RestMethodMetadata restMethodMetadata) { RequestMetadata requestMetadata = restMethodMetadata.getRequest(); // Add the placeholder as header value requestMetadata.addHeader(headerName, buildDefaultValue(parameterIndex)); diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolver.java index 0acd60b7db..d344c279fc 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolver.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolver.java @@ -50,8 +50,8 @@ public class JAXRSServiceRestMetadataResolver extends AbstractServiceRestMetadat @Override protected boolean supports0(Class serviceType) { return isAnnotationPresent(serviceType, PATH_ANNOTATION_CLASS_NAME) - // method @Path - || isServiceMethodAnnotationPresent(serviceType,PATH_ANNOTATION_CLASS_NAME); + // method @Path + || isServiceMethodAnnotationPresent(serviceType, PATH_ANNOTATION_CLASS_NAME); } @Override @@ -86,16 +86,16 @@ public class JAXRSServiceRestMetadataResolver extends AbstractServiceRestMetadat } @Override - protected void processProduces(Method serviceMethod, Class serviceType, Class serviceInterfaceClass, - Set produces) { + protected void processProduces( + Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set produces) { addAnnotationValues(serviceMethod, PRODUCES_ANNOTATION_CLASS_NAME, produces); addAnnotationValues(serviceType, PRODUCES_ANNOTATION_CLASS_NAME, produces); addAnnotationValues(serviceInterfaceClass, PRODUCES_ANNOTATION_CLASS_NAME, produces); } @Override - protected void processConsumes(Method serviceMethod, Class serviceType, Class serviceInterfaceClass, - Set consumes) { + protected void processConsumes( + Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set consumes) { addAnnotationValues(serviceMethod, CONSUMES_ANNOTATION_CLASS_NAME, consumes); addAnnotationValues(serviceType, CONSUMES_ANNOTATION_CLASS_NAME, consumes); addAnnotationValues(serviceInterfaceClass, CONSUMES_ANNOTATION_CLASS_NAME, consumes); diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/ParamAnnotationParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/ParamAnnotationParameterProcessor.java index d7dd5c05c9..e2feefb9cb 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/ParamAnnotationParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/ParamAnnotationParameterProcessor.java @@ -31,8 +31,14 @@ import java.lang.reflect.Parameter; public abstract class ParamAnnotationParameterProcessor extends AbstractAnnotatedMethodParameterProcessor { @Override - protected void process(String name, String defaultValue, Annotation annotation, Parameter parameter, - int parameterIndex, Method method, RestMethodMetadata restMethodMetadata) { + protected void process( + String name, + String defaultValue, + Annotation annotation, + Parameter parameter, + int parameterIndex, + Method method, + RestMethodMetadata restMethodMetadata) { RequestMetadata requestMetadata = restMethodMetadata.getRequest(); requestMetadata.addParam(name, defaultValue); } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/PathParamParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/PathParamParameterProcessor.java index 3ab3b8591d..478182312e 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/PathParamParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/jaxrs/PathParamParameterProcessor.java @@ -32,6 +32,4 @@ public class PathParamParameterProcessor extends AbstractAnnotatedMethodParamete public String getAnnotationName() { return PATH_PARAM_ANNOTATION_CLASS_NAME; } - - } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/media/MediaType.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/media/MediaType.java index 2414e4ffae..df59aa4961 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/media/MediaType.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/media/MediaType.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.rest.media; - import java.util.Arrays; import java.util.List; @@ -48,9 +47,7 @@ public enum MediaType { } public static List getSupportMediaTypes() { - return Arrays.asList(APPLICATION_JSON_VALUE, - APPLICATION_FORM_URLENCODED_VALUE, - TEXT_PLAIN,TEXT_XML,OCTET_STREAM); + return Arrays.asList( + APPLICATION_JSON_VALUE, APPLICATION_FORM_URLENCODED_VALUE, TEXT_PLAIN, TEXT_XML, OCTET_STREAM); } - } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/noannotaion/NoAnnotationServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/noannotaion/NoAnnotationServiceRestMetadataResolver.java index 43b6754add..61cb1abb62 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/noannotaion/NoAnnotationServiceRestMetadataResolver.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/noannotaion/NoAnnotationServiceRestMetadataResolver.java @@ -70,19 +70,26 @@ public class NoAnnotationServiceRestMetadataResolver extends AbstractServiceRest } @Override - protected void processProduces(Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set produces) { + protected void processProduces( + Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set produces) { produces.add(CONTENT_TYPE); } @Override - protected void processConsumes(Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set consumes) { + protected void processConsumes( + Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set consumes) { consumes.add(CONTENT_TYPE); } @Override - protected void processAnnotatedMethodParameter(Parameter parameter, int parameterIndex, Method serviceMethod, Class serviceType, Class serviceInterfaceClass, RestMethodMetadata metadata) { + protected void processAnnotatedMethodParameter( + Parameter parameter, + int parameterIndex, + Method serviceMethod, + Class serviceType, + Class serviceInterfaceClass, + RestMethodMetadata metadata) { ArgInfo argInfo = ArgInfo.build(parameterIndex, parameter); metadata.addArgInfo(argInfo); - } } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/PathVariableParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/PathVariableParameterProcessor.java index a1eccd888b..fe239f6221 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/PathVariableParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/PathVariableParameterProcessor.java @@ -34,10 +34,8 @@ public class PathVariableParameterProcessor extends AbstractAnnotatedMethodParam return PATH_VARIABLE_ANNOTATION_CLASS_NAME; } - @Override protected String getDefaultValue(Annotation annotation, Parameter parameter, int parameterIndex) { return null; } } - diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestHeaderParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestHeaderParameterProcessor.java index 3eaae48e4f..1edb86fc05 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestHeaderParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestHeaderParameterProcessor.java @@ -36,9 +36,14 @@ public class RequestHeaderParameterProcessor extends AbstractRequestAnnotationPa } @Override - protected void process(String name, String defaultValue, Annotation annotation, Parameter parameter, - int parameterIndex, Method method, RestMethodMetadata restMethodMetadata) { + protected void process( + String name, + String defaultValue, + Annotation annotation, + Parameter parameter, + int parameterIndex, + Method method, + RestMethodMetadata restMethodMetadata) { restMethodMetadata.getRequest().addHeader(name, defaultValue); } - } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestParamParameterProcessor.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestParamParameterProcessor.java index 7549196fe4..ad457d3c94 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestParamParameterProcessor.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/RequestParamParameterProcessor.java @@ -36,8 +36,14 @@ public class RequestParamParameterProcessor extends AbstractRequestAnnotationPar } @Override - protected void process(String name, String defaultValue, Annotation annotation, Parameter parameter, int parameterIndex, - Method method, RestMethodMetadata restMethodMetadata) { + protected void process( + String name, + String defaultValue, + Annotation annotation, + Parameter parameter, + int parameterIndex, + Method method, + RestMethodMetadata restMethodMetadata) { restMethodMetadata.getRequest().addParam(name, defaultValue); } } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolver.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolver.java index 84a21aa76b..fe8c9c2f70 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolver.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolver.java @@ -61,9 +61,9 @@ public class SpringMvcServiceRestMetadataResolver extends AbstractServiceRestMet protected boolean supports0(Class serviceType) { // class @Controller or @RequestMapping return isAnnotationPresent(serviceType, CONTROLLER_ANNOTATION_CLASS) - || isAnnotationPresent(serviceType, FEIGN_CLIENT_CLASS) - || isAnnotationPresent(serviceType, REQUEST_MAPPING_ANNOTATION_CLASS)// method @RequestMapping - || isServiceMethodAnnotationPresent(serviceType, REQUEST_MAPPING_ANNOTATION_CLASS_NAME); + || isAnnotationPresent(serviceType, FEIGN_CLIENT_CLASS) + || isAnnotationPresent(serviceType, REQUEST_MAPPING_ANNOTATION_CLASS) // method @RequestMapping + || isServiceMethodAnnotationPresent(serviceType, REQUEST_MAPPING_ANNOTATION_CLASS_NAME); } @Override @@ -96,14 +96,16 @@ public class SpringMvcServiceRestMetadataResolver extends AbstractServiceRestMet } @Override - protected void processProduces(Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set produces) { + protected void processProduces( + Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set produces) { addMediaTypes(serviceMethod, "produces", produces); addMediaTypes(serviceType, "produces", produces); addMediaTypes(serviceInterfaceClass, "produces", produces); } @Override - protected void processConsumes(Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set consumes) { + protected void processConsumes( + Method serviceMethod, Class serviceType, Class serviceInterfaceClass, Set consumes) { addMediaTypes(serviceMethod, "consumes", consumes); addMediaTypes(serviceType, "consumes", consumes); addMediaTypes(serviceInterfaceClass, "consumes", consumes); @@ -169,10 +171,12 @@ public class SpringMvcServiceRestMetadataResolver extends AbstractServiceRestMet // because of "@GetMapping" alias for ("@AliasFor") "@RequestMapping" , both of them belongs to // the artifact "spring-web" which depends on "spring-core", thus Spring core's // AnnotatedElementUtils.findMergedAnnotation(AnnotatedElement, Class) must be involved. - Method method = findMethod(ANNOTATED_ELEMENT_UTILS_CLASS, "findMergedAnnotation", AnnotatedElement.class, Class.class); + Method method = findMethod( + ANNOTATED_ELEMENT_UTILS_CLASS, "findMergedAnnotation", AnnotatedElement.class, Class.class); if (method != null) { try { - requestMapping = (Annotation) method.invoke(null, annotatedElement, REQUEST_MAPPING_ANNOTATION_CLASS); + requestMapping = + (Annotation) method.invoke(null, annotatedElement, REQUEST_MAPPING_ANNOTATION_CLASS); } catch (Exception ignored) { } } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/tag/BodyTag.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/tag/BodyTag.java index a1038c8718..c308bcee0b 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/tag/BodyTag.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/tag/BodyTag.java @@ -19,5 +19,4 @@ package org.apache.dubbo.metadata.rest.tag; /** * for @RequestBody class no found */ -public interface BodyTag { -} +public interface BodyTag {} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/tag/NoAnnotationTag.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/tag/NoAnnotationTag.java index 067a8d594c..949157b0be 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/tag/NoAnnotationTag.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/tag/NoAnnotationTag.java @@ -19,5 +19,4 @@ package org.apache.dubbo.metadata.rest.tag; /** * for no annotation mode param */ -public interface NoAnnotationTag { -} +public interface NoAnnotationTag {} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/tag/ParamTag.java b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/tag/ParamTag.java index 66249b43aa..cfc16e3664 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/tag/ParamTag.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/main/java/org/apache/dubbo/metadata/rest/tag/ParamTag.java @@ -19,5 +19,4 @@ package org.apache.dubbo.metadata.rest.tag; /** * for @RequestParam or @QueryParam class no found */ -public interface ParamTag { -} +public interface ParamTag {} diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/PathMatcherTest.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/PathMatcherTest.java index b46675c3bf..875b589b2b 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/PathMatcherTest.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/PathMatcherTest.java @@ -17,18 +17,18 @@ package org.apache.dubbo.metadata; import org.apache.dubbo.metadata.rest.PathMatcher; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.lang.reflect.Method; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + public class PathMatcherTest { @Test void testPathMatcher() { PathMatcher pathMatherMeta = new PathMatcher("/a/b/c/{path1}/d/{path2}/e"); - PathMatcher requestPathMather = new PathMatcher("/a/b/c/1/d/2/e"); Assertions.assertEquals(requestPathMather, pathMatherMeta); @@ -63,7 +63,6 @@ public class PathMatcherTest { pathMatherMeta1.setContextPath("context"); - Assertions.assertEquals(pathMatherMeta, pathMatherMeta1); Assertions.assertEquals(pathMatherMeta.toString(), pathMatherMeta1.toString()); } @@ -84,20 +83,15 @@ public class PathMatcherTest { PathMatcher pathMatchers = new PathMatcher(hashCode); Assertions.assertNotEquals(pathMatcher, pathMatchers); - // equal PathMatcher pathMatherMetaHashCode = PathMatcher.getInvokeCreatePathMatcher(hashCode); PathMatcher pathMatherMetaHashCodes = new PathMatcher(hashCode); Assertions.assertEquals(pathMatherMetaHashCode, pathMatherMetaHashCodes); - PathMatcher pathMatherMetaEquals = PathMatcher.getInvokeCreatePathMatcher(equals); PathMatcher pathMatherMetaEqual = PathMatcher.getInvokeCreatePathMatcher(equals); Assertions.assertEquals(pathMatherMetaEqual, pathMatherMetaEquals); - Assertions.assertNotEquals(pathMatherMetaHashCode, pathMatherMetaEquals); } - - } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/TestMediaType.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/TestMediaType.java index f81509e0ca..1a6fbad425 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/TestMediaType.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/TestMediaType.java @@ -17,6 +17,7 @@ package org.apache.dubbo.metadata; import org.apache.dubbo.metadata.rest.media.MediaType; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/DefaultRestService.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/DefaultRestService.java index fd0f36cc62..56075447d5 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/DefaultRestService.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/DefaultRestService.java @@ -64,19 +64,13 @@ public class DefaultRestService implements RestService { } @Override - public void noAnnotationJsonBody(User user) { - - } + public void noAnnotationJsonBody(User user) {} @Override - public void noAnnotationFormBody(User user) { - - } + public void noAnnotationFormBody(User user) {} @Override - public void noAnnotationParam(String text) { - - } + public void noAnnotationParam(String text) {} public User user(User user) { return user; diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/RestService.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/RestService.java index 60c78cf3ae..049335e0f5 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/RestService.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/RestService.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.rest; - import java.util.Map; /** @@ -41,6 +40,8 @@ public interface RestService { Map requestBodyUser(User user); void noAnnotationJsonBody(User user); + void noAnnotationFormBody(User user); - void noAnnotationParam(String text); + + void noAnnotationParam(String text); } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java index de26899585..05c3fea7ef 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/SpringRestService.java @@ -18,18 +18,18 @@ package org.apache.dubbo.metadata.rest; import org.apache.dubbo.config.annotation.DubboService; -import org.springframework.http.MediaType; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; - import java.util.HashMap; import java.util.Map; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + /** * Spring MVC {@link RestService} * @@ -47,22 +47,24 @@ public class SpringRestService implements RestService { @Override @PostMapping("/params") - public String params(@RequestParam(defaultValue = "value-a") int a, @RequestParam(defaultValue = "value-b") String b) { + public String params( + @RequestParam(defaultValue = "value-a") int a, @RequestParam(defaultValue = "value-b") String b) { return null; } @Override @GetMapping("/headers") - public String headers(@RequestHeader(name = "h", defaultValue = "value-h") String header, - @RequestHeader(name = "h2", defaultValue = "value-h2") String header2, - @RequestParam(value = "v", defaultValue = "1") Integer param) { + public String headers( + @RequestHeader(name = "h", defaultValue = "value-h") String header, + @RequestHeader(name = "h2", defaultValue = "value-h2") String header2, + @RequestParam(value = "v", defaultValue = "1") Integer param) { return null; } @Override @GetMapping("/path-variables/{p1}/{p2}") - public String pathVariables(@PathVariable("p1") String path1, - @PathVariable("p2") String path2, @RequestParam("v") String param) { + public String pathVariables( + @PathVariable("p1") String path1, @PathVariable("p2") String path2, @RequestParam("v") String param) { return null; } @@ -74,8 +76,7 @@ public class SpringRestService implements RestService { @Override @PostMapping(value = "/request/body/map", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - public User requestBodyMap(@RequestBody Map data, - @RequestParam("param") String param) { + public User requestBodyMap(@RequestBody Map data, @RequestParam("param") String param) { User user = new User(); user.setId(((Integer) data.get("id")).longValue()); user.setName((String) data.get("name")); @@ -95,19 +96,13 @@ public class SpringRestService implements RestService { @PostMapping(value = "/request/body/user/json", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) @Override - public void noAnnotationJsonBody(User user) { - - } + public void noAnnotationJsonBody(User user) {} @PostMapping(value = "/request/body/user/form", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) @Override - public void noAnnotationFormBody(User user) { - - } + public void noAnnotationFormBody(User user) {} @PostMapping(value = "/request/body/user/param") @Override - public void noAnnotationParam(String text) { - - } + public void noAnnotationParam(String text) {} } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java index 44ee3514c6..45b84b9ce3 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java @@ -28,14 +28,17 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; + import java.util.HashMap; import java.util.Map; - /** * JAX-RS {@link RestService} */ -@DubboService(version = "3.0.0", protocol = {"dubbo", "rest"}, group = "standard") +@DubboService( + version = "3.0.0", + protocol = {"dubbo", "rest"}, + group = "standard") @Path("/") public class StandardRestService implements RestService { @@ -56,8 +59,8 @@ public class StandardRestService implements RestService { @Override @Path("headers") @GET - public String headers(@HeaderParam("h") String header, - @HeaderParam("h2") String header2, @QueryParam("v") Integer param) { + public String headers( + @HeaderParam("h") String header, @HeaderParam("h2") String header2, @QueryParam("v") Integer param) { String result = header + " , " + header2 + " , " + param; return result; } @@ -65,8 +68,8 @@ public class StandardRestService implements RestService { @Override @Path("path-variables/{p1}/{p2}") @GET - public String pathVariables(@PathParam("p1") String path1, - @PathParam("p2") String path2, @QueryParam("v") String param) { + public String pathVariables( + @PathParam("p1") String path1, @PathParam("p2") String path2, @QueryParam("v") String param) { String result = path1 + " , " + path2 + " , " + param; return result; } @@ -85,8 +88,7 @@ public class StandardRestService implements RestService { @Path("request/body/map") @POST @Produces("application/json;charset=UTF-8") - public User requestBodyMap(Map data, - @QueryParam("param") String param) { + public User requestBodyMap(Map data, @QueryParam("param") String param) { User user = new User(); user.setId(((Integer) data.get("id")).longValue()); user.setName((String) data.get("name")); @@ -110,22 +112,16 @@ public class StandardRestService implements RestService { @POST @Consumes(MediaType.APPLICATION_JSON) @Override - public void noAnnotationJsonBody(User user) { - - } + public void noAnnotationJsonBody(User user) {} @Path("noAnnotationFormBody/form") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @POST @Override - public void noAnnotationFormBody(User user) { - - } + public void noAnnotationFormBody(User user) {} @Path("noAnnotationParam/text") @POST @Override - public void noAnnotationParam(String text) { - - } + public void noAnnotationParam(String text) {} } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestDoubleCheckContainsPathVariableService.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestDoubleCheckContainsPathVariableService.java index 8f5e7c1e11..324ba19ade 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestDoubleCheckContainsPathVariableService.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestDoubleCheckContainsPathVariableService.java @@ -27,7 +27,6 @@ public interface JaxrsRestDoubleCheckContainsPathVariableService { @GET String param(@QueryParam("param") String param); - @Path("/{b}/b") @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.TEXT_PLAIN) diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestDoubleCheckService.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestDoubleCheckService.java index ad0b3658c9..389af5e78c 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestDoubleCheckService.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestDoubleCheckService.java @@ -23,6 +23,7 @@ import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; + @Path("/test") public interface JaxrsRestDoubleCheckService { @Path("/param") diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestService.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestService.java index ff9909ddb2..3cc8416fbd 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestService.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestService.java @@ -66,6 +66,4 @@ public interface JaxrsRestService { @Produces(MediaType.TEXT_PLAIN) @POST String noAnno(String a); - - } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestServiceImpl.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestServiceImpl.java index 62cf3578ef..2f309e28c0 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestServiceImpl.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsRestServiceImpl.java @@ -22,7 +22,6 @@ import javax.ws.rs.core.MultivaluedMap; public class JaxrsRestServiceImpl implements JaxrsRestService { - @Override public String param(String param) { return param; diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsUsingService.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsUsingService.java index 7490c75341..4bcc761f1d 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsUsingService.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/JaxrsUsingService.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.rest.api; - import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/SpringControllerService.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/SpringControllerService.java index dfea020905..479714a4d4 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/SpringControllerService.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/SpringControllerService.java @@ -17,6 +17,7 @@ package org.apache.dubbo.metadata.rest.api; import org.apache.dubbo.metadata.rest.User; + import org.springframework.http.MediaType; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.PathVariable; @@ -29,42 +30,74 @@ import org.springframework.web.bind.annotation.RestController; @RestController public class SpringControllerService { - @RequestMapping(value = "/param", method = RequestMethod.GET, consumes = MediaType.TEXT_PLAIN_VALUE, produces = MediaType.TEXT_PLAIN_VALUE) + @RequestMapping( + value = "/param", + method = RequestMethod.GET, + consumes = MediaType.TEXT_PLAIN_VALUE, + produces = MediaType.TEXT_PLAIN_VALUE) public String param(@RequestParam String param) { return param; } - @RequestMapping(value = "/header", method = RequestMethod.GET, consumes = MediaType.TEXT_PLAIN_VALUE, produces = MediaType.TEXT_PLAIN_VALUE) + @RequestMapping( + value = "/header", + method = RequestMethod.GET, + consumes = MediaType.TEXT_PLAIN_VALUE, + produces = MediaType.TEXT_PLAIN_VALUE) public String header(@RequestHeader String header) { return header; } - @RequestMapping(value = "/body", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) + @RequestMapping( + value = "/body", + method = RequestMethod.POST, + consumes = MediaType.APPLICATION_JSON_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE) public User body(@RequestBody User user) { return user; } - @RequestMapping(value = "/multiValue", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE) + @RequestMapping( + value = "/multiValue", + method = RequestMethod.POST, + consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, + produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE) public MultiValueMap multiValue(@RequestBody MultiValueMap map) { return map; } - @RequestMapping(value = "/pathVariable/{a}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE) + @RequestMapping( + value = "/pathVariable/{a}", + method = RequestMethod.POST, + consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, + produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE) public String pathVariable(@PathVariable String a) { return a; } - @RequestMapping(value = "/noAnnoParam", method = RequestMethod.POST, consumes = MediaType.TEXT_PLAIN_VALUE, produces = MediaType.TEXT_PLAIN_VALUE) + @RequestMapping( + value = "/noAnnoParam", + method = RequestMethod.POST, + consumes = MediaType.TEXT_PLAIN_VALUE, + produces = MediaType.TEXT_PLAIN_VALUE) public String noAnnoParam(String a) { return a; } - @RequestMapping(value = "/noAnnoNumber", method = RequestMethod.POST, consumes = MediaType.ALL_VALUE, produces = MediaType.ALL_VALUE) + @RequestMapping( + value = "/noAnnoNumber", + method = RequestMethod.POST, + consumes = MediaType.ALL_VALUE, + produces = MediaType.ALL_VALUE) public int noAnnoNumber(Integer b) { return b; } - @RequestMapping(value = "/noAnnoPrimitive", method = RequestMethod.POST, consumes = MediaType.ALL_VALUE, produces = MediaType.ALL_VALUE) + @RequestMapping( + value = "/noAnnoPrimitive", + method = RequestMethod.POST, + consumes = MediaType.ALL_VALUE, + produces = MediaType.ALL_VALUE) public int noAnnoPrimitive(int c) { return c; } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/SpringRestService.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/SpringRestService.java index 3a6e591df1..8a8c727553 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/SpringRestService.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/SpringRestService.java @@ -17,45 +17,73 @@ package org.apache.dubbo.metadata.rest.api; import org.apache.dubbo.metadata.rest.User; + import org.springframework.http.MediaType; import org.springframework.util.MultiValueMap; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.PathVariable; - @RestController public interface SpringRestService { - - @RequestMapping(value = "/param", method = RequestMethod.GET, consumes = MediaType.TEXT_PLAIN_VALUE, produces = MediaType.TEXT_PLAIN_VALUE) + @RequestMapping( + value = "/param", + method = RequestMethod.GET, + consumes = MediaType.TEXT_PLAIN_VALUE, + produces = MediaType.TEXT_PLAIN_VALUE) String param(@RequestParam("param") String param); - @RequestMapping(value = "/header", method = RequestMethod.GET, consumes = MediaType.TEXT_PLAIN_VALUE, produces = MediaType.TEXT_PLAIN_VALUE) + @RequestMapping( + value = "/header", + method = RequestMethod.GET, + consumes = MediaType.TEXT_PLAIN_VALUE, + produces = MediaType.TEXT_PLAIN_VALUE) String header(@RequestHeader("header") String header); - @RequestMapping(value = "/body", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) + @RequestMapping( + value = "/body", + method = RequestMethod.POST, + consumes = MediaType.APPLICATION_JSON_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE) User body(@RequestBody User user); - @RequestMapping(value = "/multiValue", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE) + @RequestMapping( + value = "/multiValue", + method = RequestMethod.POST, + consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, + produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE) MultiValueMap multiValue(@RequestBody MultiValueMap map); - - @RequestMapping(value = "/pathVariable/{a}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE) + @RequestMapping( + value = "/pathVariable/{a}", + method = RequestMethod.POST, + consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, + produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE) String pathVariable(@PathVariable String a); - @RequestMapping(value = "/noAnnoParam", method = RequestMethod.POST, consumes = MediaType.TEXT_PLAIN_VALUE, produces = MediaType.TEXT_PLAIN_VALUE) + @RequestMapping( + value = "/noAnnoParam", + method = RequestMethod.POST, + consumes = MediaType.TEXT_PLAIN_VALUE, + produces = MediaType.TEXT_PLAIN_VALUE) String noAnnoParam(String a); - @RequestMapping(value = "/noAnnoNumber", method = RequestMethod.POST, consumes = MediaType.ALL_VALUE, produces = MediaType.ALL_VALUE) + @RequestMapping( + value = "/noAnnoNumber", + method = RequestMethod.POST, + consumes = MediaType.ALL_VALUE, + produces = MediaType.ALL_VALUE) int noAnnoNumber(Integer b); - - @RequestMapping(value = "/noAnnoPrimitive", method = RequestMethod.POST, consumes = MediaType.ALL_VALUE, produces = MediaType.ALL_VALUE) + @RequestMapping( + value = "/noAnnoPrimitive", + method = RequestMethod.POST, + consumes = MediaType.ALL_VALUE, + produces = MediaType.ALL_VALUE) int noAnnoPrimitive(int c); - } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/SpringRestServiceImpl.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/SpringRestServiceImpl.java index 3176f158b8..a9cfb9c308 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/SpringRestServiceImpl.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/api/SpringRestServiceImpl.java @@ -17,14 +17,13 @@ package org.apache.dubbo.metadata.rest.api; import org.apache.dubbo.metadata.rest.User; + import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.RestController; - @RestController public class SpringRestServiceImpl implements SpringRestService { - @Override public String param(String param) { return param; @@ -64,5 +63,4 @@ public class SpringRestServiceImpl implements SpringRestService { public int noAnnoPrimitive(int c) { return c; } - } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/feign/FeignClientController.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/feign/FeignClientController.java index fc1fe0fdbd..e3b0ecbf7b 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/feign/FeignClientController.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/feign/FeignClientController.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.metadata.rest.feign; - import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/feign/FeignClientControllerImpl.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/feign/FeignClientControllerImpl.java index 43333e1547..8f0cc225be 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/feign/FeignClientControllerImpl.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/feign/FeignClientControllerImpl.java @@ -16,9 +16,7 @@ */ package org.apache.dubbo.metadata.rest.feign; - - -public class FeignClientControllerImpl implements FeignClientController{ +public class FeignClientControllerImpl implements FeignClientController { @Override public String hello() { diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolverTest.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolverTest.java index 32643ebab7..e68b995e84 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolverTest.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JAXRSServiceRestMetadataResolverTest.java @@ -31,15 +31,15 @@ import org.apache.dubbo.metadata.rest.api.JaxrsRestServiceImpl; import org.apache.dubbo.metadata.rest.api.SpringRestService; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -51,8 +51,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; */ class JAXRSServiceRestMetadataResolverTest { - private JAXRSServiceRestMetadataResolver instance = new JAXRSServiceRestMetadataResolver(ApplicationModel.defaultModel()); - + private JAXRSServiceRestMetadataResolver instance = + new JAXRSServiceRestMetadataResolver(ApplicationModel.defaultModel()); @Test void testSupports() { @@ -72,7 +72,8 @@ class JAXRSServiceRestMetadataResolverTest { @Disabled void testResolve() { // Generated by "dubbo-metadata-processor" - ClassPathServiceRestMetadataReader reader = new ClassPathServiceRestMetadataReader("META-INF/dubbo/jax-rs-service-rest-metadata.json"); + ClassPathServiceRestMetadataReader reader = + new ClassPathServiceRestMetadataReader("META-INF/dubbo/jax-rs-service-rest-metadata.json"); List serviceRestMetadataList = reader.read(); ServiceRestMetadata expectedServiceRestMetadata = serviceRestMetadataList.get(0); @@ -81,7 +82,6 @@ class JAXRSServiceRestMetadataResolverTest { assertTrue(CollectionUtils.equals(expectedServiceRestMetadata.getMeta(), serviceRestMetadata.getMeta())); assertEquals(expectedServiceRestMetadata, serviceRestMetadata); - } @Test @@ -90,25 +90,21 @@ class JAXRSServiceRestMetadataResolverTest { testResolve(JaxrsRestServiceImpl.class); } - void testResolve(Class service) { // Generated by "dubbo-metadata-processor" List jsons = Arrays.asList( - "{\"argInfos\":[{\"annotationNameAttribute\":\"a\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.BodyTag\",\"paramName\":\"a\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"a\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/noAnno\",\"produces\":[\"text/plain\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"a\",\"defaultValue\":\"{0}\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"javax.ws.rs.PathParam\",\"paramName\":\"a\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":2}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"a\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/x-www-form-urlencoded\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/pathVariable/{a}\",\"produces\":[\"application/x-www-form-urlencoded\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"map\",\"formContentType\":true,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.BodyTag\",\"paramName\":\"map\",\"paramType\":\"javax.ws.rs.core.MultivaluedMap\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"map\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/x-www-form-urlencoded\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/multiValue\",\"produces\":[\"application/x-www-form-urlencoded\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"user\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.BodyTag\",\"paramName\":\"user\",\"paramType\":\"org.apache.dubbo.metadata.rest.User\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"user\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/body\",\"produces\":[\"application/json\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"param\",\"defaultValue\":\"{0}\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"javax.ws.rs.QueryParam\",\"paramName\":\"param\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"param\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[],\"headers\":{},\"method\":\"GET\",\"paramNames\":[\"param\"],\"params\":{\"param\":[\"{0}\"]},\"path\":\"/param\",\"produces\":[\"text/plain\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"header\",\"defaultValue\":\"{0}\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"javax.ws.rs.HeaderParam\",\"paramName\":\"header\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"header\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[\"header\"],\"headers\":{\"header\":[\"{0}\"]},\"method\":\"GET\",\"paramNames\":[],\"params\":{},\"path\":\"/header\",\"produces\":[\"text/plain\"]}}" - - ); + "{\"argInfos\":[{\"annotationNameAttribute\":\"a\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.BodyTag\",\"paramName\":\"a\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"a\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/noAnno\",\"produces\":[\"text/plain\"]}}", + "{\"argInfos\":[{\"annotationNameAttribute\":\"a\",\"defaultValue\":\"{0}\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"javax.ws.rs.PathParam\",\"paramName\":\"a\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":2}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"a\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/x-www-form-urlencoded\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/pathVariable/{a}\",\"produces\":[\"application/x-www-form-urlencoded\"]}}", + "{\"argInfos\":[{\"annotationNameAttribute\":\"map\",\"formContentType\":true,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.BodyTag\",\"paramName\":\"map\",\"paramType\":\"javax.ws.rs.core.MultivaluedMap\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"map\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/x-www-form-urlencoded\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/multiValue\",\"produces\":[\"application/x-www-form-urlencoded\"]}}", + "{\"argInfos\":[{\"annotationNameAttribute\":\"user\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.BodyTag\",\"paramName\":\"user\",\"paramType\":\"org.apache.dubbo.metadata.rest.User\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"user\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/body\",\"produces\":[\"application/json\"]}}", + "{\"argInfos\":[{\"annotationNameAttribute\":\"param\",\"defaultValue\":\"{0}\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"javax.ws.rs.QueryParam\",\"paramName\":\"param\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"param\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[],\"headers\":{},\"method\":\"GET\",\"paramNames\":[\"param\"],\"params\":{\"param\":[\"{0}\"]},\"path\":\"/param\",\"produces\":[\"text/plain\"]}}", + "{\"argInfos\":[{\"annotationNameAttribute\":\"header\",\"defaultValue\":\"{0}\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"javax.ws.rs.HeaderParam\",\"paramName\":\"header\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.jaxrs.JAXRSServiceRestMetadataResolver\",\"indexToName\":{0:[\"header\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[\"header\"],\"headers\":{\"header\":[\"{0}\"]},\"method\":\"GET\",\"paramNames\":[],\"params\":{},\"path\":\"/header\",\"produces\":[\"text/plain\"]}}"); ServiceRestMetadata jaxrsRestMetadata = new ServiceRestMetadata(); jaxrsRestMetadata.setServiceInterface(service.getName()); ServiceRestMetadata jaxrsMetadata = instance.resolve(service, jaxrsRestMetadata); - List jsonsTmp = new ArrayList<>(); for (RestMethodMetadata restMethodMetadata : jaxrsMetadata.getMeta()) { restMethodMetadata.setReflectMethod(null); @@ -125,14 +121,11 @@ class JAXRSServiceRestMetadataResolverTest { jsons.sort(comparator); jsonsTmp.sort(comparator); - for (int i = 0; i < jsons.size(); i++) { assertEquals(jsons.get(i), jsonsTmp.get(i)); } - } - @Test void testJaxrsPathPattern() { Class service = AnotherUserRestService.class; @@ -148,8 +141,7 @@ class JAXRSServiceRestMetadataResolverTest { } } - - Assertions.assertEquals("/u/1", PathUtil.resolvePathVariable("/u/{id : \\d+}", object.getArgInfos(), Arrays.asList(1))); - + Assertions.assertEquals( + "/u/1", PathUtil.resolvePathVariable("/u/{id : \\d+}", object.getArgInfos(), Arrays.asList(1))); } } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JaxrsRestDoubleCheckTest.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JaxrsRestDoubleCheckTest.java index 3e8f129f20..362e7f3acb 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JaxrsRestDoubleCheckTest.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/jaxrs/JaxrsRestDoubleCheckTest.java @@ -23,14 +23,15 @@ import org.apache.dubbo.metadata.rest.api.JaxrsRestDoubleCheckContainsPathVariab import org.apache.dubbo.metadata.rest.api.JaxrsRestDoubleCheckService; import org.apache.dubbo.metadata.rest.api.JaxrsUsingService; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.util.Map; -public class JaxrsRestDoubleCheckTest { - private JAXRSServiceRestMetadataResolver instance = new JAXRSServiceRestMetadataResolver(ApplicationModel.defaultModel()); +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +public class JaxrsRestDoubleCheckTest { + private JAXRSServiceRestMetadataResolver instance = + new JAXRSServiceRestMetadataResolver(ApplicationModel.defaultModel()); @Test void testDoubleCheckException() { @@ -46,8 +47,6 @@ public class JaxrsRestDoubleCheckTest { resolve.setServiceInterface(JaxrsRestDoubleCheckContainsPathVariableService.class.getName()); instance.resolve(JaxrsRestDoubleCheckContainsPathVariableService.class, resolve); }); - - } @Test @@ -63,14 +62,12 @@ public class JaxrsRestDoubleCheckTest { resolve.setServiceInterface(JaxrsUsingService.class.getName()); instance.resolve(JaxrsUsingService.class, resolve); - Map pathContainPathVariableToServiceMap = resolve.getPathContainPathVariableToServiceMap(); + Map pathContainPathVariableToServiceMap = + resolve.getPathContainPathVariableToServiceMap(); - - RestMethodMetadata restMethodMetadata = pathContainPathVariableToServiceMap.get(PathMatcher.getInvokeCreatePathMatcher("/usingService/aaa", null, null, null, "TEST")); + RestMethodMetadata restMethodMetadata = pathContainPathVariableToServiceMap.get( + PathMatcher.getInvokeCreatePathMatcher("/usingService/aaa", null, null, null, "TEST")); Assertions.assertNotNull(restMethodMetadata); - - } - } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/noannotation/NoAnnotationServiceRestMetadataResolverTest.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/noannotation/NoAnnotationServiceRestMetadataResolverTest.java index 7d556fe15f..1db4aae982 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/noannotation/NoAnnotationServiceRestMetadataResolverTest.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/noannotation/NoAnnotationServiceRestMetadataResolverTest.java @@ -22,57 +22,49 @@ import org.apache.dubbo.metadata.rest.RestMethodMetadata; import org.apache.dubbo.metadata.rest.ServiceRestMetadata; import org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; public class NoAnnotationServiceRestMetadataResolverTest { - private NoAnnotationServiceRestMetadataResolver instance = new NoAnnotationServiceRestMetadataResolver(ApplicationModel.defaultModel()); - + private NoAnnotationServiceRestMetadataResolver instance = + new NoAnnotationServiceRestMetadataResolver(ApplicationModel.defaultModel()); @Test void testResolve() { List jsons = Arrays.asList( - "{\"argInfos\":[{\"annotationNameAttribute\":\"form\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"form\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"form\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/form\",\"produces\":[\"application/json\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"header\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"header\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0},{\"annotationNameAttribute\":\"header2\",\"formContentType\":false,\"index\":1,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"header2\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0},{\"annotationNameAttribute\":\"param\",\"formContentType\":false,\"index\":2,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"param\",\"paramType\":\"java.lang.Integer\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"header\"],1:[\"header2\"],2:[\"param\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/headers\",\"produces\":[\"application/json\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"user\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"user\",\"paramType\":\"org.apache.dubbo.metadata.rest.User\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"user\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/noAnnotationFormBody\",\"produces\":[\"application/json\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"user\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"user\",\"paramType\":\"org.apache.dubbo.metadata.rest.User\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"user\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/noAnnotationJsonBody\",\"produces\":[\"application/json\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"text\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"text\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"text\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/noAnnotationParam\",\"produces\":[\"application/json\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"param\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"param\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"param\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/param\",\"produces\":[\"application/json\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"a\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"a\",\"paramType\":\"int\",\"urlSplitIndex\":0},{\"annotationNameAttribute\":\"b\",\"formContentType\":false,\"index\":1,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"b\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"a\"],1:[\"b\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/params\",\"produces\":[\"application/json\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"path1\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"path1\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0},{\"annotationNameAttribute\":\"path2\",\"formContentType\":false,\"index\":1,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"path2\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0},{\"annotationNameAttribute\":\"param\",\"formContentType\":false,\"index\":2,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"param\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"path1\"],1:[\"path2\"],2:[\"param\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/pathVariables\",\"produces\":[\"application/json\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"data\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"data\",\"paramType\":\"java.util.Map\",\"urlSplitIndex\":0},{\"annotationNameAttribute\":\"param\",\"formContentType\":false,\"index\":1,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"param\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"data\"],1:[\"param\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/requestBodyMap\",\"produces\":[\"application/json\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"user\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"user\",\"paramType\":\"org.apache.dubbo.metadata.rest.User\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"user\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/requestBodyUser\",\"produces\":[\"application/json\"]}}" - - ); + "{\"argInfos\":[{\"annotationNameAttribute\":\"form\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"form\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"form\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/form\",\"produces\":[\"application/json\"]}}", + "{\"argInfos\":[{\"annotationNameAttribute\":\"header\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"header\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0},{\"annotationNameAttribute\":\"header2\",\"formContentType\":false,\"index\":1,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"header2\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0},{\"annotationNameAttribute\":\"param\",\"formContentType\":false,\"index\":2,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"param\",\"paramType\":\"java.lang.Integer\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"header\"],1:[\"header2\"],2:[\"param\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/headers\",\"produces\":[\"application/json\"]}}", + "{\"argInfos\":[{\"annotationNameAttribute\":\"user\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"user\",\"paramType\":\"org.apache.dubbo.metadata.rest.User\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"user\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/noAnnotationFormBody\",\"produces\":[\"application/json\"]}}", + "{\"argInfos\":[{\"annotationNameAttribute\":\"user\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"user\",\"paramType\":\"org.apache.dubbo.metadata.rest.User\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"user\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/noAnnotationJsonBody\",\"produces\":[\"application/json\"]}}", + "{\"argInfos\":[{\"annotationNameAttribute\":\"text\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"text\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"text\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/noAnnotationParam\",\"produces\":[\"application/json\"]}}", + "{\"argInfos\":[{\"annotationNameAttribute\":\"param\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"param\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"param\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/param\",\"produces\":[\"application/json\"]}}", + "{\"argInfos\":[{\"annotationNameAttribute\":\"a\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"a\",\"paramType\":\"int\",\"urlSplitIndex\":0},{\"annotationNameAttribute\":\"b\",\"formContentType\":false,\"index\":1,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"b\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"a\"],1:[\"b\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/params\",\"produces\":[\"application/json\"]}}", + "{\"argInfos\":[{\"annotationNameAttribute\":\"path1\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"path1\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0},{\"annotationNameAttribute\":\"path2\",\"formContentType\":false,\"index\":1,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"path2\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0},{\"annotationNameAttribute\":\"param\",\"formContentType\":false,\"index\":2,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"param\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"path1\"],1:[\"path2\"],2:[\"param\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/pathVariables\",\"produces\":[\"application/json\"]}}", + "{\"argInfos\":[{\"annotationNameAttribute\":\"data\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"data\",\"paramType\":\"java.util.Map\",\"urlSplitIndex\":0},{\"annotationNameAttribute\":\"param\",\"formContentType\":false,\"index\":1,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"param\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"data\"],1:[\"param\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/requestBodyMap\",\"produces\":[\"application/json\"]}}", + "{\"argInfos\":[{\"annotationNameAttribute\":\"user\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.NoAnnotationTag\",\"paramName\":\"user\",\"paramType\":\"org.apache.dubbo.metadata.rest.User\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.noannotaion.NoAnnotationServiceRestMetadataResolver\",\"indexToName\":{0:[\"user\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/org.apache.dubbo.metadata.rest.RestService/requestBodyUser\",\"produces\":[\"application/json\"]}}"); boolean supports = instance.supports(DefaultRestService.class); - Assertions.assertEquals(true, supports); - ServiceRestMetadata serviceRestMetadata = instance.resolve(DefaultRestService.class); - - - List jsonsTmp = new ArrayList<>(); for (RestMethodMetadata restMethodMetadata : serviceRestMetadata.getMeta()) { restMethodMetadata.setReflectMethod(null); restMethodMetadata.setMethod(null); jsonsTmp.add(JsonUtils.toJson(restMethodMetadata)); - } - Comparator comparator = new Comparator() { @Override public int compare(String o1, String o2) { @@ -82,11 +74,8 @@ public class NoAnnotationServiceRestMetadataResolverTest { jsons.sort(comparator); jsonsTmp.sort(comparator); - for (int i = 0; i < jsons.size(); i++) { assertEquals(jsons.get(i), jsonsTmp.get(i)); } - - } } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/springmvc/FeignClientAnnotationTest.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/springmvc/FeignClientAnnotationTest.java index 8a819db801..f2aa5b88ff 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/springmvc/FeignClientAnnotationTest.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/springmvc/FeignClientAnnotationTest.java @@ -21,14 +21,16 @@ import org.apache.dubbo.metadata.rest.RestMethodMetadata; import org.apache.dubbo.metadata.rest.ServiceRestMetadata; import org.apache.dubbo.metadata.rest.feign.FeignClientController; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + public class FeignClientAnnotationTest { - private SpringMvcServiceRestMetadataResolver instance = new SpringMvcServiceRestMetadataResolver(ApplicationModel.defaultModel()); + private SpringMvcServiceRestMetadataResolver instance = + new SpringMvcServiceRestMetadataResolver(ApplicationModel.defaultModel()); @Test void testFeignClientAnnotationResolve() { @@ -40,8 +42,10 @@ public class FeignClientAnnotationTest { ServiceRestMetadata resolve = instance.resolve(service, serviceRestMetadata); - Map unContainPathVariableToServiceMap = resolve.getPathUnContainPathVariableToServiceMap(); - RestMethodMetadata restMethodMetadata = unContainPathVariableToServiceMap.get(PathMatcher.getInvokeCreatePathMatcher("/feign/context/hello", null, null, null, "GET")); + Map unContainPathVariableToServiceMap = + resolve.getPathUnContainPathVariableToServiceMap(); + RestMethodMetadata restMethodMetadata = unContainPathVariableToServiceMap.get( + PathMatcher.getInvokeCreatePathMatcher("/feign/context/hello", null, null, null, "GET")); Assertions.assertNotNull(restMethodMetadata); } } diff --git a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolverTest.java b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolverTest.java index a79c6e5061..4c96e38334 100644 --- a/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolverTest.java +++ b/dubbo-metadata/dubbo-metadata-rest/src/test/java/org/apache/dubbo/metadata/rest/springmvc/SpringMvcServiceRestMetadataResolverTest.java @@ -30,16 +30,16 @@ import org.apache.dubbo.metadata.rest.api.SpringRestService; import org.apache.dubbo.metadata.rest.api.SpringRestServiceImpl; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -51,7 +51,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; */ class SpringMvcServiceRestMetadataResolverTest { - private SpringMvcServiceRestMetadataResolver instance = new SpringMvcServiceRestMetadataResolver(ApplicationModel.defaultModel()); + private SpringMvcServiceRestMetadataResolver instance = + new SpringMvcServiceRestMetadataResolver(ApplicationModel.defaultModel()); @Test void testSupports() { @@ -71,7 +72,8 @@ class SpringMvcServiceRestMetadataResolverTest { @Disabled void testResolve() { // Generated by "dubbo-metadata-processor" - ClassPathServiceRestMetadataReader reader = new ClassPathServiceRestMetadataReader("META-INF/dubbo/spring-mvc-service-rest-metadata.json"); + ClassPathServiceRestMetadataReader reader = + new ClassPathServiceRestMetadataReader("META-INF/dubbo/spring-mvc-service-rest-metadata.json"); List serviceRestMetadataList = reader.read(); ServiceRestMetadata expectedServiceRestMetadata = serviceRestMetadataList.get(0); @@ -80,7 +82,6 @@ class SpringMvcServiceRestMetadataResolverTest { assertTrue(CollectionUtils.equals(expectedServiceRestMetadata.getMeta(), serviceRestMetadata.getMeta())); assertEquals(expectedServiceRestMetadata, serviceRestMetadata); - } @Test @@ -92,23 +93,19 @@ class SpringMvcServiceRestMetadataResolverTest { void testResolve(Class service) { List jsons = Arrays.asList( - "{\"argInfos\":[{\"annotationNameAttribute\":\"b\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.ParamTag\",\"paramName\":\"b\",\"paramType\":\"java.lang.Integer\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"b\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"*/*\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/noAnnoNumber\",\"produces\":[\"*/*\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"c\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.ParamTag\",\"paramName\":\"c\",\"paramType\":\"int\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"c\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"*/*\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/noAnnoPrimitive\",\"produces\":[\"*/*\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"a\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.ParamTag\",\"paramName\":\"a\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"a\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/noAnnoParam\",\"produces\":[\"text/plain\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.springframework.web.bind.annotation.PathVariable\",\"paramName\":\"a\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":2}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"a\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/x-www-form-urlencoded\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/pathVariable/{a}\",\"produces\":[\"application/x-www-form-urlencoded\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"user\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.springframework.web.bind.annotation.RequestBody\",\"paramName\":\"user\",\"paramType\":\"org.apache.dubbo.metadata.rest.User\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"user\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/body\",\"produces\":[\"application/json\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"param\",\"defaultValue\":\"{0}\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.springframework.web.bind.annotation.RequestParam\",\"paramName\":\"param\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"param\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[],\"headers\":{},\"method\":\"GET\",\"paramNames\":[\"param\"],\"params\":{\"param\":[\"{0}\"]},\"path\":\"/param\",\"produces\":[\"text/plain\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"map\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.springframework.web.bind.annotation.RequestBody\",\"paramName\":\"map\",\"paramType\":\"org.springframework.util.MultiValueMap\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"map\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/x-www-form-urlencoded\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/multiValue\",\"produces\":[\"application/x-www-form-urlencoded\"]}}", - "{\"argInfos\":[{\"annotationNameAttribute\":\"header\",\"defaultValue\":\"{0}\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.springframework.web.bind.annotation.RequestHeader\",\"paramName\":\"header\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"header\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[\"header\"],\"headers\":{\"header\":[\"{0}\"]},\"method\":\"GET\",\"paramNames\":[],\"params\":{},\"path\":\"/header\",\"produces\":[\"text/plain\"]}}" - - - ); + "{\"argInfos\":[{\"annotationNameAttribute\":\"b\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.ParamTag\",\"paramName\":\"b\",\"paramType\":\"java.lang.Integer\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"b\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"*/*\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/noAnnoNumber\",\"produces\":[\"*/*\"]}}", + "{\"argInfos\":[{\"annotationNameAttribute\":\"c\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.ParamTag\",\"paramName\":\"c\",\"paramType\":\"int\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"c\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"*/*\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/noAnnoPrimitive\",\"produces\":[\"*/*\"]}}", + "{\"argInfos\":[{\"annotationNameAttribute\":\"a\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.apache.dubbo.metadata.rest.tag.ParamTag\",\"paramName\":\"a\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"a\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/noAnnoParam\",\"produces\":[\"text/plain\"]}}", + "{\"argInfos\":[{\"annotationNameAttribute\":\"\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.springframework.web.bind.annotation.PathVariable\",\"paramName\":\"a\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":2}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"a\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/x-www-form-urlencoded\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/pathVariable/{a}\",\"produces\":[\"application/x-www-form-urlencoded\"]}}", + "{\"argInfos\":[{\"annotationNameAttribute\":\"user\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.springframework.web.bind.annotation.RequestBody\",\"paramName\":\"user\",\"paramType\":\"org.apache.dubbo.metadata.rest.User\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"user\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/json\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/body\",\"produces\":[\"application/json\"]}}", + "{\"argInfos\":[{\"annotationNameAttribute\":\"param\",\"defaultValue\":\"{0}\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.springframework.web.bind.annotation.RequestParam\",\"paramName\":\"param\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"param\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[],\"headers\":{},\"method\":\"GET\",\"paramNames\":[\"param\"],\"params\":{\"param\":[\"{0}\"]},\"path\":\"/param\",\"produces\":[\"text/plain\"]}}", + "{\"argInfos\":[{\"annotationNameAttribute\":\"map\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.springframework.web.bind.annotation.RequestBody\",\"paramName\":\"map\",\"paramType\":\"org.springframework.util.MultiValueMap\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"map\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"application/x-www-form-urlencoded\"],\"headerNames\":[],\"headers\":{},\"method\":\"POST\",\"paramNames\":[],\"params\":{},\"path\":\"/multiValue\",\"produces\":[\"application/x-www-form-urlencoded\"]}}", + "{\"argInfos\":[{\"annotationNameAttribute\":\"header\",\"defaultValue\":\"{0}\",\"formContentType\":false,\"index\":0,\"paramAnnotationType\":\"org.springframework.web.bind.annotation.RequestHeader\",\"paramName\":\"header\",\"paramType\":\"java.lang.String\",\"urlSplitIndex\":0}],\"codeStyle\":\"org.apache.dubbo.metadata.rest.springmvc.SpringMvcServiceRestMetadataResolver\",\"indexToName\":{0:[\"header\"]},\"method\":{\"annotations\":[],\"parameters\":[]},\"request\":{\"consumes\":[\"text/plain\"],\"headerNames\":[\"header\"],\"headers\":{\"header\":[\"{0}\"]},\"method\":\"GET\",\"paramNames\":[],\"params\":{},\"path\":\"/header\",\"produces\":[\"text/plain\"]}}"); ServiceRestMetadata springRestMetadata = new ServiceRestMetadata(); springRestMetadata.setServiceInterface(service.getName()); ServiceRestMetadata springMetadata = instance.resolve(service, springRestMetadata); - List jsonsTmp = new ArrayList<>(); for (RestMethodMetadata restMethodMetadata : springMetadata.getMeta()) { restMethodMetadata.setReflectMethod(null); @@ -125,11 +122,9 @@ class SpringMvcServiceRestMetadataResolverTest { jsons.sort(comparator); jsonsTmp.sort(comparator); - for (int i = 0; i < jsons.size(); i++) { assertEquals(jsons.get(i), jsonsTmp.get(i)); } - } @Test @@ -146,15 +141,16 @@ class SpringMvcServiceRestMetadataResolverTest { springMetadata.setContextPathFromUrl("//context"); Assertions.assertEquals("/context", springMetadata.getContextPathFromUrl()); springMetadata.setPort(404); - Map pathContainPathVariableToServiceMap = springMetadata.getPathContainPathVariableToServiceMap(); + Map pathContainPathVariableToServiceMap = + springMetadata.getPathContainPathVariableToServiceMap(); for (PathMatcher pathMatcher : pathContainPathVariableToServiceMap.keySet()) { Assertions.assertTrue(pathMatcher.hasPathVariable()); Assertions.assertEquals(404, pathMatcher.getPort()); } - - Map pathUnContainPathVariableToServiceMap = springMetadata.getPathUnContainPathVariableToServiceMap(); + Map pathUnContainPathVariableToServiceMap = + springMetadata.getPathUnContainPathVariableToServiceMap(); for (PathMatcher pathMatcher : pathUnContainPathVariableToServiceMap.keySet()) { Assertions.assertFalse(pathMatcher.hasPathVariable()); diff --git a/dubbo-metadata/pom.xml b/dubbo-metadata/pom.xml index d201869db8..4ef046aa6a 100644 --- a/dubbo-metadata/pom.xml +++ b/dubbo-metadata/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-parent - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + - dubbo-metadata - pom - - dubbo-metadata-api - dubbo-metadata-rest - dubbo-metadata-definition-protobuf - dubbo-metadata-processor - dubbo-metadata-report-zookeeper - dubbo-metadata-report-redis - dubbo-metadata-report-nacos - + dubbo-metadata + pom + + dubbo-metadata-api + dubbo-metadata-rest + dubbo-metadata-definition-protobuf + dubbo-metadata-processor + dubbo-metadata-report-zookeeper + dubbo-metadata-report-redis + dubbo-metadata-report-nacos + - - - org.apache.dubbo - dubbo-test-check - ${project.parent.version} - test - - + + + org.apache.dubbo + dubbo-test-check + ${project.parent.version} + test + + diff --git a/dubbo-metrics/dubbo-metrics-api/pom.xml b/dubbo-metrics/dubbo-metrics-api/pom.xml index 3ee341dcba..9b92ba14d3 100644 --- a/dubbo-metrics/dubbo-metrics-api/pom.xml +++ b/dubbo-metrics/dubbo-metrics-api/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - org.apache.dubbo - dubbo-metrics - ${revision} - ../pom.xml - - dubbo-metrics-api - jar - ${project.artifactId} - The metrics module of dubbo project - - false - - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-event - ${project.parent.version} - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - - - io.micrometer - micrometer-core - - - com.tdunning - t-digest - - + + 4.0.0 + + org.apache.dubbo + dubbo-metrics + ${revision} + ../pom.xml + + dubbo-metrics-api + jar + ${project.artifactId} + The metrics module of dubbo project + + false + + + + org.apache.dubbo + dubbo-common + ${project.parent.version} + + + org.apache.dubbo + dubbo-metrics-event + ${project.parent.version} + + + org.apache.dubbo + dubbo-rpc-api + ${project.parent.version} + + + io.micrometer + micrometer-core + + + com.tdunning + t-digest + + diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/Pane.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/Pane.java index af7908d026..a7717c022f 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/Pane.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/Pane.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.aggregate; /** diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/SampleAggregatedEntry.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/SampleAggregatedEntry.java index d4e222b970..8c3fad51db 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/SampleAggregatedEntry.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/SampleAggregatedEntry.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.aggregate; - public class SampleAggregatedEntry { private Long count; diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/SlidingWindow.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/SlidingWindow.java index b8208bf3ee..6f5d013a6a 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/SlidingWindow.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/SlidingWindow.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.aggregate; import org.apache.dubbo.common.utils.Assert; @@ -110,7 +109,8 @@ public abstract class SlidingWindow { else if (paneStartInMs == oldPane.getStartInMs()) { return oldPane; } - // The pane has deprecated. To avoid the overhead of creating a new instance, reset the original pane directly. + // The pane has deprecated. To avoid the overhead of creating a new instance, reset the original pane + // directly. else if (paneStartInMs > oldPane.getStartInMs()) { if (updateLock.tryLock()) { try { diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/TimeWindowAggregator.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/TimeWindowAggregator.java index 082f563ebd..8dface2fba 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/TimeWindowAggregator.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/TimeWindowAggregator.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.aggregate; import java.util.List; @@ -61,7 +60,7 @@ public class TimeWindowAggregator { if (count > 0) { double avg = total / count; aggregatedEntry.setAvg(Math.round(avg * 100.0) / 100.0); - }else { + } else { aggregatedEntry.setAvg(0); } @@ -147,5 +146,4 @@ public class TimeWindowAggregator { return count.sum(); } } - } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/TimeWindowCounter.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/TimeWindowCounter.java index 8cf70c7fed..702e799cea 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/TimeWindowCounter.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/TimeWindowCounter.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.aggregate; import java.util.List; @@ -42,11 +41,13 @@ public class TimeWindowCounter { } public long bucketLivedSeconds() { - return TimeUnit.MILLISECONDS.toSeconds(this.slidingWindow.values().size() * this.slidingWindow.getPaneIntervalInMs()); + return TimeUnit.MILLISECONDS.toSeconds( + this.slidingWindow.values().size() * this.slidingWindow.getPaneIntervalInMs()); } public long bucketLivedMillSeconds() { - return this.slidingWindow.getIntervalInMs() - (System.currentTimeMillis() - this.slidingWindow.currentPane().getEndInMs()); + return this.slidingWindow.getIntervalInMs() + - (System.currentTimeMillis() - this.slidingWindow.currentPane().getEndInMs()); } public void increment() { diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/TimeWindowQuantile.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/TimeWindowQuantile.java index 10828a9190..040f543cbd 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/TimeWindowQuantile.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/TimeWindowQuantile.java @@ -14,14 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.aggregate; -import com.tdunning.math.stats.TDigest; - import java.util.List; import java.util.concurrent.TimeUnit; +import com.tdunning.math.stats.TDigest; + /** * Wrapper around TDigest. */ @@ -33,7 +32,8 @@ public class TimeWindowQuantile { public TimeWindowQuantile(double compression, int bucketNum, int timeWindowSeconds) { this.compression = compression; - this.slidingWindow = new DigestSlidingWindow(compression, bucketNum, TimeUnit.SECONDS.toMillis(timeWindowSeconds)); + this.slidingWindow = + new DigestSlidingWindow(compression, bucketNum, TimeUnit.SECONDS.toMillis(timeWindowSeconds)); } public double quantile(double q) { diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ApplicationMetricsCollector.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ApplicationMetricsCollector.java index cac0635f6f..63c996d0c2 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ApplicationMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ApplicationMetricsCollector.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.collector; import org.apache.dubbo.metrics.event.TimeCounterEvent; @@ -31,6 +30,4 @@ public interface ApplicationMetricsCollector extends void increment(MetricsKey metricsKey); void addApplicationRt(String registryOpType, Long responseTime); - } - diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/CombMetricsCollector.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/CombMetricsCollector.java index 1c3ba5b74d..becf811e9f 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/CombMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/CombMetricsCollector.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.collector; import org.apache.dubbo.metrics.data.BaseStatComposite; @@ -32,12 +31,12 @@ import java.util.List; import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE; -public abstract class CombMetricsCollector extends AbstractMetricsListener implements ApplicationMetricsCollector, ServiceMetricsCollector, MethodMetricsCollector { +public abstract class CombMetricsCollector extends AbstractMetricsListener + implements ApplicationMetricsCollector, ServiceMetricsCollector, MethodMetricsCollector { protected final BaseStatComposite stats; private MetricsEventMulticaster eventMulticaster; - public CombMetricsCollector(BaseStatComposite stats) { this.stats = stats; } @@ -80,16 +79,15 @@ public abstract class CombMetricsCollector extends A stats.calcMethodKeyRt(invocation, registryOpType, responseTime); } - public void setAppNum(MetricsKey metricsKey,Long num) { + public void setAppNum(MetricsKey metricsKey, Long num) { stats.setAppKey(metricsKey, num); } - + @Override public void increment(MethodMetric methodMetric, MetricsKeyWrapper wrapper, int size) { this.stats.incrementMethodKey(wrapper, methodMetric, size); } - @Override public void init(Invocation invocation, MetricsKeyWrapper wrapper) { this.stats.initMethodKey(wrapper, invocation); @@ -108,7 +106,6 @@ public abstract class CombMetricsCollector extends A eventMulticaster.publishEvent(event); } - @Override public void onEventFinish(TimeCounterEvent event) { eventMulticaster.publishFinishEvent(event); @@ -123,4 +120,3 @@ public abstract class CombMetricsCollector extends A return stats; } } - diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MethodMetricsCollector.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MethodMetricsCollector.java index db07746bc8..03f1becd04 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MethodMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MethodMetricsCollector.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.collector; import org.apache.dubbo.metrics.event.TimeCounterEvent; @@ -33,4 +32,3 @@ public interface MethodMetricsCollector extends Metr void init(Invocation invocation, MetricsKeyWrapper wrapper); } - diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MetricsCollector.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MetricsCollector.java index 19bd58bba9..0d61468f04 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MetricsCollector.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.collector; import org.apache.dubbo.common.extension.SPI; @@ -51,6 +50,6 @@ public interface MetricsCollector extends MetricsLif */ boolean calSamplesChanged(); - default void initMetrics(MetricsEvent event) {}; - + default void initMetrics(MetricsEvent event) {} + ; } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ServiceMetricsCollector.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ServiceMetricsCollector.java index fc269b87ab..699236f3fb 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ServiceMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/ServiceMetricsCollector.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.collector; import org.apache.dubbo.metrics.event.TimeCounterEvent; @@ -35,4 +34,3 @@ public interface ServiceMetricsCollector extends Met void addServiceRt(Invocation invocation, String registryOpType, Long responseTime); } - diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/stat/MetricsStatHandler.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/stat/MetricsStatHandler.java index 95567945d4..049d6b7313 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/stat/MetricsStatHandler.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/stat/MetricsStatHandler.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.collector.stat; import org.apache.dubbo.metrics.event.MetricsEvent; @@ -32,5 +31,4 @@ public interface MetricsStatHandler { MetricsEvent decrease(String applicationName, Invocation invocation); MetricsEvent addApplication(String applicationName); - } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/ApplicationStatComposite.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/ApplicationStatComposite.java index f022b431f5..3194ba5729 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/ApplicationStatComposite.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/ApplicationStatComposite.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.data; import org.apache.dubbo.common.utils.CollectionUtils; @@ -40,7 +39,6 @@ import java.util.concurrent.atomic.AtomicLong; */ public class ApplicationStatComposite extends AbstractMetricsExport { - public ApplicationStatComposite(ApplicationModel applicationModel) { super(applicationModel); } @@ -66,7 +64,7 @@ public class ApplicationStatComposite extends AbstractMetricsExport { applicationNumStats.get(metricsKey).getAndAdd(size); } - public void setAppKey(MetricsKey metricsKey, Long num){ + public void setAppKey(MetricsKey metricsKey, Long num) { if (!applicationNumStats.containsKey(metricsKey)) { return; } @@ -83,14 +81,14 @@ public class ApplicationStatComposite extends AbstractMetricsExport { @SuppressWarnings({"rawtypes"}) private GaugeMetricSample convertToSample(MetricsKey type, MetricsCategory category, AtomicLong targetNumber) { - return new GaugeMetricSample<>(type, MetricsSupport.applicationTags(getApplicationModel()), category, targetNumber, AtomicLong::get); + return new GaugeMetricSample<>( + type, MetricsSupport.applicationTags(getApplicationModel()), category, targetNumber, AtomicLong::get); } public Map getApplicationNumStats() { return applicationNumStats; } - @Override public boolean calSamplesChanged() { // CAS to get and reset the flag in an atomic operation diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/BaseStatComposite.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/BaseStatComposite.java index 810bb21f95..efb6852ffe 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/BaseStatComposite.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/BaseStatComposite.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.data; import org.apache.dubbo.metrics.collector.MetricsCollector; @@ -33,7 +32,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; - /** * As a data aggregator, use internal data containers calculates and classifies * the registry data collected by {@link MetricsCollector MetricsCollector}, and @@ -47,7 +45,6 @@ public abstract class BaseStatComposite implements MetricsExport { private MethodStatComposite methodStatComposite; private RtStatComposite rtStatComposite; - public BaseStatComposite(ApplicationModel applicationModel) { init(new ApplicationStatComposite(applicationModel)); init(new ServiceStatComposite(applicationModel)); @@ -55,7 +52,6 @@ public abstract class BaseStatComposite implements MetricsExport { init(new RtStatComposite(applicationModel)); } - protected void init(ApplicationStatComposite applicationStatComposite) { this.applicationStatComposite = applicationStatComposite; } @@ -73,11 +69,13 @@ public abstract class BaseStatComposite implements MetricsExport { } public void calcApplicationRt(String registryOpType, Long responseTime) { - rtStatComposite.calcServiceKeyRt(registryOpType, responseTime, new ApplicationMetric(rtStatComposite.getApplicationModel())); + rtStatComposite.calcServiceKeyRt( + registryOpType, responseTime, new ApplicationMetric(rtStatComposite.getApplicationModel())); } public void calcServiceKeyRt(String serviceKey, String registryOpType, Long responseTime) { - rtStatComposite.calcServiceKeyRt(registryOpType, responseTime, new ServiceKeyMetric(rtStatComposite.getApplicationModel(), serviceKey)); + rtStatComposite.calcServiceKeyRt( + registryOpType, responseTime, new ServiceKeyMetric(rtStatComposite.getApplicationModel(), serviceKey)); } public void calcServiceKeyRt(Invocation invocation, String registryOpType, Long responseTime) { @@ -104,7 +102,8 @@ public abstract class BaseStatComposite implements MetricsExport { serviceStatComposite.incrementServiceKey(metricsKeyWrapper, attServiceKey, size); } - public void incrementServiceKey(MetricsKeyWrapper metricsKeyWrapper, String attServiceKey, Map extra, int size) { + public void incrementServiceKey( + MetricsKeyWrapper metricsKeyWrapper, String attServiceKey, Map extra, int size) { serviceStatComposite.incrementExtraServiceKey(metricsKeyWrapper, attServiceKey, extra, size); } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/MethodStatComposite.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/MethodStatComposite.java index 1e26b7e25c..a06751553e 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/MethodStatComposite.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/MethodStatComposite.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.data; import org.apache.dubbo.common.utils.CollectionUtils; @@ -68,7 +67,10 @@ public class MethodStatComposite extends AbstractMetricsExport { return; } - methodNumStats.get(wrapper).computeIfAbsent(new MethodMetric(getApplicationModel(), invocation, serviceLevel), k -> new AtomicLong(0L)); + methodNumStats + .get(wrapper) + .computeIfAbsent( + new MethodMetric(getApplicationModel(), invocation, serviceLevel), k -> new AtomicLong(0L)); samplesChanged.set(true); } @@ -78,12 +80,12 @@ public class MethodStatComposite extends AbstractMetricsExport { } AtomicLong stat = methodNumStats.get(wrapper).get(methodMetric); if (stat == null) { - methodNumStats.get(wrapper).computeIfAbsent(methodMetric, (k)-> new AtomicLong(0L)); + methodNumStats.get(wrapper).computeIfAbsent(methodMetric, (k) -> new AtomicLong(0L)); samplesChanged.set(true); stat = methodNumStats.get(wrapper).get(methodMetric); } stat.getAndAdd(size); -// MetricsSupport.fillZero(methodNumStats); + // MetricsSupport.fillZero(methodNumStats); } public List export(MetricsCategory category) { @@ -92,14 +94,16 @@ public class MethodStatComposite extends AbstractMetricsExport { Map stringAtomicLongMap = methodNumStats.get(wrapper); for (MethodMetric methodMetric : stringAtomicLongMap.keySet()) { if (wrapper.getSampleType() == MetricSample.Type.COUNTER) { - list.add(new CounterMetricSample<>(wrapper, - methodMetric.getTags(), category, stringAtomicLongMap.get(methodMetric))); + list.add(new CounterMetricSample<>( + wrapper, methodMetric.getTags(), category, stringAtomicLongMap.get(methodMetric))); } else if (wrapper.getSampleType() == MetricSample.Type.GAUGE) { - list.add(new GaugeMetricSample<>(wrapper, methodMetric.getTags(), category, stringAtomicLongMap, value -> value.get(methodMetric).get())); + list.add(new GaugeMetricSample<>( + wrapper, methodMetric.getTags(), category, stringAtomicLongMap, value -> value.get( + methodMetric) + .get())); } else { throw new MetricsNeverHappenException("Unsupported metricSample type: " + wrapper.getSampleType()); } - } } return list; diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/RtStatComposite.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/RtStatComposite.java index 878349542b..8ac99e1667 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/RtStatComposite.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/RtStatComposite.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.data; import org.apache.dubbo.metrics.model.MethodMetric; @@ -69,7 +68,8 @@ public class RtStatComposite extends AbstractMetricsExport { for (MetricsPlaceValue placeValue : placeValues) { List> containers = initStats(placeValue); for (LongContainer container : containers) { - rtStats.computeIfAbsent(container.getMetricsKeyWrapper().getType(), k -> new ArrayList<>()).add(container); + rtStats.computeIfAbsent(container.getMetricsKeyWrapper().getType(), k -> new ArrayList<>()) + .add(container); } } samplesChanged.set(true); @@ -78,13 +78,24 @@ public class RtStatComposite extends AbstractMetricsExport { private List> initStats(MetricsPlaceValue placeValue) { List> singleRtStats = new ArrayList<>(); singleRtStats.add(new AtomicLongContainer(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, placeValue))); - singleRtStats.add(new LongAccumulatorContainer(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, placeValue), new LongAccumulator(Long::min, Long.MAX_VALUE))); - singleRtStats.add(new LongAccumulatorContainer(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, placeValue), new LongAccumulator(Long::max, Long.MIN_VALUE))); - singleRtStats.add(new AtomicLongContainer(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, placeValue), (responseTime, longAccumulator) -> longAccumulator.addAndGet(responseTime))); + singleRtStats.add(new LongAccumulatorContainer( + new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, placeValue), + new LongAccumulator(Long::min, Long.MAX_VALUE))); + singleRtStats.add(new LongAccumulatorContainer( + new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, placeValue), + new LongAccumulator(Long::max, Long.MIN_VALUE))); + singleRtStats.add(new AtomicLongContainer( + new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, placeValue), + (responseTime, longAccumulator) -> longAccumulator.addAndGet(responseTime))); // AvgContainer is a special counter that stores the number of times but outputs function of sum/times - AtomicLongContainer avgContainer = new AtomicLongContainer(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, placeValue), (k, v) -> v.incrementAndGet()); + AtomicLongContainer avgContainer = new AtomicLongContainer( + new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, placeValue), (k, v) -> v.incrementAndGet()); avgContainer.setValueSupplier(applicationName -> { - LongContainer totalContainer = rtStats.values().stream().flatMap(List::stream).filter(longContainer -> longContainer.isKeyWrapper(MetricsKey.METRIC_RT_SUM, placeValue.getType())).findFirst().get(); + LongContainer totalContainer = rtStats.values().stream() + .flatMap(List::stream) + .filter(longContainer -> longContainer.isKeyWrapper(MetricsKey.METRIC_RT_SUM, placeValue.getType())) + .findFirst() + .get(); AtomicLong totalRtTimes = avgContainer.get(applicationName); AtomicLong totalRtSum = (AtomicLong) totalContainer.get(applicationName); return totalRtSum.get() / totalRtTimes.get(); @@ -108,7 +119,8 @@ public class RtStatComposite extends AbstractMetricsExport { public void calcServiceKeyRt(Invocation invocation, String registryOpType, Long responseTime) { List actions; if (invocation.getServiceModel() != null && invocation.getServiceModel().getServiceKey() != null) { - Map attributeMap = invocation.getServiceModel().getServiceMetadata().getAttributeMap(); + Map attributeMap = + invocation.getServiceModel().getServiceMetadata().getAttributeMap(); Map> cache = (Map>) attributeMap.get("ServiceKeyRt"); if (cache == null) { attributeMap.putIfAbsent("ServiceKeyRt", new ConcurrentHashMap<>(32)); @@ -151,7 +163,8 @@ public class RtStatComposite extends AbstractMetricsExport { List actions; if (invocation.getServiceModel() != null && invocation.getServiceModel().getServiceMetadata() != null) { - Map attributeMap = invocation.getServiceModel().getServiceMetadata().getAttributeMap(); + Map attributeMap = + invocation.getServiceModel().getServiceMetadata().getAttributeMap(); Map> cache = (Map>) attributeMap.get("MethodKeyRt"); if (cache == null) { attributeMap.putIfAbsent("MethodKeyRt", new ConcurrentHashMap<>(32)); @@ -195,13 +208,15 @@ public class RtStatComposite extends AbstractMetricsExport { for (LongContainer container : containers) { MetricsKeyWrapper metricsKeyWrapper = container.getMetricsKeyWrapper(); for (Metric key : container.keySet()) { - // Use keySet to obtain the original key instance reference of ConcurrentHashMap to avoid early recycling of the micrometer - list.add(new GaugeMetricSample<>(metricsKeyWrapper.targetKey(), - metricsKeyWrapper.targetDesc(), - key.getTags(), - category, - key, - value -> container.getValueSupplier().apply(value))); + // Use keySet to obtain the original key instance reference of ConcurrentHashMap to avoid early + // recycling of the micrometer + list.add(new GaugeMetricSample<>( + metricsKeyWrapper.targetKey(), + metricsKeyWrapper.targetDesc(), + key.getTags(), + category, + key, + value -> container.getValueSupplier().apply(value))); } } } @@ -212,7 +227,6 @@ public class RtStatComposite extends AbstractMetricsExport { return rtStats.values().stream().flatMap(List::stream).collect(Collectors.toList()); } - private static class Action { private final BiConsumer consumerFunc; private final Number initValue; diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/ServiceStatComposite.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/ServiceStatComposite.java index 1cf214293e..0a63ad87ee 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/ServiceStatComposite.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/ServiceStatComposite.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.data; import org.apache.dubbo.common.utils.CollectionUtils; @@ -46,7 +45,8 @@ public class ServiceStatComposite extends AbstractMetricsExport { super(applicationModel); } - private final Map> serviceWrapperNumStats = new ConcurrentHashMap<>(); + private final Map> serviceWrapperNumStats = + new ConcurrentHashMap<>(); public void initWrapper(List metricsKeyWrappers) { if (CollectionUtils.isEmpty(metricsKeyWrappers)) { @@ -62,7 +62,8 @@ public class ServiceStatComposite extends AbstractMetricsExport { incrementExtraServiceKey(wrapper, serviceKey, null, size); } - public void incrementExtraServiceKey(MetricsKeyWrapper wrapper, String serviceKey, Map extra, int size) { + public void incrementExtraServiceKey( + MetricsKeyWrapper wrapper, String serviceKey, Map extra, int size) { if (!serviceWrapperNumStats.containsKey(wrapper)) { return; } @@ -77,7 +78,7 @@ public class ServiceStatComposite extends AbstractMetricsExport { samplesChanged.set(true); } metrics.getAndAdd(size); -// MetricsSupport.fillZero(serviceWrapperNumStats); + // MetricsSupport.fillZero(serviceWrapperNumStats); } public void setServiceKey(MetricsKeyWrapper wrapper, String serviceKey, int num) { @@ -107,7 +108,10 @@ public class ServiceStatComposite extends AbstractMetricsExport { for (MetricsKeyWrapper wrapper : serviceWrapperNumStats.keySet()) { Map stringAtomicLongMap = serviceWrapperNumStats.get(wrapper); for (ServiceKeyMetric serviceKeyMetric : stringAtomicLongMap.keySet()) { - list.add(new GaugeMetricSample<>(wrapper, serviceKeyMetric.getTags(), category, stringAtomicLongMap, value -> value.get(serviceKeyMetric).get())); + list.add(new GaugeMetricSample<>( + wrapper, serviceKeyMetric.getTags(), category, stringAtomicLongMap, value -> value.get( + serviceKeyMetric) + .get())); } } return list; diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsDispatcher.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsDispatcher.java index eebe2011f3..1a976cf875 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsDispatcher.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsDispatcher.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.event; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; @@ -34,13 +33,11 @@ public class MetricsDispatcher extends SimpleMetricsEventMulticaster { ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); ExtensionLoader extensionLoader = applicationModel.getExtensionLoader(MetricsCollector.class); if (extensionLoader != null) { - List customizeCollectors = extensionLoader - .getActivateExtensions(); + List customizeCollectors = extensionLoader.getActivateExtensions(); for (MetricsCollector customizeCollector : customizeCollectors) { beanFactory.registerBean(customizeCollector); } customizeCollectors.forEach(this::addListener); } } - } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsInitEvent.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsInitEvent.java index bb01c88d7e..864cc3c174 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsInitEvent.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsInitEvent.java @@ -14,8 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.event; + import org.apache.dubbo.metrics.MetricsConstants; import org.apache.dubbo.metrics.model.MethodMetric; import org.apache.dubbo.metrics.model.MetricsSupport; @@ -23,6 +23,7 @@ import org.apache.dubbo.metrics.model.key.MetricsLevel; import org.apache.dubbo.metrics.model.key.TypeWrapper; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.model.ApplicationModel; + import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_SERVICE; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS; @@ -30,11 +31,12 @@ public class MetricsInitEvent extends TimeCounterEvent { private static final TypeWrapper METRIC_EVENT = new TypeWrapper(MetricsLevel.SERVICE, METRIC_REQUESTS); - public MetricsInitEvent(ApplicationModel source,TypeWrapper typeWrapper) { - super(source,typeWrapper); + public MetricsInitEvent(ApplicationModel source, TypeWrapper typeWrapper) { + super(source, typeWrapper); } - public static MetricsInitEvent toMetricsInitEvent(ApplicationModel applicationModel, Invocation invocation, boolean serviceLevel) { + public static MetricsInitEvent toMetricsInitEvent( + ApplicationModel applicationModel, Invocation invocation, boolean serviceLevel) { MethodMetric methodMetric = new MethodMetric(applicationModel, invocation, serviceLevel); MetricsInitEvent initEvent = new MetricsInitEvent(applicationModel, METRIC_EVENT); initEvent.putAttachment(MetricsConstants.INVOCATION, invocation); @@ -43,6 +45,4 @@ public class MetricsInitEvent extends TimeCounterEvent { initEvent.putAttachment(MetricsConstants.INVOCATION_SIDE, MetricsSupport.getSide(invocation)); return initEvent; } - - } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticaster.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticaster.java index ed172de6ee..bfc8ae2b91 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticaster.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticaster.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.event; import org.apache.dubbo.common.utils.StringUtils; diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsKeyListener.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsKeyListener.java index 2ba791e0e1..516ce04ae4 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsKeyListener.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsKeyListener.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.listener; import org.apache.dubbo.metrics.event.MetricsEvent; @@ -29,7 +28,8 @@ import java.util.function.Consumer; * build a consistent static method for general and custom monitoring consume methods * */ -public abstract class AbstractMetricsKeyListener extends AbstractMetricsListener implements MetricsLifeListener { +public abstract class AbstractMetricsKeyListener extends AbstractMetricsListener + implements MetricsLifeListener { private final MetricsKey metricsKey; @@ -46,9 +46,7 @@ public abstract class AbstractMetricsKeyListener extends AbstractMetricsListener } @Override - public void onEvent(TimeCounterEvent event) { - - } + public void onEvent(TimeCounterEvent event) {} public static AbstractMetricsKeyListener onEvent(MetricsKey metricsKey, Consumer postFunc) { @@ -79,6 +77,4 @@ public abstract class AbstractMetricsKeyListener extends AbstractMetricsListener } }; } - - } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsListener.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsListener.java index 7dc5ed2f77..dce4a8b207 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsListener.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/AbstractMetricsListener.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.listener; import org.apache.dubbo.common.utils.ReflectionUtils; @@ -31,8 +30,8 @@ public abstract class AbstractMetricsListener implements * Whether to support the general determination of event points depends on the event type */ public boolean isSupport(MetricsEvent event) { - Boolean eventMatch = eventMatchCache.computeIfAbsent(event.getClass(), - clazz -> ReflectionUtils.match(getClass(), AbstractMetricsListener.class, event)); + Boolean eventMatch = eventMatchCache.computeIfAbsent( + event.getClass(), clazz -> ReflectionUtils.match(getClass(), AbstractMetricsListener.class, event)); return event.isAvailable() && eventMatch; } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsApplicationListener.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsApplicationListener.java index 96891e6bb0..018889ec2a 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsApplicationListener.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsApplicationListener.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.listener; import org.apache.dubbo.metrics.collector.CombMetricsCollector; @@ -38,10 +37,9 @@ public class MetricsApplicationListener extends AbstractMetricsKeyListener { * @param metricsKey Monitor key * @param collector Corresponding collector */ - public static AbstractMetricsKeyListener onPostEventBuild(MetricsKey metricsKey, CombMetricsCollector collector) { - return AbstractMetricsKeyListener.onEvent(metricsKey, - event -> collector.increment(metricsKey) - ); + public static AbstractMetricsKeyListener onPostEventBuild( + MetricsKey metricsKey, CombMetricsCollector collector) { + return AbstractMetricsKeyListener.onEvent(metricsKey, event -> collector.increment(metricsKey)); } /** @@ -51,24 +49,22 @@ public class MetricsApplicationListener extends AbstractMetricsKeyListener { * @param metricsKey Monitor key * @param collector Corresponding collector */ - public static AbstractMetricsKeyListener onFinishEventBuild(MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { - return AbstractMetricsKeyListener.onFinish(metricsKey, - event -> { - collector.increment(metricsKey); - collector.addApplicationRt(placeType.getType(), event.getTimePair().calc()); - } - ); + public static AbstractMetricsKeyListener onFinishEventBuild( + MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { + return AbstractMetricsKeyListener.onFinish(metricsKey, event -> { + collector.increment(metricsKey); + collector.addApplicationRt(placeType.getType(), event.getTimePair().calc()); + }); } /** * Similar to onFinishEventBuild */ - public static AbstractMetricsKeyListener onErrorEventBuild(MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { - return AbstractMetricsKeyListener.onError(metricsKey, - event -> { - collector.increment(metricsKey); - collector.addApplicationRt(placeType.getType(), event.getTimePair().calc()); - } - ); + public static AbstractMetricsKeyListener onErrorEventBuild( + MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { + return AbstractMetricsKeyListener.onError(metricsKey, event -> { + collector.increment(metricsKey); + collector.addApplicationRt(placeType.getType(), event.getTimePair().calc()); + }); } } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsLifeListener.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsLifeListener.java index 294be1885a..67dd2ad8fd 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsLifeListener.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsLifeListener.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.listener; import org.apache.dubbo.metrics.event.TimeCounterEvent; @@ -24,9 +23,7 @@ import org.apache.dubbo.metrics.event.TimeCounterEvent; */ public interface MetricsLifeListener extends MetricsListener { - default void onEventFinish(E event) { - } + default void onEventFinish(E event) {} - default void onEventError(E event) { - } + default void onEventError(E event) {} } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsServiceListener.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsServiceListener.java index 40f27b18ca..49fa8c783f 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsServiceListener.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/listener/MetricsServiceListener.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.listener; import org.apache.dubbo.metrics.collector.ServiceMetricsCollector; @@ -34,22 +33,21 @@ public class MetricsServiceListener extends AbstractMetricsKeyListener { super(metricsKey); } - public static AbstractMetricsKeyListener onPostEventBuild(MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector collector) { - return AbstractMetricsKeyListener.onEvent(metricsKey, - event -> MetricsSupport.increment(metricsKey, placeType, collector, event) - ); + public static AbstractMetricsKeyListener onPostEventBuild( + MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector collector) { + return AbstractMetricsKeyListener.onEvent( + metricsKey, event -> MetricsSupport.increment(metricsKey, placeType, collector, event)); } - public static AbstractMetricsKeyListener onFinishEventBuild(MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector collector) { - return AbstractMetricsKeyListener.onFinish(metricsKey, - event -> MetricsSupport.incrAndAddRt(metricsKey, placeType, collector, event) - ); + public static AbstractMetricsKeyListener onFinishEventBuild( + MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector collector) { + return AbstractMetricsKeyListener.onFinish( + metricsKey, event -> MetricsSupport.incrAndAddRt(metricsKey, placeType, collector, event)); } - public static AbstractMetricsKeyListener onErrorEventBuild(MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector collector) { - return AbstractMetricsKeyListener.onError(metricsKey, - event -> MetricsSupport.incrAndAddRt(metricsKey, placeType, collector, event) - ); + public static AbstractMetricsKeyListener onErrorEventBuild( + MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector collector) { + return AbstractMetricsKeyListener.onError( + metricsKey, event -> MetricsSupport.incrAndAddRt(metricsKey, placeType, collector, event)); } - } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ApplicationMetric.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ApplicationMetric.java index c6d2734a8a..85041ebf93 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ApplicationMetric.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ApplicationMetric.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.model; import org.apache.dubbo.rpc.model.ApplicationModel; @@ -51,7 +50,6 @@ public class ApplicationMetric implements Metric { return MetricsSupport.hostTags(tags); } - public Map getExtraInfo() { return extraInfo; } @@ -69,7 +67,8 @@ public class ApplicationMetric implements Metric { return false; } ApplicationMetric that = (ApplicationMetric) o; - return getApplicationName().equals(that.applicationModel.getApplicationName()) && Objects.equals(extraInfo, that.extraInfo); + return getApplicationName().equals(that.applicationModel.getApplicationName()) + && Objects.equals(extraInfo, that.extraInfo); } private volatile int hashCode; @@ -81,5 +80,4 @@ public class ApplicationMetric implements Metric { } return hashCode; } - } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ConfigCenterMetric.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ConfigCenterMetric.java index a6f9987e03..b778e2efc4 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ConfigCenterMetric.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ConfigCenterMetric.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.model; import java.util.HashMap; @@ -39,11 +38,10 @@ public class ConfigCenterMetric implements Metric { private String configCenter; private String changeType; - public ConfigCenterMetric() { + public ConfigCenterMetric() {} - } - - public ConfigCenterMetric(String applicationName, String key, String group, String configCenter, String changeType) { + public ConfigCenterMetric( + String applicationName, String key, String group, String configCenter, String changeType) { this.applicationName = applicationName; this.key = key; this.group = group; @@ -73,8 +71,7 @@ public class ConfigCenterMetric implements Metric { ConfigCenterMetric that = (ConfigCenterMetric) o; - if (!Objects.equals(applicationName, that.applicationName)) - return false; + if (!Objects.equals(applicationName, that.applicationName)) return false; if (!Objects.equals(key, that.key)) return false; if (!Objects.equals(group, that.group)) return false; if (!Objects.equals(configCenter, that.configCenter)) return false; diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ErrorCodeMetric.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ErrorCodeMetric.java index 6553761783..3ed57483c8 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ErrorCodeMetric.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ErrorCodeMetric.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.model; import java.util.HashMap; diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MethodMetric.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MethodMetric.java index 6f4ddfffcf..6d3238d15a 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MethodMetric.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MethodMetric.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.model; import org.apache.dubbo.common.utils.StringUtils; @@ -41,7 +40,6 @@ public class MethodMetric extends ServiceKeyMetric { private String group; private String version; - public MethodMetric(ApplicationModel applicationModel, Invocation invocation, boolean serviceLevel) { super(applicationModel, MetricsSupport.getInterfaceName(invocation)); this.side = MetricsSupport.getSide(invocation); @@ -50,9 +48,8 @@ public class MethodMetric extends ServiceKeyMetric { this.methodName = serviceLevel ? null : RpcUtils.getMethodName(invocation); } - public static boolean isServiceLevel(ApplicationModel applicationModel) { - if(applicationModel == null){ + if (applicationModel == null) { return false; } ConfigManager applicationConfigManager = applicationModel.getApplicationConfigManager(); @@ -105,14 +102,13 @@ public class MethodMetric extends ServiceKeyMetric { @Override public String toString() { - return "MethodMetric{" + - "applicationName='" + getApplicationName() + '\'' + - ", side='" + side + '\'' + - ", interfaceName='" + getServiceKey() + '\'' + - ", methodName='" + methodName + '\'' + - ", group='" + group + '\'' + - ", version='" + version + '\'' + - '}'; + return "MethodMetric{" + "applicationName='" + + getApplicationName() + '\'' + ", side='" + + side + '\'' + ", interfaceName='" + + getServiceKey() + '\'' + ", methodName='" + + methodName + '\'' + ", group='" + + group + '\'' + ", version='" + + version + '\'' + '}'; } @Override @@ -120,7 +116,12 @@ public class MethodMetric extends ServiceKeyMetric { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MethodMetric that = (MethodMetric) o; - return Objects.equals(getApplicationModel(), that.getApplicationModel()) && Objects.equals(side, that.side) && Objects.equals(getServiceKey(), that.getServiceKey()) && Objects.equals(methodName, that.methodName) && Objects.equals(group, that.group) && Objects.equals(version, that.version); + return Objects.equals(getApplicationModel(), that.getApplicationModel()) + && Objects.equals(side, that.side) + && Objects.equals(getServiceKey(), that.getServiceKey()) + && Objects.equals(methodName, that.methodName) + && Objects.equals(group, that.group) + && Objects.equals(version, that.version); } private volatile int hashCode = 0; diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/Metric.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/Metric.java index c9baa9c0da..891bd356f1 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/Metric.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/Metric.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.model; import java.util.Map; diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsCategory.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsCategory.java index 66d5d8b492..3538f68705 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsCategory.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsCategory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.model; /** diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsSupport.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsSupport.java index ed723192e5..dc7b9e5aa2 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsSupport.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsSupport.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.model; import org.apache.dubbo.common.Version; @@ -33,10 +32,10 @@ import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.ApplicationModel; -import java.util.Map; import java.util.HashMap; -import java.util.Set; +import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; @@ -63,12 +62,12 @@ public class MetricsSupport { private static final String commitId = Version.getLastCommitId(); - public static Map applicationTags(ApplicationModel applicationModel) { return applicationTags(applicationModel, null); } - public static Map applicationTags(ApplicationModel applicationModel, @Nullable Map extraInfo) { + public static Map applicationTags( + ApplicationModel applicationModel, @Nullable Map extraInfo) { Map tags = new HashMap<>(); tags.put(TAG_APPLICATION_NAME, applicationModel.getApplicationName()); tags.put(TAG_APPLICATION_MODULE, applicationModel.getInternalId()); @@ -77,24 +76,28 @@ public class MetricsSupport { } return tags; } + public static Map gitTags(Map tags) { tags.put(MetricsKey.METADATA_GIT_COMMITID_METRIC.getName(), commitId); tags.put(TAG_APPLICATION_VERSION_KEY, version); return tags; } - public static Map hostTags( Map tags) { + + public static Map hostTags(Map tags) { tags.put(TAG_IP, getLocalHost()); tags.put(TAG_HOSTNAME, getLocalHostName()); return tags; } - public static Map serviceTags(ApplicationModel applicationModel, String serviceKey, Map extraInfo) { + public static Map serviceTags( + ApplicationModel applicationModel, String serviceKey, Map extraInfo) { Map tags = applicationTags(applicationModel, extraInfo); tags.put(TAG_INTERFACE_KEY, serviceKey); return tags; } - public static Map methodTags(ApplicationModel applicationModel, String serviceKey, String methodName) { + public static Map methodTags( + ApplicationModel applicationModel, String serviceKey, String methodName) { Map tags = applicationTags(applicationModel); tags.put(TAG_INTERFACE_KEY, serviceKey); tags.put(TAG_METHOD_KEY, methodName); @@ -156,7 +159,6 @@ public class MetricsSupport { return invoker.isPresent() ? invoker.get().getUrl().getSide() : PROVIDER_SIDE; } - public static String getInterfaceName(Invocation invocation) { if (invocation.getServiceModel() != null && invocation.getServiceModel().getServiceMetadata() != null) { return invocation.getServiceModel().getServiceMetadata().getServiceInterfaceName(); @@ -210,48 +212,93 @@ public class MetricsSupport { /** * Incr service num */ - public static void increment(MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector collector, MetricsEvent event) { - collector.increment(event.getAttachmentValue(ATTACHMENT_KEY_SERVICE), new MetricsKeyWrapper(metricsKey, placeType), SELF_INCREMENT_SIZE); + public static void increment( + MetricsKey metricsKey, + MetricsPlaceValue placeType, + ServiceMetricsCollector collector, + MetricsEvent event) { + collector.increment( + event.getAttachmentValue(ATTACHMENT_KEY_SERVICE), + new MetricsKeyWrapper(metricsKey, placeType), + SELF_INCREMENT_SIZE); } /** * Incr service num&&rt */ - public static void incrAndAddRt(MetricsKey metricsKey, MetricsPlaceValue placeType, ServiceMetricsCollector collector, TimeCounterEvent event) { - collector.increment(event.getAttachmentValue(ATTACHMENT_KEY_SERVICE), new MetricsKeyWrapper(metricsKey, placeType), SELF_INCREMENT_SIZE); + public static void incrAndAddRt( + MetricsKey metricsKey, + MetricsPlaceValue placeType, + ServiceMetricsCollector collector, + TimeCounterEvent event) { + collector.increment( + event.getAttachmentValue(ATTACHMENT_KEY_SERVICE), + new MetricsKeyWrapper(metricsKey, placeType), + SELF_INCREMENT_SIZE); Invocation invocation = event.getAttachmentValue(INVOCATION); if (invocation != null) { - collector.addServiceRt(invocation, placeType.getType(), event.getTimePair().calc()); + collector.addServiceRt( + invocation, placeType.getType(), event.getTimePair().calc()); } else { - collector.addServiceRt((String) event.getAttachmentValue(ATTACHMENT_KEY_SERVICE), placeType.getType(), event.getTimePair().calc()); + collector.addServiceRt( + (String) event.getAttachmentValue(ATTACHMENT_KEY_SERVICE), + placeType.getType(), + event.getTimePair().calc()); } } /** * Incr method num */ - public static void increment(MetricsKey metricsKey, MetricsPlaceValue placeType, MethodMetricsCollector collector, MetricsEvent event) { - collector.increment(event.getAttachmentValue(METHOD_METRICS), new MetricsKeyWrapper(metricsKey, placeType), SELF_INCREMENT_SIZE); + public static void increment( + MetricsKey metricsKey, + MetricsPlaceValue placeType, + MethodMetricsCollector collector, + MetricsEvent event) { + collector.increment( + event.getAttachmentValue(METHOD_METRICS), + new MetricsKeyWrapper(metricsKey, placeType), + SELF_INCREMENT_SIZE); } - - public static void init(MetricsKey metricsKey, MetricsPlaceValue placeType, MethodMetricsCollector collector, MetricsEvent event) { + public static void init( + MetricsKey metricsKey, + MetricsPlaceValue placeType, + MethodMetricsCollector collector, + MetricsEvent event) { collector.init(event.getAttachmentValue(INVOCATION), new MetricsKeyWrapper(metricsKey, placeType)); } /** * Dec method num */ - public static void dec(MetricsKey metricsKey, MetricsPlaceValue placeType, MethodMetricsCollector collector, MetricsEvent event) { - collector.increment(event.getAttachmentValue(METHOD_METRICS), new MetricsKeyWrapper(metricsKey, placeType), -SELF_INCREMENT_SIZE); + public static void dec( + MetricsKey metricsKey, + MetricsPlaceValue placeType, + MethodMetricsCollector collector, + MetricsEvent event) { + collector.increment( + event.getAttachmentValue(METHOD_METRICS), + new MetricsKeyWrapper(metricsKey, placeType), + -SELF_INCREMENT_SIZE); } /** * Incr method num&&rt */ - public static void incrAndAddRt(MetricsKey metricsKey, MetricsPlaceValue placeType, MethodMetricsCollector collector, TimeCounterEvent event) { - collector.increment(event.getAttachmentValue(METHOD_METRICS), new MetricsKeyWrapper(metricsKey, placeType), SELF_INCREMENT_SIZE); - collector.addMethodRt(event.getAttachmentValue(INVOCATION), placeType.getType(), event.getTimePair().calc()); + public static void incrAndAddRt( + MetricsKey metricsKey, + MetricsPlaceValue placeType, + MethodMetricsCollector collector, + TimeCounterEvent event) { + collector.increment( + event.getAttachmentValue(METHOD_METRICS), + new MetricsKeyWrapper(metricsKey, placeType), + SELF_INCREMENT_SIZE); + collector.addMethodRt( + event.getAttachmentValue(INVOCATION), + placeType.getType(), + event.getTimePair().calc()); } /** @@ -261,13 +308,12 @@ public class MetricsSupport { if (CollectionUtils.isEmptyMap(data)) { return; } - Set allKeyMetrics = data.values().stream().flatMap(map -> map.keySet().stream()).collect(Collectors.toSet()); - data.forEach((keyWrapper, mapVal) -> - { + Set allKeyMetrics = + data.values().stream().flatMap(map -> map.keySet().stream()).collect(Collectors.toSet()); + data.forEach((keyWrapper, mapVal) -> { for (T key : allKeyMetrics) { mapVal.computeIfAbsent(key, k -> new AtomicLong(0)); } }); - } } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ServiceKeyMetric.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ServiceKeyMetric.java index 361fd9f06e..133be3bcbd 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ServiceKeyMetric.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ServiceKeyMetric.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.model; import org.apache.dubbo.rpc.model.ApplicationModel; @@ -54,7 +53,6 @@ public class ServiceKeyMetric extends ApplicationMetric { return serviceKey.equals(that.serviceKey) && Objects.equals(extraInfo, that.extraInfo); } - private volatile int hashCode = 0; @Override @@ -67,9 +65,8 @@ public class ServiceKeyMetric extends ApplicationMetric { @Override public String toString() { - return "ServiceKeyMetric{" + - "applicationName='" + getApplicationName() + '\'' + - ", serviceKey='" + serviceKey + '\'' + - '}'; + return "ServiceKeyMetric{" + "applicationName='" + + getApplicationName() + '\'' + ", serviceKey='" + + serviceKey + '\'' + '}'; } } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ThreadPoolMetric.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ThreadPoolMetric.java index c45815f106..95550d617f 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ThreadPoolMetric.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ThreadPoolMetric.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.model; import org.apache.dubbo.common.utils.ConfigUtils; @@ -24,23 +23,22 @@ import java.util.Map; import java.util.Objects; import java.util.concurrent.ThreadPoolExecutor; - +import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME; +import static org.apache.dubbo.common.constants.MetricsConstants.TAG_HOSTNAME; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_IP; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_PID; -import static org.apache.dubbo.common.constants.MetricsConstants.TAG_HOSTNAME; -import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_THREAD_NAME; import static org.apache.dubbo.common.utils.NetUtils.getLocalHost; import static org.apache.dubbo.common.utils.NetUtils.getLocalHostName; -public class ThreadPoolMetric implements Metric{ +public class ThreadPoolMetric implements Metric { private String applicationName; private String threadPoolName; private ThreadPoolExecutor threadPoolExecutor; - + public ThreadPoolMetric(String applicationName, String threadPoolName, ThreadPoolExecutor threadPoolExecutor) { this.applicationName = applicationName; this.threadPoolExecutor = threadPoolExecutor; @@ -76,8 +74,8 @@ public class ThreadPoolMetric implements Metric{ if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ThreadPoolMetric that = (ThreadPoolMetric) o; - return Objects.equals(applicationName, that.applicationName) && - Objects.equals(threadPoolName, that.threadPoolName); + return Objects.equals(applicationName, that.applicationName) + && Objects.equals(threadPoolName, that.threadPoolName); } @Override @@ -89,7 +87,7 @@ public class ThreadPoolMetric implements Metric{ public Map getTags() { Map tags = new HashMap<>(); tags.put(TAG_IP, getLocalHost()); - tags.put(TAG_PID, ConfigUtils.getPid()+""); + tags.put(TAG_PID, ConfigUtils.getPid() + ""); tags.put(TAG_HOSTNAME, getLocalHostName()); tags.put(TAG_APPLICATION_NAME, applicationName); tags.put(TAG_THREAD_NAME, threadPoolName); @@ -112,12 +110,11 @@ public class ThreadPoolMetric implements Metric{ return threadPoolExecutor.getActiveCount(); } - public double getPoolSize(){ + public double getPoolSize() { return threadPoolExecutor.getPoolSize(); } - public double getQueueSize(){ + public double getQueueSize() { return threadPoolExecutor.getQueue().size(); } - } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ThreadPoolRejectMetric.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ThreadPoolRejectMetric.java index c2daf4b5a9..47e0fed5ec 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ThreadPoolRejectMetric.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ThreadPoolRejectMetric.java @@ -14,22 +14,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.model; import org.apache.dubbo.common.utils.ConfigUtils; + import java.util.HashMap; import java.util.Map; import java.util.Objects; -import static org.apache.dubbo.common.utils.NetUtils.getLocalHost; -import static org.apache.dubbo.common.utils.NetUtils.getLocalHostName; -import static org.apache.dubbo.common.constants.MetricsConstants.TAG_PID; + import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME; -import static org.apache.dubbo.common.constants.MetricsConstants.TAG_THREAD_NAME; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_HOSTNAME; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_IP; +import static org.apache.dubbo.common.constants.MetricsConstants.TAG_PID; +import static org.apache.dubbo.common.constants.MetricsConstants.TAG_THREAD_NAME; +import static org.apache.dubbo.common.utils.NetUtils.getLocalHost; +import static org.apache.dubbo.common.utils.NetUtils.getLocalHostName; -public class ThreadPoolRejectMetric implements Metric{ +public class ThreadPoolRejectMetric implements Metric { private String applicationName; @@ -61,8 +62,8 @@ public class ThreadPoolRejectMetric implements Metric{ if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ThreadPoolRejectMetric that = (ThreadPoolRejectMetric) o; - return Objects.equals(applicationName, that.applicationName) && - Objects.equals(threadPoolName, that.threadPoolName); + return Objects.equals(applicationName, that.applicationName) + && Objects.equals(threadPoolName, that.threadPoolName); } @Override @@ -74,11 +75,10 @@ public class ThreadPoolRejectMetric implements Metric{ public Map getTags() { Map tags = new HashMap<>(); tags.put(TAG_IP, getLocalHost()); - tags.put(TAG_PID, ConfigUtils.getPid()+""); + tags.put(TAG_PID, ConfigUtils.getPid() + ""); tags.put(TAG_HOSTNAME, getLocalHostName()); tags.put(TAG_APPLICATION_NAME, applicationName); tags.put(TAG_THREAD_NAME, threadPoolName); return tags; } - } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/container/AtomicLongContainer.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/container/AtomicLongContainer.java index 73ba419ce8..f3dcfa6256 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/container/AtomicLongContainer.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/container/AtomicLongContainer.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.model.container; - import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import java.util.concurrent.atomic.AtomicLong; @@ -32,5 +30,4 @@ public class AtomicLongContainer extends LongContainer { public AtomicLongContainer(MetricsKeyWrapper metricsKeyWrapper, BiConsumer consumerFunc) { super(metricsKeyWrapper, AtomicLong::new, consumerFunc); } - } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/container/LongAccumulatorContainer.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/container/LongAccumulatorContainer.java index 1c6952dafd..adb76e7022 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/container/LongAccumulatorContainer.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/container/LongAccumulatorContainer.java @@ -14,16 +14,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.model.container; - import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper; import java.util.concurrent.atomic.LongAccumulator; public class LongAccumulatorContainer extends LongContainer { public LongAccumulatorContainer(MetricsKeyWrapper metricsKeyWrapper, LongAccumulator accumulator) { - super(metricsKeyWrapper, () -> accumulator, (responseTime, longAccumulator) -> longAccumulator.accumulate(responseTime)); + super( + metricsKeyWrapper, + () -> accumulator, + (responseTime, longAccumulator) -> longAccumulator.accumulate(responseTime)); } } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/container/LongContainer.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/container/LongContainer.java index dad8fce4bf..8108644885 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/container/LongContainer.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/container/LongContainer.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.model.container; import org.apache.dubbo.metrics.model.Metric; @@ -50,7 +49,6 @@ public class LongContainer extends ConcurrentHashMap valueSupplier; - public LongContainer(MetricsKeyWrapper metricsKeyWrapper, Supplier initFunc, BiConsumer consumerFunc) { super(128, 0.5f); this.metricsKeyWrapper = metricsKeyWrapper; @@ -89,9 +87,7 @@ public class LongContainer extends ConcurrentHashMap tags, Type type, MetricsCategory category) { + public MetricSample( + String name, String description, Map tags, Type type, MetricsCategory category) { this(name, description, tags, type, category, null); } - public MetricSample(String name, String description, Map tags, Type type, MetricsCategory category, String baseUnit) { + public MetricSample( + String name, + String description, + Map tags, + Type type, + MetricsCategory category, + String baseUnit) { this.name = name; this.description = description; this.tags = tags; @@ -99,9 +105,12 @@ public class MetricSample { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MetricSample that = (MetricSample) o; - return Objects.equals(name, that.name) && Objects.equals(description, that.description) - && Objects.equals(baseUnit, that.baseUnit) && type == that.type - && Objects.equals(category, that.category) && Objects.equals(tags, that.tags); + return Objects.equals(name, that.name) + && Objects.equals(description, that.description) + && Objects.equals(baseUnit, that.baseUnit) + && type == that.type + && Objects.equals(category, that.category) + && Objects.equals(tags, that.tags); } @Override @@ -111,17 +120,15 @@ public class MetricSample { @Override public String toString() { - return "MetricSample{" + - "name='" + name + '\'' + - ", description='" + description + '\'' + - ", baseUnit='" + baseUnit + '\'' + - ", type=" + type + - ", category=" + category + - ", tags=" + tags + - '}'; + return "MetricSample{" + "name='" + + name + '\'' + ", description='" + + description + '\'' + ", baseUnit='" + + baseUnit + '\'' + ", type=" + + type + ", category=" + + category + ", tags=" + + tags + '}'; } - public enum Type { COUNTER, GAUGE, diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsExport.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsExport.java index 94acf74de9..7ea0c64bd8 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsExport.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsExport.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.report; import org.apache.dubbo.rpc.model.ApplicationModel; diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsReporterFactory.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsReporterFactory.java index 7eed65e340..9da4eb1319 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsReporterFactory.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsReporterFactory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.report; import org.apache.dubbo.rpc.model.ApplicationModel; diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/MetricsExport.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/MetricsExport.java index 3b1b9f3459..afb4b57b7f 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/MetricsExport.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/MetricsExport.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.report; import org.apache.dubbo.metrics.model.MetricsCategory; diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/MetricsReporter.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/MetricsReporter.java index 50770e249f..cffd93135f 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/MetricsReporter.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/MetricsReporter.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.report; /** diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/MetricsReporterFactory.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/MetricsReporterFactory.java index 21efe4762f..4fd9f21a5a 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/MetricsReporterFactory.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/MetricsReporterFactory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.report; import org.apache.dubbo.common.URL; diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsEntity.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsEntity.java index 2b28a0790f..7a04d14ce5 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsEntity.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsEntity.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.service; import org.apache.dubbo.metrics.model.MetricsCategory; @@ -32,9 +31,7 @@ public class MetricsEntity { private MetricsCategory category; private Object value; - public MetricsEntity() { - - } + public MetricsEntity() {} public MetricsEntity(String name, Map tags, MetricsCategory category, Object value) { this.name = name; @@ -80,8 +77,10 @@ public class MetricsEntity { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MetricsEntity entity = (MetricsEntity) o; - return Objects.equals(name, entity.name) && Objects.equals(tags, entity.tags) - && Objects.equals(category, entity.category) && Objects.equals(value, entity.value); + return Objects.equals(name, entity.name) + && Objects.equals(tags, entity.tags) + && Objects.equals(category, entity.category) + && Objects.equals(value, entity.value); } @Override diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsService.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsService.java index edad533812..c1f8029b52 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsService.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsService.java @@ -14,13 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.service; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; -import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.collector.MetricsCollector; +import org.apache.dubbo.metrics.model.MetricsCategory; import java.util.List; import java.util.Map; @@ -59,7 +58,8 @@ public interface MetricsService { * @param categories categories * @return metrics - key=MetricCategory value=MetricsEntityList */ - Map> getMetricsByCategories(String serviceUniqueName, List categories); + Map> getMetricsByCategories( + String serviceUniqueName, List categories); /** * Get metrics by interface、method and prefixes @@ -70,5 +70,6 @@ public interface MetricsService { * @param categories categories * @return metrics - key=MetricCategory value=MetricsEntityList */ - Map> getMetricsByCategories(String serviceUniqueName, String methodName, Class[] parameterTypes, List categories); + Map> getMetricsByCategories( + String serviceUniqueName, String methodName, Class[] parameterTypes, List categories); } diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsServiceExporter.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsServiceExporter.java index 4632a2cdfe..69deb73c52 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsServiceExporter.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsServiceExporter.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.service; import org.apache.dubbo.common.extension.ExtensionScope; diff --git a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/utils/MetricsSupportUtil.java b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/utils/MetricsSupportUtil.java index e0a02f5f04..b304197bb8 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/utils/MetricsSupportUtil.java +++ b/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/utils/MetricsSupportUtil.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.utils; import org.apache.dubbo.common.utils.ClassUtils; diff --git a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/MetricsSupportTest.java b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/MetricsSupportTest.java index 7bc12d6a49..5ea95fdff7 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/MetricsSupportTest.java +++ b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/MetricsSupportTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics; import org.apache.dubbo.common.constants.CommonConstants; @@ -26,13 +25,14 @@ import org.apache.dubbo.metrics.model.key.MetricsLevel; import org.apache.dubbo.metrics.model.key.MetricsPlaceValue; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS; public class MetricsSupportTest { @@ -45,15 +45,19 @@ public class MetricsSupportTest { applicationModel.getApplicationConfigManager().setApplication(config); Map> data = new HashMap<>(); - MetricsKeyWrapper key1 = new MetricsKeyWrapper(METRIC_REQUESTS, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)); - MetricsKeyWrapper key2 = new MetricsKeyWrapper(METRIC_REQUESTS, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)); + MetricsKeyWrapper key1 = new MetricsKeyWrapper( + METRIC_REQUESTS, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)); + MetricsKeyWrapper key2 = new MetricsKeyWrapper( + METRIC_REQUESTS, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)); ServiceKeyMetric sm1 = new ServiceKeyMetric(applicationModel, "a.b.c"); ServiceKeyMetric sm2 = new ServiceKeyMetric(applicationModel, "a.b.d"); data.computeIfAbsent(key1, k -> new HashMap<>()).put(sm1, new AtomicLong(1)); data.computeIfAbsent(key1, k -> new HashMap<>()).put(sm2, new AtomicLong(1)); data.put(key2, new HashMap<>()); - Assertions.assertEquals(2, data.values().stream().mapToLong(map -> map.values().size()).sum()); + Assertions.assertEquals( + 2, data.values().stream().mapToLong(map -> map.values().size()).sum()); MetricsSupport.fillZero(data); - Assertions.assertEquals(4, data.values().stream().mapToLong(map -> map.values().size()).sum()); + Assertions.assertEquals( + 4, data.values().stream().mapToLong(map -> map.values().size()).sum()); } } diff --git a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/PaneTest.java b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/PaneTest.java index bbce54ec84..0427bf7335 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/PaneTest.java +++ b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/PaneTest.java @@ -14,13 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.aggregate; -import org.junit.jupiter.api.Test; - import java.util.concurrent.atomic.LongAdder; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; diff --git a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/SlidingWindowTest.java b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/SlidingWindowTest.java index efcaef6af8..4cf179df22 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/SlidingWindowTest.java +++ b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/SlidingWindowTest.java @@ -14,15 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.aggregate; +import java.util.concurrent.atomic.LongAdder; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; -import java.util.concurrent.atomic.LongAdder; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; @@ -43,18 +42,17 @@ class SlidingWindowTest { @RepeatedTest(1000) void testCurrentPane() { - assertNull(window.currentPane(/* invalid time*/-1L)); + assertNull(window.currentPane(/* invalid time*/ -1L)); long timeInMs = System.currentTimeMillis(); Pane currentPane = window.currentPane(timeInMs); assertNotNull(currentPane); // reuse test - assertEquals(currentPane, - window.currentPane(timeInMs + window.getPaneIntervalInMs() * paneCount)); + assertEquals(currentPane, window.currentPane(timeInMs + window.getPaneIntervalInMs() * paneCount)); } @Test void testGetPaneData() { - assertNull(window.getPaneValue(/* invalid time*/-1L)); + assertNull(window.getPaneValue(/* invalid time*/ -1L)); window.currentPane(); assertNotNull(window.getPaneValue(System.currentTimeMillis())); assertNull(window.getPaneValue(System.currentTimeMillis() + window.getPaneIntervalInMs())); diff --git a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/TimeWindowAggregatorTest.java b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/TimeWindowAggregatorTest.java index 2a660a5dd4..6f39a571e2 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/TimeWindowAggregatorTest.java +++ b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/TimeWindowAggregatorTest.java @@ -14,21 +14,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.aggregate; +import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.concurrent.TimeUnit; - public class TimeWindowAggregatorTest { @Test public void testTimeWindowAggregator() { TimeWindowAggregator aggregator = new TimeWindowAggregator(5, 5); - //First time window, time range: 0 - 5 seconds + // First time window, time range: 0 - 5 seconds aggregator.add(10); aggregator.add(20); @@ -41,7 +39,7 @@ public class TimeWindowAggregatorTest { Assertions.assertEquals(30, entry1.getMax()); Assertions.assertEquals(10, entry1.getMin()); - //Second time window, time range: 5 - 10 seconds + // Second time window, time range: 5 - 10 seconds try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { @@ -59,8 +57,7 @@ public class TimeWindowAggregatorTest { Assertions.assertEquals(35, entry2.getMax()); Assertions.assertEquals(15, entry2.getMin()); - - //Third time window, time range: 10 - 15 seconds + // Third time window, time range: 10 - 15 seconds try { TimeUnit.SECONDS.sleep(5); @@ -79,10 +76,3 @@ public class TimeWindowAggregatorTest { Assertions.assertEquals(12, entry3.getMin()); } } - - - - - - - diff --git a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/TimeWindowCounterTest.java b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/TimeWindowCounterTest.java index c1b6897944..e7f9851299 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/TimeWindowCounterTest.java +++ b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/TimeWindowCounterTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.aggregate; import org.junit.jupiter.api.Assertions; diff --git a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/TimeWindowQuantileTest.java b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/TimeWindowQuantileTest.java index 170efd61f9..fc1e5b09c9 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/TimeWindowQuantileTest.java +++ b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/aggregate/TimeWindowQuantileTest.java @@ -14,16 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.aggregate; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - class TimeWindowQuantileTest { @Test @@ -49,18 +48,16 @@ class TimeWindowQuantileTest { for (int i = 0; i < 100; i++) { int finalI = i; Assertions.assertDoesNotThrow(() -> quantile.add(finalI)); - executorService.execute(() -> - quantile.add(finalI)); + executorService.execute(() -> quantile.add(finalI)); } index++; -// try { -// Thread.sleep(1); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } + // try { + // Thread.sleep(1); + // } catch (InterruptedException e) { + // e.printStackTrace(); + // } } executorService.shutdown(); } - } diff --git a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticasterTest.java b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticasterTest.java index ef2e173994..b101d944e4 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticasterTest.java +++ b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticasterTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.event; import org.apache.dubbo.config.ApplicationConfig; @@ -39,7 +38,7 @@ public class SimpleMetricsEventMulticasterTest { @BeforeEach public void setup() { eventMulticaster = new SimpleMetricsEventMulticaster(); - objects = new Object[]{obj}; + objects = new Object[] {obj}; eventMulticaster.addListener(new AbstractMetricsListener() { @Override public void onEvent(MetricsEvent event) { @@ -53,19 +52,17 @@ public class SimpleMetricsEventMulticasterTest { ConfigManager configManager = new ConfigManager(applicationModel); configManager.setApplication(applicationConfig); applicationModel.setConfigManager(configManager); - requestEvent = new TimeCounterEvent(applicationModel,null) { - }; + requestEvent = new TimeCounterEvent(applicationModel, null) {}; } - @Test void testPublishFinishEvent() { - //do nothing with no MetricsLifeListener + // do nothing with no MetricsLifeListener eventMulticaster.publishFinishEvent(requestEvent); Assertions.assertSame(obj, objects[0]); - //do onEventFinish with MetricsLifeListener + // do onEventFinish with MetricsLifeListener eventMulticaster.addListener((new MetricsLifeListener() { @Override @@ -74,9 +71,7 @@ public class SimpleMetricsEventMulticasterTest { } @Override - public void onEvent(TimeCounterEvent event) { - - } + public void onEvent(TimeCounterEvent event) {} @Override public void onEventFinish(TimeCounterEvent event) { @@ -84,13 +79,9 @@ public class SimpleMetricsEventMulticasterTest { } @Override - public void onEventError(TimeCounterEvent event) { - - } + public void onEventError(TimeCounterEvent event) {} })); eventMulticaster.publishFinishEvent(requestEvent); Assertions.assertNotSame(obj, objects[0]); - } - } diff --git a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/model/ApplicationMetricTest.java b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/model/ApplicationMetricTest.java index c6717d9fea..ec2a71597f 100644 --- a/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/model/ApplicationMetricTest.java +++ b/dubbo-metrics/dubbo-metrics-api/src/test/java/org/apache/dubbo/metrics/model/ApplicationMetricTest.java @@ -18,11 +18,12 @@ package org.apache.dubbo.metrics.model; import org.apache.dubbo.common.Version; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.MetricsConstants.*; import static org.apache.dubbo.common.utils.NetUtils.getLocalHost; import static org.apache.dubbo.common.utils.NetUtils.getLocalHostName; @@ -41,17 +42,21 @@ class ApplicationMetricTest { void getApplicationName() { ApplicationModel applicationModel = ApplicationModel.defaultModel(); String mockMetrics = "MockMetrics"; - applicationModel.getApplicationConfigManager().setApplication(new org.apache.dubbo.config.ApplicationConfig(mockMetrics)); + applicationModel + .getApplicationConfigManager() + .setApplication(new org.apache.dubbo.config.ApplicationConfig(mockMetrics)); ApplicationMetric applicationMetric = new ApplicationMetric(applicationModel); Assertions.assertNotNull(applicationMetric); - Assertions.assertEquals(mockMetrics,applicationMetric.getApplicationName()); + Assertions.assertEquals(mockMetrics, applicationMetric.getApplicationName()); } @Test void getTags() { ApplicationModel applicationModel = ApplicationModel.defaultModel(); String mockMetrics = "MockMetrics"; - applicationModel.getApplicationConfigManager().setApplication(new org.apache.dubbo.config.ApplicationConfig(mockMetrics)); + applicationModel + .getApplicationConfigManager() + .setApplication(new org.apache.dubbo.config.ApplicationConfig(mockMetrics)); ApplicationMetric applicationMetric = new ApplicationMetric(applicationModel); Map tags = applicationMetric.getTags(); Assertions.assertEquals(tags.get(TAG_IP), getLocalHost()); @@ -64,7 +69,9 @@ class ApplicationMetricTest { void gitTags() { ApplicationModel applicationModel = ApplicationModel.defaultModel(); String mockMetrics = "MockMetrics"; - applicationModel.getApplicationConfigManager().setApplication(new org.apache.dubbo.config.ApplicationConfig(mockMetrics)); + applicationModel + .getApplicationConfigManager() + .setApplication(new org.apache.dubbo.config.ApplicationConfig(mockMetrics)); ApplicationMetric applicationMetric = new ApplicationMetric(applicationModel); Map tags = applicationMetric.getTags(); Assertions.assertEquals(tags.get(METADATA_GIT_COMMITID_METRIC.getName()), Version.getLastCommitId()); @@ -74,7 +81,9 @@ class ApplicationMetricTest { void hostTags() { ApplicationModel applicationModel = ApplicationModel.defaultModel(); String mockMetrics = "MockMetrics"; - applicationModel.getApplicationConfigManager().setApplication(new org.apache.dubbo.config.ApplicationConfig(mockMetrics)); + applicationModel + .getApplicationConfigManager() + .setApplication(new org.apache.dubbo.config.ApplicationConfig(mockMetrics)); ApplicationMetric applicationMetric = new ApplicationMetric(applicationModel); Map tags = applicationMetric.getTags(); Assertions.assertEquals(tags.get(TAG_IP), getLocalHost()); @@ -82,18 +91,14 @@ class ApplicationMetricTest { } @Test - void getExtraInfo() { - } + void getExtraInfo() {} @Test - void setExtraInfo() { - } + void setExtraInfo() {} @Test - void testEquals() { - } + void testEquals() {} @Test - void testHashCode() { - } + void testHashCode() {} } diff --git a/dubbo-metrics/dubbo-metrics-config-center/pom.xml b/dubbo-metrics/dubbo-metrics-config-center/pom.xml index aa65f3aef0..d69c48b57e 100644 --- a/dubbo-metrics/dubbo-metrics-config-center/pom.xml +++ b/dubbo-metrics/dubbo-metrics-config-center/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - org.apache.dubbo - dubbo-metrics - ${revision} - ../pom.xml - - dubbo-metrics-config-center - ${project.artifactId} + + 4.0.0 + + org.apache.dubbo + dubbo-metrics + ${revision} + ../pom.xml + + dubbo-metrics-config-center + ${project.artifactId} - - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - - + + + org.apache.dubbo + dubbo-metrics-api + ${project.parent.version} + + diff --git a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/ConfigCenterMetricsConstants.java b/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/ConfigCenterMetricsConstants.java index 8a7d22c762..157df551d4 100644 --- a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/ConfigCenterMetricsConstants.java +++ b/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/ConfigCenterMetricsConstants.java @@ -22,5 +22,4 @@ public interface ConfigCenterMetricsConstants { String ATTACHMENT_KEY_CONFIG_GROUP = "configGroup"; String ATTACHMENT_KEY_CONFIG_PROTOCOL = "configProtocol"; String ATTACHMENT_KEY_CHANGE_TYPE = "configChangeType"; - } diff --git a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/collector/ConfigCenterMetricsCollector.java b/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/collector/ConfigCenterMetricsCollector.java index a86f97695e..3840862f68 100644 --- a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/collector/ConfigCenterMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/collector/ConfigCenterMetricsCollector.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.config.collector; import org.apache.dubbo.common.extension.Activate; @@ -39,7 +38,6 @@ import java.util.concurrent.atomic.AtomicLong; import static org.apache.dubbo.metrics.model.MetricsCategory.CONFIGCENTER; - /** * Config center implementation of {@link MetricsCollector} */ @@ -77,7 +75,8 @@ public class ConfigCenterMetricsCollector extends CombMetricsCollector new AtomicLong(0L)); @@ -86,7 +85,6 @@ public class ConfigCenterMetricsCollector extends CombMetricsCollector collect() { // Add metrics to reporter @@ -94,7 +92,8 @@ public class ConfigCenterMetricsCollector extends CombMetricsCollector list.add(new GaugeMetricSample<>(MetricsKey.CONFIGCENTER_METRIC_TOTAL, k.getTags(), CONFIGCENTER, v, AtomicLong::get))); + updatedMetrics.forEach((k, v) -> list.add(new GaugeMetricSample<>( + MetricsKey.CONFIGCENTER_METRIC_TOTAL, k.getTags(), CONFIGCENTER, v, AtomicLong::get))); return list; } diff --git a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterEvent.java b/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterEvent.java index ddf4f88fdb..58e9979f70 100644 --- a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterEvent.java +++ b/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterEvent.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.config.event; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; @@ -37,12 +36,10 @@ import static org.apache.dubbo.metrics.model.key.MetricsKey.CONFIGCENTER_METRIC_ */ public class ConfigCenterEvent extends TimeCounterEvent { - public static final String NACOS_PROTOCOL = "nacos"; public static final String APOLLO_PROTOCOL = "apollo"; public static final String ZK_PROTOCOL = "zookeeper"; - public ConfigCenterEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper) { super(applicationModel, typeWrapper); ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); @@ -53,17 +50,20 @@ public class ConfigCenterEvent extends TimeCounterEvent { } } - - public static ConfigCenterEvent toChangeEvent(ApplicationModel applicationModel, String key, String group, String protocol, String changeType, int count) { - ConfigCenterEvent configCenterEvent = new ConfigCenterEvent(applicationModel, new TypeWrapper(MetricsLevel.CONFIG, CONFIGCENTER_METRIC_TOTAL)); + public static ConfigCenterEvent toChangeEvent( + ApplicationModel applicationModel, + String key, + String group, + String protocol, + String changeType, + int count) { + ConfigCenterEvent configCenterEvent = new ConfigCenterEvent( + applicationModel, new TypeWrapper(MetricsLevel.CONFIG, CONFIGCENTER_METRIC_TOTAL)); configCenterEvent.putAttachment(ATTACHMENT_KEY_CONFIG_FILE, key); configCenterEvent.putAttachment(ATTACHMENT_KEY_CONFIG_GROUP, group); configCenterEvent.putAttachment(ATTACHMENT_KEY_CONFIG_PROTOCOL, protocol); configCenterEvent.putAttachment(ATTACHMENT_KEY_CHANGE_TYPE, changeType); configCenterEvent.putAttachment(ATTACHMENT_KEY_SIZE, count); return configCenterEvent; - } - - } diff --git a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterSubDispatcher.java b/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterSubDispatcher.java index 1604cb3b62..49eab00578 100644 --- a/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterSubDispatcher.java +++ b/dubbo-metrics/dubbo-metrics-config-center/src/main/java/org/apache/dubbo/metrics/config/event/ConfigCenterSubDispatcher.java @@ -29,7 +29,6 @@ import static org.apache.dubbo.metrics.config.ConfigCenterMetricsConstants.ATTAC import static org.apache.dubbo.metrics.config.ConfigCenterMetricsConstants.ATTACHMENT_KEY_CONFIG_GROUP; import static org.apache.dubbo.metrics.config.ConfigCenterMetricsConstants.ATTACHMENT_KEY_CONFIG_PROTOCOL; - public final class ConfigCenterSubDispatcher extends SimpleMetricsEventMulticaster { public ConfigCenterSubDispatcher(ConfigCenterMetricsCollector collector) { @@ -43,16 +42,12 @@ public final class ConfigCenterSubDispatcher extends SimpleMetricsEventMulticast @Override public void onEvent(TimeCounterEvent event) { collector.increase( - event.getAttachmentValue(ATTACHMENT_KEY_CONFIG_FILE), - event.getAttachmentValue(ATTACHMENT_KEY_CONFIG_GROUP), - event.getAttachmentValue(ATTACHMENT_KEY_CONFIG_PROTOCOL), - event.getAttachmentValue(ATTACHMENT_KEY_CHANGE_TYPE), - event.getAttachmentValue(ATTACHMENT_KEY_SIZE) - ); + event.getAttachmentValue(ATTACHMENT_KEY_CONFIG_FILE), + event.getAttachmentValue(ATTACHMENT_KEY_CONFIG_GROUP), + event.getAttachmentValue(ATTACHMENT_KEY_CONFIG_PROTOCOL), + event.getAttachmentValue(ATTACHMENT_KEY_CHANGE_TYPE), + event.getAttachmentValue(ATTACHMENT_KEY_SIZE)); } }); - } - - } diff --git a/dubbo-metrics/dubbo-metrics-config-center/src/test/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollectorTest.java b/dubbo-metrics/dubbo-metrics-config-center/src/test/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollectorTest.java index f20c047871..35c44a94ca 100644 --- a/dubbo-metrics/dubbo-metrics-config-center/src/test/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollectorTest.java +++ b/dubbo-metrics/dubbo-metrics-config-center/src/test/java/org/apache/dubbo/metrics/collector/ConfigCenterMetricsCollectorTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.collector; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; @@ -25,14 +24,15 @@ import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; + +import java.util.List; +import java.util.Map; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.List; -import java.util.Map; - import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME; import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE; @@ -83,11 +83,11 @@ class ConfigCenterMetricsCollectorTest { ConfigChangedEvent event = new ConfigChangedEvent("key", "group", null, ConfigChangeType.ADDED); - collector.increase(event.getKey(), event.getGroup(), - "apollo", ConfigChangeType.ADDED.name(), SELF_INCREMENT_SIZE); + collector.increase( + event.getKey(), event.getGroup(), "apollo", ConfigChangeType.ADDED.name(), SELF_INCREMENT_SIZE); - collector.increase(event.getKey(), event.getGroup(), - "apollo", ConfigChangeType.ADDED.name(), SELF_INCREMENT_SIZE); + collector.increase( + event.getKey(), event.getGroup(), "apollo", ConfigChangeType.ADDED.name(), SELF_INCREMENT_SIZE); List samples = collector.collect(); for (MetricSample sample : samples) { diff --git a/dubbo-metrics/dubbo-metrics-default/pom.xml b/dubbo-metrics/dubbo-metrics-default/pom.xml index fe00d02c96..8493e3c285 100644 --- a/dubbo-metrics/dubbo-metrics-default/pom.xml +++ b/dubbo-metrics/dubbo-metrics-default/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - org.apache.dubbo - dubbo-metrics - ${revision} - ../pom.xml - - dubbo-metrics-default - jar - ${project.artifactId} - The metrics module of dubbo project - - false - - - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - + + 4.0.0 + + org.apache.dubbo + dubbo-metrics + ${revision} + ../pom.xml + + dubbo-metrics-default + jar + ${project.artifactId} + The metrics module of dubbo project + + false + + + + org.apache.dubbo + dubbo-metrics-api + ${project.parent.version} + - - org.apache.dubbo - dubbo-native - ${project.parent.version} - + + org.apache.dubbo + dubbo-native + ${project.parent.version} + - - io.micrometer - micrometer-test - test - - + + io.micrometer + micrometer-test + test + + diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/DefaultConstants.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/DefaultConstants.java index a59832fd0c..bf65f6fcd6 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/DefaultConstants.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/DefaultConstants.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics; import org.apache.dubbo.common.constants.CommonConstants; @@ -46,52 +45,77 @@ public interface DefaultConstants { String METRIC_THROWABLE = "metric_filter_throwable"; List METHOD_LEVEL_KEYS = Arrays.asList( - new MetricsKeyWrapper(METRIC_REQUESTS, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), - new MetricsKeyWrapper(METRIC_REQUESTS, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), - // METRIC_REQUESTS_PROCESSING use GAUGE - new MetricsKeyWrapper(METRIC_REQUESTS_PROCESSING, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)).setSampleType(MetricSample.Type.GAUGE), - new MetricsKeyWrapper(METRIC_REQUESTS_PROCESSING, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)).setSampleType(MetricSample.Type.GAUGE), - new MetricsKeyWrapper(METRIC_REQUESTS_SUCCEED, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), - new MetricsKeyWrapper(METRIC_REQUESTS_SUCCEED, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), - new MetricsKeyWrapper(METRIC_REQUEST_BUSINESS_FAILED, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), - new MetricsKeyWrapper(METRIC_REQUEST_BUSINESS_FAILED, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), - new MetricsKeyWrapper(METRIC_REQUESTS_TIMEOUT, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), - new MetricsKeyWrapper(METRIC_REQUESTS_TIMEOUT, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), - new MetricsKeyWrapper(METRIC_REQUESTS_LIMIT, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), - new MetricsKeyWrapper(METRIC_REQUESTS_LIMIT, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), - new MetricsKeyWrapper(METRIC_REQUESTS_FAILED, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), - new MetricsKeyWrapper(METRIC_REQUESTS_FAILED, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), - new MetricsKeyWrapper(METRIC_REQUESTS_TOTAL_FAILED, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), - new MetricsKeyWrapper(METRIC_REQUESTS_TOTAL_FAILED, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), - new MetricsKeyWrapper(METRIC_REQUESTS_NETWORK_FAILED, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), - new MetricsKeyWrapper(METRIC_REQUESTS_NETWORK_FAILED, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), - new MetricsKeyWrapper(METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), - new MetricsKeyWrapper(METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), - new MetricsKeyWrapper(METRIC_REQUESTS_CODEC_FAILED, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), - new MetricsKeyWrapper(METRIC_REQUESTS_CODEC_FAILED, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)) - ); + new MetricsKeyWrapper(METRIC_REQUESTS, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), + new MetricsKeyWrapper(METRIC_REQUESTS, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), + // METRIC_REQUESTS_PROCESSING use GAUGE + new MetricsKeyWrapper( + METRIC_REQUESTS_PROCESSING, + MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)) + .setSampleType(MetricSample.Type.GAUGE), + new MetricsKeyWrapper( + METRIC_REQUESTS_PROCESSING, + MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)) + .setSampleType(MetricSample.Type.GAUGE), + new MetricsKeyWrapper( + METRIC_REQUESTS_SUCCEED, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), + new MetricsKeyWrapper( + METRIC_REQUESTS_SUCCEED, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), + new MetricsKeyWrapper( + METRIC_REQUEST_BUSINESS_FAILED, + MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), + new MetricsKeyWrapper( + METRIC_REQUEST_BUSINESS_FAILED, + MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), + new MetricsKeyWrapper( + METRIC_REQUESTS_TIMEOUT, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), + new MetricsKeyWrapper( + METRIC_REQUESTS_TIMEOUT, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), + new MetricsKeyWrapper( + METRIC_REQUESTS_LIMIT, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), + new MetricsKeyWrapper( + METRIC_REQUESTS_LIMIT, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), + new MetricsKeyWrapper( + METRIC_REQUESTS_FAILED, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), + new MetricsKeyWrapper( + METRIC_REQUESTS_FAILED, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), + new MetricsKeyWrapper( + METRIC_REQUESTS_TOTAL_FAILED, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), + new MetricsKeyWrapper( + METRIC_REQUESTS_TOTAL_FAILED, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), + new MetricsKeyWrapper( + METRIC_REQUESTS_NETWORK_FAILED, + MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), + new MetricsKeyWrapper( + METRIC_REQUESTS_NETWORK_FAILED, + MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), + new MetricsKeyWrapper( + METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED, + MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), + new MetricsKeyWrapper( + METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED, + MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)), + new MetricsKeyWrapper( + METRIC_REQUESTS_CODEC_FAILED, MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD)), + new MetricsKeyWrapper( + METRIC_REQUESTS_CODEC_FAILED, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD))); List INIT_AGG_METHOD_KEYS = Arrays.asList( - MetricsKey.METRIC_REQUESTS_TOTAL_AGG, - MetricsKey.METRIC_REQUESTS_SUCCEED_AGG, - MetricsKey.METRIC_REQUESTS_FAILED_AGG, - MetricsKey.METRIC_REQUEST_BUSINESS_FAILED_AGG, - MetricsKey.METRIC_REQUESTS_TIMEOUT_AGG, - MetricsKey.METRIC_REQUESTS_LIMIT_AGG, - MetricsKey.METRIC_REQUESTS_TOTAL_FAILED_AGG, - MetricsKey.METRIC_REQUESTS_NETWORK_FAILED_AGG, - MetricsKey.METRIC_REQUESTS_CODEC_FAILED_AGG, - MetricsKey.METRIC_REQUESTS_TOTAL_SERVICE_UNAVAILABLE_FAILED_AGG - ); + MetricsKey.METRIC_REQUESTS_TOTAL_AGG, + MetricsKey.METRIC_REQUESTS_SUCCEED_AGG, + MetricsKey.METRIC_REQUESTS_FAILED_AGG, + MetricsKey.METRIC_REQUEST_BUSINESS_FAILED_AGG, + MetricsKey.METRIC_REQUESTS_TIMEOUT_AGG, + MetricsKey.METRIC_REQUESTS_LIMIT_AGG, + MetricsKey.METRIC_REQUESTS_TOTAL_FAILED_AGG, + MetricsKey.METRIC_REQUESTS_NETWORK_FAILED_AGG, + MetricsKey.METRIC_REQUESTS_CODEC_FAILED_AGG, + MetricsKey.METRIC_REQUESTS_TOTAL_SERVICE_UNAVAILABLE_FAILED_AGG); List INIT_DEFAULT_METHOD_KEYS = Arrays.asList( - MetricsKey.METRIC_REQUESTS, - MetricsKey.METRIC_REQUESTS_PROCESSING, - MetricsKey.METRIC_REQUESTS_FAILED_AGG, - MetricsKey.METRIC_REQUESTS_SUCCEED, - MetricsKey.METRIC_REQUESTS_TOTAL_FAILED, - MetricsKey.METRIC_REQUEST_BUSINESS_FAILED - ); - - + MetricsKey.METRIC_REQUESTS, + MetricsKey.METRIC_REQUESTS_PROCESSING, + MetricsKey.METRIC_REQUESTS_FAILED_AGG, + MetricsKey.METRIC_REQUESTS_SUCCEED, + MetricsKey.METRIC_REQUESTS_TOTAL_FAILED, + MetricsKey.METRIC_REQUEST_BUSINESS_FAILED); } diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsGlobalRegistry.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsGlobalRegistry.java index 6a69e4ed80..37b76505fc 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsGlobalRegistry.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsGlobalRegistry.java @@ -14,16 +14,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics; -import io.micrometer.core.instrument.Metrics; -import io.micrometer.core.instrument.composite.CompositeMeterRegistry; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Optional; +import io.micrometer.core.instrument.Metrics; +import io.micrometer.core.instrument.composite.CompositeMeterRegistry; + /** * Get the micrometer meter registry, can choose spring, micrometer, dubbo */ @@ -38,8 +38,11 @@ public class MetricsGlobalRegistry { * 3. Dubbo's own CompositeMeterRegistry is used by default */ public static CompositeMeterRegistry getCompositeRegistry(ApplicationModel applicationModel) { - Optional configOptional = applicationModel.getApplicationConfigManager().getMetrics(); - if (configOptional.isPresent() && configOptional.get().getUseGlobalRegistry() != null && configOptional.get().getUseGlobalRegistry()) { + Optional configOptional = + applicationModel.getApplicationConfigManager().getMetrics(); + if (configOptional.isPresent() + && configOptional.get().getUseGlobalRegistry() != null + && configOptional.get().getUseGlobalRegistry()) { return Metrics.globalRegistry; } else { return compositeRegistry; diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java index 660fcc835d..01e174ad0b 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/MetricsScopeModelInitializer.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; @@ -27,9 +26,7 @@ import org.apache.dubbo.rpc.model.ScopeModelInitializer; public class MetricsScopeModelInitializer implements ScopeModelInitializer { @Override - public void initializeFrameworkModel(FrameworkModel frameworkModel) { - - } + public void initializeFrameworkModel(FrameworkModel frameworkModel) {} @Override public void initializeApplicationModel(ApplicationModel applicationModel) { @@ -38,7 +35,5 @@ public class MetricsScopeModelInitializer implements ScopeModelInitializer { } @Override - public void initializeModuleModel(ModuleModel moduleModel) { - - } + public void initializeModuleModel(ModuleModel moduleModel) {} } diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/aot/DefaultMetricsReflectionTypeDescriberRegistrar.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/aot/DefaultMetricsReflectionTypeDescriberRegistrar.java index 0a0ea43762..9261030f63 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/aot/DefaultMetricsReflectionTypeDescriberRegistrar.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/aot/DefaultMetricsReflectionTypeDescriberRegistrar.java @@ -38,6 +38,7 @@ public class DefaultMetricsReflectionTypeDescriberRegistrar implements Reflectio private TypeDescriber buildTypeDescriberWithDeclaredConstructors(Class cl) { Set memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); - return new TypeDescriber(cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); + return new TypeDescriber( + cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } } diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollector.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollector.java index f70e3bc0fd..25ad926a6c 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollector.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.collector; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; @@ -62,7 +61,8 @@ public class AggregateMetricsCollector implements MetricsCollector private int bucketNum = DEFAULT_BUCKET_NUM; private int timeWindowSeconds = DEFAULT_TIME_WINDOW_SECONDS; private int qpsTimeWindowMillSeconds = DEFAULT_QPS_TIME_WINDOW_MILL_SECONDS; - private final Map> methodTypeCounter = new ConcurrentHashMap<>(); + private final Map> methodTypeCounter = + new ConcurrentHashMap<>(); private final ConcurrentMap rt = new ConcurrentHashMap<>(); private final ConcurrentHashMap qps = new ConcurrentHashMap<>(); private final ApplicationModel applicationModel; @@ -91,14 +91,16 @@ public class AggregateMetricsCollector implements MetricsCollector registerListener(); AggregationConfig aggregation = optional.get().getAggregation(); this.bucketNum = Optional.ofNullable(aggregation.getBucketNum()).orElse(DEFAULT_BUCKET_NUM); - this.timeWindowSeconds = Optional.ofNullable(aggregation.getTimeWindowSeconds()) - .orElse(DEFAULT_TIME_WINDOW_SECONDS); + this.timeWindowSeconds = + Optional.ofNullable(aggregation.getTimeWindowSeconds()).orElse(DEFAULT_TIME_WINDOW_SECONDS); this.qpsTimeWindowMillSeconds = Optional.ofNullable(aggregation.getQpsTimeWindowMillSeconds()) .orElse(DEFAULT_QPS_TIME_WINDOW_MILL_SECONDS); this.enableQps = Optional.ofNullable(aggregation.getEnableQps()).orElse(true); - this.enableRtPxx = Optional.ofNullable(aggregation.getEnableRtPxx()).orElse(true); + this.enableRtPxx = + Optional.ofNullable(aggregation.getEnableRtPxx()).orElse(true); this.enableRt = Optional.ofNullable(aggregation.getEnableRt()).orElse(true); - this.enableRequest = Optional.ofNullable(aggregation.getEnableRequest()).orElse(true); + this.enableRequest = + Optional.ofNullable(aggregation.getEnableRequest()).orElse(true); } this.serviceLevel = MethodMetric.isServiceLevel(applicationModel); } @@ -110,12 +112,14 @@ public class AggregateMetricsCollector implements MetricsCollector } } - @Override public boolean isCollectEnabled() { if (collectEnabled == null) { ConfigManager configManager = applicationModel.getApplicationConfigManager(); - configManager.getMetrics().ifPresent(metricsConfig -> setCollectEnabled(metricsConfig.getAggregation().getEnabled())); + configManager + .getMetrics() + .ifPresent(metricsConfig -> + setCollectEnabled(metricsConfig.getAggregation().getEnabled())); } return Optional.ofNullable(collectEnabled).orElse(true); } @@ -131,8 +135,11 @@ public class AggregateMetricsCollector implements MetricsCollector MethodMetric metric = calcWindowCounter(event, MetricsKey.METRIC_REQUESTS); TimeWindowCounter qpsCounter = qps.get(metric); if (qpsCounter == null) { - qpsCounter = ConcurrentHashMapUtils.computeIfAbsent(qps, metric, - methodMetric -> new TimeWindowCounter(bucketNum, TimeUnit.MILLISECONDS.toSeconds(qpsTimeWindowMillSeconds))); + qpsCounter = ConcurrentHashMapUtils.computeIfAbsent( + qps, + metric, + methodMetric -> new TimeWindowCounter( + bucketNum, TimeUnit.MILLISECONDS.toSeconds(qpsTimeWindowMillSeconds))); samplesChanged.set(true); } qpsCounter.increment(); @@ -166,13 +173,14 @@ public class AggregateMetricsCollector implements MetricsCollector } private void onRTEvent(RequestEvent event) { - MethodMetric metric = new MethodMetric(applicationModel, event.getAttachmentValue(MetricsConstants.INVOCATION), serviceLevel); + MethodMetric metric = + new MethodMetric(applicationModel, event.getAttachmentValue(MetricsConstants.INVOCATION), serviceLevel); long responseTime = event.getTimePair().calc(); if (enableRt) { TimeWindowQuantile quantile = rt.get(metric); if (quantile == null) { - quantile = ConcurrentHashMapUtils.computeIfAbsent(rt, metric, - k -> new TimeWindowQuantile(DEFAULT_COMPRESSION, bucketNum, timeWindowSeconds)); + quantile = ConcurrentHashMapUtils.computeIfAbsent( + rt, metric, k -> new TimeWindowQuantile(DEFAULT_COMPRESSION, bucketNum, timeWindowSeconds)); samplesChanged.set(true); } quantile.add(responseTime); @@ -181,26 +189,28 @@ public class AggregateMetricsCollector implements MetricsCollector if (enableRtPxx) { TimeWindowAggregator timeWindowAggregator = rtAgr.get(metric); if (timeWindowAggregator == null) { - timeWindowAggregator = ConcurrentHashMapUtils.computeIfAbsent(rtAgr, metric, - methodMetric -> new TimeWindowAggregator(bucketNum, timeWindowSeconds)); + timeWindowAggregator = ConcurrentHashMapUtils.computeIfAbsent( + rtAgr, metric, methodMetric -> new TimeWindowAggregator(bucketNum, timeWindowSeconds)); samplesChanged.set(true); } timeWindowAggregator.add(responseTime); } } - private MethodMetric calcWindowCounter(RequestEvent event, MetricsKey targetKey) { - MetricsPlaceValue placeType = MetricsPlaceValue.of(event.getAttachmentValue(MetricsConstants.INVOCATION_SIDE), MetricsLevel.SERVICE); + MetricsPlaceValue placeType = + MetricsPlaceValue.of(event.getAttachmentValue(MetricsConstants.INVOCATION_SIDE), MetricsLevel.SERVICE); MetricsKeyWrapper metricsKeyWrapper = new MetricsKeyWrapper(targetKey, placeType); - MethodMetric metric = new MethodMetric(applicationModel, event.getAttachmentValue(MetricsConstants.INVOCATION), serviceLevel); + MethodMetric metric = + new MethodMetric(applicationModel, event.getAttachmentValue(MetricsConstants.INVOCATION), serviceLevel); - ConcurrentMap counter = methodTypeCounter.computeIfAbsent(metricsKeyWrapper, k -> new ConcurrentHashMap<>()); + ConcurrentMap counter = + methodTypeCounter.computeIfAbsent(metricsKeyWrapper, k -> new ConcurrentHashMap<>()); TimeWindowCounter windowCounter = counter.get(metric); if (windowCounter == null) { - windowCounter = ConcurrentHashMapUtils.computeIfAbsent(counter, metric, - methodMetric -> new TimeWindowCounter(bucketNum, timeWindowSeconds)); + windowCounter = ConcurrentHashMapUtils.computeIfAbsent( + counter, metric, methodMetric -> new TimeWindowCounter(bucketNum, timeWindowSeconds)); samplesChanged.set(true); } windowCounter.increment(); @@ -239,55 +249,105 @@ public class AggregateMetricsCollector implements MetricsCollector } private void collectMethod(List list, String side, MetricsKey metricsKey) { - MetricsKeyWrapper metricsKeyWrapper = new MetricsKeyWrapper(metricsKey, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)); + MetricsKeyWrapper metricsKeyWrapper = + new MetricsKeyWrapper(metricsKey, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)); ConcurrentHashMap windowCounter = methodTypeCounter.get(metricsKeyWrapper); if (windowCounter != null) { - windowCounter.forEach((k, v) -> list.add(new GaugeMetricSample<>(metricsKey.getNameByType(k.getSide()), - metricsKey.getDescription(), k.getTags(), REQUESTS, v, TimeWindowCounter::get))); + windowCounter.forEach((k, v) -> list.add(new GaugeMetricSample<>( + metricsKey.getNameByType(k.getSide()), + metricsKey.getDescription(), + k.getTags(), + REQUESTS, + v, + TimeWindowCounter::get))); } } private void collectQPS(List list) { - qps.forEach((k, v) -> list.add(new GaugeMetricSample<>(MetricsKey.METRIC_QPS.getNameByType(k.getSide()), - MetricsKey.METRIC_QPS.getDescription(), k.getTags(), QPS, v, value -> { - double total = value.get(); - long millSeconds = value.bucketLivedMillSeconds(); - return total / millSeconds * 1000; - }))); + qps.forEach((k, v) -> list.add(new GaugeMetricSample<>( + MetricsKey.METRIC_QPS.getNameByType(k.getSide()), + MetricsKey.METRIC_QPS.getDescription(), + k.getTags(), + QPS, + v, + value -> { + double total = value.get(); + long millSeconds = value.bucketLivedMillSeconds(); + return total / millSeconds * 1000; + }))); } private void collectRT(List list) { rt.forEach((k, v) -> { - list.add(new GaugeMetricSample<>(MetricsKey.METRIC_RT_P99.getNameByType(k.getSide()), - MetricsKey.METRIC_RT_P99.getDescription(), k.getTags(), RT, v, value -> value.quantile(0.99))); - list.add(new GaugeMetricSample<>(MetricsKey.METRIC_RT_P95.getNameByType(k.getSide()), - MetricsKey.METRIC_RT_P95.getDescription(), k.getTags(), RT, v, value -> value.quantile(0.95))); - list.add(new GaugeMetricSample<>(MetricsKey.METRIC_RT_P90.getNameByType(k.getSide()), - MetricsKey.METRIC_RT_P90.getDescription(), k.getTags(), RT, v, value -> value.quantile(0.90))); - list.add(new GaugeMetricSample<>(MetricsKey.METRIC_RT_P50.getNameByType(k.getSide()), - MetricsKey.METRIC_RT_P50.getDescription(), k.getTags(), RT, v, value -> value.quantile(0.50))); + list.add(new GaugeMetricSample<>( + MetricsKey.METRIC_RT_P99.getNameByType(k.getSide()), + MetricsKey.METRIC_RT_P99.getDescription(), + k.getTags(), + RT, + v, + value -> value.quantile(0.99))); + list.add(new GaugeMetricSample<>( + MetricsKey.METRIC_RT_P95.getNameByType(k.getSide()), + MetricsKey.METRIC_RT_P95.getDescription(), + k.getTags(), + RT, + v, + value -> value.quantile(0.95))); + list.add(new GaugeMetricSample<>( + MetricsKey.METRIC_RT_P90.getNameByType(k.getSide()), + MetricsKey.METRIC_RT_P90.getDescription(), + k.getTags(), + RT, + v, + value -> value.quantile(0.90))); + list.add(new GaugeMetricSample<>( + MetricsKey.METRIC_RT_P50.getNameByType(k.getSide()), + MetricsKey.METRIC_RT_P50.getDescription(), + k.getTags(), + RT, + v, + value -> value.quantile(0.50))); }); rtAgr.forEach((k, v) -> { - list.add(new GaugeMetricSample<>(MetricsKey.METRIC_RT_MIN_AGG.getNameByType(k.getSide()), - MetricsKey.METRIC_RT_MIN_AGG.getDescription(), k.getTags(), RT, v, value -> v.get().getMin())); + list.add(new GaugeMetricSample<>( + MetricsKey.METRIC_RT_MIN_AGG.getNameByType(k.getSide()), + MetricsKey.METRIC_RT_MIN_AGG.getDescription(), + k.getTags(), + RT, + v, + value -> v.get().getMin())); - list.add(new GaugeMetricSample<>(MetricsKey.METRIC_RT_MAX_AGG.getNameByType(k.getSide()), - MetricsKey.METRIC_RT_MAX_AGG.getDescription(), k.getTags(), RT, v, value -> v.get().getMax())); + list.add(new GaugeMetricSample<>( + MetricsKey.METRIC_RT_MAX_AGG.getNameByType(k.getSide()), + MetricsKey.METRIC_RT_MAX_AGG.getDescription(), + k.getTags(), + RT, + v, + value -> v.get().getMax())); - list.add(new GaugeMetricSample<>(MetricsKey.METRIC_RT_AVG_AGG.getNameByType(k.getSide()), - MetricsKey.METRIC_RT_AVG_AGG.getDescription(), k.getTags(), RT, v, value -> v.get().getAvg())); + list.add(new GaugeMetricSample<>( + MetricsKey.METRIC_RT_AVG_AGG.getNameByType(k.getSide()), + MetricsKey.METRIC_RT_AVG_AGG.getDescription(), + k.getTags(), + RT, + v, + value -> v.get().getAvg())); }); } private void registerListener() { - applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class).getEventMulticaster().addListener(this); + applicationModel + .getBeanFactory() + .getBean(DefaultMetricsCollector.class) + .getEventMulticaster() + .addListener(this); } - @Override public void initMetrics(MetricsEvent event) { - MethodMetric metric = new MethodMetric(applicationModel, event.getAttachmentValue(MetricsConstants.INVOCATION), serviceLevel); + MethodMetric metric = + new MethodMetric(applicationModel, event.getAttachmentValue(MetricsConstants.INVOCATION), serviceLevel); if (enableQps) { initMethodMetric(event); initQpsMetric(metric); @@ -305,31 +365,38 @@ public class AggregateMetricsCollector implements MetricsCollector } public void initQpsMetric(MethodMetric metric) { - ConcurrentHashMapUtils.computeIfAbsent(qps, metric, methodMetric -> new TimeWindowCounter(bucketNum, timeWindowSeconds)); + ConcurrentHashMapUtils.computeIfAbsent( + qps, metric, methodMetric -> new TimeWindowCounter(bucketNum, timeWindowSeconds)); samplesChanged.set(true); } public void initRtMetric(MethodMetric metric) { - ConcurrentHashMapUtils.computeIfAbsent(rt, metric, k -> new TimeWindowQuantile(DEFAULT_COMPRESSION, bucketNum, timeWindowSeconds)); + ConcurrentHashMapUtils.computeIfAbsent( + rt, metric, k -> new TimeWindowQuantile(DEFAULT_COMPRESSION, bucketNum, timeWindowSeconds)); samplesChanged.set(true); } public void initRtAgrMetric(MethodMetric metric) { - ConcurrentHashMapUtils.computeIfAbsent(rtAgr, metric, k -> new TimeWindowAggregator(bucketNum, timeWindowSeconds)); + ConcurrentHashMapUtils.computeIfAbsent( + rtAgr, metric, k -> new TimeWindowAggregator(bucketNum, timeWindowSeconds)); samplesChanged.set(true); } public void initWindowCounter(MetricsEvent event, MetricsKey targetKey) { - MetricsKeyWrapper metricsKeyWrapper = new MetricsKeyWrapper(targetKey, MetricsPlaceValue.of(event.getAttachmentValue(MetricsConstants.INVOCATION_SIDE), MetricsLevel.SERVICE)); + MetricsKeyWrapper metricsKeyWrapper = new MetricsKeyWrapper( + targetKey, + MetricsPlaceValue.of(event.getAttachmentValue(MetricsConstants.INVOCATION_SIDE), MetricsLevel.SERVICE)); - MethodMetric metric = new MethodMetric(applicationModel, event.getAttachmentValue(MetricsConstants.INVOCATION), serviceLevel); + MethodMetric metric = + new MethodMetric(applicationModel, event.getAttachmentValue(MetricsConstants.INVOCATION), serviceLevel); - ConcurrentMap counter = methodTypeCounter.computeIfAbsent(metricsKeyWrapper, k -> new ConcurrentHashMap<>()); + ConcurrentMap counter = + methodTypeCounter.computeIfAbsent(metricsKeyWrapper, k -> new ConcurrentHashMap<>()); - ConcurrentHashMapUtils.computeIfAbsent(counter, metric, methodMetric -> new TimeWindowCounter(bucketNum, timeWindowSeconds)); + ConcurrentHashMapUtils.computeIfAbsent( + counter, metric, methodMetric -> new TimeWindowCounter(bucketNum, timeWindowSeconds)); samplesChanged.set(true); - } @Override diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/DefaultMetricsCollector.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/DefaultMetricsCollector.java index aa13de381f..52c182f16d 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/DefaultMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/DefaultMetricsCollector.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.collector; import org.apache.dubbo.common.constants.CommonConstants; @@ -22,10 +21,10 @@ import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metrics.DefaultConstants; import org.apache.dubbo.metrics.MetricsConstants; import org.apache.dubbo.metrics.collector.sample.ErrorCodeSampler; +import org.apache.dubbo.metrics.collector.sample.MetricsCountSampleConfigurer; import org.apache.dubbo.metrics.collector.sample.MetricsSampler; import org.apache.dubbo.metrics.collector.sample.SimpleMetricsCountSampler; import org.apache.dubbo.metrics.collector.sample.ThreadPoolMetricsSampler; -import org.apache.dubbo.metrics.collector.sample.MetricsCountSampleConfigurer; import org.apache.dubbo.metrics.data.BaseStatComposite; import org.apache.dubbo.metrics.data.MethodStatComposite; import org.apache.dubbo.metrics.data.RtStatComposite; @@ -91,8 +90,9 @@ public class DefaultMetricsCollector extends CombMetricsCollector @Override protected void init(RtStatComposite rtStatComposite) { super.init(rtStatComposite); - rtStatComposite.init(MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD), - MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)); + rtStatComposite.init( + MetricsPlaceValue.of(CommonConstants.PROVIDER, MetricsLevel.METHOD), + MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD)); } }); super.setEventMulticaster(new DefaultSubDispatcher(this)); @@ -176,14 +176,14 @@ public class DefaultMetricsCollector extends CombMetricsCollector @Override public void onEvent(TimeCounterEvent event) { - if(event instanceof MetricsInitEvent){ + if (event instanceof MetricsInitEvent) { if (!metricsInitEnabled) { return; } - if(initialized.compareAndSet(false,true)) { + if (initialized.compareAndSet(false, true)) { collectors.addAll(applicationModel.getBeanFactory().getBeansOfType(MetricsCollector.class)); } - collectors.stream().forEach(collector->collector.initMetrics(event)); + collectors.stream().forEach(collector -> collector.initMetrics(event)); return; } super.onEvent(event); @@ -191,35 +191,44 @@ public class DefaultMetricsCollector extends CombMetricsCollector @Override public void initMetrics(MetricsEvent event) { - MetricsPlaceValue dynamicPlaceType = MetricsPlaceValue.of(event.getAttachmentValue(MetricsConstants.INVOCATION_SIDE), MetricsLevel.METHOD); - INIT_DEFAULT_METHOD_KEYS.stream().forEach(key->MetricsSupport.init(key, dynamicPlaceType, (MethodMetricsCollector) this, event)); - MetricsSupport.init(METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED, MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD), (MethodMetricsCollector) this, event); + MetricsPlaceValue dynamicPlaceType = + MetricsPlaceValue.of(event.getAttachmentValue(MetricsConstants.INVOCATION_SIDE), MetricsLevel.METHOD); + INIT_DEFAULT_METHOD_KEYS.stream() + .forEach(key -> MetricsSupport.init(key, dynamicPlaceType, (MethodMetricsCollector) this, event)); + MetricsSupport.init( + METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED, + MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD), + (MethodMetricsCollector) this, + event); } - public SimpleMetricsCountSampler applicationSampler = new SimpleMetricsCountSampler() { - @Override - public List sample() { - List samples = new ArrayList<>(); - this.getCount(MetricsEvent.Type.APPLICATION_INFO).filter(e -> !e.isEmpty()) - .ifPresent(map -> map.forEach((k, v) -> - samples.add(new CounterMetricSample<>(APPLICATION_METRIC_INFO.getName(), - APPLICATION_METRIC_INFO.getDescription(), - k.getTags(), APPLICATION, v))) - ); - return samples; - } + public SimpleMetricsCountSampler applicationSampler = + new SimpleMetricsCountSampler() { + @Override + public List sample() { + List samples = new ArrayList<>(); + this.getCount(MetricsEvent.Type.APPLICATION_INFO) + .filter(e -> !e.isEmpty()) + .ifPresent(map -> map.forEach((k, v) -> samples.add(new CounterMetricSample<>( + APPLICATION_METRIC_INFO.getName(), + APPLICATION_METRIC_INFO.getDescription(), + k.getTags(), + APPLICATION, + v)))); + return samples; + } - @Override - protected void countConfigure( - MetricsCountSampleConfigurer sampleConfigure) { - sampleConfigure.configureMetrics(configure -> new ApplicationMetric(applicationModel)); - } + @Override + protected void countConfigure( + MetricsCountSampleConfigurer sampleConfigure) { + sampleConfigure.configureMetrics(configure -> new ApplicationMetric(applicationModel)); + } - @Override - public boolean calSamplesChanged() { - return false; - } - }; + @Override + public boolean calSamplesChanged() { + return false; + } + }; @Override public boolean calSamplesChanged() { diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/HistogramMetricsCollector.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/HistogramMetricsCollector.java index a7169ba12a..807e31b251 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/HistogramMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/HistogramMetricsCollector.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.collector; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; @@ -32,22 +31,23 @@ import org.apache.dubbo.metrics.register.HistogramMetricRegister; import org.apache.dubbo.metrics.sample.HistogramMetricSample; import org.apache.dubbo.rpc.model.ApplicationModel; -import io.micrometer.core.instrument.Timer; - import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; +import io.micrometer.core.instrument.Timer; + import static org.apache.dubbo.metrics.model.MetricsCategory.RT; -public class HistogramMetricsCollector extends AbstractMetricsListener implements MetricsCollector { +public class HistogramMetricsCollector extends AbstractMetricsListener + implements MetricsCollector { private final ConcurrentHashMap rt = new ConcurrentHashMap<>(); private HistogramMetricRegister metricRegister; private final ApplicationModel applicationModel; - private static final Integer[] DEFAULT_BUCKETS_MS = new Integer[]{100, 300, 500, 1000, 3000, 5000, 10000}; + private static final Integer[] DEFAULT_BUCKETS_MS = new Integer[] {100, 300, 500, 1000, 3000, 5000, 10000}; private boolean serviceLevel; @@ -56,7 +56,10 @@ public class HistogramMetricsCollector extends AbstractMetricsListener metricRegister.register(sample)); timer.record(responseTime, TimeUnit.MILLISECONDS); diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ErrorCodeMetricsListenRegister.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ErrorCodeMetricsListenRegister.java index 82860dab51..f8a77c9136 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ErrorCodeMetricsListenRegister.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ErrorCodeMetricsListenRegister.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.common.logger.LogListener; @@ -28,7 +27,7 @@ public class ErrorCodeMetricsListenRegister implements LogListener { private final ErrorCodeSampler errorCodeSampler; - public ErrorCodeMetricsListenRegister(ErrorCodeSampler errorCodeSampler){ + public ErrorCodeMetricsListenRegister(ErrorCodeSampler errorCodeSampler) { FailsafeErrorTypeAwareLogger.registerGlobalListen(this); this.errorCodeSampler = errorCodeSampler; this.errorCodeSampler.addMetricName(MetricsKey.ERROR_CODE_COUNT.getName()); diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ErrorCodeSampler.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ErrorCodeSampler.java index 86fdf79237..7b77014912 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ErrorCodeSampler.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ErrorCodeSampler.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; @@ -47,20 +46,19 @@ public class ErrorCodeSampler extends MetricsNameCountSampler( - metricsKey.getNameByType(metric.getErrorCode()), - metricsKey.getDescription(), - metric.getTags(), - metricsCategory, - count - ); + metricsKey.getNameByType(metric.getErrorCode()), + metricsKey.getDescription(), + metric.getTags(), + metricsCategory, + count); } @Override protected void countConfigure(MetricsCountSampleConfigurer sampleConfigure) { sampleConfigure.configureMetrics(configure -> { - String errorCode = configure.getSource(); ErrorCodeMetric metric = errorCodeMetrics.get(errorCode); diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricThreadPoolExhaustedListener.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricThreadPoolExhaustedListener.java index 4b45ba1dd9..f7278e172b 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricThreadPoolExhaustedListener.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricThreadPoolExhaustedListener.java @@ -14,8 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.collector.sample; + import org.apache.dubbo.common.threadpool.event.ThreadPoolExhaustedEvent; import org.apache.dubbo.common.threadpool.event.ThreadPoolExhaustedListener; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; @@ -26,18 +26,19 @@ public class MetricThreadPoolExhaustedListener implements ThreadPoolExhaustedLis private final String threadPoolExecutorName; - public MetricThreadPoolExhaustedListener(String threadPoolExecutorName,DefaultMetricsCollector collector) { - this.threadPoolExecutorName=threadPoolExecutorName; + public MetricThreadPoolExhaustedListener(String threadPoolExecutorName, DefaultMetricsCollector collector) { + this.threadPoolExecutorName = threadPoolExecutorName; this.threadRejectMetricsCountSampler = new ThreadRejectMetricsCountSampler(collector); } - public MetricThreadPoolExhaustedListener(String threadPoolExecutorName,ThreadRejectMetricsCountSampler sampler) { - this.threadPoolExecutorName=threadPoolExecutorName; - this.threadRejectMetricsCountSampler=sampler; + public MetricThreadPoolExhaustedListener(String threadPoolExecutorName, ThreadRejectMetricsCountSampler sampler) { + this.threadPoolExecutorName = threadPoolExecutorName; + this.threadRejectMetricsCountSampler = sampler; this.threadRejectMetricsCountSampler.addMetricName(threadPoolExecutorName); } + @Override public void onEvent(ThreadPoolExhaustedEvent event) { - threadRejectMetricsCountSampler.inc(threadPoolExecutorName,threadPoolExecutorName); + threadRejectMetricsCountSampler.inc(threadPoolExecutorName, threadPoolExecutorName); } } diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsCountSampleConfigurer.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsCountSampleConfigurer.java index 0bb41f0a03..54267e2d34 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsCountSampleConfigurer.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsCountSampleConfigurer.java @@ -14,14 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.metrics.model.Metric; import java.util.function.Function; -public class MetricsCountSampleConfigurer { +public class MetricsCountSampleConfigurer { public S source; @@ -29,16 +28,17 @@ public class MetricsCountSampleConfigurer { public M metric; - public void setSource(S source){ + public void setSource(S source) { this.source = source; } - public MetricsCountSampleConfigurer setMetricsName(K metricName){ + public MetricsCountSampleConfigurer setMetricsName(K metricName) { this.metricName = metricName; return this; } - public MetricsCountSampleConfigurer configureMetrics(Function,M> builder){ + public MetricsCountSampleConfigurer configureMetrics( + Function, M> builder) { this.metric = builder.apply(this); return this; } @@ -50,5 +50,4 @@ public class MetricsCountSampleConfigurer { public M getMetric() { return metric; } - } diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsCountSampler.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsCountSampler.java index fe746a941b..4b02dcd365 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsCountSampler.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsCountSampler.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.metrics.model.Metric; @@ -28,5 +27,4 @@ public interface MetricsCountSampler extends MetricsSamp void inc(S source, K metricName); Optional> getCount(K metricName); - } diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsNameCountSampler.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsNameCountSampler.java index 6562e0beab..5a4457ec53 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsNameCountSampler.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsNameCountSampler.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.common.utils.ConcurrentHashSet; @@ -42,7 +41,8 @@ public abstract class MetricsNameCountSampler extends Si protected final MetricsKey metricsKey; - public MetricsNameCountSampler(DefaultMetricsCollector collector,MetricsCategory metricsCategory,MetricsKey metricsKey) { + public MetricsNameCountSampler( + DefaultMetricsCollector collector, MetricsCategory metricsCategory, MetricsKey metricsKey) { this.metricsCategory = metricsCategory; this.metricsKey = metricsKey; this.collector = collector; @@ -63,12 +63,13 @@ public abstract class MetricsNameCountSampler extends Si private void collect(List samples, K metricName) { getCount(metricName) - .filter(e -> !e.isEmpty()) - .ifPresent(map -> map.forEach((k, v) -> - samples.add(provideMetricsSample(k,v,metricsKey,metricsCategory)))); + .filter(e -> !e.isEmpty()) + .ifPresent(map -> + map.forEach((k, v) -> samples.add(provideMetricsSample(k, v, metricsKey, metricsCategory)))); } - protected abstract MetricSample provideMetricsSample(M metric,AtomicLong count,MetricsKey metricsKey,MetricsCategory metricsCategory); + protected abstract MetricSample provideMetricsSample( + M metric, AtomicLong count, MetricsKey metricsKey, MetricsCategory metricsCategory); @Override public boolean calSamplesChanged() { diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsSampler.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsSampler.java index 52578d627d..d6d813b707 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsSampler.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/MetricsSampler.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.metrics.model.sample.MetricSample; diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/SimpleMetricsCountSampler.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/SimpleMetricsCountSampler.java index 666af13f30..9944b0aca6 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/SimpleMetricsCountSampler.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/SimpleMetricsCountSampler.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.common.utils.Assert; @@ -31,9 +30,7 @@ import java.util.concurrent.atomic.AtomicLong; * @param metricsName * @param metric */ - -public abstract class SimpleMetricsCountSampler - implements MetricsCountSampler { +public abstract class SimpleMetricsCountSampler implements MetricsCountSampler { private final ConcurrentMap EMPTY_COUNT = new ConcurrentHashMap<>(); @@ -46,9 +43,7 @@ public abstract class SimpleMetricsCountSampler @Override public Optional> getCount(K metricName) { - return Optional.ofNullable(metricCounter.get(metricName) == null ? - EMPTY_COUNT : - metricCounter.get(metricName)); + return Optional.ofNullable(metricCounter.get(metricName) == null ? EMPTY_COUNT : metricCounter.get(metricName)); } protected abstract void countConfigure(MetricsCountSampleConfigurer sampleConfigure); @@ -74,7 +69,5 @@ public abstract class SimpleMetricsCountSampler atomicCounter = metricAtomic.computeIfAbsent(sampleConfigure.getMetric(), k -> new AtomicLong()); } return atomicCounter; - } - } diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSampler.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSampler.java index 8e459d3266..4250b41c91 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSampler.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSampler.java @@ -57,18 +57,19 @@ public class ThreadPoolMetricsSampler implements MetricsSampler { private final ConcurrentHashMap threadPoolMetricMap = new ConcurrentHashMap<>(); private final AtomicBoolean samplesChanged = new AtomicBoolean(true); - public ThreadPoolMetricsSampler(DefaultMetricsCollector collector) { this.collector = collector; } public void addExecutors(String name, ExecutorService executorService) { - Optional.ofNullable(executorService).filter(Objects::nonNull).filter(e -> e instanceof ThreadPoolExecutor) - .map(e -> (ThreadPoolExecutor) e) - .ifPresent(threadPoolExecutor -> { - sampleThreadPoolExecutor.put(name, threadPoolExecutor); - samplesChanged.set(true); - }); + Optional.ofNullable(executorService) + .filter(Objects::nonNull) + .filter(e -> e instanceof ThreadPoolExecutor) + .map(e -> (ThreadPoolExecutor) e) + .ifPresent(threadPoolExecutor -> { + sampleThreadPoolExecutor.put(name, threadPoolExecutor); + samplesChanged.set(true); + }); } @Override @@ -84,16 +85,47 @@ public class ThreadPoolMetricsSampler implements MetricsSampler { private List createMetricsSample(String name, ThreadPoolExecutor executor) { List list = new ArrayList<>(); - ThreadPoolMetric threadPoolMetric = ConcurrentHashMapUtils.computeIfAbsent(threadPoolMetricMap, name, - v -> new ThreadPoolMetric(collector.getApplicationName(), name, executor)); - list.add(new GaugeMetricSample<>(MetricsKey.THREAD_POOL_CORE_SIZE, threadPoolMetric.getTags(), THREAD_POOL, threadPoolMetric, ThreadPoolMetric::getCorePoolSize)); - list.add(new GaugeMetricSample<>(MetricsKey.THREAD_POOL_LARGEST_SIZE, threadPoolMetric.getTags(), THREAD_POOL, threadPoolMetric, ThreadPoolMetric::getLargestPoolSize)); - list.add(new GaugeMetricSample<>(MetricsKey.THREAD_POOL_MAX_SIZE, threadPoolMetric.getTags(), THREAD_POOL, threadPoolMetric, ThreadPoolMetric::getMaximumPoolSize)); - list.add(new GaugeMetricSample<>(MetricsKey.THREAD_POOL_ACTIVE_SIZE, threadPoolMetric.getTags(), THREAD_POOL, threadPoolMetric, ThreadPoolMetric::getActiveCount)); - list.add(new GaugeMetricSample<>(MetricsKey.THREAD_POOL_THREAD_COUNT, threadPoolMetric.getTags(), THREAD_POOL, threadPoolMetric, ThreadPoolMetric::getPoolSize)); - list.add(new GaugeMetricSample<>(MetricsKey.THREAD_POOL_QUEUE_SIZE, threadPoolMetric.getTags(), THREAD_POOL, threadPoolMetric, ThreadPoolMetric::getQueueSize)); + ThreadPoolMetric threadPoolMetric = ConcurrentHashMapUtils.computeIfAbsent( + threadPoolMetricMap, name, v -> new ThreadPoolMetric(collector.getApplicationName(), name, executor)); + list.add(new GaugeMetricSample<>( + MetricsKey.THREAD_POOL_CORE_SIZE, + threadPoolMetric.getTags(), + THREAD_POOL, + threadPoolMetric, + ThreadPoolMetric::getCorePoolSize)); + list.add(new GaugeMetricSample<>( + MetricsKey.THREAD_POOL_LARGEST_SIZE, + threadPoolMetric.getTags(), + THREAD_POOL, + threadPoolMetric, + ThreadPoolMetric::getLargestPoolSize)); + list.add(new GaugeMetricSample<>( + MetricsKey.THREAD_POOL_MAX_SIZE, + threadPoolMetric.getTags(), + THREAD_POOL, + threadPoolMetric, + ThreadPoolMetric::getMaximumPoolSize)); + list.add(new GaugeMetricSample<>( + MetricsKey.THREAD_POOL_ACTIVE_SIZE, + threadPoolMetric.getTags(), + THREAD_POOL, + threadPoolMetric, + ThreadPoolMetric::getActiveCount)); + list.add(new GaugeMetricSample<>( + MetricsKey.THREAD_POOL_THREAD_COUNT, + threadPoolMetric.getTags(), + THREAD_POOL, + threadPoolMetric, + ThreadPoolMetric::getPoolSize)); + list.add(new GaugeMetricSample<>( + MetricsKey.THREAD_POOL_QUEUE_SIZE, + threadPoolMetric.getTags(), + THREAD_POOL, + threadPoolMetric, + ThreadPoolMetric::getQueueSize)); return list; } + public void registryDefaultSampleThreadPoolExecutor() { ApplicationModel applicationModel = collector.getApplicationModel(); if (applicationModel == null) { @@ -105,18 +137,26 @@ public class ThreadPoolMetricsSampler implements MetricsSampler { } private void addExecutorRejectMetrics() { - ThreadRejectMetricsCountSampler threadRejectMetricsCountSampler = new ThreadRejectMetricsCountSampler(collector); - this.sampleThreadPoolExecutor.entrySet().stream().filter(entry -> entry.getKey().startsWith(SERVER_THREAD_POOL_NAME)).forEach(entry -> { - if (entry.getValue().getRejectedExecutionHandler() instanceof AbortPolicyWithReport) { - MetricThreadPoolExhaustedListener metricThreadPoolExhaustedListener = new MetricThreadPoolExhaustedListener(entry.getKey(), threadRejectMetricsCountSampler); - ((AbortPolicyWithReport) entry.getValue().getRejectedExecutionHandler()).addThreadPoolExhaustedEventListener(metricThreadPoolExhaustedListener); - } - }); + ThreadRejectMetricsCountSampler threadRejectMetricsCountSampler = + new ThreadRejectMetricsCountSampler(collector); + this.sampleThreadPoolExecutor.entrySet().stream() + .filter(entry -> entry.getKey().startsWith(SERVER_THREAD_POOL_NAME)) + .forEach(entry -> { + if (entry.getValue().getRejectedExecutionHandler() instanceof AbortPolicyWithReport) { + MetricThreadPoolExhaustedListener metricThreadPoolExhaustedListener = + new MetricThreadPoolExhaustedListener(entry.getKey(), threadRejectMetricsCountSampler); + ((AbortPolicyWithReport) entry.getValue().getRejectedExecutionHandler()) + .addThreadPoolExhaustedEventListener(metricThreadPoolExhaustedListener); + } + }); } private void addRpcExecutors() { if (this.dataStore == null) { - this.dataStore = collector.getApplicationModel().getExtensionLoader(DataStore.class).getDefaultExtension(); + this.dataStore = collector + .getApplicationModel() + .getExtensionLoader(DataStore.class) + .getDefaultExtension(); } if (dataStore != null) { @@ -140,11 +180,15 @@ public class ThreadPoolMetricsSampler implements MetricsSampler { private void addFrameworkExecutors() { try { if (this.frameworkExecutorRepository == null) { - this.frameworkExecutorRepository = collector.getApplicationModel().getBeanFactory() - .getBean(FrameworkExecutorRepository.class); + this.frameworkExecutorRepository = + collector.getApplicationModel().getBeanFactory().getBean(FrameworkExecutorRepository.class); } } catch (Exception ex) { - logger.warn(COMMON_METRICS_COLLECTOR_EXCEPTION, "", "", "ThreadPoolMetricsSampler! frameworkExecutorRepository non-init"); + logger.warn( + COMMON_METRICS_COLLECTOR_EXCEPTION, + "", + "", + "ThreadPoolMetricsSampler! frameworkExecutorRepository non-init"); } if (this.frameworkExecutorRepository == null) { return; @@ -152,8 +196,10 @@ public class ThreadPoolMetricsSampler implements MetricsSampler { this.addExecutors("poolRouterExecutor", frameworkExecutorRepository.getPoolRouterExecutor()); this.addExecutors("metadataRetryExecutor", frameworkExecutorRepository.getMetadataRetryExecutor()); this.addExecutors("internalServiceExecutor", frameworkExecutorRepository.getInternalServiceExecutor()); - this.addExecutors("connectivityScheduledExecutor", frameworkExecutorRepository.getConnectivityScheduledExecutor()); - this.addExecutors("cacheRefreshingScheduledExecutor", frameworkExecutorRepository.getCacheRefreshingScheduledExecutor()); + this.addExecutors( + "connectivityScheduledExecutor", frameworkExecutorRepository.getConnectivityScheduledExecutor()); + this.addExecutors( + "cacheRefreshingScheduledExecutor", frameworkExecutorRepository.getCacheRefreshingScheduledExecutor()); this.addExecutors("sharedExecutor", frameworkExecutorRepository.getSharedExecutor()); this.addExecutors("sharedScheduledExecutor", frameworkExecutorRepository.getSharedScheduledExecutor()); this.addExecutors("mappingRefreshingExecutor", frameworkExecutorRepository.getMappingRefreshingExecutor()); diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ThreadRejectMetricsCountSampler.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ThreadRejectMetricsCountSampler.java index 2638777574..e6950ade29 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ThreadRejectMetricsCountSampler.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/collector/sample/ThreadRejectMetricsCountSampler.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.collector.sample; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; @@ -31,22 +30,25 @@ import static org.apache.dubbo.metrics.model.MetricsCategory.THREAD_POOL; public class ThreadRejectMetricsCountSampler extends MetricsNameCountSampler { public ThreadRejectMetricsCountSampler(DefaultMetricsCollector collector) { - super(collector, THREAD_POOL,MetricsKey.THREAD_POOL_THREAD_REJECT_COUNT); + super(collector, THREAD_POOL, MetricsKey.THREAD_POOL_THREAD_REJECT_COUNT); } @Override - protected MetricSample provideMetricsSample(ThreadPoolRejectMetric metric, AtomicLong count, MetricsKey metricsKey, MetricsCategory metricsCategory) { + protected MetricSample provideMetricsSample( + ThreadPoolRejectMetric metric, AtomicLong count, MetricsKey metricsKey, MetricsCategory metricsCategory) { return new GaugeMetricSample<>( - metricsKey.getNameByType(metric.getThreadPoolName()), - metricsKey.getDescription(), - metric.getTags(), - metricsCategory, - count, - AtomicLong::get); + metricsKey.getNameByType(metric.getThreadPoolName()), + metricsKey.getDescription(), + metric.getTags(), + metricsCategory, + count, + AtomicLong::get); } @Override - protected void countConfigure(MetricsCountSampleConfigurer sampleConfigure) { - sampleConfigure.configureMetrics(configure -> new ThreadPoolRejectMetric(collector.getApplicationName(),configure.getSource())); + protected void countConfigure( + MetricsCountSampleConfigurer sampleConfigure) { + sampleConfigure.configureMetrics( + configure -> new ThreadPoolRejectMetric(collector.getApplicationName(), configure.getSource())); } } diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/DefaultSubDispatcher.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/DefaultSubDispatcher.java index d9a88c466d..ca84829f9e 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/DefaultSubDispatcher.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/DefaultSubDispatcher.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.event; import org.apache.dubbo.common.constants.CommonConstants; @@ -50,30 +49,43 @@ public final class DefaultSubDispatcher extends SimpleMetricsEventMulticaster { return event instanceof RequestEvent && ((RequestEvent) event).isRequestErrorEvent(); } - private final MetricsPlaceValue dynamicPlaceType = MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD); + private final MetricsPlaceValue dynamicPlaceType = + MetricsPlaceValue.of(CommonConstants.CONSUMER, MetricsLevel.METHOD); + @Override public void onEvent(RequestEvent event) { - MetricsSupport.increment(METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED, dynamicPlaceType, (MethodMetricsCollector) collector, event); + MetricsSupport.increment( + METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED, + dynamicPlaceType, + (MethodMetricsCollector) collector, + event); } }); } - private CategoryOverall initMethodRequest() { - return new CategoryOverall(null, - new MetricsCat(MetricsKey.METRIC_REQUESTS, (key, placeType, collector) -> AbstractMetricsKeyListener.onEvent(key, - event -> - { - MetricsPlaceValue dynamicPlaceType = MetricsPlaceValue.of(event.getAttachmentValue(MetricsConstants.INVOCATION_SIDE), MetricsLevel.METHOD); + return new CategoryOverall( + null, + new MetricsCat( + MetricsKey.METRIC_REQUESTS, + (key, placeType, collector) -> AbstractMetricsKeyListener.onEvent(key, event -> { + MetricsPlaceValue dynamicPlaceType = MetricsPlaceValue.of( + event.getAttachmentValue(MetricsConstants.INVOCATION_SIDE), MetricsLevel.METHOD); MetricsSupport.increment(key, dynamicPlaceType, (MethodMetricsCollector) collector, event); - MetricsSupport.increment(MetricsKey.METRIC_REQUESTS_PROCESSING, dynamicPlaceType, (MethodMetricsCollector) collector, event); + MetricsSupport.increment( + MetricsKey.METRIC_REQUESTS_PROCESSING, + dynamicPlaceType, + (MethodMetricsCollector) collector, + event); })), - new MetricsCat(MetricsKey.METRIC_REQUESTS_SUCCEED, (key, placeType, collector) -> AbstractMetricsKeyListener.onFinish(key, - event -> - { - MetricsPlaceValue dynamicPlaceType = MetricsPlaceValue.of(event.getAttachmentValue(MetricsConstants.INVOCATION_SIDE), MetricsLevel.METHOD); - MetricsSupport.dec(MetricsKey.METRIC_REQUESTS_PROCESSING, dynamicPlaceType, collector, event); + new MetricsCat( + MetricsKey.METRIC_REQUESTS_SUCCEED, + (key, placeType, collector) -> AbstractMetricsKeyListener.onFinish(key, event -> { + MetricsPlaceValue dynamicPlaceType = MetricsPlaceValue.of( + event.getAttachmentValue(MetricsConstants.INVOCATION_SIDE), MetricsLevel.METHOD); + MetricsSupport.dec( + MetricsKey.METRIC_REQUESTS_PROCESSING, dynamicPlaceType, collector, event); Object throwableObj = event.getAttachmentValue(METRIC_THROWABLE); MetricsKey targetKey; @@ -81,22 +93,32 @@ public final class DefaultSubDispatcher extends SimpleMetricsEventMulticaster { targetKey = key; } else { targetKey = MetricsSupport.getMetricsKey((Throwable) throwableObj); - MetricsSupport.increment(MetricsKey.METRIC_REQUESTS_TOTAL_FAILED, dynamicPlaceType, (MethodMetricsCollector) collector, event); + MetricsSupport.increment( + MetricsKey.METRIC_REQUESTS_TOTAL_FAILED, + dynamicPlaceType, + (MethodMetricsCollector) collector, + event); } - MetricsSupport.incrAndAddRt(targetKey, dynamicPlaceType, (MethodMetricsCollector) collector, event); + MetricsSupport.incrAndAddRt( + targetKey, dynamicPlaceType, (MethodMetricsCollector) collector, event); })), - new MetricsCat(MetricsKey.METRIC_REQUEST_BUSINESS_FAILED, (key, placeType, collector) -> AbstractMetricsKeyListener.onError(key, - event -> - { - MetricsKey targetKey = MetricsSupport.getMetricsKey(event.getAttachmentValue(METRIC_THROWABLE)); + new MetricsCat( + MetricsKey.METRIC_REQUEST_BUSINESS_FAILED, + (key, placeType, collector) -> AbstractMetricsKeyListener.onError(key, event -> { + MetricsKey targetKey = + MetricsSupport.getMetricsKey(event.getAttachmentValue(METRIC_THROWABLE)); // Dynamic metricsKey && dynamicPlaceType - MetricsPlaceValue dynamicPlaceType = MetricsPlaceValue.of(event.getAttachmentValue(MetricsConstants.INVOCATION_SIDE), MetricsLevel.METHOD); - MetricsSupport.increment(MetricsKey.METRIC_REQUESTS_TOTAL_FAILED, dynamicPlaceType, (MethodMetricsCollector) collector, event); - MetricsSupport.dec(MetricsKey.METRIC_REQUESTS_PROCESSING, dynamicPlaceType, collector, event); - MetricsSupport.incrAndAddRt(targetKey, dynamicPlaceType, (MethodMetricsCollector) collector, event); - } - ))); - + MetricsPlaceValue dynamicPlaceType = MetricsPlaceValue.of( + event.getAttachmentValue(MetricsConstants.INVOCATION_SIDE), MetricsLevel.METHOD); + MetricsSupport.increment( + MetricsKey.METRIC_REQUESTS_TOTAL_FAILED, + dynamicPlaceType, + (MethodMetricsCollector) collector, + event); + MetricsSupport.dec( + MetricsKey.METRIC_REQUESTS_PROCESSING, dynamicPlaceType, collector, event); + MetricsSupport.incrAndAddRt( + targetKey, dynamicPlaceType, (MethodMetricsCollector) collector, event); + }))); } - } diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/RequestEvent.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/RequestEvent.java index 4773ce158a..732aab1dce 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/RequestEvent.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/event/RequestEvent.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.event; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; @@ -40,10 +39,17 @@ import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUEST_BUSIN * Request related events */ public class RequestEvent extends TimeCounterEvent { - private static final TypeWrapper REQUEST_EVENT = new TypeWrapper(MetricsLevel.SERVICE, METRIC_REQUESTS, METRIC_REQUESTS_SUCCEED, METRIC_REQUEST_BUSINESS_FAILED); - private static final TypeWrapper REQUEST_ERROR_EVENT = new TypeWrapper(MetricsLevel.METHOD, MetricsKey.METRIC_REQUESTS); + private static final TypeWrapper REQUEST_EVENT = new TypeWrapper( + MetricsLevel.SERVICE, METRIC_REQUESTS, METRIC_REQUESTS_SUCCEED, METRIC_REQUEST_BUSINESS_FAILED); + private static final TypeWrapper REQUEST_ERROR_EVENT = + new TypeWrapper(MetricsLevel.METHOD, MetricsKey.METRIC_REQUESTS); - public RequestEvent(ApplicationModel applicationModel, String appName, MetricsDispatcher metricsDispatcher, DefaultMetricsCollector collector, TypeWrapper TYPE_WRAPPER) { + public RequestEvent( + ApplicationModel applicationModel, + String appName, + MetricsDispatcher metricsDispatcher, + DefaultMetricsCollector collector, + TypeWrapper TYPE_WRAPPER) { super(applicationModel, appName, metricsDispatcher, TYPE_WRAPPER); if (collector == null) { ScopeBeanFactory beanFactory = applicationModel.getBeanFactory(); @@ -54,11 +60,17 @@ public class RequestEvent extends TimeCounterEvent { super.setAvailable(collector != null && collector.isCollectEnabled()); } - public static RequestEvent toRequestEvent(ApplicationModel applicationModel, String appName, - MetricsDispatcher metricsDispatcher, DefaultMetricsCollector collector, - Invocation invocation, String side, boolean serviceLevel) { + public static RequestEvent toRequestEvent( + ApplicationModel applicationModel, + String appName, + MetricsDispatcher metricsDispatcher, + DefaultMetricsCollector collector, + Invocation invocation, + String side, + boolean serviceLevel) { MethodMetric methodMetric = new MethodMetric(applicationModel, invocation, serviceLevel); - RequestEvent requestEvent = new RequestEvent(applicationModel, appName, metricsDispatcher, collector, REQUEST_EVENT); + RequestEvent requestEvent = + new RequestEvent(applicationModel, appName, metricsDispatcher, collector, REQUEST_EVENT); requestEvent.putAttachment(MetricsConstants.INVOCATION, invocation); requestEvent.putAttachment(MetricsConstants.METHOD_METRICS, methodMetric); requestEvent.putAttachment(ATTACHMENT_KEY_SERVICE, MetricsSupport.getInterfaceName(invocation)); @@ -72,7 +84,8 @@ public class RequestEvent extends TimeCounterEvent { return; } if (!(postResult instanceof Result)) { - throw new MetricsNeverHappenException("Result type error, postResult:" + postResult.getClass().getName()); + throw new MetricsNeverHappenException( + "Result type error, postResult:" + postResult.getClass().getName()); } super.putAttachment(METRIC_THROWABLE, ((Result) postResult).getException()); } @@ -80,17 +93,25 @@ public class RequestEvent extends TimeCounterEvent { /** * Acts on MetricsClusterFilter to monitor exceptions that occur before request execution */ - public static RequestEvent toRequestErrorEvent(ApplicationModel applicationModel, String appName, MetricsDispatcher metricsDispatcher, Invocation invocation, String side, int code, boolean serviceLevel) { - RequestEvent event = new RequestEvent(applicationModel, appName, metricsDispatcher, null, REQUEST_ERROR_EVENT); + public static RequestEvent toRequestErrorEvent( + ApplicationModel applicationModel, + String appName, + MetricsDispatcher metricsDispatcher, + Invocation invocation, + String side, + int code, + boolean serviceLevel) { + RequestEvent event = new RequestEvent(applicationModel, appName, metricsDispatcher, null, REQUEST_ERROR_EVENT); event.putAttachment(ATTACHMENT_KEY_SERVICE, MetricsSupport.getInterfaceName(invocation)); event.putAttachment(MetricsConstants.INVOCATION_SIDE, side); event.putAttachment(MetricsConstants.INVOCATION, invocation); event.putAttachment(MetricsConstants.INVOCATION_REQUEST_ERROR, code); - event.putAttachment(MetricsConstants.METHOD_METRICS, new MethodMetric(applicationModel, invocation, serviceLevel)); + event.putAttachment( + MetricsConstants.METHOD_METRICS, new MethodMetric(applicationModel, invocation, serviceLevel)); return event; } - public boolean isRequestErrorEvent(){ + public boolean isRequestErrorEvent() { return super.getAttachmentValue(MetricsConstants.INVOCATION_REQUEST_ERROR) != null; } } diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsFilter.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsFilter.java index 0496443732..900dc7002b 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsFilter.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsFilter.java @@ -51,7 +51,11 @@ public class MetricsFilter implements ScopeModelAware { @Override public void setApplicationModel(ApplicationModel applicationModel) { this.applicationModel = applicationModel; - this.rpcMetricsEnable = applicationModel.getApplicationConfigManager().getMetrics().map(MetricsConfig::getEnableRpc).orElse(true); + this.rpcMetricsEnable = applicationModel + .getApplicationConfigManager() + .getMetrics() + .map(MetricsConfig::getEnableRpc) + .orElse(true); this.appName = applicationModel.tryGetApplicationName(); this.metricsDispatcher = applicationModel.getBeanFactory().getBean(MetricsDispatcher.class); this.defaultMetricsCollector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); @@ -65,8 +69,14 @@ public class MetricsFilter implements ScopeModelAware { public Result invoke(Invoker invoker, Invocation invocation, boolean isProvider) throws RpcException { if (rpcMetricsEnable) { try { - RequestEvent requestEvent = RequestEvent.toRequestEvent(applicationModel, appName, metricsDispatcher, - defaultMetricsCollector, invocation, isProvider ? PROVIDER : CONSUMER, serviceLevel); + RequestEvent requestEvent = RequestEvent.toRequestEvent( + applicationModel, + appName, + metricsDispatcher, + defaultMetricsCollector, + invocation, + isProvider ? PROVIDER : CONSUMER, + serviceLevel); MetricsEventBus.before(requestEvent); invocation.put(METRIC_FILTER_EVENT, requestEvent); } catch (Throwable t) { @@ -107,5 +117,4 @@ public class MetricsFilter implements ScopeModelAware { } } } - } diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsProviderFilter.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsProviderFilter.java index 68502bdfba..4e651a192a 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsProviderFilter.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/filter/MetricsProviderFilter.java @@ -26,10 +26,11 @@ import org.apache.dubbo.rpc.RpcException; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; -@Activate(group = {PROVIDER}, order = Integer.MIN_VALUE + 100) +@Activate( + group = {PROVIDER}, + order = Integer.MIN_VALUE + 100) public class MetricsProviderFilter extends MetricsFilter implements Filter, BaseFilter.Listener { - public MetricsProviderFilter() { - } + public MetricsProviderFilter() {} @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/register/HistogramMetricRegister.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/register/HistogramMetricRegister.java index 04a173cdee..b501da2329 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/register/HistogramMetricRegister.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/register/HistogramMetricRegister.java @@ -14,12 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.register; -import io.micrometer.core.instrument.MeterRegistry; -import io.micrometer.core.instrument.Tag; -import io.micrometer.core.instrument.Timer; import org.apache.dubbo.config.nested.HistogramConfig; import org.apache.dubbo.metrics.sample.HistogramMetricSample; @@ -28,6 +24,10 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import io.micrometer.core.instrument.MeterRegistry; +import io.micrometer.core.instrument.Tag; +import io.micrometer.core.instrument.Timer; + public class HistogramMetricRegister implements MetricRegister { private final MeterRegistry registry; @@ -49,7 +49,9 @@ public class HistogramMetricRegister implements MetricRegister { M register(S sample); - } diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsReporter.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsReporter.java index ac0700221f..b9494bb735 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsReporter.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsReporter.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.report; import org.apache.dubbo.common.URL; @@ -32,6 +31,13 @@ import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + import io.micrometer.core.instrument.FunctionCounter; import io.micrometer.core.instrument.Gauge; import io.micrometer.core.instrument.MeterRegistry; @@ -45,13 +51,6 @@ import io.micrometer.core.instrument.binder.system.ProcessorMetrics; import io.micrometer.core.instrument.binder.system.UptimeMetrics; import io.micrometer.core.instrument.composite.CompositeMeterRegistry; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION; import static org.apache.dubbo.common.constants.MetricsConstants.COLLECTOR_SYNC_PERIOD_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.ENABLE_COLLECTOR_SYNC_KEY; @@ -67,6 +66,7 @@ public abstract class AbstractMetricsReporter implements MetricsReporter { private final AtomicBoolean initialized = new AtomicBoolean(false); protected final URL url; + @SuppressWarnings("rawtypes") protected final List collectors = new ArrayList<>(); // Avoid instances being gc due to weak references @@ -103,7 +103,6 @@ public abstract class AbstractMetricsReporter implements MetricsReporter { compositeRegistry.add(registry); } - protected ApplicationModel getApplicationModel() { return applicationModel; } @@ -115,7 +114,8 @@ public abstract class AbstractMetricsReporter implements MetricsReporter { new JvmMemoryMetrics().bindTo(compositeRegistry); @SuppressWarnings("java:S2095") - // Do not change JvmGcMetrics to try-with-resources as the JvmGcMetrics will not be available after (auto-)closing. + // Do not change JvmGcMetrics to try-with-resources as the JvmGcMetrics will not be available after + // (auto-)closing. // See https://github.com/micrometer-metrics/micrometer/issues/1492 JvmGcMetrics jvmGcMetrics = new JvmGcMetrics(); jvmGcMetrics.bindTo(compositeRegistry); @@ -148,7 +148,8 @@ public abstract class AbstractMetricsReporter implements MetricsReporter { NamedThreadFactory threadFactory = new NamedThreadFactory("metrics-collector-sync-job", true); collectorSyncJobExecutor = Executors.newScheduledThreadPool(1, threadFactory); - collectorSyncJobExecutor.scheduleWithFixedDelay(this::resetIfSamplesChanged, DEFAULT_SCHEDULE_INITIAL_DELAY, collectSyncPeriod, TimeUnit.SECONDS); + collectorSyncJobExecutor.scheduleWithFixedDelay( + this::resetIfSamplesChanged, DEFAULT_SCHEDULE_INITIAL_DELAY, collectSyncPeriod, TimeUnit.SECONDS); } } @@ -165,7 +166,12 @@ public abstract class AbstractMetricsReporter implements MetricsReporter { try { registerSample(sample); } catch (Exception e) { - logger.error(COMMON_METRICS_COLLECTOR_EXCEPTION, "", "", "error occurred when synchronize metrics collector.", e); + logger.error( + COMMON_METRICS_COLLECTOR_EXCEPTION, + "", + "", + "error occurred when synchronize metrics collector.", + e); } } }); @@ -192,17 +198,17 @@ public abstract class AbstractMetricsReporter implements MetricsReporter { @SuppressWarnings({"rawtypes"}) private void registerCounterSample(CounterMetricSample sample) { FunctionCounter.builder(sample.getName(), sample.getValue(), Number::doubleValue) - .description(sample.getDescription()) - .tags(getTags(sample)) - .register(compositeRegistry); + .description(sample.getDescription()) + .tags(getTags(sample)) + .register(compositeRegistry); } @SuppressWarnings({"unchecked", "rawtypes"}) private void registerGaugeSample(GaugeMetricSample sample) { Gauge.builder(sample.getName(), sample.getValue(), sample.getApply()) - .description(sample.getDescription()) - .tags(getTags(sample)) - .register(compositeRegistry); + .description(sample.getDescription()) + .tags(getTags(sample)) + .register(compositeRegistry); } private static List getTags(MetricSample gaugeSample) { diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/DefaultMetricsReporter.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/DefaultMetricsReporter.java index 88e16ec56c..7d018ddf2e 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/DefaultMetricsReporter.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/DefaultMetricsReporter.java @@ -14,24 +14,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.report; -import io.micrometer.core.instrument.Counter; -import io.micrometer.core.instrument.Gauge; -import io.micrometer.core.instrument.Tag; -import io.micrometer.core.instrument.Timer; -import io.micrometer.core.instrument.simple.SimpleMeterRegistry; - import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.HashMap; import java.util.List; import java.util.Map; - import java.util.concurrent.TimeUnit; +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.Gauge; +import io.micrometer.core.instrument.Tag; +import io.micrometer.core.instrument.Timer; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; + public class DefaultMetricsReporter extends AbstractMetricsReporter { SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); @@ -50,31 +48,33 @@ public class DefaultMetricsReporter extends AbstractMetricsReporter { Map> metricsTags = new HashMap<>(); Map metricsValue = new HashMap<>(); StringBuilder sb = new StringBuilder(); - meterRegistry.getMeters().stream().filter(meter -> { - if (meter == null || meter.getId() == null || meter.getId().getName() == null) { - return false; - } - if (metricsName != null) { - return meter.getId().getName().contains(metricsName); - } - return true; - }).forEach(meter -> { - Object value = null; - if (meter instanceof Counter) { - Counter counter = (Counter) meter; - value = counter.count(); - } - if (meter instanceof Gauge) { - Gauge gauge = (Gauge) meter; - value = gauge.value(); - } - if (meter instanceof Timer) { - Timer timer = (Timer) meter; - value = timer.totalTime(TimeUnit.MILLISECONDS); - } - metricsTags.put(meter.getId().getName(), meter.getId().getTags()); - metricsValue.put(meter.getId().getName(), value); - }); + meterRegistry.getMeters().stream() + .filter(meter -> { + if (meter == null || meter.getId() == null || meter.getId().getName() == null) { + return false; + } + if (metricsName != null) { + return meter.getId().getName().contains(metricsName); + } + return true; + }) + .forEach(meter -> { + Object value = null; + if (meter instanceof Counter) { + Counter counter = (Counter) meter; + value = counter.count(); + } + if (meter instanceof Gauge) { + Gauge gauge = (Gauge) meter; + value = gauge.value(); + } + if (meter instanceof Timer) { + Timer timer = (Timer) meter; + value = timer.totalTime(TimeUnit.MILLISECONDS); + } + metricsTags.put(meter.getId().getName(), meter.getId().getTags()); + metricsValue.put(meter.getId().getName(), value); + }); metricsValue.forEach((key, value) -> { sb.append(key).append("{"); List tags = metricsTags.get(key); @@ -94,7 +94,5 @@ public class DefaultMetricsReporter extends AbstractMetricsReporter { } @Override - protected void doDestroy() { - - } + protected void doDestroy() {} } diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/DefaultMetricsReporterFactory.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/DefaultMetricsReporterFactory.java index 504d964db6..e64a7adf05 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/DefaultMetricsReporterFactory.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/DefaultMetricsReporterFactory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.report; import org.apache.dubbo.common.URL; diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/nop/NopMetricsReporter.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/nop/NopMetricsReporter.java index f326f5467c..9d6952c191 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/nop/NopMetricsReporter.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/nop/NopMetricsReporter.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.report.nop; import org.apache.dubbo.common.URL; @@ -25,19 +24,13 @@ import org.apache.dubbo.metrics.report.MetricsReporter; */ public class NopMetricsReporter implements MetricsReporter { - public NopMetricsReporter(URL url) { - - } + public NopMetricsReporter(URL url) {} @Override - public void init() { - - } + public void init() {} @Override - public void resetIfSamplesChanged() { - - } + public void resetIfSamplesChanged() {} @Override public String getResponse() { diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/nop/NopMetricsReporterFactory.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/nop/NopMetricsReporterFactory.java index 28980e4ef9..50e781bf20 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/nop/NopMetricsReporterFactory.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/report/nop/NopMetricsReporterFactory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.report.nop; import org.apache.dubbo.common.URL; diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/sample/HistogramMetricSample.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/sample/HistogramMetricSample.java index 8f8149c1b5..b9f2281659 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/sample/HistogramMetricSample.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/sample/HistogramMetricSample.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.sample; import org.apache.dubbo.metrics.model.MetricsCategory; @@ -28,7 +27,13 @@ public class HistogramMetricSample extends MetricSample { super(name, description, tags, Type.TIMER, category); } - public HistogramMetricSample(String name, String description, Map tags, Type type, MetricsCategory category, String baseUnit) { + public HistogramMetricSample( + String name, + String description, + Map tags, + Type type, + MetricsCategory category, + String baseUnit) { super(name, description, tags, type, category, baseUnit); } } diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/service/DefaultMetricsService.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/service/DefaultMetricsService.java index eeb07827ca..2548bb8104 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/service/DefaultMetricsService.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/metrics/service/DefaultMetricsService.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.service; import org.apache.dubbo.metrics.collector.MetricsCollector; @@ -46,12 +45,14 @@ public class DefaultMetricsService implements MetricsService { } @Override - public Map> getMetricsByCategories(String serviceUniqueName, List categories) { + public Map> getMetricsByCategories( + String serviceUniqueName, List categories) { return getMetricsByCategories(serviceUniqueName, null, null, categories); } @Override - public Map> getMetricsByCategories(String serviceUniqueName, String methodName, Class[] parameterTypes, List categories) { + public Map> getMetricsByCategories( + String serviceUniqueName, String methodName, Class[] parameterTypes, List categories) { Map> result = new HashMap<>(); for (MetricsCollector collector : collectors) { List samples = collector.collect(); diff --git a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsClusterFilter.java b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsClusterFilter.java index 9a53935032..35f9942fe4 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsClusterFilter.java +++ b/dubbo-metrics/dubbo-metrics-default/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsClusterFilter.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.filter.support; - import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; import org.apache.dubbo.metrics.event.MetricsDispatcher; @@ -76,9 +74,15 @@ public class MetricsClusterFilter implements ClusterFilter, BaseFilter.Listener, if (t instanceof RpcException) { RpcException e = (RpcException) t; if (e.isForbidden()) { - MetricsEventBus.publish(RequestEvent.toRequestErrorEvent(applicationModel, appName, metricsDispatcher, invocation, CONSUMER_SIDE, e.getCode(), serviceLevel)); + MetricsEventBus.publish(RequestEvent.toRequestErrorEvent( + applicationModel, + appName, + metricsDispatcher, + invocation, + CONSUMER_SIDE, + e.getCode(), + serviceLevel)); } } } - } diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java index 5bb8c014b7..c61fd48620 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/DefaultMetricsServiceTest.java @@ -24,15 +24,16 @@ import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.metrics.service.DefaultMetricsService; import org.apache.dubbo.metrics.service.MetricsEntity; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; import java.util.Collections; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + import static org.mockito.Mockito.when; @SuppressWarnings("rawtypes") @@ -42,7 +43,6 @@ public class DefaultMetricsServiceTest { private DefaultMetricsService defaultMetricsService; - @BeforeEach public void setUp() { ApplicationModel applicationModel = Mockito.mock(ApplicationModel.class); @@ -50,7 +50,8 @@ public class DefaultMetricsServiceTest { metricsCollector = Mockito.mock(MetricsCollector.class); when(applicationModel.getBeanFactory()).thenReturn(beanFactory); - when(beanFactory.getBeansOfType(MetricsCollector.class)).thenReturn(Collections.singletonList(metricsCollector)); + when(beanFactory.getBeansOfType(MetricsCollector.class)) + .thenReturn(Collections.singletonList(metricsCollector)); defaultMetricsService = new DefaultMetricsService(applicationModel); } @@ -58,13 +59,7 @@ public class DefaultMetricsServiceTest { @Test public void testGetMetricsByCategories() { MetricSample sample = new GaugeMetricSample<>( - "testMetric", - "testDescription", - null, - MetricsCategory.REQUESTS, - 42, - value -> 42.0 - ); + "testMetric", "testDescription", null, MetricsCategory.REQUESTS, 42, value -> 42.0); when(metricsCollector.collect()).thenReturn(Collections.singletonList(sample)); List categories = Collections.singletonList(MetricsCategory.REQUESTS); diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/TestMetricsInvoker.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/TestMetricsInvoker.java index a9edf9507a..5b53eaa087 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/TestMetricsInvoker.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/TestMetricsInvoker.java @@ -42,7 +42,7 @@ public class TestMetricsInvoker implements Invoker { @Override public URL getUrl() { - return URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side="+side); + return URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=" + side); } @Override @@ -51,7 +51,5 @@ public class TestMetricsInvoker implements Invoker { } @Override - public void destroy() { - - } + public void destroy() {} } diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java index ce34ce01fd..ef049eb49c 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/AggregateMetricsCollectorTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.collector; import org.apache.dubbo.common.URL; @@ -49,11 +48,6 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -62,6 +56,11 @@ import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_GROUP_KEY; @@ -89,7 +88,8 @@ class AggregateMetricsCollectorTest { public MethodMetric getTestMethodMetric() { - MethodMetric methodMetric = new MethodMetric(applicationModel, invocation, MethodMetric.isServiceLevel(applicationModel)); + MethodMetric methodMetric = + new MethodMetric(applicationModel, invocation, MethodMetric.isServiceLevel(applicationModel)); methodMetric.setGroup("TestGroup"); methodMetric.setVersion("1.0.0"); methodMetric.setSide("PROVIDER"); @@ -133,15 +133,29 @@ class AggregateMetricsCollectorTest { side = CommonConstants.CONSUMER; invocation.setInvoker(new TestMetricsInvoker(side)); invocation.setTargetServiceUniqueName(group + "/" + interfaceName + ":" + version); - RpcContext.getServiceContext().setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=" + side)); - + RpcContext.getServiceContext() + .setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=" + side)); } @Test void testListener() { AggregateMetricsCollector metricsCollector = new AggregateMetricsCollector(applicationModel); - RequestEvent event = RequestEvent.toRequestEvent(applicationModel, null, null, null, invocation, MetricsSupport.getSide(invocation), MethodMetric.isServiceLevel(applicationModel)); - RequestEvent beforeEvent = RequestEvent.toRequestErrorEvent(applicationModel, null, null, invocation, MetricsSupport.getSide(invocation), RpcException.FORBIDDEN_EXCEPTION, MethodMetric.isServiceLevel(applicationModel)); + RequestEvent event = RequestEvent.toRequestEvent( + applicationModel, + null, + null, + null, + invocation, + MetricsSupport.getSide(invocation), + MethodMetric.isServiceLevel(applicationModel)); + RequestEvent beforeEvent = RequestEvent.toRequestErrorEvent( + applicationModel, + null, + null, + invocation, + MetricsSupport.getSide(invocation), + RpcException.FORBIDDEN_EXCEPTION, + MethodMetric.isServiceLevel(applicationModel)); Assertions.assertTrue(metricsCollector.isSupport(event)); Assertions.assertTrue(metricsCollector.isSupport(beforeEvent)); @@ -169,7 +183,6 @@ class AggregateMetricsCollectorTest { Result result = AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation); metricsFilter.onResponse(result, new TestMetricsInvoker(side), invocation); - List samples = collector.collect(); for (MetricSample sample : samples) { Map tags = sample.getTags(); @@ -183,7 +196,8 @@ class AggregateMetricsCollectorTest { samples = collector.collect(); @SuppressWarnings("rawtypes") - Map sampleMap = samples.stream().collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); + Map sampleMap = samples.stream() + .collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); Assertions.assertEquals(sampleMap.get(MetricsKey.METRIC_REQUESTS_NETWORK_FAILED_AGG.getNameByType(side)), 1L); Assertions.assertTrue(sampleMap.containsKey(MetricsKey.METRIC_QPS.getNameByType(side))); @@ -216,7 +230,8 @@ class AggregateMetricsCollectorTest { } @SuppressWarnings("unchecked") - ConcurrentHashMap qps = (ConcurrentHashMap) ReflectionUtils.getField(collector, "qps"); + ConcurrentHashMap qps = + (ConcurrentHashMap) ReflectionUtils.getField(collector, "qps"); qps.put(methodMetric, qpsCounter); List collectedQPS = new ArrayList<>(); @@ -233,7 +248,6 @@ class AggregateMetricsCollectorTest { Assertions.assertEquals(10000, ((TimeWindowCounter) ((GaugeMetricSample) sample).getValue()).get()); } - @Test public void testRtAggregation() { metricsDispatcher.addListener(collector); @@ -248,9 +262,17 @@ class AggregateMetricsCollectorTest { rtList.add(20L); rtList.add(30L); - for (Long requestTime: rtList) { - RequestEvent requestEvent = RequestEvent.toRequestEvent(applicationModel, null, null, null, invocation, MetricsSupport.getSide(invocation), MethodMetric.isServiceLevel(applicationModel)); - TestRequestEvent testRequestEvent = new TestRequestEvent(requestEvent.getSource(), requestEvent.getTypeWrapper()); + for (Long requestTime : rtList) { + RequestEvent requestEvent = RequestEvent.toRequestEvent( + applicationModel, + null, + null, + null, + invocation, + MetricsSupport.getSide(invocation), + MethodMetric.isServiceLevel(applicationModel)); + TestRequestEvent testRequestEvent = + new TestRequestEvent(requestEvent.getSource(), requestEvent.getTypeWrapper()); testRequestEvent.putAttachment(MetricsConstants.INVOCATION, invocation); testRequestEvent.putAttachment(ATTACHMENT_KEY_SERVICE, MetricsSupport.getInterfaceName(invocation)); testRequestEvent.putAttachment(MetricsConstants.INVOCATION_SIDE, MetricsSupport.getSide(invocation)); @@ -262,11 +284,11 @@ class AggregateMetricsCollectorTest { for (MetricSample sample : samples) { GaugeMetricSample gaugeMetricSample = (GaugeMetricSample) sample; - if(gaugeMetricSample.getName().endsWith("max.milliseconds.aggregate")) { - Assertions.assertEquals(30, gaugeMetricSample.applyAsDouble()); + if (gaugeMetricSample.getName().endsWith("max.milliseconds.aggregate")) { + Assertions.assertEquals(30, gaugeMetricSample.applyAsDouble()); } if (gaugeMetricSample.getName().endsWith("min.milliseconds.aggregate")) { - Assertions.assertEquals(10L, gaugeMetricSample.applyAsDouble()); + Assertions.assertEquals(10L, gaugeMetricSample.applyAsDouble()); } if (gaugeMetricSample.getName().endsWith("avg.milliseconds.aggregate")) { @@ -299,8 +321,16 @@ class AggregateMetricsCollectorTest { double manualP99 = requestTimes.get((int) Math.round(p99Index)); for (Long requestTime : requestTimes) { - RequestEvent requestEvent = RequestEvent.toRequestEvent(applicationModel, null, null, null, invocation, MetricsSupport.getSide(invocation), MethodMetric.isServiceLevel(applicationModel)); - TestRequestEvent testRequestEvent = new TestRequestEvent(requestEvent.getSource(), requestEvent.getTypeWrapper()); + RequestEvent requestEvent = RequestEvent.toRequestEvent( + applicationModel, + null, + null, + null, + invocation, + MetricsSupport.getSide(invocation), + MethodMetric.isServiceLevel(applicationModel)); + TestRequestEvent testRequestEvent = + new TestRequestEvent(requestEvent.getSource(), requestEvent.getTypeWrapper()); testRequestEvent.putAttachment(MetricsConstants.INVOCATION, invocation); testRequestEvent.putAttachment(ATTACHMENT_KEY_SERVICE, MetricsSupport.getInterfaceName(invocation)); testRequestEvent.putAttachment(MetricsConstants.INVOCATION_SIDE, MetricsSupport.getSide(invocation)); @@ -329,7 +359,7 @@ class AggregateMetricsCollectorTest { double p95 = p95Sample.applyAsDouble(); double p99 = p99Sample.applyAsDouble(); - //An error of less than 5% is allowed + // An error of less than 5% is allowed System.out.println(Math.abs(1 - p95 / manualP95)); Assertions.assertTrue(Math.abs(1 - p95 / manualP95) < 0.05); Assertions.assertTrue(Math.abs(1 - p99 / manualP99) < 0.05); @@ -337,7 +367,8 @@ class AggregateMetricsCollectorTest { @Test void testGenericCache() { - List> classGenerics = ReflectionUtils.getClassGenerics(AggregateMetricsCollector.class, MetricsListener.class); + List> classGenerics = + ReflectionUtils.getClassGenerics(AggregateMetricsCollector.class, MetricsListener.class); Assertions.assertTrue(CollectionUtils.isNotEmpty(classGenerics)); Assertions.assertEquals(RequestEvent.class, classGenerics.get(0)); } @@ -357,7 +388,6 @@ class AggregateMetricsCollectorTest { public TimePair getTimePair() { return new TestTimePair(rt); } - } public static class TestTimePair extends TimePair { @@ -375,4 +405,3 @@ class AggregateMetricsCollectorTest { } } } - diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/DefaultCollectorTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/DefaultCollectorTest.java index 724c685da1..9105d1b518 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/DefaultCollectorTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/DefaultCollectorTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.collector; import org.apache.dubbo.common.URL; @@ -22,7 +21,6 @@ import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.config.ApplicationConfig; -import org.apache.dubbo.metrics.MetricsConstants; import org.apache.dubbo.metrics.TestMetricsInvoker; import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.metrics.event.RequestEvent; @@ -46,16 +44,16 @@ import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME; @@ -66,7 +64,6 @@ import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS_SUCC import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS_TIMEOUT; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS_TOTAL_FAILED; - class DefaultCollectorTest { private ApplicationModel applicationModel; @@ -106,7 +103,8 @@ class DefaultCollectorTest { side = CommonConstants.CONSUMER; invocation.setInvoker(new TestMetricsInvoker(side)); invocation.setTargetServiceUniqueName(group + "/" + interfaceName + ":" + version); - RpcContext.getServiceContext().setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=" + side)); + RpcContext.getServiceContext() + .setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=" + side)); metricsFilter = new MetricsFilter(); metricsFilter.setApplicationModel(applicationModel); @@ -115,8 +113,22 @@ class DefaultCollectorTest { @Test void testListener() { DefaultMetricsCollector metricsCollector = new DefaultMetricsCollector(applicationModel); - RequestEvent event = RequestEvent.toRequestEvent(applicationModel, null, null, null, invocation, MetricsSupport.getSide(invocation), MethodMetric.isServiceLevel(applicationModel)); - RequestEvent beforeEvent = RequestEvent.toRequestErrorEvent(applicationModel, null, null, invocation, MetricsSupport.getSide(invocation), RpcException.FORBIDDEN_EXCEPTION, MethodMetric.isServiceLevel(applicationModel)); + RequestEvent event = RequestEvent.toRequestEvent( + applicationModel, + null, + null, + null, + invocation, + MetricsSupport.getSide(invocation), + MethodMetric.isServiceLevel(applicationModel)); + RequestEvent beforeEvent = RequestEvent.toRequestErrorEvent( + applicationModel, + null, + null, + invocation, + MetricsSupport.getSide(invocation), + RpcException.FORBIDDEN_EXCEPTION, + MethodMetric.isServiceLevel(applicationModel)); Assertions.assertTrue(metricsCollector.isSupport(event)); Assertions.assertTrue(metricsCollector.isSupport(beforeEvent)); @@ -134,11 +146,12 @@ class DefaultCollectorTest { void testRequestEventNoRt() { applicationModel.getBeanFactory().getOrRegisterBean(MetricsDispatcher.class); - DefaultMetricsCollector collector = applicationModel.getBeanFactory().getOrRegisterBean(DefaultMetricsCollector.class); + DefaultMetricsCollector collector = + applicationModel.getBeanFactory().getOrRegisterBean(DefaultMetricsCollector.class); collector.setCollectEnabled(true); ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DefaultCollectorTest.class); - logger.warn("0-99","","","Test error code message."); + logger.warn("0-99", "", "", "Test error code message."); metricsFilter.invoke(new TestMetricsInvoker(side), invocation); try { @@ -147,7 +160,7 @@ class DefaultCollectorTest { e.printStackTrace(); } AppResponse mockRpcResult = new AppResponse(); -// mockRpcResult.setException(new RpcException("hessian")); + // mockRpcResult.setException(new RpcException("hessian")); Result result = AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation); metricsFilter.onResponse(result, new TestMetricsInvoker(side), invocation); @@ -156,13 +169,19 @@ class DefaultCollectorTest { // push finish rt +1 List metricSamples = collector.collect(); - //num(total+success+processing) + rt(5) + error code = 9 - Assertions.assertEquals(metricSamples.size(),9); - List metricsNames = metricSamples.stream().map(MetricSample::getName).collect(Collectors.toList()); + // num(total+success+processing) + rt(5) + error code = 9 + Assertions.assertEquals(metricSamples.size(), 9); + List metricsNames = + metricSamples.stream().map(MetricSample::getName).collect(Collectors.toList()); // No error will contain total+success+processing - String REQUESTS = new MetricsKeyWrapper(METRIC_REQUESTS, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)).targetKey(); - String SUCCEED = new MetricsKeyWrapper(METRIC_REQUESTS_SUCCEED, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)).targetKey(); - String PROCESSING = new MetricsKeyWrapper(METRIC_REQUESTS_PROCESSING, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)).targetKey(); + String REQUESTS = + new MetricsKeyWrapper(METRIC_REQUESTS, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)).targetKey(); + String SUCCEED = new MetricsKeyWrapper( + METRIC_REQUESTS_SUCCEED, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)) + .targetKey(); + String PROCESSING = new MetricsKeyWrapper( + METRIC_REQUESTS_PROCESSING, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)) + .targetKey(); Assertions.assertTrue(metricsNames.contains(REQUESTS)); Assertions.assertTrue(metricsNames.contains(SUCCEED)); Assertions.assertTrue(metricsNames.contains(PROCESSING)); @@ -173,10 +192,12 @@ class DefaultCollectorTest { if (objVal instanceof Map) { Map value = (Map) objVal; if (metricSample.getName().equals(REQUESTS)) { - Assertions.assertTrue(value.values().stream().allMatch(atomicLong -> atomicLong.intValue() == 1)); + Assertions.assertTrue( + value.values().stream().allMatch(atomicLong -> atomicLong.intValue() == 1)); } if (metricSample.getName().equals(PROCESSING)) { - Assertions.assertTrue(value.values().stream().allMatch(atomicLong -> atomicLong.intValue() == 0)); + Assertions.assertTrue( + value.values().stream().allMatch(atomicLong -> atomicLong.intValue() == 0)); } } } else { @@ -193,7 +214,8 @@ class DefaultCollectorTest { } catch (InterruptedException e) { e.printStackTrace(); } - metricsFilter.onError(new RpcException(RpcException.TIMEOUT_EXCEPTION, "timeout"), new TestMetricsInvoker(side), invocation); + metricsFilter.onError( + new RpcException(RpcException.TIMEOUT_EXCEPTION, "timeout"), new TestMetricsInvoker(side), invocation); eventObj = (RequestEvent) invocation.get(METRIC_FILTER_EVENT); long c2 = eventObj.getTimePair().calc(); metricSamples = collector.collect(); @@ -201,28 +223,38 @@ class DefaultCollectorTest { // num(total+success+error+total_error+processing) + rt(5) + error code = 11 Assertions.assertEquals(11, metricSamples.size()); - String TIMEOUT = new MetricsKeyWrapper(METRIC_REQUESTS_TIMEOUT, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)).targetKey(); - String TOTAL_FAILED = new MetricsKeyWrapper(METRIC_REQUESTS_TOTAL_FAILED, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)).targetKey(); + String TIMEOUT = new MetricsKeyWrapper( + METRIC_REQUESTS_TIMEOUT, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)) + .targetKey(); + String TOTAL_FAILED = new MetricsKeyWrapper( + METRIC_REQUESTS_TOTAL_FAILED, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)) + .targetKey(); for (MetricSample metricSample : metricSamples) { if (metricSample instanceof GaugeMetricSample) { GaugeMetricSample gaugeMetricSample = (GaugeMetricSample) metricSample; Object objVal = gaugeMetricSample.getValue(); if (objVal instanceof Map) { - Map value = (Map) ((GaugeMetricSample) metricSample).getValue(); + Map value = + (Map) ((GaugeMetricSample) metricSample).getValue(); if (metricSample.getName().equals(REQUESTS)) { - Assertions.assertTrue(value.values().stream().allMatch(atomicLong -> atomicLong.intValue() == 2)); + Assertions.assertTrue( + value.values().stream().allMatch(atomicLong -> atomicLong.intValue() == 2)); } if (metricSample.getName().equals(REQUESTS)) { - Assertions.assertTrue(value.values().stream().allMatch(atomicLong -> atomicLong.intValue() == 2)); + Assertions.assertTrue( + value.values().stream().allMatch(atomicLong -> atomicLong.intValue() == 2)); } if (metricSample.getName().equals(PROCESSING)) { - Assertions.assertTrue(value.values().stream().allMatch(atomicLong -> atomicLong.intValue() == 0)); + Assertions.assertTrue( + value.values().stream().allMatch(atomicLong -> atomicLong.intValue() == 0)); } if (metricSample.getName().equals(TIMEOUT)) { - Assertions.assertTrue(value.values().stream().allMatch(atomicLong -> atomicLong.intValue() == 1)); + Assertions.assertTrue( + value.values().stream().allMatch(atomicLong -> atomicLong.intValue() == 1)); } if (metricSample.getName().equals(TOTAL_FAILED)) { - Assertions.assertTrue(value.values().stream().allMatch(atomicLong -> atomicLong.intValue() == 1)); + Assertions.assertTrue( + value.values().stream().allMatch(atomicLong -> atomicLong.intValue() == 1)); } } } else { @@ -233,20 +265,40 @@ class DefaultCollectorTest { } } - // calc rt for (MetricSample sample : metricSamples) { Map tags = sample.getTags(); Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), applicationModel.getApplicationName()); } - Map sampleMap = metricSamples.stream().filter(metricSample -> metricSample instanceof GaugeMetricSample).collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); + Map sampleMap = metricSamples.stream() + .filter(metricSample -> metricSample instanceof GaugeMetricSample) + .collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)).targetKey()), c2); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)).targetKey()), Math.min(c1, c2)); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)).targetKey()), Math.max(c1, c2)); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)).targetKey()), (c1 + c2) / 2); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)).targetKey()), c1 + c2); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper( + MetricsKey.METRIC_RT_LAST, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)) + .targetKey()), + c2); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper( + MetricsKey.METRIC_RT_MIN, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)) + .targetKey()), + Math.min(c1, c2)); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper( + MetricsKey.METRIC_RT_MAX, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)) + .targetKey()), + Math.max(c1, c2)); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper( + MetricsKey.METRIC_RT_AVG, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)) + .targetKey()), + (c1 + c2) / 2); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper( + MetricsKey.METRIC_RT_SUM, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)) + .targetKey()), + c1 + c2); } - } diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/InitServiceMetricsTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/InitServiceMetricsTest.java index eff1d0bc8f..f036eb7dfa 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/InitServiceMetricsTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/InitServiceMetricsTest.java @@ -14,8 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.collector; + import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MetricsConfig; @@ -34,15 +34,17 @@ import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; + import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.metrics.DefaultConstants.INIT_AGG_METHOD_KEYS; import static org.apache.dubbo.metrics.DefaultConstants.INIT_DEFAULT_METHOD_KEYS; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS; @@ -80,10 +82,11 @@ class InitServiceMetricsTest { applicationModel.getApplicationConfigManager().setMetrics(metricsConfig); applicationModel.getApplicationConfigManager().setApplication(config); - defaultCollector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); + defaultCollector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class); defaultCollector.setCollectEnabled(true); - aggregateMetricsCollector = applicationModel.getBeanFactory().getOrRegisterBean(AggregateMetricsCollector.class); + aggregateMetricsCollector = + applicationModel.getBeanFactory().getOrRegisterBean(AggregateMetricsCollector.class); aggregateMetricsCollector.setCollectEnabled(true); interfaceName = "org.apache.dubbo.MockInterface"; @@ -92,13 +95,14 @@ class InitServiceMetricsTest { version = "1.0.0"; side = CommonConstants.PROVIDER_SIDE; - String serviceKey=group+"/"+interfaceName+":"+version; + String serviceKey = group + "/" + interfaceName + ":" + version; - String protocolServiceKey=serviceKey+":dubbo"; - - RpcInvocation invocation = new RpcInvocation(serviceKey,null,methodName,interfaceName, protocolServiceKey, null, null,null,null,null,null); - MetricsEventBus.publish(MetricsInitEvent.toMetricsInitEvent(applicationModel,invocation, MethodMetric.isServiceLevel(applicationModel))); + String protocolServiceKey = serviceKey + ":dubbo"; + RpcInvocation invocation = new RpcInvocation( + serviceKey, null, methodName, interfaceName, protocolServiceKey, null, null, null, null, null, null); + MetricsEventBus.publish(MetricsInitEvent.toMetricsInitEvent( + applicationModel, invocation, MethodMetric.isServiceLevel(applicationModel))); } @AfterEach @@ -106,17 +110,20 @@ class InitServiceMetricsTest { applicationModel.destroy(); } - @Test void testMetricsInitEvent() { List metricSamples = defaultCollector.collect(); - //INIT_DEFAULT_METHOD_KEYS.size() = 6 + // INIT_DEFAULT_METHOD_KEYS.size() = 6 Assertions.assertEquals(INIT_DEFAULT_METHOD_KEYS.size(), metricSamples.size()); - List metricsNames = metricSamples.stream().map(MetricSample::getName).collect(Collectors.toList()); + List metricsNames = + metricSamples.stream().map(MetricSample::getName).collect(Collectors.toList()); - String REQUESTS = new MetricsKeyWrapper(METRIC_REQUESTS, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)).targetKey(); - String PROCESSING = new MetricsKeyWrapper(METRIC_REQUESTS_PROCESSING, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)).targetKey(); + String REQUESTS = + new MetricsKeyWrapper(METRIC_REQUESTS, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)).targetKey(); + String PROCESSING = new MetricsKeyWrapper( + METRIC_REQUESTS_PROCESSING, MetricsPlaceValue.of(side, MetricsLevel.SERVICE)) + .targetKey(); Assertions.assertTrue(metricsNames.contains(REQUESTS)); Assertions.assertTrue(metricsNames.contains(PROCESSING)); for (MetricSample metricSample : metricSamples) { @@ -133,21 +140,18 @@ class InitServiceMetricsTest { } } - List samples = aggregateMetricsCollector.collect(); - //INIT_AGG_METHOD_KEYS.size(10) + qps(1) + rt(4) +rtAgr(3)= 18 - Assertions.assertEquals(INIT_AGG_METHOD_KEYS.size()+ 1+ 4+ 3, samples.size()); + // INIT_AGG_METHOD_KEYS.size(10) + qps(1) + rt(4) +rtAgr(3)= 18 + Assertions.assertEquals(INIT_AGG_METHOD_KEYS.size() + 1 + 4 + 3, samples.size()); for (MetricSample metricSample : samples) { if (metricSample instanceof GaugeMetricSample) { GaugeMetricSample gaugeMetricSample = (GaugeMetricSample) metricSample; Object objVal = gaugeMetricSample.getValue(); if (objVal instanceof TimeWindowCounter) { - Assertions.assertEquals(0.0,((TimeWindowCounter) objVal).get()); + Assertions.assertEquals(0.0, ((TimeWindowCounter) objVal).get()); } } } - } - } diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java index dab9485771..d33fcc1070 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/collector/sample/ThreadPoolMetricsSamplerTest.java @@ -25,11 +25,6 @@ import org.apache.dubbo.metrics.model.ThreadPoolMetric; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; import java.lang.reflect.Field; import java.util.HashMap; @@ -39,6 +34,12 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SHARED_EXECUTOR_SERVICE_COMPONENT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_SERVICE_COMPONENT_KEY; import static org.mockito.Mockito.when; @@ -167,7 +168,7 @@ public class ThreadPoolMetricsSamplerTest { Field f = ThreadPoolMetricsSampler.class.getDeclaredField("sampleThreadPoolExecutor"); f.setAccessible(true); - Map executors = (Map) f.get(sampler2); + Map executors = (Map) f.get(sampler2); Assertions.assertEquals(8, executors.size()); Assertions.assertTrue(executors.containsKey("DubboServerHandler-server1")); diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/filter/MetricsFilterTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/filter/MetricsFilterTest.java index 358c4872d3..b668c77024 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/filter/MetricsFilterTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/filter/MetricsFilterTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.filter; import org.apache.dubbo.common.URL; @@ -38,11 +37,6 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -50,6 +44,11 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.stream.Collectors; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_PARAMETER_DESC; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_GROUP_KEY; @@ -76,7 +75,6 @@ class MetricsFilterTest { private AtomicBoolean initApplication = new AtomicBoolean(false); - @BeforeEach public void setup() { ApplicationConfig config = new ApplicationConfig(); @@ -94,7 +92,8 @@ class MetricsFilterTest { filter.setApplicationModel(applicationModel); side = CommonConstants.CONSUMER; invocation.setInvoker(new TestMetricsInvoker(side)); - RpcContext.getServiceContext().setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=" + side)); + RpcContext.getServiceContext() + .setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=" + side)); } @AfterEach @@ -112,7 +111,6 @@ class MetricsFilterTest { Assertions.assertTrue(metricsMap.isEmpty()); } - @Test void testUnknownFailedRequests() { collector.setCollectEnabled(true); @@ -167,7 +165,6 @@ class MetricsFilterTest { Assertions.assertEquals(tags.get(TAG_VERSION_KEY), VERSION); } - @Test void testTimeoutRequests() { collector.setCollectEnabled(true); @@ -192,7 +189,8 @@ class MetricsFilterTest { MetricSample timeoutSample = metricsMap.get(MetricsKey.METRIC_REQUESTS_TIMEOUT.getNameByType(side)); Assertions.assertSame(((CounterMetricSample) timeoutSample).getValue().longValue(), count); - CounterMetricSample failedSample = (CounterMetricSample) metricsMap.get(MetricsKey.METRIC_REQUESTS_TOTAL_FAILED.getNameByType(side)); + CounterMetricSample failedSample = + (CounterMetricSample) metricsMap.get(MetricsKey.METRIC_REQUESTS_TOTAL_FAILED.getNameByType(side)); Assertions.assertSame(failedSample.getValue().longValue(), count); } @@ -250,7 +248,7 @@ class MetricsFilterTest { given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); invocation.setTargetServiceUniqueName(INTERFACE_NAME + ":" + VERSION); invocation.setMethodName(METHOD_NAME); - invocation.setParameterTypes(new Class[]{String.class}); + invocation.setParameterTypes(new Class[] {String.class}); Result result = filter.invoke(invoker, invocation); @@ -273,9 +271,9 @@ class MetricsFilterTest { testFilterError(RpcException.NETWORK_EXCEPTION, MetricsKey.METRIC_REQUESTS_NETWORK_FAILED); } - private void testFilterError(int errorCode, MetricsKey metricsKey) { - String targetKey = new MetricsKeyWrapper(metricsKey, MetricsPlaceValue.of(side, MetricsLevel.METHOD)).targetKey(); + String targetKey = + new MetricsKeyWrapper(metricsKey, MetricsPlaceValue.of(side, MetricsLevel.METHOD)).targetKey(); setup(); collector.setCollectEnabled(true); given(invoker.invoke(invocation)).willThrow(new RpcException(errorCode)); @@ -298,7 +296,6 @@ class MetricsFilterTest { Assertions.assertSame(((CounterMetricSample) sample).getValue().longValue(), count); - Assertions.assertFalse(metricsMap.containsKey(metricsKey.getName())); Map tags = sample.getTags(); @@ -316,7 +313,7 @@ class MetricsFilterTest { given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); invocation.setTargetServiceUniqueName(GROUP + "/" + INTERFACE_NAME); invocation.setMethodName(METHOD_NAME); - invocation.setParameterTypes(new Class[]{String.class}); + invocation.setParameterTypes(new Class[] {String.class}); Result result = filter.invoke(invoker, invocation); @@ -339,7 +336,7 @@ class MetricsFilterTest { given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); invocation.setTargetServiceUniqueName(INTERFACE_NAME); invocation.setMethodName(METHOD_NAME); - invocation.setParameterTypes(new Class[]{String.class}); + invocation.setParameterTypes(new Class[] {String.class}); Result result = filter.invoke(invoker, invocation); @@ -362,13 +359,13 @@ class MetricsFilterTest { given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); invocation.setTargetServiceUniqueName(INTERFACE_NAME); invocation.setMethodName(METHOD_NAME); - invocation.setParameterTypes(new Class[]{String.class}); + invocation.setParameterTypes(new Class[] {String.class}); Result result = filter.invoke(invoker, invocation); invocation.setMethodName($INVOKE); invocation.setParameterTypesDesc(GENERIC_PARAMETER_DESC); - invocation.setArguments(new Object[]{METHOD_NAME, new String[]{"java.lang.String"}, new Object[]{"mock"}}); + invocation.setArguments(new Object[] {METHOD_NAME, new String[] {"java.lang.String"}, new Object[] {"mock"}}); filter.onResponse(result, invoker, invocation); @@ -384,7 +381,7 @@ class MetricsFilterTest { private void initParam() { invocation.setTargetServiceUniqueName(GROUP + "/" + INTERFACE_NAME + ":" + VERSION); invocation.setMethodName(METHOD_NAME); - invocation.setParameterTypes(new Class[]{String.class}); + invocation.setParameterTypes(new Class[] {String.class}); } private Map getMetricsMap() { @@ -403,7 +400,7 @@ class MetricsFilterTest { void testThrowable() { invocation.setTargetServiceUniqueName(INTERFACE_NAME); invocation.setMethodName(METHOD_NAME); - invocation.setParameterTypes(new Class[]{String.class}); + invocation.setParameterTypes(new Class[] {String.class}); given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); Result result = filter.invoke(invoker, invocation); result.setException(new RuntimeException("failed")); diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/MethodMetricTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/MethodMetricTest.java index 93f1c6593f..0218d872e4 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/MethodMetricTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/MethodMetricTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.metrics.model; import org.apache.dubbo.common.URL; @@ -25,23 +24,20 @@ import org.apache.dubbo.metrics.model.key.MetricsLevel; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; + +import java.util.Map; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import java.util.Map; - import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_GROUP_KEY; -import static org.apache.dubbo.common.constants.MetricsConstants.TAG_HOSTNAME; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_INTERFACE_KEY; -import static org.apache.dubbo.common.constants.MetricsConstants.TAG_IP; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_METHOD_KEY; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_VERSION_KEY; -import static org.apache.dubbo.common.utils.NetUtils.getLocalHost; -import static org.apache.dubbo.common.utils.NetUtils.getLocalHostName; class MethodMetricTest { @@ -69,12 +65,14 @@ class MethodMetricTest { invocation.setTargetServiceUniqueName(group + "/" + interfaceName + ":" + version); invocation.setAttachment(GROUP_KEY, group); invocation.setAttachment(VERSION_KEY, version); - RpcContext.getServiceContext().setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=consumer")); + RpcContext.getServiceContext() + .setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=consumer")); } @Test void test() { - MethodMetric metric = new MethodMetric(applicationModel, invocation, MethodMetric.isServiceLevel(applicationModel)); + MethodMetric metric = + new MethodMetric(applicationModel, invocation, MethodMetric.isServiceLevel(applicationModel)); Assertions.assertEquals(metric.getServiceKey(), interfaceName); Assertions.assertEquals(metric.getMethodName(), methodName); Assertions.assertEquals(metric.getGroup(), group); @@ -94,7 +92,8 @@ class MethodMetricTest { MetricsConfig metricConfig = new MetricsConfig(); applicationModel.getApplicationConfigManager().setMetrics(metricConfig); metricConfig.setRpcLevel(MetricsLevel.SERVICE.name()); - MethodMetric metric = new MethodMetric(applicationModel, invocation, MethodMetric.isServiceLevel(applicationModel)); + MethodMetric metric = + new MethodMetric(applicationModel, invocation, MethodMetric.isServiceLevel(applicationModel)); Assertions.assertEquals(metric.getServiceKey(), interfaceName); Assertions.assertNull(metric.getMethodName(), methodName); Assertions.assertEquals(metric.getGroup(), group); diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/sample/ErrorCodeSampleTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/sample/ErrorCodeSampleTest.java index 89b2ca5fa3..d571214f92 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/sample/ErrorCodeSampleTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/sample/ErrorCodeSampleTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.metrics.model.sample; import org.apache.dubbo.common.utils.Assert; @@ -27,11 +26,12 @@ import org.apache.dubbo.metrics.model.sample.CounterMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.junit.jupiter.api.Test; import java.util.List; import java.util.concurrent.atomic.AtomicLong; +import org.junit.jupiter.api.Test; + public class ErrorCodeSampleTest { @Test @@ -47,9 +47,11 @@ public class ErrorCodeSampleTest { DefaultMetricsCollector defaultMetricsCollector = new DefaultMetricsCollector(applicationModel); defaultMetricsCollector.setCollectEnabled(true); - ErrorCodeSampler sampler = (ErrorCodeSampler) ReflectionUtils.getField(defaultMetricsCollector, "errorCodeSampler"); + ErrorCodeSampler sampler = + (ErrorCodeSampler) ReflectionUtils.getField(defaultMetricsCollector, "errorCodeSampler"); - ErrorCodeMetricsListenRegister register = (ErrorCodeMetricsListenRegister) ReflectionUtils.getField(sampler, "register"); + ErrorCodeMetricsListenRegister register = + (ErrorCodeMetricsListenRegister) ReflectionUtils.getField(sampler, "register"); register.onMessage("0-1", null); register.onMessage("0-1", null); @@ -62,8 +64,9 @@ public class ErrorCodeSampleTest { List samples = defaultMetricsCollector.collect(); - Assert.assertTrue(samples.size() == 4,"Wrong number of samples."); - samples.forEach(metricSample -> Assert.assertTrue(((AtomicLong)((CounterMetricSample)metricSample).getValue()).get() == 2L,"Sample count error.")); + Assert.assertTrue(samples.size() == 4, "Wrong number of samples."); + samples.forEach(metricSample -> Assert.assertTrue( + ((AtomicLong) ((CounterMetricSample) metricSample).getValue()).get() == 2L, "Sample count error.")); System.out.println(samples); } diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/sample/GaugeMetricSampleTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/sample/GaugeMetricSampleTest.java index d43e969370..b2a0aa369f 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/sample/GaugeMetricSampleTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/sample/GaugeMetricSampleTest.java @@ -14,22 +14,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.metrics.model.sample; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import java.util.function.ToDoubleFunction; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + class GaugeMetricSampleTest { private static String name; @@ -53,7 +52,8 @@ class GaugeMetricSampleTest { @Test void test() { - GaugeMetricSample sample = new GaugeMetricSample<>(name, description, tags, category, baseUnit, value, apply); + GaugeMetricSample sample = + new GaugeMetricSample<>(name, description, tags, category, baseUnit, value, apply); Assertions.assertEquals(sample.getName(), name); Assertions.assertEquals(sample.getDescription(), description); Assertions.assertEquals(sample.getTags(), tags); diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/sample/MetricSampleTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/sample/MetricSampleTest.java index b7bc85662b..4901ad5dff 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/sample/MetricSampleTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/sample/MetricSampleTest.java @@ -14,18 +14,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.metrics.model.sample; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.model.sample.MetricSample; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + class MetricSampleTest { private static String name; diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/service/MetricsEntityTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/service/MetricsEntityTest.java index 19285ad59f..39f52c40fc 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/service/MetricsEntityTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/service/MetricsEntityTest.java @@ -14,18 +14,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.metrics.service; import org.apache.dubbo.metrics.model.MetricsCategory; import org.apache.dubbo.metrics.service.MetricsEntity; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + class MetricsEntityTest { private static String name; diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/rpc/cluster/filter/MetricsClusterFilterTest.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/rpc/cluster/filter/MetricsClusterFilterTest.java index a0c00adb2f..be8e517696 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/rpc/cluster/filter/MetricsClusterFilterTest.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/rpc/cluster/filter/MetricsClusterFilterTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.filter; import org.apache.dubbo.common.URL; @@ -33,10 +32,6 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.filter.support.MetricsClusterFilter; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; @@ -45,17 +40,22 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.stream.Collectors; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; class MetricsClusterFilterTest { - private ApplicationModel applicationModel; - private MetricsFilter filter; - private MetricsClusterFilter metricsClusterFilter; - private DefaultMetricsCollector collector; - private RpcInvocation invocation; - private final Invoker invoker = mock(Invoker.class); + private ApplicationModel applicationModel; + private MetricsFilter filter; + private MetricsClusterFilter metricsClusterFilter; + private DefaultMetricsCollector collector; + private RpcInvocation invocation; + private final Invoker invoker = mock(Invoker.class); private static final String INTERFACE_NAME = "org.apache.dubbo.MockInterface"; private static final String METHOD_NAME = "mockMethod"; @@ -65,12 +65,11 @@ class MetricsClusterFilterTest { private AtomicBoolean initApplication = new AtomicBoolean(false); - @BeforeEach public void setup() { ApplicationConfig config = new ApplicationConfig(); config.setName("MockMetrics"); - //RpcContext.getContext().setAttachment("MockMetrics","MockMetrics"); + // RpcContext.getContext().setAttachment("MockMetrics","MockMetrics"); applicationModel = ApplicationModel.defaultModel(); applicationModel.getApplicationConfigManager().setApplication(config); @@ -79,14 +78,15 @@ class MetricsClusterFilterTest { filter = new MetricsFilter(); collector = applicationModel.getBeanFactory().getOrRegisterBean(DefaultMetricsCollector.class); - if(!initApplication.get()) { + if (!initApplication.get()) { collector.collectApplication(); initApplication.set(true); } filter.setApplicationModel(applicationModel); side = CommonConstants.CONSUMER; invocation.setInvoker(new TestMetricsInvoker(side)); - RpcContext.getServiceContext().setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=" + side)); + RpcContext.getServiceContext() + .setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=" + side)); metricsClusterFilter = new MetricsClusterFilter(); metricsClusterFilter.setApplicationModel(applicationModel); @@ -98,12 +98,13 @@ class MetricsClusterFilterTest { } @Test - public void testNoProvider(){ - testClusterFilterError(RpcException.FORBIDDEN_EXCEPTION, - MetricsKey.METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED.getNameByType(CommonConstants.CONSUMER)); + public void testNoProvider() { + testClusterFilterError( + RpcException.FORBIDDEN_EXCEPTION, + MetricsKey.METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED.getNameByType(CommonConstants.CONSUMER)); } - private void testClusterFilterError(int errorCode,String name){ + private void testClusterFilterError(int errorCode, String name) { collector.setCollectEnabled(true); given(invoker.invoke(invocation)).willThrow(new RpcException(errorCode)); initParam(); @@ -127,12 +128,10 @@ class MetricsClusterFilterTest { teardown(); } - - private void initParam() { invocation.setTargetServiceUniqueName(GROUP + "/" + INTERFACE_NAME + ":" + VERSION); invocation.setMethodName(METHOD_NAME); - invocation.setParameterTypes(new Class[]{String.class}); + invocation.setParameterTypes(new Class[] {String.class}); } private Map getMetricsMap() { @@ -167,7 +166,7 @@ class MetricsClusterFilterTest { @Override public URL getUrl() { - return URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side="+side); + return URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=" + side); } @Override @@ -176,8 +175,6 @@ class MetricsClusterFilterTest { } @Override - public void destroy() { - - } + public void destroy() {} } } diff --git a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/rpc/cluster/filter/MockInvocation.java b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/rpc/cluster/filter/MockInvocation.java index 9bd89552e3..2ca6eff0ce 100644 --- a/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/rpc/cluster/filter/MockInvocation.java +++ b/dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/rpc/cluster/filter/MockInvocation.java @@ -119,9 +119,7 @@ public class MockInvocation extends RpcInvocation { } @Override - public void setServiceModel(ServiceModel serviceModel) { - - } + public void setServiceModel(ServiceModel serviceModel) {} @Override public ServiceModel getServiceModel() { @@ -164,5 +162,4 @@ public class MockInvocation extends RpcInvocation { } return result; } - } diff --git a/dubbo-metrics/dubbo-metrics-event/pom.xml b/dubbo-metrics/dubbo-metrics-event/pom.xml index 4db769019c..abdaf820d5 100644 --- a/dubbo-metrics/dubbo-metrics-event/pom.xml +++ b/dubbo-metrics/dubbo-metrics-event/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - org.apache.dubbo - dubbo-metrics - ${revision} - ../pom.xml - - dubbo-metrics-event - jar - ${project.artifactId} - The metrics event-related api module of dubbo project - - false - + + 4.0.0 + + org.apache.dubbo + dubbo-metrics + ${revision} + ../pom.xml + + dubbo-metrics-event + jar + ${project.artifactId} + The metrics event-related api module of dubbo project + + false + - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - + + + org.apache.dubbo + dubbo-common + ${project.parent.version} + + diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/MetricsConstants.java b/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/MetricsConstants.java index b03a63dddc..019f949321 100644 --- a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/MetricsConstants.java +++ b/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/MetricsConstants.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics; public interface MetricsConstants { @@ -23,7 +22,7 @@ public interface MetricsConstants { String METHOD_METRICS = "metric_filter_method_metrics"; String INVOCATION_METRICS_COUNTER = "metric_filter_invocation_counter"; String INVOCATION_SIDE = "metric_filter_side"; - String INVOCATION_REQUEST_ERROR = "metric_request_error"; + String INVOCATION_REQUEST_ERROR = "metric_request_error"; String ATTACHMENT_KEY_SERVICE = "serviceKey"; String ATTACHMENT_KEY_SIZE = "size"; @@ -33,5 +32,4 @@ public interface MetricsConstants { int SELF_INCREMENT_SIZE = 1; String NETTY_METRICS_MAP = "nettyMetricsMap"; - } diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEvent.java b/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEvent.java index b0e587a396..25a040d858 100644 --- a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEvent.java +++ b/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEvent.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.event; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; @@ -34,7 +33,8 @@ public abstract class MetricsEvent { /** * Metric object. (eg. MethodMetric) */ - protected transient final ApplicationModel source; + protected final transient ApplicationModel source; + private boolean available = true; private final TypeWrapper typeWrapper; private final String appName; @@ -46,7 +46,11 @@ public abstract class MetricsEvent { this(source, null, null, typeWrapper); } - public MetricsEvent(ApplicationModel source, String appName, MetricsEventMulticaster metricsEventMulticaster, TypeWrapper typeWrapper) { + public MetricsEvent( + ApplicationModel source, + String appName, + MetricsEventMulticaster metricsEventMulticaster, + TypeWrapper typeWrapper) { this.typeWrapper = typeWrapper; if (source == null) { this.source = ApplicationModel.defaultModel(); @@ -105,10 +109,7 @@ public abstract class MetricsEvent { return available; } - - public void customAfterPost(Object postResult) { - - } + public void customAfterPost(Object postResult) {} public ApplicationModel getSource() { return source; @@ -160,7 +161,6 @@ public abstract class MetricsEvent { return String.format(name, type); } - Type(String name) { this.name = name; } diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventBus.java b/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventBus.java index 2d0888d17a..7654c2d902 100644 --- a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventBus.java +++ b/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventBus.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.event; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -58,7 +57,6 @@ public class MetricsEventBus { */ public static T post(MetricsEvent event, Supplier targetSupplier) { return post(event, targetSupplier, null); - } /** diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventMulticaster.java b/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventMulticaster.java index 459b0744e3..2f1381a726 100644 --- a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventMulticaster.java +++ b/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventMulticaster.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.event; import org.apache.dubbo.metrics.listener.MetricsListener; diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEvent.java b/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEvent.java index e814465b36..7cfb2c607f 100644 --- a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEvent.java +++ b/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEvent.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.event; import org.apache.dubbo.metrics.model.TimePair; @@ -33,7 +32,11 @@ public abstract class TimeCounterEvent extends MetricsEvent { this.timePair = TimePair.start(); } - public TimeCounterEvent(ApplicationModel source, String appName,MetricsEventMulticaster metricsDispatcher, TypeWrapper typeWrapper) { + public TimeCounterEvent( + ApplicationModel source, + String appName, + MetricsEventMulticaster metricsDispatcher, + TypeWrapper typeWrapper) { super(source, appName, metricsDispatcher, typeWrapper); this.timePair = TimePair.start(); } @@ -41,5 +44,4 @@ public abstract class TimeCounterEvent extends MetricsEvent { public TimePair getTimePair() { return timePair; } - } diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/exception/MetricsNeverHappenException.java b/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/exception/MetricsNeverHappenException.java index 1f5336611b..e1969f10a2 100644 --- a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/exception/MetricsNeverHappenException.java +++ b/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/exception/MetricsNeverHappenException.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.exception; public class MetricsNeverHappenException extends RuntimeException { diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/listener/MetricsListener.java b/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/listener/MetricsListener.java index 3411e6f046..048625fb02 100644 --- a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/listener/MetricsListener.java +++ b/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/listener/MetricsListener.java @@ -14,18 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.listener; import org.apache.dubbo.metrics.event.MetricsEvent; - /** * Metrics Listener. */ public interface MetricsListener { - boolean isSupport(MetricsEvent event); /** @@ -34,5 +31,4 @@ public interface MetricsListener { * @param event BaseMetricsEvent */ void onEvent(E event); - } diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/TimePair.java b/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/TimePair.java index 70e0aba1d6..c00e96bbb7 100644 --- a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/TimePair.java +++ b/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/TimePair.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.model; public class TimePair { diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKey.java b/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKey.java index d426898255..9fa9ae48e7 100644 --- a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKey.java +++ b/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKey.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.model.key; public enum MetricsKey { @@ -33,19 +32,24 @@ public enum MetricsKey { METRIC_REQUESTS_FAILED("dubbo.%s.requests.unknown.failed.total", "Total Unknown Failed Requests"), METRIC_REQUESTS_TOTAL_FAILED("dubbo.%s.requests.failed.total", "Total Failed Requests"), METRIC_REQUESTS_NETWORK_FAILED("dubbo.%s.requests.failed.network.total", "Total network Failed Requests"), - METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED("dubbo.%s.requests.failed.service.unavailable.total", "Total Service Unavailable Failed Requests"), + METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED( + "dubbo.%s.requests.failed.service.unavailable.total", "Total Service Unavailable Failed Requests"), METRIC_REQUESTS_CODEC_FAILED("dubbo.%s.requests.failed.codec.total", "Total Codec Failed Requests"), METRIC_REQUESTS_TOTAL_AGG("dubbo.%s.requests.total.aggregate", "Aggregated Total Requests"), METRIC_REQUESTS_SUCCEED_AGG("dubbo.%s.requests.succeed.aggregate", "Aggregated Succeed Requests"), METRIC_REQUESTS_FAILED_AGG("dubbo.%s.requests.failed.aggregate", "Aggregated Failed Requests"), - METRIC_REQUEST_BUSINESS_FAILED_AGG("dubbo.%s.requests.business.failed.aggregate", "Aggregated Business Failed Requests"), + METRIC_REQUEST_BUSINESS_FAILED_AGG( + "dubbo.%s.requests.business.failed.aggregate", "Aggregated Business Failed Requests"), METRIC_REQUESTS_TIMEOUT_AGG("dubbo.%s.requests.timeout.failed.aggregate", "Aggregated timeout Failed Requests"), METRIC_REQUESTS_LIMIT_AGG("dubbo.%s.requests.limit.aggregate", "Aggregated limit Requests"), METRIC_REQUESTS_TOTAL_FAILED_AGG("dubbo.%s.requests.failed.total.aggregate", "Aggregated failed total Requests"), - METRIC_REQUESTS_NETWORK_FAILED_AGG("dubbo.%s.requests.failed.network.total.aggregate", "Aggregated failed network total Requests"), - METRIC_REQUESTS_CODEC_FAILED_AGG("dubbo.%s.requests.failed.codec.total.aggregate", "Aggregated failed codec total Requests"), - METRIC_REQUESTS_TOTAL_SERVICE_UNAVAILABLE_FAILED_AGG("dubbo.%s.requests.failed.service.unavailable.total.aggregate", "Aggregated failed codec total Requests"), + METRIC_REQUESTS_NETWORK_FAILED_AGG( + "dubbo.%s.requests.failed.network.total.aggregate", "Aggregated failed network total Requests"), + METRIC_REQUESTS_CODEC_FAILED_AGG( + "dubbo.%s.requests.failed.codec.total.aggregate", "Aggregated failed codec total Requests"), + METRIC_REQUESTS_TOTAL_SERVICE_UNAVAILABLE_FAILED_AGG( + "dubbo.%s.requests.failed.service.unavailable.total.aggregate", "Aggregated failed codec total Requests"), METRIC_QPS("dubbo.%s.qps.total", "Query Per Seconds"), METRIC_RT_LAST("dubbo.%s.rt.milliseconds.last", "Last Response Time"), @@ -67,7 +71,6 @@ public enum MetricsKey { REGISTER_METRIC_REQUESTS_FAILED("dubbo.registry.register.requests.failed.total", "Failed Register Requests"), METRIC_RT_HISTOGRAM("dubbo.%s.rt.milliseconds.histogram", "Response Time Histogram"), - GENERIC_METRIC_REQUESTS("dubbo.%s.requests.total", "Total %s Requests"), GENERIC_METRIC_REQUESTS_SUCCEED("dubbo.%s.requests.succeed.total", "Succeed %s Requests"), GENERIC_METRIC_REQUESTS_FAILED("dubbo.%s.requests.failed.total", "Failed %s Requests"), @@ -101,18 +104,23 @@ public enum MetricsKey { // metadata subscribe metrics key METADATA_SUBSCRIBE_METRIC_NUM("dubbo.metadata.subscribe.num.total", "Total Metadata Subscribe Num"), - METADATA_SUBSCRIBE_METRIC_NUM_SUCCEED("dubbo.metadata.subscribe.num.succeed.total", "Succeed Metadata Subscribe Num"), + METADATA_SUBSCRIBE_METRIC_NUM_SUCCEED( + "dubbo.metadata.subscribe.num.succeed.total", "Succeed Metadata Subscribe Num"), METADATA_SUBSCRIBE_METRIC_NUM_FAILED("dubbo.metadata.subscribe.num.failed.total", "Failed Metadata Subscribe Num"), // register service metrics key SERVICE_REGISTER_METRIC_REQUESTS("dubbo.registry.register.service.total", "Total Service-Level Register Requests"), - SERVICE_REGISTER_METRIC_REQUESTS_SUCCEED("dubbo.registry.register.service.succeed.total", "Succeed Service-Level Register Requests"), - SERVICE_REGISTER_METRIC_REQUESTS_FAILED("dubbo.registry.register.service.failed.total", "Failed Service-Level Register Requests"), + SERVICE_REGISTER_METRIC_REQUESTS_SUCCEED( + "dubbo.registry.register.service.succeed.total", "Succeed Service-Level Register Requests"), + SERVICE_REGISTER_METRIC_REQUESTS_FAILED( + "dubbo.registry.register.service.failed.total", "Failed Service-Level Register Requests"), // subscribe metrics key SERVICE_SUBSCRIBE_METRIC_NUM("dubbo.registry.subscribe.service.num.total", "Total Service-Level Subscribe Num"), - SERVICE_SUBSCRIBE_METRIC_NUM_SUCCEED("dubbo.registry.subscribe.service.num.succeed.total", "Succeed Service-Level Num"), - SERVICE_SUBSCRIBE_METRIC_NUM_FAILED("dubbo.registry.subscribe.service.num.failed.total", "Failed Service-Level Num"), + SERVICE_SUBSCRIBE_METRIC_NUM_SUCCEED( + "dubbo.registry.subscribe.service.num.succeed.total", "Succeed Service-Level Num"), + SERVICE_SUBSCRIBE_METRIC_NUM_FAILED( + "dubbo.registry.subscribe.service.num.failed.total", "Failed Service-Level Num"), // store provider metadata service key STORE_PROVIDER_METADATA("dubbo.metadata.store.provider.total", "Store Provider Metadata"), @@ -122,21 +130,24 @@ public enum MetricsKey { METADATA_GIT_COMMITID_METRIC("git.commit.id", "Git Commit Id Metrics"), // consumer metrics key - INVOKER_NO_AVAILABLE_COUNT("dubbo.consumer.invoker.no.available.count", "Request Throw No Invoker Available Exception Count"), + INVOKER_NO_AVAILABLE_COUNT( + "dubbo.consumer.invoker.no.available.count", "Request Throw No Invoker Available Exception Count"), // count the number of occurrences of each error code - ERROR_CODE_COUNT("dubbo.error.code.count","The Count Of Occurrences for Each Error Code"), + ERROR_CODE_COUNT("dubbo.error.code.count", "The Count Of Occurrences for Each Error Code"), // netty metrics key NETTY_ALLOCATOR_HEAP_MEMORY_USED("netty.allocator.memory.used", "Netty Allocator Memory Used"), NETTY_ALLOCATOR_DIRECT_MEMORY_USED("netty.allocator.direct.memory.used", "Netty Allocator Direct Memory Used"), - NETTY_ALLOCATOR_PINNED_DIRECT_MEMORY("netty.allocator.pinned.direct.memory", "Netty Allocator Pinned Direct Memory"), + NETTY_ALLOCATOR_PINNED_DIRECT_MEMORY( + "netty.allocator.pinned.direct.memory", "Netty Allocator Pinned Direct Memory"), NETTY_ALLOCATOR_PINNED_HEAP_MEMORY("netty.allocator.pinned.heap.memory", "Netty Allocator Pinned Heap Memory"), NETTY_ALLOCATOR_HEAP_ARENAS_NUM("netty.allocator.heap.arenas.num", "Netty Allocator Heap Arenas Num"), NETTY_ALLOCATOR_DIRECT_ARENAS_NUM("netty.allocator.direct.arenas.num", "Netty Allocator Direct Arenas Num"), NETTY_ALLOCATOR_NORMAL_CACHE_SIZE("netty.allocator.normal.cache.size", "Netty Allocator Normal Cache Size"), NETTY_ALLOCATOR_SMALL_CACHE_SIZE("netty.allocator.small.cache.size", "Netty Allocator Small Cache Size"), - NETTY_ALLOCATOR_THREAD_LOCAL_CACHES_NUM("netty.allocator.thread.local.caches.num", "Netty Allocator Thread Local Caches Num"), + NETTY_ALLOCATOR_THREAD_LOCAL_CACHES_NUM( + "netty.allocator.thread.local.caches.num", "Netty Allocator Thread Local Caches Num"), NETTY_ALLOCATOR_CHUNK_SIZE("netty.allocator.chunk.size", "Netty Allocator Chunk Size"), ; @@ -151,7 +162,7 @@ public enum MetricsKey { return String.format(name, type); } - public static MetricsKey getMetricsByName(String name){ + public static MetricsKey getMetricsByName(String name) { for (MetricsKey metricsKey : MetricsKey.values()) { if (metricsKey.getName().equals(name)) { return metricsKey; diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/MetricsLevel.java b/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/MetricsLevel.java index 9a81e17ef8..2f255c7032 100644 --- a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/MetricsLevel.java +++ b/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/MetricsLevel.java @@ -14,9 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.model.key; public enum MetricsLevel { - APP, SERVICE, METHOD, CONFIG, REGISTRY + APP, + SERVICE, + METHOD, + CONFIG, + REGISTRY } diff --git a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/TypeWrapper.java b/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/TypeWrapper.java index 76c37a5899..803900821f 100644 --- a/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/TypeWrapper.java +++ b/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/TypeWrapper.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.model.key; import org.apache.dubbo.common.utils.Assert; @@ -44,5 +43,4 @@ public class TypeWrapper { Assert.notNull(type, "Type can not be null"); return type.equals(postType) || type.equals(finishType) || type.equals(errorType); } - } diff --git a/dubbo-metrics/dubbo-metrics-metadata/pom.xml b/dubbo-metrics/dubbo-metrics-metadata/pom.xml index f454e9558e..d6cf291fdc 100644 --- a/dubbo-metrics/dubbo-metrics-metadata/pom.xml +++ b/dubbo-metrics/dubbo-metrics-metadata/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - org.apache.dubbo - dubbo-metrics - ${revision} - ../pom.xml - - dubbo-metrics-metadata - jar - ${project.artifactId} - The metrics module of dubbo project - - false - - - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - - + + 4.0.0 + + org.apache.dubbo + dubbo-metrics + ${revision} + ../pom.xml + + dubbo-metrics-metadata + jar + ${project.artifactId} + The metrics module of dubbo project + + false + + + + org.apache.dubbo + dubbo-metrics-api + ${project.parent.version} + + diff --git a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/MetadataMetricsConstants.java b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/MetadataMetricsConstants.java index 14fc3b8dab..9f3a43db2f 100644 --- a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/MetadataMetricsConstants.java +++ b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/MetadataMetricsConstants.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.metadata; import org.apache.dubbo.metrics.model.key.MetricsKey; @@ -39,16 +38,21 @@ public interface MetadataMetricsConstants { MetricsPlaceValue OP_TYPE_PUSH = MetricsPlaceValue.of("push", MetricsLevel.APP); MetricsPlaceValue OP_TYPE_SUBSCRIBE = MetricsPlaceValue.of("subscribe", MetricsLevel.APP); - MetricsPlaceValue OP_TYPE_STORE_PROVIDER_INTERFACE = MetricsPlaceValue.of("store.provider.interface", MetricsLevel.SERVICE); + MetricsPlaceValue OP_TYPE_STORE_PROVIDER_INTERFACE = + MetricsPlaceValue.of("store.provider.interface", MetricsLevel.SERVICE); // App-level - List APP_LEVEL_KEYS = Arrays.asList(METADATA_PUSH_METRIC_NUM, METADATA_PUSH_METRIC_NUM_SUCCEED, METADATA_PUSH_METRIC_NUM_FAILED, - METADATA_SUBSCRIBE_METRIC_NUM, METADATA_SUBSCRIBE_METRIC_NUM_SUCCEED, METADATA_SUBSCRIBE_METRIC_NUM_FAILED); + List APP_LEVEL_KEYS = Arrays.asList( + METADATA_PUSH_METRIC_NUM, + METADATA_PUSH_METRIC_NUM_SUCCEED, + METADATA_PUSH_METRIC_NUM_FAILED, + METADATA_SUBSCRIBE_METRIC_NUM, + METADATA_SUBSCRIBE_METRIC_NUM_SUCCEED, + METADATA_SUBSCRIBE_METRIC_NUM_FAILED); // Service-level List SERVICE_LEVEL_KEYS = Arrays.asList( - new MetricsKeyWrapper(STORE_PROVIDER_METADATA, OP_TYPE_STORE_PROVIDER_INTERFACE), - new MetricsKeyWrapper(STORE_PROVIDER_METADATA_SUCCEED, OP_TYPE_STORE_PROVIDER_INTERFACE), - new MetricsKeyWrapper(STORE_PROVIDER_METADATA_FAILED, OP_TYPE_STORE_PROVIDER_INTERFACE) - ); + new MetricsKeyWrapper(STORE_PROVIDER_METADATA, OP_TYPE_STORE_PROVIDER_INTERFACE), + new MetricsKeyWrapper(STORE_PROVIDER_METADATA_SUCCEED, OP_TYPE_STORE_PROVIDER_INTERFACE), + new MetricsKeyWrapper(STORE_PROVIDER_METADATA_FAILED, OP_TYPE_STORE_PROVIDER_INTERFACE)); } diff --git a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/MetadataMetricsCollector.java b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/MetadataMetricsCollector.java index 82b5e689d3..82dcc7cd97 100644 --- a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/MetadataMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/collector/MetadataMetricsCollector.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.metadata.collector; import org.apache.dubbo.common.extension.Activate; @@ -40,7 +39,6 @@ import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_STORE_PROVIDER_INTERFACE; import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_SUBSCRIBE; - /** * Registry implementation of {@link MetricsCollector} */ diff --git a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataEvent.java b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataEvent.java index 2222bda162..a14c669052 100644 --- a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataEvent.java +++ b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataEvent.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.metadata.event; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; @@ -50,17 +49,34 @@ public class MetadataEvent extends TimeCounterEvent { } public static MetadataEvent toPushEvent(ApplicationModel applicationModel) { - return new MetadataEvent(applicationModel, new TypeWrapper(MetricsLevel.APP, METADATA_PUSH_METRIC_NUM, METADATA_PUSH_METRIC_NUM_SUCCEED, METADATA_PUSH_METRIC_NUM_FAILED)); + return new MetadataEvent( + applicationModel, + new TypeWrapper( + MetricsLevel.APP, + METADATA_PUSH_METRIC_NUM, + METADATA_PUSH_METRIC_NUM_SUCCEED, + METADATA_PUSH_METRIC_NUM_FAILED)); } public static MetadataEvent toSubscribeEvent(ApplicationModel applicationModel) { - return new MetadataEvent(applicationModel, new TypeWrapper(MetricsLevel.APP, METADATA_SUBSCRIBE_METRIC_NUM, METADATA_SUBSCRIBE_METRIC_NUM_SUCCEED, METADATA_SUBSCRIBE_METRIC_NUM_FAILED)); + return new MetadataEvent( + applicationModel, + new TypeWrapper( + MetricsLevel.APP, + METADATA_SUBSCRIBE_METRIC_NUM, + METADATA_SUBSCRIBE_METRIC_NUM_SUCCEED, + METADATA_SUBSCRIBE_METRIC_NUM_FAILED)); } public static MetadataEvent toServiceSubscribeEvent(ApplicationModel applicationModel, String serviceKey) { - MetadataEvent metadataEvent = new MetadataEvent(applicationModel, new TypeWrapper(MetricsLevel.APP, STORE_PROVIDER_METADATA, STORE_PROVIDER_METADATA_SUCCEED, STORE_PROVIDER_METADATA_FAILED)); + MetadataEvent metadataEvent = new MetadataEvent( + applicationModel, + new TypeWrapper( + MetricsLevel.APP, + STORE_PROVIDER_METADATA, + STORE_PROVIDER_METADATA_SUCCEED, + STORE_PROVIDER_METADATA_FAILED)); metadataEvent.putAttachment(ATTACHMENT_KEY_SERVICE, serviceKey); return metadataEvent; } - } diff --git a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataSubDispatcher.java b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataSubDispatcher.java index ebbe20f8a8..bc7ec7fa0f 100644 --- a/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataSubDispatcher.java +++ b/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataSubDispatcher.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.metadata.event; import org.apache.dubbo.metrics.event.SimpleMetricsEventMulticaster; @@ -36,8 +35,7 @@ public final class MetadataSubDispatcher extends SimpleMetricsEventMulticaster { public MetadataSubDispatcher(MetadataMetricsCollector collector) { - CategorySet.ALL.forEach(categorySet -> - { + CategorySet.ALL.forEach(categorySet -> { super.addListener(categorySet.getPost().getEventFunc().apply(collector)); if (categorySet.getFinish() != null) { super.addListener(categorySet.getFinish().getEventFunc().apply(collector)); @@ -46,17 +44,24 @@ public final class MetadataSubDispatcher extends SimpleMetricsEventMulticaster { super.addListener(categorySet.getError().getEventFunc().apply(collector)); } }); - - } /** * A closer aggregation of MetricsCat, a summary collection of certain types of events */ interface CategorySet { - CategoryOverall APPLICATION_PUSH = new CategoryOverall(OP_TYPE_PUSH, MCat.APPLICATION_PUSH_POST, MCat.APPLICATION_PUSH_FINISH, MCat.APPLICATION_PUSH_ERROR); - CategoryOverall APPLICATION_SUBSCRIBE = new CategoryOverall(OP_TYPE_SUBSCRIBE, MCat.APPLICATION_SUBSCRIBE_POST, MCat.APPLICATION_SUBSCRIBE_FINISH, MCat.APPLICATION_SUBSCRIBE_ERROR); - CategoryOverall SERVICE_SUBSCRIBE = new CategoryOverall(OP_TYPE_STORE_PROVIDER_INTERFACE, MCat.SERVICE_SUBSCRIBE_POST, MCat.SERVICE_SUBSCRIBE_FINISH, MCat.SERVICE_SUBSCRIBE_ERROR); + CategoryOverall APPLICATION_PUSH = new CategoryOverall( + OP_TYPE_PUSH, MCat.APPLICATION_PUSH_POST, MCat.APPLICATION_PUSH_FINISH, MCat.APPLICATION_PUSH_ERROR); + CategoryOverall APPLICATION_SUBSCRIBE = new CategoryOverall( + OP_TYPE_SUBSCRIBE, + MCat.APPLICATION_SUBSCRIBE_POST, + MCat.APPLICATION_SUBSCRIBE_FINISH, + MCat.APPLICATION_SUBSCRIBE_ERROR); + CategoryOverall SERVICE_SUBSCRIBE = new CategoryOverall( + OP_TYPE_STORE_PROVIDER_INTERFACE, + MCat.SERVICE_SUBSCRIBE_POST, + MCat.SERVICE_SUBSCRIBE_FINISH, + MCat.SERVICE_SUBSCRIBE_ERROR); List ALL = Arrays.asList(APPLICATION_PUSH, APPLICATION_SUBSCRIBE, SERVICE_SUBSCRIBE); } @@ -67,21 +72,27 @@ public final class MetadataSubDispatcher extends SimpleMetricsEventMulticaster { */ interface MCat { // MetricsPushListener - MetricsCat APPLICATION_PUSH_POST = new MetricsCat(MetricsKey.METADATA_PUSH_METRIC_NUM, MetricsApplicationListener::onPostEventBuild); - MetricsCat APPLICATION_PUSH_FINISH = new MetricsCat(MetricsKey.METADATA_PUSH_METRIC_NUM_SUCCEED, MetricsApplicationListener::onFinishEventBuild); - MetricsCat APPLICATION_PUSH_ERROR = new MetricsCat(MetricsKey.METADATA_PUSH_METRIC_NUM_FAILED, MetricsApplicationListener::onErrorEventBuild); + MetricsCat APPLICATION_PUSH_POST = + new MetricsCat(MetricsKey.METADATA_PUSH_METRIC_NUM, MetricsApplicationListener::onPostEventBuild); + MetricsCat APPLICATION_PUSH_FINISH = new MetricsCat( + MetricsKey.METADATA_PUSH_METRIC_NUM_SUCCEED, MetricsApplicationListener::onFinishEventBuild); + MetricsCat APPLICATION_PUSH_ERROR = new MetricsCat( + MetricsKey.METADATA_PUSH_METRIC_NUM_FAILED, MetricsApplicationListener::onErrorEventBuild); // MetricsSubscribeListener - MetricsCat APPLICATION_SUBSCRIBE_POST = new MetricsCat(MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM, MetricsApplicationListener::onPostEventBuild); - MetricsCat APPLICATION_SUBSCRIBE_FINISH = new MetricsCat(MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM_SUCCEED, MetricsApplicationListener::onFinishEventBuild); - MetricsCat APPLICATION_SUBSCRIBE_ERROR = new MetricsCat(MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM_FAILED, MetricsApplicationListener::onErrorEventBuild); + MetricsCat APPLICATION_SUBSCRIBE_POST = + new MetricsCat(MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM, MetricsApplicationListener::onPostEventBuild); + MetricsCat APPLICATION_SUBSCRIBE_FINISH = new MetricsCat( + MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM_SUCCEED, MetricsApplicationListener::onFinishEventBuild); + MetricsCat APPLICATION_SUBSCRIBE_ERROR = new MetricsCat( + MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM_FAILED, MetricsApplicationListener::onErrorEventBuild); // MetricsSubscribeListener - MetricsCat SERVICE_SUBSCRIBE_POST = new MetricsCat(MetricsKey.STORE_PROVIDER_METADATA, MetricsServiceListener::onPostEventBuild); - MetricsCat SERVICE_SUBSCRIBE_FINISH = new MetricsCat(MetricsKey.STORE_PROVIDER_METADATA_SUCCEED, MetricsServiceListener::onFinishEventBuild); - MetricsCat SERVICE_SUBSCRIBE_ERROR = new MetricsCat(MetricsKey.STORE_PROVIDER_METADATA_FAILED, MetricsServiceListener::onErrorEventBuild); - + MetricsCat SERVICE_SUBSCRIBE_POST = + new MetricsCat(MetricsKey.STORE_PROVIDER_METADATA, MetricsServiceListener::onPostEventBuild); + MetricsCat SERVICE_SUBSCRIBE_FINISH = + new MetricsCat(MetricsKey.STORE_PROVIDER_METADATA_SUCCEED, MetricsServiceListener::onFinishEventBuild); + MetricsCat SERVICE_SUBSCRIBE_ERROR = + new MetricsCat(MetricsKey.STORE_PROVIDER_METADATA_FAILED, MetricsServiceListener::onErrorEventBuild); } - - } diff --git a/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataMetricsCollectorTest.java b/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataMetricsCollectorTest.java index 564b0ba9c5..8ee31a9e79 100644 --- a/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataMetricsCollectorTest.java +++ b/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataMetricsCollectorTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.metadata; import org.apache.dubbo.config.ApplicationConfig; @@ -31,23 +30,22 @@ import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; import java.util.stream.Collectors; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME; import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_PUSH; import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_STORE_PROVIDER_INTERFACE; import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_SUBSCRIBE; - class MetadataMetricsCollectorTest { private ApplicationModel applicationModel; @@ -71,13 +69,11 @@ class MetadataMetricsCollectorTest { @Test void testListener() { MetadataEvent event = MetadataEvent.toPushEvent(applicationModel); - MetricsEvent otherEvent = new MetricsEvent(applicationModel,null, null, null){ - }; + MetricsEvent otherEvent = new MetricsEvent(applicationModel, null, null, null) {}; Assertions.assertTrue(collector.isSupport(event)); Assertions.assertFalse(collector.isSupport(otherEvent)); } - @AfterEach public void teardown() { applicationModel.destroy(); @@ -85,20 +81,20 @@ class MetadataMetricsCollectorTest { @Test void testPushMetrics() { -// MetadataMetricsCollector collector = getCollector(); + // MetadataMetricsCollector collector = getCollector(); MetadataEvent pushEvent = MetadataEvent.toPushEvent(applicationModel); - MetricsEventBus.post(pushEvent, - () -> { - List metricSamples = collector.collect(); + MetricsEventBus.post(pushEvent, () -> { + List metricSamples = collector.collect(); - // push success +1 - Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size(), metricSamples.size()); - Assertions.assertTrue(metricSamples.stream().allMatch(metricSample -> metricSample instanceof GaugeMetricSample)); - Assertions.assertTrue(metricSamples.stream().anyMatch(metricSample -> ((GaugeMetricSample) metricSample).applyAsDouble() == 1)); - return null; - } - ); + // push success +1 + Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size(), metricSamples.size()); + Assertions.assertTrue( + metricSamples.stream().allMatch(metricSample -> metricSample instanceof GaugeMetricSample)); + Assertions.assertTrue(metricSamples.stream() + .anyMatch(metricSample -> ((GaugeMetricSample) metricSample).applyAsDouble() == 1)); + return null; + }); // push finish rt +1 List metricSamples = collector.collect(); @@ -108,16 +104,17 @@ class MetadataMetricsCollectorTest { pushEvent = MetadataEvent.toPushEvent(applicationModel); TimePair lastTimePair = pushEvent.getTimePair(); - MetricsEventBus.post(pushEvent, - () -> { - try { - Thread.sleep(50); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return null; - }, Objects::nonNull - ); + MetricsEventBus.post( + pushEvent, + () -> { + try { + Thread.sleep(50); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return null; + }, + Objects::nonNull); // push error rt +1 long c2 = lastTimePair.calc(); metricSamples = collector.collect(); @@ -132,31 +129,41 @@ class MetadataMetricsCollectorTest { } @SuppressWarnings("rawtypes") - Map sampleMap = metricSamples.stream().collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); + Map sampleMap = metricSamples.stream() + .collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_PUSH).targetKey()), lastTimePair.calc()); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_PUSH).targetKey()), Math.min(c1, c2)); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_PUSH).targetKey()), Math.max(c1, c2)); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_PUSH).targetKey()), (c1 + c2) / 2); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_PUSH).targetKey()), c1 + c2); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_PUSH).targetKey()), + lastTimePair.calc()); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_PUSH).targetKey()), + Math.min(c1, c2)); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_PUSH).targetKey()), + Math.max(c1, c2)); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_PUSH).targetKey()), + (c1 + c2) / 2); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_PUSH).targetKey()), c1 + c2); } @Test void testSubscribeMetrics() { -// MetadataMetricsCollector collector = getCollector(); + // MetadataMetricsCollector collector = getCollector(); MetadataEvent subscribeEvent = MetadataEvent.toSubscribeEvent(applicationModel); - MetricsEventBus.post(subscribeEvent, - () -> { - List metricSamples = collector.collect(); + MetricsEventBus.post(subscribeEvent, () -> { + List metricSamples = collector.collect(); - // push success +1 - Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size(), metricSamples.size()); - Assertions.assertTrue(metricSamples.stream().allMatch(metricSample -> metricSample instanceof GaugeMetricSample)); - Assertions.assertTrue(metricSamples.stream().anyMatch(metricSample -> ((GaugeMetricSample) metricSample).applyAsDouble() == 1)); - return null; - } - ); + // push success +1 + Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size(), metricSamples.size()); + Assertions.assertTrue( + metricSamples.stream().allMatch(metricSample -> metricSample instanceof GaugeMetricSample)); + Assertions.assertTrue(metricSamples.stream() + .anyMatch(metricSample -> ((GaugeMetricSample) metricSample).applyAsDouble() == 1)); + return null; + }); long c1 = subscribeEvent.getTimePair().calc(); // push finish rt +1 @@ -166,16 +173,17 @@ class MetadataMetricsCollectorTest { subscribeEvent = MetadataEvent.toSubscribeEvent(applicationModel); TimePair lastTimePair = subscribeEvent.getTimePair(); - MetricsEventBus.post(subscribeEvent, - () -> { - try { - Thread.sleep(50); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return null; - }, Objects::nonNull - ); + MetricsEventBus.post( + subscribeEvent, + () -> { + try { + Thread.sleep(50); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return null; + }, + Objects::nonNull); // push error rt +1 long c2 = lastTimePair.calc(); @@ -191,33 +199,42 @@ class MetadataMetricsCollectorTest { } @SuppressWarnings("rawtypes") - Map sampleMap = metricSamples.stream().collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); + Map sampleMap = metricSamples.stream() + .collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_SUBSCRIBE).targetKey()), lastTimePair.calc()); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_SUBSCRIBE).targetKey()), Math.min(c1, c2)); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_SUBSCRIBE).targetKey()), Math.max(c1, c2)); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_SUBSCRIBE).targetKey()), (c1 + c2) / 2); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_SUBSCRIBE).targetKey()), c1 + c2); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_SUBSCRIBE).targetKey()), + lastTimePair.calc()); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_SUBSCRIBE).targetKey()), + Math.min(c1, c2)); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_SUBSCRIBE).targetKey()), + Math.max(c1, c2)); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_SUBSCRIBE).targetKey()), + (c1 + c2) / 2); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_SUBSCRIBE).targetKey()), c1 + c2); } - @Test void testStoreProviderMetadataMetrics() { -// MetadataMetricsCollector collector = getCollector(); + // MetadataMetricsCollector collector = getCollector(); String serviceKey = "store.provider.test"; MetadataEvent metadataEvent = MetadataEvent.toServiceSubscribeEvent(applicationModel, serviceKey); - MetricsEventBus.post(metadataEvent, - () -> { - List metricSamples = collector.collect(); + MetricsEventBus.post(metadataEvent, () -> { + List metricSamples = collector.collect(); - // App(6) + service success(1) - Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 1, metricSamples.size()); - Assertions.assertTrue(metricSamples.stream().allMatch(metricSample -> metricSample instanceof GaugeMetricSample)); - Assertions.assertTrue(metricSamples.stream().anyMatch(metricSample -> ((GaugeMetricSample) metricSample).applyAsDouble() == 1)); - return null; - } - ); + // App(6) + service success(1) + Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 1, metricSamples.size()); + Assertions.assertTrue( + metricSamples.stream().allMatch(metricSample -> metricSample instanceof GaugeMetricSample)); + Assertions.assertTrue(metricSamples.stream() + .anyMatch(metricSample -> ((GaugeMetricSample) metricSample).applyAsDouble() == 1)); + return null; + }); // push finish rt +1 List metricSamples = collector.collect(); @@ -227,23 +244,24 @@ class MetadataMetricsCollectorTest { long c1 = metadataEvent.getTimePair().calc(); metadataEvent = MetadataEvent.toServiceSubscribeEvent(applicationModel, serviceKey); TimePair lastTimePair = metadataEvent.getTimePair(); - MetricsEventBus.post(metadataEvent, - () -> { - try { - Thread.sleep(50); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return null; - }, Objects::nonNull - ); + MetricsEventBus.post( + metadataEvent, + () -> { + try { + Thread.sleep(50); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return null; + }, + Objects::nonNull); // push error rt +1 long c2 = lastTimePair.calc(); metricSamples = collector.collect(); // App(6) + service total/success/failed(3) + rt(5) - Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() +3 + 5, metricSamples.size()); + Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 3 + 5, metricSamples.size()); // calc rt for (MetricSample sample : metricSamples) { @@ -252,13 +270,29 @@ class MetadataMetricsCollectorTest { } @SuppressWarnings("rawtypes") - Map sampleMap = metricSamples.stream().collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); + Map sampleMap = metricSamples.stream() + .collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_STORE_PROVIDER_INTERFACE).targetKey()), lastTimePair.calc()); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_STORE_PROVIDER_INTERFACE).targetKey()), Math.min(c1, c2)); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_STORE_PROVIDER_INTERFACE).targetKey()), Math.max(c1, c2)); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_STORE_PROVIDER_INTERFACE).targetKey()), (c1 + c2) / 2); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_STORE_PROVIDER_INTERFACE).targetKey()), c1 + c2); + Assertions.assertEquals( + sampleMap.get( + new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_STORE_PROVIDER_INTERFACE).targetKey()), + lastTimePair.calc()); + Assertions.assertEquals( + sampleMap.get( + new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_STORE_PROVIDER_INTERFACE).targetKey()), + Math.min(c1, c2)); + Assertions.assertEquals( + sampleMap.get( + new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_STORE_PROVIDER_INTERFACE).targetKey()), + Math.max(c1, c2)); + Assertions.assertEquals( + sampleMap.get( + new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_STORE_PROVIDER_INTERFACE).targetKey()), + (c1 + c2) / 2); + Assertions.assertEquals( + sampleMap.get( + new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_STORE_PROVIDER_INTERFACE).targetKey()), + c1 + c2); } @Test @@ -266,10 +300,10 @@ class MetadataMetricsCollectorTest { for (int i = 0; i < 10; i++) { MetadataEvent event = MetadataEvent.toPushEvent(applicationModel); - if(i %2 ==0 ) { - MetricsEventBus.post(event,() -> true, r -> r); - }else { - MetricsEventBus.post(event,() -> false, r -> r); + if (i % 2 == 0) { + MetricsEventBus.post(event, () -> true, r -> r); + } else { + MetricsEventBus.post(event, () -> false, r -> r); } } @@ -279,36 +313,39 @@ class MetadataMetricsCollectorTest { GaugeMetricSample succeedNum = getSample(MetricsKey.METADATA_PUSH_METRIC_NUM_SUCCEED.getName(), samples); GaugeMetricSample failedNum = getSample(MetricsKey.METADATA_PUSH_METRIC_NUM_FAILED.getName(), samples); - Assertions.assertEquals(10,totalNum.applyAsLong()); - Assertions.assertEquals(5,succeedNum.applyAsLong()); - Assertions.assertEquals(5,failedNum.applyAsLong()); + Assertions.assertEquals(10, totalNum.applyAsLong()); + Assertions.assertEquals(5, succeedNum.applyAsLong()); + Assertions.assertEquals(5, failedNum.applyAsLong()); } @Test - void testSubscribeSum(){ + void testSubscribeSum() { for (int i = 0; i < 10; i++) { MetadataEvent event = MetadataEvent.toSubscribeEvent(applicationModel); - if(i %2 ==0 ) { - MetricsEventBus.post(event,() -> true, r -> r); - }else { - MetricsEventBus.post(event,() -> false, r -> r); + if (i % 2 == 0) { + MetricsEventBus.post(event, () -> true, r -> r); + } else { + MetricsEventBus.post(event, () -> false, r -> r); } } List samples = collector.collect(); GaugeMetricSample totalNum = getSample(MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM.getName(), samples); - GaugeMetricSample succeedNum = getSample(MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM_SUCCEED.getName(), samples); + GaugeMetricSample succeedNum = + getSample(MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM_SUCCEED.getName(), samples); GaugeMetricSample failedNum = getSample(MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM_FAILED.getName(), samples); - Assertions.assertEquals(10,totalNum.applyAsLong()); - Assertions.assertEquals(5,succeedNum.applyAsLong()); - Assertions.assertEquals(5,failedNum.applyAsLong()); + Assertions.assertEquals(10, totalNum.applyAsLong()); + Assertions.assertEquals(5, succeedNum.applyAsLong()); + Assertions.assertEquals(5, failedNum.applyAsLong()); } GaugeMetricSample getSample(String name, List samples) { - return (GaugeMetricSample) samples.stream().filter(metricSample -> metricSample.getName().equals(name)).findFirst().orElseThrow(NoSuchElementException::new); + return (GaugeMetricSample) samples.stream() + .filter(metricSample -> metricSample.getName().equals(name)) + .findFirst() + .orElseThrow(NoSuchElementException::new); } - } diff --git a/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataStatCompositeTest.java b/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataStatCompositeTest.java index 7e7292b721..eb6efba201 100644 --- a/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataStatCompositeTest.java +++ b/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataStatCompositeTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.metadata; import org.apache.dubbo.config.ApplicationConfig; @@ -28,14 +27,15 @@ import org.apache.dubbo.metrics.model.container.LongContainer; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicLong; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_PUSH; import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_STORE_PROVIDER_INTERFACE; import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_SUBSCRIBE; @@ -74,14 +74,22 @@ public class MetadataStatCompositeTest { @Test void testInit() { - Assertions.assertEquals(statComposite.getApplicationStatComposite().getApplicationNumStats().size(), MetadataMetricsConstants.APP_LEVEL_KEYS.size()); + Assertions.assertEquals( + statComposite + .getApplicationStatComposite() + .getApplicationNumStats() + .size(), + MetadataMetricsConstants.APP_LEVEL_KEYS.size()); - //(rt)5 * (push,subscribe,service)3 - Assertions.assertEquals(5 * 3, statComposite.getRtStatComposite().getRtStats().size()); - statComposite.getApplicationStatComposite().getApplicationNumStats().values().forEach((v -> - Assertions.assertEquals(v.get(), new AtomicLong(0L).get()))); - statComposite.getRtStatComposite().getRtStats().forEach(rtContainer -> - { + // (rt)5 * (push,subscribe,service)3 + Assertions.assertEquals( + 5 * 3, statComposite.getRtStatComposite().getRtStats().size()); + statComposite + .getApplicationStatComposite() + .getApplicationNumStats() + .values() + .forEach((v -> Assertions.assertEquals(v.get(), new AtomicLong(0L).get()))); + statComposite.getRtStatComposite().getRtStats().forEach(rtContainer -> { for (Map.Entry entry : rtContainer.entrySet()) { Assertions.assertEquals(0L, rtContainer.getValueSupplier().apply(entry.getKey())); } @@ -92,14 +100,25 @@ public class MetadataStatCompositeTest { void testIncrement() { statComposite.incrementApp(MetricsKey.METADATA_PUSH_METRIC_NUM, 1); - Assertions.assertEquals(1L, statComposite.getApplicationStatComposite().getApplicationNumStats().get(MetricsKey.METADATA_PUSH_METRIC_NUM).get()); + Assertions.assertEquals( + 1L, + statComposite + .getApplicationStatComposite() + .getApplicationNumStats() + .get(MetricsKey.METADATA_PUSH_METRIC_NUM) + .get()); } @Test void testCalcRt() { statComposite.calcApplicationRt(OP_TYPE_SUBSCRIBE.getType(), 10L); - Assertions.assertTrue(statComposite.getRtStatComposite().getRtStats().stream().anyMatch(longContainer -> longContainer.specifyType(OP_TYPE_SUBSCRIBE.getType()))); - Optional> subContainer = statComposite.getRtStatComposite().getRtStats().stream().filter(longContainer -> longContainer.specifyType(OP_TYPE_SUBSCRIBE.getType())).findFirst(); - subContainer.ifPresent(v -> Assertions.assertEquals(10L, v.get(new ApplicationMetric(applicationModel)).longValue())); + Assertions.assertTrue(statComposite.getRtStatComposite().getRtStats().stream() + .anyMatch(longContainer -> longContainer.specifyType(OP_TYPE_SUBSCRIBE.getType()))); + Optional> subContainer = + statComposite.getRtStatComposite().getRtStats().stream() + .filter(longContainer -> longContainer.specifyType(OP_TYPE_SUBSCRIBE.getType())) + .findFirst(); + subContainer.ifPresent(v -> Assertions.assertEquals( + 10L, v.get(new ApplicationMetric(applicationModel)).longValue())); } } diff --git a/dubbo-metrics/dubbo-metrics-netty/pom.xml b/dubbo-metrics/dubbo-metrics-netty/pom.xml index 95067ef1b0..e3d1c50f97 100644 --- a/dubbo-metrics/dubbo-metrics-netty/pom.xml +++ b/dubbo-metrics/dubbo-metrics-netty/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - org.apache.dubbo - dubbo-metrics - ${revision} - ../pom.xml - - dubbo-metrics-netty - jar - ${project.artifactId} - The metrics module of dubbo project - - false - - - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - - + + 4.0.0 + + org.apache.dubbo + dubbo-metrics + ${revision} + ../pom.xml + + dubbo-metrics-netty + jar + ${project.artifactId} + The metrics module of dubbo project + + false + + + + org.apache.dubbo + dubbo-metrics-api + ${project.parent.version} + + diff --git a/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/NettyMetricsConstants.java b/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/NettyMetricsConstants.java index 236ba2d254..388b8e93e8 100644 --- a/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/NettyMetricsConstants.java +++ b/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/NettyMetricsConstants.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.registry; import org.apache.dubbo.metrics.model.key.MetricsKey; @@ -36,9 +35,15 @@ import static org.apache.dubbo.metrics.model.key.MetricsKey.NETTY_ALLOCATOR_THRE public interface NettyMetricsConstants { // App-level - List APP_LEVEL_KEYS = Arrays.asList(NETTY_ALLOCATOR_HEAP_MEMORY_USED,NETTY_ALLOCATOR_DIRECT_MEMORY_USED - ,NETTY_ALLOCATOR_PINNED_DIRECT_MEMORY,NETTY_ALLOCATOR_PINNED_HEAP_MEMORY,NETTY_ALLOCATOR_HEAP_ARENAS_NUM - ,NETTY_ALLOCATOR_DIRECT_ARENAS_NUM,NETTY_ALLOCATOR_NORMAL_CACHE_SIZE,NETTY_ALLOCATOR_SMALL_CACHE_SIZE,NETTY_ALLOCATOR_THREAD_LOCAL_CACHES_NUM - ,NETTY_ALLOCATOR_CHUNK_SIZE); - + List APP_LEVEL_KEYS = Arrays.asList( + NETTY_ALLOCATOR_HEAP_MEMORY_USED, + NETTY_ALLOCATOR_DIRECT_MEMORY_USED, + NETTY_ALLOCATOR_PINNED_DIRECT_MEMORY, + NETTY_ALLOCATOR_PINNED_HEAP_MEMORY, + NETTY_ALLOCATOR_HEAP_ARENAS_NUM, + NETTY_ALLOCATOR_DIRECT_ARENAS_NUM, + NETTY_ALLOCATOR_NORMAL_CACHE_SIZE, + NETTY_ALLOCATOR_SMALL_CACHE_SIZE, + NETTY_ALLOCATOR_THREAD_LOCAL_CACHES_NUM, + NETTY_ALLOCATOR_CHUNK_SIZE); } diff --git a/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/collector/NettyMetricsCollector.java b/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/collector/NettyMetricsCollector.java index 5c66a3f36b..0a30e63fe4 100644 --- a/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/collector/NettyMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/collector/NettyMetricsCollector.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.registry.collector; import org.apache.dubbo.common.extension.Activate; @@ -36,7 +35,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; - /** * Netty implementation of {@link MetricsCollector} */ @@ -83,7 +81,6 @@ public class NettyMetricsCollector extends CombMetricsCollector { return Optional.ofNullable(collectEnabled).orElse(true); } - @Override public List collect() { List list = new ArrayList<>(); diff --git a/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettyEvent.java b/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettyEvent.java index 72c8aff56f..9af8812b82 100644 --- a/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettyEvent.java +++ b/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettyEvent.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.registry.event; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; @@ -26,13 +25,12 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import static org.apache.dubbo.metrics.MetricsConstants.NETTY_METRICS_MAP; - /** * Netty related events */ public class NettyEvent extends TimeCounterEvent { public NettyEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper) { - super(applicationModel,typeWrapper); + super(applicationModel, typeWrapper); ScopeBeanFactory beanFactory = getSource().getBeanFactory(); NettyMetricsCollector collector; if (!beanFactory.isDestroyed()) { @@ -42,13 +40,11 @@ public class NettyEvent extends TimeCounterEvent { } public static NettyEvent toNettyEvent(ApplicationModel applicationModel) { - return new NettyEvent(applicationModel, new TypeWrapper(MetricsLevel.APP, null,null, null)) { + return new NettyEvent(applicationModel, new TypeWrapper(MetricsLevel.APP, null, null, null)) { @Override public void customAfterPost(Object postResult) { super.putAttachment(NETTY_METRICS_MAP, postResult); } }; } - - } diff --git a/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettySubDispatcher.java b/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettySubDispatcher.java index 040014c3f2..5dfacadf29 100644 --- a/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettySubDispatcher.java +++ b/dubbo-metrics/dubbo-metrics-netty/src/main/java/org/apache/dubbo/metrics/registry/event/NettySubDispatcher.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.registry.event; import org.apache.dubbo.metrics.event.MetricsEvent; @@ -25,7 +24,6 @@ import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.registry.collector.NettyMetricsCollector; import java.util.Collections; - import java.util.Map; import static org.apache.dubbo.metrics.MetricsConstants.NETTY_METRICS_MAP; @@ -42,11 +40,10 @@ public final class NettySubDispatcher extends SimpleMetricsEventMulticaster { @Override public void onEventFinish(TimeCounterEvent event) { Map lastNumMap = Collections.unmodifiableMap(event.getAttachmentValue(NETTY_METRICS_MAP)); - lastNumMap.forEach( - (k, v) -> { - MetricsKey metricsKey = MetricsKey.getMetricsByName(k); - collector.setAppNum(metricsKey, v); - }); + lastNumMap.forEach((k, v) -> { + MetricsKey metricsKey = MetricsKey.getMetricsByName(k); + collector.setAppNum(metricsKey, v); + }); } }); } diff --git a/dubbo-metrics/dubbo-metrics-prometheus/pom.xml b/dubbo-metrics/dubbo-metrics-prometheus/pom.xml index 27f8fc3581..1a88d4951b 100644 --- a/dubbo-metrics/dubbo-metrics-prometheus/pom.xml +++ b/dubbo-metrics/dubbo-metrics-prometheus/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - org.apache.dubbo - dubbo-metrics - ${revision} - ../pom.xml - - dubbo-metrics-prometheus - jar - ${project.artifactId} - The prometheus metrics module of dubbo project - - false - - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - - - io.micrometer - micrometer-registry-prometheus - - - io.prometheus - simpleclient_pushgateway - - - org.apache.httpcomponents - httpclient - test - - - org.apache.dubbo - dubbo-qos-api - ${project.parent.version} - compile - - + + 4.0.0 + + org.apache.dubbo + dubbo-metrics + ${revision} + ../pom.xml + + dubbo-metrics-prometheus + jar + ${project.artifactId} + The prometheus metrics module of dubbo project + + false + + + + org.apache.dubbo + dubbo-common + ${project.parent.version} + + + org.apache.dubbo + dubbo-metrics-default + ${project.parent.version} + + + io.micrometer + micrometer-registry-prometheus + + + io.prometheus + simpleclient_pushgateway + + + org.apache.httpcomponents + httpclient + test + + + org.apache.dubbo + dubbo-qos-api + ${project.parent.version} + compile + + diff --git a/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/NopPrometheusMetricsReporter.java b/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/NopPrometheusMetricsReporter.java index a5bf1a94d9..f0211ba396 100644 --- a/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/NopPrometheusMetricsReporter.java +++ b/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/NopPrometheusMetricsReporter.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.prometheus; import org.apache.dubbo.metrics.report.MetricsReporter; @@ -26,14 +25,10 @@ import org.apache.dubbo.metrics.report.MetricsReporter; public class NopPrometheusMetricsReporter implements MetricsReporter { @Override - public void init() { - - } + public void init() {} @Override - public void resetIfSamplesChanged() { - - } + public void resetIfSamplesChanged() {} @Override public String getResponse() { diff --git a/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporter.java b/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporter.java index 111f56634a..96948e1531 100644 --- a/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporter.java +++ b/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporter.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.prometheus; import org.apache.dubbo.common.URL; @@ -25,16 +24,16 @@ import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.metrics.report.AbstractMetricsReporter; import org.apache.dubbo.rpc.model.ApplicationModel; -import io.micrometer.prometheus.PrometheusConfig; -import io.micrometer.prometheus.PrometheusMeterRegistry; -import io.prometheus.client.exporter.BasicAuthHttpConnectionFactory; -import io.prometheus.client.exporter.PushGateway; - import java.io.IOException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import io.micrometer.prometheus.PrometheusConfig; +import io.micrometer.prometheus.PrometheusMeterRegistry; +import io.prometheus.client.exporter.BasicAuthHttpConnectionFactory; +import io.prometheus.client.exporter.PushGateway; + import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION; import static org.apache.dubbo.common.constants.MetricsConstants.PROMETHEUS_DEFAULT_JOB_NAME; import static org.apache.dubbo.common.constants.MetricsConstants.PROMETHEUS_DEFAULT_PUSH_INTERVAL; @@ -74,7 +73,8 @@ public class PrometheusMetricsReporter extends AbstractMetricsReporter { if (pushEnabled) { String baseUrl = url.getParameter(PROMETHEUS_PUSHGATEWAY_BASE_URL_KEY); String job = url.getParameter(PROMETHEUS_PUSHGATEWAY_JOB_KEY, PROMETHEUS_DEFAULT_JOB_NAME); - int pushInterval = url.getParameter(PROMETHEUS_PUSHGATEWAY_PUSH_INTERVAL_KEY, PROMETHEUS_DEFAULT_PUSH_INTERVAL); + int pushInterval = + url.getParameter(PROMETHEUS_PUSHGATEWAY_PUSH_INTERVAL_KEY, PROMETHEUS_DEFAULT_PUSH_INTERVAL); String username = url.getParameter(PROMETHEUS_PUSHGATEWAY_USERNAME_KEY); String password = url.getParameter(PROMETHEUS_PUSHGATEWAY_PASSWORD_KEY); @@ -85,7 +85,8 @@ public class PrometheusMetricsReporter extends AbstractMetricsReporter { pushGateway.setConnectionFactory(new BasicAuthHttpConnectionFactory(username, password)); } - pushJobExecutor.scheduleWithFixedDelay(() -> push(pushGateway, job), pushInterval, pushInterval, TimeUnit.SECONDS); + pushJobExecutor.scheduleWithFixedDelay( + () -> push(pushGateway, job), pushInterval, pushInterval, TimeUnit.SECONDS); } } @@ -94,7 +95,12 @@ public class PrometheusMetricsReporter extends AbstractMetricsReporter { resetIfSamplesChanged(); pushGateway.pushAdd(prometheusRegistry.getPrometheusRegistry(), job); } catch (IOException e) { - logger.error(COMMON_METRICS_COLLECTOR_EXCEPTION, "", "", "Error occurred when pushing metrics to prometheus: ", e); + logger.error( + COMMON_METRICS_COLLECTOR_EXCEPTION, + "", + "", + "Error occurred when pushing metrics to prometheus: ", + e); } } diff --git a/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterCmd.java b/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterCmd.java index c5df78394c..0626b6380b 100644 --- a/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterCmd.java +++ b/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterCmd.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.prometheus; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -38,7 +37,8 @@ import java.util.Optional; @Cmd(name = "metrics", summary = "reuse qos report") public class PrometheusMetricsReporterCmd implements BaseCommand { - private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PrometheusMetricsReporterCmd.class); + private final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(PrometheusMetricsReporterCmd.class); public FrameworkModel frameworkModel; @@ -85,7 +85,9 @@ public class PrometheusMetricsReporterCmd implements BaseCommand { } private String specifySingleApplication(String appName, List models) { - Optional modelOptional = models.stream().filter(applicationModel -> appName.equals(applicationModel.getApplicationName())).findFirst(); + Optional modelOptional = models.stream() + .filter(applicationModel -> appName.equals(applicationModel.getApplicationName())) + .findFirst(); if (modelOptional.isPresent()) { return getResponseByApplication(modelOptional.get()); } else { @@ -122,12 +124,10 @@ public class PrometheusMetricsReporterCmd implements BaseCommand { logger.debug(String.format("scrape end,Elapsed Time:%s", System.currentTimeMillis() - begin)); } response = metricsReporter.getResponse(); - } return response; } - private static long getLineNumber(String content) { LineNumberReader lnr = new LineNumberReader(new CharArrayReader(content.toCharArray())); @@ -138,5 +138,4 @@ public class PrometheusMetricsReporterCmd implements BaseCommand { } return lnr.getLineNumber(); } - } diff --git a/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterFactory.java b/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterFactory.java index c549d6688b..fcad830e1e 100644 --- a/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterFactory.java +++ b/dubbo-metrics/dubbo-metrics-prometheus/src/main/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterFactory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.prometheus; import org.apache.dubbo.common.URL; @@ -31,7 +30,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERR */ public class PrometheusMetricsReporterFactory extends AbstractMetricsReporterFactory { - private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PrometheusMetricsReporterFactory.class); + private final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(PrometheusMetricsReporterFactory.class); public PrometheusMetricsReporterFactory(ApplicationModel applicationModel) { super(applicationModel); @@ -44,9 +44,24 @@ public class PrometheusMetricsReporterFactory extends AbstractMetricsReporterFac } catch (NoClassDefFoundError ncde) { String msg = ncde.getMessage(); if (dependenciesNotFound(msg)) { - logger.error(INTERNAL_ERROR, "", "", "Failed to load class \"org.apache.dubbo.metrics.prometheus.PrometheusMetricsReporter\".", ncde); - logger.error(INTERNAL_ERROR, "", "", "Defaulting to no-operation (NOP) metricsReporter implementation", ncde); - logger.error(INTERNAL_ERROR, "", "", "Introduce the micrometer-core package to use the ability of metrics", ncde); + logger.error( + INTERNAL_ERROR, + "", + "", + "Failed to load class \"org.apache.dubbo.metrics.prometheus.PrometheusMetricsReporter\".", + ncde); + logger.error( + INTERNAL_ERROR, + "", + "", + "Defaulting to no-operation (NOP) metricsReporter implementation", + ncde); + logger.error( + INTERNAL_ERROR, + "", + "", + "Introduce the micrometer-core package to use the ability of metrics", + ncde); return new NopPrometheusMetricsReporter(); } else { logger.error(INTERNAL_ERROR, "", "", "Failed to instantiate PrometheusMetricsReporter", ncde); diff --git a/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterFactoryTest.java b/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterFactoryTest.java index 50725ca82f..88646278ff 100644 --- a/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterFactoryTest.java +++ b/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterFactoryTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.prometheus; import org.apache.dubbo.common.URL; diff --git a/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterTest.java b/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterTest.java index 8badfebab7..5304963a04 100644 --- a/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterTest.java +++ b/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsReporterTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.prometheus; import org.apache.dubbo.config.ApplicationConfig; @@ -24,6 +23,16 @@ import org.apache.dubbo.metrics.collector.DefaultMetricsCollector; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.ScheduledExecutorService; +import java.util.stream.Collectors; + import com.sun.net.httpserver.HttpServer; import io.micrometer.prometheus.PrometheusMeterRegistry; import org.apache.http.client.methods.CloseableHttpResponse; @@ -35,16 +44,6 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.net.InetSocketAddress; -import java.nio.charset.StandardCharsets; -import java.util.concurrent.ScheduledExecutorService; -import java.util.stream.Collectors; - import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS; class PrometheusMetricsReporterTest { @@ -78,8 +77,10 @@ class PrometheusMetricsReporterTest { PrometheusMeterRegistry prometheusRegistry = reporter.getPrometheusRegistry(); Double d1 = prometheusRegistry.getPrometheusRegistry().getSampleValue("none_exist_metric"); - Double d2 = prometheusRegistry.getPrometheusRegistry().getSampleValue("jvm_gc_memory_promoted_bytes_total", - new String[]{"application_name"}, new String[]{name}); + Double d2 = prometheusRegistry + .getPrometheusRegistry() + .getSampleValue( + "jvm_gc_memory_promoted_bytes_total", new String[] {"application_name"}, new String[] {name}); Assertions.assertNull(d1); Assertions.assertNull(d2); } @@ -87,7 +88,7 @@ class PrometheusMetricsReporterTest { @Test void testExporter() { int port = 31539; -// NetUtils.getAvailablePort(); + // NetUtils.getAvailablePort(); PrometheusConfig prometheusConfig = new PrometheusConfig(); PrometheusConfig.Exporter exporter = new PrometheusConfig.Exporter(); exporter.setEnabled(true); @@ -95,7 +96,9 @@ class PrometheusMetricsReporterTest { metricsConfig.setPrometheus(prometheusConfig); metricsConfig.setEnableJvm(true); - ApplicationModel.defaultModel().getApplicationConfigManager().setApplication(new ApplicationConfig("metrics-test")); + ApplicationModel.defaultModel() + .getApplicationConfigManager() + .setApplication(new ApplicationConfig("metrics-test")); PrometheusMetricsReporter reporter = new PrometheusMetricsReporter(metricsConfig.toUrl(), applicationModel); reporter.init(); exportHttpServer(reporter, port); @@ -108,7 +111,9 @@ class PrometheusMetricsReporterTest { HttpGet request = new HttpGet("http://localhost:" + port + "/metrics"); CloseableHttpResponse response = client.execute(request); InputStream inputStream = response.getEntity().getContent(); - String text = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines().collect(Collectors.joining("\n")); + String text = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)) + .lines() + .collect(Collectors.joining("\n")); Assertions.assertTrue(text.contains("jvm_gc_memory_promoted_bytes_total")); } catch (Exception e) { Assertions.fail(e); @@ -138,7 +143,6 @@ class PrometheusMetricsReporterTest { Assertions.assertTrue(executor.isTerminated() || executor.isShutdown()); } - private void exportHttpServer(PrometheusMetricsReporter reporter, int port) { try { @@ -158,5 +162,4 @@ class PrometheusMetricsReporterTest { throw new RuntimeException(e); } } - } diff --git a/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsThreadPoolTest.java b/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsThreadPoolTest.java index 4b30009cf1..5591cd8c54 100644 --- a/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsThreadPoolTest.java +++ b/dubbo-metrics/dubbo-metrics-prometheus/src/test/java/org/apache/dubbo/metrics/prometheus/PrometheusMetricsThreadPoolTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -25,16 +25,6 @@ import org.apache.dubbo.metrics.model.sample.GaugeMetricSample; import org.apache.dubbo.metrics.model.sample.MetricSample; import org.apache.dubbo.rpc.model.ApplicationModel; -import com.sun.net.httpserver.HttpServer; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -46,6 +36,16 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import com.sun.net.httpserver.HttpServer; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME; import static org.apache.dubbo.common.constants.MetricsConstants.TAG_HOSTNAME; @@ -54,7 +54,6 @@ import static org.apache.dubbo.common.constants.MetricsConstants.TAG_THREAD_NAME import static org.apache.dubbo.common.utils.NetUtils.getLocalHost; import static org.apache.dubbo.common.utils.NetUtils.getLocalHostName; - public class PrometheusMetricsThreadPoolTest { private ApplicationModel applicationModel; @@ -95,20 +94,22 @@ public class PrometheusMetricsThreadPoolTest { metricsCollector.collectApplication(); PrometheusMetricsReporter reporter = new PrometheusMetricsReporter(metricsConfig.toUrl(), applicationModel); reporter.init(); - exportHttpServer(reporter,port); + exportHttpServer(reporter, port); try { Thread.sleep(5000); } catch (InterruptedException e) { throw new RuntimeException(e); } - if(metricsConfig.getEnableThreadpool()) { + if (metricsConfig.getEnableThreadpool()) { metricsCollector.registryDefaultSample(); } try (CloseableHttpClient client = HttpClients.createDefault()) { HttpGet request = new HttpGet("http://localhost:" + port + "/metrics"); CloseableHttpResponse response = client.execute(request); InputStream inputStream = response.getEntity().getContent(); - String text = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines().collect(Collectors.joining("\n")); + String text = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)) + .lines() + .collect(Collectors.joining("\n")); Assertions.assertTrue(text.contains("dubbo_thread_pool_core_size")); Assertions.assertTrue(text.contains("dubbo_thread_pool_thread_count")); } catch (Exception e) { @@ -118,7 +119,6 @@ public class PrometheusMetricsThreadPoolTest { } } - private void exportHttpServer(PrometheusMetricsReporter reporter, int port) { try { HttpServer prometheusExporterHttpServer = HttpServer.create(new InetSocketAddress(port), 0); @@ -137,17 +137,16 @@ public class PrometheusMetricsThreadPoolTest { } } - - @Test @SuppressWarnings("rawtypes") void testThreadPoolRejectMetrics() { DefaultMetricsCollector collector = new DefaultMetricsCollector(applicationModel); collector.setCollectEnabled(true); collector.setApplicationName(applicationModel.getApplicationName()); - String threadPoolExecutorName="DubboServerHandler-20816"; - ThreadRejectMetricsCountSampler threadRejectMetricsCountSampler=new ThreadRejectMetricsCountSampler(collector); - threadRejectMetricsCountSampler.inc(threadPoolExecutorName,threadPoolExecutorName); + String threadPoolExecutorName = "DubboServerHandler-20816"; + ThreadRejectMetricsCountSampler threadRejectMetricsCountSampler = + new ThreadRejectMetricsCountSampler(collector); + threadRejectMetricsCountSampler.inc(threadPoolExecutorName, threadPoolExecutorName); threadRejectMetricsCountSampler.addMetricName(threadPoolExecutorName); List samples = collector.collect(); for (MetricSample sample : samples) { @@ -161,5 +160,4 @@ public class PrometheusMetricsThreadPoolTest { Assertions.assertEquals(gaugeSample.applyAsLong(), 1); } } - } diff --git a/dubbo-metrics/dubbo-metrics-registry/pom.xml b/dubbo-metrics/dubbo-metrics-registry/pom.xml index 86f190ff76..f03625270a 100644 --- a/dubbo-metrics/dubbo-metrics-registry/pom.xml +++ b/dubbo-metrics/dubbo-metrics-registry/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - org.apache.dubbo - dubbo-metrics - ${revision} - ../pom.xml - - dubbo-metrics-registry - jar - ${project.artifactId} - The metrics module of dubbo project - - false - - - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - - + + 4.0.0 + + org.apache.dubbo + dubbo-metrics + ${revision} + ../pom.xml + + dubbo-metrics-registry + jar + ${project.artifactId} + The metrics module of dubbo project + + false + + + + org.apache.dubbo + dubbo-metrics-api + ${project.parent.version} + + diff --git a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/RegistryMetricsConstants.java b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/RegistryMetricsConstants.java index 18dac35bc6..da52afe33b 100644 --- a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/RegistryMetricsConstants.java +++ b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/RegistryMetricsConstants.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.registry; import org.apache.dubbo.metrics.model.key.MetricsKey; @@ -61,22 +60,25 @@ public interface RegistryMetricsConstants { List APP_LEVEL_KEYS = Collections.singletonList(NOTIFY_METRIC_REQUESTS); // Registry-level - List REGISTER_LEVEL_KEYS = Arrays.asList(REGISTER_METRIC_REQUESTS, REGISTER_METRIC_REQUESTS_SUCCEED, REGISTER_METRIC_REQUESTS_FAILED, - SUBSCRIBE_METRIC_NUM, SUBSCRIBE_METRIC_NUM_SUCCEED, SUBSCRIBE_METRIC_NUM_FAILED - ); + List REGISTER_LEVEL_KEYS = Arrays.asList( + REGISTER_METRIC_REQUESTS, + REGISTER_METRIC_REQUESTS_SUCCEED, + REGISTER_METRIC_REQUESTS_FAILED, + SUBSCRIBE_METRIC_NUM, + SUBSCRIBE_METRIC_NUM_SUCCEED, + SUBSCRIBE_METRIC_NUM_FAILED); // Service-level List SERVICE_LEVEL_KEYS = Arrays.asList( - new MetricsKeyWrapper(NOTIFY_METRIC_NUM_LAST, OP_TYPE_NOTIFY), - new MetricsKeyWrapper(SERVICE_REGISTER_METRIC_REQUESTS, OP_TYPE_REGISTER_SERVICE), - new MetricsKeyWrapper(SERVICE_REGISTER_METRIC_REQUESTS_SUCCEED, OP_TYPE_REGISTER_SERVICE), - new MetricsKeyWrapper(SERVICE_REGISTER_METRIC_REQUESTS_FAILED, OP_TYPE_REGISTER_SERVICE), - new MetricsKeyWrapper(SERVICE_SUBSCRIBE_METRIC_NUM, OP_TYPE_SUBSCRIBE_SERVICE), - new MetricsKeyWrapper(SERVICE_SUBSCRIBE_METRIC_NUM_SUCCEED, OP_TYPE_SUBSCRIBE_SERVICE), - new MetricsKeyWrapper(SERVICE_SUBSCRIBE_METRIC_NUM_FAILED, OP_TYPE_SUBSCRIBE_SERVICE), - new MetricsKeyWrapper(DIRECTORY_METRIC_NUM_VALID, OP_TYPE_DIRECTORY), - new MetricsKeyWrapper(DIRECTORY_METRIC_NUM_TO_RECONNECT, OP_TYPE_DIRECTORY), - new MetricsKeyWrapper(DIRECTORY_METRIC_NUM_DISABLE, OP_TYPE_DIRECTORY), - new MetricsKeyWrapper(DIRECTORY_METRIC_NUM_ALL, OP_TYPE_DIRECTORY) - ); + new MetricsKeyWrapper(NOTIFY_METRIC_NUM_LAST, OP_TYPE_NOTIFY), + new MetricsKeyWrapper(SERVICE_REGISTER_METRIC_REQUESTS, OP_TYPE_REGISTER_SERVICE), + new MetricsKeyWrapper(SERVICE_REGISTER_METRIC_REQUESTS_SUCCEED, OP_TYPE_REGISTER_SERVICE), + new MetricsKeyWrapper(SERVICE_REGISTER_METRIC_REQUESTS_FAILED, OP_TYPE_REGISTER_SERVICE), + new MetricsKeyWrapper(SERVICE_SUBSCRIBE_METRIC_NUM, OP_TYPE_SUBSCRIBE_SERVICE), + new MetricsKeyWrapper(SERVICE_SUBSCRIBE_METRIC_NUM_SUCCEED, OP_TYPE_SUBSCRIBE_SERVICE), + new MetricsKeyWrapper(SERVICE_SUBSCRIBE_METRIC_NUM_FAILED, OP_TYPE_SUBSCRIBE_SERVICE), + new MetricsKeyWrapper(DIRECTORY_METRIC_NUM_VALID, OP_TYPE_DIRECTORY), + new MetricsKeyWrapper(DIRECTORY_METRIC_NUM_TO_RECONNECT, OP_TYPE_DIRECTORY), + new MetricsKeyWrapper(DIRECTORY_METRIC_NUM_DISABLE, OP_TYPE_DIRECTORY), + new MetricsKeyWrapper(DIRECTORY_METRIC_NUM_ALL, OP_TYPE_DIRECTORY)); } diff --git a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/RegistryMetricsCollector.java b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/RegistryMetricsCollector.java index 6559a49ed2..c10bca41dd 100644 --- a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/RegistryMetricsCollector.java +++ b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/RegistryMetricsCollector.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.registry.collector; import org.apache.dubbo.common.constants.RegistryConstants; @@ -49,7 +48,6 @@ import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_SUBSCRIBE; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_SUBSCRIBE_SERVICE; - /** * Registry implementation of {@link MetricsCollector} */ @@ -77,7 +75,12 @@ public class RegistryMetricsCollector extends CombMetricsCollector collect() { List list = new ArrayList<>(); @@ -116,33 +118,40 @@ public class RegistryMetricsCollector extends CombMetricsCollector internalStat.incrMetricsNum(metricsKey, name)); } - public void incrRegisterFinishNum(MetricsKey metricsKey, String registryOpType, List registryClusterNames, Long responseTime) { - registryClusterNames.forEach(name -> - { + public void incrRegisterFinishNum( + MetricsKey metricsKey, String registryOpType, List registryClusterNames, Long responseTime) { + registryClusterNames.forEach(name -> { ApplicationMetric applicationMetric = new ApplicationMetric(applicationModel); - applicationMetric.setExtraInfo(Collections.singletonMap(RegistryConstants.REGISTRY_CLUSTER_KEY.toLowerCase(), name)); + applicationMetric.setExtraInfo( + Collections.singletonMap(RegistryConstants.REGISTRY_CLUSTER_KEY.toLowerCase(), name)); internalStat.incrMetricsNum(metricsKey, name); getStats().getRtStatComposite().calcServiceKeyRt(registryOpType, responseTime, applicationMetric); }); - } - public void incrServiceRegisterNum(MetricsKeyWrapper wrapper, String serviceKey, List registryClusterNames, int size) { - registryClusterNames.forEach(name -> - stats.incrementServiceKey(wrapper, serviceKey, Collections.singletonMap(RegistryConstants.REGISTRY_CLUSTER_KEY.toLowerCase(), name), size) - ); + public void incrServiceRegisterNum( + MetricsKeyWrapper wrapper, String serviceKey, List registryClusterNames, int size) { + registryClusterNames.forEach(name -> stats.incrementServiceKey( + wrapper, + serviceKey, + Collections.singletonMap(RegistryConstants.REGISTRY_CLUSTER_KEY.toLowerCase(), name), + size)); } - public void incrServiceRegisterFinishNum(MetricsKeyWrapper wrapper, String serviceKey, List registryClusterNames, int size, Long responseTime) { - registryClusterNames.forEach(name -> - { - Map extraInfo = Collections.singletonMap(RegistryConstants.REGISTRY_CLUSTER_KEY.toLowerCase(), name); - ServiceKeyMetric serviceKeyMetric = new ServiceKeyMetric(applicationModel, serviceKey); - serviceKeyMetric.setExtraInfo(extraInfo); - stats.incrementServiceKey(wrapper, serviceKey, extraInfo, size); - getStats().getRtStatComposite().calcServiceKeyRt(wrapper.getType(), responseTime, serviceKeyMetric); - } - ); + public void incrServiceRegisterFinishNum( + MetricsKeyWrapper wrapper, + String serviceKey, + List registryClusterNames, + int size, + Long responseTime) { + registryClusterNames.forEach(name -> { + Map extraInfo = + Collections.singletonMap(RegistryConstants.REGISTRY_CLUSTER_KEY.toLowerCase(), name); + ServiceKeyMetric serviceKeyMetric = new ServiceKeyMetric(applicationModel, serviceKey); + serviceKeyMetric.setExtraInfo(extraInfo); + stats.incrementServiceKey(wrapper, serviceKey, extraInfo, size); + getStats().getRtStatComposite().calcServiceKeyRt(wrapper.getType(), responseTime, serviceKeyMetric); + }); } public void setNum(MetricsKeyWrapper metricsKey, String serviceKey, int num, Map attachments) { diff --git a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/RegistryStatComposite.java b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/RegistryStatComposite.java index 68bbd2fcba..567b6d6ee0 100644 --- a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/RegistryStatComposite.java +++ b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/collector/RegistryStatComposite.java @@ -65,7 +65,10 @@ public class RegistryStatComposite extends AbstractMetricsExport { for (MetricsKey metricsKey : appStats.keySet()) { Map stringAtomicLongMap = appStats.get(metricsKey); for (ApplicationMetric registerKeyMetric : stringAtomicLongMap.keySet()) { - list.add(new GaugeMetricSample<>(metricsKey, registerKeyMetric.getTags(), category, stringAtomicLongMap, value -> value.get(registerKeyMetric).get())); + list.add(new GaugeMetricSample<>( + metricsKey, registerKeyMetric.getTags(), category, stringAtomicLongMap, value -> value.get( + registerKeyMetric) + .get())); } } return list; @@ -76,7 +79,8 @@ public class RegistryStatComposite extends AbstractMetricsExport { return; } ApplicationMetric applicationMetric = new ApplicationMetric(getApplicationModel()); - applicationMetric.setExtraInfo(Collections.singletonMap(RegistryConstants.REGISTRY_CLUSTER_KEY.toLowerCase(), name)); + applicationMetric.setExtraInfo( + Collections.singletonMap(RegistryConstants.REGISTRY_CLUSTER_KEY.toLowerCase(), name)); Map stats = appStats.get(metricsKey); AtomicLong metrics = stats.get(applicationMetric); if (metrics == null) { diff --git a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistryEvent.java b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistryEvent.java index 97b9bac1ac..d122ecabc3 100644 --- a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistryEvent.java +++ b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistryEvent.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.registry.event; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; @@ -35,7 +34,6 @@ import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_LAST_NUM_ import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_SERVICE; import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_SIZE; - /** * Registry related events */ @@ -50,7 +48,11 @@ public class RegistryEvent extends TimeCounterEvent { } } - private static final TypeWrapper REGISTER_EVENT = new TypeWrapper(MetricsLevel.APP, MetricsKey.REGISTER_METRIC_REQUESTS, MetricsKey.REGISTER_METRIC_REQUESTS_SUCCEED, MetricsKey.REGISTER_METRIC_REQUESTS_FAILED); + private static final TypeWrapper REGISTER_EVENT = new TypeWrapper( + MetricsLevel.APP, + MetricsKey.REGISTER_METRIC_REQUESTS, + MetricsKey.REGISTER_METRIC_REQUESTS_SUCCEED, + MetricsKey.REGISTER_METRIC_REQUESTS_FAILED); public static RegistryEvent toRegisterEvent(ApplicationModel applicationModel, List registryClusterNames) { RegistryEvent registryEvent = new RegistryEvent(applicationModel, REGISTER_EVENT); @@ -58,17 +60,21 @@ public class RegistryEvent extends TimeCounterEvent { return registryEvent; } - - private static final TypeWrapper SUBSCRIBE_EVENT = new TypeWrapper(MetricsLevel.APP, MetricsKey.SUBSCRIBE_METRIC_NUM, MetricsKey.SUBSCRIBE_METRIC_NUM_SUCCEED, MetricsKey.SUBSCRIBE_METRIC_NUM_FAILED); + private static final TypeWrapper SUBSCRIBE_EVENT = new TypeWrapper( + MetricsLevel.APP, + MetricsKey.SUBSCRIBE_METRIC_NUM, + MetricsKey.SUBSCRIBE_METRIC_NUM_SUCCEED, + MetricsKey.SUBSCRIBE_METRIC_NUM_FAILED); public static RegistryEvent toSubscribeEvent(ApplicationModel applicationModel, String registryClusterName) { RegistryEvent ddEvent = new RegistryEvent(applicationModel, SUBSCRIBE_EVENT); - ddEvent.putAttachment(RegistryMetricsConstants.ATTACHMENT_REGISTRY_KEY, Collections.singletonList(registryClusterName)); + ddEvent.putAttachment( + RegistryMetricsConstants.ATTACHMENT_REGISTRY_KEY, Collections.singletonList(registryClusterName)); return ddEvent; } - - private static final TypeWrapper NOTIFY_EVENT = new TypeWrapper(MetricsLevel.APP, MetricsKey.NOTIFY_METRIC_REQUESTS, MetricsKey.NOTIFY_METRIC_NUM_LAST, (MetricsKey) null); + private static final TypeWrapper NOTIFY_EVENT = new TypeWrapper( + MetricsLevel.APP, MetricsKey.NOTIFY_METRIC_REQUESTS, MetricsKey.NOTIFY_METRIC_NUM_LAST, (MetricsKey) null); public static RegistryEvent toNotifyEvent(ApplicationModel applicationModel) { return new RegistryEvent(applicationModel, NOTIFY_EVENT) { @@ -79,9 +85,14 @@ public class RegistryEvent extends TimeCounterEvent { }; } - private static final TypeWrapper RS_EVENT = new TypeWrapper(MetricsLevel.SERVICE, MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS, MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_SUCCEED, MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_FAILED); + private static final TypeWrapper RS_EVENT = new TypeWrapper( + MetricsLevel.SERVICE, + MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS, + MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_SUCCEED, + MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_FAILED); - public static RegistryEvent toRsEvent(ApplicationModel applicationModel, String serviceKey, int size, List serviceDiscoveryNames) { + public static RegistryEvent toRsEvent( + ApplicationModel applicationModel, String serviceKey, int size, List serviceDiscoveryNames) { RegistryEvent ddEvent = new RegistryEvent(applicationModel, RS_EVENT); ddEvent.putAttachment(ATTACHMENT_KEY_SERVICE, serviceKey); ddEvent.putAttachment(ATTACHMENT_KEY_SIZE, size); @@ -89,9 +100,14 @@ public class RegistryEvent extends TimeCounterEvent { return ddEvent; } - private static final TypeWrapper SS_EVENT = new TypeWrapper(MetricsLevel.SERVICE, MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM, MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM_SUCCEED, MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM_FAILED); + private static final TypeWrapper SS_EVENT = new TypeWrapper( + MetricsLevel.SERVICE, + MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM, + MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM_SUCCEED, + MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM_FAILED); - public static RegistryEvent toSsEvent(ApplicationModel applicationModel, String serviceKey, List serviceDiscoveryNames) { + public static RegistryEvent toSsEvent( + ApplicationModel applicationModel, String serviceKey, List serviceDiscoveryNames) { RegistryEvent ddEvent = new RegistryEvent(applicationModel, SS_EVENT); ddEvent.putAttachment(ATTACHMENT_KEY_SERVICE, serviceKey); ddEvent.putAttachment(ATTACHMENT_KEY_SIZE, 1); @@ -99,14 +115,16 @@ public class RegistryEvent extends TimeCounterEvent { return ddEvent; } - private static final TypeWrapper DIRECTORY_EVENT = new TypeWrapper(MetricsLevel.APP, MetricsKey.DIRECTORY_METRIC_NUM_VALID, null, null); + private static final TypeWrapper DIRECTORY_EVENT = + new TypeWrapper(MetricsLevel.APP, MetricsKey.DIRECTORY_METRIC_NUM_VALID, null, null); - public static RegistryEvent refreshDirectoryEvent(ApplicationModel applicationModel, Map> summaryMap, Map attachments) { + public static RegistryEvent refreshDirectoryEvent( + ApplicationModel applicationModel, + Map> summaryMap, + Map attachments) { RegistryEvent registryEvent = new RegistryEvent(applicationModel, DIRECTORY_EVENT); registryEvent.putAttachment(ATTACHMENT_DIRECTORY_MAP, summaryMap); registryEvent.putAttachments(attachments); return registryEvent; } - - } diff --git a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySpecListener.java b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySpecListener.java index 6e44fea1b1..a28ec570f1 100644 --- a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySpecListener.java +++ b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySpecListener.java @@ -52,87 +52,98 @@ public class RegistrySpecListener { * Can use a custom listener instead of this generic operation */ public static AbstractMetricsKeyListener onPost(MetricsKey metricsKey, CombMetricsCollector collector) { - return AbstractMetricsKeyListener.onEvent(metricsKey, - event -> ((RegistryMetricsCollector) collector).incrMetricsNum(metricsKey, getRgs(event)) - ); + return AbstractMetricsKeyListener.onEvent( + metricsKey, event -> ((RegistryMetricsCollector) collector).incrMetricsNum(metricsKey, getRgs(event))); } public static AbstractMetricsKeyListener onFinish(MetricsKey metricsKey, CombMetricsCollector collector) { - return AbstractMetricsKeyListener.onFinish(metricsKey, - event -> ((RegistryMetricsCollector) collector).incrRegisterFinishNum(metricsKey, OP_TYPE_REGISTER.getType(), getRgs(event), event.getTimePair().calc()) - ); + return AbstractMetricsKeyListener.onFinish(metricsKey, event -> ((RegistryMetricsCollector) collector) + .incrRegisterFinishNum( + metricsKey, + OP_TYPE_REGISTER.getType(), + getRgs(event), + event.getTimePair().calc())); } public static AbstractMetricsKeyListener onError(MetricsKey metricsKey, CombMetricsCollector collector) { - return AbstractMetricsKeyListener.onError(metricsKey, - event -> ((RegistryMetricsCollector) collector).incrRegisterFinishNum(metricsKey, OP_TYPE_REGISTER.getType(), getRgs(event), event.getTimePair().calc()) - ); + return AbstractMetricsKeyListener.onError(metricsKey, event -> ((RegistryMetricsCollector) collector) + .incrRegisterFinishNum( + metricsKey, + OP_TYPE_REGISTER.getType(), + getRgs(event), + event.getTimePair().calc())); } - public static AbstractMetricsKeyListener onPostOfService(MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { - return AbstractMetricsKeyListener.onEvent(metricsKey, - event -> ((RegistryMetricsCollector) collector).incrServiceRegisterNum(new MetricsKeyWrapper(metricsKey, placeType), getServiceKey(event), getRgs(event), getSize(event)) - ); + public static AbstractMetricsKeyListener onPostOfService( + MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { + return AbstractMetricsKeyListener.onEvent(metricsKey, event -> ((RegistryMetricsCollector) collector) + .incrServiceRegisterNum( + new MetricsKeyWrapper(metricsKey, placeType), + getServiceKey(event), + getRgs(event), + getSize(event))); } - public static AbstractMetricsKeyListener onFinishOfService(MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { - return AbstractMetricsKeyListener.onFinish(metricsKey, - event -> ((RegistryMetricsCollector) collector).incrServiceRegisterFinishNum(new MetricsKeyWrapper(metricsKey, placeType), getServiceKey(event), getRgs(event), getSize(event), event.getTimePair().calc()) - ); + public static AbstractMetricsKeyListener onFinishOfService( + MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { + return AbstractMetricsKeyListener.onFinish(metricsKey, event -> ((RegistryMetricsCollector) collector) + .incrServiceRegisterFinishNum( + new MetricsKeyWrapper(metricsKey, placeType), + getServiceKey(event), + getRgs(event), + getSize(event), + event.getTimePair().calc())); } - public static AbstractMetricsKeyListener onErrorOfService(MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { - return AbstractMetricsKeyListener.onError(metricsKey, - event -> ((RegistryMetricsCollector) collector).incrServiceRegisterFinishNum(new MetricsKeyWrapper(metricsKey, placeType), getServiceKey(event), getRgs(event), getSize(event), event.getTimePair().calc()) - ); + public static AbstractMetricsKeyListener onErrorOfService( + MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { + return AbstractMetricsKeyListener.onError(metricsKey, event -> ((RegistryMetricsCollector) collector) + .incrServiceRegisterFinishNum( + new MetricsKeyWrapper(metricsKey, placeType), + getServiceKey(event), + getRgs(event), + getSize(event), + event.getTimePair().calc())); } /** * Every time an event is triggered, multiple serviceKey related to notify are increment */ - public static AbstractMetricsKeyListener onFinishOfNotify(MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { - return AbstractMetricsKeyListener.onFinish(metricsKey, - event -> - { - collector.addServiceRt(event.appName(), placeType.getType(), event.getTimePair().calc()); - Map lastNumMap = Collections.unmodifiableMap(event.getAttachmentValue(ATTACHMENT_KEY_LAST_NUM_MAP)); - lastNumMap.forEach( - (k, v) -> collector.setNum(new MetricsKeyWrapper(metricsKey, OP_TYPE_NOTIFY), k, v)); - } - ); + public static AbstractMetricsKeyListener onFinishOfNotify( + MetricsKey metricsKey, MetricsPlaceValue placeType, CombMetricsCollector collector) { + return AbstractMetricsKeyListener.onFinish(metricsKey, event -> { + collector.addServiceRt( + event.appName(), placeType.getType(), event.getTimePair().calc()); + Map lastNumMap = + Collections.unmodifiableMap(event.getAttachmentValue(ATTACHMENT_KEY_LAST_NUM_MAP)); + lastNumMap.forEach((k, v) -> collector.setNum(new MetricsKeyWrapper(metricsKey, OP_TYPE_NOTIFY), k, v)); + }); } /** * Every time an event is triggered, multiple fixed key related to directory are increment, which has nothing to do with the monitored key */ - public static AbstractMetricsKeyListener onPostOfDirectory(MetricsKey metricsKey, CombMetricsCollector collector) { - return AbstractMetricsKeyListener.onEvent(metricsKey, - event -> { - Map> summaryMap = event.getAttachmentValue(ATTACHMENT_DIRECTORY_MAP); - Map otherAttachments = new HashMap<>(); - for (Map.Entry entry : event.getAttachments().entrySet()) { - if (entry.getValue() instanceof String) { - otherAttachments.put(entry.getKey().toLowerCase(Locale.ROOT), (String) entry.getValue()); - } + public static AbstractMetricsKeyListener onPostOfDirectory( + MetricsKey metricsKey, CombMetricsCollector collector) { + return AbstractMetricsKeyListener.onEvent(metricsKey, event -> { + Map> summaryMap = event.getAttachmentValue(ATTACHMENT_DIRECTORY_MAP); + Map otherAttachments = new HashMap<>(); + for (Map.Entry entry : event.getAttachments().entrySet()) { + if (entry.getValue() instanceof String) { + otherAttachments.put(entry.getKey().toLowerCase(Locale.ROOT), (String) entry.getValue()); } - summaryMap.forEach((summaryKey, map) -> - map.forEach( - (k, v) -> - { - if (CollectionUtils.isEmptyMap(otherAttachments)) { - collector.setNum(new MetricsKeyWrapper(summaryKey, OP_TYPE_DIRECTORY), k, v); - } else { - ((RegistryMetricsCollector) collector).setNum(new MetricsKeyWrapper(summaryKey, OP_TYPE_DIRECTORY), k, v, otherAttachments); - } - } - - )); - } - ); + summaryMap.forEach((summaryKey, map) -> map.forEach((k, v) -> { + if (CollectionUtils.isEmptyMap(otherAttachments)) { + collector.setNum(new MetricsKeyWrapper(summaryKey, OP_TYPE_DIRECTORY), k, v); + } else { + ((RegistryMetricsCollector) collector) + .setNum(new MetricsKeyWrapper(summaryKey, OP_TYPE_DIRECTORY), k, v, otherAttachments); + } + })); + }); } - /** * Get the number of multiple registries */ @@ -150,5 +161,4 @@ public class RegistrySpecListener { public static String getServiceKey(MetricsEvent event) { return event.getAttachmentValue(ATTACHMENT_KEY_SERVICE); } - } diff --git a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySubDispatcher.java b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySubDispatcher.java index 27cbcb4f61..458ed9d7af 100644 --- a/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySubDispatcher.java +++ b/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySubDispatcher.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.registry.event; import org.apache.dubbo.metrics.event.SimpleMetricsEventMulticaster; @@ -36,11 +35,9 @@ import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE public final class RegistrySubDispatcher extends SimpleMetricsEventMulticaster { - public RegistrySubDispatcher(RegistryMetricsCollector collector) { - CategorySet.ALL.forEach(categorySet -> - { + CategorySet.ALL.forEach(categorySet -> { super.addListener(categorySet.getPost().getEventFunc().apply(collector)); if (categorySet.getFinish() != null) { super.addListener(categorySet.getFinish().getEventFunc().apply(collector)); @@ -55,52 +52,84 @@ public final class RegistrySubDispatcher extends SimpleMetricsEventMulticaster { * A closer aggregation of MetricsCat, a summary collection of certain types of events */ interface CategorySet { - CategoryOverall APPLICATION_REGISTER = new CategoryOverall(OP_TYPE_REGISTER, MCat.APPLICATION_REGISTER_POST, MCat.APPLICATION_REGISTER_FINISH, MCat.APPLICATION_REGISTER_ERROR); - CategoryOverall APPLICATION_SUBSCRIBE = new CategoryOverall(OP_TYPE_SUBSCRIBE, MCat.APPLICATION_SUBSCRIBE_POST, MCat.APPLICATION_SUBSCRIBE_FINISH, MCat.APPLICATION_SUBSCRIBE_ERROR); - CategoryOverall APPLICATION_NOTIFY = new CategoryOverall(OP_TYPE_NOTIFY, MCat.APPLICATION_NOTIFY_POST, MCat.APPLICATION_NOTIFY_FINISH, null); - CategoryOverall SERVICE_DIRECTORY = new CategoryOverall(OP_TYPE_DIRECTORY, MCat.APPLICATION_DIRECTORY_POST, null, null); - CategoryOverall SERVICE_REGISTER = new CategoryOverall(OP_TYPE_REGISTER_SERVICE, MCat.SERVICE_REGISTER_POST, MCat.SERVICE_REGISTER_FINISH, MCat.SERVICE_REGISTER_ERROR); - CategoryOverall SERVICE_SUBSCRIBE = new CategoryOverall(OP_TYPE_SUBSCRIBE_SERVICE, MCat.SERVICE_SUBSCRIBE_POST, MCat.SERVICE_SUBSCRIBE_FINISH, MCat.SERVICE_SUBSCRIBE_ERROR); + CategoryOverall APPLICATION_REGISTER = new CategoryOverall( + OP_TYPE_REGISTER, + MCat.APPLICATION_REGISTER_POST, + MCat.APPLICATION_REGISTER_FINISH, + MCat.APPLICATION_REGISTER_ERROR); + CategoryOverall APPLICATION_SUBSCRIBE = new CategoryOverall( + OP_TYPE_SUBSCRIBE, + MCat.APPLICATION_SUBSCRIBE_POST, + MCat.APPLICATION_SUBSCRIBE_FINISH, + MCat.APPLICATION_SUBSCRIBE_ERROR); + CategoryOverall APPLICATION_NOTIFY = + new CategoryOverall(OP_TYPE_NOTIFY, MCat.APPLICATION_NOTIFY_POST, MCat.APPLICATION_NOTIFY_FINISH, null); + CategoryOverall SERVICE_DIRECTORY = + new CategoryOverall(OP_TYPE_DIRECTORY, MCat.APPLICATION_DIRECTORY_POST, null, null); + CategoryOverall SERVICE_REGISTER = new CategoryOverall( + OP_TYPE_REGISTER_SERVICE, + MCat.SERVICE_REGISTER_POST, + MCat.SERVICE_REGISTER_FINISH, + MCat.SERVICE_REGISTER_ERROR); + CategoryOverall SERVICE_SUBSCRIBE = new CategoryOverall( + OP_TYPE_SUBSCRIBE_SERVICE, + MCat.SERVICE_SUBSCRIBE_POST, + MCat.SERVICE_SUBSCRIBE_FINISH, + MCat.SERVICE_SUBSCRIBE_ERROR); - List ALL = Arrays.asList(APPLICATION_REGISTER, APPLICATION_SUBSCRIBE, APPLICATION_NOTIFY, SERVICE_DIRECTORY, SERVICE_REGISTER, SERVICE_SUBSCRIBE); + List ALL = Arrays.asList( + APPLICATION_REGISTER, + APPLICATION_SUBSCRIBE, + APPLICATION_NOTIFY, + SERVICE_DIRECTORY, + SERVICE_REGISTER, + SERVICE_SUBSCRIBE); } - /** * {@link MetricsCat} MetricsCat collection, for better classification processing * Except for a few custom functions, most of them can build standard event listening functions through the static methods of MetricsApplicationListener */ interface MCat { // MetricsRegisterListener - MetricsCat APPLICATION_REGISTER_POST = new MetricsCat(MetricsKey.REGISTER_METRIC_REQUESTS, RegistrySpecListener::onPost); - MetricsCat APPLICATION_REGISTER_FINISH = new MetricsCat(MetricsKey.REGISTER_METRIC_REQUESTS_SUCCEED, RegistrySpecListener::onFinish); - MetricsCat APPLICATION_REGISTER_ERROR = new MetricsCat(MetricsKey.REGISTER_METRIC_REQUESTS_FAILED, RegistrySpecListener::onError); + MetricsCat APPLICATION_REGISTER_POST = + new MetricsCat(MetricsKey.REGISTER_METRIC_REQUESTS, RegistrySpecListener::onPost); + MetricsCat APPLICATION_REGISTER_FINISH = + new MetricsCat(MetricsKey.REGISTER_METRIC_REQUESTS_SUCCEED, RegistrySpecListener::onFinish); + MetricsCat APPLICATION_REGISTER_ERROR = + new MetricsCat(MetricsKey.REGISTER_METRIC_REQUESTS_FAILED, RegistrySpecListener::onError); // MetricsSubscribeListener - MetricsCat APPLICATION_SUBSCRIBE_POST = new MetricsCat(MetricsKey.SUBSCRIBE_METRIC_NUM, RegistrySpecListener::onPost); - MetricsCat APPLICATION_SUBSCRIBE_FINISH = new MetricsCat(MetricsKey.SUBSCRIBE_METRIC_NUM_SUCCEED, RegistrySpecListener::onFinish); - MetricsCat APPLICATION_SUBSCRIBE_ERROR = new MetricsCat(MetricsKey.SUBSCRIBE_METRIC_NUM_FAILED, RegistrySpecListener::onError); + MetricsCat APPLICATION_SUBSCRIBE_POST = + new MetricsCat(MetricsKey.SUBSCRIBE_METRIC_NUM, RegistrySpecListener::onPost); + MetricsCat APPLICATION_SUBSCRIBE_FINISH = + new MetricsCat(MetricsKey.SUBSCRIBE_METRIC_NUM_SUCCEED, RegistrySpecListener::onFinish); + MetricsCat APPLICATION_SUBSCRIBE_ERROR = + new MetricsCat(MetricsKey.SUBSCRIBE_METRIC_NUM_FAILED, RegistrySpecListener::onError); // MetricsNotifyListener - MetricsCat APPLICATION_NOTIFY_POST = new MetricsCat(MetricsKey.NOTIFY_METRIC_REQUESTS, MetricsApplicationListener::onPostEventBuild); - MetricsCat APPLICATION_NOTIFY_FINISH = new MetricsCat(MetricsKey.NOTIFY_METRIC_NUM_LAST, RegistrySpecListener::onFinishOfNotify); - - MetricsCat APPLICATION_DIRECTORY_POST = new MetricsCat(MetricsKey.DIRECTORY_METRIC_NUM_VALID, RegistrySpecListener::onPostOfDirectory); + MetricsCat APPLICATION_NOTIFY_POST = + new MetricsCat(MetricsKey.NOTIFY_METRIC_REQUESTS, MetricsApplicationListener::onPostEventBuild); + MetricsCat APPLICATION_NOTIFY_FINISH = + new MetricsCat(MetricsKey.NOTIFY_METRIC_NUM_LAST, RegistrySpecListener::onFinishOfNotify); + MetricsCat APPLICATION_DIRECTORY_POST = + new MetricsCat(MetricsKey.DIRECTORY_METRIC_NUM_VALID, RegistrySpecListener::onPostOfDirectory); // MetricsServiceRegisterListener - MetricsCat SERVICE_REGISTER_POST = new MetricsCat(MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS, RegistrySpecListener::onPostOfService); - MetricsCat SERVICE_REGISTER_FINISH = new MetricsCat(MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_SUCCEED, RegistrySpecListener::onFinishOfService); - MetricsCat SERVICE_REGISTER_ERROR = new MetricsCat(MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_FAILED, RegistrySpecListener::onErrorOfService); - + MetricsCat SERVICE_REGISTER_POST = + new MetricsCat(MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS, RegistrySpecListener::onPostOfService); + MetricsCat SERVICE_REGISTER_FINISH = new MetricsCat( + MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_SUCCEED, RegistrySpecListener::onFinishOfService); + MetricsCat SERVICE_REGISTER_ERROR = new MetricsCat( + MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_FAILED, RegistrySpecListener::onErrorOfService); // MetricsServiceSubscribeListener - MetricsCat SERVICE_SUBSCRIBE_POST = new MetricsCat(MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM, RegistrySpecListener::onPostOfService); - MetricsCat SERVICE_SUBSCRIBE_FINISH = new MetricsCat(MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM_SUCCEED, RegistrySpecListener::onFinishOfService); - MetricsCat SERVICE_SUBSCRIBE_ERROR = new MetricsCat(MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM_FAILED, RegistrySpecListener::onErrorOfService); - - + MetricsCat SERVICE_SUBSCRIBE_POST = + new MetricsCat(MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM, RegistrySpecListener::onPostOfService); + MetricsCat SERVICE_SUBSCRIBE_FINISH = new MetricsCat( + MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM_SUCCEED, RegistrySpecListener::onFinishOfService); + MetricsCat SERVICE_SUBSCRIBE_ERROR = + new MetricsCat(MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM_FAILED, RegistrySpecListener::onErrorOfService); } - - } diff --git a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsCollectorTest.java b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsCollectorTest.java index ff289caca3..442b9a7142 100644 --- a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsCollectorTest.java +++ b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsCollectorTest.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.registry.metrics.collector; -import com.google.common.collect.Lists; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metrics.event.MetricsDispatcher; import org.apache.dubbo.metrics.event.MetricsEventBus; @@ -31,10 +29,6 @@ import org.apache.dubbo.metrics.registry.collector.RegistryMetricsCollector; import org.apache.dubbo.metrics.registry.event.RegistryEvent; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashMap; @@ -43,6 +37,12 @@ import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; +import com.google.common.collect.Lists; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.APP_LEVEL_KEYS; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_REGISTER; @@ -50,7 +50,6 @@ import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_SUBSCRIBE_SERVICE; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.REGISTER_LEVEL_KEYS; - class RegistryMetricsCollectorTest { private ApplicationModel applicationModel; @@ -78,16 +77,16 @@ class RegistryMetricsCollectorTest { void testRegisterMetrics() { RegistryEvent registryEvent = RegistryEvent.toRegisterEvent(applicationModel, Lists.newArrayList("reg1")); - MetricsEventBus.post(registryEvent, - () -> { - List metricSamples = collector.collect(); - // push success +1 -> other default 0 = APP_LEVEL_KEYS.size() - Assertions.assertEquals(APP_LEVEL_KEYS.size() + REGISTER_LEVEL_KEYS.size(), metricSamples.size()); - Assertions.assertTrue(metricSamples.stream().allMatch(metricSample -> metricSample instanceof GaugeMetricSample)); - Assertions.assertTrue(metricSamples.stream().anyMatch(metricSample -> ((GaugeMetricSample) metricSample).applyAsDouble() == 1)); - return null; - } - ); + MetricsEventBus.post(registryEvent, () -> { + List metricSamples = collector.collect(); + // push success +1 -> other default 0 = APP_LEVEL_KEYS.size() + Assertions.assertEquals(APP_LEVEL_KEYS.size() + REGISTER_LEVEL_KEYS.size(), metricSamples.size()); + Assertions.assertTrue( + metricSamples.stream().allMatch(metricSample -> metricSample instanceof GaugeMetricSample)); + Assertions.assertTrue(metricSamples.stream() + .anyMatch(metricSample -> ((GaugeMetricSample) metricSample).applyAsDouble() == 1)); + return null; + }); // push finish rt +1 List metricSamples = collector.collect(); @@ -95,19 +94,19 @@ class RegistryMetricsCollectorTest { Assertions.assertEquals(APP_LEVEL_KEYS.size() + REGISTER_LEVEL_KEYS.size() + 5, metricSamples.size()); long c1 = registryEvent.getTimePair().calc(); - registryEvent = RegistryEvent.toRegisterEvent(applicationModel, Lists.newArrayList("reg1")); TimePair lastTimePair = registryEvent.getTimePair(); - MetricsEventBus.post(registryEvent, - () -> { - try { - Thread.sleep(50); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return null; - }, Objects::nonNull - ); + MetricsEventBus.post( + registryEvent, + () -> { + try { + Thread.sleep(50); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return null; + }, + Objects::nonNull); // push error rt +1 long c2 = lastTimePair.calc(); @@ -123,16 +122,25 @@ class RegistryMetricsCollectorTest { } @SuppressWarnings("rawtypes") - Map sampleMap = metricSamples.stream().collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); + Map sampleMap = metricSamples.stream() + .collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_REGISTER).targetKey()), lastTimePair.calc()); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_REGISTER).targetKey()), Math.min(c1, c2)); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_REGISTER).targetKey()), Math.max(c1, c2)); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_REGISTER).targetKey()), (c1 + c2) / 2); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_REGISTER).targetKey()), c1 + c2); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_REGISTER).targetKey()), + lastTimePair.calc()); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_REGISTER).targetKey()), + Math.min(c1, c2)); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_REGISTER).targetKey()), + Math.max(c1, c2)); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_REGISTER).targetKey()), + (c1 + c2) / 2); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_REGISTER).targetKey()), c1 + c2); } - @Test void testServicePushMetrics() { @@ -140,17 +148,20 @@ class RegistryMetricsCollectorTest { List rcNames = Lists.newArrayList("demo1"); RegistryEvent registryEvent = RegistryEvent.toRsEvent(applicationModel, serviceName, 2, rcNames); - MetricsEventBus.post(registryEvent, - () -> { - List metricSamples = collector.collect(); + MetricsEventBus.post(registryEvent, () -> { + List metricSamples = collector.collect(); - // push success +1 - Assertions.assertEquals(RegistryMetricsConstants.APP_LEVEL_KEYS.size() + 1, metricSamples.size()); - // Service num only 1 and contains tag of interface - Assertions.assertEquals(1, metricSamples.stream().filter(metricSample -> serviceName.equals(metricSample.getTags().get("interface"))).count()); - return null; - } - ); + // push success +1 + Assertions.assertEquals(RegistryMetricsConstants.APP_LEVEL_KEYS.size() + 1, metricSamples.size()); + // Service num only 1 and contains tag of interface + Assertions.assertEquals( + 1, + metricSamples.stream() + .filter(metricSample -> + serviceName.equals(metricSample.getTags().get("interface"))) + .count()); + return null; + }); // push finish rt +1 List metricSamples = collector.collect(); @@ -160,16 +171,17 @@ class RegistryMetricsCollectorTest { long c1 = registryEvent.getTimePair().calc(); registryEvent = RegistryEvent.toRsEvent(applicationModel, serviceName, 2, rcNames); TimePair lastTimePair = registryEvent.getTimePair(); - MetricsEventBus.post(registryEvent, - () -> { - try { - Thread.sleep(50); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return null; - }, Objects::nonNull - ); + MetricsEventBus.post( + registryEvent, + () -> { + try { + Thread.sleep(50); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return null; + }, + Objects::nonNull); // push error rt +1 long c2 = lastTimePair.calc(); @@ -185,34 +197,50 @@ class RegistryMetricsCollectorTest { } @SuppressWarnings("rawtypes") - Map sampleMap = metricSamples.stream().collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); + Map sampleMap = metricSamples.stream() + .collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_REGISTER_SERVICE).targetKey()), lastTimePair.calc()); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_REGISTER_SERVICE).targetKey()), Math.min(c1, c2)); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_REGISTER_SERVICE).targetKey()), Math.max(c1, c2)); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_REGISTER_SERVICE).targetKey()), (c1 + c2) / 2); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_REGISTER_SERVICE).targetKey()), c1 + c2); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_REGISTER_SERVICE).targetKey()), + lastTimePair.calc()); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_REGISTER_SERVICE).targetKey()), + Math.min(c1, c2)); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_REGISTER_SERVICE).targetKey()), + Math.max(c1, c2)); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_REGISTER_SERVICE).targetKey()), + (c1 + c2) / 2); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_REGISTER_SERVICE).targetKey()), + c1 + c2); } - @Test void testServiceSubscribeMetrics() { String serviceName = "demo.gameService"; - RegistryEvent subscribeEvent = RegistryEvent.toSsEvent(applicationModel, serviceName, Collections.singletonList("demo1")); - MetricsEventBus.post(subscribeEvent, - () -> { - List metricSamples = collector.collect(); - Assertions.assertTrue(metricSamples.stream().allMatch(metricSample -> metricSample instanceof GaugeMetricSample)); - Assertions.assertTrue(metricSamples.stream().anyMatch(metricSample -> ((GaugeMetricSample) metricSample).applyAsDouble() == 1)); - // App(default=7) + (service success +1) - Assertions.assertEquals(RegistryMetricsConstants.APP_LEVEL_KEYS.size() + 1, metricSamples.size()); - // Service num only 1 and contains tag of interface - Assertions.assertEquals(1, metricSamples.stream().filter(metricSample -> serviceName.equals(metricSample.getTags().get("interface"))).count()); - return null; - } - ); + RegistryEvent subscribeEvent = + RegistryEvent.toSsEvent(applicationModel, serviceName, Collections.singletonList("demo1")); + MetricsEventBus.post(subscribeEvent, () -> { + List metricSamples = collector.collect(); + Assertions.assertTrue( + metricSamples.stream().allMatch(metricSample -> metricSample instanceof GaugeMetricSample)); + Assertions.assertTrue(metricSamples.stream() + .anyMatch(metricSample -> ((GaugeMetricSample) metricSample).applyAsDouble() == 1)); + // App(default=7) + (service success +1) + Assertions.assertEquals(RegistryMetricsConstants.APP_LEVEL_KEYS.size() + 1, metricSamples.size()); + // Service num only 1 and contains tag of interface + Assertions.assertEquals( + 1, + metricSamples.stream() + .filter(metricSample -> + serviceName.equals(metricSample.getTags().get("interface"))) + .count()); + return null; + }); // push finish rt +1 List metricSamples = collector.collect(); @@ -222,16 +250,17 @@ class RegistryMetricsCollectorTest { long c1 = subscribeEvent.getTimePair().calc(); subscribeEvent = RegistryEvent.toSsEvent(applicationModel, serviceName, Collections.singletonList("demo1")); TimePair lastTimePair = subscribeEvent.getTimePair(); - MetricsEventBus.post(subscribeEvent, - () -> { - try { - Thread.sleep(50); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return null; - }, Objects::nonNull - ); + MetricsEventBus.post( + subscribeEvent, + () -> { + try { + Thread.sleep(50); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return null; + }, + Objects::nonNull); // push error rt +1 long c2 = lastTimePair.calc(); @@ -247,36 +276,43 @@ class RegistryMetricsCollectorTest { } @SuppressWarnings("rawtypes") - Map sampleMap = metricSamples.stream().collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); + Map sampleMap = metricSamples.stream() + .collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_SUBSCRIBE_SERVICE).targetKey()), lastTimePair.calc()); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_SUBSCRIBE_SERVICE).targetKey()), Math.min(c1, c2)); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_SUBSCRIBE_SERVICE).targetKey()), Math.max(c1, c2)); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_SUBSCRIBE_SERVICE).targetKey()), (c1 + c2) / 2); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_SUBSCRIBE_SERVICE).targetKey()), c1 + c2); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_SUBSCRIBE_SERVICE).targetKey()), + lastTimePair.calc()); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_SUBSCRIBE_SERVICE).targetKey()), + Math.min(c1, c2)); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_SUBSCRIBE_SERVICE).targetKey()), + Math.max(c1, c2)); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_SUBSCRIBE_SERVICE).targetKey()), + (c1 + c2) / 2); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_SUBSCRIBE_SERVICE).targetKey()), + c1 + c2); } - @Test public void testNotify() { Map lastNumMap = new HashMap<>(); - MetricsEventBus.post(RegistryEvent.toNotifyEvent(applicationModel), - () -> { - try { - Thread.sleep(50L); - } catch (InterruptedException e) { - e.printStackTrace(); - } - // 1 different services - lastNumMap.put("demo.service1", 3); - lastNumMap.put("demo.service2", 4); - lastNumMap.put("demo.service3", 5); - return lastNumMap; + MetricsEventBus.post(RegistryEvent.toNotifyEvent(applicationModel), () -> { + try { + Thread.sleep(50L); + } catch (InterruptedException e) { + e.printStackTrace(); } - ); + // 1 different services + lastNumMap.put("demo.service1", 3); + lastNumMap.put("demo.service2", 4); + lastNumMap.put("demo.service3", 5); + return lastNumMap; + }); List metricSamples = collector.collect(); // App(7) + num(service*3) + rt(5) = 9 Assertions.assertEquals((RegistryMetricsConstants.APP_LEVEL_KEYS.size() + 3 + 5), metricSamples.size()); - } } diff --git a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsSampleTest.java b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsSampleTest.java index bd59ab5dae..1138b85c8b 100644 --- a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsSampleTest.java +++ b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsSampleTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.registry.metrics.collector; import org.apache.dubbo.config.ApplicationConfig; @@ -26,15 +25,15 @@ import org.apache.dubbo.metrics.registry.collector.RegistryMetricsCollector; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_REGISTER; @@ -57,8 +56,7 @@ class RegistryMetricsSampleTest { } @Test - void testRegisterMetrics() { - } + void testRegisterMetrics() {} @Test void testRTMetrics() { @@ -75,13 +73,19 @@ class RegistryMetricsSampleTest { } @SuppressWarnings("rawtypes") - Map sampleMap = samples.stream().collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); + Map sampleMap = samples.stream() + .collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong())); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_REGISTER).targetKey()), 0L); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_REGISTER).targetKey()), 0L); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_REGISTER).targetKey()), 10L); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_REGISTER).targetKey()), 5L); - Assertions.assertEquals(sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_REGISTER).targetKey()), 10L); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_REGISTER).targetKey()), 0L); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_REGISTER).targetKey()), 0L); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_REGISTER).targetKey()), 10L); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_REGISTER).targetKey()), 5L); + Assertions.assertEquals( + sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_REGISTER).targetKey()), 10L); } @Test @@ -90,5 +94,4 @@ class RegistryMetricsSampleTest { collector.setCollectEnabled(true); collector.increment(MetricsKey.REGISTER_METRIC_REQUESTS); } - } diff --git a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java index 5610bef232..db06191028 100644 --- a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java +++ b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsTest.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.registry.metrics.collector; -import com.google.common.collect.Lists; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.context.ConfigManager; @@ -29,9 +27,6 @@ import org.apache.dubbo.metrics.registry.collector.RegistryMetricsCollector; import org.apache.dubbo.metrics.registry.event.RegistryEvent; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; import java.util.List; import java.util.NoSuchElementException; @@ -42,10 +37,14 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import com.google.common.collect.Lists; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; - public class RegistryMetricsTest { ApplicationModel applicationModel; @@ -74,7 +73,8 @@ public class RegistryMetricsTest { } List samples = collector.collect(); - GaugeMetricSample succeedRequests = getSample(MetricsKey.REGISTER_METRIC_REQUESTS_SUCCEED.getName(), samples); + GaugeMetricSample succeedRequests = + getSample(MetricsKey.REGISTER_METRIC_REQUESTS_SUCCEED.getName(), samples); GaugeMetricSample failedRequests = getSample(MetricsKey.REGISTER_METRIC_REQUESTS_FAILED.getName(), samples); GaugeMetricSample totalRequests = getSample(MetricsKey.REGISTER_METRIC_REQUESTS.getName(), samples); @@ -221,14 +221,15 @@ public class RegistryMetricsTest { } List samples = collector.collect(); - GaugeMetricSample succeedRequests = getSample(MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_SUCCEED.getName(), samples); - GaugeMetricSample failedRequests = getSample(MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_FAILED.getName(), samples); + GaugeMetricSample succeedRequests = + getSample(MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_SUCCEED.getName(), samples); + GaugeMetricSample failedRequests = + getSample(MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_FAILED.getName(), samples); GaugeMetricSample totalRequests = getSample(MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS.getName(), samples); Assertions.assertEquals(5L, succeedRequests.applyAsLong()); Assertions.assertEquals(5L, failedRequests.applyAsLong()); Assertions.assertEquals(10L, totalRequests.applyAsLong()); - } @Test @@ -253,9 +254,11 @@ public class RegistryMetricsTest { Assertions.assertEquals(10L, totalRequests.applyAsLong()); } - GaugeMetricSample getSample(String name, List samples) { - return (GaugeMetricSample) samples.stream().filter(metricSample -> metricSample.getName().equals(name)).findFirst().orElseThrow(NoSuchElementException::new); + return (GaugeMetricSample) samples.stream() + .filter(metricSample -> metricSample.getName().equals(name)) + .findFirst() + .orElseThrow(NoSuchElementException::new); } RegistryEvent applicationRegister() { @@ -341,7 +344,6 @@ public class RegistryMetricsTest { return new RegistryMetricsCollector(applicationModel); } - /** * make the control of thread sleep time more precise */ @@ -360,5 +362,4 @@ public class RegistryMetricsTest { } } } - } diff --git a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryStatCompositeTest.java b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryStatCompositeTest.java index 3c0d00826e..c7af23b792 100644 --- a/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryStatCompositeTest.java +++ b/dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryStatCompositeTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.metrics.registry.metrics.collector; import org.apache.dubbo.common.constants.RegistryConstants; @@ -34,16 +33,16 @@ import org.apache.dubbo.metrics.registry.collector.RegistryStatComposite; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicLong; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_RT_AVG; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_RT_MAX; import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_RT_MIN; @@ -54,7 +53,6 @@ import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_SUBSCRIBE; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_SUBSCRIBE_SERVICE; - public class RegistryStatCompositeTest { private ApplicationModel applicationModel; private String applicationName; @@ -85,7 +83,12 @@ public class RegistryStatCompositeTest { @Override protected void init(RtStatComposite rtStatComposite) { super.init(rtStatComposite); - rtStatComposite.init(OP_TYPE_REGISTER, OP_TYPE_SUBSCRIBE, OP_TYPE_NOTIFY, OP_TYPE_REGISTER_SERVICE, OP_TYPE_SUBSCRIBE_SERVICE); + rtStatComposite.init( + OP_TYPE_REGISTER, + OP_TYPE_SUBSCRIBE, + OP_TYPE_NOTIFY, + OP_TYPE_REGISTER_SERVICE, + OP_TYPE_SUBSCRIBE_SERVICE); } }; regStatComposite = new RegistryStatComposite(applicationModel); @@ -93,13 +96,21 @@ public class RegistryStatCompositeTest { @Test void testInit() { - Assertions.assertEquals(statComposite.getApplicationStatComposite().getApplicationNumStats().size(), RegistryMetricsConstants.APP_LEVEL_KEYS.size()); - //(rt)5 * (applicationRegister,subscribe,notify,applicationRegister.service,subscribe.service) - Assertions.assertEquals(5 * 5, statComposite.getRtStatComposite().getRtStats().size()); - statComposite.getApplicationStatComposite().getApplicationNumStats().values().forEach((v -> - Assertions.assertEquals(v.get(), new AtomicLong(0L).get()))); - statComposite.getRtStatComposite().getRtStats().forEach(rtContainer -> - { + Assertions.assertEquals( + statComposite + .getApplicationStatComposite() + .getApplicationNumStats() + .size(), + RegistryMetricsConstants.APP_LEVEL_KEYS.size()); + // (rt)5 * (applicationRegister,subscribe,notify,applicationRegister.service,subscribe.service) + Assertions.assertEquals( + 5 * 5, statComposite.getRtStatComposite().getRtStats().size()); + statComposite + .getApplicationStatComposite() + .getApplicationNumStats() + .values() + .forEach((v -> Assertions.assertEquals(v.get(), new AtomicLong(0L).get()))); + statComposite.getRtStatComposite().getRtStats().forEach(rtContainer -> { for (Map.Entry entry : rtContainer.entrySet()) { Assertions.assertEquals(0L, rtContainer.getValueSupplier().apply(entry.getKey())); } @@ -110,16 +121,28 @@ public class RegistryStatCompositeTest { void testIncrement() { regStatComposite.incrMetricsNum(REGISTER_METRIC_REQUESTS, "beijing"); ApplicationMetric applicationMetric = new ApplicationMetric(applicationModel); - applicationMetric.setExtraInfo(Collections.singletonMap(RegistryConstants.REGISTRY_CLUSTER_KEY.toLowerCase(), "beijing")); - Assertions.assertEquals(1L, regStatComposite.getAppStats().get(REGISTER_METRIC_REQUESTS).get(applicationMetric).get()); + applicationMetric.setExtraInfo( + Collections.singletonMap(RegistryConstants.REGISTRY_CLUSTER_KEY.toLowerCase(), "beijing")); + Assertions.assertEquals( + 1L, + regStatComposite + .getAppStats() + .get(REGISTER_METRIC_REQUESTS) + .get(applicationMetric) + .get()); } @Test void testCalcRt() { statComposite.calcApplicationRt(OP_TYPE_NOTIFY.getType(), 10L); - Assertions.assertTrue(statComposite.getRtStatComposite().getRtStats().stream().anyMatch(longContainer -> longContainer.specifyType(OP_TYPE_NOTIFY.getType()))); - Optional> subContainer = statComposite.getRtStatComposite().getRtStats().stream().filter(longContainer -> longContainer.specifyType(OP_TYPE_NOTIFY.getType())).findFirst(); - subContainer.ifPresent(v -> Assertions.assertEquals(10L, v.get(new ApplicationMetric(applicationModel)).longValue())); + Assertions.assertTrue(statComposite.getRtStatComposite().getRtStats().stream() + .anyMatch(longContainer -> longContainer.specifyType(OP_TYPE_NOTIFY.getType()))); + Optional> subContainer = + statComposite.getRtStatComposite().getRtStats().stream() + .filter(longContainer -> longContainer.specifyType(OP_TYPE_NOTIFY.getType())) + .findFirst(); + subContainer.ifPresent(v -> Assertions.assertEquals( + 10L, v.get(new ApplicationMetric(applicationModel)).longValue())); } @Test @@ -136,17 +159,20 @@ public class RegistryStatCompositeTest { List exportedRtMetrics = statComposite.export(MetricsCategory.RT); GaugeMetricSample minSample = (GaugeMetricSample) exportedRtMetrics.stream() - .filter(sample -> sample.getTags().containsValue(applicationName)) - .filter(sample -> sample.getName().equals(METRIC_RT_MIN.getNameByType("register.service"))) - .findFirst().orElse(null); + .filter(sample -> sample.getTags().containsValue(applicationName)) + .filter(sample -> sample.getName().equals(METRIC_RT_MIN.getNameByType("register.service"))) + .findFirst() + .orElse(null); GaugeMetricSample maxSample = (GaugeMetricSample) exportedRtMetrics.stream() - .filter(sample -> sample.getTags().containsValue(applicationName)) - .filter(sample -> sample.getName().equals(METRIC_RT_MAX.getNameByType("register.service"))) - .findFirst().orElse(null); + .filter(sample -> sample.getTags().containsValue(applicationName)) + .filter(sample -> sample.getName().equals(METRIC_RT_MAX.getNameByType("register.service"))) + .findFirst() + .orElse(null); GaugeMetricSample avgSample = (GaugeMetricSample) exportedRtMetrics.stream() - .filter(sample -> sample.getTags().containsValue(applicationName)) - .filter(sample -> sample.getName().equals(METRIC_RT_AVG.getNameByType("register.service"))) - .findFirst().orElse(null); + .filter(sample -> sample.getTags().containsValue(applicationName)) + .filter(sample -> sample.getName().equals(METRIC_RT_AVG.getNameByType("register.service"))) + .findFirst() + .orElse(null); Assertions.assertNotNull(minSample); Assertions.assertNotNull(maxSample); @@ -156,6 +182,4 @@ public class RegistryStatCompositeTest { Assertions.assertEquals(responseTime2, maxSample.applyAsLong()); Assertions.assertEquals((responseTime1 + responseTime2) / 2, avgSample.applyAsLong()); } - - } diff --git a/dubbo-metrics/dubbo-tracing/pom.xml b/dubbo-metrics/dubbo-tracing/pom.xml index 760e3e7bfd..83e8f51b07 100644 --- a/dubbo-metrics/dubbo-tracing/pom.xml +++ b/dubbo-metrics/dubbo-tracing/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - org.apache.dubbo - dubbo-metrics - ${revision} - ../pom.xml - + + 4.0.0 + + org.apache.dubbo + dubbo-metrics + ${revision} + ../pom.xml + - dubbo-tracing - jar - ${project.artifactId} - The tracing module of dubbo project + dubbo-tracing + jar + ${project.artifactId} + The tracing module of dubbo project - - false - + + false + - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - org.apache.dubbo - dubbo-cluster - ${project.parent.version} - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - + + + org.apache.dubbo + dubbo-common + ${project.parent.version} + + + org.apache.dubbo + dubbo-cluster + ${project.parent.version} + + + org.apache.dubbo + dubbo-rpc-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-metrics-default + ${project.parent.version} + - - - io.micrometer - micrometer-core - - - io.micrometer - micrometer-tracing - - - io.micrometer - micrometer-test - test - - - io.micrometer - micrometer-tracing-integration-test - test - + + + io.micrometer + micrometer-core + + + io.micrometer + micrometer-tracing + + + io.micrometer + micrometer-test + test + + + io.micrometer + micrometer-tracing-integration-test + test + - - - io.micrometer - micrometer-tracing-bridge-otel - true - - - io.micrometer - micrometer-tracing-bridge-brave - true - + + + io.micrometer + micrometer-tracing-bridge-otel + true + + + io.micrometer + micrometer-tracing-bridge-brave + true + - - - io.opentelemetry - opentelemetry-exporter-zipkin - true - - - io.opentelemetry - opentelemetry-exporter-otlp - true - - - io.zipkin.reporter2 - zipkin-reporter-brave - true - + + + io.opentelemetry + opentelemetry-exporter-zipkin + true + + + io.opentelemetry + opentelemetry-exporter-otlp + true + + + io.zipkin.reporter2 + zipkin-reporter-brave + true + - - - io.zipkin.reporter2 - zipkin-sender-urlconnection - true - - + + + io.zipkin.reporter2 + zipkin-sender-urlconnection + true + + diff --git a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/AbstractDefaultDubboObservationConvention.java b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/AbstractDefaultDubboObservationConvention.java index a688a4c826..938274e2d2 100644 --- a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/AbstractDefaultDubboObservationConvention.java +++ b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/AbstractDefaultDubboObservationConvention.java @@ -16,15 +16,15 @@ */ package org.apache.dubbo.tracing; -import io.micrometer.common.KeyValues; -import io.micrometer.common.docs.KeyName; -import io.micrometer.common.lang.Nullable; - import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.support.RpcUtils; +import io.micrometer.common.KeyValues; +import io.micrometer.common.docs.KeyName; +import io.micrometer.common.lang.Nullable; + import static org.apache.dubbo.tracing.DubboObservationDocumentation.LowCardinalityKeyNames.RPC_METHOD; import static org.apache.dubbo.tracing.DubboObservationDocumentation.LowCardinalityKeyNames.RPC_SERVICE; import static org.apache.dubbo.tracing.DubboObservationDocumentation.LowCardinalityKeyNames.RPC_SYSTEM; @@ -32,7 +32,9 @@ import static org.apache.dubbo.tracing.DubboObservationDocumentation.LowCardinal class AbstractDefaultDubboObservationConvention { KeyValues getLowCardinalityKeyValues(Invocation invocation) { KeyValues keyValues = KeyValues.of(RPC_SYSTEM.withValue("apache_dubbo")); - String serviceName = StringUtils.hasText(invocation.getServiceName()) ? invocation.getServiceName() : readServiceName(invocation.getTargetServiceUniqueName()); + String serviceName = StringUtils.hasText(invocation.getServiceName()) + ? invocation.getServiceName() + : readServiceName(invocation.getTargetServiceUniqueName()); keyValues = appendNonNull(keyValues, RPC_SERVICE, serviceName); return appendNonNull(keyValues, RPC_METHOD, RpcUtils.getMethodName(invocation)); } @@ -45,14 +47,17 @@ class AbstractDefaultDubboObservationConvention { } String getContextualName(Invocation invocation) { - String serviceName = StringUtils.hasText(invocation.getServiceName()) ? invocation.getServiceName() : readServiceName(invocation.getTargetServiceUniqueName()); + String serviceName = StringUtils.hasText(invocation.getServiceName()) + ? invocation.getServiceName() + : readServiceName(invocation.getTargetServiceUniqueName()); String methodName = RpcUtils.getMethodName(invocation); String method = StringUtils.hasText(methodName) ? methodName : ""; return serviceName + CommonConstants.PATH_SEPARATOR + method; } private String readServiceName(String targetServiceUniqueName) { - String[] splitByHyphen = targetServiceUniqueName.split(CommonConstants.PATH_SEPARATOR); // foo-provider/a.b.c:1.0.0 or a.b.c:1.0.0 + String[] splitByHyphen = targetServiceUniqueName.split( + CommonConstants.PATH_SEPARATOR); // foo-provider/a.b.c:1.0.0 or a.b.c:1.0.0 String withVersion = splitByHyphen.length == 1 ? targetServiceUniqueName : splitByHyphen[1]; String[] splitByVersion = withVersion.split(CommonConstants.GROUP_CHAR_SEPARATOR); // a.b.c:1.0.0 if (splitByVersion.length == 1) { diff --git a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DefaultDubboClientObservationConvention.java b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DefaultDubboClientObservationConvention.java index 481861d1f9..003ba06228 100644 --- a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DefaultDubboClientObservationConvention.java +++ b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DefaultDubboClientObservationConvention.java @@ -22,17 +22,18 @@ import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcContextAttachment; import org.apache.dubbo.tracing.context.DubboClientContext; -import io.micrometer.common.KeyValues; - import java.util.List; +import io.micrometer.common.KeyValues; + import static org.apache.dubbo.tracing.DubboObservationDocumentation.LowCardinalityKeyNames.NET_PEER_NAME; import static org.apache.dubbo.tracing.DubboObservationDocumentation.LowCardinalityKeyNames.NET_PEER_PORT; /** * Default implementation of the {@link DubboClientObservationConvention}. */ -public class DefaultDubboClientObservationConvention extends AbstractDefaultDubboObservationConvention implements DubboClientObservationConvention { +public class DefaultDubboClientObservationConvention extends AbstractDefaultDubboObservationConvention + implements DubboClientObservationConvention { /** * Singleton instance of {@link DefaultDubboClientObservationConvention}. */ @@ -77,7 +78,9 @@ public class DefaultDubboClientObservationConvention extends AbstractDefaultDubb if (remotePort != null) { return remotePort; } - return rpcContextAttachment.getRemotePort() != 0 ? rpcContextAttachment.getRemotePort() : rpcContextAttachment.getLocalPort(); + return rpcContextAttachment.getRemotePort() != 0 + ? rpcContextAttachment.getRemotePort() + : rpcContextAttachment.getLocalPort(); } private KeyValues withRemoteHostPort(KeyValues keyValues, String remoteHostName, int remotePort) { diff --git a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DefaultDubboServerObservationConvention.java b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DefaultDubboServerObservationConvention.java index c78be59806..084e27aa32 100644 --- a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DefaultDubboServerObservationConvention.java +++ b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DefaultDubboServerObservationConvention.java @@ -23,7 +23,8 @@ import io.micrometer.common.KeyValues; /** * Default implementation of the {@link DubboServerObservationConvention}. */ -public class DefaultDubboServerObservationConvention extends AbstractDefaultDubboObservationConvention implements DubboServerObservationConvention { +public class DefaultDubboServerObservationConvention extends AbstractDefaultDubboObservationConvention + implements DubboServerObservationConvention { /** * Singleton instance of {@link DefaultDubboServerObservationConvention}. diff --git a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DubboObservationDocumentation.java b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DubboObservationDocumentation.java index cd0dfe3d61..38f430bd5b 100644 --- a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DubboObservationDocumentation.java +++ b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DubboObservationDocumentation.java @@ -40,7 +40,6 @@ public enum DubboObservationDocumentation implements ObservationDocumentation { public KeyName[] getLowCardinalityKeyNames() { return LowCardinalityKeyNames.values(); } - }, /** @@ -56,7 +55,6 @@ public enum DubboObservationDocumentation implements ObservationDocumentation { public KeyName[] getLowCardinalityKeyNames() { return LowCardinalityKeyNames.values(); } - }; @NonNullApi @@ -117,5 +115,4 @@ public enum DubboObservationDocumentation implements ObservationDocumentation { } } } - } diff --git a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DubboObservationRegistry.java b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DubboObservationRegistry.java index a8497d998b..5ace0906b0 100644 --- a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DubboObservationRegistry.java +++ b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DubboObservationRegistry.java @@ -32,7 +32,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_NOT_F public class DubboObservationRegistry { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboObservationRegistry.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(DubboObservationRegistry.class); private final ApplicationModel applicationModel; @@ -45,7 +46,8 @@ public class DubboObservationRegistry { public void initObservationRegistry() { // If get ObservationRegistry.class from external(eg Spring.), use external. - io.micrometer.observation.ObservationRegistry externalObservationRegistry = applicationModel.getBeanFactory().getBean(io.micrometer.observation.ObservationRegistry.class); + io.micrometer.observation.ObservationRegistry externalObservationRegistry = + applicationModel.getBeanFactory().getBean(io.micrometer.observation.ObservationRegistry.class); if (externalObservationRegistry != null) { if (logger.isDebugEnabled()) { logger.debug("ObservationRegistry.class from external is existed."); @@ -59,7 +61,11 @@ public class DubboObservationRegistry { TracerProvider tracerProvider = TracerProviderFactory.getProvider(applicationModel, tracingConfig); if (tracerProvider == null) { - logger.warn(COMMON_NOT_FOUND_TRACER_DEPENDENCY, "", "", "Can not found OpenTelemetry/Brave tracer dependencies, skip init ObservationRegistry."); + logger.warn( + COMMON_NOT_FOUND_TRACER_DEPENDENCY, + "", + "", + "Can not found OpenTelemetry/Brave tracer dependencies, skip init ObservationRegistry."); return; } // The real tracer will come from tracer implementation (OTel / Brave) @@ -67,20 +73,28 @@ public class DubboObservationRegistry { // The real propagator will come from tracer implementation (OTel / Brave) PropagatorProvider propagatorProvider = PropagatorProviderFactory.getPropagatorProvider(); - io.micrometer.tracing.propagation.Propagator propagator = propagatorProvider != null ? propagatorProvider.getPropagator() : io.micrometer.tracing.propagation.Propagator.NOOP; + io.micrometer.tracing.propagation.Propagator propagator = propagatorProvider != null + ? propagatorProvider.getPropagator() + : io.micrometer.tracing.propagation.Propagator.NOOP; io.micrometer.observation.ObservationRegistry registry = io.micrometer.observation.ObservationRegistry.create(); registry.observationConfig() // set up a first matching handler that creates spans - it comes from Micrometer Tracing. // set up spans for sending and receiving data over the wire and a default one. - .observationHandler(new io.micrometer.observation.ObservationHandler.FirstMatchingCompositeObservationHandler( - new io.micrometer.tracing.handler.PropagatingSenderTracingObservationHandler<>(tracer, propagator), - new io.micrometer.tracing.handler.PropagatingReceiverTracingObservationHandler<>(tracer, propagator), - new io.micrometer.tracing.handler.DefaultTracingObservationHandler(tracer))); + .observationHandler( + new io.micrometer.observation.ObservationHandler.FirstMatchingCompositeObservationHandler( + new io.micrometer.tracing.handler.PropagatingSenderTracingObservationHandler<>( + tracer, propagator), + new io.micrometer.tracing.handler.PropagatingReceiverTracingObservationHandler<>( + tracer, propagator), + new io.micrometer.tracing.handler.DefaultTracingObservationHandler(tracer))); if (MetricsSupportUtil.isSupportMetrics()) { - io.micrometer.core.instrument.MeterRegistry meterRegistry = MetricsGlobalRegistry.getCompositeRegistry(applicationModel); - registry.observationConfig().observationHandler(new io.micrometer.core.instrument.observation.DefaultMeterObservationHandler(meterRegistry)); + io.micrometer.core.instrument.MeterRegistry meterRegistry = + MetricsGlobalRegistry.getCompositeRegistry(applicationModel); + registry.observationConfig() + .observationHandler(new io.micrometer.core.instrument.observation.DefaultMeterObservationHandler( + meterRegistry)); } applicationModel.getBeanFactory().registerBean(registry); diff --git a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/context/DubboClientContext.java b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/context/DubboClientContext.java index f1998bc91a..3491585f40 100644 --- a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/context/DubboClientContext.java +++ b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/context/DubboClientContext.java @@ -16,11 +16,12 @@ */ package org.apache.dubbo.tracing.context; +import org.apache.dubbo.rpc.Invocation; +import org.apache.dubbo.rpc.Invoker; + import java.util.Objects; import io.micrometer.observation.transport.SenderContext; -import org.apache.dubbo.rpc.Invocation; -import org.apache.dubbo.rpc.Invoker; /** * Provider context for RPC. diff --git a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/context/DubboServerContext.java b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/context/DubboServerContext.java index 3e5bd13fae..85de37203c 100644 --- a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/context/DubboServerContext.java +++ b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/context/DubboServerContext.java @@ -16,10 +16,11 @@ */ package org.apache.dubbo.tracing.context; -import io.micrometer.observation.transport.ReceiverContext; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; +import io.micrometer.observation.transport.ReceiverContext; + /** * Consumer context for RPC. */ diff --git a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/exporter/otlp/OTlpSpanExporter.java b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/exporter/otlp/OTlpSpanExporter.java index 2f2a4acd9f..806043da07 100644 --- a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/exporter/otlp/OTlpSpanExporter.java +++ b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/exporter/otlp/OTlpSpanExporter.java @@ -19,24 +19,27 @@ package org.apache.dubbo.tracing.exporter.otlp; import org.apache.dubbo.config.nested.ExporterConfig; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.Map; + import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter; import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter; import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder; import io.opentelemetry.sdk.trace.export.SpanExporter; -import java.util.Map; - /** * OTlp span exporter for OTel. */ public class OTlpSpanExporter { - public static SpanExporter getSpanExporter(ApplicationModel applicationModel, ExporterConfig.OtlpConfig otlpConfig) { - OtlpGrpcSpanExporter externalOTlpGrpcSpanExporter = applicationModel.getBeanFactory().getBean(OtlpGrpcSpanExporter.class); + public static SpanExporter getSpanExporter( + ApplicationModel applicationModel, ExporterConfig.OtlpConfig otlpConfig) { + OtlpGrpcSpanExporter externalOTlpGrpcSpanExporter = + applicationModel.getBeanFactory().getBean(OtlpGrpcSpanExporter.class); if (externalOTlpGrpcSpanExporter != null) { return externalOTlpGrpcSpanExporter; } - OtlpHttpSpanExporter externalOtlpHttpSpanExporter = applicationModel.getBeanFactory().getBean(OtlpHttpSpanExporter.class); + OtlpHttpSpanExporter externalOtlpHttpSpanExporter = + applicationModel.getBeanFactory().getBean(OtlpHttpSpanExporter.class); if (externalOtlpHttpSpanExporter != null) { return externalOtlpHttpSpanExporter; } diff --git a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanExporter.java b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanExporter.java index e8a7a9f3d1..c2b3d1bb4f 100644 --- a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanExporter.java +++ b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanExporter.java @@ -28,7 +28,8 @@ import zipkin2.codec.SpanBytesEncoder; */ public class ZipkinSpanExporter { - public static io.opentelemetry.sdk.trace.export.SpanExporter getSpanExporter(ApplicationModel applicationModel, ExporterConfig.ZipkinConfig zipkinConfig) { + public static io.opentelemetry.sdk.trace.export.SpanExporter getSpanExporter( + ApplicationModel applicationModel, ExporterConfig.ZipkinConfig zipkinConfig) { return io.opentelemetry.exporter.zipkin.ZipkinSpanExporter.builder() .setEncoder(getSpanBytesEncoder(applicationModel)) .setEndpoint(zipkinConfig.getEndpoint()) diff --git a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanHandler.java b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanHandler.java index f56173a8ad..2e870e422b 100644 --- a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanHandler.java +++ b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanHandler.java @@ -31,7 +31,8 @@ import zipkin2.reporter.urlconnection.URLConnectionSender; */ public class ZipkinSpanHandler { - public static SpanHandler getSpanHandler(ApplicationModel applicationModel, ExporterConfig.ZipkinConfig zipkinConfig) { + public static SpanHandler getSpanHandler( + ApplicationModel applicationModel, ExporterConfig.ZipkinConfig zipkinConfig) { URLConnectionSender sender = applicationModel.getBeanFactory().getBean(URLConnectionSender.class); if (sender == null) { URLConnectionSender.Builder builder = URLConnectionSender.newBuilder(); diff --git a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/filter/ObservationReceiverFilter.java b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/filter/ObservationReceiverFilter.java index 25b7008c67..75d70d26f7 100644 --- a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/filter/ObservationReceiverFilter.java +++ b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/filter/ObservationReceiverFilter.java @@ -38,7 +38,10 @@ import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; /** * A {@link Filter} that creates an {@link Observation} around the incoming message. */ -@Activate(group = PROVIDER, order = Integer.MIN_VALUE + 50, onClass = "io.micrometer.observation.NoopObservationRegistry") +@Activate( + group = PROVIDER, + order = Integer.MIN_VALUE + 50, + onClass = "io.micrometer.observation.NoopObservationRegistry") public class ObservationReceiverFilter implements Filter, BaseFilter.Listener, ScopeModelAware { private ObservationRegistry observationRegistry; @@ -59,7 +62,8 @@ public class ObservationReceiverFilter implements Filter, BaseFilter.Listener, S final Observation observation = DubboObservationDocumentation.SERVER.observation( this.serverObservationConvention, DefaultDubboServerObservationConvention.getInstance(), - () -> receiverContext, observationRegistry); + () -> receiverContext, + observationRegistry); invocation.put(Observation.class, observation.start()); return observation.scoped(() -> invoker.invoke(invocation)); } diff --git a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/filter/ObservationSenderFilter.java b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/filter/ObservationSenderFilter.java index bce47b7b9a..3d0cd0ab20 100644 --- a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/filter/ObservationSenderFilter.java +++ b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/filter/ObservationSenderFilter.java @@ -39,7 +39,10 @@ import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; /** * A {@link Filter} that creates an {@link Observation} around the outgoing message. */ -@Activate(group = CONSUMER, order = Integer.MIN_VALUE + 50, onClass = "io.micrometer.observation.NoopObservationRegistry") +@Activate( + group = CONSUMER, + order = Integer.MIN_VALUE + 50, + onClass = "io.micrometer.observation.NoopObservationRegistry") public class ObservationSenderFilter implements ClusterFilter, BaseFilter.Listener, ScopeModelAware { private ObservationRegistry observationRegistry; @@ -60,7 +63,8 @@ public class ObservationSenderFilter implements ClusterFilter, BaseFilter.Listen final Observation observation = DubboObservationDocumentation.CLIENT.observation( this.clientObservationConvention, DefaultDubboClientObservationConvention.getInstance(), - () -> senderContext, observationRegistry); + () -> senderContext, + observationRegistry); invocation.put(Observation.class, observation.start()); return observation.scoped(() -> invoker.invoke(invocation)); } diff --git a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/TracerProvider.java b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/TracerProvider.java index 05305ada67..219aca615d 100644 --- a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/TracerProvider.java +++ b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/TracerProvider.java @@ -26,5 +26,4 @@ public interface TracerProvider { * @return Tracer */ Tracer getTracer(); - } diff --git a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/brave/BravePropagatorProvider.java b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/brave/BravePropagatorProvider.java index 56e23d3670..70d6257d14 100644 --- a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/brave/BravePropagatorProvider.java +++ b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/brave/BravePropagatorProvider.java @@ -21,7 +21,6 @@ import org.apache.dubbo.tracing.tracer.PropagatorProvider; import io.micrometer.tracing.brave.bridge.BravePropagator; import io.micrometer.tracing.propagation.Propagator; - public class BravePropagatorProvider implements PropagatorProvider { private static Propagator propagator; diff --git a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/brave/BraveProvider.java b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/brave/BraveProvider.java index 9f178f400b..8d3cff46b7 100644 --- a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/brave/BraveProvider.java +++ b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/brave/BraveProvider.java @@ -28,6 +28,11 @@ import org.apache.dubbo.tracing.exporter.zipkin.ZipkinSpanHandler; import org.apache.dubbo.tracing.tracer.TracerProvider; import org.apache.dubbo.tracing.utils.PropagationType; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + import io.micrometer.tracing.CurrentTraceContext; import io.micrometer.tracing.Tracer; import io.micrometer.tracing.brave.bridge.BraveBaggageManager; @@ -35,18 +40,12 @@ import io.micrometer.tracing.brave.bridge.BraveCurrentTraceContext; import io.micrometer.tracing.brave.bridge.BraveTracer; import io.micrometer.tracing.brave.bridge.W3CPropagation; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Optional; - import static org.apache.dubbo.tracing.utils.ObservationConstants.DEFAULT_APPLICATION_NAME; import static org.apache.dubbo.tracing.utils.ObservationSupportUtil.isSupportBraveURLSender; - public class BraveProvider implements TracerProvider { - private final static ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(BraveProvider.class); + private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(BraveProvider.class); private static final BraveBaggageManager BRAVE_BAGGAGE_MANAGER = new BraveBaggageManager(); @@ -63,20 +62,22 @@ public class BraveProvider implements TracerProvider { // [Brave component] SpanHandler is a component that gets called when a span is finished. List spanHandlerList = getSpanHandlers(); - String applicationName = applicationModel.getApplicationConfigManager().getApplication() + String applicationName = applicationModel + .getApplicationConfigManager() + .getApplication() .map(ApplicationConfig::getName) .orElse(DEFAULT_APPLICATION_NAME); // [Brave component] CurrentTraceContext is a Brave component that allows you to // retrieve the current TraceContext. - brave.propagation.ThreadLocalCurrentTraceContext braveCurrentTraceContext = brave.propagation.ThreadLocalCurrentTraceContext.newBuilder() - .addScopeDecorator(correlationScopeDecorator()) // Brave's automatic MDC setup - .build(); + brave.propagation.ThreadLocalCurrentTraceContext braveCurrentTraceContext = + brave.propagation.ThreadLocalCurrentTraceContext.newBuilder() + .addScopeDecorator(correlationScopeDecorator()) // Brave's automatic MDC setup + .build(); // [Micrometer Tracing component] A Micrometer Tracing wrapper for Brave's CurrentTraceContext CurrentTraceContext bridgeContext = new BraveCurrentTraceContext(braveCurrentTraceContext); - // [Brave component] Tracing is the root component that allows to configure the // tracer, handlers, context propagation etc. brave.Tracing.Builder builder = brave.Tracing.newBuilder() @@ -127,8 +128,10 @@ public class BraveProvider implements TracerProvider { return Optional.of((builder) -> { List correlationFields = correlation.getFields(); for (String field : correlationFields) { - builder.add(brave.baggage.CorrelationScopeConfig.SingleCorrelationField.newBuilder(brave.baggage.BaggageField.create(field)) - .flushOnUpdate().build()); + builder.add(brave.baggage.CorrelationScopeConfig.SingleCorrelationField.newBuilder( + brave.baggage.BaggageField.create(field)) + .flushOnUpdate() + .build()); } }); } @@ -149,36 +152,47 @@ public class BraveProvider implements TracerProvider { return getPropagationFactoryWithBaggage(tracingConfig); } - private static brave.propagation.Propagation.Factory getPropagationFactoryWithoutBaggage(TracingConfig tracingConfig) { - PropagationType propagationType = PropagationType.forValue(tracingConfig.getPropagation().getType()); + private static brave.propagation.Propagation.Factory getPropagationFactoryWithoutBaggage( + TracingConfig tracingConfig) { + PropagationType propagationType = + PropagationType.forValue(tracingConfig.getPropagation().getType()); if (PropagationType.W3C == propagationType) { return new io.micrometer.tracing.brave.bridge.W3CPropagation(); } else { // Brave default propagation is B3 - return brave.propagation.B3Propagation.newFactoryBuilder().injectFormat(brave.propagation.B3Propagation.Format.SINGLE_NO_PARENT).build(); + return brave.propagation.B3Propagation.newFactoryBuilder() + .injectFormat(brave.propagation.B3Propagation.Format.SINGLE_NO_PARENT) + .build(); } } - private static brave.propagation.Propagation.Factory getPropagationFactoryWithBaggage(TracingConfig tracingConfig) { - PropagationType propagationType = PropagationType.forValue(tracingConfig.getPropagation().getType()); + private static brave.propagation.Propagation.Factory getPropagationFactoryWithBaggage( + TracingConfig tracingConfig) { + PropagationType propagationType = + PropagationType.forValue(tracingConfig.getPropagation().getType()); brave.propagation.Propagation.Factory delegate; if (PropagationType.W3C == propagationType) { delegate = new W3CPropagation(BRAVE_BAGGAGE_MANAGER, Collections.emptyList()); } else { // Brave default propagation is B3 - delegate = brave.propagation.B3Propagation.newFactoryBuilder().injectFormat(brave.propagation.B3Propagation.Format.SINGLE_NO_PARENT).build(); + delegate = brave.propagation.B3Propagation.newFactoryBuilder() + .injectFormat(brave.propagation.B3Propagation.Format.SINGLE_NO_PARENT) + .build(); } return getBaggageFactoryBuilder(delegate, tracingConfig).build(); } - private static brave.baggage.BaggagePropagation.FactoryBuilder getBaggageFactoryBuilder(brave.propagation.Propagation.Factory delegate, TracingConfig tracingConfig) { - brave.baggage.BaggagePropagation.FactoryBuilder builder = brave.baggage.BaggagePropagation.newFactoryBuilder(delegate); + private static brave.baggage.BaggagePropagation.FactoryBuilder getBaggageFactoryBuilder( + brave.propagation.Propagation.Factory delegate, TracingConfig tracingConfig) { + brave.baggage.BaggagePropagation.FactoryBuilder builder = + brave.baggage.BaggagePropagation.newFactoryBuilder(delegate); getBaggagePropagationCustomizers(tracingConfig).forEach((customizer) -> customizer.customize(builder)); return builder; } - private static List getBaggagePropagationCustomizers(TracingConfig tracingConfig) { + private static List getBaggagePropagationCustomizers( + TracingConfig tracingConfig) { List res = new ArrayList<>(); if (tracingConfig.getBaggage().getCorrelation().isEnabled()) { res.add(remoteFieldsBaggagePropagationCustomizer(tracingConfig)); @@ -186,11 +200,13 @@ public class BraveProvider implements TracerProvider { return res; } - private static brave.baggage.BaggagePropagationCustomizer remoteFieldsBaggagePropagationCustomizer(TracingConfig tracingConfig) { + private static brave.baggage.BaggagePropagationCustomizer remoteFieldsBaggagePropagationCustomizer( + TracingConfig tracingConfig) { return (builder) -> { List remoteFields = tracingConfig.getBaggage().getRemoteFields(); for (String fieldName : remoteFields) { - builder.add(brave.baggage.BaggagePropagationConfig.SingleBaggageField.remote(brave.baggage.BaggageField.create(fieldName))); + builder.add(brave.baggage.BaggagePropagationConfig.SingleBaggageField.remote( + brave.baggage.BaggageField.create(fieldName))); } }; } diff --git a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/otel/OpenTelemetryProvider.java b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/otel/OpenTelemetryProvider.java index bf00771b99..2eefadf619 100644 --- a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/otel/OpenTelemetryProvider.java +++ b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/otel/OpenTelemetryProvider.java @@ -32,6 +32,10 @@ import org.apache.dubbo.tracing.exporter.zipkin.ZipkinSpanExporter; import org.apache.dubbo.tracing.tracer.TracerProvider; import org.apache.dubbo.tracing.utils.PropagationType; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + import io.micrometer.tracing.Tracer; import io.micrometer.tracing.otel.bridge.CompositeSpanExporter; import io.micrometer.tracing.otel.bridge.EventListener; @@ -43,15 +47,12 @@ import io.micrometer.tracing.otel.bridge.Slf4JBaggageEventListener; import io.micrometer.tracing.otel.bridge.Slf4JEventListener; import io.micrometer.tracing.otel.propagation.BaggageTextMapPropagator; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - import static org.apache.dubbo.tracing.utils.ObservationConstants.DEFAULT_APPLICATION_NAME; public class OpenTelemetryProvider implements TracerProvider { - private final static ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(OpenTelemetryProvider.class); + private static final ErrorTypeAwareLogger LOGGER = + LoggerFactory.getErrorTypeAwareLogger(OpenTelemetryProvider.class); private final ApplicationModel applicationModel; private final TracingConfig tracingConfig; @@ -69,7 +70,9 @@ public class OpenTelemetryProvider implements TracerProvider { // [OTel component] SpanExporter is a component that gets called when a span is finished. List spanExporters = getSpanExporters(); - String applicationName = applicationModel.getApplicationConfigManager().getApplication() + String applicationName = applicationModel + .getApplicationConfigManager() + .getApplication() .map(ApplicationConfig::getName) .orElse(DEFAULT_APPLICATION_NAME); @@ -79,13 +82,17 @@ public class OpenTelemetryProvider implements TracerProvider { this.otelCurrentTraceContext = createCurrentTraceContext(); // [OTel component] SdkTracerProvider is an SDK implementation for TracerProvider - io.opentelemetry.sdk.trace.SdkTracerProvider sdkTracerProvider = io.opentelemetry.sdk.trace.SdkTracerProvider.builder() - .setSampler(getSampler()) - .setResource(io.opentelemetry.sdk.resources.Resource.create(io.opentelemetry.api.common.Attributes.of(io.opentelemetry.semconv.resource.attributes.ResourceAttributes.SERVICE_NAME, applicationName))) - .addSpanProcessor(io.opentelemetry.sdk.trace.export.BatchSpanProcessor - .builder(new CompositeSpanExporter(spanExporters, null, null, null)) - .build()) - .build(); + io.opentelemetry.sdk.trace.SdkTracerProvider sdkTracerProvider = + io.opentelemetry.sdk.trace.SdkTracerProvider.builder() + .setSampler(getSampler()) + .setResource(io.opentelemetry.sdk.resources.Resource.create( + io.opentelemetry.api.common.Attributes.of( + io.opentelemetry.semconv.resource.attributes.ResourceAttributes.SERVICE_NAME, + applicationName))) + .addSpanProcessor(io.opentelemetry.sdk.trace.export.BatchSpanProcessor.builder( + new CompositeSpanExporter(spanExporters, null, null, null)) + .build()) + .build(); io.opentelemetry.context.propagation.ContextPropagators otelContextPropagators = createOtelContextPropagators(); @@ -96,14 +103,18 @@ public class OpenTelemetryProvider implements TracerProvider { .build(); // [OTel component] Tracer is a component that handles the life-cycle of a span - io.opentelemetry.api.trace.Tracer otelTracer = openTelemetrySdk.getTracerProvider() - .get("org.apache.dubbo", Version.getVersion()); + io.opentelemetry.api.trace.Tracer otelTracer = + openTelemetrySdk.getTracerProvider().get("org.apache.dubbo", Version.getVersion()); OTelPropagatorProvider.createMicrometerPropagator(otelContextPropagators, otelTracer); // [Micrometer Tracing component] A Micrometer Tracing wrapper for OTel's Tracer. - return new OtelTracer(otelTracer, otelCurrentTraceContext, publisher, - new OtelBaggageManager(otelCurrentTraceContext, + return new OtelTracer( + otelTracer, + otelCurrentTraceContext, + publisher, + new OtelBaggageManager( + otelCurrentTraceContext, tracingConfig.getBaggage().getRemoteFields(), Collections.emptyList())); } @@ -131,7 +142,9 @@ public class OpenTelemetryProvider implements TracerProvider { * @return sampler */ private io.opentelemetry.sdk.trace.samplers.Sampler getSampler() { - io.opentelemetry.sdk.trace.samplers.Sampler rootSampler = io.opentelemetry.sdk.trace.samplers.Sampler.traceIdRatioBased(tracingConfig.getSampling().getProbability()); + io.opentelemetry.sdk.trace.samplers.Sampler rootSampler = + io.opentelemetry.sdk.trace.samplers.Sampler.traceIdRatioBased( + tracingConfig.getSampling().getProbability()); return io.opentelemetry.sdk.trace.samplers.Sampler.parentBased(rootSampler); } @@ -145,7 +158,8 @@ public class OpenTelemetryProvider implements TracerProvider { if (tracingConfig.getBaggage().getEnabled()) { // [Micrometer Tracing component] A Micrometer Tracing listener for setting Baggage in MDC. // Customizable with correlation fields. - Slf4JBaggageEventListener slf4JBaggageEventListener = new Slf4JBaggageEventListener(tracingConfig.getBaggage().getCorrelation().getFields()); + Slf4JBaggageEventListener slf4JBaggageEventListener = new Slf4JBaggageEventListener( + tracingConfig.getBaggage().getCorrelation().getFields()); listeners.add(slf4JBaggageEventListener); } @@ -159,11 +173,8 @@ public class OpenTelemetryProvider implements TracerProvider { private io.opentelemetry.context.propagation.ContextPropagators createOtelContextPropagators() { return io.opentelemetry.context.propagation.ContextPropagators.create( - io.opentelemetry.context.propagation.TextMapPropagator.composite( - PropagatorFactory.getPropagator(tracingConfig.getPropagation(), - tracingConfig.getBaggage(), - otelCurrentTraceContext - ))); + io.opentelemetry.context.propagation.TextMapPropagator.composite(PropagatorFactory.getPropagator( + tracingConfig.getPropagation(), tracingConfig.getBaggage(), otelCurrentTraceContext))); } static class OTelEventPublisher implements OtelTracer.EventPublisher { @@ -184,16 +195,18 @@ public class OpenTelemetryProvider implements TracerProvider { static class PropagatorFactory { - public static io.opentelemetry.context.propagation.TextMapPropagator getPropagator(PropagationConfig propagationConfig, - @Nullable BaggageConfig baggageConfig, - @Nullable OtelCurrentTraceContext currentTraceContext) { + public static io.opentelemetry.context.propagation.TextMapPropagator getPropagator( + PropagationConfig propagationConfig, + @Nullable BaggageConfig baggageConfig, + @Nullable OtelCurrentTraceContext currentTraceContext) { if (baggageConfig == null || !baggageConfig.getEnabled()) { return getPropagatorWithoutBaggage(propagationConfig); } return getPropagatorWithBaggage(propagationConfig, baggageConfig, currentTraceContext); } - private static io.opentelemetry.context.propagation.TextMapPropagator getPropagatorWithoutBaggage(PropagationConfig propagationConfig) { + private static io.opentelemetry.context.propagation.TextMapPropagator getPropagatorWithoutBaggage( + PropagationConfig propagationConfig) { String type = propagationConfig.getType(); PropagationType propagationType = PropagationType.forValue(type); @@ -205,20 +218,26 @@ public class OpenTelemetryProvider implements TracerProvider { return io.opentelemetry.context.propagation.TextMapPropagator.noop(); } - private static io.opentelemetry.context.propagation.TextMapPropagator getPropagatorWithBaggage(PropagationConfig propagationConfig, - BaggageConfig baggageConfig, - OtelCurrentTraceContext currentTraceContext) { + private static io.opentelemetry.context.propagation.TextMapPropagator getPropagatorWithBaggage( + PropagationConfig propagationConfig, + BaggageConfig baggageConfig, + OtelCurrentTraceContext currentTraceContext) { String type = propagationConfig.getType(); PropagationType propagationType = PropagationType.forValue(type); if (PropagationType.B3 == propagationType) { List remoteFields = baggageConfig.getRemoteFields(); - return io.opentelemetry.context.propagation.TextMapPropagator.composite(io.opentelemetry.extension.trace.propagation.B3Propagator.injectingSingleHeader(), - new BaggageTextMapPropagator(remoteFields, + return io.opentelemetry.context.propagation.TextMapPropagator.composite( + io.opentelemetry.extension.trace.propagation.B3Propagator.injectingSingleHeader(), + new BaggageTextMapPropagator( + remoteFields, new OtelBaggageManager(currentTraceContext, remoteFields, Collections.emptyList()))); } else if (PropagationType.W3C == propagationType) { List remoteFields = baggageConfig.getRemoteFields(); - return io.opentelemetry.context.propagation.TextMapPropagator.composite(io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator.getInstance(), - io.opentelemetry.api.baggage.propagation.W3CBaggagePropagator.getInstance(), new BaggageTextMapPropagator(remoteFields, + return io.opentelemetry.context.propagation.TextMapPropagator.composite( + io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator.getInstance(), + io.opentelemetry.api.baggage.propagation.W3CBaggagePropagator.getInstance(), + new BaggageTextMapPropagator( + remoteFields, new OtelBaggageManager(currentTraceContext, remoteFields, Collections.emptyList()))); } return io.opentelemetry.context.propagation.TextMapPropagator.noop(); diff --git a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/utils/ObservationConstants.java b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/utils/ObservationConstants.java index 819e6ac44b..fc68b1ea9d 100644 --- a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/utils/ObservationConstants.java +++ b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/utils/ObservationConstants.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.tracing.utils; public class ObservationConstants { diff --git a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/utils/PropagationType.java b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/utils/PropagationType.java index 8ed5c56135..8d2f9f3252 100644 --- a/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/utils/PropagationType.java +++ b/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/utils/PropagationType.java @@ -14,11 +14,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.tracing.utils; public enum PropagationType { - W3C("W3C"), B3("B3"); diff --git a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/DefaultDubboClientObservationConventionTest.java b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/DefaultDubboClientObservationConventionTest.java index 0f1e641c4a..163c9a0173 100644 --- a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/DefaultDubboClientObservationConventionTest.java +++ b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/DefaultDubboClientObservationConventionTest.java @@ -25,10 +25,10 @@ import io.micrometer.common.KeyValues; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; - public class DefaultDubboClientObservationConventionTest { - static DubboClientObservationConvention dubboClientObservationConvention = DefaultDubboClientObservationConvention.getInstance(); + static DubboClientObservationConvention dubboClientObservationConvention = + DefaultDubboClientObservationConvention.getInstance(); @Test void testGetName() { @@ -50,7 +50,8 @@ public class DefaultDubboClientObservationConventionTest { KeyValues keyValues = dubboClientObservationConvention.getLowCardinalityKeyValues(context); Assertions.assertEquals("testMethod", ObservationConventionUtils.getValueForKey(keyValues, "rpc.method")); - Assertions.assertEquals("targetServiceName1", ObservationConventionUtils.getValueForKey(keyValues, "rpc.service")); + Assertions.assertEquals( + "targetServiceName1", ObservationConventionUtils.getValueForKey(keyValues, "rpc.service")); Assertions.assertEquals("apache_dubbo", ObservationConventionUtils.getValueForKey(keyValues, "rpc.system")); } @@ -68,6 +69,4 @@ public class DefaultDubboClientObservationConventionTest { String contextualName = convention.getContextualName(context); Assertions.assertEquals("com.example.TestService/testMethod", contextualName); } - - } diff --git a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/DefaultDubboServerObservationConventionTest.java b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/DefaultDubboServerObservationConventionTest.java index 95a755cd98..041359cd04 100644 --- a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/DefaultDubboServerObservationConventionTest.java +++ b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/DefaultDubboServerObservationConventionTest.java @@ -29,7 +29,8 @@ import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") public class DefaultDubboServerObservationConventionTest { - static DubboServerObservationConvention dubboServerObservationConvention = DefaultDubboServerObservationConvention.getInstance(); + static DubboServerObservationConvention dubboServerObservationConvention = + DefaultDubboServerObservationConvention.getInstance(); @Test void testGetName() { @@ -51,7 +52,8 @@ public class DefaultDubboServerObservationConventionTest { KeyValues keyValues = dubboServerObservationConvention.getLowCardinalityKeyValues(context); Assertions.assertEquals("testMethod", ObservationConventionUtils.getValueForKey(keyValues, "rpc.method")); - Assertions.assertEquals("targetServiceName1", ObservationConventionUtils.getValueForKey(keyValues, "rpc.service")); + Assertions.assertEquals( + "targetServiceName1", ObservationConventionUtils.getValueForKey(keyValues, "rpc.service")); Assertions.assertEquals("apache_dubbo", ObservationConventionUtils.getValueForKey(keyValues, "rpc.system")); } diff --git a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/MockInvocation.java b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/MockInvocation.java index cd9c0335dd..0f9d1dc7a1 100644 --- a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/MockInvocation.java +++ b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/MockInvocation.java @@ -68,11 +68,11 @@ public class MockInvocation extends RpcInvocation { } public Class[] getParameterTypes() { - return new Class[]{String.class}; + return new Class[] {String.class}; } public Object[] getArguments() { - return new Object[]{"aa"}; + return new Object[] {"aa"}; } public Map getAttachments() { @@ -119,9 +119,7 @@ public class MockInvocation extends RpcInvocation { } @Override - public void setServiceModel(ServiceModel serviceModel) { - - } + public void setServiceModel(ServiceModel serviceModel) {} @Override public ServiceModel getServiceModel() { @@ -164,5 +162,4 @@ public class MockInvocation extends RpcInvocation { } return result; } - } diff --git a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/exporter/otlp/OTlpSpanExporterTest.java b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/exporter/otlp/OTlpSpanExporterTest.java index a57933ea2e..9c48fd4bed 100644 --- a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/exporter/otlp/OTlpSpanExporterTest.java +++ b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/exporter/otlp/OTlpSpanExporterTest.java @@ -19,12 +19,12 @@ package org.apache.dubbo.tracing.exporter.otlp; import org.apache.dubbo.config.nested.ExporterConfig; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.time.Duration; + import io.opentelemetry.sdk.trace.export.SpanExporter; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.time.Duration; - import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -40,4 +40,4 @@ class OTlpSpanExporterTest { SpanExporter spanExporter = OTlpSpanExporter.getSpanExporter(ApplicationModel.defaultModel(), otlpConfig); Assertions.assertNotNull(spanExporter); } -} \ No newline at end of file +} diff --git a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanExporterTest.java b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanExporterTest.java index c6bd0922e0..effc700b58 100644 --- a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanExporterTest.java +++ b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanExporterTest.java @@ -19,16 +19,15 @@ package org.apache.dubbo.tracing.exporter.zipkin; import org.apache.dubbo.config.nested.ExporterConfig; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.time.Duration; + import io.opentelemetry.sdk.trace.export.SpanExporter; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.time.Duration; - import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; - class ZipkinSpanExporterTest { @Test @@ -41,4 +40,4 @@ class ZipkinSpanExporterTest { SpanExporter spanExporter = ZipkinSpanExporter.getSpanExporter(ApplicationModel.defaultModel(), zipkinConfig); Assertions.assertNotNull(spanExporter); } -} \ No newline at end of file +} diff --git a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanHandlerTest.java b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanHandlerTest.java index b30b2a8f04..0ebbe7bfba 100644 --- a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanHandlerTest.java +++ b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanHandlerTest.java @@ -19,12 +19,12 @@ package org.apache.dubbo.tracing.exporter.zipkin; import org.apache.dubbo.config.nested.ExporterConfig; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.time.Duration; + import brave.handler.SpanHandler; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.time.Duration; - import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -39,4 +39,4 @@ class ZipkinSpanHandlerTest { SpanHandler spanHandler = ZipkinSpanHandler.getSpanHandler(ApplicationModel.defaultModel(), zipkinConfig); Assertions.assertNotNull(spanHandler); } -} \ No newline at end of file +} diff --git a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/filter/AbstractObservationFilterTest.java b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/filter/AbstractObservationFilterTest.java index 046a0f1f95..ce56ae3662 100644 --- a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/filter/AbstractObservationFilterTest.java +++ b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/filter/AbstractObservationFilterTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.tracing.filter; import org.apache.dubbo.config.ApplicationConfig; @@ -80,7 +79,6 @@ abstract class AbstractObservationFilterTest extends SampleTestRunner { private void initParam() { invocation.setTargetServiceUniqueName(GROUP + "/" + INTERFACE_NAME + ":" + VERSION); invocation.setMethodName(METHOD_NAME); - invocation.setParameterTypes(new Class[]{String.class}); + invocation.setParameterTypes(new Class[] {String.class}); } - } diff --git a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/filter/ObservationReceiverFilterTest.java b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/filter/ObservationReceiverFilterTest.java index 4cb0282430..76eac81ad9 100644 --- a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/filter/ObservationReceiverFilterTest.java +++ b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/filter/ObservationReceiverFilterTest.java @@ -14,14 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.tracing.filter; -import io.micrometer.common.KeyValues; -import io.micrometer.core.tck.MeterRegistryAssert; -import io.micrometer.tracing.Span; -import io.micrometer.tracing.Tracer; -import io.micrometer.tracing.test.simple.SpansAssert; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Filter; @@ -32,6 +26,11 @@ import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.ApplicationModel; +import io.micrometer.common.KeyValues; +import io.micrometer.core.tck.MeterRegistryAssert; +import io.micrometer.tracing.Span; +import io.micrometer.tracing.Tracer; +import io.micrometer.tracing.test.simple.SpansAssert; import org.assertj.core.api.BDDAssertions; class ObservationReceiverFilterTest extends AbstractObservationFilterTest { @@ -48,22 +47,32 @@ class ObservationReceiverFilterTest extends AbstractObservationFilterTest { senderFilter.onResponse(null, invoker, invocation); MeterRegistryAssert.then(meterRegistry) - .hasMeterWithNameAndTags("rpc.server.duration", KeyValues.of("rpc.method", "mockMethod", "rpc.service", "DemoService", "rpc.system", "apache_dubbo")); + .hasMeterWithNameAndTags( + "rpc.server.duration", + KeyValues.of( + "rpc.method", + "mockMethod", + "rpc.service", + "DemoService", + "rpc.system", + "apache_dubbo")); SpansAssert.then(buildingBlocks.getFinishedSpans()) - .hasASpanWithNameIgnoreCase("DemoService/mockMethod", spanAssert -> - spanAssert - .hasTag("rpc.method", "mockMethod") - .hasTag("rpc.service", "DemoService") - .hasTag("rpc.system", "apache_dubbo")); + .hasASpanWithNameIgnoreCase("DemoService/mockMethod", spanAssert -> spanAssert + .hasTag("rpc.method", "mockMethod") + .hasTag("rpc.service", "DemoService") + .hasTag("rpc.system", "apache_dubbo")); }; } void setupAttachments(Tracer tracer) { - RpcContext.getServerAttachment().setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=consumer")); + RpcContext.getServerAttachment() + .setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=consumer")); RpcContext.getServerAttachment().setMethodName("foo"); RpcContext.getServerAttachment().setRemoteAddress("foo.bar.com", 8080); - RpcContext.getServerAttachment().setAttachment("X-B3-TraceId", tracer.currentSpan().context().traceId()); - RpcContext.getServerAttachment().setAttachment("X-B3-SpanId", tracer.currentSpan().context().spanId()); + RpcContext.getServerAttachment() + .setAttachment("X-B3-TraceId", tracer.currentSpan().context().traceId()); + RpcContext.getServerAttachment() + .setAttachment("X-B3-SpanId", tracer.currentSpan().context().spanId()); RpcContext.getServerAttachment().setAttachment("X-B3-Sampled", "1"); } @@ -97,9 +106,7 @@ class ObservationReceiverFilterTest extends AbstractObservationFilterTest { } @Override - public void destroy() { - - } + public void destroy() {} @Override public Class getInterface() { @@ -110,11 +117,11 @@ class ObservationReceiverFilterTest extends AbstractObservationFilterTest { public Result invoke(Invocation invocation) throws RpcException { Span span = this.tracer.currentSpan(); BDDAssertions.then(span.context().traceId()) - .as("Should propagate the trace id from the attributes") - .isEqualTo(this.expectedTraceId); + .as("Should propagate the trace id from the attributes") + .isEqualTo(this.expectedTraceId); BDDAssertions.then(span.context().spanId()) - .as("A child span must be created") - .isNotEqualTo(this.parentSpanId); + .as("A child span must be created") + .isNotEqualTo(this.parentSpanId); return new AppResponse("OK"); } } diff --git a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/filter/ObservationSenderFilterTest.java b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/filter/ObservationSenderFilterTest.java index 071bc0e978..8239c4128e 100644 --- a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/filter/ObservationSenderFilterTest.java +++ b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/filter/ObservationSenderFilterTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.tracing.filter; import org.apache.dubbo.common.URL; @@ -41,20 +40,32 @@ class ObservationSenderFilterTest extends AbstractObservationFilterTest { BDDAssertions.then(invocation.getObjectAttachment("X-B3-TraceId")).isNotNull(); MeterRegistryAssert.then(meterRegistry) - .hasMeterWithNameAndTags("rpc.client.duration", KeyValues.of("net.peer.name", "foo.bar.com", "net.peer.port", "8080", "rpc.method", "mockMethod", "rpc.service", "DemoService", "rpc.system", "apache_dubbo")); + .hasMeterWithNameAndTags( + "rpc.client.duration", + KeyValues.of( + "net.peer.name", + "foo.bar.com", + "net.peer.port", + "8080", + "rpc.method", + "mockMethod", + "rpc.service", + "DemoService", + "rpc.system", + "apache_dubbo")); SpansAssert.then(buildingBlocks.getFinishedSpans()) - .hasASpanWithNameIgnoreCase("DemoService/mockMethod", spanAssert -> - spanAssert - .hasTag("net.peer.name", "foo.bar.com") - .hasTag("net.peer.port", "8080") - .hasTag("rpc.method", "mockMethod") - .hasTag("rpc.service", "DemoService") - .hasTag("rpc.system", "apache_dubbo")); + .hasASpanWithNameIgnoreCase("DemoService/mockMethod", spanAssert -> spanAssert + .hasTag("net.peer.name", "foo.bar.com") + .hasTag("net.peer.port", "8080") + .hasTag("rpc.method", "mockMethod") + .hasTag("rpc.service", "DemoService") + .hasTag("rpc.system", "apache_dubbo")); }; } void setupAttachments() { - RpcContext.getClientAttachment().setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=consumer")); + RpcContext.getClientAttachment() + .setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=consumer")); RpcContext.getClientAttachment().setRemoteAddress("foo.bar.com", 8080); } diff --git a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/PropagatorProviderFactoryTest.java b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/PropagatorProviderFactoryTest.java index 18f1a74e0e..84a61599f2 100644 --- a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/PropagatorProviderFactoryTest.java +++ b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/PropagatorProviderFactoryTest.java @@ -31,4 +31,4 @@ class PropagatorProviderFactoryTest { Assert.notNull(propagatorProvider, "PropagatorProvider should not be null"); assertEquals(OTelPropagatorProvider.class, propagatorProvider.getClass()); } -} \ No newline at end of file +} diff --git a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/brave/BravePropagatorProviderTest.java b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/brave/BravePropagatorProviderTest.java index b9c6c32489..1892381a50 100644 --- a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/brave/BravePropagatorProviderTest.java +++ b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/brave/BravePropagatorProviderTest.java @@ -35,4 +35,4 @@ class BravePropagatorProviderTest { Propagator propagator = bravePropagatorProvider.getPropagator(); Assert.notNull(propagator, "Propagator don't be null."); } -} \ No newline at end of file +} diff --git a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/brave/BraveProviderTest.java b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/brave/BraveProviderTest.java index a622a3c6a1..7bdf257d76 100644 --- a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/brave/BraveProviderTest.java +++ b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/brave/BraveProviderTest.java @@ -24,13 +24,13 @@ import org.apache.dubbo.config.nested.PropagationConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.tracing.utils.PropagationType; +import java.util.ArrayList; +import java.util.List; + import brave.propagation.Propagation; import io.micrometer.tracing.Tracer; import org.junit.jupiter.api.Test; -import java.util.ArrayList; -import java.util.List; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -63,11 +63,15 @@ class BraveProviderTest { when(baggageConfig.getEnabled()).thenReturn(Boolean.FALSE); when(propagationConfig.getType()).thenReturn(PropagationType.W3C.getValue()); - Propagation.Factory w3cPropagationFactoryWithoutBaggage = BraveProvider.PropagatorFactory.getPropagationFactory(tracingConfig); - assertEquals(io.micrometer.tracing.brave.bridge.W3CPropagation.class, w3cPropagationFactoryWithoutBaggage.getClass()); + Propagation.Factory w3cPropagationFactoryWithoutBaggage = + BraveProvider.PropagatorFactory.getPropagationFactory(tracingConfig); + assertEquals( + io.micrometer.tracing.brave.bridge.W3CPropagation.class, + w3cPropagationFactoryWithoutBaggage.getClass()); when(propagationConfig.getType()).thenReturn(PropagationType.B3.getValue()); - Propagation.Factory b3PropagationFactoryWithoutBaggage = BraveProvider.PropagatorFactory.getPropagationFactory(tracingConfig); + Propagation.Factory b3PropagationFactoryWithoutBaggage = + BraveProvider.PropagatorFactory.getPropagationFactory(tracingConfig); Assert.notNull(b3PropagationFactoryWithoutBaggage, "b3PropagationFactoryWithoutBaggage should not be null."); // with baggage @@ -80,7 +84,8 @@ class BraveProviderTest { remoteFields.add("test-hd-" + i); } when(baggageConfig.getRemoteFields()).thenReturn(remoteFields); - Propagation.Factory propagationFactoryWithBaggage = BraveProvider.PropagatorFactory.getPropagationFactory(tracingConfig); + Propagation.Factory propagationFactoryWithBaggage = + BraveProvider.PropagatorFactory.getPropagationFactory(tracingConfig); Assert.notNull(propagationFactoryWithBaggage, "propagationFactoryWithBaggage should not be null."); } -} \ No newline at end of file +} diff --git a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/otel/OTelPropagatorProviderTest.java b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/otel/OTelPropagatorProviderTest.java index 24b1e3f11d..265194c75a 100644 --- a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/otel/OTelPropagatorProviderTest.java +++ b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/otel/OTelPropagatorProviderTest.java @@ -23,7 +23,6 @@ import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.context.propagation.ContextPropagators; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; class OTelPropagatorProviderTest { @@ -37,4 +36,4 @@ class OTelPropagatorProviderTest { Propagator propagator = oTelPropagatorProvider.getPropagator(); Assert.notNull(propagator, "Propagator don't be null."); } -} \ No newline at end of file +} diff --git a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/otel/OpenTelemetryProviderTest.java b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/otel/OpenTelemetryProviderTest.java index b48c624cd8..2fda855a84 100644 --- a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/otel/OpenTelemetryProviderTest.java +++ b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/otel/OpenTelemetryProviderTest.java @@ -47,13 +47,15 @@ class OpenTelemetryProviderTest { ExporterConfig exporterConfig = new ExporterConfig(); exporterConfig.setZipkinConfig(new ExporterConfig.ZipkinConfig("")); tracingConfig.setTracingExporter(exporterConfig); - TracerProvider tracerProvider1 = TracerProviderFactory.getProvider(ApplicationModel.defaultModel(), tracingConfig); + TracerProvider tracerProvider1 = + TracerProviderFactory.getProvider(ApplicationModel.defaultModel(), tracingConfig); Assert.notNull(tracerProvider1, "TracerProvider should not be null."); Tracer tracer1 = tracerProvider1.getTracer(); assertEquals(OtelTracer.class, tracer1.getClass()); tracingConfig.setBaggage(new BaggageConfig(false)); - TracerProvider tracerProvider2 = TracerProviderFactory.getProvider(ApplicationModel.defaultModel(), tracingConfig); + TracerProvider tracerProvider2 = + TracerProviderFactory.getProvider(ApplicationModel.defaultModel(), tracingConfig); Assert.notNull(tracerProvider2, "TracerProvider should not be null."); Tracer tracer2 = tracerProvider2.getTracer(); assertEquals(OtelTracer.class, tracer2.getClass()); @@ -68,18 +70,18 @@ class OpenTelemetryProviderTest { when(baggageConfig.getEnabled()).thenReturn(Boolean.FALSE); when(propagationConfig.getType()).thenReturn(PropagationType.B3.getValue()); - TextMapPropagator b3PropagatorWithoutBaggage = OpenTelemetryProvider.PropagatorFactory.getPropagator(propagationConfig, baggageConfig, otelCurrentTraceContext); + TextMapPropagator b3PropagatorWithoutBaggage = OpenTelemetryProvider.PropagatorFactory.getPropagator( + propagationConfig, baggageConfig, otelCurrentTraceContext); assertEquals(B3Propagator.class, b3PropagatorWithoutBaggage.getClass()); when(propagationConfig.getType()).thenReturn(PropagationType.W3C.getValue()); - TextMapPropagator w3cPropagatorWithoutBaggage = OpenTelemetryProvider.PropagatorFactory.getPropagator(propagationConfig, baggageConfig, otelCurrentTraceContext); + TextMapPropagator w3cPropagatorWithoutBaggage = OpenTelemetryProvider.PropagatorFactory.getPropagator( + propagationConfig, baggageConfig, otelCurrentTraceContext); assertEquals(W3CTraceContextPropagator.class, w3cPropagatorWithoutBaggage.getClass()); - when(baggageConfig.getEnabled()).thenReturn(Boolean.TRUE); - TextMapPropagator propagatorWithBaggage = OpenTelemetryProvider.PropagatorFactory.getPropagator(propagationConfig, baggageConfig, otelCurrentTraceContext); + TextMapPropagator propagatorWithBaggage = OpenTelemetryProvider.PropagatorFactory.getPropagator( + propagationConfig, baggageConfig, otelCurrentTraceContext); Assert.notNull(propagatorWithBaggage, "PropagatorWithBaggage should not be null"); } - - -} \ No newline at end of file +} diff --git a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/utils/ObservationConventionUtils.java b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/utils/ObservationConventionUtils.java index f0b75c8c2c..6154231e38 100644 --- a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/utils/ObservationConventionUtils.java +++ b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/utils/ObservationConventionUtils.java @@ -19,24 +19,25 @@ package org.apache.dubbo.tracing.utils; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invoker; +import java.lang.reflect.Field; + import io.micrometer.common.KeyValue; import io.micrometer.common.KeyValues; import org.mockito.Mockito; -import java.lang.reflect.Field; - public class ObservationConventionUtils { - - public static Invoker getMockInvokerWithUrl(){ - URL url = URL.valueOf("dubbo://127.0.0.1:12345/com.example.TestService?anyhost=true&application=test&category=providers&dubbo=2.0.2&generic=false&interface=com.example.TestService&methods=testMethod&pid=26716&side=provider×tamp=1633863896653"); + public static Invoker getMockInvokerWithUrl() { + URL url = URL.valueOf( + "dubbo://127.0.0.1:12345/com.example.TestService?anyhost=true&application=test&category=providers&dubbo=2.0.2&generic=false&interface=com.example.TestService&methods=testMethod&pid=26716&side=provider×tamp=1633863896653"); Invoker invoker = Mockito.mock(Invoker.class); Mockito.when(invoker.getUrl()).thenReturn(url); return invoker; } - public static String getValueForKey(KeyValues keyValues, Object key) throws NoSuchFieldException, IllegalAccessException { - Field f = KeyValues.class.getDeclaredField("keyValues"); + public static String getValueForKey(KeyValues keyValues, Object key) + throws NoSuchFieldException, IllegalAccessException { + Field f = KeyValues.class.getDeclaredField("keyValues"); f.setAccessible(true); KeyValue[] kv = (KeyValue[]) f.get(keyValues); for (KeyValue keyValue : kv) { diff --git a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/utils/ObservationSupportUtilTest.java b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/utils/ObservationSupportUtilTest.java index 3903053ca8..524cb2f7fa 100644 --- a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/utils/ObservationSupportUtilTest.java +++ b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/utils/ObservationSupportUtilTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.tracing.utils; import org.apache.dubbo.common.utils.Assert; diff --git a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/utils/PropagationTypeTest.java b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/utils/PropagationTypeTest.java index 857c7a84f3..75cd0ec4c1 100644 --- a/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/utils/PropagationTypeTest.java +++ b/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/utils/PropagationTypeTest.java @@ -34,4 +34,4 @@ class PropagationTypeTest { PropagationType propagationType3 = PropagationType.forValue("B33"); assertNull(propagationType3); } -} \ No newline at end of file +} diff --git a/dubbo-metrics/pom.xml b/dubbo-metrics/pom.xml index 901a7888ec..2c2692f3f9 100644 --- a/dubbo-metrics/pom.xml +++ b/dubbo-metrics/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - dubbo-metrics-api - dubbo-metrics-event - dubbo-metrics-default - dubbo-metrics-registry - dubbo-metrics-metadata - dubbo-metrics-prometheus - dubbo-metrics-config-center - dubbo-tracing - dubbo-metrics-netty - - - org.apache.dubbo - dubbo-parent - ${revision} - ../pom.xml - - dubbo-metrics - pom - ${project.artifactId} - The metrics module of dubbo project - - false - + + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + + dubbo-metrics + pom + ${project.artifactId} + The metrics module of dubbo project + + dubbo-metrics-api + dubbo-metrics-event + dubbo-metrics-default + dubbo-metrics-registry + dubbo-metrics-metadata + dubbo-metrics-prometheus + dubbo-metrics-config-center + dubbo-tracing + dubbo-metrics-netty + + + false + - - - org.apache.dubbo - dubbo-test-check - ${project.parent.version} - test - - + + + org.apache.dubbo + dubbo-test-check + ${project.parent.version} + test + + diff --git a/dubbo-monitor/dubbo-monitor-api/pom.xml b/dubbo-monitor/dubbo-monitor-api/pom.xml index 62fa246b7c..60a8ac3c3f 100644 --- a/dubbo-monitor/dubbo-monitor-api/pom.xml +++ b/dubbo-monitor/dubbo-monitor-api/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-monitor - ${revision} - ../pom.xml - - dubbo-monitor-api - jar - ${project.artifactId} - The monitor module of dubbo project - - false - - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - + 4.0.0 + + org.apache.dubbo + dubbo-monitor + ${revision} + ../pom.xml + + dubbo-monitor-api + jar + ${project.artifactId} + The monitor module of dubbo project + + false + + + + org.apache.dubbo + dubbo-common + ${project.parent.version} + + diff --git a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MetricsService.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MetricsService.java index 6670c85299..94c7f9dc3f 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MetricsService.java +++ b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MetricsService.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.monitor; /** diff --git a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/Monitor.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/Monitor.java index d6fd2fd018..85abadd878 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/Monitor.java +++ b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/Monitor.java @@ -23,6 +23,4 @@ import org.apache.dubbo.common.Node; * * @see org.apache.dubbo.monitor.MonitorFactory#getMonitor(org.apache.dubbo.common.URL) */ -public interface Monitor extends Node, MonitorService { - -} +public interface Monitor extends Node, MonitorService {} diff --git a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MonitorFactory.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MonitorFactory.java index 0571d97323..45403bc3bc 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MonitorFactory.java +++ b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MonitorFactory.java @@ -35,5 +35,4 @@ public interface MonitorFactory { */ @Adaptive(CommonConstants.PROTOCOL_KEY) Monitor getMonitor(URL url); - } diff --git a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MonitorService.java b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MonitorService.java index 31ecbb03a8..bc14cb9ebc 100644 --- a/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MonitorService.java +++ b/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MonitorService.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.monitor; - import org.apache.dubbo.common.URL; import java.util.List; @@ -49,5 +48,4 @@ public interface MonitorService { * @return statistics */ List lookup(URL query); - } diff --git a/dubbo-monitor/dubbo-monitor-common/pom.xml b/dubbo-monitor/dubbo-monitor-common/pom.xml index 7dadb8b337..f83f017a98 100644 --- a/dubbo-monitor/dubbo-monitor-common/pom.xml +++ b/dubbo-monitor/dubbo-monitor-common/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-monitor - ${revision} - ../pom.xml - - dubbo-monitor-common - jar - ${project.artifactId} - The monitor common module of dubbo project - - false - - - - org.apache.dubbo - dubbo-monitor-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-cluster - ${project.parent.version} - - + 4.0.0 + + org.apache.dubbo + dubbo-monitor + ${revision} + ../pom.xml + + dubbo-monitor-common + jar + ${project.artifactId} + The monitor common module of dubbo project + + false + + + + org.apache.dubbo + dubbo-monitor-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-cluster + ${project.parent.version} + + diff --git a/dubbo-monitor/dubbo-monitor-common/src/main/java/org/apache/dubbo/monitor/support/AbstractMonitorFactory.java b/dubbo-monitor/dubbo-monitor-common/src/main/java/org/apache/dubbo/monitor/support/AbstractMonitorFactory.java index c26c09cceb..0e774cc018 100644 --- a/dubbo-monitor/dubbo-monitor-common/src/main/java/org/apache/dubbo/monitor/support/AbstractMonitorFactory.java +++ b/dubbo-monitor/dubbo-monitor-common/src/main/java/org/apache/dubbo/monitor/support/AbstractMonitorFactory.java @@ -42,7 +42,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_MONIT * AbstractMonitorFactory. (SPI, Singleton, ThreadSafe) */ public abstract class AbstractMonitorFactory implements MonitorFactory { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractMonitorFactory.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(AbstractMonitorFactory.class); /** * The lock for getting monitor center @@ -59,7 +60,13 @@ public abstract class AbstractMonitorFactory implements MonitorFactory { /** * The monitor create executor */ - private static final ExecutorService EXECUTOR = new ThreadPoolExecutor(0, 10, 60L, TimeUnit.SECONDS, new SynchronousQueue(), new NamedThreadFactory("DubboMonitorCreator", true)); + private static final ExecutorService EXECUTOR = new ThreadPoolExecutor( + 0, + 10, + 60L, + TimeUnit.SECONDS, + new SynchronousQueue(), + new NamedThreadFactory("DubboMonitorCreator", true)); public static Collection getMonitors() { return Collections.unmodifiableCollection(MONITORS.values()); @@ -91,7 +98,13 @@ public abstract class AbstractMonitorFactory implements MonitorFactory { FUTURES.remove(key); return m; } catch (Throwable e) { - logger.warn(COMMON_MONITOR_EXCEPTION, "", "", "Create monitor failed, monitor data will not be collected until you fix this problem. monitorUrl: " + monitorUrl, e); + logger.warn( + COMMON_MONITOR_EXCEPTION, + "", + "", + "Create monitor failed, monitor data will not be collected until you fix this problem. monitorUrl: " + + monitorUrl, + e); return null; } }); @@ -104,5 +117,4 @@ public abstract class AbstractMonitorFactory implements MonitorFactory { } protected abstract Monitor createMonitor(URL url); - } diff --git a/dubbo-monitor/dubbo-monitor-common/src/main/java/org/apache/dubbo/monitor/support/MetricsServiceDetector.java b/dubbo-monitor/dubbo-monitor-common/src/main/java/org/apache/dubbo/monitor/support/MetricsServiceDetector.java index 0eb6406bc3..a357b8b344 100644 --- a/dubbo-monitor/dubbo-monitor-common/src/main/java/org/apache/dubbo/monitor/support/MetricsServiceDetector.java +++ b/dubbo-monitor/dubbo-monitor-common/src/main/java/org/apache/dubbo/monitor/support/MetricsServiceDetector.java @@ -30,5 +30,4 @@ public class MetricsServiceDetector implements BuiltinServiceDetector { public Class getService() { return MetricsService.class; } - } diff --git a/dubbo-monitor/dubbo-monitor-common/src/main/java/org/apache/dubbo/monitor/support/MonitorClusterFilter.java b/dubbo-monitor/dubbo-monitor-common/src/main/java/org/apache/dubbo/monitor/support/MonitorClusterFilter.java index 06ea364db6..e6e9e3c061 100644 --- a/dubbo-monitor/dubbo-monitor-common/src/main/java/org/apache/dubbo/monitor/support/MonitorClusterFilter.java +++ b/dubbo-monitor/dubbo-monitor-common/src/main/java/org/apache/dubbo/monitor/support/MonitorClusterFilter.java @@ -22,5 +22,4 @@ import org.apache.dubbo.rpc.cluster.filter.ClusterFilter; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; @Activate(group = {CONSUMER}) -public class MonitorClusterFilter extends MonitorFilter implements ClusterFilter { -} +public class MonitorClusterFilter extends MonitorFilter implements ClusterFilter {} diff --git a/dubbo-monitor/dubbo-monitor-common/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java b/dubbo-monitor/dubbo-monitor-common/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java index 2d0ec9823b..08d4d2738c 100644 --- a/dubbo-monitor/dubbo-monitor-common/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java +++ b/dubbo-monitor/dubbo-monitor-common/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.java @@ -82,7 +82,6 @@ public class MonitorFilter implements Filter, Filter.Listener { this.monitorFactory = monitorFactory; } - /** * The invocation interceptor,it will collect the invoke data about this invocation and send it to monitor center * @@ -95,7 +94,8 @@ public class MonitorFilter implements Filter, Filter.Listener { public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { if (invoker.getUrl().hasAttribute(MONITOR_KEY)) { invocation.put(MONITOR_FILTER_START_TIME, System.currentTimeMillis()); - invocation.put(MONITOR_REMOTE_HOST_STORE, RpcContext.getServiceContext().getRemoteHost()); + invocation.put( + MONITOR_REMOTE_HOST_STORE, RpcContext.getServiceContext().getRemoteHost()); // count up getConcurrent(invoker, invocation).incrementAndGet(); } @@ -125,7 +125,13 @@ public class MonitorFilter implements Filter, Filter.Listener { if (invoker.getUrl().hasAttribute(MONITOR_KEY)) { Long startTime = (Long) invocation.get(MONITOR_FILTER_START_TIME); if (startTime != null) { - collect(invoker, invocation, result, (String) invocation.get(MONITOR_REMOTE_HOST_STORE), startTime, false); + collect( + invoker, + invocation, + result, + (String) invocation.get(MONITOR_REMOTE_HOST_STORE), + startTime, + false); } // count down getConcurrent(invoker, invocation).decrementAndGet(); @@ -154,7 +160,8 @@ public class MonitorFilter implements Filter, Filter.Listener { * @param start the timestamp the invocation begin * @param error if there is an error on the invocation */ - private void collect(Invoker invoker, Invocation invocation, Result result, String remoteHost, long start, boolean error) { + private void collect( + Invoker invoker, Invocation invocation, Result result, String remoteHost, long start, boolean error) { try { Object monitorUrl; monitorUrl = invoker.getUrl().getAttribute(MONITOR_KEY); @@ -167,7 +174,12 @@ public class MonitorFilter implements Filter, Filter.Listener { monitor.collect(statisticsUrl.toSerializableURL()); } } catch (Throwable t) { - logger.warn(COMMON_MONITOR_EXCEPTION, "", "", "Failed to monitor count service " + invoker.getUrl() + ", cause: " + t.getMessage(), t); + logger.warn( + COMMON_MONITOR_EXCEPTION, + "", + "", + "Failed to monitor count service " + invoker.getUrl() + ", cause: " + t.getMessage(), + t); } } @@ -182,7 +194,8 @@ public class MonitorFilter implements Filter, Filter.Listener { * @param error * @return */ - private URL createStatisticsUrl(Invoker invoker, Invocation invocation, Result result, String remoteHost, long start, boolean error) { + private URL createStatisticsUrl( + Invoker invoker, Invocation invocation, Result result, String remoteHost, long start, boolean error) { // ---- service statistics ---- // invocation cost long elapsed = System.currentTimeMillis() - start; @@ -217,20 +230,32 @@ public class MonitorFilter implements Filter, Filter.Listener { output = result.getAttachment(OUTPUT_KEY); } - return new ServiceConfigURL(COUNT_PROTOCOL, NetUtils.getLocalHost(), localPort, - service + PATH_SEPARATOR + method, - APPLICATION_KEY, application, - INTERFACE_KEY, service, - METHOD_KEY, method, - remoteKey, remoteValue, - error ? FAILURE_KEY : SUCCESS_KEY, "1", - ELAPSED_KEY, String.valueOf(elapsed), - CONCURRENT_KEY, String.valueOf(concurrent), - INPUT_KEY, input, - OUTPUT_KEY, output, - GROUP_KEY, group, - VERSION_KEY, version); + return new ServiceConfigURL( + COUNT_PROTOCOL, + NetUtils.getLocalHost(), + localPort, + service + PATH_SEPARATOR + method, + APPLICATION_KEY, + application, + INTERFACE_KEY, + service, + METHOD_KEY, + method, + remoteKey, + remoteValue, + error ? FAILURE_KEY : SUCCESS_KEY, + "1", + ELAPSED_KEY, + String.valueOf(elapsed), + CONCURRENT_KEY, + String.valueOf(concurrent), + INPUT_KEY, + input, + OUTPUT_KEY, + output, + GROUP_KEY, + group, + VERSION_KEY, + version); } - - } diff --git a/dubbo-monitor/dubbo-monitor-common/src/main/java/org/apache/dubbo/monitor/support/MonitorServiceDetector.java b/dubbo-monitor/dubbo-monitor-common/src/main/java/org/apache/dubbo/monitor/support/MonitorServiceDetector.java index 3ae4e104dd..0b8cd37f63 100644 --- a/dubbo-monitor/dubbo-monitor-common/src/main/java/org/apache/dubbo/monitor/support/MonitorServiceDetector.java +++ b/dubbo-monitor/dubbo-monitor-common/src/main/java/org/apache/dubbo/monitor/support/MonitorServiceDetector.java @@ -25,5 +25,4 @@ public class MonitorServiceDetector implements BuiltinServiceDetector { public Class getService() { return MonitorService.class; } - } diff --git a/dubbo-monitor/dubbo-monitor-common/src/test/java/org/apache/dubbo/monitor/support/AbstractMonitorFactoryTest.java b/dubbo-monitor/dubbo-monitor-common/src/test/java/org/apache/dubbo/monitor/support/AbstractMonitorFactoryTest.java index 821ab63814..7b32aef725 100644 --- a/dubbo-monitor/dubbo-monitor-common/src/test/java/org/apache/dubbo/monitor/support/AbstractMonitorFactoryTest.java +++ b/dubbo-monitor/dubbo-monitor-common/src/test/java/org/apache/dubbo/monitor/support/AbstractMonitorFactoryTest.java @@ -21,11 +21,11 @@ import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.monitor.Monitor; import org.apache.dubbo.monitor.MonitorFactory; +import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.List; - /** * AbstractMonitorFactoryTest */ @@ -46,16 +46,13 @@ class AbstractMonitorFactoryTest { } @Override - public void destroy() { - } + public void destroy() {} - public void collect(URL statistics) { - } + public void collect(URL statistics) {} public List lookup(URL query) { return null; } - }; } }; @@ -99,5 +96,4 @@ class AbstractMonitorFactoryTest { } Assertions.assertNotSame(monitor1, monitor2); } - -} \ No newline at end of file +} diff --git a/dubbo-monitor/dubbo-monitor-common/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java b/dubbo-monitor/dubbo-monitor-common/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java index 6a644a5fec..d32f565872 100644 --- a/dubbo-monitor/dubbo-monitor-common/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java +++ b/dubbo-monitor/dubbo-monitor-common/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.java @@ -29,13 +29,13 @@ import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; +import java.util.Arrays; +import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.Arrays; -import java.util.List; - import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; @@ -69,9 +69,9 @@ class MonitorFilterTest { } public URL getUrl() { - return URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880?" + - APPLICATION_KEY + "=abc&" + SIDE_KEY + "=" + CONSUMER_SIDE) - .putAttribute(MONITOR_KEY, URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":7070")); + return URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880?" + APPLICATION_KEY + "=abc&" + SIDE_KEY + + "=" + CONSUMER_SIDE) + .putAttribute(MONITOR_KEY, URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":7070")); } @Override @@ -86,8 +86,7 @@ class MonitorFilterTest { } @Override - public void destroy() { - } + public void destroy() {} }; private MonitorFactory monitorFactory = url -> new Monitor() { @@ -101,8 +100,7 @@ class MonitorFilterTest { } @Override - public void destroy() { - } + public void destroy() {} public void collect(URL statistics) { MonitorFilterTest.this.lastStatistics = statistics; @@ -117,8 +115,11 @@ class MonitorFilterTest { void testFilter() throws Exception { MonitorFilter monitorFilter = new MonitorFilter(); monitorFilter.setMonitorFactory(monitorFactory); - Invocation invocation = new RpcInvocation("aaa", MonitorService.class.getName(), "", new Class[0], new Object[0]); - RpcContext.getServiceContext().setRemoteAddress(NetUtils.getLocalHost(), 20880).setLocalAddress(NetUtils.getLocalHost(), 2345); + Invocation invocation = + new RpcInvocation("aaa", MonitorService.class.getName(), "", new Class[0], new Object[0]); + RpcContext.getServiceContext() + .setRemoteAddress(NetUtils.getLocalHost(), 20880) + .setLocalAddress(NetUtils.getLocalHost(), 2345); Result result = monitorFilter.invoke(serviceInvoker, invocation); result.whenCompleteWithContext((r, t) -> { if (t == null) { @@ -147,9 +148,12 @@ class MonitorFilterTest { MonitorFilter monitorFilter = new MonitorFilter(); MonitorFactory mockMonitorFactory = mock(MonitorFactory.class); monitorFilter.setMonitorFactory(mockMonitorFactory); - Invocation invocation = new RpcInvocation("aaa", MonitorService.class.getName(), "", new Class[0], new Object[0]); + Invocation invocation = + new RpcInvocation("aaa", MonitorService.class.getName(), "", new Class[0], new Object[0]); Invoker invoker = mock(Invoker.class); - given(invoker.getUrl()).willReturn(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880?" + APPLICATION_KEY + "=abc&" + SIDE_KEY + "=" + CONSUMER_SIDE)); + given(invoker.getUrl()) + .willReturn(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880?" + APPLICATION_KEY + "=abc&" + + SIDE_KEY + "=" + CONSUMER_SIDE)); monitorFilter.invoke(invoker, invocation); @@ -160,8 +164,15 @@ class MonitorFilterTest { void testGenericFilter() throws Exception { MonitorFilter monitorFilter = new MonitorFilter(); monitorFilter.setMonitorFactory(monitorFactory); - Invocation invocation = new RpcInvocation("$invoke", MonitorService.class.getName(), "", new Class[]{String.class, String[].class, Object[].class}, new Object[]{"xxx", new String[]{}, new Object[]{}}); - RpcContext.getServiceContext().setRemoteAddress(NetUtils.getLocalHost(), 20880).setLocalAddress(NetUtils.getLocalHost(), 2345); + Invocation invocation = new RpcInvocation( + "$invoke", + MonitorService.class.getName(), + "", + new Class[] {String.class, String[].class, Object[].class}, + new Object[] {"xxx", new String[] {}, new Object[] {}}); + RpcContext.getServiceContext() + .setRemoteAddress(NetUtils.getLocalHost(), 20880) + .setLocalAddress(NetUtils.getLocalHost(), 2345); Result result = monitorFilter.invoke(serviceInvoker, invocation); result.whenCompleteWithContext((r, t) -> { if (t == null) { @@ -194,7 +205,8 @@ class MonitorFilterTest { monitorFilter.setMonitorFactory(mockMonitorFactory); given(mockMonitorFactory.getMonitor(any(URL.class))).willReturn(mockMonitor); - Invocation invocation = new RpcInvocation("aaa", MonitorService.class.getName(), "", new Class[0], new Object[0]); + Invocation invocation = + new RpcInvocation("aaa", MonitorService.class.getName(), "", new Class[0], new Object[0]); monitorFilter.invoke(serviceInvoker, invocation); } @@ -206,7 +218,8 @@ class MonitorFilterTest { Monitor mockMonitor = mock(Monitor.class); monitorFilter.setMonitorFactory(mockMonitorFactory); given(mockMonitorFactory.getMonitor(any(URL.class))).willReturn(mockMonitor); - Invocation invocation = new RpcInvocation("aaa", MonitorService.class.getName(), "", new Class[0], new Object[0]); + Invocation invocation = + new RpcInvocation("aaa", MonitorService.class.getName(), "", new Class[0], new Object[0]); Result result = monitorFilter.invoke(serviceInvoker, invocation); invocation.getAttributes().remove("monitor_filter_start_time"); @@ -221,9 +234,10 @@ class MonitorFilterTest { Monitor mockMonitor = mock(Monitor.class); monitorFilter.setMonitorFactory(mockMonitorFactory); given(mockMonitorFactory.getMonitor(any(URL.class))).willReturn(mockMonitor); - Invocation invocation = new RpcInvocation("aaa", MonitorService.class.getName(), "", new Class[0], new Object[0]); + Invocation invocation = + new RpcInvocation("aaa", MonitorService.class.getName(), "", new Class[0], new Object[0]); Throwable rpcException = new RpcException(); monitorFilter.onError(rpcException, serviceInvoker, invocation); } -} \ No newline at end of file +} diff --git a/dubbo-monitor/dubbo-monitor-default/pom.xml b/dubbo-monitor/dubbo-monitor-default/pom.xml index 3d001020e5..b2de57b61b 100644 --- a/dubbo-monitor/dubbo-monitor-default/pom.xml +++ b/dubbo-monitor/dubbo-monitor-default/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - org.apache.dubbo - dubbo-monitor - ${revision} - ../pom.xml - - dubbo-monitor-default - jar - ${project.artifactId} - The default monitor module of dubbo project - - false - - - - org.apache.dubbo - dubbo-monitor-common - ${project.parent.version} - - - com.alibaba.middleware - metrics-core-api - - - com.alibaba.middleware - metrics-core-impl - - - com.alibaba.middleware - metrics-common - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.parent.version} - test - - - com.google.code.gson - gson - test - - - org.slf4j - slf4j-log4j12 - test - - + + 4.0.0 + + org.apache.dubbo + dubbo-monitor + ${revision} + ../pom.xml + + dubbo-monitor-default + jar + ${project.artifactId} + The default monitor module of dubbo project + + false + + + + org.apache.dubbo + dubbo-monitor-common + ${project.parent.version} + + + com.alibaba.middleware + metrics-core-api + + + com.alibaba.middleware + metrics-core-impl + + + com.alibaba.middleware + metrics-common + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.parent.version} + test + + + com.google.code.gson + gson + test + + + org.slf4j + slf4j-log4j12 + test + + diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitor.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitor.java index e66fd5f485..215ba5daa5 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitor.java +++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitor.java @@ -77,19 +77,34 @@ public class DubboMonitor implements Monitor { public DubboMonitor(Invoker monitorInvoker, MonitorService monitorService) { this.monitorInvoker = monitorInvoker; this.monitorService = monitorService; - scheduledExecutorService = monitorInvoker.getUrl().getOrDefaultFrameworkModel().getBeanFactory() - .getBean(FrameworkExecutorRepository.class).getSharedScheduledExecutor(); + scheduledExecutorService = monitorInvoker + .getUrl() + .getOrDefaultFrameworkModel() + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class) + .getSharedScheduledExecutor(); // The time interval for timer scheduledExecutorService to send data - final long monitorInterval = monitorInvoker.getUrl().getPositiveParameter(MONITOR_SEND_DATA_INTERVAL_KEY, DEFAULT_MONITOR_SEND_DATA_INTERVAL); + final long monitorInterval = monitorInvoker + .getUrl() + .getPositiveParameter(MONITOR_SEND_DATA_INTERVAL_KEY, DEFAULT_MONITOR_SEND_DATA_INTERVAL); // collect timer for collecting statistics data - sendFuture = scheduledExecutorService.scheduleWithFixedDelay(() -> { - try { - // collect data - send(); - } catch (Throwable t) { - logger.error(COMMON_MONITOR_EXCEPTION, "", "", "Unexpected error occur at send statistic, cause: " + t.getMessage(), t); - } - }, monitorInterval, monitorInterval, TimeUnit.MILLISECONDS); + sendFuture = scheduledExecutorService.scheduleWithFixedDelay( + () -> { + try { + // collect data + send(); + } catch (Throwable t) { + logger.error( + COMMON_MONITOR_EXCEPTION, + "", + "", + "Unexpected error occur at send statistic, cause: " + t.getMessage(), + t); + } + }, + monitorInterval, + monitorInterval, + TimeUnit.MILLISECONDS); } public void send() { @@ -105,20 +120,33 @@ public class DubboMonitor implements Monitor { StatisticsItem statisticsItem = reference.get(); // send statistics data - URL url = statistics.getUrl() - .addParameters(TIMESTAMP_KEY, timestamp, - SUCCESS_KEY, String.valueOf(statisticsItem.getSuccess()), - FAILURE_KEY, String.valueOf(statisticsItem.getFailure()), - INPUT_KEY, String.valueOf(statisticsItem.getInput()), - OUTPUT_KEY, String.valueOf(statisticsItem.getOutput()), - ELAPSED_KEY, String.valueOf(statisticsItem.getElapsed()), - CONCURRENT_KEY, String.valueOf(statisticsItem.getConcurrent()), - MAX_INPUT_KEY, String.valueOf(statisticsItem.getMaxInput()), - MAX_OUTPUT_KEY, String.valueOf(statisticsItem.getMaxOutput()), - MAX_ELAPSED_KEY, String.valueOf(statisticsItem.getMaxElapsed()), - MAX_CONCURRENT_KEY, String.valueOf(statisticsItem.getMaxConcurrent()), - DEFAULT_PROTOCOL, getUrl().getParameter(DEFAULT_PROTOCOL) - ); + URL url = statistics + .getUrl() + .addParameters( + TIMESTAMP_KEY, + timestamp, + SUCCESS_KEY, + String.valueOf(statisticsItem.getSuccess()), + FAILURE_KEY, + String.valueOf(statisticsItem.getFailure()), + INPUT_KEY, + String.valueOf(statisticsItem.getInput()), + OUTPUT_KEY, + String.valueOf(statisticsItem.getOutput()), + ELAPSED_KEY, + String.valueOf(statisticsItem.getElapsed()), + CONCURRENT_KEY, + String.valueOf(statisticsItem.getConcurrent()), + MAX_INPUT_KEY, + String.valueOf(statisticsItem.getMaxInput()), + MAX_OUTPUT_KEY, + String.valueOf(statisticsItem.getMaxOutput()), + MAX_ELAPSED_KEY, + String.valueOf(statisticsItem.getMaxElapsed()), + MAX_CONCURRENT_KEY, + String.valueOf(statisticsItem.getMaxConcurrent()), + DEFAULT_PROTOCOL, + getUrl().getParameter(DEFAULT_PROTOCOL)); monitorService.collect(url.toSerializableURL()); // reset @@ -130,13 +158,12 @@ public class DubboMonitor implements Monitor { update.setItems(0, 0, 0, 0, 0, 0); } else { update.setItems( - current.getSuccess() - statisticsItem.getSuccess(), - current.getFailure() - statisticsItem.getFailure(), - current.getInput() - statisticsItem.getInput(), - current.getOutput() - statisticsItem.getOutput(), - current.getElapsed() - statisticsItem.getElapsed(), - current.getConcurrent() - statisticsItem.getConcurrent() - ); + current.getSuccess() - statisticsItem.getSuccess(), + current.getFailure() - statisticsItem.getFailure(), + current.getInput() - statisticsItem.getInput(), + current.getOutput() - statisticsItem.getOutput(), + current.getElapsed() - statisticsItem.getElapsed(), + current.getConcurrent() - statisticsItem.getConcurrent()); } } while (!reference.compareAndSet(current, update)); } @@ -153,27 +180,28 @@ public class DubboMonitor implements Monitor { int concurrent = url.getParameter(CONCURRENT_KEY, 0); // init atomic reference Statistics statistics = new Statistics(url); - AtomicReference reference = ConcurrentHashMapUtils.computeIfAbsent(statisticsMap, statistics, k -> new AtomicReference<>()); + AtomicReference reference = + ConcurrentHashMapUtils.computeIfAbsent(statisticsMap, statistics, k -> new AtomicReference<>()); // use CompareAndSet to sum StatisticsItem current; StatisticsItem update = new StatisticsItem(); do { current = reference.get(); if (current == null) { - update.setItems(success, failure, input, output, elapsed, concurrent, input, output, elapsed, concurrent); + update.setItems( + success, failure, input, output, elapsed, concurrent, input, output, elapsed, concurrent); } else { update.setItems( - current.getSuccess() + success, - current.getFailure() + failure, - current.getInput() + input, - current.getOutput() + output, - current.getElapsed() + elapsed, - (current.getConcurrent() + concurrent) / 2, - current.getMaxInput() > input ? current.getMaxInput() : input, - current.getMaxOutput() > output ? current.getMaxOutput() : output, - current.getMaxElapsed() > elapsed ? current.getMaxElapsed() : elapsed, - current.getMaxConcurrent() > concurrent ? current.getMaxConcurrent() : concurrent - ); + current.getSuccess() + success, + current.getFailure() + failure, + current.getInput() + input, + current.getOutput() + output, + current.getElapsed() + elapsed, + (current.getConcurrent() + concurrent) / 2, + current.getMaxInput() > input ? current.getMaxInput() : input, + current.getMaxOutput() > output ? current.getMaxOutput() : output, + current.getMaxElapsed() > elapsed ? current.getMaxElapsed() : elapsed, + current.getMaxConcurrent() > concurrent ? current.getMaxConcurrent() : concurrent); } } while (!reference.compareAndSet(current, update)); } @@ -198,9 +226,13 @@ public class DubboMonitor implements Monitor { try { ExecutorUtil.cancelScheduledFuture(sendFuture); } catch (Throwable t) { - logger.error(COMMON_MONITOR_EXCEPTION, "", "", "Unexpected error occur at cancel sender timer, cause: " + t.getMessage(), t); + logger.error( + COMMON_MONITOR_EXCEPTION, + "", + "", + "Unexpected error occur at cancel sender timer, cause: " + t.getMessage(), + t); } monitorInvoker.destroy(); } - } diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java index 3ca881f4da..1bffa1a200 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java +++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.java @@ -61,11 +61,9 @@ public class DubboMonitorFactory extends AbstractMonitorFactory { } else { filter = filter + ","; } - urlBuilder.addParameters(CHECK_KEY, String.valueOf(false), - REFERENCE_FILTER_KEY, filter + "-monitor"); + urlBuilder.addParameters(CHECK_KEY, String.valueOf(false), REFERENCE_FILTER_KEY, filter + "-monitor"); Invoker monitorInvoker = protocol.refer(MonitorService.class, urlBuilder.build()); MonitorService monitorService = proxyFactory.getProxy(monitorInvoker); return new DubboMonitor(monitorInvoker, monitorService); } - } diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java index 9ee73d03de..1b45878253 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java +++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.java @@ -36,16 +36,6 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ScopeModelAware; import org.apache.dubbo.rpc.support.RpcUtils; -import com.alibaba.metrics.FastCompass; -import com.alibaba.metrics.MetricLevel; -import com.alibaba.metrics.MetricManager; -import com.alibaba.metrics.MetricName; -import com.alibaba.metrics.MetricRegistry; -import com.alibaba.metrics.common.CollectLevel; -import com.alibaba.metrics.common.MetricObject; -import com.alibaba.metrics.common.MetricsCollector; -import com.alibaba.metrics.common.MetricsCollectorFactory; - import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -57,6 +47,16 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import com.alibaba.metrics.FastCompass; +import com.alibaba.metrics.MetricLevel; +import com.alibaba.metrics.MetricManager; +import com.alibaba.metrics.MetricName; +import com.alibaba.metrics.MetricRegistry; +import com.alibaba.metrics.common.CollectLevel; +import com.alibaba.metrics.common.MetricObject; +import com.alibaba.metrics.common.MetricsCollector; +import com.alibaba.metrics.common.MetricsCollectorFactory; + import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_PROTOCOL; import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_SERVICE_COMPONENT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; @@ -94,21 +94,28 @@ public class MetricsFilter implements Filter, ExtensionAccessorAware, ScopeModel @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { if (exported.compareAndSet(false, true)) { - this.protocolName = invoker.getUrl().getParameter(METRICS_PROTOCOL) == null ? - DEFAULT_PROTOCOL : invoker.getUrl().getParameter(METRICS_PROTOCOL); + this.protocolName = invoker.getUrl().getParameter(METRICS_PROTOCOL) == null + ? DEFAULT_PROTOCOL + : invoker.getUrl().getParameter(METRICS_PROTOCOL); - Protocol protocol = extensionAccessor.getExtensionLoader(Protocol.class).getExtension(protocolName); + Protocol protocol = + extensionAccessor.getExtensionLoader(Protocol.class).getExtension(protocolName); - this.port = invoker.getUrl().getParameter(METRICS_PORT) == null ? - protocol.getDefaultPort() : Integer.valueOf(invoker.getUrl().getParameter(METRICS_PORT)); + this.port = invoker.getUrl().getParameter(METRICS_PORT) == null + ? protocol.getDefaultPort() + : Integer.valueOf(invoker.getUrl().getParameter(METRICS_PORT)); Invoker metricsInvoker = initMetricsInvoker(); try { protocol.export(metricsInvoker); } catch (RuntimeException e) { - logger.error(COMMON_METRICS_COLLECTOR_EXCEPTION, "", "", "Metrics Service need to be configured" + - " when multiple processes are running on a host" + e.getMessage()); + logger.error( + COMMON_METRICS_COLLECTOR_EXCEPTION, + "", + "", + "Metrics Service need to be configured" + " when multiple processes are running on a host" + + e.getMessage()); } } @@ -160,27 +167,34 @@ public class MetricsFilter implements Filter, ExtensionAccessorAware, ScopeModel return (typeName == null ? "void" : typeName) + " " + method; } - private void reportMetrics(Invoker invoker, Invocation invocation, long duration, String result, boolean isProvider) { + private void reportMetrics( + Invoker invoker, Invocation invocation, long duration, String result, boolean isProvider) { String serviceName = invoker.getInterface().getName(); String methodName = buildMethodName(invocation); MetricName global; MetricName method; if (isProvider) { global = new MetricName(DUBBO_PROVIDER, MetricLevel.MAJOR); - method = new MetricName(DUBBO_PROVIDER_METHOD, new HashMap(4) { - { - put(SERVICE, serviceName); - put(METHOD_KEY, methodName); - } - }, MetricLevel.NORMAL); + method = new MetricName( + DUBBO_PROVIDER_METHOD, + new HashMap(4) { + { + put(SERVICE, serviceName); + put(METHOD_KEY, methodName); + } + }, + MetricLevel.NORMAL); } else { global = new MetricName(DUBBO_CONSUMER, MetricLevel.MAJOR); - method = new MetricName(DUBBO_CONSUMER_METHOD, new HashMap(4) { - { - put(SERVICE, serviceName); - put(METHOD_KEY, methodName); - } - }, MetricLevel.NORMAL); + method = new MetricName( + DUBBO_CONSUMER_METHOD, + new HashMap(4) { + { + put(SERVICE, serviceName); + put(METHOD_KEY, methodName); + } + }, + MetricLevel.NORMAL); } setCompassQuantity(DUBBO_GROUP, result, duration, global, method); } @@ -193,7 +207,8 @@ public class MetricsFilter implements Filter, ExtensionAccessorAware, ScopeModel } private List getThreadPoolMessage() { - DataStore dataStore = extensionAccessor.getExtensionLoader(DataStore.class).getDefaultExtension(); + DataStore dataStore = + extensionAccessor.getExtensionLoader(DataStore.class).getDefaultExtension(); Map executors = dataStore.get(EXECUTOR_SERVICE_COMPONENT_KEY); List threadPoolMtricList = new ArrayList<>(); @@ -203,9 +218,11 @@ public class MetricsFilter implements Filter, ExtensionAccessorAware, ScopeModel if (executor instanceof ThreadPoolExecutor) { ThreadPoolExecutor tp = (ThreadPoolExecutor) executor; - threadPoolMtricList.add(value2MetricObject("threadPool.active", tp.getActiveCount(), MetricLevel.MAJOR)); + threadPoolMtricList.add( + value2MetricObject("threadPool.active", tp.getActiveCount(), MetricLevel.MAJOR)); threadPoolMtricList.add(value2MetricObject("threadPool.core", tp.getCorePoolSize(), MetricLevel.MAJOR)); - threadPoolMtricList.add(value2MetricObject("threadPool.max", tp.getMaximumPoolSize(), MetricLevel.MAJOR)); + threadPoolMtricList.add( + value2MetricObject("threadPool.max", tp.getMaximumPoolSize(), MetricLevel.MAJOR)); threadPoolMtricList.add(value2MetricObject("threadPool.current", tp.getPoolSize(), MetricLevel.MAJOR)); } } @@ -218,11 +235,10 @@ public class MetricsFilter implements Filter, ExtensionAccessorAware, ScopeModel return null; } - return new MetricObject - .Builder(metric) - .withValue(value) - .withLevel(level) - .build(); + return new MetricObject.Builder(metric) + .withValue(value) + .withLevel(level) + .build(); } private Invoker initMetricsInvoker() { @@ -243,9 +259,8 @@ public class MetricsFilter implements Filter, ExtensionAccessorAware, ScopeModel double rateFactor = TimeUnit.SECONDS.toSeconds(1); double durationFactor = 1.0 / TimeUnit.MILLISECONDS.toNanos(1); - MetricsCollector collector = MetricsCollectorFactory.createNew( - CollectLevel.NORMAL, Collections.EMPTY_MAP, rateFactor, durationFactor, null); + CollectLevel.NORMAL, Collections.EMPTY_MAP, rateFactor, durationFactor, null); for (Map.Entry entry : fastCompasses.entrySet()) { collector.collect(entry.getKey(), entry.getValue(), timestamp); @@ -258,7 +273,8 @@ public class MetricsFilter implements Filter, ExtensionAccessorAware, ScopeModel @Override public URL getUrl() { - return URL.valueOf(protocolName + "://" + NetUtils.getIpByConfig(applicationModel) + ":" + port + "/" + MetricsService.class.getName()); + return URL.valueOf(protocolName + "://" + NetUtils.getIpByConfig(applicationModel) + ":" + port + "/" + + MetricsService.class.getName()); } @Override @@ -267,9 +283,7 @@ public class MetricsFilter implements Filter, ExtensionAccessorAware, ScopeModel } @Override - public void destroy() { - - } + public void destroy() {} }; return metricsInvoker; diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/Statistics.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/Statistics.java index a4a0ef5fa6..7c859aeb8d 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/Statistics.java +++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/Statistics.java @@ -213,5 +213,4 @@ public class Statistics implements Serializable { public String toString() { return url.toString(); } - } diff --git a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/StatisticsItem.java b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/StatisticsItem.java index 17a6e38f8d..c33d003580 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/StatisticsItem.java +++ b/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/StatisticsItem.java @@ -29,15 +29,23 @@ public class StatisticsItem { private long maxElapsed; private long maxConcurrent; - public StatisticsItem() { - } + public StatisticsItem() {} public void setItems(long success, long failure, long input, long output, long elapsed, long concurrent) { this.setItems(success, failure, input, output, elapsed, concurrent, 0, 0, 0, 0); } - public void setItems(long success, long failure, long input, long output, long elapsed, long concurrent, - long maxInput, long maxOutput, long maxElapsed, long maxConcurrent) { + public void setItems( + long success, + long failure, + long input, + long output, + long elapsed, + long concurrent, + long maxInput, + long maxOutput, + long maxElapsed, + long maxConcurrent) { this.success = success; this.failure = failure; this.input = input; diff --git a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactoryTest.java b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactoryTest.java index d5fdb3b4a6..c676528cc3 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactoryTest.java +++ b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactoryTest.java @@ -39,6 +39,7 @@ import static org.mockito.MockitoAnnotations.initMocks; class DubboMonitorFactoryTest { private DubboMonitorFactory dubboMonitorFactory; + @Mock private ProxyFactory proxyFactory; @@ -66,4 +67,4 @@ class DubboMonitorFactoryTest { Invoker invoker = invokerArgumentCaptor.getValue(); assertThat(invoker.getUrl().getParameter(REFERENCE_FILTER_KEY), containsString("testFilter")); } -} \ No newline at end of file +} diff --git a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorTest.java b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorTest.java index df40e97627..891a45e107 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorTest.java +++ b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorTest.java @@ -30,16 +30,16 @@ import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; -import org.hamcrest.CustomMatcher; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; - import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit; +import org.hamcrest.CustomMatcher; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; @@ -90,8 +90,7 @@ class DubboMonitorTest { } @Override - public void destroy() { - } + public void destroy() {} }; private volatile URL lastStatistics; private final MonitorService monitorService = new MonitorService() { @@ -103,24 +102,23 @@ class DubboMonitorTest { public List lookup(URL query) { return Arrays.asList(DubboMonitorTest.this.lastStatistics); } - }; @Test void testCount() { DubboMonitor monitor = new DubboMonitor(monitorInvoker, monitorService); URL statistics = new URLBuilder(DUBBO_PROTOCOL, "10.20.153.10", 0) - .addParameter(APPLICATION_KEY, "morgan") - .addParameter(INTERFACE_KEY, "MemberService") - .addParameter(METHOD_KEY, "findPerson") - .addParameter(CONSUMER, "10.20.153.11") - .addParameter(SUCCESS_KEY, 1) - .addParameter(FAILURE_KEY, 0) - .addParameter(ELAPSED_KEY, 3) - .addParameter(MAX_ELAPSED_KEY, 3) - .addParameter(CONCURRENT_KEY, 1) - .addParameter(MAX_CONCURRENT_KEY, 1) - .build(); + .addParameter(APPLICATION_KEY, "morgan") + .addParameter(INTERFACE_KEY, "MemberService") + .addParameter(METHOD_KEY, "findPerson") + .addParameter(CONSUMER, "10.20.153.11") + .addParameter(SUCCESS_KEY, 1) + .addParameter(FAILURE_KEY, 0) + .addParameter(ELAPSED_KEY, 3) + .addParameter(MAX_ELAPSED_KEY, 3) + .addParameter(CONCURRENT_KEY, 1) + .addParameter(MAX_CONCURRENT_KEY, 1) + .build(); monitor.collect(statistics.toSerializableURL()); monitor.send(); await().atMost(60, TimeUnit.SECONDS).until(() -> lastStatistics != null); @@ -144,23 +142,28 @@ class DubboMonitorTest { void testMonitorFactory() { MockMonitorService monitorService = new MockMonitorService(); URL statistics = new URLBuilder(DUBBO_PROTOCOL, "10.20.153.10", 0) - .addParameter(APPLICATION_KEY, "morgan") - .addParameter(INTERFACE_KEY, "MemberService") - .addParameter(METHOD_KEY, "findPerson") - .addParameter(CONSUMER, "10.20.153.11") - .addParameter(SUCCESS_KEY, 1) - .addParameter(FAILURE_KEY, 0) - .addParameter(ELAPSED_KEY, 3) - .addParameter(MAX_ELAPSED_KEY, 3) - .addParameter(CONCURRENT_KEY, 1) - .addParameter(MAX_CONCURRENT_KEY, 1) - .build(); + .addParameter(APPLICATION_KEY, "morgan") + .addParameter(INTERFACE_KEY, "MemberService") + .addParameter(METHOD_KEY, "findPerson") + .addParameter(CONSUMER, "10.20.153.11") + .addParameter(SUCCESS_KEY, 1) + .addParameter(FAILURE_KEY, 0) + .addParameter(ELAPSED_KEY, 3) + .addParameter(MAX_ELAPSED_KEY, 3) + .addParameter(CONCURRENT_KEY, 1) + .addParameter(MAX_CONCURRENT_KEY, 1) + .build(); Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - MonitorFactory monitorFactory = ExtensionLoader.getExtensionLoader(MonitorFactory.class).getAdaptiveExtension(); + ProxyFactory proxyFactory = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + MonitorFactory monitorFactory = + ExtensionLoader.getExtensionLoader(MonitorFactory.class).getAdaptiveExtension(); - Exporter exporter = protocol.export(proxyFactory.getInvoker(monitorService, MonitorService.class, URL.valueOf("dubbo://127.0.0.1:17979/" + MonitorService.class.getName()))); + Exporter exporter = protocol.export(proxyFactory.getInvoker( + monitorService, + MonitorService.class, + URL.valueOf("dubbo://127.0.0.1:17979/" + MonitorService.class.getName()))); try { Monitor monitor = null; long start = System.currentTimeMillis(); @@ -171,15 +174,15 @@ class DubboMonitorTest { } try { monitor.collect(statistics.toSerializableURL()); - await() - .atLeast(10, TimeUnit.MILLISECONDS) - .atMost(60, TimeUnit.SECONDS) - .until(() -> monitorService.getStatistics().stream().anyMatch(s -> s.getParameter(SUCCESS_KEY, 0) == 1)); + await().atLeast(10, TimeUnit.MILLISECONDS) + .atMost(60, TimeUnit.SECONDS) + .until(() -> monitorService.getStatistics().stream() + .anyMatch(s -> s.getParameter(SUCCESS_KEY, 0) == 1)); List statisticsUrls = monitorService.getStatistics(); Optional url = statisticsUrls.stream() - .filter(s -> s.getParameter(SUCCESS_KEY, 0) == 1) - .findFirst(); + .filter(s -> s.getParameter(SUCCESS_KEY, 0) == 1) + .findFirst(); Assertions.assertTrue(url.isPresent()); Assertions.assertEquals(1, url.get().getParameter(SUCCESS_KEY, 0)); Assertions.assertEquals(3, url.get().getParameter(ELAPSED_KEY, 0)); @@ -210,17 +213,17 @@ class DubboMonitorTest { @Test void testSum() { URL statistics = new URLBuilder(DUBBO_PROTOCOL, "10.20.153.11", 0) - .addParameter(APPLICATION_KEY, "morgan") - .addParameter(INTERFACE_KEY, "MemberService") - .addParameter(METHOD_KEY, "findPerson") - .addParameter(CONSUMER, "10.20.153.11") - .addParameter(SUCCESS_KEY, 1) - .addParameter(FAILURE_KEY, 0) - .addParameter(ELAPSED_KEY, 3) - .addParameter(MAX_ELAPSED_KEY, 3) - .addParameter(CONCURRENT_KEY, 1) - .addParameter(MAX_CONCURRENT_KEY, 1) - .build(); + .addParameter(APPLICATION_KEY, "morgan") + .addParameter(INTERFACE_KEY, "MemberService") + .addParameter(METHOD_KEY, "findPerson") + .addParameter(CONSUMER, "10.20.153.11") + .addParameter(SUCCESS_KEY, 1) + .addParameter(FAILURE_KEY, 0) + .addParameter(ELAPSED_KEY, 3) + .addParameter(MAX_ELAPSED_KEY, 3) + .addParameter(CONCURRENT_KEY, 1) + .addParameter(MAX_CONCURRENT_KEY, 1) + .build(); Invoker invoker = mock(Invoker.class); MonitorService monitorService = mock(MonitorService.class); @@ -228,9 +231,16 @@ class DubboMonitorTest { DubboMonitor dubboMonitor = new DubboMonitor(invoker, monitorService); dubboMonitor.collect(statistics.toSerializableURL()); - dubboMonitor.collect(statistics.addParameter(SUCCESS_KEY, 3).addParameter(CONCURRENT_KEY, 2) - .addParameter(INPUT_KEY, 1).addParameter(OUTPUT_KEY, 2).toSerializableURL()); - dubboMonitor.collect(statistics.addParameter(SUCCESS_KEY, 6).addParameter(ELAPSED_KEY, 2).toSerializableURL()); + dubboMonitor.collect(statistics + .addParameter(SUCCESS_KEY, 3) + .addParameter(CONCURRENT_KEY, 2) + .addParameter(INPUT_KEY, 1) + .addParameter(OUTPUT_KEY, 2) + .toSerializableURL()); + dubboMonitor.collect(statistics + .addParameter(SUCCESS_KEY, 6) + .addParameter(ELAPSED_KEY, 2) + .toSerializableURL()); dubboMonitor.send(); diff --git a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MetricsFilterTest.java b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MetricsFilterTest.java index 508f3d3b10..864d52fe23 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MetricsFilterTest.java +++ b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MetricsFilterTest.java @@ -31,6 +31,14 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.concurrent.Callable; +import java.util.function.Function; + import com.alibaba.metrics.FastCompass; import com.alibaba.metrics.IMetricManager; import com.alibaba.metrics.MetricLevel; @@ -43,14 +51,6 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.concurrent.Callable; -import java.util.function.Function; - import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; @@ -81,8 +81,8 @@ class MetricsFilterTest { }; private URL getUrl() { - return URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":" + port + - "/org.apache.dubbo.monitor.dubbo.service.DemoService?" + "metrics.port" + "=" + port); + return URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":" + port + + "/org.apache.dubbo.monitor.dubbo.service.DemoService?" + "metrics.port" + "=" + port); } private void onInvokeReturns(Invoker invoker, AppResponse response) { @@ -90,7 +90,8 @@ class MetricsFilterTest { } public void onInvokerThrows(Invoker invoker) { - given(invoker.invoke(Mockito.any(Invocation.class))).willThrow(new RpcException(RpcException.TIMEOUT_EXCEPTION)); + given(invoker.invoke(Mockito.any(Invocation.class))) + .willThrow(new RpcException(RpcException.TIMEOUT_EXCEPTION)); } @Test @@ -141,28 +142,37 @@ class MetricsFilterTest { metricManager.clear(); MetricsFilter metricsFilter = new MetricsFilter(); metricsFilter.setExtensionAccessor(ApplicationModel.defaultModel()); - Invocation invocation = new RpcInvocation("sayName", DemoService.class.getName(), "", new Class[]{Integer.class}, new Object[0]); - RpcContext.getServiceContext().setRemoteAddress(NetUtils.getLocalHost(), port).setLocalAddress(NetUtils.getLocalHost(), 2345); + Invocation invocation = new RpcInvocation( + "sayName", DemoService.class.getName(), "", new Class[] {Integer.class}, new Object[0]); + RpcContext.getServiceContext() + .setRemoteAddress(NetUtils.getLocalHost(), port) + .setLocalAddress(NetUtils.getLocalHost(), 2345); URL url = getUrl().addParameter(SIDE_KEY, CONSUMER_SIDE); Invoker invoker = invokerFunction.apply(url); - AppResponse response = AppResponseBuilder.create() - .build(); + AppResponse response = AppResponseBuilder.create().build(); onInvokeReturns(invoker, response); for (int i = 0; i < 100; i++) { metricsFilter.invoke(invoker, invocation); } - FastCompass dubboClient = metricManager.getFastCompass(DUBBO_GROUP, new MetricName(DUBBO_CONSUMER, MetricLevel.MAJOR)); - FastCompass dubboMethod = metricManager.getFastCompass(DUBBO_GROUP, new MetricName(DUBBO_CONSUMER_METHOD, new HashMap(4) { - { - put(SERVICE, "org.apache.dubbo.monitor.dubbo.service.DemoService"); - put(METHOD_KEY, "void sayName(Integer)"); - } - }, MetricLevel.NORMAL)); + FastCompass dubboClient = + metricManager.getFastCompass(DUBBO_GROUP, new MetricName(DUBBO_CONSUMER, MetricLevel.MAJOR)); + FastCompass dubboMethod = metricManager.getFastCompass( + DUBBO_GROUP, + new MetricName( + DUBBO_CONSUMER_METHOD, + new HashMap(4) { + { + put(SERVICE, "org.apache.dubbo.monitor.dubbo.service.DemoService"); + put(METHOD_KEY, "void sayName(Integer)"); + } + }, + MetricLevel.NORMAL)); long timestamp = System.currentTimeMillis() / 5000 * 5000; - Assertions.assertEquals(100, dubboClient.getMethodCountPerCategory(0).get("success").get(timestamp)); + Assertions.assertEquals( + 100, dubboClient.getMethodCountPerCategory(0).get("success").get(timestamp)); timestamp = timestamp / 15000 * 15000; - Assertions.assertEquals(100, dubboMethod.getMethodCountPerCategory(0).get("success").get(timestamp)); - + Assertions.assertEquals( + 100, dubboMethod.getMethodCountPerCategory(0).get("success").get(timestamp)); } private void testConsumerTimeout() { @@ -171,30 +181,38 @@ class MetricsFilterTest { MetricsFilter metricsFilter = new MetricsFilter(); metricsFilter.setExtensionAccessor(ApplicationModel.defaultModel()); Invocation invocation = new RpcInvocation("timeoutException", DemoService.class.getName(), "", null, null); - RpcContext.getServiceContext().setRemoteAddress(NetUtils.getLocalHost(), port).setLocalAddress(NetUtils.getLocalHost(), 2345); - URL url = getUrl().addParameter(SIDE_KEY, CONSUMER_SIDE) - .addParameter(TIMEOUT_KEY, 300); + RpcContext.getServiceContext() + .setRemoteAddress(NetUtils.getLocalHost(), port) + .setLocalAddress(NetUtils.getLocalHost(), 2345); + URL url = getUrl().addParameter(SIDE_KEY, CONSUMER_SIDE).addParameter(TIMEOUT_KEY, 300); Invoker invoker = invokerFunction.apply(url); onInvokerThrows(invoker); for (int i = 0; i < 10; i++) { try { metricsFilter.invoke(invoker, invocation); } catch (RpcException e) { - //ignore + // ignore } } - FastCompass dubboClient = metricManager.getFastCompass(DUBBO_GROUP, new MetricName(DUBBO_CONSUMER, MetricLevel.MAJOR)); - FastCompass dubboMethod = metricManager.getFastCompass(DUBBO_GROUP, new MetricName(DUBBO_CONSUMER_METHOD, new HashMap(4) { - { - put(SERVICE, "org.apache.dubbo.monitor.dubbo.service.DemoService"); - put(METHOD_KEY, "void timeoutException()"); - } - }, MetricLevel.NORMAL)); + FastCompass dubboClient = + metricManager.getFastCompass(DUBBO_GROUP, new MetricName(DUBBO_CONSUMER, MetricLevel.MAJOR)); + FastCompass dubboMethod = metricManager.getFastCompass( + DUBBO_GROUP, + new MetricName( + DUBBO_CONSUMER_METHOD, + new HashMap(4) { + { + put(SERVICE, "org.apache.dubbo.monitor.dubbo.service.DemoService"); + put(METHOD_KEY, "void timeoutException()"); + } + }, + MetricLevel.NORMAL)); long timestamp = System.currentTimeMillis() / 5000 * 5000; - Assertions.assertEquals(10, dubboClient.getMethodCountPerCategory(0).get("timeoutError").get(timestamp)); + Assertions.assertEquals( + 10, dubboClient.getMethodCountPerCategory(0).get("timeoutError").get(timestamp)); timestamp = timestamp / 15000 * 15000; - Assertions.assertEquals(10, dubboMethod.getMethodCountPerCategory(0).get("timeoutError").get(timestamp)); - + Assertions.assertEquals( + 10, dubboMethod.getMethodCountPerCategory(0).get("timeoutError").get(timestamp)); } private void testProviderSuccess() { @@ -202,28 +220,37 @@ class MetricsFilterTest { metricManager.clear(); MetricsFilter metricsFilter = new MetricsFilter(); metricsFilter.setExtensionAccessor(ApplicationModel.defaultModel()); - Invocation invocation = new RpcInvocation("sayName", DemoService.class.getName(), "", new Class[0], new Object[0]); - RpcContext.getServiceContext().setRemoteAddress(NetUtils.getLocalHost(), port).setLocalAddress(NetUtils.getLocalHost(), 2345); - URL url = getUrl().addParameter(SIDE_KEY, PROVIDER) - .addParameter(TIMEOUT_KEY, 300); + Invocation invocation = + new RpcInvocation("sayName", DemoService.class.getName(), "", new Class[0], new Object[0]); + RpcContext.getServiceContext() + .setRemoteAddress(NetUtils.getLocalHost(), port) + .setLocalAddress(NetUtils.getLocalHost(), 2345); + URL url = getUrl().addParameter(SIDE_KEY, PROVIDER).addParameter(TIMEOUT_KEY, 300); Invoker invoker = invokerFunction.apply(url); - AppResponse response = AppResponseBuilder.create() - .build(); + AppResponse response = AppResponseBuilder.create().build(); onInvokeReturns(invoker, response); for (int i = 0; i < 100; i++) { metricsFilter.invoke(invoker, invocation); } - FastCompass dubboClient = metricManager.getFastCompass(DUBBO_GROUP, new MetricName(DUBBO_PROVIDER, MetricLevel.MAJOR)); - FastCompass dubboMethod = metricManager.getFastCompass(DUBBO_GROUP, new MetricName(DUBBO_PROVIDER_METHOD, new HashMap(4) { - { - put(SERVICE, "org.apache.dubbo.monitor.dubbo.service.DemoService"); - put(METHOD_KEY, "void sayName()"); - } - }, MetricLevel.NORMAL)); + FastCompass dubboClient = + metricManager.getFastCompass(DUBBO_GROUP, new MetricName(DUBBO_PROVIDER, MetricLevel.MAJOR)); + FastCompass dubboMethod = metricManager.getFastCompass( + DUBBO_GROUP, + new MetricName( + DUBBO_PROVIDER_METHOD, + new HashMap(4) { + { + put(SERVICE, "org.apache.dubbo.monitor.dubbo.service.DemoService"); + put(METHOD_KEY, "void sayName()"); + } + }, + MetricLevel.NORMAL)); long timestamp = System.currentTimeMillis() / 5000 * 5000; - Assertions.assertEquals(100, dubboClient.getMethodCountPerCategory(0).get("success").get(timestamp)); + Assertions.assertEquals( + 100, dubboClient.getMethodCountPerCategory(0).get("success").get(timestamp)); timestamp = timestamp / 15000 * 15000; - Assertions.assertEquals(100, dubboMethod.getMethodCountPerCategory(0).get("success").get(timestamp)); + Assertions.assertEquals( + 100, dubboMethod.getMethodCountPerCategory(0).get("success").get(timestamp)); } private void testInvokeMetricsService() { @@ -231,10 +258,12 @@ class MetricsFilterTest { metricManager.clear(); MetricsFilter metricsFilter = new MetricsFilter(); metricsFilter.setExtensionAccessor(ApplicationModel.defaultModel()); - Invocation invocation = new RpcInvocation("sayName", DemoService.class.getName(), "", new Class[0], new Object[0]); - RpcContext.getServiceContext().setRemoteAddress(NetUtils.getLocalHost(), port).setLocalAddress(NetUtils.getLocalHost(), 2345); - URL url = getUrl().addParameter(SIDE_KEY, PROVIDER) - .addParameter(TIMEOUT_KEY, 300); + Invocation invocation = + new RpcInvocation("sayName", DemoService.class.getName(), "", new Class[0], new Object[0]); + RpcContext.getServiceContext() + .setRemoteAddress(NetUtils.getLocalHost(), port) + .setLocalAddress(NetUtils.getLocalHost(), 2345); + URL url = getUrl().addParameter(SIDE_KEY, PROVIDER).addParameter(TIMEOUT_KEY, 300); Invoker serviceInvoker = invokerFunction.apply(url); Invoker timeoutInvoker = invokerFunction.apply(url); AppResponse response = AppResponseBuilder.create().build(); @@ -245,14 +274,18 @@ class MetricsFilterTest { metricsFilter.invoke(serviceInvoker, invocation); metricsFilter.invoke(timeoutInvoker, invocation); } catch (RpcException e) { - //ignore + // ignore } } Protocol protocol = new DubboProtocol(FrameworkModel.defaultModel()); - // using host name might cause connection failure because multiple addresses might be configured to the same name! + // using host name might cause connection failure because multiple addresses might be configured to the same + // name! url = URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":" + port + "/" + MetricsService.class.getName()); Invoker invoker = protocol.refer(MetricsService.class, url); - invocation = new RpcInvocation("getMetricsByGroup", DemoService.class.getName(), "", new Class[]{String.class}, new Object[]{DUBBO_GROUP}); + invocation = new RpcInvocation( + "getMetricsByGroup", DemoService.class.getName(), "", new Class[] {String.class}, new Object[] { + DUBBO_GROUP + }); try { Thread.sleep(5000); } catch (Exception e) { @@ -260,8 +293,8 @@ class MetricsFilterTest { } String resStr = invoker.invoke(invocation).getValue().toString(); // MetricObject do not have setter, should use gson to parse - List metricObjectList = new Gson().fromJson(resStr, new TypeToken>() { - }.getType()); + List metricObjectList = + new Gson().fromJson(resStr, new TypeToken>() {}.getType()); Map metricMap = new HashMap<>(); for (int i = 0; i < metricObjectList.size(); i++) { MetricObject object = metricObjectList.get(i); @@ -282,11 +315,14 @@ class MetricsFilterTest { metricManager.clear(); MetricsFilter metricsFilter = new MetricsFilter(); metricsFilter.setExtensionAccessor(ApplicationModel.defaultModel()); - Invocation sayNameInvocation = new RpcInvocation("sayName", DemoService.class.getName(), "", new Class[0], new Object[0]); - Invocation echoInvocation = new RpcInvocation("echo", DemoService.class.getName(), "", new Class[]{Integer.class}, new Integer[]{1}); - RpcContext.getServiceContext().setRemoteAddress(NetUtils.getLocalHost(), port).setLocalAddress(NetUtils.getLocalHost(), 2345); - URL url = getUrl().addParameter(SIDE_KEY, PROVIDER) - .addParameter(TIMEOUT_KEY, 300); + Invocation sayNameInvocation = + new RpcInvocation("sayName", DemoService.class.getName(), "", new Class[0], new Object[0]); + Invocation echoInvocation = new RpcInvocation( + "echo", DemoService.class.getName(), "", new Class[] {Integer.class}, new Integer[] {1}); + RpcContext.getServiceContext() + .setRemoteAddress(NetUtils.getLocalHost(), port) + .setLocalAddress(NetUtils.getLocalHost(), 2345); + URL url = getUrl().addParameter(SIDE_KEY, PROVIDER).addParameter(TIMEOUT_KEY, 300); Invoker serviceInvoker = invokerFunction.apply(url); Invoker timeoutInvoker = invokerFunction.apply(url); AppResponse response = AppResponseBuilder.create().build(); @@ -308,18 +344,22 @@ class MetricsFilterTest { } Protocol protocol = new DubboProtocol(FrameworkModel.defaultModel()); - // using host name might cause connection failure because multiple addresses might be configured to the same name! + // using host name might cause connection failure because multiple addresses might be configured to the same + // name! url = URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":" + port + "/" + MetricsService.class.getName()); Invoker invoker = protocol.refer(MetricsService.class, url); - Invocation invocation = new RpcInvocation("getMetricsByGroup", DemoService.class.getName(), "", new Class[]{String.class}, new Object[]{DUBBO_GROUP}); + Invocation invocation = new RpcInvocation( + "getMetricsByGroup", DemoService.class.getName(), "", new Class[] {String.class}, new Object[] { + DUBBO_GROUP + }); try { Thread.sleep(15000); } catch (Exception e) { // ignore } String resStr = invoker.invoke(invocation).getValue().toString(); - List metricObjectList = new Gson().fromJson(resStr, new TypeToken>() { - }.getType()); + List metricObjectList = + new Gson().fromJson(resStr, new TypeToken>() {}.getType()); Map> methodMetricMap = new HashMap<>(); for (int i = 0; i < metricObjectList.size(); i++) { MetricObject object = metricObjectList.get(i); @@ -334,24 +374,48 @@ class MetricsFilterTest { map.put(metric, object.getValue()); } - Assertions.assertEquals(50.0, - methodMetricMap.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void sayName()").get("success_bucket_count")); - Assertions.assertEquals(50.0, - methodMetricMap.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void echo(Integer)").get("success_bucket_count")); + Assertions.assertEquals( + 50.0, + methodMetricMap + .get("org.apache.dubbo.monitor.dubbo.service.DemoService.void sayName()") + .get("success_bucket_count")); + Assertions.assertEquals( + 50.0, + methodMetricMap + .get("org.apache.dubbo.monitor.dubbo.service.DemoService.void echo(Integer)") + .get("success_bucket_count")); - Assertions.assertEquals(50.0, - methodMetricMap.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void sayName()").get("timeoutError_bucket_count")); - Assertions.assertEquals(50.0, - methodMetricMap.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void echo(Integer)").get("timeoutError_bucket_count")); + Assertions.assertEquals( + 50.0, + methodMetricMap + .get("org.apache.dubbo.monitor.dubbo.service.DemoService.void sayName()") + .get("timeoutError_bucket_count")); + Assertions.assertEquals( + 50.0, + methodMetricMap + .get("org.apache.dubbo.monitor.dubbo.service.DemoService.void echo(Integer)") + .get("timeoutError_bucket_count")); - Assertions.assertEquals(100.0 / 15, - methodMetricMap.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void sayName()").get("qps")); - Assertions.assertEquals(100.0 / 15, - methodMetricMap.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void echo(Integer)").get("qps")); + Assertions.assertEquals( + 100.0 / 15, + methodMetricMap + .get("org.apache.dubbo.monitor.dubbo.service.DemoService.void sayName()") + .get("qps")); + Assertions.assertEquals( + 100.0 / 15, + methodMetricMap + .get("org.apache.dubbo.monitor.dubbo.service.DemoService.void echo(Integer)") + .get("qps")); - Assertions.assertEquals(50.0 / 100.0, - methodMetricMap.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void sayName()").get("success_rate")); - Assertions.assertEquals(50.0 / 100.0, - methodMetricMap.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void echo(Integer)").get("success_rate")); + Assertions.assertEquals( + 50.0 / 100.0, + methodMetricMap + .get("org.apache.dubbo.monitor.dubbo.service.DemoService.void sayName()") + .get("success_rate")); + Assertions.assertEquals( + 50.0 / 100.0, + methodMetricMap + .get("org.apache.dubbo.monitor.dubbo.service.DemoService.void echo(Integer)") + .get("success_rate")); } } diff --git a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MockMonitorService.java b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MockMonitorService.java index 7c1a1b093f..ba435e70d1 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MockMonitorService.java +++ b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MockMonitorService.java @@ -40,5 +40,4 @@ public class MockMonitorService implements MonitorService { public List lookup(URL query) { return statistics; } - } diff --git a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/StatisticsTest.java b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/StatisticsTest.java index ca2b2b869d..ac41877382 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/StatisticsTest.java +++ b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/StatisticsTest.java @@ -106,4 +106,4 @@ class StatisticsTest { MatcherAssert.assertThat(statisticsWithDetailInfo.getGroup(), equalTo(statistics.getGroup())); MatcherAssert.assertThat(statisticsWithDetailInfo, not(equalTo(statistics))); } -} \ No newline at end of file +} diff --git a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/service/DemoService.java b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/service/DemoService.java index a2fb2d1178..ac0e13c81d 100644 --- a/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/service/DemoService.java +++ b/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/service/DemoService.java @@ -25,6 +25,4 @@ public interface DemoService { void throwDemoException() throws Exception; int echo(int i); - - } diff --git a/dubbo-monitor/pom.xml b/dubbo-monitor/pom.xml index 25aff40141..e859ef6bad 100644 --- a/dubbo-monitor/pom.xml +++ b/dubbo-monitor/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-parent - ${revision} - ../pom.xml - - dubbo-monitor - pom - ${project.artifactId} - The monitor module of dubbo project - - false - - - dubbo-monitor-api - dubbo-monitor-common - dubbo-monitor-default - + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + + dubbo-monitor + pom + ${project.artifactId} + The monitor module of dubbo project + + dubbo-monitor-api + dubbo-monitor-common + dubbo-monitor-default + + + false + - - - org.apache.dubbo - dubbo-test-check - ${project.parent.version} - test - - + + + org.apache.dubbo + dubbo-test-check + ${project.parent.version} + test + + diff --git a/dubbo-plugin/dubbo-auth/pom.xml b/dubbo-plugin/dubbo-auth/pom.xml index 6fcc9a6ac1..49c7f0fc63 100644 --- a/dubbo-plugin/dubbo-auth/pom.xml +++ b/dubbo-plugin/dubbo-auth/pom.xml @@ -1,3 +1,4 @@ + - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - 4.0.0 + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + - dubbo-auth - jar + dubbo-auth + jar - - false - + + false + - - - org.apache.dubbo - dubbo-common - ${project.version} - - - org.apache.dubbo - dubbo-rpc-api - ${project.version} - - + + + org.apache.dubbo + dubbo-common + ${project.version} + + + org.apache.dubbo + dubbo-rpc-api + ${project.version} + + diff --git a/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/AccessKeyAuthenticator.java b/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/AccessKeyAuthenticator.java index 875a3c3304..0b642b5e61 100644 --- a/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/AccessKeyAuthenticator.java +++ b/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/AccessKeyAuthenticator.java @@ -40,7 +40,9 @@ public class AccessKeyAuthenticator implements Authenticator { public void sign(Invocation invocation, URL url) { String currentTime = String.valueOf(System.currentTimeMillis()); AccessKeyPair accessKeyPair = getAccessKeyPair(invocation, url); - invocation.setAttachment(Constants.REQUEST_SIGNATURE_KEY, getSignature(url, invocation, accessKeyPair.getSecretKey(), currentTime)); + invocation.setAttachment( + Constants.REQUEST_SIGNATURE_KEY, + getSignature(url, invocation, accessKeyPair.getSecretKey(), currentTime)); invocation.setAttachment(Constants.REQUEST_TIMESTAMP_KEY, currentTime); invocation.setAttachment(Constants.AK_KEY, accessKeyPair.getAccessKey()); invocation.setAttachment(CommonConstants.CONSUMER, url.getApplication()); @@ -71,13 +73,15 @@ public class AccessKeyAuthenticator implements Authenticator { } AccessKeyPair getAccessKeyPair(Invocation invocation, URL url) { - AccessKeyStorage accessKeyStorage = applicationModel.getExtensionLoader(AccessKeyStorage.class) + AccessKeyStorage accessKeyStorage = applicationModel + .getExtensionLoader(AccessKeyStorage.class) .getExtension(url.getParameter(Constants.ACCESS_KEY_STORAGE_KEY, Constants.DEFAULT_ACCESS_KEY_STORAGE)); AccessKeyPair accessKeyPair; try { accessKeyPair = accessKeyStorage.getAccessKey(url, invocation); - if (accessKeyPair == null || StringUtils.isAnyEmpty(accessKeyPair.getAccessKey(), accessKeyPair.getSecretKey())) { + if (accessKeyPair == null + || StringUtils.isAnyEmpty(accessKeyPair.getAccessKey(), accessKeyPair.getSecretKey())) { throw new AccessKeyNotFoundException("AccessKeyId or secretAccessKey not found"); } } catch (Exception e) { @@ -87,7 +91,12 @@ public class AccessKeyAuthenticator implements Authenticator { } String getSignature(URL url, Invocation invocation, String secretKey, String time) { - String requestString = String.format(Constants.SIGNATURE_STRING_FORMAT, url.getColonSeparatedKey(), RpcUtils.getMethodName(invocation), secretKey, time); + String requestString = String.format( + Constants.SIGNATURE_STRING_FORMAT, + url.getColonSeparatedKey(), + RpcUtils.getMethodName(invocation), + secretKey, + time); boolean parameterEncrypt = url.getParameter(Constants.PARAMETER_SIGNATURE_ENABLE_KEY, false); if (parameterEncrypt) { return SignatureUtils.sign(invocation.getArguments(), requestString, secretKey); diff --git a/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/Constants.java b/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/Constants.java index 307cd18fcc..f331c0444a 100644 --- a/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/Constants.java +++ b/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/Constants.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.auth; - public interface Constants { String SERVICE_AUTH = "auth"; diff --git a/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/DefaultAccessKeyStorage.java b/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/DefaultAccessKeyStorage.java index c6d8abfb12..3bae5f1e71 100644 --- a/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/DefaultAccessKeyStorage.java +++ b/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/DefaultAccessKeyStorage.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.auth; - import org.apache.dubbo.auth.model.AccessKeyPair; import org.apache.dubbo.auth.spi.AccessKeyStorage; import org.apache.dubbo.common.URL; diff --git a/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/exception/AccessKeyNotFoundException.java b/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/exception/AccessKeyNotFoundException.java index 5b53db2d17..526c7a5dff 100644 --- a/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/exception/AccessKeyNotFoundException.java +++ b/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/exception/AccessKeyNotFoundException.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.auth.exception; - import org.apache.dubbo.auth.model.AccessKeyPair; /** @@ -25,12 +24,9 @@ import org.apache.dubbo.auth.model.AccessKeyPair; public class AccessKeyNotFoundException extends Exception { private static final long serialVersionUID = 7106108446396804404L; - public AccessKeyNotFoundException() { - } + public AccessKeyNotFoundException() {} public AccessKeyNotFoundException(String message) { super(message); } - - } diff --git a/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/exception/RpcAuthenticationException.java b/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/exception/RpcAuthenticationException.java index 9e0f5cf298..8dd5b208fd 100644 --- a/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/exception/RpcAuthenticationException.java +++ b/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/exception/RpcAuthenticationException.java @@ -16,10 +16,8 @@ */ package org.apache.dubbo.auth.exception; - public class RpcAuthenticationException extends Exception { - public RpcAuthenticationException() { - } + public RpcAuthenticationException() {} public RpcAuthenticationException(String message) { super(message); diff --git a/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/filter/ConsumerSignFilter.java b/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/filter/ConsumerSignFilter.java index fea562fde2..9356e47206 100644 --- a/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/filter/ConsumerSignFilter.java +++ b/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/filter/ConsumerSignFilter.java @@ -46,7 +46,8 @@ public class ConsumerSignFilter implements Filter { URL url = invoker.getUrl(); boolean shouldAuth = url.getParameter(Constants.SERVICE_AUTH, false); if (shouldAuth) { - Authenticator authenticator = applicationModel.getExtensionLoader(Authenticator.class) + Authenticator authenticator = applicationModel + .getExtensionLoader(Authenticator.class) .getExtension(url.getParameter(Constants.AUTHENTICATOR, Constants.DEFAULT_AUTHENTICATOR)); authenticator.sign(invocation, url); } diff --git a/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/filter/ProviderAuthFilter.java b/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/filter/ProviderAuthFilter.java index fb76cdfdf4..79dc883ecd 100644 --- a/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/filter/ProviderAuthFilter.java +++ b/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/filter/ProviderAuthFilter.java @@ -42,7 +42,8 @@ public class ProviderAuthFilter implements Filter { URL url = invoker.getUrl(); boolean shouldAuth = url.getParameter(Constants.SERVICE_AUTH, false); if (shouldAuth) { - Authenticator authenticator = applicationModel.getExtensionLoader(Authenticator.class) + Authenticator authenticator = applicationModel + .getExtensionLoader(Authenticator.class) .getExtension(url.getParameter(Constants.AUTHENTICATOR, Constants.DEFAULT_AUTHENTICATOR)); try { authenticator.authenticate(invocation, url); @@ -52,6 +53,4 @@ public class ProviderAuthFilter implements Filter { } return invoker.invoke(invocation); } - - } diff --git a/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/model/AccessKeyPair.java b/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/model/AccessKeyPair.java index 212f609c41..aff0c94db4 100644 --- a/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/model/AccessKeyPair.java +++ b/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/model/AccessKeyPair.java @@ -77,13 +77,12 @@ public class AccessKeyPair { @Override public String toString() { - return "AccessKeyPair{" + - "accessKey='" + accessKey + '\'' + - ", secretKey='" + secretKey + '\'' + - ", consumerSide='" + consumerSide + '\'' + - ", providerSide='" + providerSide + '\'' + - ", creator='" + creator + '\'' + - ", options='" + options + '\'' + - '}'; + return "AccessKeyPair{" + "accessKey='" + + accessKey + '\'' + ", secretKey='" + + secretKey + '\'' + ", consumerSide='" + + consumerSide + '\'' + ", providerSide='" + + providerSide + '\'' + ", creator='" + + creator + '\'' + ", options='" + + options + '\'' + '}'; } } diff --git a/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/spi/AccessKeyStorage.java b/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/spi/AccessKeyStorage.java index b7d15eb796..19ffbdc2bc 100644 --- a/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/spi/AccessKeyStorage.java +++ b/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/spi/AccessKeyStorage.java @@ -21,7 +21,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.rpc.Invocation; - /** * This SPI Extension support us to store our {@link AccessKeyPair} or load {@link AccessKeyPair} from other * storage, such as filesystem. diff --git a/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/spi/Authenticator.java b/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/spi/Authenticator.java index 45fd9138e4..c8b61057b7 100644 --- a/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/spi/Authenticator.java +++ b/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/spi/Authenticator.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.auth.spi; - import org.apache.dubbo.auth.exception.RpcAuthenticationException; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.SPI; @@ -33,7 +32,6 @@ public interface Authenticator { */ void sign(Invocation invocation, URL url); - /** * verify the signature of the request is valid or not * @param invocation diff --git a/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/utils/SignatureUtils.java b/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/utils/SignatureUtils.java index babe23c6b9..3267835bb3 100644 --- a/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/utils/SignatureUtils.java +++ b/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/utils/SignatureUtils.java @@ -18,6 +18,7 @@ package org.apache.dubbo.auth.utils; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; + import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutput; @@ -60,17 +61,17 @@ public class SignatureUtils { Mac mac; try { mac = Mac.getInstance(HMAC_SHA256_ALGORITHM); - } catch(NoSuchAlgorithmException e) { + } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Failed to generate HMAC: no such algorithm exception " + HMAC_SHA256_ALGORITHM); } SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA256_ALGORITHM); try { mac.init(signingKey); - } catch(InvalidKeyException e) { + } catch (InvalidKeyException e) { throw new RuntimeException("Failed to generate HMAC: invalid key exception"); } byte[] rawHmac; - try{ + try { // compute the hmac on input data bytes rawHmac = mac.doFinal(data); } catch (IllegalStateException e) { @@ -81,7 +82,8 @@ public class SignatureUtils { } private static byte[] toByteArray(Object[] parameters) throws IOException { - try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) { + try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ObjectOutput out = new ObjectOutputStream(bos)) { out.writeObject(parameters); out.flush(); return bos.toByteArray(); diff --git a/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/AccessKeyAuthenticatorTest.java b/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/AccessKeyAuthenticatorTest.java index 163ca15d88..e886d6e83d 100644 --- a/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/AccessKeyAuthenticatorTest.java +++ b/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/AccessKeyAuthenticatorTest.java @@ -24,10 +24,10 @@ import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; @@ -39,7 +39,6 @@ import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; - class AccessKeyAuthenticatorTest { @Test @@ -52,7 +51,8 @@ class AccessKeyAuthenticatorTest { AccessKeyAuthenticator helper = mock(AccessKeyAuthenticator.class); doCallRealMethod().when(helper).sign(invocation, url); - when(helper.getSignature(eq(url), eq(invocation), eq("sk"), anyString())).thenReturn("dubbo"); + when(helper.getSignature(eq(url), eq(invocation), eq("sk"), anyString())) + .thenReturn("dubbo"); AccessKeyPair accessKeyPair = mock(AccessKeyPair.class); when(accessKeyPair.getSecretKey()).thenReturn("sk"); @@ -78,7 +78,8 @@ class AccessKeyAuthenticatorTest { AccessKeyAuthenticator helper = mock(AccessKeyAuthenticator.class); doCallRealMethod().when(helper).authenticate(invocation, url); - when(helper.getSignature(eq(url), eq(invocation), eq("sk"), anyString())).thenReturn("dubbo"); + when(helper.getSignature(eq(url), eq(invocation), eq("sk"), anyString())) + .thenReturn("dubbo"); AccessKeyPair accessKeyPair = mock(AccessKeyPair.class); when(accessKeyPair.getSecretKey()).thenReturn("sk"); @@ -100,8 +101,7 @@ class AccessKeyAuthenticatorTest { @Test void testGetAccessKeyPairFailed() { - URL url = URL.valueOf("dubbo://10.10.10.10:2181") - .addParameter(Constants.ACCESS_KEY_ID_KEY, "ak"); + URL url = URL.valueOf("dubbo://10.10.10.10:2181").addParameter(Constants.ACCESS_KEY_ID_KEY, "ak"); AccessKeyAuthenticator helper = new AccessKeyAuthenticator(ApplicationModel.defaultModel()); Invocation invocation = mock(Invocation.class); assertThrows(RuntimeException.class, () -> helper.getAccessKeyPair(invocation, url)); @@ -134,4 +134,4 @@ class AccessKeyAuthenticatorTest { String signature1 = helper.getSignature(url, invocation, secretKey, String.valueOf(System.currentTimeMillis())); assertNotEquals(signature, signature1); } -} \ No newline at end of file +} diff --git a/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/DefaultAccessKeyStorageTest.java b/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/DefaultAccessKeyStorageTest.java index 1e0603a0d4..567e43fe1b 100644 --- a/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/DefaultAccessKeyStorageTest.java +++ b/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/DefaultAccessKeyStorageTest.java @@ -26,7 +26,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.mock; - class DefaultAccessKeyStorageTest { @Test @@ -40,4 +39,4 @@ class DefaultAccessKeyStorageTest { assertEquals(accessKey.getAccessKey(), "ak"); assertEquals(accessKey.getSecretKey(), "sk"); } -} \ No newline at end of file +} diff --git a/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/filter/ConsumerSignFilterTest.java b/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/filter/ConsumerSignFilterTest.java index 0dafb77c9f..2bf31d74b9 100644 --- a/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/filter/ConsumerSignFilterTest.java +++ b/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/filter/ConsumerSignFilterTest.java @@ -33,7 +33,6 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; - class ConsumerSignFilterTest { @Test @@ -61,4 +60,4 @@ class ConsumerSignFilterTest { consumerSignFilter.invoke(invoker, invocation); verify(invocation, times(1)).setAttachment(eq(Constants.REQUEST_SIGNATURE_KEY), anyString()); } -} \ No newline at end of file +} diff --git a/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/filter/ProviderAuthFilterTest.java b/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/filter/ProviderAuthFilterTest.java index e6f614afe8..e0c2b5c906 100644 --- a/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/filter/ProviderAuthFilterTest.java +++ b/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/filter/ProviderAuthFilterTest.java @@ -39,7 +39,6 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; - class ProviderAuthFilterTest { @Test void testAuthDisabled() { @@ -67,7 +66,6 @@ class ProviderAuthFilterTest { verify(invocation, atLeastOnce()).getAttachment(anyString()); } - @Test void testAuthFailed() { URL url = URL.valueOf("dubbo://10.10.10.10:2181") @@ -83,7 +81,6 @@ class ProviderAuthFilterTest { ProviderAuthFilter providerAuthFilter = new ProviderAuthFilter(ApplicationModel.defaultModel()); Result result = providerAuthFilter.invoke(invoker, invocation); assertTrue(result.hasException()); - } @Test @@ -126,7 +123,7 @@ class ProviderAuthFilterTest { void testAuthFailedWhenParameterError() { String service = "org.apache.dubbo.DemoService"; String method = "test"; - Object[] originalParams = new Object[]{"dubbo1", "dubbo2"}; + Object[] originalParams = new Object[] {"dubbo1", "dubbo2"}; long currentTimeMillis = System.currentTimeMillis(); URL url = URL.valueOf("dubbo://10.10.10.10:2181") .setServiceInterface(service) @@ -142,13 +139,16 @@ class ProviderAuthFilterTest { when(invocation.getObjectAttachment(CommonConstants.CONSUMER)).thenReturn("test-consumer"); when(invocation.getObjectAttachment(Constants.REQUEST_TIMESTAMP_KEY)).thenReturn(currentTimeMillis); when(invocation.getMethodName()).thenReturn(method); - Object[] fakeParams = new Object[]{"dubbo1", "dubbo3"}; + Object[] fakeParams = new Object[] {"dubbo1", "dubbo3"}; when(invocation.getArguments()).thenReturn(fakeParams); when(invoker.getUrl()).thenReturn(url); - - String requestString = String.format(Constants.SIGNATURE_STRING_FORMAT, - url.getColonSeparatedKey(), invocation.getMethodName(), "sk", currentTimeMillis); + String requestString = String.format( + Constants.SIGNATURE_STRING_FORMAT, + url.getColonSeparatedKey(), + invocation.getMethodName(), + "sk", + currentTimeMillis); String sign = SignatureUtils.sign(originalParams, requestString, "sk"); when(invocation.getObjectAttachment(Constants.REQUEST_SIGNATURE_KEY)).thenReturn(sign); @@ -177,9 +177,12 @@ class ProviderAuthFilterTest { when(invocation.getMethodName()).thenReturn(method); when(invoker.getUrl()).thenReturn(url); - - String requestString = String.format(Constants.SIGNATURE_STRING_FORMAT, - url.getColonSeparatedKey(), invocation.getMethodName(), "sk", currentTimeMillis); + String requestString = String.format( + Constants.SIGNATURE_STRING_FORMAT, + url.getColonSeparatedKey(), + invocation.getMethodName(), + "sk", + currentTimeMillis); String sign = SignatureUtils.sign(requestString, "sk"); when(invocation.getAttachment(Constants.REQUEST_SIGNATURE_KEY)).thenReturn(sign); @@ -187,4 +190,4 @@ class ProviderAuthFilterTest { Result result = providerAuthFilter.invoke(invoker, invocation); assertNull(result); } -} \ No newline at end of file +} diff --git a/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/utils/SignatureUtilsTest.java b/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/utils/SignatureUtilsTest.java index ef5c1a9f26..b8e014d527 100644 --- a/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/utils/SignatureUtilsTest.java +++ b/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/utils/SignatureUtilsTest.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.auth.utils; +import java.util.ArrayList; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.ArrayList; - class SignatureUtilsTest { @Test @@ -29,10 +29,10 @@ class SignatureUtilsTest { String encryptWithObject = SignatureUtils.sign(objects, "TestMethod#hello", "TOKEN"); Assertions.assertEquals(encryptWithObject, "t6c7PasKguovqSrVRcTQU4wTZt/ybl0jBCUMgAt/zQw="); } - + @Test void testEncryptWithNoParameters() { String encryptWithNoParams = SignatureUtils.sign(null, "TestMethod#hello", "TOKEN"); Assertions.assertEquals(encryptWithNoParams, "2DGkTcyXg4plU24rY8MZkEJwOMRW3o+wUP3HssRc3EE="); } -} \ No newline at end of file +} diff --git a/dubbo-plugin/dubbo-compiler/pom.xml b/dubbo-plugin/dubbo-compiler/pom.xml index 0fcb560f13..d583915239 100644 --- a/dubbo-plugin/dubbo-compiler/pom.xml +++ b/dubbo-plugin/dubbo-compiler/pom.xml @@ -1,3 +1,4 @@ + + + 4.0.0 - - 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + + dubbo-compiler + jar - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - jar - dubbo-compiler + ${project.artifactId} + Dubbo customized RPC stub compiler. - ${project.artifactId} - Dubbo customized RPC stub compiler. + + false + - - false - + + + com.github.spullara.mustache.java + compiler + + + io.grpc + grpc-core + + + io.grpc + grpc-stub + + + io.grpc + grpc-protobuf + + + io.grpc + grpc-context + + + com.salesforce.servicelibs + grpc-contrib + + - - - com.github.spullara.mustache.java - compiler - - - io.grpc - grpc-core - - - io.grpc - grpc-stub - - - io.grpc - grpc-protobuf - - - io.grpc - grpc-context - - - com.salesforce.servicelibs - grpc-contrib - - + + + + org.apache.maven.plugins + maven-compiler-plugin + + -proc:none + + - - - - org.apache.maven.plugins - maven-compiler-plugin - - -proc:none - - + + org.apache.maven.plugins + maven-jar-plugin + + + + true + org.apache.dubbo.gen.grpc.DubboGrpcGenerator + + + + - - org.apache.maven.plugins - maven-jar-plugin - - - - true - org.apache.dubbo.gen.grpc.DubboGrpcGenerator - - - - - - - - com.salesforce.servicelibs - canteen-maven-plugin - 1.1.0 - - - - bootstrap - - - - - - + + com.salesforce.servicelibs + canteen-maven-plugin + 1.1.0 + + + + bootstrap + + + + + + diff --git a/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/AbstractGenerator.java b/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/AbstractGenerator.java index e2d387eae4..ab141ae24a 100644 --- a/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/AbstractGenerator.java +++ b/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/AbstractGenerator.java @@ -16,6 +16,20 @@ */ package org.apache.dubbo.gen; +import org.apache.dubbo.gen.utils.ProtoTypeMap; + +import javax.annotation.Nonnull; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + import com.github.mustachejava.DefaultMustacheFactory; import com.github.mustachejava.Mustache; import com.github.mustachejava.MustacheFactory; @@ -29,20 +43,8 @@ import com.google.protobuf.DescriptorProtos.MethodDescriptorProto; import com.google.protobuf.DescriptorProtos.ServiceDescriptorProto; import com.google.protobuf.DescriptorProtos.SourceCodeInfo.Location; import com.google.protobuf.compiler.PluginProtos; -import org.apache.dubbo.gen.utils.ProtoTypeMap; -import javax.annotation.Nonnull; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -public abstract class AbstractGenerator { +public abstract class AbstractGenerator { private static final MustacheFactory MUSTACHE_FACTORY = new DefaultMustacheFactory(); private static final int SERVICE_NUMBER_OF_PATHS = 2; @@ -64,7 +66,6 @@ public abstract class AbstractGenerator { return getClassPrefix() + getClassSuffix() + "InterfaceStub.mustache"; } - private String getServiceJavaDocPrefix() { return " "; } @@ -77,34 +78,30 @@ public abstract class AbstractGenerator { final ProtoTypeMap typeMap = ProtoTypeMap.of(request.getProtoFileList()); List protosToGenerate = request.getProtoFileList().stream() - .filter(protoFile -> request.getFileToGenerateList().contains(protoFile.getName())) - .collect(Collectors.toList()); + .filter(protoFile -> request.getFileToGenerateList().contains(protoFile.getName())) + .collect(Collectors.toList()); List services = findServices(protosToGenerate, typeMap); return generateFiles(services); } - private List findServices(List protos, - ProtoTypeMap typeMap) { + private List findServices(List protos, ProtoTypeMap typeMap) { List contexts = new ArrayList<>(); protos.forEach(fileProto -> { - for (int serviceNumber = 0; serviceNumber < fileProto.getServiceCount(); - serviceNumber++) { + for (int serviceNumber = 0; serviceNumber < fileProto.getServiceCount(); serviceNumber++) { ServiceContext serviceContext = buildServiceContext( - fileProto.getService(serviceNumber), - typeMap, - fileProto.getSourceCodeInfo().getLocationList(), - serviceNumber - ); + fileProto.getService(serviceNumber), + typeMap, + fileProto.getSourceCodeInfo().getLocationList(), + serviceNumber); serviceContext.protoName = fileProto.getName(); serviceContext.packageName = extractPackageName(fileProto); if (!Strings.isNullOrEmpty(fileProto.getOptions().getJavaOuterClassname())) { serviceContext.outerClassName = fileProto.getOptions().getJavaOuterClassname(); } serviceContext.commonPackageName = extractCommonPackageName(fileProto); - serviceContext.multipleFiles = - fileProto.getOptions().getJavaMultipleFiles(); + serviceContext.multipleFiles = fileProto.getOptions().getJavaMultipleFiles(); contexts.add(serviceContext); } }); @@ -126,41 +123,32 @@ public abstract class AbstractGenerator { return Strings.nullToEmpty(proto.getPackage()); } - private ServiceContext buildServiceContext(ServiceDescriptorProto serviceProto, - ProtoTypeMap typeMap, List locations, int serviceNumber) { + private ServiceContext buildServiceContext( + ServiceDescriptorProto serviceProto, ProtoTypeMap typeMap, List locations, int serviceNumber) { ServiceContext serviceContext = new ServiceContext(); - serviceContext.fileName = - getClassPrefix() + serviceProto.getName() + getClassSuffix() + ".java"; + serviceContext.fileName = getClassPrefix() + serviceProto.getName() + getClassSuffix() + ".java"; serviceContext.className = getClassPrefix() + serviceProto.getName() + getClassSuffix(); serviceContext.outerClassName = serviceProto.getName() + "OuterClass"; serviceContext.interfaceFileName = serviceProto.getName() + ".java"; serviceContext.interfaceClassName = serviceProto.getName(); serviceContext.serviceName = serviceProto.getName(); - serviceContext.deprecated = - serviceProto.getOptions().getDeprecated(); + serviceContext.deprecated = serviceProto.getOptions().getDeprecated(); List allLocationsForService = locations.stream() - .filter(location -> - location.getPathCount() >= 2 && - location.getPath(0) == FileDescriptorProto.SERVICE_FIELD_NUMBER && - location.getPath(1) == serviceNumber - ) - .collect(Collectors.toList()); + .filter(location -> location.getPathCount() >= 2 + && location.getPath(0) == FileDescriptorProto.SERVICE_FIELD_NUMBER + && location.getPath(1) == serviceNumber) + .collect(Collectors.toList()); Location serviceLocation = allLocationsForService.stream() - .filter(location -> location.getPathCount() == SERVICE_NUMBER_OF_PATHS) - .findFirst() - .orElseGet(Location::getDefaultInstance); - serviceContext.javaDoc = getJavaDoc(getComments(serviceLocation), - getServiceJavaDocPrefix()); + .filter(location -> location.getPathCount() == SERVICE_NUMBER_OF_PATHS) + .findFirst() + .orElseGet(Location::getDefaultInstance); + serviceContext.javaDoc = getJavaDoc(getComments(serviceLocation), getServiceJavaDocPrefix()); for (int methodNumber = 0; methodNumber < serviceProto.getMethodCount(); methodNumber++) { - MethodContext methodContext = buildMethodContext( - serviceProto.getMethod(methodNumber), - typeMap, - locations, - methodNumber - ); + MethodContext methodContext = + buildMethodContext(serviceProto.getMethod(methodNumber), typeMap, locations, methodNumber); serviceContext.methods.add(methodContext); serviceContext.methodTypes.add(methodContext.inputType); @@ -169,26 +157,23 @@ public abstract class AbstractGenerator { return serviceContext; } - private MethodContext buildMethodContext(MethodDescriptorProto methodProto, - ProtoTypeMap typeMap, List locations, int methodNumber) { + private MethodContext buildMethodContext( + MethodDescriptorProto methodProto, ProtoTypeMap typeMap, List locations, int methodNumber) { MethodContext methodContext = new MethodContext(); methodContext.originMethodName = methodProto.getName(); methodContext.methodName = lowerCaseFirst(methodProto.getName()); methodContext.inputType = typeMap.toJavaTypeName(methodProto.getInputType()); methodContext.outputType = typeMap.toJavaTypeName(methodProto.getOutputType()); - methodContext.deprecated = - methodProto.getOptions().getDeprecated(); + methodContext.deprecated = methodProto.getOptions().getDeprecated(); methodContext.isManyInput = methodProto.getClientStreaming(); methodContext.isManyOutput = methodProto.getServerStreaming(); methodContext.methodNumber = methodNumber; Location methodLocation = locations.stream() - .filter(location -> - location.getPathCount() == METHOD_NUMBER_OF_PATHS && - location.getPath(METHOD_NUMBER_OF_PATHS - 1) == methodNumber - ) - .findFirst() - .orElseGet(Location::getDefaultInstance); + .filter(location -> location.getPathCount() == METHOD_NUMBER_OF_PATHS + && location.getPath(METHOD_NUMBER_OF_PATHS - 1) == methodNumber) + .findFirst() + .orElseGet(Location::getDefaultInstance); methodContext.javaDoc = getJavaDoc(getComments(methodLocation), getMethodJavaDocPrefix()); if (!methodProto.getClientStreaming() && !methodProto.getServerStreaming()) { @@ -214,8 +199,7 @@ public abstract class AbstractGenerator { return Character.toLowerCase(s.charAt(0)) + s.substring(1); } - private List generateFiles( - List services) { + private List generateFiles(List services) { List allServiceFiles = new ArrayList<>(); for (ServiceContext context : services) { List files = buildFile(context); @@ -235,27 +219,24 @@ public abstract class AbstractGenerator { String content = applyTemplate(getTemplateFileName(), context); String dir = absoluteDir(context); - files.add(PluginProtos.CodeGeneratorResponse.File - .newBuilder() - .setName(getFileName(dir, context.fileName)) - .setContent(content) - .build()); + files.add(PluginProtos.CodeGeneratorResponse.File.newBuilder() + .setName(getFileName(dir, context.fileName)) + .setContent(content) + .build()); content = applyTemplate(getInterfaceTemplateFileName(), context); - files.add(PluginProtos.CodeGeneratorResponse.File - .newBuilder() - .setName(getFileName(dir, context.interfaceFileName)) - .setContent(content) - .build()); + files.add(PluginProtos.CodeGeneratorResponse.File.newBuilder() + .setName(getFileName(dir, context.interfaceFileName)) + .setContent(content) + .build()); } else { String content = applyTemplate(getSingleTemplateFileName(), context); String dir = absoluteDir(context); - files.add(PluginProtos.CodeGeneratorResponse.File - .newBuilder() - .setName(getFileName(dir, context.fileName)) - .setContent(content) - .build()); + files.add(PluginProtos.CodeGeneratorResponse.File.newBuilder() + .setName(getFileName(dir, context.fileName)) + .setContent(content) + .build()); } return files; @@ -274,7 +255,6 @@ public abstract class AbstractGenerator { } } - private String absoluteDir(ServiceContext ctx) { return ctx.packageName.replace('.', '/'); } @@ -287,20 +267,17 @@ public abstract class AbstractGenerator { } private String getComments(Location location) { - return location.getLeadingComments().isEmpty() ? location.getTrailingComments() - : location.getLeadingComments(); + return location.getLeadingComments().isEmpty() ? location.getTrailingComments() : location.getLeadingComments(); } private String getJavaDoc(String comments, String prefix) { if (!comments.isEmpty()) { - StringBuilder builder = new StringBuilder("/**\n") - .append(prefix).append(" *
\n");
+            StringBuilder builder = new StringBuilder("/**\n").append(prefix).append(" * 
\n");
             Arrays.stream(HtmlEscapers.htmlEscaper().escape(comments).split("\n"))
-                .map(line -> line.replace("*/", "*/").replace("*", "*"))
-                .forEach(line -> builder.append(prefix).append(" * ").append(line).append("\n"));
-            builder
-                .append(prefix).append(" * 
\n") - .append(prefix).append(" */"); + .map(line -> line.replace("*/", "*/").replace("*", "*")) + .forEach(line -> + builder.append(prefix).append(" * ").append(line).append("\n")); + builder.append(prefix).append(" *
\n").append(prefix).append(" */"); return builder.toString(); } return null; @@ -334,13 +311,15 @@ public abstract class AbstractGenerator { } public List unaryMethods() { - return methods.stream().filter(m -> (!m.isManyInput && !m.isManyOutput)) - .collect(Collectors.toList()); + return methods.stream() + .filter(m -> (!m.isManyInput && !m.isManyOutput)) + .collect(Collectors.toList()); } public List serverStreamingMethods() { - return methods.stream().filter(m -> !m.isManyInput && m.isManyOutput) - .collect(Collectors.toList()); + return methods.stream() + .filter(m -> !m.isManyInput && m.isManyOutput) + .collect(Collectors.toList()); } public List biStreamingMethods() { @@ -348,19 +327,18 @@ public abstract class AbstractGenerator { } public List biStreamingWithoutClientStreamMethods() { - return methods.stream().filter(m -> m.isManyInput && m.isManyOutput) - .collect(Collectors.toList()); + return methods.stream().filter(m -> m.isManyInput && m.isManyOutput).collect(Collectors.toList()); } public List clientStreamingMethods() { - return methods.stream().filter(m -> m.isManyInput && !m.isManyOutput) - .collect(Collectors.toList()); + return methods.stream() + .filter(m -> m.isManyInput && !m.isManyOutput) + .collect(Collectors.toList()); } public List methods() { return methods; } - } /** @@ -388,8 +366,9 @@ public abstract class AbstractGenerator { for (int i = 0; i < methodName.length(); i++) { char c = methodName.charAt(i); s.append(Character.toUpperCase(c)); - if ((i < methodName.length() - 1) && Character.isLowerCase(c) - && Character.isUpperCase(methodName.charAt(i + 1))) { + if ((i < methodName.length() - 1) + && Character.isLowerCase(c) + && Character.isUpperCase(methodName.charAt(i + 1))) { s.append('_'); } } diff --git a/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/DubboGeneratorPlugin.java b/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/DubboGeneratorPlugin.java index 70254505dc..309477ae19 100644 --- a/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/DubboGeneratorPlugin.java +++ b/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/DubboGeneratorPlugin.java @@ -16,31 +16,38 @@ */ package org.apache.dubbo.gen; -import com.google.protobuf.compiler.PluginProtos; - import java.io.IOException; import java.util.List; +import com.google.protobuf.compiler.PluginProtos; public class DubboGeneratorPlugin { public static void generate(AbstractGenerator generator) { - try{ + try { PluginProtos.CodeGeneratorRequest request = PluginProtos.CodeGeneratorRequest.parseFrom(System.in); List files = generator.generateFiles(request); - PluginProtos.CodeGeneratorResponse.newBuilder().addAllFile(files).setSupportedFeatures(PluginProtos.CodeGeneratorResponse.Feature.FEATURE_PROTO3_OPTIONAL.getNumber()).build().writeTo(System.out); - }catch (Exception e){ + PluginProtos.CodeGeneratorResponse.newBuilder() + .addAllFile(files) + .setSupportedFeatures( + PluginProtos.CodeGeneratorResponse.Feature.FEATURE_PROTO3_OPTIONAL.getNumber()) + .build() + .writeTo(System.out); + } catch (Exception e) { try { - PluginProtos.CodeGeneratorResponse.newBuilder().setError(e.getMessage()).build().writeTo(System.out); + PluginProtos.CodeGeneratorResponse.newBuilder() + .setError(e.getMessage()) + .build() + .writeTo(System.out); } catch (IOException var6) { exit(e); } - }catch (Throwable var8) { + } catch (Throwable var8) { exit(var8); } } - public static void exit(Throwable e){ + public static void exit(Throwable e) { e.printStackTrace(System.err); System.exit(1); } diff --git a/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/dubbo/Dubbo3Generator.java b/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/dubbo/Dubbo3Generator.java index f10bec29e8..d882c7fbee 100644 --- a/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/dubbo/Dubbo3Generator.java +++ b/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/dubbo/Dubbo3Generator.java @@ -36,16 +36,15 @@ public class Dubbo3Generator extends AbstractGenerator { } @Override - protected String getTemplateFileName () { + protected String getTemplateFileName() { return "Dubbo3Stub.mustache"; } @Override - protected String getInterfaceTemplateFileName () { + protected String getInterfaceTemplateFileName() { return "Dubbo3InterfaceStub.mustache"; } - @Override protected String getSingleTemplateFileName() { return "DubboStub3Single.mustache"; diff --git a/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/dubbo/DubboGenerator.java b/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/dubbo/DubboGenerator.java index 8b20009a2a..793253b3e4 100644 --- a/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/dubbo/DubboGenerator.java +++ b/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/dubbo/DubboGenerator.java @@ -19,7 +19,6 @@ package org.apache.dubbo.gen.dubbo; import org.apache.dubbo.gen.AbstractGenerator; import org.apache.dubbo.gen.DubboGeneratorPlugin; - public class DubboGenerator extends AbstractGenerator { public static void main(String[] args) { diff --git a/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/grpc/DubboGrpcGenerator.java b/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/grpc/DubboGrpcGenerator.java index e8608545c5..bc3ee340ad 100644 --- a/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/grpc/DubboGrpcGenerator.java +++ b/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/grpc/DubboGrpcGenerator.java @@ -19,7 +19,6 @@ package org.apache.dubbo.gen.grpc; import org.apache.dubbo.gen.AbstractGenerator; import org.apache.dubbo.gen.DubboGeneratorPlugin; - public class DubboGrpcGenerator extends AbstractGenerator { public static void main(String[] args) { diff --git a/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/grpc/reactive/ReactorDubboGrpcGenerator.java b/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/grpc/reactive/ReactorDubboGrpcGenerator.java index ef80564ccd..b053db4b3f 100644 --- a/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/grpc/reactive/ReactorDubboGrpcGenerator.java +++ b/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/grpc/reactive/ReactorDubboGrpcGenerator.java @@ -19,8 +19,6 @@ package org.apache.dubbo.gen.grpc.reactive; import org.apache.dubbo.gen.AbstractGenerator; import org.apache.dubbo.gen.DubboGeneratorPlugin; - - public class ReactorDubboGrpcGenerator extends AbstractGenerator { @Override diff --git a/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri/Dubbo3TripleGenerator.java b/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri/Dubbo3TripleGenerator.java index 9b08e2a502..3cb8ff91fd 100644 --- a/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri/Dubbo3TripleGenerator.java +++ b/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri/Dubbo3TripleGenerator.java @@ -45,7 +45,6 @@ public class Dubbo3TripleGenerator extends AbstractGenerator { return "Dubbo3TripleInterfaceStub.mustache"; } - @Override protected String getSingleTemplateFileName() { throw new IllegalStateException("Do not support single template!"); diff --git a/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri/reactive/ReactorDubbo3TripleGenerator.java b/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri/reactive/ReactorDubbo3TripleGenerator.java index a5d2f55abc..26a25a8b5f 100644 --- a/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri/reactive/ReactorDubbo3TripleGenerator.java +++ b/dubbo-plugin/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri/reactive/ReactorDubbo3TripleGenerator.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.gen.tri.reactive; import org.apache.dubbo.gen.AbstractGenerator; diff --git a/dubbo-plugin/dubbo-filter-cache/pom.xml b/dubbo-plugin/dubbo-filter-cache/pom.xml index 8e132e04a0..0f1ee6f109 100644 --- a/dubbo-plugin/dubbo-filter-cache/pom.xml +++ b/dubbo-plugin/dubbo-filter-cache/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-plugin - ${revision} - - dubbo-filter-cache - jar - ${project.artifactId} - The cache module of dubbo project - - false - 3.12.13 - - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - - - javax.cache - cache-api - - - com.hazelcast - hazelcast - test - ${hazelcast_version} - - + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + + dubbo-filter-cache + jar + ${project.artifactId} + The cache module of dubbo project + + false + 3.12.13 + + + + org.apache.dubbo + dubbo-rpc-api + ${project.parent.version} + + + javax.cache + cache-api + + + com.hazelcast + hazelcast + ${hazelcast_version} + test + + diff --git a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/Cache.java b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/Cache.java index 69ae6710ee..898905af84 100644 --- a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/Cache.java +++ b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/Cache.java @@ -39,5 +39,4 @@ public interface Cache { * @return Return stored object against key */ Object get(Object key); - } diff --git a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/CacheFactory.java b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/CacheFactory.java index 66b5b59e2c..ed36b40851 100644 --- a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/CacheFactory.java +++ b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/CacheFactory.java @@ -39,5 +39,4 @@ public interface CacheFactory { */ @Adaptive("cache") Cache getCache(URL url, Invocation invocation); - } diff --git a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java index 209776d3a5..b22eaec658 100644 --- a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java +++ b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java @@ -64,7 +64,9 @@ import static org.apache.dubbo.common.constants.FilterConstants.CACHE_KEY; * @see org.apache.dubbo.cache.support.expiring.ExpiringCache * */ -@Activate(group = {CONSUMER, PROVIDER}, value = CACHE_KEY) +@Activate( + group = {CONSUMER, PROVIDER}, + value = CACHE_KEY) public class CacheFilter implements Filter { private CacheFactory cacheFactory; @@ -91,7 +93,8 @@ public class CacheFilter implements Filter { */ @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { - if (cacheFactory == null || ConfigUtils.isEmpty(invoker.getUrl().getMethodParameter(invocation.getMethodName(), CACHE_KEY))) { + if (cacheFactory == null + || ConfigUtils.isEmpty(invoker.getUrl().getMethodParameter(invocation.getMethodName(), CACHE_KEY))) { return invoker.invoke(invocation); } Cache cache = cacheFactory.getCache(invoker.getUrl(), invocation); @@ -100,16 +103,18 @@ public class CacheFilter implements Filter { } String key = StringUtils.toArgumentString(invocation.getArguments()); Object value = cache.get(key); - return (value != null) ? onCacheValuePresent(invocation, value) : onCacheValueNotPresent(invoker, invocation, cache, key); + return (value != null) + ? onCacheValuePresent(invocation, value) + : onCacheValueNotPresent(invoker, invocation, cache, key); } - + private Result onCacheValuePresent(Invocation invocation, Object value) { if (value instanceof ValueWrapper) { return AsyncRpcResult.newDefaultAsyncResult(((ValueWrapper) value).get(), invocation); } return AsyncRpcResult.newDefaultAsyncResult(value, invocation); } - + private Result onCacheValueNotPresent(Invoker invoker, Invocation invocation, Cache cache, String key) { Result result = invoker.invoke(invocation); if (!result.hasException()) { @@ -127,7 +132,7 @@ public class CacheFilter implements Filter { private final Object value; - public ValueWrapper (Object value) { + public ValueWrapper(Object value) { this.value = value; } diff --git a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java index 2d716a3207..00276dda8c 100644 --- a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java +++ b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java @@ -85,5 +85,4 @@ public abstract class AbstractCacheFactory implements CacheFactory { * @return Create and return new instance of cache store used as storage for caching return values. */ protected abstract Cache createCache(URL url); - } diff --git a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringCache.java b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringCache.java index afaf8c6135..c8d1fd1bed 100644 --- a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringCache.java +++ b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringCache.java @@ -68,10 +68,8 @@ public class ExpiringCache implements Cache { * @param key Unique identifier for cache lookup * @return Return stored object against key */ - @Override public Object get(Object key) { return store.get(key); } - } diff --git a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringCacheFactory.java b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringCacheFactory.java index 5259d74b6e..bb0553f074 100644 --- a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringCacheFactory.java +++ b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringCacheFactory.java @@ -20,7 +20,6 @@ import org.apache.dubbo.cache.Cache; import org.apache.dubbo.cache.support.AbstractCacheFactory; import org.apache.dubbo.common.URL; - /** * Implement {@link org.apache.dubbo.cache.CacheFactory} by extending {@link AbstractCacheFactory} and provide * instance of new {@link ExpiringCache}. @@ -29,7 +28,6 @@ import org.apache.dubbo.common.URL; * @see ExpiringCache * @see Cache */ - public class ExpiringCacheFactory extends AbstractCacheFactory { /** diff --git a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringMap.java b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringMap.java index 3516b0a214..cec8854d7d 100644 --- a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringMap.java +++ b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringMap.java @@ -194,10 +194,9 @@ public class ExpiringMap implements Map { @Override public String toString() { - return "ExpiringMap{" + - "delegateMap=" + delegateMap.toString() + - ", expireThread=" + expireThread.toString() + - '}'; + return "ExpiringMap{" + "delegateMap=" + + delegateMap.toString() + ", expireThread=" + + expireThread.toString() + '}'; } /** @@ -248,11 +247,7 @@ public class ExpiringMap implements Map { @Override public String toString() { - return "ExpiryObject{" + - "key=" + key + - ", value=" + value + - ", lastAccessTime=" + lastAccessTime + - '}'; + return "ExpiryObject{" + "key=" + key + ", value=" + value + ", lastAccessTime=" + lastAccessTime + '}'; } } @@ -267,12 +262,11 @@ public class ExpiringMap implements Map { @Override public String toString() { - return "ExpireThread{" + - ", timeToLiveMillis=" + timeToLiveMillis + - ", expirationIntervalMillis=" + expirationIntervalMillis + - ", running=" + running + - ", expirerThread=" + expirerThread + - '}'; + return "ExpireThread{" + ", timeToLiveMillis=" + + timeToLiveMillis + ", expirationIntervalMillis=" + + expirationIntervalMillis + ", running=" + + running + ", expirerThread=" + + expirerThread + '}'; } public ExpireThread() { @@ -381,6 +375,3 @@ public class ExpiringMap implements Map { } } } - - - diff --git a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCache.java b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCache.java index 7972a9dd9a..291962617e 100644 --- a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCache.java +++ b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCache.java @@ -27,6 +27,7 @@ import javax.cache.configuration.MutableConfiguration; import javax.cache.expiry.CreatedExpiryPolicy; import javax.cache.expiry.Duration; import javax.cache.spi.CachingProvider; + import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; @@ -51,19 +52,21 @@ public class JCache implements org.apache.dubbo.cache.Cache { // jcache parameter is the full-qualified class name of SPI implementation String type = url.getParameter("jcache"); - CachingProvider provider = StringUtils.isEmpty(type) ? Caching.getCachingProvider() : Caching.getCachingProvider(type); + CachingProvider provider = + StringUtils.isEmpty(type) ? Caching.getCachingProvider() : Caching.getCachingProvider(type); CacheManager cacheManager = provider.getCacheManager(); Cache cache = cacheManager.getCache(key); if (cache == null) { try { - //configure the cache - MutableConfiguration config = - new MutableConfiguration<>() - .setTypes(Object.class, Object.class) - .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MILLISECONDS, url.getMethodParameter(method, "cache.write.expire", 60 * 1000)))) - .setStoreByValue(false) - .setManagementEnabled(true) - .setStatisticsEnabled(true); + // configure the cache + MutableConfiguration config = new MutableConfiguration<>() + .setTypes(Object.class, Object.class) + .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration( + TimeUnit.MILLISECONDS, + url.getMethodParameter(method, "cache.write.expire", 60 * 1000)))) + .setStoreByValue(false) + .setManagementEnabled(true) + .setStatisticsEnabled(true); cache = cacheManager.createCache(key, config); } catch (CacheException e) { // concurrent cache initialization @@ -83,5 +86,4 @@ public class JCache implements org.apache.dubbo.cache.Cache { public Object get(Object key) { return store.get(key); } - } diff --git a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCacheFactory.java b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCacheFactory.java index aba9a2f9c4..43186f510e 100644 --- a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCacheFactory.java +++ b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCacheFactory.java @@ -44,5 +44,4 @@ public class JCacheFactory extends AbstractCacheFactory { protected Cache createCache(URL url) { return new JCache(url); } - } diff --git a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lfu/LfuCache.java b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lfu/LfuCache.java index f505c16b1d..b59c647177 100644 --- a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lfu/LfuCache.java +++ b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lfu/LfuCache.java @@ -53,7 +53,7 @@ public class LfuCache implements Cache { * @param url A valid URL instance */ @SuppressWarnings("rawtypes") - public LfuCache (URL url) { + public LfuCache(URL url) { final int max = url.getParameter("cache.size", 1000); final float factor = url.getParameter("cache.evictionFactor", 0.75f); this.store = new LFUCache(max, factor); @@ -80,5 +80,4 @@ public class LfuCache implements Cache { public Object get(Object key) { return store.get(key); } - } diff --git a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lfu/LfuCacheFactory.java b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lfu/LfuCacheFactory.java index f04edca429..0ecc8cf967 100644 --- a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lfu/LfuCacheFactory.java +++ b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lfu/LfuCacheFactory.java @@ -39,5 +39,4 @@ public class LfuCacheFactory extends AbstractCacheFactory { protected Cache createCache(URL url) { return new LfuCache(url); } - } diff --git a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCache.java b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCache.java index 5b7c2564f4..b84bebb0af 100644 --- a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCache.java +++ b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCache.java @@ -76,5 +76,4 @@ public class LruCache implements Cache { public Object get(Object key) { return store.get(key); } - } diff --git a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCacheFactory.java b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCacheFactory.java index 9ec94862a5..3954cd4c19 100644 --- a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCacheFactory.java +++ b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCacheFactory.java @@ -39,5 +39,4 @@ public class LruCacheFactory extends AbstractCacheFactory { protected Cache createCache(URL url) { return new LruCache(url); } - } diff --git a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCache.java b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCache.java index 12b3b5ca03..8627f23924 100644 --- a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCache.java +++ b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCache.java @@ -73,5 +73,4 @@ public class ThreadLocalCache implements Cache { public Object get(Object key) { return store.get().get(key); } - } diff --git a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactory.java b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactory.java index cdda6cf3e4..cee476890b 100644 --- a/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactory.java +++ b/dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactory.java @@ -39,5 +39,4 @@ public class ThreadLocalCacheFactory extends AbstractCacheFactory { protected Cache createCache(URL url) { return new ThreadLocalCache(url); } - } diff --git a/dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/filter/CacheFilterTest.java b/dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/filter/CacheFilterTest.java index f420f3fa04..03bc486da2 100644 --- a/dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/filter/CacheFilterTest.java +++ b/dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/filter/CacheFilterTest.java @@ -27,13 +27,13 @@ import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcInvocation; +import java.util.stream.Stream; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import java.util.stream.Stream; - import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -51,8 +51,7 @@ class CacheFilterTest { Arguments.of("lru", new LruCacheFactory()), Arguments.of("jcache", new JCacheFactory()), Arguments.of("threadlocal", new ThreadLocalCacheFactory()), - Arguments.of("expiring", new ExpiringCacheFactory()) - ); + Arguments.of("expiring", new ExpiringCacheFactory())); } public void setUp(String cacheType, CacheFactory cacheFactory) { @@ -70,7 +69,8 @@ class CacheFilterTest { given(invoker2.invoke(invocation)).willReturn(AsyncRpcResult.newDefaultAsyncResult("value2", invocation)); given(invoker2.getUrl()).willReturn(url); - given(invoker3.invoke(invocation)).willReturn(AsyncRpcResult.newDefaultAsyncResult(new RuntimeException(), invocation)); + given(invoker3.invoke(invocation)) + .willReturn(AsyncRpcResult.newDefaultAsyncResult(new RuntimeException(), invocation)); given(invoker3.getUrl()).willReturn(url); given(invoker4.invoke(invocation)).willReturn(AsyncRpcResult.newDefaultAsyncResult(invocation)); @@ -82,8 +82,8 @@ class CacheFilterTest { public void testNonArgsMethod(String cacheType, CacheFactory cacheFactory) { setUp(cacheType, cacheFactory); invocation.setMethodName("echo"); - invocation.setParameterTypes(new Class[]{}); - invocation.setArguments(new Object[]{}); + invocation.setParameterTypes(new Class[] {}); + invocation.setArguments(new Object[] {}); cacheFilter.invoke(invoker, invocation); cacheFilter.invoke(invoker, invocation); @@ -98,8 +98,8 @@ class CacheFilterTest { public void testMethodWithArgs(String cacheType, CacheFactory cacheFactory) { setUp(cacheType, cacheFactory); invocation.setMethodName("echo1"); - invocation.setParameterTypes(new Class[]{String.class}); - invocation.setArguments(new Object[]{"arg1"}); + invocation.setParameterTypes(new Class[] {String.class}); + invocation.setArguments(new Object[] {"arg1"}); cacheFilter.invoke(invoker, invocation); cacheFilter.invoke(invoker, invocation); @@ -114,8 +114,8 @@ class CacheFilterTest { public void testException(String cacheType, CacheFactory cacheFactory) { setUp(cacheType, cacheFactory); invocation.setMethodName("echo1"); - invocation.setParameterTypes(new Class[]{String.class}); - invocation.setArguments(new Object[]{"arg2"}); + invocation.setParameterTypes(new Class[] {String.class}); + invocation.setArguments(new Object[] {"arg2"}); cacheFilter.invoke(invoker3, invocation); cacheFilter.invoke(invoker3, invocation); @@ -128,8 +128,8 @@ class CacheFilterTest { public void testNull(String cacheType, CacheFactory cacheFactory) { setUp(cacheType, cacheFactory); invocation.setMethodName("echo1"); - invocation.setParameterTypes(new Class[]{String.class}); - invocation.setArguments(new Object[]{"arg3"}); + invocation.setParameterTypes(new Class[] {String.class}); + invocation.setArguments(new Object[] {"arg3"}); cacheFilter.invoke(invoker4, invocation); cacheFilter.invoke(invoker4, invocation); @@ -138,4 +138,4 @@ class CacheFilterTest { Assertions.assertNull(result1.getValue()); Assertions.assertNull(result2.getValue()); } -} \ No newline at end of file +} diff --git a/dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/AbstractCacheFactoryTest.java b/dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/AbstractCacheFactoryTest.java index f93a453eeb..8887bdd952 100644 --- a/dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/AbstractCacheFactoryTest.java +++ b/dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/AbstractCacheFactoryTest.java @@ -30,4 +30,4 @@ public abstract class AbstractCacheFactoryTest { } protected abstract AbstractCacheFactory getCacheFactory(); -} \ No newline at end of file +} diff --git a/dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/expiring/ExpiringCacheFactoryTest.java b/dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/expiring/ExpiringCacheFactoryTest.java index bedb6a9d2a..70bfc06ad9 100644 --- a/dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/expiring/ExpiringCacheFactoryTest.java +++ b/dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/expiring/ExpiringCacheFactoryTest.java @@ -23,10 +23,10 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.RpcInvocation; -import org.junit.jupiter.api.Test; - import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -107,4 +107,4 @@ class ExpiringCacheFactoryTest extends AbstractCacheFactoryTest { protected AbstractCacheFactory getCacheFactory() { return new ExpiringCacheFactory(); } -} \ No newline at end of file +} diff --git a/dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/lru/LruCacheFactoryTest.java b/dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/lru/LruCacheFactoryTest.java index 131defdd41..47c92249e9 100644 --- a/dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/lru/LruCacheFactoryTest.java +++ b/dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/lru/LruCacheFactoryTest.java @@ -25,7 +25,7 @@ import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; -class LruCacheFactoryTest extends AbstractCacheFactoryTest{ +class LruCacheFactoryTest extends AbstractCacheFactoryTest { @Test void testLruCacheFactory() throws Exception { Cache cache = super.constructCache(); @@ -36,4 +36,4 @@ class LruCacheFactoryTest extends AbstractCacheFactoryTest{ protected AbstractCacheFactory getCacheFactory() { return new LruCacheFactory(); } -} \ No newline at end of file +} diff --git a/dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactoryTest.java b/dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactoryTest.java index 31184ec142..b2999f42d1 100644 --- a/dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactoryTest.java +++ b/dubbo-plugin/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactoryTest.java @@ -36,4 +36,4 @@ class ThreadLocalCacheFactoryTest extends AbstractCacheFactoryTest { protected AbstractCacheFactory getCacheFactory() { return new ThreadLocalCacheFactory(); } -} \ No newline at end of file +} diff --git a/dubbo-plugin/dubbo-filter-validation/pom.xml b/dubbo-plugin/dubbo-filter-validation/pom.xml index a07374e399..bae8a9b8fb 100644 --- a/dubbo-plugin/dubbo-filter-validation/pom.xml +++ b/dubbo-plugin/dubbo-filter-validation/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-plugin - ${revision} - - dubbo-filter-validation - jar - ${project.artifactId} - The validation module of dubbo project - - false - 5.2.4.Final - 2.2.5 - 2.2.7 - - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - - - jakarta.validation - jakarta.validation-api - - - javax.validation - validation-api - - - org.hibernate - hibernate-validator - ${hibernate_validator_version} - test - - - javax.el - javax.el-api - test - ${el_api_version} - - - javax.xml.bind - jaxb-api - test - ${jaxb_api_version} - - - com.sun.xml.bind - jaxb-impl - test - ${jaxb_api_version} - - - com.sun.xml.bind - jaxb-core - test - ${jaxb_api_version} - - + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + + dubbo-filter-validation + jar + ${project.artifactId} + The validation module of dubbo project + + false + 5.2.4.Final + 2.2.5 + 2.2.7 + + + + org.apache.dubbo + dubbo-rpc-api + ${project.parent.version} + + + jakarta.validation + jakarta.validation-api + + + javax.validation + validation-api + + + org.hibernate + hibernate-validator + ${hibernate_validator_version} + test + + + javax.el + javax.el-api + ${el_api_version} + test + + + javax.xml.bind + jaxb-api + ${jaxb_api_version} + test + + + com.sun.xml.bind + jaxb-impl + ${jaxb_api_version} + test + + + com.sun.xml.bind + jaxb-core + ${jaxb_api_version} + test + + diff --git a/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validation.java b/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validation.java index 73c4cd8cdc..54469c921e 100644 --- a/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validation.java +++ b/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validation.java @@ -35,5 +35,4 @@ public interface Validation { */ @Adaptive(VALIDATION_KEY) Validator getValidator(URL url); - } diff --git a/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validator.java b/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validator.java index c78c62a116..f60f31bc2e 100644 --- a/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validator.java +++ b/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validator.java @@ -23,5 +23,4 @@ package org.apache.dubbo.validation; public interface Validator { void validate(String methodName, Class[] parameterTypes, Object[] arguments) throws Exception; - } diff --git a/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java b/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java index ab742d3561..849cf65839 100644 --- a/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java +++ b/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java @@ -59,7 +59,10 @@ import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY; * @see Filter * @see org.apache.dubbo.validation.support.AbstractValidation */ -@Activate(group = {CONSUMER, PROVIDER}, value = VALIDATION_KEY, order = 10000) +@Activate( + group = {CONSUMER, PROVIDER}, + value = VALIDATION_KEY, + order = 10000) public class ValidationFilter implements Filter { private Validation validation; @@ -87,7 +90,8 @@ public class ValidationFilter implements Filter { try { Validator validator = validation.getValidator(invoker.getUrl()); if (validator != null) { - validator.validate(invocation.getMethodName(), invocation.getParameterTypes(), invocation.getArguments()); + validator.validate( + invocation.getMethodName(), invocation.getParameterTypes(), invocation.getArguments()); } } catch (RpcException e) { throw e; @@ -99,7 +103,8 @@ public class ValidationFilter implements Filter { } private boolean needValidate(URL url, String methodName) { - return validation != null && !methodName.startsWith("$") && ConfigUtils.isNotEmpty(url.getMethodParameter(methodName, VALIDATION_KEY)); + return validation != null + && !methodName.startsWith("$") + && ConfigUtils.isNotEmpty(url.getMethodParameter(methodName, VALIDATION_KEY)); } - } diff --git a/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/AbstractValidation.java b/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/AbstractValidation.java index a6f9c8eda3..0b91b60c1d 100644 --- a/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/AbstractValidation.java +++ b/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/AbstractValidation.java @@ -47,5 +47,4 @@ public abstract class AbstractValidation implements Validation { } protected abstract Validator createValidator(URL url); - } diff --git a/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidation.java b/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidation.java index 6b4b71f9c6..6a8890fbb8 100644 --- a/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidation.java +++ b/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidation.java @@ -36,5 +36,4 @@ public class JValidation extends AbstractValidation { protected Validator createValidator(URL url) { return new JValidator(url); } - } diff --git a/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidationNew.java b/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidationNew.java index 32cec16927..a1dccd2e4f 100644 --- a/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidationNew.java +++ b/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidationNew.java @@ -36,5 +36,4 @@ public class JValidationNew extends AbstractValidation { protected Validator createValidator(URL url) { return new JValidatorNew(url); } - } diff --git a/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java b/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java index b55fb9a0d9..e19904ac16 100644 --- a/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java +++ b/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java @@ -25,6 +25,26 @@ import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.validation.MethodValidated; import org.apache.dubbo.validation.Validator; +import javax.validation.Constraint; +import javax.validation.ConstraintViolation; +import javax.validation.ConstraintViolationException; +import javax.validation.Validation; +import javax.validation.ValidatorFactory; +import javax.validation.groups.Default; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Parameter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import javassist.ClassPool; import javassist.CtClass; import javassist.CtField; @@ -48,26 +68,6 @@ import javassist.bytecode.annotation.MemberValue; import javassist.bytecode.annotation.ShortMemberValue; import javassist.bytecode.annotation.StringMemberValue; -import javax.validation.Constraint; -import javax.validation.ConstraintViolation; -import javax.validation.ConstraintViolationException; -import javax.validation.Validation; -import javax.validation.ValidatorFactory; -import javax.validation.groups.Default; -import java.lang.annotation.Annotation; -import java.lang.reflect.Array; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION; /** @@ -92,7 +92,9 @@ public class JValidator implements Validator { String jvalidation = url.getParameter("jvalidation"); ValidatorFactory factory; if (StringUtils.isNotEmpty(jvalidation)) { - factory = Validation.byProvider((Class) ReflectUtils.forName(jvalidation)).configure().buildValidatorFactory(); + factory = Validation.byProvider((Class) ReflectUtils.forName(jvalidation)) + .configure() + .buildValidatorFactory(); } else { factory = Validation.buildDefaultValidatorFactory(); } @@ -152,11 +154,13 @@ public class JValidator implements Validator { Annotation[][] parameterAnnotations = method.getParameterAnnotations(); for (int i = 0; i < parameters.length; i++) { Annotation[] annotations = parameterAnnotations[i]; - AnnotationsAttribute attribute = new AnnotationsAttribute(classFile.getConstPool(), AnnotationsAttribute.visibleTag); + AnnotationsAttribute attribute = + new AnnotationsAttribute(classFile.getConstPool(), AnnotationsAttribute.visibleTag); for (Annotation annotation : annotations) { if (annotation.annotationType().isAnnotationPresent(Constraint.class)) { javassist.bytecode.annotation.Annotation ja = new javassist.bytecode.annotation.Annotation( - classFile.getConstPool(), pool.getCtClass(annotation.annotationType().getName())); + classFile.getConstPool(), + pool.getCtClass(annotation.annotationType().getName())); Method[] members = annotation.annotationType().getMethods(); for (Method member : members) { if (Modifier.isPublic(member.getModifiers()) @@ -165,7 +169,9 @@ public class JValidator implements Validator { Object value = member.invoke(annotation); if (null != value) { MemberValue memberValue = createMemberValue( - classFile.getConstPool(), pool.get(member.getReturnType().getName()), value); + classFile.getConstPool(), + pool.get(member.getReturnType().getName()), + value); ja.addMemberValue(member.getName(), memberValue); } } @@ -176,7 +182,9 @@ public class JValidator implements Validator { Parameter parameter = parameters[i]; Class type = parameter.getType(); String fieldName = parameter.getName(); - CtField ctField = CtField.make("public " + type.getCanonicalName() + " " + fieldName + ";", pool.getCtClass(parameterClassName)); + CtField ctField = CtField.make( + "public " + type.getCanonicalName() + " " + fieldName + ";", + pool.getCtClass(parameterClassName)); ctField.getFieldInfo().addAttribute(attribute); ctClass.addField(ctField); } @@ -188,7 +196,8 @@ public class JValidator implements Validator { } private static String generateMethodParameterClassName(Class clazz, Method method) { - StringBuilder builder = new StringBuilder().append(clazz.getName()) + StringBuilder builder = new StringBuilder() + .append(clazz.getName()) .append('_') .append(toUpperMethodName(method.getName())) .append("Parameter"); @@ -291,8 +300,12 @@ public class JValidator implements Validator { } if (!violations.isEmpty()) { - logger.info("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations); - throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations); + logger.info("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + + violations); + throw new ConstraintViolationException( + "Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + + violations, + violations); } } @@ -304,7 +317,8 @@ public class JValidator implements Validator { return cached == clazz ? null : cached; } try { - methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader()); + methodClass = + Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader()); methodClassMap.put(methodClassName, methodClass); } catch (ClassNotFoundException e) { methodClassMap.put(methodClassName, clazz); @@ -332,5 +346,4 @@ public class JValidator implements Validator { } } } - } diff --git a/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidatorNew.java b/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidatorNew.java index b217131c82..9e6f4017c9 100644 --- a/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidatorNew.java +++ b/dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidatorNew.java @@ -25,12 +25,19 @@ import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.validation.MethodValidated; import org.apache.dubbo.validation.Validator; -import jakarta.validation.Constraint; -import jakarta.validation.ConstraintViolation; -import jakarta.validation.ConstraintViolationException; -import jakarta.validation.Validation; -import jakarta.validation.ValidatorFactory; -import jakarta.validation.groups.Default; +import java.lang.annotation.Annotation; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Parameter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import javassist.ClassPool; import javassist.CtClass; import javassist.CtField; @@ -54,19 +61,12 @@ import javassist.bytecode.annotation.MemberValue; import javassist.bytecode.annotation.ShortMemberValue; import javassist.bytecode.annotation.StringMemberValue; -import java.lang.annotation.Annotation; -import java.lang.reflect.Array; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; +import jakarta.validation.Constraint; +import jakarta.validation.ConstraintViolation; +import jakarta.validation.ConstraintViolationException; +import jakarta.validation.Validation; +import jakarta.validation.ValidatorFactory; +import jakarta.validation.groups.Default; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION; @@ -92,7 +92,9 @@ public class JValidatorNew implements Validator { String jvalidation = url.getParameter("jvalidationNew"); ValidatorFactory factory; if (StringUtils.isNotEmpty(jvalidation)) { - factory = Validation.byProvider((Class) ReflectUtils.forName(jvalidation)).configure().buildValidatorFactory(); + factory = Validation.byProvider((Class) ReflectUtils.forName(jvalidation)) + .configure() + .buildValidatorFactory(); } else { factory = Validation.buildDefaultValidatorFactory(); } @@ -152,11 +154,13 @@ public class JValidatorNew implements Validator { Annotation[][] parameterAnnotations = method.getParameterAnnotations(); for (int i = 0; i < parameters.length; i++) { Annotation[] annotations = parameterAnnotations[i]; - AnnotationsAttribute attribute = new AnnotationsAttribute(classFile.getConstPool(), AnnotationsAttribute.visibleTag); + AnnotationsAttribute attribute = + new AnnotationsAttribute(classFile.getConstPool(), AnnotationsAttribute.visibleTag); for (Annotation annotation : annotations) { if (annotation.annotationType().isAnnotationPresent(Constraint.class)) { javassist.bytecode.annotation.Annotation ja = new javassist.bytecode.annotation.Annotation( - classFile.getConstPool(), pool.getCtClass(annotation.annotationType().getName())); + classFile.getConstPool(), + pool.getCtClass(annotation.annotationType().getName())); Method[] members = annotation.annotationType().getMethods(); for (Method member : members) { if (Modifier.isPublic(member.getModifiers()) @@ -165,7 +169,9 @@ public class JValidatorNew implements Validator { Object value = member.invoke(annotation); if (null != value) { MemberValue memberValue = createMemberValue( - classFile.getConstPool(), pool.get(member.getReturnType().getName()), value); + classFile.getConstPool(), + pool.get(member.getReturnType().getName()), + value); ja.addMemberValue(member.getName(), memberValue); } } @@ -176,7 +182,9 @@ public class JValidatorNew implements Validator { Parameter parameter = parameters[i]; Class type = parameter.getType(); String fieldName = parameter.getName(); - CtField ctField = CtField.make("public " + type.getCanonicalName() + " " + fieldName + ";", pool.getCtClass(parameterClassName)); + CtField ctField = CtField.make( + "public " + type.getCanonicalName() + " " + fieldName + ";", + pool.getCtClass(parameterClassName)); ctField.getFieldInfo().addAttribute(attribute); ctClass.addField(ctField); } @@ -188,7 +196,8 @@ public class JValidatorNew implements Validator { } private static String generateMethodParameterClassName(Class clazz, Method method) { - StringBuilder builder = new StringBuilder().append(clazz.getName()) + StringBuilder builder = new StringBuilder() + .append(clazz.getName()) .append('_') .append(toUpperMethodName(method.getName())) .append("Parameter"); @@ -291,8 +300,12 @@ public class JValidatorNew implements Validator { } if (!violations.isEmpty()) { - logger.info("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations); - throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations); + logger.info("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + + violations); + throw new ConstraintViolationException( + "Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + + violations, + violations); } } @@ -304,7 +317,8 @@ public class JValidatorNew implements Validator { return cached == clazz ? null : cached; } try { - methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader()); + methodClass = + Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader()); methodClassMap.put(methodClassName, methodClass); } catch (ClassNotFoundException e) { methodClassMap.put(methodClassName, clazz); @@ -332,5 +346,4 @@ public class JValidatorNew implements Validator { } } } - } diff --git a/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/filter/ValidationFilterTest.java b/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/filter/ValidationFilterTest.java index 4260d76e50..2bdb65602e 100644 --- a/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/filter/ValidationFilterTest.java +++ b/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/filter/ValidationFilterTest.java @@ -55,14 +55,13 @@ class ValidationFilterTest { given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); given(invoker.getUrl()).willReturn(url); given(invocation.getMethodName()).willReturn("echo1"); - given(invocation.getParameterTypes()).willReturn(new Class[]{String.class}); - given(invocation.getArguments()).willReturn(new Object[]{"arg1"}); + given(invocation.getParameterTypes()).willReturn(new Class[] {String.class}); + given(invocation.getArguments()).willReturn(new Object[] {"arg1"}); validationFilter.setValidation(validation); Result result = validationFilter.invoke(invoker, invocation); assertThat(result.getException().getMessage(), is("Not found class test, cause: test")); - } @Test @@ -73,8 +72,8 @@ class ValidationFilterTest { given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); given(invoker.getUrl()).willReturn(url); given(invocation.getMethodName()).willReturn("echo1"); - given(invocation.getParameterTypes()).willReturn(new Class[]{String.class}); - given(invocation.getArguments()).willReturn(new Object[]{"arg1"}); + given(invocation.getParameterTypes()).willReturn(new Class[] {String.class}); + given(invocation.getArguments()).willReturn(new Object[] {"arg1"}); validationFilter.setValidation(validation); Result result = validationFilter.invoke(invoker, invocation); @@ -90,8 +89,8 @@ class ValidationFilterTest { given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); given(invoker.getUrl()).willReturn(url); given(invocation.getMethodName()).willReturn("echo1"); - given(invocation.getParameterTypes()).willReturn(new Class[]{String.class}); - given(invocation.getArguments()).willReturn(new Object[]{"arg1"}); + given(invocation.getParameterTypes()).willReturn(new Class[] {String.class}); + given(invocation.getArguments()).willReturn(new Object[] {"arg1"}); validationFilter.setValidation(validation); Result result = validationFilter.invoke(invoker, invocation); @@ -107,17 +106,15 @@ class ValidationFilterTest { given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); given(invoker.getUrl()).willReturn(url); given(invocation.getMethodName()).willReturn("$echo1"); - given(invocation.getParameterTypes()).willReturn(new Class[]{String.class}); - given(invocation.getArguments()).willReturn(new Object[]{"arg1"}); + given(invocation.getParameterTypes()).willReturn(new Class[] {String.class}); + given(invocation.getArguments()).willReturn(new Object[] {"arg1"}); validationFilter.setValidation(validation); Result result = validationFilter.invoke(invoker, invocation); assertThat(String.valueOf(result.getValue()), is("success")); - } - @Test void testItWhileThrowoutRpcException() { Assertions.assertThrows(RpcException.class, () -> { @@ -127,11 +124,11 @@ class ValidationFilterTest { given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); given(invoker.getUrl()).willReturn(url); given(invocation.getMethodName()).willReturn("echo1"); - given(invocation.getParameterTypes()).willReturn(new Class[]{String.class}); - given(invocation.getArguments()).willReturn(new Object[]{"arg1"}); + given(invocation.getParameterTypes()).willReturn(new Class[] {String.class}); + given(invocation.getArguments()).willReturn(new Object[] {"arg1"}); validationFilter.setValidation(validation); validationFilter.invoke(invoker, invocation); }); } -} \ No newline at end of file +} diff --git a/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidationTest.java b/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidationTest.java index c016cbbf27..5e6e837703 100644 --- a/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidationTest.java +++ b/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidationTest.java @@ -20,11 +20,11 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.validation.Validation; import org.apache.dubbo.validation.Validator; +import javax.validation.ValidationException; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import javax.validation.ValidationException; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; @@ -33,11 +33,10 @@ class JValidationTest { void testReturnTypeWithInvalidValidationProvider() { Assertions.assertThrows(ValidationException.class, () -> { Validation jValidation = new JValidation(); - URL url = URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.JValidation?" + - "jvalidation=org.apache.dubbo.validation.Validation"); + URL url = URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.JValidation?" + + "jvalidation=org.apache.dubbo.validation.Validation"); jValidation.getValidator(url); }); - } @Test @@ -47,4 +46,4 @@ class JValidationTest { Validator validator = jValidation.getValidator(url); assertThat(validator instanceof JValidator, is(true)); } -} \ No newline at end of file +} diff --git a/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidatorTest.java b/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidatorTest.java index a434b6d7dd..de9f87cdcf 100644 --- a/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidatorTest.java +++ b/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidatorTest.java @@ -20,16 +20,17 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget; import org.apache.dubbo.validation.support.jvalidation.mock.ValidationParameter; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import javax.validation.ConstraintViolationException; import javax.validation.ValidationException; + import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.instanceOf; @@ -39,73 +40,93 @@ class JValidatorTest { @Test void testItWithNonExistMethod() { Assertions.assertThrows(NoSuchMethodException.class, () -> { - URL url = URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); + URL url = URL.valueOf( + "test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); JValidator jValidator = new JValidator(url); - jValidator.validate("nonExistingMethod", new Class[]{String.class}, new Object[]{"arg1"}); + jValidator.validate("nonExistingMethod", new Class[] {String.class}, new Object[] {"arg1"}); }); } @Test void testItWithExistMethod() throws Exception { - URL url = URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); + URL url = + URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); JValidator jValidator = new JValidator(url); - jValidator.validate("someMethod1", new Class[]{String.class}, new Object[]{"anything"}); + jValidator.validate("someMethod1", new Class[] {String.class}, new Object[] {"anything"}); } @Test void testItWhenItViolatedConstraint() { Assertions.assertThrows(ValidationException.class, () -> { - URL url = URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); + URL url = URL.valueOf( + "test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); JValidator jValidator = new JValidator(url); - jValidator.validate("someMethod2", new Class[]{ValidationParameter.class}, new Object[]{new ValidationParameter()}); + jValidator.validate( + "someMethod2", new Class[] {ValidationParameter.class}, new Object[] {new ValidationParameter() + }); }); } @Test void testItWhenItMeetsConstraint() throws Exception { - URL url = URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); + URL url = + URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); JValidator jValidator = new JValidator(url); - jValidator.validate("someMethod2", new Class[]{ValidationParameter.class}, new Object[]{new ValidationParameter("NotBeNull")}); + jValidator.validate("someMethod2", new Class[] {ValidationParameter.class}, new Object[] { + new ValidationParameter("NotBeNull") + }); } @Test void testItWithArrayArg() throws Exception { - URL url = URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); + URL url = + URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); JValidator jValidator = new JValidator(url); - jValidator.validate("someMethod3", new Class[]{ValidationParameter[].class}, new Object[]{new ValidationParameter[]{new ValidationParameter("parameter")}}); + jValidator.validate("someMethod3", new Class[] {ValidationParameter[].class}, new Object[] { + new ValidationParameter[] {new ValidationParameter("parameter")} + }); } @Test void testItWithCollectionArg() throws Exception { - URL url = URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); + URL url = + URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); JValidator jValidator = new JValidator(url); - jValidator.validate("someMethod4", new Class[]{List.class}, new Object[]{Collections.singletonList("parameter")}); + jValidator.validate( + "someMethod4", new Class[] {List.class}, new Object[] {Collections.singletonList("parameter")}); } @Test void testItWithMapArg() throws Exception { - URL url = URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); + URL url = + URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); JValidator jValidator = new JValidator(url); Map map = new HashMap<>(); map.put("key", "value"); - jValidator.validate("someMethod5", new Class[]{Map.class}, new Object[]{map}); + jValidator.validate("someMethod5", new Class[] {Map.class}, new Object[] {map}); } @Test void testItWithPrimitiveArg() { Assertions.assertThrows(ValidationException.class, () -> { - URL url = URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); + URL url = URL.valueOf( + "test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); JValidator jValidator = new JValidator(url); - jValidator.validate("someMethod6", new Class[]{Integer.class, String.class, Long.class}, new Object[]{null, null, null}); + jValidator.validate("someMethod6", new Class[] {Integer.class, String.class, Long.class}, new Object[] { + null, null, null + }); }); } @Test void testItWithPrimitiveArgWithProvidedMessage() { - URL url = URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); + URL url = + URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); JValidator jValidator = new JValidator(url); try { - jValidator.validate("someMethod6", new Class[]{Integer.class, String.class, Long.class}, new Object[]{null, "", null}); + jValidator.validate("someMethod6", new Class[] {Integer.class, String.class, Long.class}, new Object[] { + null, "", null + }); Assertions.fail(); } catch (Exception e) { assertThat(e.getMessage(), containsString("string must not be blank")); @@ -115,10 +136,13 @@ class JValidatorTest { @Test void testItWithPartialParameterValidation() { - URL url = URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); + URL url = + URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); JValidator jValidator = new JValidator(url); try { - jValidator.validate("someMethod6", new Class[]{Integer.class, String.class, Long.class}, new Object[]{null, "", null}); + jValidator.validate("someMethod6", new Class[] {Integer.class, String.class, Long.class}, new Object[] { + null, "", null + }); Assertions.fail(); } catch (Exception e) { assertThat(e, instanceOf(ConstraintViolationException.class)); @@ -130,19 +154,23 @@ class JValidatorTest { @Test void testItWithNestedParameterValidationWithNullParam() { Assertions.assertThrows(ValidationException.class, () -> { - URL url = URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); + URL url = URL.valueOf( + "test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); JValidator jValidator = new JValidator(url); - jValidator.validate("someMethod7", new Class[]{JValidatorTestTarget.BaseParam.class}, new Object[]{null}); + jValidator.validate( + "someMethod7", new Class[] {JValidatorTestTarget.BaseParam.class}, new Object[] {null}); }); } @Test void testItWithNestedParameterValidationWithNullNestedParam() { - URL url = URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); + URL url = + URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); JValidator jValidator = new JValidator(url); try { JValidatorTestTarget.BaseParam param = new JValidatorTestTarget.BaseParam<>(); - jValidator.validate("someMethod7", new Class[]{JValidatorTestTarget.BaseParam.class}, new Object[]{param}); + jValidator.validate( + "someMethod7", new Class[] {JValidatorTestTarget.BaseParam.class}, new Object[] {param}); Assertions.fail(); } catch (Exception e) { assertThat(e, instanceOf(ConstraintViolationException.class)); @@ -154,12 +182,14 @@ class JValidatorTest { @Test void testItWithNestedParameterValidationWithNullNestedParams() { - URL url = URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); + URL url = + URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget"); JValidator jValidator = new JValidator(url); try { JValidatorTestTarget.BaseParam param = new JValidatorTestTarget.BaseParam<>(); param.setBody(new JValidatorTestTarget.Param()); - jValidator.validate("someMethod7", new Class[]{JValidatorTestTarget.BaseParam.class}, new Object[]{param}); + jValidator.validate( + "someMethod7", new Class[] {JValidatorTestTarget.BaseParam.class}, new Object[] {param}); Assertions.fail(); } catch (Exception e) { assertThat(e, instanceOf(ConstraintViolationException.class)); @@ -168,5 +198,4 @@ class JValidatorTest { assertThat(e1.getMessage(), containsString("name must not be null")); } } - } diff --git a/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/mock/JValidatorTestTarget.java b/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/mock/JValidatorTestTarget.java index 9cf5dec6f3..cc288eb2bc 100644 --- a/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/mock/JValidatorTestTarget.java +++ b/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/mock/JValidatorTestTarget.java @@ -18,13 +18,14 @@ package org.apache.dubbo.validation.support.jvalidation.mock; import org.apache.dubbo.validation.MethodValidated; -import org.hibernate.validator.constraints.NotBlank; - import javax.validation.Valid; import javax.validation.constraints.NotNull; + import java.util.List; import java.util.Map; +import org.hibernate.validator.constraints.NotBlank; + public interface JValidatorTestTarget { @MethodValidated void someMethod1(String anything); @@ -38,14 +39,14 @@ public interface JValidatorTestTarget { void someMethod5(Map map); - void someMethod6(Integer intValue, - @NotBlank(message = "string must not be blank") String string, - @NotNull(message = "longValue must not be null") Long longValue); + void someMethod6( + Integer intValue, + @NotBlank(message = "string must not be blank") String string, + @NotNull(message = "longValue must not be null") Long longValue); void someMethod7(@NotNull BaseParam baseParam); - @interface Test2 { - } + @interface Test2 {} class BaseParam { @@ -75,5 +76,4 @@ public interface JValidatorTestTarget { this.name = name; } } - } diff --git a/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/mock/ValidationParameter.java b/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/mock/ValidationParameter.java index 0b54a047ae..fb4b598dbd 100644 --- a/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/mock/ValidationParameter.java +++ b/dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/mock/ValidationParameter.java @@ -22,8 +22,7 @@ public class ValidationParameter { @NotNull private String parameter; - public ValidationParameter() { - } + public ValidationParameter() {} public ValidationParameter(String parameter) { this.parameter = parameter; diff --git a/dubbo-plugin/dubbo-native/pom.xml b/dubbo-plugin/dubbo-native/pom.xml index 10cf45a60b..0bab55afc4 100644 --- a/dubbo-plugin/dubbo-native/pom.xml +++ b/dubbo-plugin/dubbo-native/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + - dubbo-native - jar + dubbo-native + jar - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - + + + org.apache.dubbo + dubbo-common + ${project.parent.version} + + diff --git a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ConditionalDescriber.java b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ConditionalDescriber.java index 7a291743a7..0112f7abb1 100644 --- a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ConditionalDescriber.java +++ b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ConditionalDescriber.java @@ -22,5 +22,4 @@ package org.apache.dubbo.aot.api; public interface ConditionalDescriber { String getReachableType(); - } diff --git a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ExecutableMode.java b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ExecutableMode.java index a44fe7f06d..b9af8148a9 100644 --- a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ExecutableMode.java +++ b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ExecutableMode.java @@ -1,11 +1,12 @@ /* - * Copyright 2002-2022 the original author or authors. + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 * - * 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 - * - * https://www.apache.org/licenses/LICENSE-2.0 + * 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, @@ -13,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.aot.api; import java.lang.reflect.Executable; @@ -25,24 +25,23 @@ import java.lang.reflect.Executable; */ public enum ExecutableMode { - /** - * Only retrieving the {@link Executable} and its metadata is required. - */ - INTROSPECT, + /** + * Only retrieving the {@link Executable} and its metadata is required. + */ + INTROSPECT, - /** - * Full reflection support is required, including the ability to invoke - * the {@link Executable}. - */ - INVOKE; - - /** - * Specify if this mode already includes the specified {@code other} mode. - * @param other the other mode to check - * @return {@code true} if this mode includes the other mode - */ - boolean includes(ExecutableMode other) { - return (other == null || this.ordinal() >= other.ordinal()); - } + /** + * Full reflection support is required, including the ability to invoke + * the {@link Executable}. + */ + INVOKE; + /** + * Specify if this mode already includes the specified {@code other} mode. + * @param other the other mode to check + * @return {@code true} if this mode includes the other mode + */ + boolean includes(ExecutableMode other) { + return (other == null || this.ordinal() >= other.ordinal()); + } } diff --git a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/JdkProxyDescriber.java b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/JdkProxyDescriber.java index 325f544132..b9b98104c0 100644 --- a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/JdkProxyDescriber.java +++ b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/JdkProxyDescriber.java @@ -28,7 +28,6 @@ public class JdkProxyDescriber implements ConditionalDescriber { private final String reachableType; - public JdkProxyDescriber(List proxiedInterfaces, String reachableType) { this.proxiedInterfaces = proxiedInterfaces; this.reachableType = reachableType; @@ -52,7 +51,8 @@ public class JdkProxyDescriber implements ConditionalDescriber { return false; } JdkProxyDescriber that = (JdkProxyDescriber) o; - return Objects.equals(proxiedInterfaces, that.proxiedInterfaces) && Objects.equals(reachableType, that.reachableType); + return Objects.equals(proxiedInterfaces, that.proxiedInterfaces) + && Objects.equals(reachableType, that.reachableType); } @Override diff --git a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/MemberCategory.java b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/MemberCategory.java index fc8659d05f..ddf64b5e30 100644 --- a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/MemberCategory.java +++ b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/MemberCategory.java @@ -1,11 +1,12 @@ /* - * Copyright 2002-2022 the original author or authors. + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 * - * 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 - * - * https://www.apache.org/licenses/LICENSE-2.0 + * 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, @@ -13,13 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.aot.api; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; + /** * Represent predefined {@linkplain Member members} groups. * @@ -29,97 +30,96 @@ import java.lang.reflect.Method; */ public enum MemberCategory { - /** - * A category that represents public {@linkplain Field fields}. - * @see Class#getFields() - */ - PUBLIC_FIELDS, + /** + * A category that represents public {@linkplain Field fields}. + * @see Class#getFields() + */ + PUBLIC_FIELDS, - /** - * A category that represents {@linkplain Class#getDeclaredFields() declared - * fields}, that is all fields defined by the class, but not inherited ones. - * @see Class#getDeclaredFields() - */ - DECLARED_FIELDS, + /** + * A category that represents {@linkplain Class#getDeclaredFields() declared + * fields}, that is all fields defined by the class, but not inherited ones. + * @see Class#getDeclaredFields() + */ + DECLARED_FIELDS, - /** - * A category that defines public {@linkplain Constructor constructors} can - * be introspected, but not invoked. - * @see Class#getConstructors() - * @see ExecutableMode#INTROSPECT - */ - INTROSPECT_PUBLIC_CONSTRUCTORS, + /** + * A category that defines public {@linkplain Constructor constructors} can + * be introspected, but not invoked. + * @see Class#getConstructors() + * @see ExecutableMode#INTROSPECT + */ + INTROSPECT_PUBLIC_CONSTRUCTORS, - /** - * A category that defines {@linkplain Class#getDeclaredConstructors() all - * constructors} can be introspected, but not invoked. - * @see Class#getDeclaredConstructors() - * @see ExecutableMode#INTROSPECT - */ - INTROSPECT_DECLARED_CONSTRUCTORS, + /** + * A category that defines {@linkplain Class#getDeclaredConstructors() all + * constructors} can be introspected, but not invoked. + * @see Class#getDeclaredConstructors() + * @see ExecutableMode#INTROSPECT + */ + INTROSPECT_DECLARED_CONSTRUCTORS, - /** - * A category that defines public {@linkplain Constructor constructors} can - * be invoked. - * @see Class#getConstructors() - * @see ExecutableMode#INVOKE - */ - INVOKE_PUBLIC_CONSTRUCTORS, + /** + * A category that defines public {@linkplain Constructor constructors} can + * be invoked. + * @see Class#getConstructors() + * @see ExecutableMode#INVOKE + */ + INVOKE_PUBLIC_CONSTRUCTORS, - /** - * A category that defines {@linkplain Class#getDeclaredConstructors() all - * constructors} can be invoked. - * @see Class#getDeclaredConstructors() - * @see ExecutableMode#INVOKE - */ - INVOKE_DECLARED_CONSTRUCTORS, + /** + * A category that defines {@linkplain Class#getDeclaredConstructors() all + * constructors} can be invoked. + * @see Class#getDeclaredConstructors() + * @see ExecutableMode#INVOKE + */ + INVOKE_DECLARED_CONSTRUCTORS, - /** - * A category that defines public {@linkplain Method methods}, including - * inherited ones can be introspect, but not invoked. - * @see Class#getMethods() - * @see ExecutableMode#INTROSPECT - */ - INTROSPECT_PUBLIC_METHODS, + /** + * A category that defines public {@linkplain Method methods}, including + * inherited ones can be introspect, but not invoked. + * @see Class#getMethods() + * @see ExecutableMode#INTROSPECT + */ + INTROSPECT_PUBLIC_METHODS, - /** - * A category that defines {@linkplain Class#getDeclaredMethods() all - * methods}, excluding inherited ones can be introspected, but not invoked. - * @see Class#getDeclaredMethods() - * @see ExecutableMode#INTROSPECT - */ - INTROSPECT_DECLARED_METHODS, + /** + * A category that defines {@linkplain Class#getDeclaredMethods() all + * methods}, excluding inherited ones can be introspected, but not invoked. + * @see Class#getDeclaredMethods() + * @see ExecutableMode#INTROSPECT + */ + INTROSPECT_DECLARED_METHODS, - /** - * A category that defines public {@linkplain Method methods}, including - * inherited ones can be invoked. - * @see Class#getMethods() - * @see ExecutableMode#INVOKE - */ - INVOKE_PUBLIC_METHODS, + /** + * A category that defines public {@linkplain Method methods}, including + * inherited ones can be invoked. + * @see Class#getMethods() + * @see ExecutableMode#INVOKE + */ + INVOKE_PUBLIC_METHODS, - /** - * A category that defines {@linkplain Class#getDeclaredMethods() all - * methods}, excluding inherited ones can be invoked. - * @see Class#getDeclaredMethods() - * @see ExecutableMode#INVOKE - */ - INVOKE_DECLARED_METHODS, + /** + * A category that defines {@linkplain Class#getDeclaredMethods() all + * methods}, excluding inherited ones can be invoked. + * @see Class#getDeclaredMethods() + * @see ExecutableMode#INVOKE + */ + INVOKE_DECLARED_METHODS, - /** - * A category that represents public {@linkplain Class#getClasses() inner - * classes}. Contrary to other categories, this does not register any - * particular reflection for them but rather make sure they are available - * via a call to {@link Class#getClasses}. - */ - PUBLIC_CLASSES, - - /** - * A category that represents all {@linkplain Class#getDeclaredClasses() - * inner classes}. Contrary to other categories, this does not register any - * particular reflection for them but rather make sure they are available - * via a call to {@link Class#getDeclaredClasses}. - */ - DECLARED_CLASSES; + /** + * A category that represents public {@linkplain Class#getClasses() inner + * classes}. Contrary to other categories, this does not register any + * particular reflection for them but rather make sure they are available + * via a call to {@link Class#getClasses}. + */ + PUBLIC_CLASSES, + /** + * A category that represents all {@linkplain Class#getDeclaredClasses() + * inner classes}. Contrary to other categories, this does not register any + * particular reflection for them but rather make sure they are available + * via a call to {@link Class#getDeclaredClasses}. + */ + DECLARED_CLASSES; } diff --git a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ResourceBundleDescriber.java b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ResourceBundleDescriber.java index 0e640974aa..9bedbafbeb 100644 --- a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ResourceBundleDescriber.java +++ b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ResourceBundleDescriber.java @@ -31,7 +31,6 @@ public class ResourceBundleDescriber implements ConditionalDescriber { private final String reachableType; - public ResourceBundleDescriber(String name, List locales, String reachableType) { this.name = name; this.locales = locales; diff --git a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ResourcePatternDescriber.java b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ResourcePatternDescriber.java index d52ea4d2b9..f501ee5716 100644 --- a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ResourcePatternDescriber.java +++ b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/ResourcePatternDescriber.java @@ -47,12 +47,9 @@ public class ResourcePatternDescriber implements ConditionalDescriber { String prefix = (this.pattern.startsWith("*") ? ".*" : ""); String suffix = (this.pattern.endsWith("*") ? ".*" : ""); String regex = Arrays.stream(this.pattern.split("\\*")) - .filter(s -> !s.isEmpty()) - .map(Pattern::quote) - .collect(Collectors.joining(".*", prefix, suffix)); + .filter(s -> !s.isEmpty()) + .map(Pattern::quote) + .collect(Collectors.joining(".*", prefix, suffix)); return Pattern.compile(regex); } - - - } diff --git a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/TypeDescriber.java b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/TypeDescriber.java index 37451b6baa..e8fab121e4 100644 --- a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/TypeDescriber.java +++ b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/api/TypeDescriber.java @@ -37,9 +37,13 @@ public class TypeDescriber implements ConditionalDescriber { private final Set memberCategories; - public TypeDescriber(String name, String reachableType, Set fields, - Set constructors, Set methods, - Set memberCategories) { + public TypeDescriber( + String name, + String reachableType, + Set fields, + Set constructors, + Set methods, + Set memberCategories) { this.name = name; this.reachableType = reachableType; this.fields = fields; @@ -48,7 +52,6 @@ public class TypeDescriber implements ConditionalDescriber { this.memberCategories = memberCategories; } - public String getName() { return name; } diff --git a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/AotProcessor.java b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/AotProcessor.java index dfb0257ef1..bfa3350cca 100644 --- a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/AotProcessor.java +++ b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/AotProcessor.java @@ -40,18 +40,22 @@ public class AotProcessor { NativeConfigurationWriter writer = new NativeConfigurationWriter(Paths.get(args[2]), args[4], args[5]); ResourceConfigMetadataRepository resourceRepository = new ResourceConfigMetadataRepository(); - resourceRepository.registerIncludesPatterns(ResourceScanner.INSTANCE.distinctSpiResource().toArray(new String[]{})); - resourceRepository.registerIncludesPatterns(ResourceScanner.INSTANCE.distinctSecurityResource().toArray(new String[]{})); + resourceRepository.registerIncludesPatterns( + ResourceScanner.INSTANCE.distinctSpiResource().toArray(new String[] {})); + resourceRepository.registerIncludesPatterns( + ResourceScanner.INSTANCE.distinctSecurityResource().toArray(new String[] {})); writer.writeResourceConfig(resourceRepository); - ReflectConfigMetadataRepository reflectRepository = new ReflectConfigMetadataRepository(); reflectRepository - .registerSpiExtensionType(new ArrayList<>(ClassSourceScanner.INSTANCE.distinctSpiExtensionClasses(ResourceScanner.INSTANCE.distinctSpiResource()).values())) - .registerAdaptiveType(new ArrayList<>(ClassSourceScanner.INSTANCE.adaptiveClasses().values())) - .registerBeanType(ClassSourceScanner.INSTANCE.scopeModelInitializer()) - .registerConfigType(ClassSourceScanner.INSTANCE.configClasses()) - .registerTypeDescriber(getTypes()); + .registerSpiExtensionType(new ArrayList<>(ClassSourceScanner.INSTANCE + .distinctSpiExtensionClasses(ResourceScanner.INSTANCE.distinctSpiResource()) + .values())) + .registerAdaptiveType(new ArrayList<>( + ClassSourceScanner.INSTANCE.adaptiveClasses().values())) + .registerBeanType(ClassSourceScanner.INSTANCE.scopeModelInitializer()) + .registerConfigType(ClassSourceScanner.INSTANCE.configClasses()) + .registerTypeDescriber(getTypes()); writer.writeReflectionConfig(reflectRepository); ProxyConfigMetadataRepository proxyRepository = new ProxyConfigMetadataRepository(); @@ -61,30 +65,37 @@ public class AotProcessor { private static List getTypes() { List typeDescribers = new ArrayList<>(); - FrameworkModel.defaultModel().defaultApplication().getExtensionLoader(ReflectionTypeDescriberRegistrar.class).getSupportedExtensionInstances().forEach(reflectionTypeDescriberRegistrar -> { - List describers = new ArrayList<>(); - try { - describers = reflectionTypeDescriberRegistrar.getTypeDescribers(); - } catch (Throwable e) { - // The ReflectionTypeDescriberRegistrar implementation classes are shaded, causing some unused classes to be loaded. - // When loading a dependent class may appear that cannot be found, it does not affect. - // ignore - } + FrameworkModel.defaultModel() + .defaultApplication() + .getExtensionLoader(ReflectionTypeDescriberRegistrar.class) + .getSupportedExtensionInstances() + .forEach(reflectionTypeDescriberRegistrar -> { + List describers = new ArrayList<>(); + try { + describers = reflectionTypeDescriberRegistrar.getTypeDescribers(); + } catch (Throwable e) { + // The ReflectionTypeDescriberRegistrar implementation classes are shaded, causing some unused + // classes to be loaded. + // When loading a dependent class may appear that cannot be found, it does not affect. + // ignore + } - typeDescribers.addAll(describers); - }); + typeDescribers.addAll(describers); + }); return typeDescribers; } private static List getProxyDescribers() { List jdkProxyDescribers = new ArrayList<>(); - FrameworkModel.defaultModel().defaultApplication().getExtensionLoader(ProxyDescriberRegistrar.class).getSupportedExtensionInstances().forEach(reflectionTypeDescriberRegistrar -> { - jdkProxyDescribers.addAll(reflectionTypeDescriberRegistrar.getJdkProxyDescribers()); - }); + FrameworkModel.defaultModel() + .defaultApplication() + .getExtensionLoader(ProxyDescriberRegistrar.class) + .getSupportedExtensionInstances() + .forEach(reflectionTypeDescriberRegistrar -> { + jdkProxyDescribers.addAll(reflectionTypeDescriberRegistrar.getJdkProxyDescribers()); + }); return jdkProxyDescribers; } - - } diff --git a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ClassSourceScanner.java b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ClassSourceScanner.java index b3fda54d4a..6653a25473 100644 --- a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ClassSourceScanner.java +++ b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ClassSourceScanner.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.aot.generate; - import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.common.utils.StringUtils; @@ -55,17 +54,22 @@ public class ClassSourceScanner extends JarScanner { */ public List> spiClassesWithAdaptive() { Map> allClasses = getClasses(); - List> spiClasses = new ArrayList<>(allClasses.values()).stream().filter(it -> { - if (null == it) { - return false; - } - Annotation anno = it.getAnnotation(SPI.class); - if (null == anno) { - return false; - } - Optional optional = Arrays.stream(it.getMethods()).filter(it2 -> it2.getAnnotation(Adaptive.class) != null).findAny(); - return optional.isPresent(); - }).collect(Collectors.toList()); + List> spiClasses = new ArrayList<>(allClasses.values()) + .stream() + .filter(it -> { + if (null == it) { + return false; + } + Annotation anno = it.getAnnotation(SPI.class); + if (null == anno) { + return false; + } + Optional optional = Arrays.stream(it.getMethods()) + .filter(it2 -> it2.getAnnotation(Adaptive.class) != null) + .findAny(); + return optional.isPresent(); + }) + .collect(Collectors.toList()); return spiClasses; } @@ -76,7 +80,9 @@ public class ClassSourceScanner extends JarScanner { * @return adaptive class */ public Map> adaptiveClasses() { - List res = spiClassesWithAdaptive().stream().map((c) -> c.getName() + "$Adaptive").collect(Collectors.toList()); + List res = spiClassesWithAdaptive().stream() + .map((c) -> c.getName() + "$Adaptive") + .collect(Collectors.toList()); return forNames(res); } @@ -86,7 +92,9 @@ public class ClassSourceScanner extends JarScanner { * @return configuration class */ public List> configClasses() { - return getClasses().values().stream().filter(c -> AbstractConfig.class.isAssignableFrom(c) && !Modifier.isAbstract(c.getModifiers())).collect(Collectors.toList()); + return getClasses().values().stream() + .filter(c -> AbstractConfig.class.isAssignableFrom(c) && !Modifier.isAbstract(c.getModifiers())) + .collect(Collectors.toList()); } public Map> distinctSpiExtensionClasses(Set spiResource) { @@ -114,15 +122,21 @@ public class ClassSourceScanner extends JarScanner { * For example, the RouterSnapshotSwitcher that needs to be injected when ClusterScopeModelInitializer executes initializeFrameworkModel * @return Beans that need to be injected in advance */ - public List> scopeModelInitializer(){ + public List> scopeModelInitializer() { List> classes = new ArrayList<>(); classes.addAll(FrameworkModel.defaultModel().getBeanFactory().getRegisteredClasses()); - classes.addAll(FrameworkModel.defaultModel().defaultApplication().getBeanFactory().getRegisteredClasses()); - classes.addAll(FrameworkModel.defaultModel().defaultApplication().getDefaultModule().getBeanFactory().getRegisteredClasses()); + classes.addAll(FrameworkModel.defaultModel() + .defaultApplication() + .getBeanFactory() + .getRegisteredClasses()); + classes.addAll(FrameworkModel.defaultModel() + .defaultApplication() + .getDefaultModule() + .getBeanFactory() + .getRegisteredClasses()); return classes.stream().distinct().collect(Collectors.toList()); } - private Map> loadResource(URL resourceUrl) { Map> extensionClasses = new HashMap<>(); try { @@ -151,8 +165,8 @@ public class ClassSourceScanner extends JarScanner { private List getResourceContent(URL resourceUrl) throws IOException { List newContentList = new ArrayList<>(); - try (BufferedReader reader = new BufferedReader( - new InputStreamReader(resourceUrl.openStream(), StandardCharsets.UTF_8))) { + try (BufferedReader reader = + new BufferedReader(new InputStreamReader(resourceUrl.openStream(), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { final int ci = line.indexOf('#'); @@ -169,6 +183,4 @@ public class ClassSourceScanner extends JarScanner { } return newContentList; } - - } diff --git a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ExecutableDescriber.java b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ExecutableDescriber.java index b272a17a2b..8e9bebd7d6 100644 --- a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ExecutableDescriber.java +++ b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ExecutableDescriber.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.aot.generate; - import org.apache.dubbo.aot.api.ExecutableMode; import org.apache.dubbo.aot.api.MemberDescriber; @@ -36,9 +35,13 @@ public class ExecutableDescriber extends MemberDescriber { private final ExecutableMode mode; - public ExecutableDescriber(Constructor constructor, ExecutableMode mode) { - this("", Arrays.stream(constructor.getParameterTypes()).map(Class::getName).collect(Collectors.toList()),mode); + this( + "", + Arrays.stream(constructor.getParameterTypes()) + .map(Class::getName) + .collect(Collectors.toList()), + mode); } public ExecutableDescriber(String name, List parameterTypes, ExecutableMode mode) { @@ -47,7 +50,6 @@ public class ExecutableDescriber extends MemberDescriber { this.mode = mode; } - public List getParameterTypes() { return parameterTypes; } diff --git a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/JarScanner.java b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/JarScanner.java index dc7e480ef5..86fad8ec6a 100644 --- a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/JarScanner.java +++ b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/JarScanner.java @@ -42,7 +42,6 @@ public class JarScanner { private final List resourcePathCache; - protected Map> getClasses() { if (classesCache == null || classesCache.size() == 0) { this.classesCache = forNames(classNameCache.values()); @@ -68,7 +67,6 @@ public class JarScanner { return classes; } - private void scanURL(String prefixName) { try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); @@ -126,7 +124,6 @@ public class JarScanner { } else { resourcePathCache.add(name); } - } } @@ -139,6 +136,8 @@ public class JarScanner { } private String toClassName(String path) { - return path.contains(File.separator) ? path.substring(0, path.length() - 6).replace(File.separator, ".") : path.substring(0, path.length() - 6).replace("/", "."); + return path.contains(File.separator) + ? path.substring(0, path.length() - 6).replace(File.separator, ".") + : path.substring(0, path.length() - 6).replace("/", "."); } } diff --git a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/NativeClassSourceWriter.java b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/NativeClassSourceWriter.java index 2e727fc0d1..042d5ff331 100644 --- a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/NativeClassSourceWriter.java +++ b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/NativeClassSourceWriter.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.aot.generate; -import org.apache.commons.io.FileUtils; import org.apache.dubbo.common.extension.AdaptiveClassCodeGenerator; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.common.utils.StringUtils; @@ -28,6 +27,8 @@ import java.nio.file.Paths; import java.util.List; import java.util.regex.Matcher; +import org.apache.commons.io.FileUtils; + /** * Write the Adaptive bytecode class dynamically generated. */ @@ -45,7 +46,9 @@ public class NativeClassSourceWriter { AdaptiveClassCodeGenerator codeGenerator = new AdaptiveClassCodeGenerator(it, value); String code = codeGenerator.generate(true); try { - String file = generatedSources + File.separator + it.getName().replaceAll("\\.", Matcher.quoteReplacement(File.separator)); + String file = generatedSources + + File.separator + + it.getName().replaceAll("\\.", Matcher.quoteReplacement(File.separator)); String dir = Paths.get(file).getParent().toString(); FileUtils.forceMkdir(new File(dir)); code = LICENSED_STR + code + "\n"; @@ -57,20 +60,20 @@ public class NativeClassSourceWriter { }); } - private static final String LICENSED_STR = "/*\n" + - " * Licensed to the Apache Software Foundation (ASF) under one or more\n" + - " * contributor license agreements. See the NOTICE file distributed with\n" + - " * this work for additional information regarding copyright ownership.\n" + - " * The ASF licenses this file to You under the Apache License, Version 2.0\n" + - " * (the \"License\"); you may not use this file except in compliance with\n" + - " * the License. You may obtain a copy of the License at\n" + - " *\n" + - " * http://www.apache.org/licenses/LICENSE-2.0\n" + - " *\n" + - " * Unless required by applicable law or agreed to in writing, software\n" + - " * distributed under the License is distributed on an \"AS IS\" BASIS,\n" + - " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + - " * See the License for the specific language governing permissions and\n" + - " * limitations under the License.\n" + - " */\n"; + private static final String LICENSED_STR = + "/*\n" + " * Licensed to the Apache Software Foundation (ASF) under one or more\n" + + " * contributor license agreements. See the NOTICE file distributed with\n" + + " * this work for additional information regarding copyright ownership.\n" + + " * The ASF licenses this file to You under the Apache License, Version 2.0\n" + + " * (the \"License\"); you may not use this file except in compliance with\n" + + " * the License. You may obtain a copy of the License at\n" + + " *\n" + + " * http://www.apache.org/licenses/LICENSE-2.0\n" + + " *\n" + + " * Unless required by applicable law or agreed to in writing, software\n" + + " * distributed under the License is distributed on an \"AS IS\" BASIS,\n" + + " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + + " * See the License for the specific language governing permissions and\n" + + " * limitations under the License.\n" + + " */\n"; } diff --git a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/NativeConfigurationWriter.java b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/NativeConfigurationWriter.java index 88770d5484..a4e1fdd353 100644 --- a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/NativeConfigurationWriter.java +++ b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/NativeConfigurationWriter.java @@ -58,7 +58,10 @@ public class NativeConfigurationWriter { private File createIfNecessary(String filename) throws IOException { Path outputDirectory = this.basePath.resolve("META-INF").resolve("native-image"); if (this.groupId != null && this.artifactId != null) { - outputDirectory = outputDirectory.resolve(this.groupId).resolve(this.artifactId).resolve("dubbo"); + outputDirectory = outputDirectory + .resolve(this.groupId) + .resolve(this.artifactId) + .resolve("dubbo"); } outputDirectory.toFile().mkdirs(); File file = outputDirectory.resolve(filename).toFile(); @@ -66,25 +69,19 @@ public class NativeConfigurationWriter { return file; } - public void writeReflectionConfig(ReflectConfigMetadataRepository repository) { - writeTo("reflect-config.json", writer -> - ReflectionConfigWriter.INSTANCE.write(writer, repository)); + writeTo("reflect-config.json", writer -> ReflectionConfigWriter.INSTANCE.write(writer, repository)); } public void writeResourceConfig(ResourceConfigMetadataRepository repository) { - writeTo("resource-config.json", writer -> - ResourceConfigWriter.INSTANCE.write(writer, repository)); + writeTo("resource-config.json", writer -> ResourceConfigWriter.INSTANCE.write(writer, repository)); } public void writeProxyConfig(ProxyConfigMetadataRepository repository) { - writeTo("proxy-config.json", writer -> - ProxyConfigWriter.INSTANCE.write(writer, repository)); + writeTo("proxy-config.json", writer -> ProxyConfigWriter.INSTANCE.write(writer, repository)); } private BasicJsonWriter createJsonWriter(Writer out) { return new BasicJsonWriter(out); } - - } diff --git a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ProxyConfigMetadataRepository.java b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ProxyConfigMetadataRepository.java index 25b89d8844..93a795c08e 100644 --- a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ProxyConfigMetadataRepository.java +++ b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ProxyConfigMetadataRepository.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.aot.generate; - import org.apache.dubbo.aot.api.JdkProxyDescriber; import java.util.LinkedHashSet; @@ -39,11 +38,11 @@ public class ProxyConfigMetadataRepository { } public ProxyConfigMetadataRepository registerProxyDescribers(List describers) { - this.jdkProxyDescribers.addAll(describers.stream().filter(Objects::nonNull).collect(Collectors.toList())); + this.jdkProxyDescribers.addAll( + describers.stream().filter(Objects::nonNull).collect(Collectors.toList())); return this; } - public Set getProxyDescribers() { return jdkProxyDescribers; } diff --git a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ProxyConfigWriter.java b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ProxyConfigWriter.java index ac429341d0..cf0fb808d3 100644 --- a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ProxyConfigWriter.java +++ b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ProxyConfigWriter.java @@ -31,7 +31,8 @@ public class ProxyConfigWriter { public static final ProxyConfigWriter INSTANCE = new ProxyConfigWriter(); public void write(BasicJsonWriter writer, ProxyConfigMetadataRepository repository) { - writer.writeArray(repository.getProxyDescribers().stream().map(this::toAttributes).collect(Collectors.toList())); + writer.writeArray( + repository.getProxyDescribers().stream().map(this::toAttributes).collect(Collectors.toList())); } private Map toAttributes(JdkProxyDescriber describer) { diff --git a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ReflectConfigMetadataRepository.java b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ReflectConfigMetadataRepository.java index 5cb546dbd2..728159ccdd 100644 --- a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ReflectConfigMetadataRepository.java +++ b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ReflectConfigMetadataRepository.java @@ -38,27 +38,41 @@ public class ReflectConfigMetadataRepository { } protected ReflectConfigMetadataRepository registerSpiExtensionType(List> classes) { - types.addAll(classes.stream().filter(Objects::nonNull).map(this::buildTypeDescriberWithConstructor).collect(Collectors.toList())); + types.addAll(classes.stream() + .filter(Objects::nonNull) + .map(this::buildTypeDescriberWithConstructor) + .collect(Collectors.toList())); return this; } protected ReflectConfigMetadataRepository registerAdaptiveType(List> classes) { - types.addAll(classes.stream().filter(Objects::nonNull).map(this::buildTypeDescriberWithConstructor).collect(Collectors.toList())); + types.addAll(classes.stream() + .filter(Objects::nonNull) + .map(this::buildTypeDescriberWithConstructor) + .collect(Collectors.toList())); return this; } protected ReflectConfigMetadataRepository registerBeanType(List> classes) { - types.addAll(classes.stream().filter(Objects::nonNull).map(this::buildTypeDescriberWithConstructor).collect(Collectors.toList())); + types.addAll(classes.stream() + .filter(Objects::nonNull) + .map(this::buildTypeDescriberWithConstructor) + .collect(Collectors.toList())); return this; } protected ReflectConfigMetadataRepository registerConfigType(List> classes) { - types.addAll(classes.stream().filter(Objects::nonNull).map(this::buildTypeDescriberWithConstructor).collect(Collectors.toList())); + types.addAll(classes.stream() + .filter(Objects::nonNull) + .map(this::buildTypeDescriberWithConstructor) + .collect(Collectors.toList())); return this; } private TypeDescriber buildTypeDescriberWithConstructor(Class c) { - Set constructors = Arrays.stream(c.getConstructors()).map((constructor) -> new ExecutableDescriber(constructor, INVOKE)).collect(Collectors.toSet()); + Set constructors = Arrays.stream(c.getConstructors()) + .map((constructor) -> new ExecutableDescriber(constructor, INVOKE)) + .collect(Collectors.toSet()); Set memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.INVOKE_PUBLIC_METHODS); return new TypeDescriber(c.getName(), null, new HashSet<>(), constructors, new HashSet<>(), memberCategories); diff --git a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ReflectionConfigWriter.java b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ReflectionConfigWriter.java index aed6145992..0bfae969e9 100644 --- a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ReflectionConfigWriter.java +++ b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ReflectionConfigWriter.java @@ -60,7 +60,10 @@ public class ReflectionConfigWriter { } private void handleFields(Map attributes, Set fieldDescribers) { - addIfNotEmpty(attributes, "fields", fieldDescribers.stream().map(this::toAttributes).collect(Collectors.toList())); + addIfNotEmpty( + attributes, + "fields", + fieldDescribers.stream().map(this::toAttributes).collect(Collectors.toList())); } private Map toAttributes(FieldDescriber describer) { @@ -70,12 +73,20 @@ public class ReflectionConfigWriter { } private void handleExecutables(Map attributes, Set executableDescribers) { - addIfNotEmpty(attributes, "methods", executableDescribers.stream() - .filter(h -> h.getMode().equals(ExecutableMode.INVOKE)) - .map(this::toAttributes).collect(Collectors.toList())); - addIfNotEmpty(attributes, "queriedMethods", executableDescribers.stream() - .filter(h -> h.getMode().equals(ExecutableMode.INTROSPECT)) - .map(this::toAttributes).collect(Collectors.toList())); + addIfNotEmpty( + attributes, + "methods", + executableDescribers.stream() + .filter(h -> h.getMode().equals(ExecutableMode.INVOKE)) + .map(this::toAttributes) + .collect(Collectors.toList())); + addIfNotEmpty( + attributes, + "queriedMethods", + executableDescribers.stream() + .filter(h -> h.getMode().equals(ExecutableMode.INTROSPECT)) + .map(this::toAttributes) + .collect(Collectors.toList())); } private Map toAttributes(ExecutableDescriber describer) { @@ -87,48 +98,47 @@ public class ReflectionConfigWriter { private void handleCategories(Map attributes, Set categories) { categories.forEach(category -> { - switch (category) { - case PUBLIC_FIELDS: - attributes.put("allPublicFields", true); - break; - case DECLARED_FIELDS: - attributes.put("allDeclaredFields", true); - break; - case INTROSPECT_PUBLIC_CONSTRUCTORS: - attributes.put("queryAllPublicConstructors", true); - break; - case INTROSPECT_DECLARED_CONSTRUCTORS: - attributes.put("queryAllDeclaredConstructors", true); - break; - case INVOKE_PUBLIC_CONSTRUCTORS: - attributes.put("allPublicConstructors", true); - break; - case INVOKE_DECLARED_CONSTRUCTORS: - attributes.put("allDeclaredConstructors", true); - break; - case INTROSPECT_PUBLIC_METHODS: - attributes.put("queryAllPublicMethods", true); - break; - case INTROSPECT_DECLARED_METHODS: - attributes.put("queryAllDeclaredMethods", true); - break; - case INVOKE_PUBLIC_METHODS: - attributes.put("allPublicMethods", true); - break; - case INVOKE_DECLARED_METHODS: - attributes.put("allDeclaredMethods", true); - break; - case PUBLIC_CLASSES: - attributes.put("allPublicClasses", true); - break; - case DECLARED_CLASSES: - attributes.put("allDeclaredClasses", true); - break; - default: - break; - } + switch (category) { + case PUBLIC_FIELDS: + attributes.put("allPublicFields", true); + break; + case DECLARED_FIELDS: + attributes.put("allDeclaredFields", true); + break; + case INTROSPECT_PUBLIC_CONSTRUCTORS: + attributes.put("queryAllPublicConstructors", true); + break; + case INTROSPECT_DECLARED_CONSTRUCTORS: + attributes.put("queryAllDeclaredConstructors", true); + break; + case INVOKE_PUBLIC_CONSTRUCTORS: + attributes.put("allPublicConstructors", true); + break; + case INVOKE_DECLARED_CONSTRUCTORS: + attributes.put("allDeclaredConstructors", true); + break; + case INTROSPECT_PUBLIC_METHODS: + attributes.put("queryAllPublicMethods", true); + break; + case INTROSPECT_DECLARED_METHODS: + attributes.put("queryAllDeclaredMethods", true); + break; + case INVOKE_PUBLIC_METHODS: + attributes.put("allPublicMethods", true); + break; + case INVOKE_DECLARED_METHODS: + attributes.put("allDeclaredMethods", true); + break; + case PUBLIC_CLASSES: + attributes.put("allPublicClasses", true); + break; + case DECLARED_CLASSES: + attributes.put("allDeclaredClasses", true); + break; + default: + break; } - ); + }); } private void addIfNotEmpty(Map attributes, String name, Object value) { diff --git a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceConfigMetadataRepository.java b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceConfigMetadataRepository.java index c44ddc0800..a810d4b0d7 100644 --- a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceConfigMetadataRepository.java +++ b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceConfigMetadataRepository.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.aot.generate; - import org.apache.dubbo.aot.api.ResourceBundleDescriber; import org.apache.dubbo.aot.api.ResourcePatternDescriber; @@ -41,7 +40,7 @@ public class ResourceConfigMetadataRepository { public ResourceConfigMetadataRepository registerIncludesPatterns(String... patterns) { for (String pattern : patterns) { - registerIncludesPattern(new ResourcePatternDescriber(pattern,null)); + registerIncludesPattern(new ResourcePatternDescriber(pattern, null)); } return this; } diff --git a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceConfigWriter.java b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceConfigWriter.java index bb8c8f5816..97141edcc1 100644 --- a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceConfigWriter.java +++ b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceConfigWriter.java @@ -42,15 +42,26 @@ public class ResourceConfigWriter { writer.writeObject(attributes); } - private Map toAttributes(List includes, List excludes) { + private Map toAttributes( + List includes, List excludes) { Map attributes = new LinkedHashMap<>(); - addIfNotEmpty(attributes, "includes", includes.stream().distinct().map(this::toAttributes).collect(Collectors.toList())); - addIfNotEmpty(attributes, "excludes", excludes.stream().distinct().map(this::toAttributes).collect(Collectors.toList())); + addIfNotEmpty( + attributes, + "includes", + includes.stream().distinct().map(this::toAttributes).collect(Collectors.toList())); + addIfNotEmpty( + attributes, + "excludes", + excludes.stream().distinct().map(this::toAttributes).collect(Collectors.toList())); return attributes; } - private void handleResourceBundles(Map attributes, Set resourceBundleDescribers) { - addIfNotEmpty(attributes, "bundles", resourceBundleDescribers.stream().map(this::toAttributes).collect(Collectors.toList())); + private void handleResourceBundles( + Map attributes, Set resourceBundleDescribers) { + addIfNotEmpty( + attributes, + "bundles", + resourceBundleDescribers.stream().map(this::toAttributes).collect(Collectors.toList())); } private Map toAttributes(ResourceBundleDescriber describer) { diff --git a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceScanner.java b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceScanner.java index a2191caf48..bbfebbf508 100644 --- a/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceScanner.java +++ b/dubbo-plugin/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceScanner.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.aot.generate; - import java.util.Set; import java.util.stream.Collectors; @@ -36,11 +35,17 @@ public class ResourceScanner extends JarScanner { public static final ResourceScanner INSTANCE = new ResourceScanner(); public Set distinctSpiResource() { - return getResourcePath().stream().distinct().filter(this::matchedSpiResource).collect(Collectors.toSet()); + return getResourcePath().stream() + .distinct() + .filter(this::matchedSpiResource) + .collect(Collectors.toSet()); } public Set distinctSecurityResource() { - return getResourcePath().stream().distinct().filter(this::matchedSecurityResource).collect(Collectors.toSet()); + return getResourcePath().stream() + .distinct() + .filter(this::matchedSecurityResource) + .collect(Collectors.toSet()); } private boolean matchedSecurityResource(String path) { @@ -49,9 +54,7 @@ public class ResourceScanner extends JarScanner { private boolean matchedSpiResource(String path) { return path.startsWith(DUBBO_INTERNAL_RESOURCE_DIRECTORY) - || path.startsWith(DUBBO_RESOURCE_DIRECTORY) - || path.startsWith(SERVICES_RESOURCE_DIRECTORY); + || path.startsWith(DUBBO_RESOURCE_DIRECTORY) + || path.startsWith(SERVICES_RESOURCE_DIRECTORY); } - - } diff --git a/dubbo-plugin/dubbo-native/src/test/java/org/apache/dubbo/aot/generate/ResourcePatternDescriberTest.java b/dubbo-plugin/dubbo-native/src/test/java/org/apache/dubbo/aot/generate/ResourcePatternDescriberTest.java index f93a953ebf..0a83c924b6 100644 --- a/dubbo-plugin/dubbo-native/src/test/java/org/apache/dubbo/aot/generate/ResourcePatternDescriberTest.java +++ b/dubbo-plugin/dubbo-native/src/test/java/org/apache/dubbo/aot/generate/ResourcePatternDescriberTest.java @@ -17,13 +17,17 @@ package org.apache.dubbo.aot.generate; import org.apache.dubbo.aot.api.ResourcePatternDescriber; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class ResourcePatternDescriberTest { @Test public void testToRegex() { - ResourcePatternDescriber describer = new ResourcePatternDescriber("META-INF/dubbo/internal/org.apache.dubbo.common.extension.ExtensionInjector", null); - Assertions.assertEquals("\\QMETA-INF/dubbo/internal/org.apache.dubbo.common.extension.ExtensionInjector\\E",describer.toRegex().toString()); + ResourcePatternDescriber describer = new ResourcePatternDescriber( + "META-INF/dubbo/internal/org.apache.dubbo.common.extension.ExtensionInjector", null); + Assertions.assertEquals( + "\\QMETA-INF/dubbo/internal/org.apache.dubbo.common.extension.ExtensionInjector\\E", + describer.toRegex().toString()); } } diff --git a/dubbo-plugin/dubbo-plugin-access-log/pom.xml b/dubbo-plugin/dubbo-plugin-access-log/pom.xml index 4ddf4c5cfb..c295f23aff 100644 --- a/dubbo-plugin/dubbo-plugin-access-log/pom.xml +++ b/dubbo-plugin/dubbo-plugin-access-log/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + - dubbo-plugin-access-log - jar + dubbo-plugin-access-log + jar - - - org.apache.dubbo - dubbo-cluster - ${project.version} - - - org.apache.dubbo - dubbo-config-api - ${project.version} - - + + + org.apache.dubbo + dubbo-cluster + ${project.version} + + + org.apache.dubbo + dubbo-config-api + ${project.version} + + diff --git a/dubbo-plugin/dubbo-plugin-access-log/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java b/dubbo-plugin/dubbo-plugin-access-log/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java index 184aaf2001..1469630781 100644 --- a/dubbo-plugin/dubbo-plugin-access-log/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java +++ b/dubbo-plugin/dubbo-plugin-access-log/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java @@ -94,8 +94,7 @@ public class AccessLogFilter implements Filter { * Default constructor initialize demon thread for writing into access log file with names with access log key * defined in url accesslog */ - public AccessLogFilter() { - } + public AccessLogFilter() {} /** * This method logs the access log for service method invocation call. @@ -110,8 +109,10 @@ public class AccessLogFilter implements Filter { String accessLogKey = invoker.getUrl().getParameter(Constants.ACCESS_LOG_KEY); boolean isFixedPath = invoker.getUrl().getParameter(ACCESS_LOG_FIXED_PATH_KEY, true); if (StringUtils.isEmpty(accessLogKey)) { - // Notice that disable accesslog of one service may cause the whole application to stop collecting accesslog. - // It's recommended to use application level configuration to enable or disable accesslog if dynamically configuration is needed . + // Notice that disable accesslog of one service may cause the whole application to stop collecting + // accesslog. + // It's recommended to use application level configuration to enable or disable accesslog if dynamically + // configuration is needed . if (future != null && !future.isCancelled()) { future.cancel(true); logger.info("Access log task cancelled ..."); @@ -120,16 +121,29 @@ public class AccessLogFilter implements Filter { } if (scheduled.compareAndSet(false, true)) { - future = inv.getModuleModel().getApplicationModel().getFrameworkModel().getBeanFactory() - .getBean(FrameworkExecutorRepository.class).getSharedScheduledExecutor() - .scheduleWithFixedDelay(new AccesslogRefreshTask(isFixedPath), LOG_OUTPUT_INTERVAL, LOG_OUTPUT_INTERVAL, TimeUnit.MILLISECONDS); + future = inv.getModuleModel() + .getApplicationModel() + .getFrameworkModel() + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class) + .getSharedScheduledExecutor() + .scheduleWithFixedDelay( + new AccesslogRefreshTask(isFixedPath), + LOG_OUTPUT_INTERVAL, + LOG_OUTPUT_INTERVAL, + TimeUnit.MILLISECONDS); logger.info("Access log task started ..."); } Optional optionalAccessLogData = Optional.empty(); try { optionalAccessLogData = Optional.of(buildAccessLogData(invoker, inv)); } catch (Throwable t) { - logger.warn(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", "Exception in AccessLogFilter of service(" + invoker + " -> " + inv + ")", t); + logger.warn( + CONFIG_FILTER_VALIDATION_EXCEPTION, + "", + "", + "Exception in AccessLogFilter of service(" + invoker + " -> " + inv + ")", + t); } try { return invoker.invoke(inv); @@ -143,15 +157,20 @@ public class AccessLogFilter implements Filter { } private void log(String accessLog, AccessLogData accessLogData, boolean isFixedPath) { - Queue logQueue = ConcurrentHashMapUtils.computeIfAbsent(logEntries, accessLog, k -> new ConcurrentLinkedQueue<>()); + Queue logQueue = + ConcurrentHashMapUtils.computeIfAbsent(logEntries, accessLog, k -> new ConcurrentLinkedQueue<>()); if (logQueue.size() < LOG_MAX_BUFFER) { logQueue.add(accessLogData); } else { - logger.warn(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", "AccessLog buffer is full. Do a force writing to file to clear buffer."); - //just write current logSet to file. + logger.warn( + CONFIG_FILTER_VALIDATION_EXCEPTION, + "", + "", + "AccessLog buffer is full. Do a force writing to file to clear buffer."); + // just write current logSet to file. writeLogSetToFile(accessLog, logQueue, isFixedPath); - //after force writing, add accessLogData to current logSet + // after force writing, add accessLogData to current logSet logQueue.add(accessLogData); } } @@ -162,13 +181,21 @@ public class AccessLogFilter implements Filter { processWithServiceLogger(logSet); } else { if (isFixedPath) { - logger.warn(VULNERABILITY_WARNING, "Change of accesslog file path not allowed. ", "", "Will write to the default location, \" +\n" + - " \"please enable this feature by setting 'accesslog.fixed.path=true' and restart the process. \" +\n" + - " \"We highly recommend to not enable this feature in production for security concerns, \" +\n" + - " \"please be fully aware of the potential risks before doing so!"); + logger.warn( + VULNERABILITY_WARNING, + "Change of accesslog file path not allowed. ", + "", + "Will write to the default location, \" +\n" + + " \"please enable this feature by setting 'accesslog.fixed.path=true' and restart the process. \" +\n" + + " \"We highly recommend to not enable this feature in production for security concerns, \" +\n" + + " \"please be fully aware of the potential risks before doing so!"); processWithServiceLogger(logSet); } else { - logger.warn(VULNERABILITY_WARNING, "Accesslog file path changed to " + accessLog + ", be aware of possible vulnerabilities!", "", ""); + logger.warn( + VULNERABILITY_WARNING, + "Accesslog file path changed to " + accessLog + ", be aware of possible vulnerabilities!", + "", + ""); File file = new File(accessLog); createIfLogDirAbsent(file); if (logger.isDebugEnabled()) { diff --git a/dubbo-plugin/dubbo-plugin-access-log/src/main/java/org/apache/dubbo/rpc/support/AccessLogData.java b/dubbo-plugin/dubbo-plugin-access-log/src/main/java/org/apache/dubbo/rpc/support/AccessLogData.java index a3acfb2efd..ac452956d7 100644 --- a/dubbo-plugin/dubbo-plugin-access-log/src/main/java/org/apache/dubbo/rpc/support/AccessLogData.java +++ b/dubbo-plugin/dubbo-plugin-access-log/src/main/java/org/apache/dubbo/rpc/support/AccessLogData.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.support; - import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.ToStringUtils; import org.apache.dubbo.rpc.Invocation; @@ -79,7 +78,6 @@ public final class AccessLogData { return new AccessLogData(); } - /** * Add version information. * @@ -197,25 +195,26 @@ public final class AccessLogData { return get(SERVICE).toString(); } - public String getLogMessage() { StringBuilder sn = new StringBuilder(); sn.append("[") - .append(LocalDateTime.ofInstant(getInvocationTime().toInstant(), ZoneId.systemDefault()).format(MESSAGE_DATE_FORMATTER)) - .append("] ") - .append("-> ") - .append("[") - .append(LocalDateTime.ofInstant(getOutTime().toInstant(), ZoneId.systemDefault()).format(MESSAGE_DATE_FORMATTER)) - .append("] ") - .append(get(REMOTE_HOST)) - .append(':') - .append(get(REMOTE_PORT)) - .append(" -> ") - .append(get(LOCAL_HOST)) - .append(':') - .append(get(LOCAL_PORT)) - .append(" - "); + .append(LocalDateTime.ofInstant(getInvocationTime().toInstant(), ZoneId.systemDefault()) + .format(MESSAGE_DATE_FORMATTER)) + .append("] ") + .append("-> ") + .append("[") + .append(LocalDateTime.ofInstant(getOutTime().toInstant(), ZoneId.systemDefault()) + .format(MESSAGE_DATE_FORMATTER)) + .append("] ") + .append(get(REMOTE_HOST)) + .append(':') + .append(get(REMOTE_PORT)) + .append(" -> ") + .append(get(LOCAL_HOST)) + .append(':') + .append(get(LOCAL_PORT)) + .append(" - "); String group = get(GROUP) != null ? get(GROUP).toString() : ""; if (StringUtils.isNotEmpty(group)) { @@ -245,7 +244,6 @@ public final class AccessLogData { } sn.append(") "); - Object[] args = get(ARGUMENTS) != null ? (Object[]) get(ARGUMENTS) : null; if (args != null && args.length > 0) { sn.append(ToStringUtils.printToString(args)); @@ -259,7 +257,7 @@ public final class AccessLogData { } private Date getOutTime() { - return (Date)get(OUT_TIME); + return (Date) get(OUT_TIME); } /** @@ -291,5 +289,4 @@ public final class AccessLogData { setTypes(inv.getParameterTypes()); setArguments(inv.getArguments()); } - } diff --git a/dubbo-plugin/dubbo-plugin-access-log/src/test/java/org/apache/dubbo/rpc/filter/AccessLogFilterTest.java b/dubbo-plugin/dubbo-plugin-access-log/src/test/java/org/apache/dubbo/rpc/filter/AccessLogFilterTest.java index 570522af78..6b96546cb3 100644 --- a/dubbo-plugin/dubbo-plugin-access-log/src/test/java/org/apache/dubbo/rpc/filter/AccessLogFilterTest.java +++ b/dubbo-plugin/dubbo-plugin-access-log/src/test/java/org/apache/dubbo/rpc/filter/AccessLogFilterTest.java @@ -27,6 +27,10 @@ import org.apache.dubbo.rpc.support.AccessLogData; import org.apache.dubbo.rpc.support.MockInvocation; import org.apache.dubbo.rpc.support.MyInvoker; +import java.lang.reflect.Field; +import java.util.Map; +import java.util.Queue; + import org.apache.log4j.Appender; import org.apache.log4j.Level; import org.apache.log4j.spi.LoggingEvent; @@ -34,10 +38,6 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; -import java.lang.reflect.Field; -import java.util.Map; -import java.util.Queue; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -102,7 +102,10 @@ class AccessLogFilterTest { ArgumentCaptor argument = ArgumentCaptor.forClass(LoggingEvent.class); verify(appender, times(2)).doAppend(argument.capture()); assertEquals(Level.WARN, argument.getAllValues().get(1).getLevel()); - assertTrue(argument.getAllValues().get(1).getRenderedMessage().contains("Change of accesslog file path not allowed")); + assertTrue(argument.getAllValues() + .get(1) + .getRenderedMessage() + .contains("Change of accesslog file path not allowed")); } finally { customAccessLogFilter.destroy(); realLogger.removeAppender(appender); @@ -140,5 +143,4 @@ class AccessLogFilterTest { e.printStackTrace(); } } - } diff --git a/dubbo-plugin/dubbo-plugin-access-log/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java b/dubbo-plugin/dubbo-plugin-access-log/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java index ae8a69cc5d..ffcabd8d47 100644 --- a/dubbo-plugin/dubbo-plugin-access-log/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java +++ b/dubbo-plugin/dubbo-plugin-access-log/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java @@ -68,11 +68,11 @@ public class MockInvocation extends RpcInvocation { } public Class[] getParameterTypes() { - return new Class[]{String.class}; + return new Class[] {String.class}; } public Object[] getArguments() { - return new Object[]{"aa"}; + return new Object[] {"aa"}; } public Map getAttachments() { @@ -119,9 +119,7 @@ public class MockInvocation extends RpcInvocation { } @Override - public void setServiceModel(ServiceModel serviceModel) { - - } + public void setServiceModel(ServiceModel serviceModel) {} @Override public ServiceModel getServiceModel() { @@ -164,5 +162,4 @@ public class MockInvocation extends RpcInvocation { } return result; } - } diff --git a/dubbo-plugin/dubbo-plugin-access-log/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java b/dubbo-plugin/dubbo-plugin-access-log/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java index f2dbe07081..670a3f7885 100644 --- a/dubbo-plugin/dubbo-plugin-access-log/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java +++ b/dubbo-plugin/dubbo-plugin-access-log/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java @@ -86,5 +86,4 @@ public class MyInvoker implements Invoker { public String toString() { return "MyInvoker.toString()"; } - } diff --git a/dubbo-plugin/dubbo-plugin-classloader-filter/pom.xml b/dubbo-plugin/dubbo-plugin-classloader-filter/pom.xml index 9423bb7945..334ef7244e 100644 --- a/dubbo-plugin/dubbo-plugin-classloader-filter/pom.xml +++ b/dubbo-plugin/dubbo-plugin-classloader-filter/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + - dubbo-plugin-classloader-filter - jar + dubbo-plugin-classloader-filter + jar - - - org.apache.dubbo - dubbo-cluster - ${project.version} - - - org.apache.dubbo - dubbo-config-api - ${project.version} - - + + + org.apache.dubbo + dubbo-cluster + ${project.version} + + + org.apache.dubbo + dubbo-config-api + ${project.version} + + diff --git a/dubbo-plugin/dubbo-plugin-classloader-filter/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ConsumerClassLoaderFilter.java b/dubbo-plugin/dubbo-plugin-classloader-filter/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ConsumerClassLoaderFilter.java index c16b5f3e98..8447906d4c 100644 --- a/dubbo-plugin/dubbo-plugin-classloader-filter/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ConsumerClassLoaderFilter.java +++ b/dubbo-plugin/dubbo-plugin-classloader-filter/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ConsumerClassLoaderFilter.java @@ -35,8 +35,8 @@ public class ConsumerClassLoaderFilter implements ClusterFilter { ClassLoader originClassLoader = Thread.currentThread().getContextClassLoader(); try { Optional.ofNullable(invocation.getServiceModel()) - .map(ServiceModel::getClassLoader) - .ifPresent(Thread.currentThread()::setContextClassLoader); + .map(ServiceModel::getClassLoader) + .ifPresent(Thread.currentThread()::setContextClassLoader); return invoker.invoke(invocation); } finally { Thread.currentThread().setContextClassLoader(originClassLoader); diff --git a/dubbo-plugin/dubbo-plugin-classloader-filter/src/test/java/org/apache/dubbo/rpc/filter/ClassLoaderFilterTest.java b/dubbo-plugin/dubbo-plugin-classloader-filter/src/test/java/org/apache/dubbo/rpc/filter/ClassLoaderFilterTest.java index a133ea327b..041b6e5880 100644 --- a/dubbo-plugin/dubbo-plugin-classloader-filter/src/test/java/org/apache/dubbo/rpc/filter/ClassLoaderFilterTest.java +++ b/dubbo-plugin/dubbo-plugin-classloader-filter/src/test/java/org/apache/dubbo/rpc/filter/ClassLoaderFilterTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.URL; @@ -26,12 +25,12 @@ import org.apache.dubbo.rpc.model.ServiceModel; import org.apache.dubbo.rpc.support.DemoService; import org.apache.dubbo.rpc.support.MyInvoker; +import java.net.URLClassLoader; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.net.URLClassLoader; - class ClassLoaderFilterTest { private ClassLoaderFilter classLoaderFilter = new ClassLoaderFilter(); @@ -41,7 +40,7 @@ class ClassLoaderFilterTest { URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1"); String path = DemoService.class.getResource("/").getPath(); - final URLClassLoader cl = new URLClassLoader(new java.net.URL[]{new java.net.URL("file:" + path)}) { + final URLClassLoader cl = new URLClassLoader(new java.net.URL[] {new java.net.URL("file:" + path)}) { @Override public Class loadClass(String name) throws ClassNotFoundException { try { diff --git a/dubbo-plugin/dubbo-plugin-classloader-filter/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java b/dubbo-plugin/dubbo-plugin-classloader-filter/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java index f2dbe07081..670a3f7885 100644 --- a/dubbo-plugin/dubbo-plugin-classloader-filter/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java +++ b/dubbo-plugin/dubbo-plugin-classloader-filter/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java @@ -86,5 +86,4 @@ public class MyInvoker implements Invoker { public String toString() { return "MyInvoker.toString()"; } - } diff --git a/dubbo-plugin/dubbo-plugin-cluster-mergeable/pom.xml b/dubbo-plugin/dubbo-plugin-cluster-mergeable/pom.xml index 35e33c0c25..09b9e73c01 100644 --- a/dubbo-plugin/dubbo-plugin-cluster-mergeable/pom.xml +++ b/dubbo-plugin/dubbo-plugin-cluster-mergeable/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + - dubbo-plugin-cluster-mergeable - jar + dubbo-plugin-cluster-mergeable + jar - - - org.apache.dubbo - dubbo-cluster - ${project.version} - - + + + org.apache.dubbo + dubbo-cluster + ${project.version} + + diff --git a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/MergeableClusterScopeModelInitializer.java b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/MergeableClusterScopeModelInitializer.java index 43067890bd..1788e4d4ed 100644 --- a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/MergeableClusterScopeModelInitializer.java +++ b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/MergeableClusterScopeModelInitializer.java @@ -25,8 +25,7 @@ import org.apache.dubbo.rpc.model.ScopeModelInitializer; public class MergeableClusterScopeModelInitializer implements ScopeModelInitializer { @Override - public void initializeFrameworkModel(FrameworkModel frameworkModel) { - } + public void initializeFrameworkModel(FrameworkModel frameworkModel) {} @Override public void initializeApplicationModel(ApplicationModel applicationModel) { @@ -35,6 +34,5 @@ public class MergeableClusterScopeModelInitializer implements ScopeModelInitiali } @Override - public void initializeModuleModel(ModuleModel moduleModel) { - } + public void initializeModuleModel(ModuleModel moduleModel) {} } diff --git a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/BooleanArrayMerger.java b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/BooleanArrayMerger.java index 9ff15becb7..cc08d3fb2e 100644 --- a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/BooleanArrayMerger.java +++ b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/BooleanArrayMerger.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.merger; import org.apache.dubbo.common.utils.ArrayUtils; @@ -43,5 +42,4 @@ public class BooleanArrayMerger implements Merger { } return result; } - } diff --git a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/ByteArrayMerger.java b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/ByteArrayMerger.java index ae7685fd48..60d417b9af 100644 --- a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/ByteArrayMerger.java +++ b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/ByteArrayMerger.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.merger; import org.apache.dubbo.common.utils.ArrayUtils; @@ -43,5 +42,4 @@ public class ByteArrayMerger implements Merger { } return result; } - } diff --git a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/CharArrayMerger.java b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/CharArrayMerger.java index ad03f1136f..e4e03f121f 100644 --- a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/CharArrayMerger.java +++ b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/CharArrayMerger.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.merger; import org.apache.dubbo.common.utils.ArrayUtils; diff --git a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/DoubleArrayMerger.java b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/DoubleArrayMerger.java index 9dbe83a035..83f20559e0 100644 --- a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/DoubleArrayMerger.java +++ b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/DoubleArrayMerger.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.merger; import org.apache.dubbo.common.utils.ArrayUtils; @@ -30,7 +29,8 @@ public class DoubleArrayMerger implements Merger { if (ArrayUtils.isEmpty(items)) { return new double[0]; } - return Arrays.stream(items).filter(Objects::nonNull) + return Arrays.stream(items) + .filter(Objects::nonNull) .flatMapToDouble(Arrays::stream) .toArray(); } diff --git a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/FloatArrayMerger.java b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/FloatArrayMerger.java index cf6d635151..1c49117e82 100644 --- a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/FloatArrayMerger.java +++ b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/FloatArrayMerger.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.merger; import org.apache.dubbo.common.utils.ArrayUtils; diff --git a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/IntArrayMerger.java b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/IntArrayMerger.java index da676dec05..cc8603d2f1 100644 --- a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/IntArrayMerger.java +++ b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/IntArrayMerger.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.merger; import org.apache.dubbo.common.utils.ArrayUtils; @@ -30,9 +29,9 @@ public class IntArrayMerger implements Merger { if (ArrayUtils.isEmpty(items)) { return new int[0]; } - return Arrays.stream(items).filter(Objects::nonNull) + return Arrays.stream(items) + .filter(Objects::nonNull) .flatMapToInt(Arrays::stream) .toArray(); } - } diff --git a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/ListMerger.java b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/ListMerger.java index d01f1f3dc1..2364ae325d 100644 --- a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/ListMerger.java +++ b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/ListMerger.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.merger; import org.apache.dubbo.common.utils.ArrayUtils; @@ -34,10 +33,9 @@ public class ListMerger implements Merger> { if (ArrayUtils.isEmpty(items)) { return Collections.emptyList(); } - return Stream.of(items).filter(Objects::nonNull) + return Stream.of(items) + .filter(Objects::nonNull) .flatMap(Collection::stream) .collect(Collectors.toList()); - } - } diff --git a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/LongArrayMerger.java b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/LongArrayMerger.java index 4583e06a35..99e5b28ab5 100644 --- a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/LongArrayMerger.java +++ b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/LongArrayMerger.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.merger; import org.apache.dubbo.common.utils.ArrayUtils; @@ -30,7 +29,8 @@ public class LongArrayMerger implements Merger { if (ArrayUtils.isEmpty(items)) { return new long[0]; } - return Arrays.stream(items).filter(Objects::nonNull) + return Arrays.stream(items) + .filter(Objects::nonNull) .flatMapToLong(Arrays::stream) .toArray(); } diff --git a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/MapMerger.java b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/MapMerger.java index 484c4c2423..eaa863ed64 100644 --- a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/MapMerger.java +++ b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/MapMerger.java @@ -36,5 +36,4 @@ public class MapMerger implements Merger> { Stream.of(items).filter(Objects::nonNull).forEach(result::putAll); return result; } - } diff --git a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/MergerFactory.java b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/MergerFactory.java index 038e38f2b0..3aa07f2ad3 100644 --- a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/MergerFactory.java +++ b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/MergerFactory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.merger; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -69,13 +68,17 @@ public class MergerFactory implements ScopeModelAware { } private void loadMergers() { - Set names = scopeModel.getExtensionLoader(Merger.class) - .getSupportedExtensions(); + Set names = scopeModel.getExtensionLoader(Merger.class).getSupportedExtensions(); for (String name : names) { Merger m = scopeModel.getExtensionLoader(Merger.class).getExtension(name); Class actualTypeArg = getActualTypeArgument(m.getClass()); if (actualTypeArg == null) { - logger.warn(CLUSTER_FAILED_LOAD_MERGER,"load merger config failed","","Failed to get actual type argument from merger " + m.getClass().getName()); + logger.warn( + CLUSTER_FAILED_LOAD_MERGER, + "load merger config failed", + "", + "Failed to get actual type argument from merger " + + m.getClass().getName()); continue; } MERGER_CACHE.putIfAbsent(actualTypeArg, m); @@ -94,7 +97,7 @@ public class MergerFactory implements ScopeModelAware { ParameterizedType mergerType; for (Type it : interfaceTypes) { if (it instanceof ParameterizedType - && (mergerType = ((ParameterizedType) it)).getRawType() == Merger.class) { + && (mergerType = ((ParameterizedType) it)).getRawType() == Merger.class) { Type typeArg = mergerType.getActualTypeArguments()[0]; return TypeUtils.getRawClass(typeArg); } diff --git a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/ShortArrayMerger.java b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/ShortArrayMerger.java index ebf9157d5e..36792d7c52 100644 --- a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/ShortArrayMerger.java +++ b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/merger/ShortArrayMerger.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.merger; import org.apache.dubbo.common.utils.ArrayUtils; diff --git a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableCluster.java b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableCluster.java index 720d21dfad..9bc030729f 100644 --- a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableCluster.java +++ b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableCluster.java @@ -28,5 +28,4 @@ public class MergeableCluster extends AbstractCluster { public AbstractClusterInvoker doJoin(Directory directory) throws RpcException { return new MergeableClusterInvoker(directory); } - } diff --git a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java index 00525d1af5..7ae3796e90 100644 --- a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java +++ b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/main/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvoker.java @@ -51,14 +51,16 @@ import static org.apache.dubbo.rpc.Constants.MERGER_KEY; @SuppressWarnings("unchecked") public class MergeableClusterInvoker extends AbstractClusterInvoker { - private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(MergeableClusterInvoker.class); + private static final ErrorTypeAwareLogger log = + LoggerFactory.getErrorTypeAwareLogger(MergeableClusterInvoker.class); public MergeableClusterInvoker(Directory directory) { super(directory); } @Override - protected Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) throws RpcException { + protected Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) + throws RpcException { String merger = getUrl().getMethodParameter(invocation.getMethodName(), MERGER_KEY); if (ConfigUtils.isEmpty(merger)) { // If a method doesn't have a merger, only invoke one Group for (final Invoker invoker : invokers) { @@ -68,7 +70,7 @@ public class MergeableClusterInvoker extends AbstractClusterInvoker { } catch (RpcException e) { if (e.isNoInvokerAvailableAfterFilter()) { log.debug("No available provider for service" + getUrl().getServiceKey() + " on group " - + invoker.getUrl().getGroup() + ", will continue to try another group."); + + invoker.getUrl().getGroup() + ", will continue to try another group."); } else { throw e; } @@ -80,7 +82,9 @@ public class MergeableClusterInvoker extends AbstractClusterInvoker { Class returnType; try { - returnType = getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes()).getReturnType(); + returnType = getInterface() + .getMethod(invocation.getMethodName(), invocation.getParameterTypes()) + .getReturnType(); } catch (NoSuchMethodException e) { returnType = null; } @@ -101,8 +105,12 @@ public class MergeableClusterInvoker extends AbstractClusterInvoker { try { Result r = asyncResult.get(Integer.MAX_VALUE, TimeUnit.MILLISECONDS); if (r.hasException()) { - log.error(LoggerCodeConstants.CLUSTER_FAILED_GROUP_MERGE, "Invoke " + getGroupDescFromServiceKey(entry.getKey()) + - " failed: " + r.getException().getMessage(), "", r.getException().getMessage()); + log.error( + LoggerCodeConstants.CLUSTER_FAILED_GROUP_MERGE, + "Invoke " + getGroupDescFromServiceKey(entry.getKey()) + " failed: " + + r.getException().getMessage(), + "", + r.getException().getMessage()); } else { resultList.add(r); } @@ -127,8 +135,8 @@ public class MergeableClusterInvoker extends AbstractClusterInvoker { try { method = returnType.getMethod(merger, returnType); } catch (NoSuchMethodException | NullPointerException e) { - throw new RpcException("Can not merge result because missing method [ " + merger + " ] in class [ " + - returnType.getName() + " ]"); + throw new RpcException("Can not merge result because missing method [ " + merger + " ] in class [ " + + returnType.getName() + " ]"); } if (!Modifier.isPublic(method.getModifiers())) { method.setAccessible(true); @@ -136,7 +144,7 @@ public class MergeableClusterInvoker extends AbstractClusterInvoker { result = resultList.remove(0).getValue(); try { if (method.getReturnType() != void.class - && method.getReturnType().isAssignableFrom(result.getClass())) { + && method.getReturnType().isAssignableFrom(result.getClass())) { for (Result r : resultList) { result = method.invoke(result, r.getValue()); } @@ -150,10 +158,14 @@ public class MergeableClusterInvoker extends AbstractClusterInvoker { } } else { Merger resultMerger; - ApplicationModel applicationModel = ScopeModelUtil.getApplicationModel(invocation.getModuleModel().getApplicationModel()); + ApplicationModel applicationModel = ScopeModelUtil.getApplicationModel( + invocation.getModuleModel().getApplicationModel()); if (ConfigUtils.isDefault(merger)) { - resultMerger = applicationModel.getBeanFactory().getBean(MergerFactory.class).getMerger(returnType); + resultMerger = applicationModel + .getBeanFactory() + .getBean(MergerFactory.class) + .getMerger(returnType); } else { resultMerger = applicationModel.getExtensionLoader(Merger.class).getExtension(merger); } @@ -170,7 +182,6 @@ public class MergeableClusterInvoker extends AbstractClusterInvoker { return AsyncRpcResult.newDefaultAsyncResult(result, invocation); } - @Override public Class getInterface() { return directory.getInterface(); diff --git a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/merger/DoubleSumMerger.java b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/merger/DoubleSumMerger.java index 35e210668f..f3e69adaef 100644 --- a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/merger/DoubleSumMerger.java +++ b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/merger/DoubleSumMerger.java @@ -25,7 +25,9 @@ public class DoubleSumMerger implements Merger { @Override public Double merge(Double... items) { - return Arrays.stream(items).filter(Objects::nonNull) - .mapToDouble(Double::doubleValue).sum(); + return Arrays.stream(items) + .filter(Objects::nonNull) + .mapToDouble(Double::doubleValue) + .sum(); } } diff --git a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/merger/FloatSumMerger.java b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/merger/FloatSumMerger.java index 6831327231..0efaf99a3c 100644 --- a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/merger/FloatSumMerger.java +++ b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/merger/FloatSumMerger.java @@ -25,7 +25,6 @@ public class FloatSumMerger implements Merger { @Override public Float merge(Float... items) { - return Arrays.stream(items).filter(Objects::nonNull) - .reduce(0.0F, (f1, f2) -> f1 + f2); + return Arrays.stream(items).filter(Objects::nonNull).reduce(0.0F, (f1, f2) -> f1 + f2); } } diff --git a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/merger/IntSumMerger.java b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/merger/IntSumMerger.java index e3551d26d2..703ee77507 100644 --- a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/merger/IntSumMerger.java +++ b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/merger/IntSumMerger.java @@ -25,7 +25,9 @@ public class IntSumMerger implements Merger { @Override public Integer merge(Integer... items) { - return Arrays.stream(items).filter(Objects::nonNull) - .mapToInt(Integer::intValue).sum(); + return Arrays.stream(items) + .filter(Objects::nonNull) + .mapToInt(Integer::intValue) + .sum(); } } diff --git a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/merger/LongSumMerger.java b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/merger/LongSumMerger.java index 5e8e139c31..aaca3236c7 100644 --- a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/merger/LongSumMerger.java +++ b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/merger/LongSumMerger.java @@ -25,7 +25,9 @@ public class LongSumMerger implements Merger { @Override public Long merge(Long... items) { - return Arrays.stream(items).filter(Objects::nonNull) - .mapToLong(Long::longValue).sum(); + return Arrays.stream(items) + .filter(Objects::nonNull) + .mapToLong(Long::longValue) + .sum(); } } diff --git a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/merger/ResultMergerTest.java b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/merger/ResultMergerTest.java index 0ea163b7cd..8606ce322c 100644 --- a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/merger/ResultMergerTest.java +++ b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/merger/ResultMergerTest.java @@ -17,12 +17,7 @@ package org.apache.dubbo.rpc.cluster.merger; import org.apache.dubbo.rpc.cluster.Merger; -import org.apache.dubbo.rpc.cluster.merger.ArrayMerger; -import org.apache.dubbo.rpc.cluster.merger.MergerFactory; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; import java.lang.reflect.Array; import java.util.ArrayList; @@ -36,9 +31,13 @@ import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + class ResultMergerTest { private MergerFactory mergerFactory; - + @BeforeEach public void setup() { mergerFactory = new MergerFactory(); @@ -243,25 +242,31 @@ class ResultMergerTest { */ @Test void testListMerger() { - List list1 = new ArrayList() {{ - add(null); - add("1"); - add("2"); - }}; - List list2 = new ArrayList() {{ - add("3"); - add("4"); - }}; + List list1 = new ArrayList() { + { + add(null); + add("1"); + add("2"); + } + }; + List list2 = new ArrayList() { + { + add("3"); + add("4"); + } + }; List result = mergerFactory.getMerger(List.class).merge(list1, list2, null); Assertions.assertEquals(5, result.size()); - ArrayList expected = new ArrayList() {{ - add(null); - add("1"); - add("2"); - add("3"); - add("4"); - }}; + ArrayList expected = new ArrayList() { + { + add(null); + add("1"); + add("2"); + add("3"); + add("4"); + } + }; Assertions.assertEquals(expected, result); result = mergerFactory.getMerger(List.class).merge(null); @@ -276,22 +281,28 @@ class ResultMergerTest { */ @Test void testMapArrayMerger() { - Map mapOne = new HashMap() {{ - put("11", 222); - put("223", 11); - }}; - Map mapTwo = new HashMap() {{ - put("3333", 3232); - put("444", 2323); - }}; + Map mapOne = new HashMap() { + { + put("11", 222); + put("223", 11); + } + }; + Map mapTwo = new HashMap() { + { + put("3333", 3232); + put("444", 2323); + } + }; Map result = mergerFactory.getMerger(Map.class).merge(mapOne, mapTwo, null); Assertions.assertEquals(4, result.size()); - Map mergedResult = new HashMap() {{ - put("11", 222); - put("223", 11); - put("3333", 3232); - put("444", 2323); - }}; + Map mergedResult = new HashMap() { + { + put("11", 222); + put("223", 11); + put("3333", 3232); + put("444", 2323); + } + }; Assertions.assertEquals(mergedResult, result); result = mergerFactory.getMerger(Map.class).merge(null); @@ -327,28 +338,34 @@ class ResultMergerTest { */ @Test void testSetMerger() { - Set set1 = new HashSet() {{ - add(null); - add("1"); - add("2"); - }}; - - Set set2 = new HashSet() {{ - add("2"); - add("3"); - }}; - - Set result = mergerFactory.getMerger(Set.class).merge(set1, set2, null); - - Assertions.assertEquals(4, result.size()); - Assertions.assertEquals(new HashSet() { + Set set1 = new HashSet() { { add(null); add("1"); add("2"); + } + }; + + Set set2 = new HashSet() { + { + add("2"); add("3"); } - }, result); + }; + + Set result = mergerFactory.getMerger(Set.class).merge(set1, set2, null); + + Assertions.assertEquals(4, result.size()); + Assertions.assertEquals( + new HashSet() { + { + add(null); + add("1"); + add("2"); + add("3"); + } + }, + result); result = mergerFactory.getMerger(Set.class).merge(null); Assertions.assertEquals(0, result.size()); @@ -387,7 +404,7 @@ class ResultMergerTest { Merger merger = ApplicationModel.defaultModel().getExtension(Merger.class, "intsum"); Assertions.assertEquals(5050, merger.merge(intArr)); - intArr = new Integer[]{}; + intArr = new Integer[] {}; Assertions.assertEquals(0, merger.merge(intArr)); } @@ -396,11 +413,12 @@ class ResultMergerTest { */ @Test void testDoubleSumMerger() { - Double[] doubleArr = DoubleStream.iterate(1, v -> ++v).limit(100).boxed().toArray(Double[]::new); + Double[] doubleArr = + DoubleStream.iterate(1, v -> ++v).limit(100).boxed().toArray(Double[]::new); Merger merger = ApplicationModel.defaultModel().getExtension(Merger.class, "doublesum"); Assertions.assertEquals(5050, merger.merge(doubleArr)); - doubleArr = new Double[]{}; + doubleArr = new Double[] {}; Assertions.assertEquals(0, merger.merge(doubleArr)); } @@ -413,7 +431,7 @@ class ResultMergerTest { Merger merger = ApplicationModel.defaultModel().getExtension(Merger.class, "floatsum"); Assertions.assertEquals(5050, merger.merge(floatArr)); - floatArr = new Float[]{}; + floatArr = new Float[] {}; Assertions.assertEquals(0, merger.merge(floatArr)); } @@ -426,7 +444,7 @@ class ResultMergerTest { Merger merger = ApplicationModel.defaultModel().getExtension(Merger.class, "longsum"); Assertions.assertEquals(5050, merger.merge(longArr)); - longArr = new Long[]{}; + longArr = new Long[] {}; Assertions.assertEquals(0, merger.merge(longArr)); } @@ -439,7 +457,7 @@ class ResultMergerTest { Merger merger = ApplicationModel.defaultModel().getExtension(Merger.class, "intany"); Assertions.assertNotNull(merger.merge(intArr)); - intArr = new Integer[]{}; + intArr = new Integer[] {}; Assertions.assertNull(merger.merge(intArr)); } @@ -452,7 +470,7 @@ class ResultMergerTest { Merger merger = ApplicationModel.defaultModel().getExtension(Merger.class, "intfirst"); Assertions.assertEquals(1, merger.merge(intArr)); - intArr = new Integer[]{}; + intArr = new Integer[] {}; Assertions.assertNull(merger.merge(intArr)); } } diff --git a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/support/Menu.java b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/support/Menu.java index cfd5a55bc6..93e5e46eb9 100644 --- a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/support/Menu.java +++ b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/support/Menu.java @@ -26,8 +26,7 @@ class Menu { private Map> menus = new HashMap>(); - public Menu() { - } + public Menu() {} public Menu(Map> menus) { for (Map.Entry> entry : menus.entrySet()) { @@ -62,5 +61,4 @@ class Menu { addMenu(entry.getKey(), entry.getValue()); } } - } diff --git a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/support/MenuService.java b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/support/MenuService.java index f1b6f7566f..d1f2b9ba8d 100644 --- a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/support/MenuService.java +++ b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/support/MenuService.java @@ -23,5 +23,4 @@ public interface MenuService { Menu getMenu(); void addMenu(String menu, List items); - } diff --git a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java index 1c20308bfe..97e07c76f3 100644 --- a/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java +++ b/dubbo-plugin/dubbo-plugin-cluster-mergeable/src/test/java/org/apache/dubbo/rpc/cluster/support/MergeableClusterInvokerTest.java @@ -27,9 +27,6 @@ import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; import java.lang.reflect.Proxy; import java.util.ArrayList; @@ -39,6 +36,10 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.rpc.Constants.MERGER_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -97,7 +98,6 @@ class MergeableClusterInvokerTest { firstInvoker = mock(Invoker.class); secondInvoker = mock(Invoker.class); invocation = mock(RpcInvocation.class); - } @Test @@ -107,36 +107,38 @@ class MergeableClusterInvokerTest { url = url.addParameter(MERGER_KEY, ".merge"); given(invocation.getMethodName()).willReturn("getMenu"); - given(invocation.getParameterTypes()).willReturn(new Class[]{}); - given(invocation.getArguments()).willReturn(new Object[]{}); + given(invocation.getParameterTypes()).willReturn(new Class[] {}); + given(invocation.getArguments()).willReturn(new Object[] {}); given(invocation.getObjectAttachments()).willReturn(new HashMap<>()); given(invocation.getInvoker()).willReturn(firstInvoker); - firstInvoker = (Invoker) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{Invoker.class}, (proxy, method, args) -> { - if ("getUrl".equals(method.getName())) { - return url.addParameter(GROUP_KEY, "first"); - } - if ("getInterface".equals(method.getName())) { - return MenuService.class; - } - if ("invoke".equals(method.getName())) { - return AsyncRpcResult.newDefaultAsyncResult(firstMenu, invocation); - } - return null; - }); + firstInvoker = (Invoker) Proxy.newProxyInstance( + getClass().getClassLoader(), new Class[] {Invoker.class}, (proxy, method, args) -> { + if ("getUrl".equals(method.getName())) { + return url.addParameter(GROUP_KEY, "first"); + } + if ("getInterface".equals(method.getName())) { + return MenuService.class; + } + if ("invoke".equals(method.getName())) { + return AsyncRpcResult.newDefaultAsyncResult(firstMenu, invocation); + } + return null; + }); - secondInvoker = (Invoker) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{Invoker.class}, (proxy, method, args) -> { - if ("getUrl".equals(method.getName())) { - return url.addParameter(GROUP_KEY, "second"); - } - if ("getInterface".equals(method.getName())) { - return MenuService.class; - } - if ("invoke".equals(method.getName())) { - return AsyncRpcResult.newDefaultAsyncResult(secondMenu, invocation); - } - return null; - }); + secondInvoker = (Invoker) Proxy.newProxyInstance( + getClass().getClassLoader(), new Class[] {Invoker.class}, (proxy, method, args) -> { + if ("getUrl".equals(method.getName())) { + return url.addParameter(GROUP_KEY, "second"); + } + if ("getInterface".equals(method.getName())) { + return MenuService.class; + } + if ("invoke".equals(method.getName())) { + return AsyncRpcResult.newDefaultAsyncResult(secondMenu, invocation); + } + return null; + }); given(directory.list(invocation)).willReturn(new ArrayList() { @@ -183,8 +185,8 @@ class MergeableClusterInvokerTest { }; given(invocation.getMethodName()).willReturn("addMenu"); - given(invocation.getParameterTypes()).willReturn(new Class[]{String.class, List.class}); - given(invocation.getArguments()).willReturn(new Object[]{menu, menuItems}); + given(invocation.getParameterTypes()).willReturn(new Class[] {String.class, List.class}); + given(invocation.getArguments()).willReturn(new Object[] {menu, menuItems}); given(invocation.getObjectAttachments()).willReturn(new HashMap<>()); given(invocation.getInvoker()).willReturn(firstInvoker); @@ -214,7 +216,6 @@ class MergeableClusterInvokerTest { Result result = mergeableClusterInvoker.invoke(invocation); Assertions.assertNull(result.getValue()); - } @Test @@ -232,36 +233,38 @@ class MergeableClusterInvokerTest { }; given(invocation.getMethodName()).willReturn("addMenu"); - given(invocation.getParameterTypes()).willReturn(new Class[]{String.class, List.class}); - given(invocation.getArguments()).willReturn(new Object[]{menu, menuItems}); + given(invocation.getParameterTypes()).willReturn(new Class[] {String.class, List.class}); + given(invocation.getArguments()).willReturn(new Object[] {menu, menuItems}); given(invocation.getObjectAttachments()).willReturn(new HashMap<>()); given(invocation.getInvoker()).willReturn(firstInvoker); - firstInvoker = (Invoker) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{Invoker.class}, (proxy, method, args) -> { - if ("getUrl".equals(method.getName())) { - return url.addParameter(GROUP_KEY, "first"); - } - if ("getInterface".equals(method.getName())) { - return MenuService.class; - } - if ("invoke".equals(method.getName())) { - return AsyncRpcResult.newDefaultAsyncResult(firstMenu, invocation); - } - return null; - }); + firstInvoker = (Invoker) Proxy.newProxyInstance( + getClass().getClassLoader(), new Class[] {Invoker.class}, (proxy, method, args) -> { + if ("getUrl".equals(method.getName())) { + return url.addParameter(GROUP_KEY, "first"); + } + if ("getInterface".equals(method.getName())) { + return MenuService.class; + } + if ("invoke".equals(method.getName())) { + return AsyncRpcResult.newDefaultAsyncResult(firstMenu, invocation); + } + return null; + }); - secondInvoker = (Invoker) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{Invoker.class}, (proxy, method, args) -> { - if ("getUrl".equals(method.getName())) { - return url.addParameter(GROUP_KEY, "second"); - } - if ("getInterface".equals(method.getName())) { - return MenuService.class; - } - if ("invoke".equals(method.getName())) { - return AsyncRpcResult.newDefaultAsyncResult(secondMenu, invocation); - } - return null; - }); + secondInvoker = (Invoker) Proxy.newProxyInstance( + getClass().getClassLoader(), new Class[] {Invoker.class}, (proxy, method, args) -> { + if ("getUrl".equals(method.getName())) { + return url.addParameter(GROUP_KEY, "second"); + } + if ("getInterface".equals(method.getName())) { + return MenuService.class; + } + if ("invoke".equals(method.getName())) { + return AsyncRpcResult.newDefaultAsyncResult(secondMenu, invocation); + } + return null; + }); given(directory.list(invocation)).willReturn(new ArrayList() { @@ -279,7 +282,6 @@ class MergeableClusterInvokerTest { Result result = mergeableClusterInvoker.invoke(invocation); Assertions.assertNull(result.getValue()); - } @Test @@ -293,8 +295,8 @@ class MergeableClusterInvokerTest { }; given(invocation.getMethodName()).willReturn("addMenu"); - given(invocation.getParameterTypes()).willReturn(new Class[]{String.class, List.class}); - given(invocation.getArguments()).willReturn(new Object[]{menu, menuItems}); + given(invocation.getParameterTypes()).willReturn(new Class[] {String.class, List.class}); + given(invocation.getArguments()).willReturn(new Object[] {menu, menuItems}); given(invocation.getObjectAttachments()).willReturn(new HashMap<>()); given(invocation.getInvoker()).willReturn(firstInvoker); @@ -302,13 +304,15 @@ class MergeableClusterInvokerTest { given(firstInvoker.getInterface()).willReturn(MenuService.class); given(firstInvoker.invoke(invocation)).willReturn(new AppResponse()); given(firstInvoker.isAvailable()).willReturn(true); - given(firstInvoker.invoke(invocation)).willThrow(new RpcException(RpcException.NO_INVOKER_AVAILABLE_AFTER_FILTER)); + given(firstInvoker.invoke(invocation)) + .willThrow(new RpcException(RpcException.NO_INVOKER_AVAILABLE_AFTER_FILTER)); given(secondInvoker.getUrl()).willReturn(url.addParameter(GROUP_KEY, "second")); given(secondInvoker.getInterface()).willReturn(MenuService.class); given(secondInvoker.invoke(invocation)).willReturn(new AppResponse()); given(secondInvoker.isAvailable()).willReturn(true); - given(secondInvoker.invoke(invocation)).willThrow(new RpcException(RpcException.NO_INVOKER_AVAILABLE_AFTER_FILTER)); + given(secondInvoker.invoke(invocation)) + .willThrow(new RpcException(RpcException.NO_INVOKER_AVAILABLE_AFTER_FILTER)); given(directory.list(invocation)).willReturn(new ArrayList() { @@ -348,8 +352,8 @@ class MergeableClusterInvokerTest { }; given(invocation.getMethodName()).willReturn("addMenu"); - given(invocation.getParameterTypes()).willReturn(new Class[]{String.class, List.class}); - given(invocation.getArguments()).willReturn(new Object[]{menu, menuItems}); + given(invocation.getParameterTypes()).willReturn(new Class[] {String.class, List.class}); + given(invocation.getArguments()).willReturn(new Object[] {menu, menuItems}); given(invocation.getObjectAttachments()).willReturn(new HashMap<>()); given(invocation.getInvoker()).willReturn(firstInvoker); @@ -396,8 +400,8 @@ class MergeableClusterInvokerTest { url = url.addParameter(MERGER_KEY, ".merge"); given(invocation.getMethodName()).willReturn("getMenu"); - given(invocation.getParameterTypes()).willReturn(new Class[]{}); - given(invocation.getArguments()).willReturn(new Object[]{}); + given(invocation.getParameterTypes()).willReturn(new Class[] {}); + given(invocation.getArguments()).willReturn(new Object[] {}); given(invocation.getObjectAttachments()).willReturn(new HashMap<>()); given(invocation.getInvoker()).willReturn(firstInvoker); @@ -442,40 +446,41 @@ class MergeableClusterInvokerTest { url = url.addParameter(MERGER_KEY, "default"); given(invocation.getMethodName()).willReturn("getMenu"); - given(invocation.getParameterTypes()).willReturn(new Class[]{}); - given(invocation.getArguments()).willReturn(new Object[]{}); + given(invocation.getParameterTypes()).willReturn(new Class[] {}); + given(invocation.getArguments()).willReturn(new Object[] {}); given(invocation.getObjectAttachments()).willReturn(new HashMap<>()); given(invocation.getInvoker()).willReturn(firstInvoker); // mock ApplicationModel given(invocation.getModuleModel()).willReturn(moduleModel); given(invocation.getModuleModel().getApplicationModel()).willReturn(ApplicationModel.defaultModel()); + firstInvoker = (Invoker) Proxy.newProxyInstance( + getClass().getClassLoader(), new Class[] {Invoker.class}, (proxy, method, args) -> { + if ("getUrl".equals(method.getName())) { + return url.addParameter(GROUP_KEY, "first"); + } + if ("getInterface".equals(method.getName())) { + return MenuService.class; + } + if ("invoke".equals(method.getName())) { + return AsyncRpcResult.newDefaultAsyncResult(firstMenu, invocation); + } + return null; + }); - firstInvoker = (Invoker) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{Invoker.class}, (proxy, method, args) -> { - if ("getUrl".equals(method.getName())) { - return url.addParameter(GROUP_KEY, "first"); - } - if ("getInterface".equals(method.getName())) { - return MenuService.class; - } - if ("invoke".equals(method.getName())) { - return AsyncRpcResult.newDefaultAsyncResult(firstMenu, invocation); - } - return null; - }); - - secondInvoker = (Invoker) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{Invoker.class}, (proxy, method, args) -> { - if ("getUrl".equals(method.getName())) { - return url.addParameter(GROUP_KEY, "second"); - } - if ("getInterface".equals(method.getName())) { - return MenuService.class; - } - if ("invoke".equals(method.getName())) { - return AsyncRpcResult.newDefaultAsyncResult(secondMenu, invocation); - } - return null; - }); + secondInvoker = (Invoker) Proxy.newProxyInstance( + getClass().getClassLoader(), new Class[] {Invoker.class}, (proxy, method, args) -> { + if ("getUrl".equals(method.getName())) { + return url.addParameter(GROUP_KEY, "second"); + } + if ("getInterface".equals(method.getName())) { + return MenuService.class; + } + if ("invoke".equals(method.getName())) { + return AsyncRpcResult.newDefaultAsyncResult(secondMenu, invocation); + } + return null; + }); given(directory.list(invocation)).willReturn(new ArrayList() { @@ -502,8 +507,8 @@ class MergeableClusterInvokerTest { @Test void testDestroy() { given(invocation.getMethodName()).willReturn("getMenu"); - given(invocation.getParameterTypes()).willReturn(new Class[]{}); - given(invocation.getArguments()).willReturn(new Object[]{}); + given(invocation.getParameterTypes()).willReturn(new Class[] {}); + given(invocation.getArguments()).willReturn(new Object[] {}); given(invocation.getObjectAttachments()).willReturn(new HashMap<>()); given(invocation.getInvoker()).willReturn(firstInvoker); diff --git a/dubbo-plugin/dubbo-plugin-context/pom.xml b/dubbo-plugin/dubbo-plugin-context/pom.xml index aeb355c5a8..e0a296d1e4 100644 --- a/dubbo-plugin/dubbo-plugin-context/pom.xml +++ b/dubbo-plugin/dubbo-plugin-context/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + - dubbo-plugin-context - jar + dubbo-plugin-context + jar - - - org.apache.dubbo - dubbo-cluster - ${project.version} - - - org.apache.dubbo - dubbo-config-api - ${project.version} - - + + + org.apache.dubbo + dubbo-cluster + ${project.version} + + + org.apache.dubbo + dubbo-config-api + ${project.version} + + diff --git a/dubbo-plugin/dubbo-plugin-context/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ConsumerContextFilter.java b/dubbo-plugin/dubbo-plugin-context/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ConsumerContextFilter.java index a5a6dcf534..674e4a61e4 100644 --- a/dubbo-plugin/dubbo-plugin-context/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ConsumerContextFilter.java +++ b/dubbo-plugin/dubbo-plugin-context/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ConsumerContextFilter.java @@ -56,16 +56,17 @@ public class ConsumerContextFilter implements ClusterFilter, ClusterFilter.Liste private Set supportedSelectors; public ConsumerContextFilter(ApplicationModel applicationModel) { - ExtensionLoader selectorExtensionLoader = applicationModel.getExtensionLoader(PenetrateAttachmentSelector.class); + ExtensionLoader selectorExtensionLoader = + applicationModel.getExtensionLoader(PenetrateAttachmentSelector.class); supportedSelectors = selectorExtensionLoader.getSupportedExtensionInstances(); } @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { RpcContext.getServiceContext() - .setInvoker(invoker) - .setInvocation(invocation) - .setLocalAddress(NetUtils.getLocalHost(), 0); + .setInvoker(invoker) + .setInvocation(invocation) + .setLocalAddress(NetUtils.getLocalHost(), 0); RpcContext context = RpcContext.getClientAttachment(); context.setAttachment(REMOTE_APPLICATION_KEY, invoker.getUrl().getApplication()); @@ -75,15 +76,18 @@ public class ConsumerContextFilter implements ClusterFilter, ClusterFilter.Liste if (CollectionUtils.isNotEmpty(supportedSelectors)) { for (PenetrateAttachmentSelector supportedSelector : supportedSelectors) { - Map selected = supportedSelector.select(invocation, RpcContext.getClientAttachment(), RpcContext.getServerAttachment()); + Map selected = supportedSelector.select( + invocation, RpcContext.getClientAttachment(), RpcContext.getServerAttachment()); if (CollectionUtils.isNotEmptyMap(selected)) { ((RpcInvocation) invocation).addObjectAttachments(selected); } } } else { - ((RpcInvocation) invocation).addObjectAttachments(RpcContext.getServerAttachment().getObjectAttachments()); + ((RpcInvocation) invocation) + .addObjectAttachments(RpcContext.getServerAttachment().getObjectAttachments()); } - Map contextAttachments = RpcContext.getClientAttachment().getObjectAttachments(); + Map contextAttachments = + RpcContext.getClientAttachment().getObjectAttachments(); if (CollectionUtils.isNotEmptyMap(contextAttachments)) { /** * invocation.addAttachmentsIfAbsent(context){@link RpcInvocation#addAttachmentsIfAbsent(Map)}should not be used here, @@ -106,9 +110,12 @@ public class ConsumerContextFilter implements ClusterFilter, ClusterFilter.Liste TimeoutCountDown timeoutCountDown = (TimeoutCountDown) countDown; if (timeoutCountDown.isExpired()) { - return AsyncRpcResult.newDefaultAsyncResult(new RpcException(RpcException.TIMEOUT_TERMINATE, - "No time left for making the following call: " + invocation.getServiceName() + "." - + RpcUtils.getMethodName(invocation) + ", terminate directly."), invocation); + return AsyncRpcResult.newDefaultAsyncResult( + new RpcException( + RpcException.TIMEOUT_TERMINATE, + "No time left for making the following call: " + invocation.getServiceName() + "." + + RpcUtils.getMethodName(invocation) + ", terminate directly."), + invocation); } } } @@ -135,14 +142,15 @@ public class ConsumerContextFilter implements ClusterFilter, ClusterFilter.Liste RpcInvocation rpcInvocation = (RpcInvocation) invocation; if (rpcInvocation.getInvokeMode() != null) { // clear service context if not in sync mode - if (rpcInvocation.getInvokeMode() == InvokeMode.ASYNC || rpcInvocation.getInvokeMode() == InvokeMode.FUTURE) { + if (rpcInvocation.getInvokeMode() == InvokeMode.ASYNC + || rpcInvocation.getInvokeMode() == InvokeMode.FUTURE) { RpcContext.removeServiceContext(); } } } // server context must not be removed because user might use it on callback. - // So the clear of is delayed til the start of the next rpc call, see RpcContext.removeServerContext(); in invoke() above + // So the clear of is delayed til the start of the next rpc call, see RpcContext.removeServerContext(); in + // invoke() above // RpcContext.removeServerContext(); } - } diff --git a/dubbo-plugin/dubbo-plugin-context/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java b/dubbo-plugin/dubbo-plugin-context/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java index 5320b1894e..5a955a958d 100644 --- a/dubbo-plugin/dubbo-plugin-context/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java +++ b/dubbo-plugin/dubbo-plugin-context/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java @@ -16,21 +16,21 @@ */ package org.apache.dubbo.rpc.filter; +import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.CollectionUtils; -import org.apache.dubbo.rpc.model.ApplicationModel; -import org.apache.dubbo.rpc.support.RpcUtils; -import org.apache.dubbo.rpc.TimeoutCountDown; -import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.PenetrateAttachmentSelector; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.PenetrateAttachmentSelector; +import org.apache.dubbo.rpc.TimeoutCountDown; +import org.apache.dubbo.rpc.model.ApplicationModel; +import org.apache.dubbo.rpc.support.RpcUtils; import java.util.HashMap; import java.util.HashSet; @@ -53,7 +53,6 @@ import static org.apache.dubbo.rpc.Constants.ASYNC_KEY; import static org.apache.dubbo.rpc.Constants.FORCE_USE_TAG; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; - /** * ContextFilter set the provider RpcContext with invoker, invocation, local port it is using and host for * current execution thread. @@ -65,7 +64,8 @@ public class ContextFilter implements Filter, Filter.Listener { private final Set supportedSelectors; public ContextFilter(ApplicationModel applicationModel) { - ExtensionLoader selectorExtensionLoader = applicationModel.getExtensionLoader(PenetrateAttachmentSelector.class); + ExtensionLoader selectorExtensionLoader = + applicationModel.getExtensionLoader(PenetrateAttachmentSelector.class); supportedSelectors = selectorExtensionLoader.getSupportedExtensionInstances(); } @@ -102,11 +102,10 @@ public class ContextFilter implements Filter, Filter.Listener { attachments = newAttach; } - RpcContext.getServiceContext().setInvoker(invoker) - .setInvocation(invocation); + RpcContext.getServiceContext().setInvoker(invoker).setInvocation(invocation); RpcContext context = RpcContext.getServerAttachment(); -// .setAttachments(attachments) // merged from dubbox + // .setAttachments(attachments) // merged from dubbox if (context.getLocalAddress() == null) { context.setLocalAddress(invoker.getUrl().getHost(), invoker.getUrl().getPort()); } @@ -121,7 +120,9 @@ public class ContextFilter implements Filter, Filter.Listener { long timeout = RpcUtils.getTimeout(invocation, -1); if (timeout != -1) { // pass to next hop - RpcContext.getServerAttachment().setObjectAttachment(TIME_COUNTDOWN_KEY, TimeoutCountDown.newCountDown(timeout, TimeUnit.MILLISECONDS)); + RpcContext.getServerAttachment() + .setObjectAttachment( + TIME_COUNTDOWN_KEY, TimeoutCountDown.newCountDown(timeout, TimeUnit.MILLISECONDS)); } // merged from dubbox @@ -155,13 +156,15 @@ public class ContextFilter implements Filter, Filter.Listener { // pass attachments to result if (CollectionUtils.isNotEmpty(supportedSelectors)) { for (PenetrateAttachmentSelector supportedSelector : supportedSelectors) { - Map selected = supportedSelector.selectReverse(invocation, RpcContext.getClientResponseContext(), RpcContext.getServerResponseContext()); + Map selected = supportedSelector.selectReverse( + invocation, RpcContext.getClientResponseContext(), RpcContext.getServerResponseContext()); if (CollectionUtils.isNotEmptyMap(selected)) { appResponse.addObjectAttachments(selected); } } } else { - appResponse.addObjectAttachments(RpcContext.getClientResponseContext().getObjectAttachments()); + appResponse.addObjectAttachments( + RpcContext.getClientResponseContext().getObjectAttachments()); } appResponse.addObjectAttachments(RpcContext.getServerResponseContext().getObjectAttachments()); removeContext(); diff --git a/dubbo-plugin/dubbo-plugin-context/src/test/java/org/apache/dubbo/rpc/filter/ContextFilterTest.java b/dubbo-plugin/dubbo-plugin-context/src/test/java/org/apache/dubbo/rpc/filter/ContextFilterTest.java index 6bab37aab6..bdb39c6447 100644 --- a/dubbo-plugin/dubbo-plugin-context/src/test/java/org/apache/dubbo/rpc/filter/ContextFilterTest.java +++ b/dubbo-plugin/dubbo-plugin-context/src/test/java/org/apache/dubbo/rpc/filter/ContextFilterTest.java @@ -49,8 +49,8 @@ class ContextFilterTest { void testSetContext() { invocation = mock(Invocation.class); given(invocation.getMethodName()).willReturn("$enumlength"); - given(invocation.getParameterTypes()).willReturn(new Class[]{Enum.class}); - given(invocation.getArguments()).willReturn(new Object[]{"hello"}); + given(invocation.getParameterTypes()).willReturn(new Class[] {Enum.class}); + given(invocation.getArguments()).willReturn(new Object[] {"hello"}); given(invocation.getObjectAttachments()).willReturn(null); invoker = mock(Invoker.class); diff --git a/dubbo-plugin/dubbo-plugin-context/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java b/dubbo-plugin/dubbo-plugin-context/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java index ae8a69cc5d..ffcabd8d47 100644 --- a/dubbo-plugin/dubbo-plugin-context/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java +++ b/dubbo-plugin/dubbo-plugin-context/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java @@ -68,11 +68,11 @@ public class MockInvocation extends RpcInvocation { } public Class[] getParameterTypes() { - return new Class[]{String.class}; + return new Class[] {String.class}; } public Object[] getArguments() { - return new Object[]{"aa"}; + return new Object[] {"aa"}; } public Map getAttachments() { @@ -119,9 +119,7 @@ public class MockInvocation extends RpcInvocation { } @Override - public void setServiceModel(ServiceModel serviceModel) { - - } + public void setServiceModel(ServiceModel serviceModel) {} @Override public ServiceModel getServiceModel() { @@ -164,5 +162,4 @@ public class MockInvocation extends RpcInvocation { } return result; } - } diff --git a/dubbo-plugin/dubbo-plugin-context/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java b/dubbo-plugin/dubbo-plugin-context/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java index f2dbe07081..670a3f7885 100644 --- a/dubbo-plugin/dubbo-plugin-context/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java +++ b/dubbo-plugin/dubbo-plugin-context/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java @@ -86,5 +86,4 @@ public class MyInvoker implements Invoker { public String toString() { return "MyInvoker.toString()"; } - } diff --git a/dubbo-plugin/dubbo-plugin-generic-invoke/pom.xml b/dubbo-plugin/dubbo-plugin-generic-invoke/pom.xml index 05e37ea69c..39665670ef 100644 --- a/dubbo-plugin/dubbo-plugin-generic-invoke/pom.xml +++ b/dubbo-plugin/dubbo-plugin-generic-invoke/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + - dubbo-plugin-generic-invoke - jar + dubbo-plugin-generic-invoke + jar - - - org.apache.dubbo - dubbo-cluster - ${project.version} - - - org.apache.dubbo - dubbo-config-api - ${project.version} - - + + + org.apache.dubbo + dubbo-cluster + ${project.version} + + + org.apache.dubbo + dubbo-config-api + ${project.version} + + diff --git a/dubbo-plugin/dubbo-plugin-generic-invoke/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java b/dubbo-plugin/dubbo-plugin-generic-invoke/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java index e9cb1cc816..c06450b578 100644 --- a/dubbo-plugin/dubbo-plugin-generic-invoke/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java +++ b/dubbo-plugin/dubbo-plugin-generic-invoke/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java @@ -86,9 +86,9 @@ public class GenericFilter implements Filter, Filter.Listener, ScopeModelAware { @Override public Result invoke(Invoker invoker, Invocation inv) throws RpcException { if ((inv.getMethodName().equals($INVOKE) || inv.getMethodName().equals($INVOKE_ASYNC)) - && inv.getArguments() != null - && inv.getArguments().length == 3 - && !GenericService.class.isAssignableFrom(invoker.getInterface())) { + && inv.getArguments() != null + && inv.getArguments().length == 3 + && !GenericService.class.isAssignableFrom(invoker.getInterface())) { String name = ((String) inv.getArguments()[0]).trim(); String[] types = (String[]) inv.getArguments()[1]; Object[] args = (Object[]) inv.getArguments()[2]; @@ -104,8 +104,8 @@ public class GenericFilter implements Filter, Filter.Listener, ScopeModelAware { } if (args.length != types.length) { - throw new RpcException("GenericFilter#invoke args.length != types.length, please check your " - + "params"); + throw new RpcException( + "GenericFilter#invoke args.length != types.length, please check your " + "params"); } String generic = inv.getAttachment(GENERIC_KEY); @@ -114,26 +114,34 @@ public class GenericFilter implements Filter, Filter.Listener, ScopeModelAware { } if (StringUtils.isEmpty(generic) - || ProtocolUtils.isDefaultGenericSerialization(generic) - || ProtocolUtils.isGenericReturnRawResult(generic)) { + || ProtocolUtils.isDefaultGenericSerialization(generic) + || ProtocolUtils.isGenericReturnRawResult(generic)) { try { args = PojoUtils.realize(args, params, method.getGenericParameterTypes()); } catch (Exception e) { - logger.error(LoggerCodeConstants.PROTOCOL_ERROR_DESERIALIZE, "", "", - "Deserialize generic invocation failed. ServiceKey: " + inv.getTargetServiceUniqueName(), e); + logger.error( + LoggerCodeConstants.PROTOCOL_ERROR_DESERIALIZE, + "", + "", + "Deserialize generic invocation failed. ServiceKey: " + + inv.getTargetServiceUniqueName(), + e); throw new RpcException(e); } } else if (ProtocolUtils.isGsonGenericSerialization(generic)) { args = getGsonGenericArgs(args, method.getGenericParameterTypes()); } else if (ProtocolUtils.isJavaGenericSerialization(generic)) { - Configuration configuration = ApplicationModel.ofNullable(applicationModel).modelEnvironment().getConfiguration(); + Configuration configuration = ApplicationModel.ofNullable(applicationModel) + .modelEnvironment() + .getConfiguration(); if (!configuration.getBoolean(CommonConstants.ENABLE_NATIVE_JAVA_GENERIC_SERIALIZE, false)) { - String notice = "Trigger the safety barrier! " + - "Native Java Serializer is not allowed by default." + - "This means currently maybe being attacking by others. " + - "If you are sure this is a mistake, " + - "please set `" + CommonConstants.ENABLE_NATIVE_JAVA_GENERIC_SERIALIZE + "` enable in configuration! " + - "Before doing so, please make sure you have configure JEP290 to prevent serialization attack."; + String notice = "Trigger the safety barrier! " + + "Native Java Serializer is not allowed by default." + + "This means currently maybe being attacking by others. " + + "If you are sure this is a mistake, " + + "please set `" + + CommonConstants.ENABLE_NATIVE_JAVA_GENERIC_SERIALIZE + "` enable in configuration! " + + "Before doing so, please make sure you have configure JEP290 to prevent serialization attack."; logger.error(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", notice); throw new RpcException(new IllegalStateException(notice)); } @@ -141,20 +149,20 @@ public class GenericFilter implements Filter, Filter.Listener, ScopeModelAware { for (int i = 0; i < args.length; i++) { if (byte[].class == args[i].getClass()) { try (UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream((byte[]) args[i])) { - args[i] = applicationModel.getExtensionLoader(Serialization.class) - .getExtension(GENERIC_SERIALIZATION_NATIVE_JAVA) - .deserialize(null, is).readObject(); + args[i] = applicationModel + .getExtensionLoader(Serialization.class) + .getExtension(GENERIC_SERIALIZATION_NATIVE_JAVA) + .deserialize(null, is) + .readObject(); } catch (Exception e) { throw new RpcException("Deserialize argument [" + (i + 1) + "] failed.", e); } } else { - throw new RpcException( - "Generic serialization [" + - GENERIC_SERIALIZATION_NATIVE_JAVA + - "] only support message type " + - byte[].class + - " and your message type is " + - args[i].getClass()); + throw new RpcException("Generic serialization [" + GENERIC_SERIALIZATION_NATIVE_JAVA + + "] only support message type " + + byte[].class + + " and your message type is " + + args[i].getClass()); } } } else if (ProtocolUtils.isBeanGenericSerialization(generic)) { @@ -163,13 +171,11 @@ public class GenericFilter implements Filter, Filter.Listener, ScopeModelAware { if (args[i] instanceof JavaBeanDescriptor) { args[i] = JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor) args[i]); } else { - throw new RpcException( - "Generic serialization [" + - GENERIC_SERIALIZATION_BEAN + - "] only support message type " + - JavaBeanDescriptor.class.getName() + - " and your message type is " + - args[i].getClass().getName()); + throw new RpcException("Generic serialization [" + GENERIC_SERIALIZATION_BEAN + + "] only support message type " + + JavaBeanDescriptor.class.getName() + + " and your message type is " + + args[i].getClass().getName()); } } } @@ -177,28 +183,36 @@ public class GenericFilter implements Filter, Filter.Listener, ScopeModelAware { // as proto3 only accept one protobuf parameter if (args.length == 1 && args[0] instanceof String) { try (UnsafeByteArrayInputStream is = - new UnsafeByteArrayInputStream(((String) args[0]).getBytes())) { - args[0] = applicationModel.getExtensionLoader(Serialization.class) - .getExtension(GENERIC_SERIALIZATION_PROTOBUF) - .deserialize(null, is).readObject(method.getParameterTypes()[0]); + new UnsafeByteArrayInputStream(((String) args[0]).getBytes())) { + args[0] = applicationModel + .getExtensionLoader(Serialization.class) + .getExtension(GENERIC_SERIALIZATION_PROTOBUF) + .deserialize(null, is) + .readObject(method.getParameterTypes()[0]); } catch (Exception e) { throw new RpcException("Deserialize argument failed.", e); } } else { - throw new RpcException( - "Generic serialization [" + - GENERIC_SERIALIZATION_PROTOBUF + - "] only support one " + String.class.getName() + - " argument and your message size is " + - args.length + " and type is" + - args[0].getClass().getName()); + throw new RpcException("Generic serialization [" + GENERIC_SERIALIZATION_PROTOBUF + + "] only support one " + + String.class.getName() + " argument and your message size is " + + args.length + + " and type is" + args[0].getClass().getName()); } } - RpcInvocation rpcInvocation = new RpcInvocation(inv.getTargetServiceUniqueName(), - invoker.getUrl().getServiceModel(), method.getName(), invoker.getInterface().getName(), invoker.getUrl().getProtocolServiceKey(), - method.getParameterTypes(), args, inv.getObjectAttachments(), - inv.getInvoker(), inv.getAttributes(), inv instanceof RpcInvocation ? ((RpcInvocation) inv).getInvokeMode() : null); + RpcInvocation rpcInvocation = new RpcInvocation( + inv.getTargetServiceUniqueName(), + invoker.getUrl().getServiceModel(), + method.getName(), + invoker.getInterface().getName(), + invoker.getUrl().getProtocolServiceKey(), + method.getParameterTypes(), + args, + inv.getObjectAttachments(), + inv.getInvoker(), + inv.getAttributes(), + inv instanceof RpcInvocation ? ((RpcInvocation) inv).getInvokeMode() : null); return invoker.invoke(rpcInvocation); } catch (NoSuchMethodException | ClassNotFoundException e) { @@ -209,20 +223,23 @@ public class GenericFilter implements Filter, Filter.Listener, ScopeModelAware { } private Object[] getGsonGenericArgs(final Object[] args, Type[] types) { - return IntStream.range(0, args.length).mapToObj(i -> { - if (args[i] == null) { - return null; - } - if (!(args[i] instanceof String)) { - throw new RpcException("When using GSON to deserialize generic dubbo request arguments, the arguments must be of type String"); - } - String str = args[i].toString(); - try { - return GsonUtils.fromJson(str, types[i]); - } catch (RuntimeException ex) { - throw new RpcException(ex.getMessage()); - } - }).toArray(); + return IntStream.range(0, args.length) + .mapToObj(i -> { + if (args[i] == null) { + return null; + } + if (!(args[i] instanceof String)) { + throw new RpcException( + "When using GSON to deserialize generic dubbo request arguments, the arguments must be of type String"); + } + String str = args[i].toString(); + try { + return GsonUtils.fromJson(str, types[i]); + } catch (RuntimeException ex) { + throw new RpcException(ex.getMessage()); + } + }) + .toArray(); } private String getGenericValueFromRpcContext() { @@ -233,8 +250,9 @@ public class GenericFilter implements Filter, Filter.Listener, ScopeModelAware { return generic; } - public Method findMethodByMethodSignature(Class clazz, String methodName, String[] parameterTypes, ServiceModel serviceModel) - throws NoSuchMethodException, ClassNotFoundException { + public Method findMethodByMethodSignature( + Class clazz, String methodName, String[] parameterTypes, ServiceModel serviceModel) + throws NoSuchMethodException, ClassNotFoundException { Method method; if (parameterTypes == null) { List finded = new ArrayList<>(); @@ -247,8 +265,9 @@ public class GenericFilter implements Filter, Filter.Listener, ScopeModelAware { throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz); } if (finded.size() > 1) { - String msg = String.format("Not unique method for method name(%s) in class(%s), find %d methods.", - methodName, clazz.getName(), finded.size()); + String msg = String.format( + "Not unique method for method name(%s) in class(%s), find %d methods.", + methodName, clazz.getName(), finded.size()); throw new IllegalStateException(msg); } method = finded.get(0); @@ -269,7 +288,8 @@ public class GenericFilter implements Filter, Filter.Listener, ScopeModelAware { } } if (serviceModel != null) { - MethodDescriptor methodDescriptor = serviceModel.getServiceModel().getMethod(methodName, types); + MethodDescriptor methodDescriptor = + serviceModel.getServiceModel().getMethod(methodName, types); if (methodDescriptor == null) { throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz); } @@ -284,28 +304,30 @@ public class GenericFilter implements Filter, Filter.Listener, ScopeModelAware { @Override public void onResponse(Result appResponse, Invoker invoker, Invocation inv) { if ((inv.getMethodName().equals($INVOKE) || inv.getMethodName().equals($INVOKE_ASYNC)) - && inv.getArguments() != null - && inv.getArguments().length == 3 - && !GenericService.class.isAssignableFrom(invoker.getInterface())) { + && inv.getArguments() != null + && inv.getArguments().length == 3 + && !GenericService.class.isAssignableFrom(invoker.getInterface())) { String generic = inv.getAttachment(GENERIC_KEY); if (StringUtils.isBlank(generic)) { generic = getGenericValueFromRpcContext(); } - if (appResponse.hasException() && - Dubbo2CompactUtils.isEnabled() && Dubbo2GenericExceptionUtils.isGenericExceptionClassLoaded()) { + if (appResponse.hasException() + && Dubbo2CompactUtils.isEnabled() + && Dubbo2GenericExceptionUtils.isGenericExceptionClassLoaded()) { Throwable appException = appResponse.getException(); if (appException instanceof GenericException) { GenericException tmp = (GenericException) appException; - GenericException recreated = Dubbo2GenericExceptionUtils.newGenericException(tmp.getMessage(), tmp.getCause(), - tmp.getExceptionClass(), tmp.getExceptionMessage()); + GenericException recreated = Dubbo2GenericExceptionUtils.newGenericException( + tmp.getMessage(), tmp.getCause(), tmp.getExceptionClass(), tmp.getExceptionMessage()); if (recreated != null) { appException = recreated; } appException.setStackTrace(tmp.getStackTrace()); } - if (!(Dubbo2GenericExceptionUtils.getGenericExceptionClass().isAssignableFrom(appException.getClass()))) { + if (!(Dubbo2GenericExceptionUtils.getGenericExceptionClass() + .isAssignableFrom(appException.getClass()))) { GenericException recreated = Dubbo2GenericExceptionUtils.newGenericException(appException); if (recreated != null) { appException = recreated; @@ -319,28 +341,33 @@ public class GenericFilter implements Filter, Filter.Listener, ScopeModelAware { if (ProtocolUtils.isJavaGenericSerialization(generic)) { try { UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(512); - applicationModel.getExtensionLoader(Serialization.class).getExtension(GENERIC_SERIALIZATION_NATIVE_JAVA) - .serialize(null, os).writeObject(appResponse.getValue()); + applicationModel + .getExtensionLoader(Serialization.class) + .getExtension(GENERIC_SERIALIZATION_NATIVE_JAVA) + .serialize(null, os) + .writeObject(appResponse.getValue()); appResponse.setValue(os.toByteArray()); } catch (IOException e) { throw new RpcException( - "Generic serialization [" + - GENERIC_SERIALIZATION_NATIVE_JAVA + - "] serialize result failed.", e); + "Generic serialization [" + GENERIC_SERIALIZATION_NATIVE_JAVA + + "] serialize result failed.", + e); } } else if (ProtocolUtils.isBeanGenericSerialization(generic)) { appResponse.setValue(JavaBeanSerializeUtil.serialize(appResponse.getValue(), JavaBeanAccessor.METHOD)); } else if (ProtocolUtils.isProtobufGenericSerialization(generic)) { try { UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(512); - applicationModel.getExtensionLoader(Serialization.class) - .getExtension(GENERIC_SERIALIZATION_PROTOBUF) - .serialize(null, os).writeObject(appResponse.getValue()); + applicationModel + .getExtensionLoader(Serialization.class) + .getExtension(GENERIC_SERIALIZATION_PROTOBUF) + .serialize(null, os) + .writeObject(appResponse.getValue()); appResponse.setValue(os.toString()); } catch (IOException e) { - throw new RpcException("Generic serialization [" + - GENERIC_SERIALIZATION_PROTOBUF + - "] serialize result failed.", e); + throw new RpcException( + "Generic serialization [" + GENERIC_SERIALIZATION_PROTOBUF + "] serialize result failed.", + e); } } else if (ProtocolUtils.isGsonGenericSerialization(generic)) { appResponse.setValue(GsonUtils.toJson(appResponse.getValue())); @@ -351,7 +378,5 @@ public class GenericFilter implements Filter, Filter.Listener, ScopeModelAware { } @Override - public void onError(Throwable t, Invoker invoker, Invocation invocation) { - - } + public void onError(Throwable t, Invoker invoker, Invocation invocation) {} } diff --git a/dubbo-plugin/dubbo-plugin-generic-invoke/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java b/dubbo-plugin/dubbo-plugin-generic-invoke/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java index 65c8bd16e8..e4be336a69 100644 --- a/dubbo-plugin/dubbo-plugin-generic-invoke/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java +++ b/dubbo-plugin/dubbo-plugin-generic-invoke/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java @@ -59,7 +59,8 @@ public class GenericImplFilter implements Filter, Filter.Listener { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(GenericImplFilter.class); - private static final Class[] GENERIC_PARAMETER_TYPES = new Class[]{String.class, String[].class, Object[].class}; + private static final Class[] GENERIC_PARAMETER_TYPES = + new Class[] {String.class, String[].class, Object[].class}; private static final String GENERIC_IMPL_MARKER = "GENERIC_IMPL"; @@ -108,7 +109,7 @@ public class GenericImplFilter implements Filter, Filter.Listener { } invocation2.setParameterTypes(GENERIC_PARAMETER_TYPES); invocation2.setParameterTypesDesc(GENERIC_PARAMETER_DESC); - invocation2.setArguments(new Object[]{methodName, types, args}); + invocation2.setArguments(new Object[] {methodName, types, args}); return invoker.invoke(invocation2); } // making a generic call to a normal service @@ -125,19 +126,22 @@ public class GenericImplFilter implements Filter, Filter.Listener { } else if (ProtocolUtils.isBeanGenericSerialization(generic)) { for (Object arg : args) { if (arg != null && !(arg instanceof JavaBeanDescriptor)) { - error(generic, JavaBeanDescriptor.class.getName(), arg.getClass().getName()); + error( + generic, + JavaBeanDescriptor.class.getName(), + arg.getClass().getName()); } } } - invocation.setAttachment( - GENERIC_KEY, invoker.getUrl().getParameter(GENERIC_KEY)); + invocation.setAttachment(GENERIC_KEY, invoker.getUrl().getParameter(GENERIC_KEY)); } return invoker.invoke(invocation); } private void error(String generic, String expected, String actual) throws RpcException { - throw new RpcException("Generic serialization [" + generic + "] only support message type " + expected + " and your message type is " + actual); + throw new RpcException("Generic serialization [" + generic + "] only support message type " + expected + + " and your message type is " + actual); } @Override @@ -151,8 +155,9 @@ public class GenericImplFilter implements Filter, Filter.Listener { Object value = appResponse.getValue(); try { Class invokerInterface = invoker.getInterface(); - if (!$INVOKE.equals(methodName) && !$INVOKE_ASYNC.equals(methodName) - && invokerInterface.isAssignableFrom(GenericService.class)) { + if (!$INVOKE.equals(methodName) + && !$INVOKE_ASYNC.equals(methodName) + && invokerInterface.isAssignableFrom(GenericService.class)) { try { // find the real interface from url String realInterface = invoker.getUrl().getParameter(Constants.INTERFACE); @@ -169,7 +174,9 @@ public class GenericImplFilter implements Filter, Filter.Listener { } else if (value instanceof JavaBeanDescriptor) { appResponse.setValue(JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor) value)); } else { - throw new RpcException("The type of result value is " + value.getClass().getName() + " other than " + JavaBeanDescriptor.class.getName() + ", and the result is " + value); + throw new RpcException("The type of result value is " + + value.getClass().getName() + " other than " + JavaBeanDescriptor.class.getName() + + ", and the result is " + value); } } else { Type[] types = ReflectUtils.getReturnTypes(method); @@ -178,24 +185,33 @@ public class GenericImplFilter implements Filter, Filter.Listener { } catch (NoSuchMethodException e) { throw new RpcException(e.getMessage(), e); } - } else if (Dubbo2CompactUtils.isEnabled() && Dubbo2GenericExceptionUtils.isGenericExceptionClassLoaded() - && Dubbo2GenericExceptionUtils.getGenericExceptionClass().isAssignableFrom(appResponse.getException().getClass())) { + } else if (Dubbo2CompactUtils.isEnabled() + && Dubbo2GenericExceptionUtils.isGenericExceptionClassLoaded() + && Dubbo2GenericExceptionUtils.getGenericExceptionClass() + .isAssignableFrom(appResponse.getException().getClass())) { // TODO we should cast if is apache GenericException or not? - org.apache.dubbo.rpc.service.GenericException exception = (org.apache.dubbo.rpc.service.GenericException) appResponse.getException(); + org.apache.dubbo.rpc.service.GenericException exception = + (org.apache.dubbo.rpc.service.GenericException) appResponse.getException(); try { String className = exception.getExceptionClass(); - DefaultSerializeClassChecker classChecker = moduleModel.getApplicationModel() - .getFrameworkModel().getBeanFactory().getBean(DefaultSerializeClassChecker.class); - Class clazz = classChecker.loadClass(Thread.currentThread().getContextClassLoader(), className); + DefaultSerializeClassChecker classChecker = moduleModel + .getApplicationModel() + .getFrameworkModel() + .getBeanFactory() + .getBean(DefaultSerializeClassChecker.class); + Class clazz = + classChecker.loadClass(Thread.currentThread().getContextClassLoader(), className); Throwable targetException = null; Throwable lastException = null; try { - targetException = (Throwable) clazz.getDeclaredConstructor().newInstance(); + targetException = + (Throwable) clazz.getDeclaredConstructor().newInstance(); } catch (Throwable e) { lastException = e; for (Constructor constructor : clazz.getConstructors()) { try { - targetException = (Throwable) constructor.newInstance(new Object[constructor.getParameterTypes().length]); + targetException = (Throwable) + constructor.newInstance(new Object[constructor.getParameterTypes().length]); break; } catch (Throwable e1) { lastException = e1; @@ -217,28 +233,29 @@ public class GenericImplFilter implements Filter, Filter.Listener { throw lastException; } } catch (Throwable e) { - throw new RpcException("Can not deserialize exception " + exception.getExceptionClass() + ", message: " + exception.getExceptionMessage(), e); + throw new RpcException( + "Can not deserialize exception " + exception.getExceptionClass() + ", message: " + + exception.getExceptionMessage(), + e); } } } } @Override - public void onError(Throwable t, Invoker invoker, Invocation invocation) { - - } + public void onError(Throwable t, Invoker invoker, Invocation invocation) {} private boolean isCallingGenericImpl(String generic, Invocation invocation) { return ProtocolUtils.isGeneric(generic) - && (!$INVOKE.equals(invocation.getMethodName()) && !$INVOKE_ASYNC.equals(invocation.getMethodName())) - && invocation instanceof RpcInvocation; + && (!$INVOKE.equals(invocation.getMethodName()) && !$INVOKE_ASYNC.equals(invocation.getMethodName())) + && invocation instanceof RpcInvocation; } private boolean isMakingGenericCall(String generic, Invocation invocation) { - return (invocation.getMethodName().equals($INVOKE) || invocation.getMethodName().equals($INVOKE_ASYNC)) - && invocation.getArguments() != null - && invocation.getArguments().length == 3 - && ProtocolUtils.isGeneric(generic); + return (invocation.getMethodName().equals($INVOKE) + || invocation.getMethodName().equals($INVOKE_ASYNC)) + && invocation.getArguments() != null + && invocation.getArguments().length == 3 + && ProtocolUtils.isGeneric(generic); } - } diff --git a/dubbo-plugin/dubbo-plugin-generic-invoke/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java b/dubbo-plugin/dubbo-plugin-generic-invoke/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java index 17f26e1005..5ef6f985bb 100644 --- a/dubbo-plugin/dubbo-plugin-generic-invoke/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java +++ b/dubbo-plugin/dubbo-plugin-generic-invoke/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.java @@ -28,14 +28,14 @@ import org.apache.dubbo.rpc.service.GenericService; import org.apache.dubbo.rpc.support.DemoService; import org.apache.dubbo.rpc.support.Person; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; import static org.apache.dubbo.common.constants.CommonConstants.ENABLE_NATIVE_JAVA_GENERIC_SERIALIZE; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; @@ -55,13 +55,16 @@ class GenericFilterTest { person.put("name", "dubbo"); person.put("age", 10); - RpcInvocation invocation = new RpcInvocation($INVOKE, GenericService.class.getName(), "", genericInvoke.getParameterTypes(), - new Object[]{"getPerson", new String[]{Person.class.getCanonicalName()}, new Object[]{person}}); + RpcInvocation invocation = new RpcInvocation( + $INVOKE, GenericService.class.getName(), "", genericInvoke.getParameterTypes(), new Object[] { + "getPerson", new String[] {Person.class.getCanonicalName()}, new Object[] {person} + }); - URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + - "accesslog=true&group=dubbo&version=1.1"); + URL url = URL.valueOf( + "test://test:11/org.apache.dubbo.rpc.support.DemoService?" + "accesslog=true&group=dubbo&version=1.1"); Invoker invoker = Mockito.mock(Invoker.class); - when(invoker.invoke(any(Invocation.class))).thenReturn(AsyncRpcResult.newDefaultAsyncResult(new Person("person", 10), invocation)); + when(invoker.invoke(any(Invocation.class))) + .thenReturn(AsyncRpcResult.newDefaultAsyncResult(new Person("person", 10), invocation)); when(invoker.getUrl()).thenReturn(url); when(invoker.getInterface()).thenReturn(DemoService.class); @@ -71,7 +74,6 @@ class GenericFilterTest { genericFilter.onResponse(appResponse, invoker, invocation); Assertions.assertEquals(HashMap.class, appResponse.getValue().getClass()); Assertions.assertEquals(10, ((HashMap) appResponse.getValue()).get("age")); - } @Test @@ -85,12 +87,14 @@ class GenericFilterTest { person.put("name", "dubbo"); person.put("age", 10); - RpcInvocation invocation = new RpcInvocation($INVOKE, GenericService.class.getName(), "", genericInvoke.getParameterTypes(), - new Object[]{"getPerson", new String[]{Person.class.getCanonicalName()}, new Object[]{person}}); + RpcInvocation invocation = new RpcInvocation( + $INVOKE, GenericService.class.getName(), "", genericInvoke.getParameterTypes(), new Object[] { + "getPerson", new String[] {Person.class.getCanonicalName()}, new Object[] {person} + }); invocation.setAttachment(GENERIC_KEY, GENERIC_SERIALIZATION_NATIVE_JAVA); - URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + - "accesslog=true&group=dubbo&version=1.1"); + URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + + "accesslog=true&group=dubbo&version=1.1"); Invoker invoker = Mockito.mock(Invoker.class); when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse(new Person("person", 10))); when(invoker.getUrl()).thenReturn(url); @@ -110,11 +114,13 @@ class GenericFilterTest { person.put("name", "dubbo"); person.put("age", 10); - RpcInvocation invocation = new RpcInvocation("sayHi", GenericService.class.getName(), "", genericInvoke.getParameterTypes() - , new Object[]{"getPerson", new String[]{Person.class.getCanonicalName()}, new Object[]{person}}); + RpcInvocation invocation = new RpcInvocation( + "sayHi", GenericService.class.getName(), "", genericInvoke.getParameterTypes(), new Object[] { + "getPerson", new String[] {Person.class.getCanonicalName()}, new Object[] {person} + }); - URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + - "accesslog=true&group=dubbo&version=1.1"); + URL url = URL.valueOf( + "test://test:11/org.apache.dubbo.rpc.support.DemoService?" + "accesslog=true&group=dubbo&version=1.1"); Invoker invoker = Mockito.mock(Invoker.class); when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse(new Person("person", 10))); when(invoker.getUrl()).thenReturn(url); @@ -134,11 +140,13 @@ class GenericFilterTest { person.put("name", "dubbo"); person.put("age", 10); - RpcInvocation invocation = new RpcInvocation($INVOKE, GenericService.class.getName(), "", genericInvoke.getParameterTypes() - , new Object[]{"getPerson", new String[]{Person.class.getCanonicalName()}}); + RpcInvocation invocation = new RpcInvocation( + $INVOKE, GenericService.class.getName(), "", genericInvoke.getParameterTypes(), new Object[] { + "getPerson", new String[] {Person.class.getCanonicalName()} + }); - URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + - "accesslog=true&group=dubbo&version=1.1"); + URL url = URL.valueOf( + "test://test:11/org.apache.dubbo.rpc.support.DemoService?" + "accesslog=true&group=dubbo&version=1.1"); Invoker invoker = Mockito.mock(Invoker.class); when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse(new Person("person", 10))); when(invoker.getUrl()).thenReturn(url); @@ -148,5 +156,4 @@ class GenericFilterTest { Assertions.assertEquals(Person.class, result.getValue().getClass()); Assertions.assertEquals(10, ((Person) (result.getValue())).getAge()); } - } diff --git a/dubbo-plugin/dubbo-plugin-generic-invoke/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java b/dubbo-plugin/dubbo-plugin-generic-invoke/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java index ecf08b6e36..222a258564 100644 --- a/dubbo-plugin/dubbo-plugin-generic-invoke/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java +++ b/dubbo-plugin/dubbo-plugin-generic-invoke/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.java @@ -29,15 +29,15 @@ import org.apache.dubbo.rpc.service.GenericService; import org.apache.dubbo.rpc.support.DemoService; import org.apache.dubbo.rpc.support.Person; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; - import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; import static org.mockito.Mockito.any; @@ -45,17 +45,21 @@ import static org.mockito.Mockito.when; class GenericImplFilterTest { - private GenericImplFilter genericImplFilter = new GenericImplFilter(ApplicationModel.defaultModel().getDefaultModule()); + private GenericImplFilter genericImplFilter = + new GenericImplFilter(ApplicationModel.defaultModel().getDefaultModule()); @Test void testInvoke() throws Exception { - RpcInvocation invocation = new RpcInvocation("getPerson", "org.apache.dubbo.rpc.support.DemoService", - "org.apache.dubbo.rpc.support.DemoService:dubbo", new Class[]{Person.class}, new Object[]{new Person("dubbo", 10)}); + RpcInvocation invocation = new RpcInvocation( + "getPerson", + "org.apache.dubbo.rpc.support.DemoService", + "org.apache.dubbo.rpc.support.DemoService:dubbo", + new Class[] {Person.class}, + new Object[] {new Person("dubbo", 10)}); - - URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + - "accesslog=true&group=dubbo&version=1.1&generic=true"); + URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + + "accesslog=true&group=dubbo&version=1.1&generic=true"); Invoker invoker = Mockito.mock(Invoker.class); Map person = new HashMap(); @@ -63,7 +67,8 @@ class GenericImplFilterTest { person.put("age", 10); AppResponse mockRpcResult = new AppResponse(person); - when(invoker.invoke(any(Invocation.class))).thenReturn(AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation)); + when(invoker.invoke(any(Invocation.class))) + .thenReturn(AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation)); when(invoker.getUrl()).thenReturn(url); when(invoker.getInterface()).thenReturn(DemoService.class); @@ -79,15 +84,20 @@ class GenericImplFilterTest { @Disabled("Apache Generic Exception not support cast exception now") void testInvokeWithException1() throws Exception { - RpcInvocation invocation = new RpcInvocation("getPerson", "org.apache.dubbo.rpc.support.DemoService", - "org.apache.dubbo.rpc.support.DemoService:dubbo", new Class[]{Person.class}, new Object[]{new Person("dubbo", 10)}); + RpcInvocation invocation = new RpcInvocation( + "getPerson", + "org.apache.dubbo.rpc.support.DemoService", + "org.apache.dubbo.rpc.support.DemoService:dubbo", + new Class[] {Person.class}, + new Object[] {new Person("dubbo", 10)}); - URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + - "accesslog=true&group=dubbo&version=1.1&generic=true"); + URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + + "accesslog=true&group=dubbo&version=1.1&generic=true"); Invoker invoker = Mockito.mock(Invoker.class); AppResponse mockRpcResult = new AppResponse(new GenericException(new RuntimeException("failed"))); - when(invoker.invoke(any(Invocation.class))).thenReturn(AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation)); + when(invoker.invoke(any(Invocation.class))) + .thenReturn(AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation)); when(invoker.getUrl()).thenReturn(url); when(invoker.getInterface()).thenReturn(DemoService.class); @@ -95,21 +105,25 @@ class GenericImplFilterTest { Result result = asyncResult.get(); genericImplFilter.onResponse(result, invoker, invocation); Assertions.assertEquals(RuntimeException.class, result.getException().getClass()); - } @Test void testInvokeWithException2() throws Exception { - RpcInvocation invocation = new RpcInvocation("getPerson", "org.apache.dubbo.rpc.support.DemoService", - "org.apache.dubbo.rpc.support.DemoService:dubbo", new Class[]{Person.class}, new Object[]{new Person("dubbo", 10)}); + RpcInvocation invocation = new RpcInvocation( + "getPerson", + "org.apache.dubbo.rpc.support.DemoService", + "org.apache.dubbo.rpc.support.DemoService:dubbo", + new Class[] {Person.class}, + new Object[] {new Person("dubbo", 10)}); - URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + - "accesslog=true&group=dubbo&version=1.1&generic=true"); + URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + + "accesslog=true&group=dubbo&version=1.1&generic=true"); Invoker invoker = Mockito.mock(Invoker.class); AppResponse mockRpcResult = new AppResponse(new GenericException(new RuntimeException("failed"))); - when(invoker.invoke(any(Invocation.class))).thenReturn(AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation)); + when(invoker.invoke(any(Invocation.class))) + .thenReturn(AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation)); when(invoker.getUrl()).thenReturn(url); when(invoker.getInterface()).thenReturn(DemoService.class); @@ -117,7 +131,6 @@ class GenericImplFilterTest { Result result = asyncResult.get(); genericImplFilter.onResponse(result, invoker, invocation); Assertions.assertEquals(GenericException.class, result.getException().getClass()); - } @Test @@ -129,17 +142,20 @@ class GenericImplFilterTest { person.put("name", "dubbo"); person.put("age", 10); - RpcInvocation invocation = new RpcInvocation($INVOKE, GenericService.class.getName(), "org.apache.dubbo.rpc.support.DemoService:dubbo", - genericInvoke.getParameterTypes(), new Object[]{"getPerson", new String[]{Person.class.getCanonicalName()}, new Object[]{person}}); + RpcInvocation invocation = new RpcInvocation( + $INVOKE, + GenericService.class.getName(), + "org.apache.dubbo.rpc.support.DemoService:dubbo", + genericInvoke.getParameterTypes(), + new Object[] {"getPerson", new String[] {Person.class.getCanonicalName()}, new Object[] {person}}); - URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + - "accesslog=true&group=dubbo&version=1.1&generic=true"); + URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?" + + "accesslog=true&group=dubbo&version=1.1&generic=true"); Invoker invoker = Mockito.mock(Invoker.class); when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse(new Person("person", 10))); when(invoker.getUrl()).thenReturn(url); genericImplFilter.invoke(invoker, invocation); Assertions.assertEquals("true", invocation.getAttachment(GENERIC_KEY)); - } } diff --git a/dubbo-plugin/dubbo-plugin-generic-invoke/src/test/java/org/apache/dubbo/rpc/support/DemoService.java b/dubbo-plugin/dubbo-plugin-generic-invoke/src/test/java/org/apache/dubbo/rpc/support/DemoService.java index fcc3b9d718..0a8caa5f21 100644 --- a/dubbo-plugin/dubbo-plugin-generic-invoke/src/test/java/org/apache/dubbo/rpc/support/DemoService.java +++ b/dubbo-plugin/dubbo-plugin-generic-invoke/src/test/java/org/apache/dubbo/rpc/support/DemoService.java @@ -19,5 +19,4 @@ package org.apache.dubbo.rpc.support; public interface DemoService { Person getPerson(Person person); - } diff --git a/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/pom.xml b/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/pom.xml index 26fa460315..fb25984343 100644 --- a/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/pom.xml +++ b/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + - dubbo-plugin-loadbalance-adaptive - jar + dubbo-plugin-loadbalance-adaptive + jar - - - org.apache.dubbo - dubbo-cluster - ${project.version} - - - org.apache.dubbo - dubbo-config-api - ${project.version} - - + + + org.apache.dubbo + dubbo-cluster + ${project.version} + + + org.apache.dubbo + dubbo-config-api + ${project.version} + + diff --git a/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/main/java/org/apache/dubbo/rpc/AdaptiveMetrics.java b/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/main/java/org/apache/dubbo/rpc/AdaptiveMetrics.java index e48c591b05..dfd077f947 100644 --- a/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/main/java/org/apache/dubbo/rpc/AdaptiveMetrics.java +++ b/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/main/java/org/apache/dubbo/rpc/AdaptiveMetrics.java @@ -37,7 +37,7 @@ public class AdaptiveMetrics { private long lastLatency = 0; private long currentTime = 0; - //Allow some time disorder + // Allow some time disorder private long pickTime = System.currentTimeMillis(); private double beta = 0.5; @@ -49,7 +49,7 @@ public class AdaptiveMetrics { public double getLoad(String idKey, int weight, int timeout) { AdaptiveMetrics metrics = getStatus(idKey); - //If the time more than 2 times, mandatory selected + // If the time more than 2 times, mandatory selected if (System.currentTimeMillis() - metrics.pickTime > timeout * 2) { return 0; } @@ -58,7 +58,7 @@ public class AdaptiveMetrics { long multiple = (System.currentTimeMillis() - metrics.currentTime) / timeout + 1; if (multiple > 0) { if (metrics.currentProviderTime == metrics.currentTime) { - //penalty value + // penalty value metrics.lastLatency = timeout * 2L; } else { metrics.lastLatency = metrics.lastLatency >> multiple; @@ -69,7 +69,10 @@ public class AdaptiveMetrics { } long inflight = metrics.consumerReq.get() - metrics.consumerSuccess.get() - metrics.errorReq.get(); - return metrics.providerCPULoad * (Math.sqrt(metrics.ewma) + 1) * (inflight + 1) / ((((double) metrics.consumerSuccess.get() / (double) (metrics.consumerReq.get() + 1)) * weight) + 1); + return metrics.providerCPULoad + * (Math.sqrt(metrics.ewma) + 1) + * (inflight + 1) + / ((((double) metrics.consumerSuccess.get() / (double) (metrics.consumerReq.get() + 1)) * weight) + 1); } public AdaptiveMetrics getStatus(String idKey) { @@ -96,26 +99,29 @@ public class AdaptiveMetrics { metrics.pickTime = time; } - public void setProviderMetrics(String idKey, Map metricsMap) { AdaptiveMetrics metrics = getStatus(idKey); - long serviceTime = Long.parseLong(Optional.ofNullable(metricsMap.get("curTime")).filter(v -> StringUtils.isNumeric(v, false)).orElse("0")); - //If server time is less than the current time, discard + long serviceTime = Long.parseLong(Optional.ofNullable(metricsMap.get("curTime")) + .filter(v -> StringUtils.isNumeric(v, false)) + .orElse("0")); + // If server time is less than the current time, discard if (metrics.currentProviderTime > serviceTime) { return; } metrics.currentProviderTime = serviceTime; metrics.currentTime = serviceTime; - metrics.providerCPULoad = Double.parseDouble(Optional.ofNullable(metricsMap.get("load")).filter(v -> StringUtils.isNumeric(v, true)).orElse("0")); - metrics.lastLatency = Long.parseLong((Optional.ofNullable(metricsMap.get("rt")).filter(v -> StringUtils.isNumeric(v, false)).orElse("0"))); + metrics.providerCPULoad = Double.parseDouble(Optional.ofNullable(metricsMap.get("load")) + .filter(v -> StringUtils.isNumeric(v, true)) + .orElse("0")); + metrics.lastLatency = Long.parseLong((Optional.ofNullable(metricsMap.get("rt")) + .filter(v -> StringUtils.isNumeric(v, false)) + .orElse("0"))); metrics.beta = 0.5; - //Vt = β * Vt-1 + (1 - β ) * θt + // Vt = β * Vt-1 + (1 - β ) * θt metrics.ewma = metrics.beta * metrics.ewma + (1 - metrics.beta) * metrics.lastLatency; - } } - diff --git a/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/main/java/org/apache/dubbo/rpc/AdaptiveScopeModelInitializer.java b/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/main/java/org/apache/dubbo/rpc/AdaptiveScopeModelInitializer.java index 83c0ea8ee6..2d7c0f3c1c 100644 --- a/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/main/java/org/apache/dubbo/rpc/AdaptiveScopeModelInitializer.java +++ b/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/main/java/org/apache/dubbo/rpc/AdaptiveScopeModelInitializer.java @@ -24,8 +24,7 @@ import org.apache.dubbo.rpc.model.ScopeModelInitializer; public class AdaptiveScopeModelInitializer implements ScopeModelInitializer { @Override - public void initializeFrameworkModel(FrameworkModel frameworkModel) { - } + public void initializeFrameworkModel(FrameworkModel frameworkModel) {} @Override public void initializeApplicationModel(ApplicationModel applicationModel) { @@ -34,6 +33,5 @@ public class AdaptiveScopeModelInitializer implements ScopeModelInitializer { } @Override - public void initializeModuleModel(ModuleModel moduleModel) { - } + public void initializeModuleModel(ModuleModel moduleModel) {} } diff --git a/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/AdaptiveLoadBalance.java b/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/AdaptiveLoadBalance.java index 7f99e371af..501d2b10aa 100644 --- a/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/AdaptiveLoadBalance.java +++ b/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/AdaptiveLoadBalance.java @@ -41,36 +41,36 @@ public class AdaptiveLoadBalance extends AbstractLoadBalance { public static final String NAME = "adaptive"; - //default key + // default key private String attachmentKey = "mem,load"; private final AdaptiveMetrics adaptiveMetrics; - public AdaptiveLoadBalance(ApplicationModel scopeModel){ + public AdaptiveLoadBalance(ApplicationModel scopeModel) { adaptiveMetrics = scopeModel.getBeanFactory().getBean(AdaptiveMetrics.class); } @Override protected Invoker doSelect(List> invokers, URL url, Invocation invocation) { - Invoker invoker = selectByP2C(invokers,invocation); - invocation.setAttachment(Constants.ADAPTIVE_LOADBALANCE_ATTACHMENT_KEY,attachmentKey); + Invoker invoker = selectByP2C(invokers, invocation); + invocation.setAttachment(Constants.ADAPTIVE_LOADBALANCE_ATTACHMENT_KEY, attachmentKey); long startTime = System.currentTimeMillis(); - invocation.getAttributes().put(Constants.ADAPTIVE_LOADBALANCE_START_TIME,startTime); - invocation.getAttributes().put(LOADBALANCE_KEY,LoadbalanceRules.ADAPTIVE); - adaptiveMetrics.addConsumerReq(getServiceKey(invoker,invocation)); - adaptiveMetrics.setPickTime(getServiceKey(invoker,invocation),startTime); + invocation.getAttributes().put(Constants.ADAPTIVE_LOADBALANCE_START_TIME, startTime); + invocation.getAttributes().put(LOADBALANCE_KEY, LoadbalanceRules.ADAPTIVE); + adaptiveMetrics.addConsumerReq(getServiceKey(invoker, invocation)); + adaptiveMetrics.setPickTime(getServiceKey(invoker, invocation), startTime); return invoker; } - private Invoker selectByP2C(List> invokers, Invocation invocation){ + private Invoker selectByP2C(List> invokers, Invocation invocation) { int length = invokers.size(); - if(length == 1) { + if (length == 1) { return invokers.get(0); } - if(length == 2) { - return chooseLowLoadInvoker(invokers.get(0),invokers.get(1),invocation); + if (length == 2) { + return chooseLowLoadInvoker(invokers.get(0), invokers.get(1), invocation); } int pos1 = ThreadLocalRandom.current().nextInt(length); @@ -79,22 +79,22 @@ public class AdaptiveLoadBalance extends AbstractLoadBalance { pos2 = pos2 + 1; } - return chooseLowLoadInvoker(invokers.get(pos1),invokers.get(pos2),invocation); + return chooseLowLoadInvoker(invokers.get(pos1), invokers.get(pos2), invocation); } - private String getServiceKey(Invoker invoker,Invocation invocation){ + private String getServiceKey(Invoker invoker, Invocation invocation) { String key = (String) invocation.getAttributes().get(invoker); - if (StringUtils.isNotEmpty(key)){ + if (StringUtils.isNotEmpty(key)) { return key; } - key = buildServiceKey(invoker,invocation); - invocation.getAttributes().put(invoker,key); + key = buildServiceKey(invoker, invocation); + invocation.getAttributes().put(invoker, key); return key; } - private String buildServiceKey(Invoker invoker,Invocation invocation){ + private String buildServiceKey(Invoker invoker, Invocation invocation) { URL url = invoker.getUrl(); StringBuilder sb = new StringBuilder(128); sb.append(url.getAddress()).append(":").append(invocation.getProtocolServiceKey()); @@ -104,16 +104,19 @@ public class AdaptiveLoadBalance extends AbstractLoadBalance { private int getTimeout(Invoker invoker, Invocation invocation) { URL url = invoker.getUrl(); String methodName = RpcUtils.getMethodName(invocation); - return (int) RpcUtils.getTimeout(url,methodName, RpcContext.getClientAttachment(),invocation, DEFAULT_TIMEOUT); + return (int) + RpcUtils.getTimeout(url, methodName, RpcContext.getClientAttachment(), invocation, DEFAULT_TIMEOUT); } - private Invoker chooseLowLoadInvoker(Invoker invoker1,Invoker invoker2,Invocation invocation){ + private Invoker chooseLowLoadInvoker(Invoker invoker1, Invoker invoker2, Invocation invocation) { int weight1 = getWeight(invoker1, invocation); int weight2 = getWeight(invoker2, invocation); int timeout1 = getTimeout(invoker1, invocation); int timeout2 = getTimeout(invoker2, invocation); - long load1 = Double.doubleToLongBits(adaptiveMetrics.getLoad(getServiceKey(invoker1,invocation),weight1,timeout1 )); - long load2 = Double.doubleToLongBits(adaptiveMetrics.getLoad(getServiceKey(invoker2,invocation),weight2,timeout2 )); + long load1 = Double.doubleToLongBits( + adaptiveMetrics.getLoad(getServiceKey(invoker1, invocation), weight1, timeout1)); + long load2 = Double.doubleToLongBits( + adaptiveMetrics.getLoad(getServiceKey(invoker2, invocation), weight2, timeout2)); if (load1 == load2) { // The sum of weights @@ -129,5 +132,4 @@ public class AdaptiveLoadBalance extends AbstractLoadBalance { } return load1 > load2 ? invoker2 : invoker1; } - } diff --git a/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/main/java/org/apache/dubbo/rpc/filter/AdaptiveLoadBalanceFilter.java b/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/main/java/org/apache/dubbo/rpc/filter/AdaptiveLoadBalanceFilter.java index b41e72e391..b6cd7411b2 100644 --- a/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/main/java/org/apache/dubbo/rpc/filter/AdaptiveLoadBalanceFilter.java +++ b/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/main/java/org/apache/dubbo/rpc/filter/AdaptiveLoadBalanceFilter.java @@ -45,7 +45,10 @@ import static org.apache.dubbo.common.constants.CommonConstants.LOADBALANCE_KEY; * @see org.apache.dubbo.rpc.Filter * @see org.apache.dubbo.rpc.RpcContext */ -@Activate(group = CONSUMER, order = -200000, value = {"loadbalance:adaptive"}) +@Activate( + group = CONSUMER, + order = -200000, + value = {"loadbalance:adaptive"}) public class AdaptiveLoadBalanceFilter implements Filter, Filter.Listener { /** @@ -59,12 +62,18 @@ public class AdaptiveLoadBalanceFilter implements Filter, Filter.Listener { adaptiveMetrics = scopeModel.getBeanFactory().getBean(AdaptiveMetrics.class); } - private ThreadPoolExecutor getExecutor(){ + private ThreadPoolExecutor getExecutor() { if (null == executor) { synchronized (this) { if (null == executor) { - executor = new ThreadPoolExecutor(1, 1, 0L,TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024), - new NamedInternalThreadFactory("Dubbo-framework-loadbalance-adaptive", true), new ThreadPoolExecutor.DiscardOldestPolicy()); + executor = new ThreadPoolExecutor( + 1, + 1, + 0L, + TimeUnit.MILLISECONDS, + new LinkedBlockingQueue<>(1024), + new NamedInternalThreadFactory("Dubbo-framework-loadbalance-adaptive", true), + new ThreadPoolExecutor.DiscardOldestPolicy()); GlobalResourcesRepository.getInstance().registerDisposable(() -> this.executor.shutdown()); } } @@ -77,21 +86,21 @@ public class AdaptiveLoadBalanceFilter implements Filter, Filter.Listener { return invoker.invoke(invocation); } - private String buildServiceKey(Invocation invocation){ + private String buildServiceKey(Invocation invocation) { StringBuilder sb = new StringBuilder(128); sb.append(invocation.getInvoker().getUrl().getAddress()).append(":").append(invocation.getProtocolServiceKey()); return sb.toString(); } - private String getServiceKey(Invocation invocation){ + private String getServiceKey(Invocation invocation) { String key = (String) invocation.getAttributes().get(invocation.getInvoker()); - if (StringUtils.isNotEmpty(key)){ + if (StringUtils.isNotEmpty(key)) { return key; } key = buildServiceKey(invocation); - invocation.getAttributes().put(invocation.getInvoker(),key); + invocation.getAttributes().put(invocation.getInvoker(), key); return key; } @@ -100,8 +109,7 @@ public class AdaptiveLoadBalanceFilter implements Filter, Filter.Listener { try { String loadBalance = (String) invocation.getAttributes().get(LOADBALANCE_KEY); - if (StringUtils.isEmpty(loadBalance) - || !LoadbalanceRules.ADAPTIVE.equals(loadBalance)) { + if (StringUtils.isEmpty(loadBalance) || !LoadbalanceRules.ADAPTIVE.equals(loadBalance)) { return; } adaptiveMetrics.addConsumerSuccess(getServiceKey(invocation)); @@ -129,23 +137,18 @@ public class AdaptiveLoadBalanceFilter implements Filter, Filter.Listener { adaptiveMetrics.setProviderMetrics(getServiceKey(invocation), metricsMap); }); } - } - finally { + } finally { appResponse.getAttachments().remove(Constants.ADAPTIVE_LOADBALANCE_ATTACHMENT_KEY); } - } @Override public void onError(Throwable t, Invoker invoker, Invocation invocation) { String loadBalance = (String) invocation.getAttributes().get(LOADBALANCE_KEY); - if (StringUtils.isNotEmpty(loadBalance) - && LoadbalanceRules.ADAPTIVE.equals(loadBalance)) { + if (StringUtils.isNotEmpty(loadBalance) && LoadbalanceRules.ADAPTIVE.equals(loadBalance)) { getExecutor().execute(() -> { adaptiveMetrics.addErrorReq(getServiceKey(invocation)); }); } } - - } diff --git a/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/AdaptiveLoadBalanceTest.java b/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/AdaptiveLoadBalanceTest.java index 1a8e90f5ff..0f8c80f1df 100644 --- a/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/AdaptiveLoadBalanceTest.java +++ b/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/AdaptiveLoadBalanceTest.java @@ -21,18 +21,18 @@ import org.apache.dubbo.rpc.AdaptiveMetrics; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Order; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; - import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.stream.Collectors; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class AdaptiveLoadBalanceTest extends LoadBalanceBaseTest { @@ -74,12 +74,12 @@ class AdaptiveLoadBalanceTest extends LoadBalanceBaseTest { Assertions.assertEquals(sumInvoker1 + sumInvoker2 + sumInvoker3, loop, "select failed!"); } - private String buildServiceKey(Invoker invoker){ + private String buildServiceKey(Invoker invoker) { URL url = invoker.getUrl(); return url.getAddress() + ":" + invocation.getProtocolServiceKey(); } - private AdaptiveMetrics getAdaptiveMetricsInstance(){ + private AdaptiveMetrics getAdaptiveMetricsInstance() { if (adaptiveMetrics == null) { adaptiveMetrics = scopeModel.getBeanFactory().getBean(AdaptiveMetrics.class); } @@ -109,7 +109,7 @@ class AdaptiveLoadBalanceTest extends LoadBalanceBaseTest { sumInvoker1++; metricsMap.put("rt", "10"); metricsMap.put("load", "10"); - metricsMap.put("curTime", String.valueOf(System.currentTimeMillis()-10)); + metricsMap.put("curTime", String.valueOf(System.currentTimeMillis() - 10)); getAdaptiveMetricsInstance().addConsumerSuccess(idKey); } @@ -117,29 +117,29 @@ class AdaptiveLoadBalanceTest extends LoadBalanceBaseTest { sumInvoker2++; metricsMap.put("rt", "100"); metricsMap.put("load", "40"); - metricsMap.put("curTime", String.valueOf(System.currentTimeMillis()-100)); + metricsMap.put("curTime", String.valueOf(System.currentTimeMillis() - 100)); getAdaptiveMetricsInstance().addConsumerSuccess(idKey); } if (selected.getUrl().getProtocol().equals("test5")) { metricsMap.put("rt", "5000"); - metricsMap.put("load", "400");//400% + metricsMap.put("load", "400"); // 400% metricsMap.put("curTime", String.valueOf(System.currentTimeMillis() - 5000)); getAdaptiveMetricsInstance().addErrorReq(idKey); sumInvoker5++; } - getAdaptiveMetricsInstance().setProviderMetrics(idKey,metricsMap); - + getAdaptiveMetricsInstance().setProviderMetrics(idKey, metricsMap); } Map, Integer> weightMap = weightInvokersSR.stream() - .collect(Collectors.toMap(Function.identity(), e -> Integer.valueOf(e.getUrl().getParameter("weight")))); + .collect(Collectors.toMap( + Function.identity(), e -> Integer.valueOf(e.getUrl().getParameter("weight")))); Integer totalWeight = weightMap.values().stream().reduce(0, Integer::sum); // max deviation = expectWeightValue * 2 int expectWeightValue = loop / totalWeight; int maxDeviation = expectWeightValue * 2; double beta = 0.5; - //this EMA is an approximate value + // this EMA is an approximate value double ewma1 = beta * 50 + (1 - beta) * 10; double ewma2 = beta * 50 + (1 - beta) * 100; double ewma5 = beta * 50 + (1 - beta) * 5000; @@ -147,21 +147,25 @@ class AdaptiveLoadBalanceTest extends LoadBalanceBaseTest { AtomicInteger weight1 = new AtomicInteger(); AtomicInteger weight2 = new AtomicInteger(); AtomicInteger weight5 = new AtomicInteger(); - weightMap.forEach((k, v) ->{ - if (k.getUrl().getProtocol().equals("test1")){ + weightMap.forEach((k, v) -> { + if (k.getUrl().getProtocol().equals("test1")) { weight1.set(v); - } - else if (k.getUrl().getProtocol().equals("test2")){ + } else if (k.getUrl().getProtocol().equals("test2")) { weight2.set(v); - } - else if (k.getUrl().getProtocol().equals("test5")){ + } else if (k.getUrl().getProtocol().equals("test5")) { weight5.set(v); } }); Assertions.assertEquals(sumInvoker1 + sumInvoker2 + sumInvoker5, loop, "select failed!"); - Assertions.assertTrue(Math.abs(sumInvoker1 / (weightMap.get(weightInvoker1) * ewma1) - expectWeightValue) < maxDeviation, "select failed!"); - Assertions.assertTrue(Math.abs(sumInvoker2 / (weightMap.get(weightInvoker2) * ewma2) - expectWeightValue) < maxDeviation, "select failed!"); - Assertions.assertTrue(Math.abs(sumInvoker5 / (weightMap.get(weightInvoker5) * ewma5) - expectWeightValue) < maxDeviation, "select failed!"); + Assertions.assertTrue( + Math.abs(sumInvoker1 / (weightMap.get(weightInvoker1) * ewma1) - expectWeightValue) < maxDeviation, + "select failed!"); + Assertions.assertTrue( + Math.abs(sumInvoker2 / (weightMap.get(weightInvoker2) * ewma2) - expectWeightValue) < maxDeviation, + "select failed!"); + Assertions.assertTrue( + Math.abs(sumInvoker5 / (weightMap.get(weightInvoker5) * ewma5) - expectWeightValue) < maxDeviation, + "select failed!"); } } diff --git a/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LoadBalanceBaseTest.java b/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LoadBalanceBaseTest.java index 835b5a7eff..a1a7e4e57b 100644 --- a/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LoadBalanceBaseTest.java +++ b/dubbo-plugin/dubbo-plugin-loadbalance-adaptive/src/test/java/org/apache/dubbo/rpc/cluster/loadbalance/LoadBalanceBaseTest.java @@ -24,11 +24,6 @@ import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.RpcStatus; import org.apache.dubbo.rpc.cluster.LoadBalance; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; import java.util.ArrayList; import java.util.List; @@ -36,6 +31,12 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_WARMUP; import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_WEIGHT; import static org.mockito.BDDMockito.given; @@ -66,8 +67,7 @@ class LoadBalanceBaseTest { * @throws Exception */ @BeforeAll - public static void setUpBeforeClass() throws Exception { - } + public static void setUpBeforeClass() throws Exception {} /** * @throws Exception @@ -77,14 +77,14 @@ class LoadBalanceBaseTest { invocation = mock(Invocation.class); given(invocation.getMethodName()).willReturn("method1"); - given(invocation.getArguments()).willReturn(new Object[] {"arg1","arg2","arg3"}); + given(invocation.getArguments()).willReturn(new Object[] {"arg1", "arg2", "arg3"}); genericInvocation = mock(Invocation.class); String methodName = "method1"; given(genericInvocation.getMethodName()).willReturn("$invoke"); - String[] paraTypes = new String[] {String.class.getName(),String.class.getName(),String.class.getName()}; - Object[] argsObject = new Object[] {"arg1","arg2","arg3"}; - Object[] args = new Object[] {methodName,paraTypes,argsObject}; + String[] paraTypes = new String[] {String.class.getName(), String.class.getName(), String.class.getName()}; + Object[] argsObject = new Object[] {"arg1", "arg2", "arg3"}; + Object[] args = new Object[] {methodName, paraTypes, argsObject}; given(genericInvocation.getArguments()).willReturn(args); invoker1 = mock(Invoker.class); @@ -155,7 +155,8 @@ class LoadBalanceBaseTest { } protected AbstractLoadBalance getLoadBalance(String loadbalanceName) { - return (AbstractLoadBalance) ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(loadbalanceName); + return (AbstractLoadBalance) + ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(loadbalanceName); } @Test @@ -228,7 +229,7 @@ class LoadBalanceBaseTest { } protected List> weightInvokers = new ArrayList>(); - protected List> weightInvokersSR= new ArrayList>(); + protected List> weightInvokersSR = new ArrayList>(); protected Invoker weightInvoker1; protected Invoker weightInvoker2; @@ -286,7 +287,6 @@ class LoadBalanceBaseTest { weightTestRpcStatus3 = RpcStatus.getStatus(weightInvoker3.getUrl(), weightTestInvocation.getMethodName()); weightTestRpcStatus5 = RpcStatus.getStatus(weightInvoker5.getUrl(), weightTestInvocation.getMethodName()); - // weightTestRpcStatus3 active is 1 RpcStatus.beginCount(weightInvoker3.getUrl(), weightTestInvocation.getMethodName()); @@ -301,7 +301,7 @@ class LoadBalanceBaseTest { Map counter = new ConcurrentHashMap(); AbstractLoadBalance lb = getLoadBalance(loadbalanceName); int totalWeight = 0; - for (int i = 0; i < weightInvokers.size(); i ++) { + for (int i = 0; i < weightInvokers.size(); i++) { InvokeResult invokeResult = new InvokeResult(lb.getWeight(weightInvokers.get(i), weightTestInvocation)); counter.put(weightInvokers.get(i), invokeResult); totalWeight += invokeResult.getWeight(); @@ -316,5 +316,4 @@ class LoadBalanceBaseTest { } return counter; } - } diff --git a/dubbo-plugin/dubbo-plugin-loom/pom.xml b/dubbo-plugin/dubbo-plugin-loom/pom.xml index 8a6cfc2444..0f637ac38b 100644 --- a/dubbo-plugin/dubbo-plugin-loom/pom.xml +++ b/dubbo-plugin/dubbo-plugin-loom/pom.xml @@ -15,43 +15,41 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + - dubbo-plugin-loom + dubbo-plugin-loom - - false - + + false + - - - org.apache.dubbo - dubbo-common - ${project.version} - true - - + + + org.apache.dubbo + dubbo-common + ${project.version} + true + + - - - - org.apache.maven.plugins - maven-compiler-plugin - - 21 - 21 - 21 - - - - + + + + org.apache.maven.plugins + maven-compiler-plugin + + 21 + 21 + 21 + + + + diff --git a/dubbo-plugin/dubbo-plugin-loom/src/main/java/org/apache/dubbo/common/threadpool/support/loom/VirtualThreadPool.java b/dubbo-plugin/dubbo-plugin-loom/src/main/java/org/apache/dubbo/common/threadpool/support/loom/VirtualThreadPool.java index 55e145ec8f..4e807991d6 100644 --- a/dubbo-plugin/dubbo-plugin-loom/src/main/java/org/apache/dubbo/common/threadpool/support/loom/VirtualThreadPool.java +++ b/dubbo-plugin/dubbo-plugin-loom/src/main/java/org/apache/dubbo/common/threadpool/support/loom/VirtualThreadPool.java @@ -33,10 +33,9 @@ import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; public class VirtualThreadPool implements ThreadPool { @Override public Executor getExecutor(URL url) { - String name = url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME)); + String name = + url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME)); return Executors.newThreadPerTaskExecutor( - Thread.ofVirtual() - .name(name, 1) - .factory()); + Thread.ofVirtual().name(name, 1).factory()); } } diff --git a/dubbo-plugin/dubbo-plugin-loom/src/test/java/org/apache/dubbo/common/threadpool/support/loom/VirtualThreadPoolTest.java b/dubbo-plugin/dubbo-plugin-loom/src/test/java/org/apache/dubbo/common/threadpool/support/loom/VirtualThreadPoolTest.java index 42653cd8bd..beebc26f72 100644 --- a/dubbo-plugin/dubbo-plugin-loom/src/test/java/org/apache/dubbo/common/threadpool/support/loom/VirtualThreadPoolTest.java +++ b/dubbo-plugin/dubbo-plugin-loom/src/test/java/org/apache/dubbo/common/threadpool/support/loom/VirtualThreadPoolTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -19,14 +19,14 @@ package org.apache.dubbo.common.threadpool.support.loom; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadpool.ThreadPool; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executor; + import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledForJreRange; import org.junit.jupiter.api.condition.JRE; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executor; - import static org.apache.dubbo.common.constants.CommonConstants.QUEUES_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; import static org.hamcrest.MatcherAssert.assertThat; @@ -39,8 +39,7 @@ public class VirtualThreadPoolTest { @Test @EnabledForJreRange(min = JRE.JAVA_21) void getExecutor1() throws Exception { - URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + - THREAD_NAME_KEY + "=demo"); + URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + THREAD_NAME_KEY + "=demo"); ThreadPool threadPool = new VirtualThreadPool(); Executor executor = threadPool.getExecutor(url); @@ -61,6 +60,8 @@ public class VirtualThreadPoolTest { void getExecutor2() { URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + QUEUES_KEY + "=1"); ThreadPool threadPool = new VirtualThreadPool(); - assertThat(threadPool.getExecutor(url).getClass().getName(), Matchers.is("java.util.concurrent.ThreadPerTaskExecutor")); + assertThat( + threadPool.getExecutor(url).getClass().getName(), + Matchers.is("java.util.concurrent.ThreadPerTaskExecutor")); } } diff --git a/dubbo-plugin/dubbo-plugin-mock/pom.xml b/dubbo-plugin/dubbo-plugin-mock/pom.xml index 5da1b2f37d..3cd3988b70 100644 --- a/dubbo-plugin/dubbo-plugin-mock/pom.xml +++ b/dubbo-plugin/dubbo-plugin-mock/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + - dubbo-plugin-mock - jar + dubbo-plugin-mock + jar - - - org.apache.dubbo - dubbo-cluster - ${project.version} - - - org.apache.dubbo - dubbo-config-api - ${project.version} - - + + + org.apache.dubbo + dubbo-cluster + ${project.version} + + + org.apache.dubbo + dubbo-config-api + ${project.version} + + diff --git a/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelector.java b/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelector.java index 1ea813c598..c8526eb0ff 100644 --- a/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelector.java +++ b/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelector.java @@ -49,9 +49,14 @@ public class MockInvokersSelector extends AbstractStateRouter { } @Override - protected BitList> doRoute(BitList> invokers, URL url, Invocation invocation, - boolean needToPrintMessage, Holder> nodeHolder, - Holder messageHolder) throws RpcException { + protected BitList> doRoute( + BitList> invokers, + URL url, + Invocation invocation, + boolean needToPrintMessage, + Holder> nodeHolder, + Holder messageHolder) + throws RpcException { if (CollectionUtils.isEmpty(invokers)) { if (needToPrintMessage) { messageHolder.set("Empty invokers. Directly return."); @@ -108,6 +113,8 @@ public class MockInvokersSelector extends AbstractStateRouter { Map>> grouping = new HashMap<>(); grouping.put("Mocked", mockedInvokers); grouping.put("Normal", normalInvokers); - return new RouterGroupingState<>(this.getClass().getSimpleName(), mockedInvokers.size() + normalInvokers.size(), grouping).toString(); + return new RouterGroupingState<>( + this.getClass().getSimpleName(), mockedInvokers.size() + normalInvokers.size(), grouping) + .toString(); } } diff --git a/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockStateRouterFactory.java b/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockStateRouterFactory.java index 4297ac9522..9bff80a573 100644 --- a/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockStateRouterFactory.java +++ b/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockStateRouterFactory.java @@ -32,5 +32,4 @@ public class MockStateRouterFactory implements StateRouterFactory { public StateRouter getRouter(Class interfaceClass, URL url) { return new MockInvokersSelector(url); } - } diff --git a/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java b/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java index 348c6e032d..f5c10fbb6b 100644 --- a/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java +++ b/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvoker.java @@ -47,7 +47,8 @@ import static org.apache.dubbo.rpc.cluster.Constants.INVOCATION_NEED_MOCK; public class MockClusterInvoker implements ClusterInvoker { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MockClusterInvoker.class); - private static final boolean setFutureWhenSync = Boolean.parseBoolean(System.getProperty(CommonConstants.SET_FUTURE_IN_SYNC_MODE, "true")); + private static final boolean setFutureWhenSync = + Boolean.parseBoolean(System.getProperty(CommonConstants.SET_FUTURE_IN_SYNC_MODE, "true")); private final Directory directory; @@ -97,22 +98,29 @@ public class MockClusterInvoker implements ClusterInvoker { public Result invoke(Invocation invocation) throws RpcException { Result result; - String value = getUrl().getMethodParameter(RpcUtils.getMethodName(invocation), MOCK_KEY, Boolean.FALSE.toString()).trim(); + String value = getUrl().getMethodParameter( + RpcUtils.getMethodName(invocation), MOCK_KEY, Boolean.FALSE.toString()) + .trim(); if (ConfigUtils.isEmpty(value)) { - //no mock + // no mock result = this.invoker.invoke(invocation); } else if (value.startsWith(FORCE_KEY)) { if (logger.isWarnEnabled()) { - logger.warn(CLUSTER_FAILED_MOCK_REQUEST,"force mock","","force-mock: " + RpcUtils.getMethodName(invocation) + " force-mock enabled , url : " + getUrl()); + logger.warn( + CLUSTER_FAILED_MOCK_REQUEST, + "force mock", + "", + "force-mock: " + RpcUtils.getMethodName(invocation) + " force-mock enabled , url : " + + getUrl()); } - //force:direct mock + // force:direct mock result = doMockInvoke(invocation, null); } else { - //fail-mock + // fail-mock try { result = this.invoker.invoke(invocation); - //fix:#4585 + // fix:#4585 if (result.getException() != null && result.getException() instanceof RpcException) { RpcException rpcException = (RpcException) result.getException(); if (rpcException.isBiz()) { @@ -128,7 +136,13 @@ public class MockClusterInvoker implements ClusterInvoker { } if (logger.isWarnEnabled()) { - logger.warn(CLUSTER_FAILED_MOCK_REQUEST,"failed to mock invoke","","fail-mock: " + RpcUtils.getMethodName(invocation) + " fail-mock enabled , url : " + getUrl(),e); + logger.warn( + CLUSTER_FAILED_MOCK_REQUEST, + "failed to mock invoke", + "", + "fail-mock: " + RpcUtils.getMethodName(invocation) + " fail-mock enabled , url : " + + getUrl(), + e); } result = doMockInvoke(invocation, e); } @@ -141,8 +155,8 @@ public class MockClusterInvoker implements ClusterInvoker { Result result; Invoker mockInvoker; - RpcInvocation rpcInvocation = (RpcInvocation)invocation; - rpcInvocation.setInvokeMode(RpcUtils.getInvokeMode(getUrl(),invocation)); + RpcInvocation rpcInvocation = (RpcInvocation) invocation; + rpcInvocation.setInvokeMode(RpcUtils.getInvokeMode(getUrl(), invocation)); List> mockInvokers = selectMockInvoker(invocation); if (CollectionUtils.isEmpty(mockInvokers)) { @@ -156,14 +170,16 @@ public class MockClusterInvoker implements ClusterInvoker { if (mockException.isBiz()) { result = AsyncRpcResult.newDefaultAsyncResult(mockException.getCause(), invocation); } else { - throw new RpcException(mockException.getCode(), getMockExceptionMessage(e, mockException), mockException.getCause()); + throw new RpcException( + mockException.getCode(), getMockExceptionMessage(e, mockException), mockException.getCause()); } } catch (Throwable me) { throw new RpcException(getMockExceptionMessage(e, me), me.getCause()); } if (setFutureWhenSync || rpcInvocation.getInvokeMode() != InvokeMode.SYNC) { // set server context - RpcContext.getServiceContext().setFuture(new FutureAdapter<>(((AsyncRpcResult)result).getResponseFuture())); + RpcContext.getServiceContext() + .setFuture(new FutureAdapter<>(((AsyncRpcResult) result).getResponseFuture())); } return result; } @@ -187,19 +203,23 @@ public class MockClusterInvoker implements ClusterInvoker { */ private List> selectMockInvoker(Invocation invocation) { List> invokers = null; - //TODO generic invoker? + // TODO generic invoker? if (invocation instanceof RpcInvocation) { - //Note the implicit contract (although the description is added to the interface declaration, but extensibility is a problem. The practice placed in the attachment needs to be improved) + // Note the implicit contract (although the description is added to the interface declaration, but + // extensibility is a problem. The practice placed in the attachment needs to be improved) invocation.setAttachment(INVOCATION_NEED_MOCK, Boolean.TRUE.toString()); - //directory will return a list of normal invokers if Constants.INVOCATION_NEED_MOCK is absent or not true in invocation, otherwise, a list of mock invokers will return. + // directory will return a list of normal invokers if Constants.INVOCATION_NEED_MOCK is absent or not true + // in invocation, otherwise, a list of mock invokers will return. try { RpcContext.getServiceContext().setConsumerUrl(getUrl()); invokers = directory.list(invocation); } catch (RpcException e) { if (logger.isInfoEnabled()) { - logger.info("Exception when try to invoke mock. Get mock invokers error for service:" - + getUrl().getServiceInterface() + ", method:" + RpcUtils.getMethodName(invocation) - + ", will construct a new mock with 'new MockInvoker()'.", e); + logger.info( + "Exception when try to invoke mock. Get mock invokers error for service:" + + getUrl().getServiceInterface() + ", method:" + RpcUtils.getMethodName(invocation) + + ", will construct a new mock with 'new MockInvoker()'.", + e); } } } diff --git a/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterWrapper.java b/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterWrapper.java index 4f8be0a28a..0836e48e25 100644 --- a/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterWrapper.java +++ b/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterWrapper.java @@ -35,8 +35,7 @@ public class MockClusterWrapper implements Cluster { @Override public Invoker join(Directory directory, boolean buildFilterChain) throws RpcException { - return new MockClusterInvoker(directory, - this.cluster.join(directory, buildFilterChain)); + return new MockClusterInvoker(directory, this.cluster.join(directory, buildFilterChain)); } public Cluster getCluster() { diff --git a/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/support/MockConfigPostProcessor.java b/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/support/MockConfigPostProcessor.java index 4a1253993c..72796c786f 100644 --- a/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/support/MockConfigPostProcessor.java +++ b/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/support/MockConfigPostProcessor.java @@ -55,25 +55,26 @@ public class MockConfigPostProcessor implements ConfigPostProcessor { if (normalizedMock.startsWith(RETURN_PREFIX)) { normalizedMock = normalizedMock.substring(RETURN_PREFIX.length()).trim(); try { - //Check whether the mock value is legal, if it is illegal, throw exception + // Check whether the mock value is legal, if it is illegal, throw exception MockInvoker.parseMockValue(normalizedMock); } catch (Exception e) { - throw new IllegalStateException("Illegal mock return in "); + throw new IllegalStateException( + "Illegal mock return in "); } } else if (normalizedMock.startsWith(THROW_PREFIX)) { normalizedMock = normalizedMock.substring(THROW_PREFIX.length()).trim(); if (ConfigUtils.isNotEmpty(normalizedMock)) { try { - //Check whether the mock value is legal + // Check whether the mock value is legal MockInvoker.getThrowable(normalizedMock); } catch (Exception e) { - throw new IllegalStateException("Illegal mock throw in "); + throw new IllegalStateException( + "Illegal mock throw in "); } } } else { - //Check whether the mock class is a implementation of the interfaceClass, and if it has a default constructor + // Check whether the mock class is a implementation of the interfaceClass, and if it has a default + // constructor MockInvoker.getMockObject(config.getScopeModel().getExtensionDirector(), normalizedMock, interfaceClass); } } diff --git a/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java b/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java index eab455ce46..9e798e51df 100644 --- a/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java +++ b/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java @@ -45,10 +45,10 @@ import static org.apache.dubbo.rpc.Constants.RETURN_KEY; import static org.apache.dubbo.rpc.Constants.RETURN_PREFIX; import static org.apache.dubbo.rpc.Constants.THROW_PREFIX; -final public class MockInvoker implements Invoker { +public final class MockInvoker implements Invoker { private final ProxyFactory proxyFactory; - private final static Map> MOCK_MAP = new ConcurrentHashMap>(); - private final static Map THROWABLE_MAP = new ConcurrentHashMap(); + private static final Map> MOCK_MAP = new ConcurrentHashMap>(); + private static final Map THROWABLE_MAP = new ConcurrentHashMap(); private final URL url; private final Class type; @@ -56,7 +56,9 @@ final public class MockInvoker implements Invoker { public MockInvoker(URL url, Class type) { this.url = url; this.type = type; - this.proxyFactory = url.getOrDefaultFrameworkModel().getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + this.proxyFactory = url.getOrDefaultFrameworkModel() + .getExtensionLoader(ProxyFactory.class) + .getAdaptiveExtension(); } public static Object parseMockValue(String mock) throws Exception { @@ -66,15 +68,16 @@ final public class MockInvoker implements Invoker { public static Object parseMockValue(String mock, Type[] returnTypes) throws Exception { Object value; if ("empty".equals(mock)) { - value = ReflectUtils.getEmptyObject(returnTypes != null && returnTypes.length > 0 ? (Class) returnTypes[0] : null); + value = ReflectUtils.getEmptyObject( + returnTypes != null && returnTypes.length > 0 ? (Class) returnTypes[0] : null); } else if ("null".equals(mock)) { value = null; } else if ("true".equals(mock)) { value = true; } else if ("false".equals(mock)) { value = false; - } else if (mock.length() >= 2 && (mock.startsWith("\"") && mock.endsWith("\"") - || mock.startsWith("\'") && mock.endsWith("\'"))) { + } else if (mock.length() >= 2 + && (mock.startsWith("\"") && mock.endsWith("\"") || mock.startsWith("\'") && mock.endsWith("\'"))) { value = mock.subSequence(1, mock.length() - 1); } else if (returnTypes != null && returnTypes.length > 0 && returnTypes[0] == String.class) { value = mock; @@ -111,8 +114,10 @@ final public class MockInvoker implements Invoker { Object value = parseMockValue(mock, returnTypes); return AsyncRpcResult.newDefaultAsyncResult(value, invocation); } catch (Exception ew) { - throw new RpcException("mock return invoke error. method :" + invocation.getMethodName() - + ", mock:" + mock + ", url: " + url, ew); + throw new RpcException( + "mock return invoke error. method :" + invocation.getMethodName() + ", mock:" + mock + ", url: " + + url, + ew); } } else if (mock.startsWith(THROW_PREFIX)) { mock = mock.substring(THROW_PREFIX.length()).trim(); @@ -122,7 +127,7 @@ final public class MockInvoker implements Invoker { Throwable t = getThrowable(mock); throw new RpcException(RpcException.BIZ_EXCEPTION, t); } - } else { //impl mock + } else { // impl mock try { Invoker invoker = getInvoker(mock); return invoker.invoke(invocation); @@ -143,7 +148,7 @@ final public class MockInvoker implements Invoker { Class bizException = ReflectUtils.forName(throwstr); Constructor constructor; constructor = ReflectUtils.findConstructor(bizException, String.class); - t = (Throwable) constructor.newInstance(new Object[]{"mocked exception for service degradation."}); + t = (Throwable) constructor.newInstance(new Object[] {"mocked exception for service degradation."}); if (THROWABLE_MAP.size() < 1000) { THROWABLE_MAP.put(throwstr, t); } @@ -181,22 +186,25 @@ final public class MockInvoker implements Invoker { try { mockClass = ReflectUtils.forName(mockService); } catch (Exception e) { - if (!isDefault) {// does not check Spring bean if it is default config. - ExtensionInjector extensionFactory = - extensionDirector.getExtensionLoader(ExtensionInjector.class).getAdaptiveExtension(); + if (!isDefault) { // does not check Spring bean if it is default config. + ExtensionInjector extensionFactory = extensionDirector + .getExtensionLoader(ExtensionInjector.class) + .getAdaptiveExtension(); Object obj = extensionFactory.getInstance(serviceType, mockService); if (obj != null) { return obj; } } - throw new IllegalStateException("Did not find mock class or instance " - + mockService - + ", please check if there's mock class or instance implementing interface " - + serviceType.getName(), e); + throw new IllegalStateException( + "Did not find mock class or instance " + + mockService + + ", please check if there's mock class or instance implementing interface " + + serviceType.getName(), + e); } if (mockClass == null || !serviceType.isAssignableFrom(mockClass)) { - throw new IllegalStateException("The mock class " + mockClass.getName() + - " not implement interface " + serviceType.getName()); + throw new IllegalStateException( + "The mock class " + mockClass.getName() + " not implement interface " + serviceType.getName()); } try { @@ -208,7 +216,6 @@ final public class MockInvoker implements Invoker { } } - /** * Normalize mock string: * @@ -269,7 +276,7 @@ final public class MockInvoker implements Invoker { @Override public void destroy() { - //do nothing + // do nothing } @Override diff --git a/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/support/MockProtocol.java b/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/support/MockProtocol.java index f2d46d80b4..f0ea53fd3c 100644 --- a/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/support/MockProtocol.java +++ b/dubbo-plugin/dubbo-plugin-mock/src/main/java/org/apache/dubbo/rpc/support/MockProtocol.java @@ -25,7 +25,7 @@ import org.apache.dubbo.rpc.protocol.AbstractProtocol; /** * MockProtocol is used for generating a mock invoker by URL and type on consumer side */ -final public class MockProtocol extends AbstractProtocol { +public final class MockProtocol extends AbstractProtocol { @Override public int getDefaultPort() { diff --git a/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelectorTest.java b/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelectorTest.java index 011e871e6a..7ad19152e4 100644 --- a/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelectorTest.java +++ b/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelectorTest.java @@ -22,13 +22,13 @@ import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.router.state.BitList; +import java.util.Arrays; +import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.Arrays; -import java.util.List; - import static org.apache.dubbo.rpc.cluster.Constants.INVOCATION_NEED_MOCK; class MockInvokersSelectorTest { @@ -51,21 +51,22 @@ class MockInvokersSelectorTest { URL consumerURL = URL.valueOf("test://127.0.0.1"); selector.notify(providers); - // rpcInvocation does not have an attached "invocation.need.mock" parameter, so normal invokers will be filtered out - List> invokers = selector.route(providers.clone(), consumerURL, rpcInvocation, false, new Holder<>()); - Assertions.assertEquals(invokers.size(),1); + // rpcInvocation does not have an attached "invocation.need.mock" parameter, so normal invokers will be filtered + // out + List> invokers = + selector.route(providers.clone(), consumerURL, rpcInvocation, false, new Holder<>()); + Assertions.assertEquals(invokers.size(), 1); Assertions.assertTrue(invokers.contains(invoker3)); - // rpcInvocation have an attached "invocation.need.mock" parameter, so it will filter out the invoker whose protocol is mock - Mockito.when(rpcInvocation.getObjectAttachmentWithoutConvert(INVOCATION_NEED_MOCK)).thenReturn("true"); + // rpcInvocation have an attached "invocation.need.mock" parameter, so it will filter out the invoker whose + // protocol is mock + Mockito.when(rpcInvocation.getObjectAttachmentWithoutConvert(INVOCATION_NEED_MOCK)) + .thenReturn("true"); invokers = selector.route(providers.clone(), consumerURL, rpcInvocation, false, new Holder<>()); - Assertions.assertEquals(invokers.size(),2); + Assertions.assertEquals(invokers.size(), 2); Assertions.assertTrue(invokers.contains(invoker1)); Assertions.assertTrue(invokers.contains(invoker2)); - } - class DemoService{ - - } + class DemoService {} } diff --git a/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java b/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java index b15c87324f..cc4dbb94bc 100644 --- a/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java +++ b/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockClusterInvokerTest.java @@ -32,16 +32,16 @@ import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.support.MockProtocol; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; @@ -61,18 +61,16 @@ class MockClusterInvokerTest { @Test void testMockInvokerInvoke_normal() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()); - url = url.addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + IHelloService.class.getName() - + "&" + "mock=fail")); + url = url.addParameter( + REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=fail")); Invoker cluster = getClusterInvoker(url); - URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.class.getName() - + "?getSomething.mock=return aa"); + URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.class.getName() + "?getSomething.mock=return aa"); Protocol protocol = new MockProtocol(); Invoker mInvoker1 = protocol.refer(IHelloService.class, mockUrl); invokers.add(mInvoker1); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); @@ -91,13 +89,13 @@ class MockClusterInvokerTest { @Test void testMockInvokerInvoke_failmock() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + IHelloService.class.getName() - + "&" + "mock=fail:return null")) + .addParameter( + REFER_KEY, + URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=fail:return null")) .addParameter("invoke_return_error", "true"); URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.class.getName()) - .addParameter("mock","fail:return null") - .addParameter("getSomething.mock","return aa") + .addParameter("mock", "fail:return null") + .addParameter("getSomething.mock", "return aa") .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName())) .addParameter("invoke_return_error", "true"); @@ -105,7 +103,7 @@ class MockClusterInvokerTest { Invoker mInvoker1 = protocol.refer(IHelloService.class, mockUrl); Invoker cluster = getClusterInvokerMock(url, mInvoker1); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); @@ -124,28 +122,27 @@ class MockClusterInvokerTest { Assertions.assertNull(ret.getValue()); } - /** * Test if mock policy works fine: force-mock */ @Test void testMockInvokerInvoke_forcemock() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + IHelloService.class.getName() - + "&" + "mock=force:return null")); + .addParameter( + REFER_KEY, + URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=force:return null")); URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.class.getName()) - .addParameter("mock","force:return null") - .addParameter("getSomething.mock","return aa") - .addParameter("getSomething3xx.mock","return xx") + .addParameter("mock", "force:return null") + .addParameter("getSomething.mock", "return aa") + .addParameter("getSomething3xx.mock", "return xx") .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName())); Protocol protocol = new MockProtocol(); Invoker mInvoker1 = protocol.refer(IHelloService.class, mockUrl); Invoker cluster = getClusterInvokerMock(url, mInvoker1); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); @@ -162,21 +159,17 @@ class MockClusterInvokerTest { invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); Assertions.assertNull(ret.getValue()); - - - } @Test void testMockInvokerInvoke_forcemock_defaultreturn() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + IHelloService.class.getName() - + "&" + "mock=force")); + .addParameter( + REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=force")); Invoker cluster = getClusterInvoker(url); URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.class.getName() - + "?getSomething.mock=return aa&getSomething3xx.mock=return xx&sayHello.mock=return ") + + "?getSomething.mock=return aa&getSomething3xx.mock=return xx&sayHello.mock=return ") .addParameters(url.getParameters()); Protocol protocol = new MockProtocol(); @@ -195,12 +188,13 @@ class MockClusterInvokerTest { @Test void testMockInvokerFromOverride_Invoke_Fock_someMethods() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, + .addParameter( + REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getSomething.mock=fail:return x" + "&" + "getSomething2.mock=force:return y")); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); @@ -231,13 +225,14 @@ class MockClusterInvokerTest { @Test void testMockInvokerFromOverride_Invoke_Fock_WithOutDefault() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, + .addParameter( + REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getSomething.mock=fail:return x" + "&" + "getSomething2.mock=fail:return y")) .addParameter("invoke_return_error", "true"); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); @@ -266,14 +261,15 @@ class MockClusterInvokerTest { @Test void testMockInvokerFromOverride_Invoke_Fock_WithDefault() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, + .addParameter( + REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock" + "=" + "fail:return null" + "&" + "getSomething.mock" + "=" + "fail:return x" + "&" + "getSomething2.mock" + "=" + "fail:return y")) .addParameter("invoke_return_error", "true"); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); @@ -304,14 +300,15 @@ class MockClusterInvokerTest { @Test void testMockInvokerFromOverride_Invoke_Fock_WithFailDefault() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, + .addParameter( + REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=fail:return z" + "&" + "getSomething.mock=fail:return x" + "&" + "getSomething2.mock=force:return y")) .addParameter("invoke_return_error", "true"); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); @@ -329,7 +326,7 @@ class MockClusterInvokerTest { ret = cluster.invoke(invocation); Assertions.assertEquals("z", ret.getValue()); - //If no mock was configured, return null directly + // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); @@ -342,32 +339,33 @@ class MockClusterInvokerTest { @Test void testMockInvokerFromOverride_Invoke_Fock_WithForceDefault() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, + .addParameter( + REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=force:return z" + "&" + "getSomething.mock=fail:return x" + "&" + "getSomething2.mock=force:return y")) .addParameter("invoke_return_error", "true"); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assertions.assertEquals("x", ret.getValue()); - //If no mock was configured, return null directly + // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("getSomething2"); ret = cluster.invoke(invocation); Assertions.assertEquals("y", ret.getValue()); - //If no mock was configured, return null directly + // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("getSomething3"); ret = cluster.invoke(invocation); Assertions.assertEquals("z", ret.getValue()); - //If no mock was configured, return null directly + // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); @@ -380,24 +378,24 @@ class MockClusterInvokerTest { @Test void testMockInvokerFromOverride_Invoke_Fock_Default() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + IHelloService.class.getName() - + "&" + "mock=fail:return x")) + .addParameter( + REFER_KEY, + URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=fail:return x")) .addParameter("invoke_return_error", "true"); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assertions.assertEquals("x", ret.getValue()); - //If no mock was configured, return null directly + // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("getSomething2"); ret = cluster.invoke(invocation); Assertions.assertEquals("x", ret.getValue()); - //If no mock was configured, return null directly + // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("sayHello"); ret = cluster.invoke(invocation); @@ -410,18 +408,18 @@ class MockClusterInvokerTest { @Test void testMockInvokerFromOverride_Invoke_checkCompatible_return() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + IHelloService.class.getName() - + "&" + "getSomething.mock=return x")) + .addParameter( + REFER_KEY, + URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getSomething.mock=return x")) .addParameter("invoke_return_error", "true"); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); Assertions.assertEquals("x", ret.getValue()); - //If no mock was configured, return null directly + // If no mock was configured, return null directly invocation = new RpcInvocation(); invocation.setMethodName("getSomething3"); try { @@ -438,13 +436,13 @@ class MockClusterInvokerTest { @Test void testMockInvokerFromOverride_Invoke_checkCompatible_ImplMock() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + IHelloService.class.getName() - + "&" + "mock=true" - + "&" + "proxy=jdk")) + .addParameter( + REFER_KEY, + URL.encode( + PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=true" + "&" + "proxy=jdk")) .addParameter("invoke_return_error", "true"); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); @@ -457,11 +455,10 @@ class MockClusterInvokerTest { @Test void testMockInvokerFromOverride_Invoke_checkCompatible_ImplMock2() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=fail")) + .addParameter(REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=fail")) .addParameter("invoke_return_error", "true"); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); @@ -474,10 +471,10 @@ class MockClusterInvokerTest { @Test void testMockInvokerFromOverride_Invoke_checkCompatible_ImplMock3() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=force")); + .addParameter( + REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=force")); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); @@ -488,60 +485,70 @@ class MockClusterInvokerTest { void testMockInvokerFromOverride_Invoke_check_String() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter("getSomething.mock", "force:return 1688") - .addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + IHelloService.class.getName() - + "&" + "getSomething.mock=force:return 1688")) + .addParameter( + REFER_KEY, + URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + + "getSomething.mock=force:return 1688")) .addParameter("invoke_return_error", "true"); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); Result ret = cluster.invoke(invocation); - Assertions.assertTrue(ret.getValue() instanceof String, "result type must be String but was : " + ret.getValue().getClass()); + Assertions.assertTrue( + ret.getValue() instanceof String, + "result type must be String but was : " + ret.getValue().getClass()); Assertions.assertEquals("1688", ret.getValue()); } @Test void testMockInvokerFromOverride_Invoke_check_int() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + IHelloService.class.getName() - + "&" + "getInt1.mock=force:return 1688")) + .addParameter( + REFER_KEY, + URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + + "getInt1.mock=force:return 1688")) .addParameter("invoke_return_error", "true"); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getInt1"); Result ret = cluster.invoke(invocation); - Assertions.assertTrue(ret.getValue() instanceof Integer, "result type must be integer but was : " + ret.getValue().getClass()); + Assertions.assertTrue( + ret.getValue() instanceof Integer, + "result type must be integer but was : " + ret.getValue().getClass()); Assertions.assertEquals(new Integer(1688), (Integer) ret.getValue()); } @Test void testMockInvokerFromOverride_Invoke_check_boolean() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + IHelloService.class.getName() - + "&" + "getBoolean1.mock=force:return true")) + .addParameter( + REFER_KEY, + URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + + "getBoolean1.mock=force:return true")) .addParameter("invoke_return_error", "true"); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getBoolean1"); Result ret = cluster.invoke(invocation); - Assertions.assertTrue(ret.getValue() instanceof Boolean, "result type must be Boolean but was : " + ret.getValue().getClass()); + Assertions.assertTrue( + ret.getValue() instanceof Boolean, + "result type must be Boolean but was : " + ret.getValue().getClass()); Assertions.assertTrue(Boolean.parseBoolean(ret.getValue().toString())); } @Test void testMockInvokerFromOverride_Invoke_check_Boolean() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + IHelloService.class.getName() - + "&" + "getBoolean2.mock=force:return true")) + .addParameter( + REFER_KEY, + URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + + "getBoolean2.mock=force:return true")) .addParameter("invoke_return_error", "true"); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getBoolean2"); Result ret = cluster.invoke(invocation); @@ -552,12 +559,13 @@ class MockClusterInvokerTest { @Test void testMockInvokerFromOverride_Invoke_check_ListString_empty() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + IHelloService.class.getName() - + "&" + "getListString.mock=force:return empty")) + .addParameter( + REFER_KEY, + URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + + "getListString.mock=force:return empty")) .addParameter("invoke_return_error", "true"); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getListString"); Result ret = cluster.invoke(invocation); @@ -568,12 +576,13 @@ class MockClusterInvokerTest { @Test void testMockInvokerFromOverride_Invoke_check_ListString() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + IHelloService.class.getName() - + "&" + "getListString.mock=force:return [\"hi\",\"hi2\"]")) + .addParameter( + REFER_KEY, + URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + + "getListString.mock=force:return [\"hi\",\"hi2\"]")) .addParameter("invoke_return_error", "true"); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getListString"); Result ret = cluster.invoke(invocation); @@ -586,26 +595,28 @@ class MockClusterInvokerTest { @Test void testMockInvokerFromOverride_Invoke_check_ListPojo_empty() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + IHelloService.class.getName() - + "&" + "getUsers.mock=force:return empty")) + .addParameter( + REFER_KEY, + URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + + "getUsers.mock=force:return empty")) .addParameter("invoke_return_error", "true"); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getUsers"); Result ret = cluster.invoke(invocation); Assertions.assertEquals(0, ((List) ret.getValue()).size()); } + @Test void testMockInvokerFromOverride_Invoke_check_ListPojoAsync() throws ExecutionException, InterruptedException { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + IHelloService.class.getName() - + "&" + "getUsersAsync.mock=force")) - .addParameter("invoke_return_error", "true"); + .addParameter( + REFER_KEY, + URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getUsersAsync.mock=force")) + .addParameter("invoke_return_error", "true"); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getUsersAsync"); invocation.setReturnType(CompletableFuture.class); @@ -620,17 +631,17 @@ class MockClusterInvokerTest { Assertions.assertEquals("Tommock", cf.get().get(0).getName()); } - @SuppressWarnings("unchecked") @Test void testMockInvokerFromOverride_Invoke_check_ListPojo() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + IHelloService.class.getName() - + "&" + "getUsers.mock=force:return [{id:1, name:\"hi1\"}, {id:2, name:\"hi2\"}]")) + .addParameter( + REFER_KEY, + URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + + "getUsers.mock=force:return [{id:1, name:\"hi1\"}, {id:2, name:\"hi2\"}]")) .addParameter("invoke_return_error", "true"); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getUsers"); Result ret = cluster.invoke(invocation); @@ -643,12 +654,13 @@ class MockClusterInvokerTest { @Test void testMockInvokerFromOverride_Invoke_check_ListPojo_error() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + IHelloService.class.getName() - + "&" + "getUsers.mock=force:return [{id:x, name:\"hi1\"}]")) + .addParameter( + REFER_KEY, + URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + + "getUsers.mock=force:return [{id:x, name:\"hi1\"}]")) .addParameter("invoke_return_error", "true"); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getUsers"); try { @@ -660,12 +672,13 @@ class MockClusterInvokerTest { @Test void testMockInvokerFromOverride_Invoke_force_throw() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + IHelloService.class.getName() - + "&" + "getBoolean2.mock=force:throw ")) + .addParameter( + REFER_KEY, + URL.encode( + PATH_KEY + "=" + IHelloService.class.getName() + "&" + "getBoolean2.mock=force:throw ")) .addParameter("invoke_return_error", "true"); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getBoolean2"); try { @@ -679,12 +692,14 @@ class MockClusterInvokerTest { @Test void testMockInvokerFromOverride_Invoke_force_throwCustemException() throws Throwable { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + IHelloService.class.getName() - + "&" + "getBoolean2.mock=force:throw org.apache.dubbo.rpc.cluster.support.wrapper.MyMockException")) + .addParameter( + REFER_KEY, + URL.encode( + PATH_KEY + "=" + IHelloService.class.getName() + "&" + + "getBoolean2.mock=force:throw org.apache.dubbo.rpc.cluster.support.wrapper.MyMockException")) .addParameter("invoke_return_error", "true"); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getBoolean2"); try { @@ -698,12 +713,13 @@ class MockClusterInvokerTest { @Test void testMockInvokerFromOverride_Invoke_force_throwCustemExceptionNotFound() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + IHelloService.class.getName() - + "&" + "getBoolean2.mock=force:throw java.lang.RuntimeException2")) + .addParameter( + REFER_KEY, + URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + + "getBoolean2.mock=force:throw java.lang.RuntimeException2")) .addParameter("invoke_return_error", "true"); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getBoolean2"); try { @@ -717,12 +733,11 @@ class MockClusterInvokerTest { @Test void testMockInvokerFromOverride_Invoke_mock_false() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) - .addParameter(REFER_KEY, - URL.encode(PATH_KEY + "=" + IHelloService.class.getName() - + "&" + "mock=false")) + .addParameter( + REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() + "&" + "mock=false")) .addParameter("invoke_return_error", "true"); Invoker cluster = getClusterInvoker(url); - //Configured with mock + // Configured with mock RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getBoolean2"); try { @@ -734,10 +749,12 @@ class MockClusterInvokerTest { } private Invoker getClusterInvokerMock(URL url, Invoker mockInvoker) { - // As `javassist` have a strict restriction of argument types, request will fail if Invocation do not contains complete parameter type information + // As `javassist` have a strict restriction of argument types, request will fail if Invocation do not contains + // complete parameter type information final URL durl = url.addParameter("proxy", "jdk"); invokers.clear(); - ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getExtension("jdk"); + ProxyFactory proxy = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getExtension("jdk"); Invoker invoker1 = proxy.getInvoker(new HelloService(), IHelloService.class, durl); invokers.add(invoker1); if (mockInvoker != null) { @@ -819,17 +836,17 @@ class MockClusterInvokerTest { } public List getListString() { - return Arrays.asList(new String[]{"Tom", "Jerry"}); + return Arrays.asList(new String[] {"Tom", "Jerry"}); } public List getUsers() { - return Arrays.asList(new User[]{new User(1, "Tom"), new User(2, "Jerry")}); + return Arrays.asList(new User[] {new User(1, "Tom"), new User(2, "Jerry")}); } @Override public CompletableFuture> getUsersAsync() { - CompletableFuture> cf=new CompletableFuture<>(); - cf.complete(Arrays.asList(new User[]{new User(1, "Tom"), new User(2, "Jerry")})); + CompletableFuture> cf = new CompletableFuture<>(); + cf.complete(Arrays.asList(new User[] {new User(1, "Tom"), new User(2, "Jerry")})); return cf; } @@ -839,9 +856,7 @@ class MockClusterInvokerTest { } public static class IHelloServiceMock implements IHelloService { - public IHelloServiceMock() { - - } + public IHelloServiceMock() {} public String getSomething() { return "somethingmock"; @@ -860,17 +875,17 @@ class MockClusterInvokerTest { } public List getListString() { - return Arrays.asList(new String[]{"Tommock", "Jerrymock"}); + return Arrays.asList(new String[] {"Tommock", "Jerrymock"}); } public List getUsers() { - return Arrays.asList(new User[]{new User(1, "Tommock"), new User(2, "Jerrymock")}); + return Arrays.asList(new User[] {new User(1, "Tommock"), new User(2, "Jerrymock")}); } @Override public CompletableFuture> getUsersAsync() { - CompletableFuture> cf=new CompletableFuture<>(); - cf.complete(Arrays.asList(new User[]{new User(1, "Tommock"), new User(2, "Jerrymock")})); + CompletableFuture> cf = new CompletableFuture<>(); + cf.complete(Arrays.asList(new User[] {new User(1, "Tommock"), new User(2, "Jerrymock")})); return cf; } @@ -895,8 +910,7 @@ class MockClusterInvokerTest { private int id; private String name; - public User() { - } + public User() {} public User(int id, String name) { super(); @@ -919,6 +933,5 @@ class MockClusterInvokerTest { public void setName(String name) { this.name = name; } - } } diff --git a/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockProviderRpcExceptionTest.java b/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockProviderRpcExceptionTest.java index e692aae745..697f4b68d2 100644 --- a/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockProviderRpcExceptionTest.java +++ b/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MockProviderRpcExceptionTest.java @@ -28,16 +28,16 @@ import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.LoadBalance; import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker; - import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.rpc.Constants.MOCK_KEY; import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; @@ -58,8 +58,10 @@ class MockProviderRpcExceptionTest { @Test void testMockInvokerProviderRpcException() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloRpcService.class.getName()); - url = url.addParameter(MOCK_KEY, "true").addParameter("invoke_return_error", "true") - .addParameter(REFER_KEY, + url = url.addParameter(MOCK_KEY, "true") + .addParameter("invoke_return_error", "true") + .addParameter( + REFER_KEY, URL.encode(PATH_KEY + "=" + MockProviderRpcExceptionTest.IHelloRpcService.class.getName() + "&" + "mock=true" + "&" + "proxy=jdk")); @@ -68,15 +70,15 @@ class MockProviderRpcExceptionTest { invocation.setMethodName("getSomething4"); Result ret = cluster.invoke(invocation); Assertions.assertEquals("something4mock", ret.getValue()); - } - private Invoker getClusterInvokerMock(URL url, Invoker mockInvoker) { - // As `javassist` have a strict restriction of argument types, request will fail if Invocation do not contains complete parameter type information + // As `javassist` have a strict restriction of argument types, request will fail if Invocation do not contains + // complete parameter type information final URL durl = url.addParameter("proxy", "jdk"); invokers.clear(); - ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getExtension("jdk"); + ProxyFactory proxy = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getExtension("jdk"); Invoker invoker1 = proxy.getInvoker(new HelloRpcService(), IHelloRpcService.class, durl); invokers.add(invoker1); if (mockInvoker != null) { @@ -156,11 +158,11 @@ class MockProviderRpcExceptionTest { } public List getListString() { - return Arrays.asList(new String[]{"Tom", "Jerry"}); + return Arrays.asList(new String[] {"Tom", "Jerry"}); } public List getUsers() { - return Arrays.asList(new User[]{new User(1, "Tom"), new User(2, "Jerry")}); + return Arrays.asList(new User[] {new User(1, "Tom"), new User(2, "Jerry")}); } public void sayHello() { @@ -169,9 +171,7 @@ class MockProviderRpcExceptionTest { } public static class IHelloRpcServiceMock implements IHelloRpcService { - public IHelloRpcServiceMock() { - - } + public IHelloRpcServiceMock() {} public String getSomething() { return "somethingmock"; @@ -190,11 +190,11 @@ class MockProviderRpcExceptionTest { } public List getListString() { - return Arrays.asList(new String[]{"Tommock", "Jerrymock"}); + return Arrays.asList(new String[] {"Tommock", "Jerrymock"}); } public List getUsers() { - return Arrays.asList(new User[]{new User(1, "Tommock"), new User(2, "Jerrymock")}); + return Arrays.asList(new User[] {new User(1, "Tommock"), new User(2, "Jerrymock")}); } public int getInt1() { @@ -218,8 +218,7 @@ class MockProviderRpcExceptionTest { private int id; private String name; - public User() { - } + public User() {} public User(int id, String name) { super(); @@ -242,6 +241,5 @@ class MockProviderRpcExceptionTest { public void setName(String name) { this.name = name; } - } } diff --git a/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MyMockException.java b/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MyMockException.java index f353745cc7..9e10bc1c90 100644 --- a/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MyMockException.java +++ b/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/cluster/support/wrapper/MyMockException.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.support.wrapper; - public class MyMockException extends RuntimeException { private static final long serialVersionUID = 2851692379597990457L; @@ -24,5 +23,4 @@ public class MyMockException extends RuntimeException { public MyMockException(String message) { super(message); } - } diff --git a/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/DemoServiceAMock.java b/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/DemoServiceAMock.java index 23c623ac1f..928bb46382 100644 --- a/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/DemoServiceAMock.java +++ b/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/DemoServiceAMock.java @@ -19,8 +19,9 @@ package org.apache.dubbo.rpc.support; /** * default mock service for DemoServiceA */ -public class DemoServiceAMock implements DemoServiceA{ +public class DemoServiceAMock implements DemoServiceA { public static final String MOCK_VALUE = "mockA"; + @Override public String methodA() { return MOCK_VALUE; diff --git a/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/Greeting.java b/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/Greeting.java index 928f6d40b9..a1f97d3023 100644 --- a/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/Greeting.java +++ b/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/Greeting.java @@ -6,7 +6,7 @@ * (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 + * 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, diff --git a/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/GreetingMock1.java b/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/GreetingMock1.java index b79e2a9b68..e484f4aa18 100644 --- a/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/GreetingMock1.java +++ b/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/GreetingMock1.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -16,5 +16,4 @@ */ package org.apache.dubbo.rpc.support; -public class GreetingMock1 { -} +public class GreetingMock1 {} diff --git a/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/GreetingMock2.java b/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/GreetingMock2.java index 654478e04a..052f8832ef 100644 --- a/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/GreetingMock2.java +++ b/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/GreetingMock2.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -17,8 +17,7 @@ package org.apache.dubbo.rpc.support; public class GreetingMock2 implements Greeting { - private GreetingMock2() { - } + private GreetingMock2() {} @Override public String hello() { diff --git a/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/MockAbstractClusterInvokerTest.java b/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/MockAbstractClusterInvokerTest.java index cb0e2a7095..07ac207352 100644 --- a/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/MockAbstractClusterInvokerTest.java +++ b/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/MockAbstractClusterInvokerTest.java @@ -28,6 +28,12 @@ import org.apache.dubbo.rpc.cluster.LoadBalance; import org.apache.dubbo.rpc.cluster.directory.StaticDirectory; import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker; import org.apache.dubbo.rpc.model.ApplicationModel; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; @@ -35,11 +41,6 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import static org.apache.dubbo.common.constants.CommonConstants.ENABLE_CONNECTIVITY_VALIDATION; import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_AVAILABLE_CHECK_KEY; import static org.apache.dubbo.rpc.cluster.Constants.INVOCATION_NEED_MOCK; @@ -58,8 +59,11 @@ class MockAbstractClusterInvokerTest { AbstractClusterInvoker cluster_nocheck; StaticDirectory dic; RpcInvocation invocation = new RpcInvocation(); - URL url = URL.valueOf("registry://localhost:9090/org.apache.dubbo.rpc.cluster.support.AbstractClusterInvokerTest.IHelloService?refer=" + URL.encode("application=abstractClusterInvokerTest")); - URL consumerUrl = URL.valueOf("dubbo://localhost?application=abstractClusterInvokerTest&refer=application%3DabstractClusterInvokerTest"); + URL url = URL.valueOf( + "registry://localhost:9090/org.apache.dubbo.rpc.cluster.support.AbstractClusterInvokerTest.IHelloService?refer=" + + URL.encode("application=abstractClusterInvokerTest")); + URL consumerUrl = URL.valueOf( + "dubbo://localhost?application=abstractClusterInvokerTest&refer=application%3DabstractClusterInvokerTest"); Invoker invoker1; Invoker invoker2; @@ -131,24 +135,26 @@ class MockAbstractClusterInvokerTest { cluster = new AbstractClusterInvoker(dic) { @Override protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance) - throws RpcException { - return null; - } - }; - - cluster_nocheck = new AbstractClusterInvoker(dic, url.addParameterIfAbsent(CLUSTER_AVAILABLE_CHECK_KEY, Boolean.FALSE.toString())) { - @Override - protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance) - throws RpcException { + throws RpcException { return null; } }; + cluster_nocheck = + new AbstractClusterInvoker( + dic, url.addParameterIfAbsent(CLUSTER_AVAILABLE_CHECK_KEY, Boolean.FALSE.toString())) { + @Override + protected Result doInvoke(Invocation invocation, List invokers, LoadBalance loadbalance) + throws RpcException { + return null; + } + }; } private void initlistsize5() { invokers.clear(); - selectedInvokers.clear();//Clear first, previous test case will make sure that the right invoker2 will be used. + selectedInvokers + .clear(); // Clear first, previous test case will make sure that the right invoker2 will be used. invokers.add(invoker1); invokers.add(invoker2); invokers.add(invoker3); @@ -181,6 +187,5 @@ class MockAbstractClusterInvokerTest { Assertions.assertEquals(5, invokers.size()); } - public static interface IHelloService { - } + public static interface IHelloService {} } diff --git a/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/MockConfigPostProcessorTest.java b/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/MockConfigPostProcessorTest.java index 3ebb18e983..bffab58fc4 100644 --- a/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/MockConfigPostProcessorTest.java +++ b/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/MockConfigPostProcessorTest.java @@ -17,6 +17,7 @@ package org.apache.dubbo.rpc.support; import org.apache.dubbo.config.AbstractInterfaceConfig; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -28,7 +29,6 @@ class MockConfigPostProcessorTest { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setMock("return {a, b}"); MockConfigPostProcessor.checkMock(Greeting.class, interfaceConfig); - }); } @@ -50,7 +50,5 @@ class MockConfigPostProcessorTest { }); } - public static class InterfaceConfig extends AbstractInterfaceConfig { - - } + public static class InterfaceConfig extends AbstractInterfaceConfig {} } diff --git a/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/MockInvokerTest.java b/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/MockInvokerTest.java index 019b39c3f4..9769818621 100644 --- a/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/MockInvokerTest.java +++ b/dubbo-plugin/dubbo-plugin-mock/src/test/java/org/apache/dubbo/rpc/support/MockInvokerTest.java @@ -21,14 +21,14 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.io.Serializable; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.rpc.Constants.MOCK_KEY; class MockInvokerTest { @@ -46,12 +46,9 @@ class MockInvokerTest { Assertions.assertEquals("foo", MockInvoker.parseMockValue("\"foo\"")); Assertions.assertEquals("foo", MockInvoker.parseMockValue("\'foo\'")); - Assertions.assertEquals( - new HashMap<>(), MockInvoker.parseMockValue("{}")); - Assertions.assertEquals( - new ArrayList<>(), MockInvoker.parseMockValue("[]")); - Assertions.assertEquals("foo", - MockInvoker.parseMockValue("foo", new Type[]{String.class})); + Assertions.assertEquals(new HashMap<>(), MockInvoker.parseMockValue("{}")); + Assertions.assertEquals(new ArrayList<>(), MockInvoker.parseMockValue("[]")); + Assertions.assertEquals("foo", MockInvoker.parseMockValue("foo", new Type[] {String.class})); } @Test @@ -62,8 +59,7 @@ class MockInvokerTest { RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); - Assertions.assertEquals(new HashMap<>(), - mockInvoker.invoke(invocation).getObjectAttachments()); + Assertions.assertEquals(new HashMap<>(), mockInvoker.invoke(invocation).getObjectAttachments()); } @Test @@ -76,8 +72,7 @@ class MockInvokerTest { RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("methodA"); - Assertions.assertEquals(new HashMap<>(), - mockInvoker.invoke(invocation).getObjectAttachments()); + Assertions.assertEquals(new HashMap<>(), mockInvoker.invoke(invocation).getObjectAttachments()); // test methodB in DemoServiceBMock final Class demoServiceBClass = DemoServiceB.class; @@ -86,18 +81,15 @@ class MockInvokerTest { mockInvoker = new MockInvoker(url, demoServiceBClass); invocation = new RpcInvocation(); invocation.setMethodName("methodB"); - Assertions.assertEquals(new HashMap<>(), - mockInvoker.invoke(invocation).getObjectAttachments()); + Assertions.assertEquals(new HashMap<>(), mockInvoker.invoke(invocation).getObjectAttachments()); } - @Test void testInvokeThrowsRpcException1() { URL url = URL.valueOf("remote://1.2.3.4/" + String.class.getName()); MockInvoker mockInvoker = new MockInvoker(url, null); - Assertions.assertThrows(RpcException.class, - () -> mockInvoker.invoke(new RpcInvocation())); + Assertions.assertThrows(RpcException.class, () -> mockInvoker.invoke(new RpcInvocation())); } @Test @@ -108,8 +100,7 @@ class MockInvokerTest { RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); - Assertions.assertThrows(RpcException.class, - () -> mockInvoker.invoke(invocation)); + Assertions.assertThrows(RpcException.class, () -> mockInvoker.invoke(invocation)); } @Test @@ -120,29 +111,39 @@ class MockInvokerTest { RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("getSomething"); - Assertions.assertThrows(RpcException.class, - () -> mockInvoker.invoke(invocation)); + Assertions.assertThrows(RpcException.class, () -> mockInvoker.invoke(invocation)); } @Test void testGetThrowable() { - Assertions.assertThrows(RpcException.class, - () -> MockInvoker.getThrowable("Exception.class")); + Assertions.assertThrows(RpcException.class, () -> MockInvoker.getThrowable("Exception.class")); } @Test void testGetMockObject() { - Assertions.assertEquals("", - MockInvoker.getMockObject(ApplicationModel.defaultModel().getExtensionDirector(), "java.lang.String", String.class)); + Assertions.assertEquals( + "", + MockInvoker.getMockObject( + ApplicationModel.defaultModel().getExtensionDirector(), "java.lang.String", String.class)); - Assertions.assertThrows(IllegalStateException.class, () -> MockInvoker - .getMockObject(ApplicationModel.defaultModel().getExtensionDirector(), "true", String.class)); - Assertions.assertThrows(IllegalStateException.class, () -> MockInvoker - .getMockObject(ApplicationModel.defaultModel().getExtensionDirector(), "default", String.class)); - Assertions.assertThrows(IllegalStateException.class, () -> MockInvoker - .getMockObject(ApplicationModel.defaultModel().getExtensionDirector(), "java.lang.String", Integer.class)); - Assertions.assertThrows(IllegalStateException.class, () -> MockInvoker - .getMockObject(ApplicationModel.defaultModel().getExtensionDirector(), "java.io.Serializable", Serializable.class)); + Assertions.assertThrows( + IllegalStateException.class, + () -> MockInvoker.getMockObject( + ApplicationModel.defaultModel().getExtensionDirector(), "true", String.class)); + Assertions.assertThrows( + IllegalStateException.class, + () -> MockInvoker.getMockObject( + ApplicationModel.defaultModel().getExtensionDirector(), "default", String.class)); + Assertions.assertThrows( + IllegalStateException.class, + () -> MockInvoker.getMockObject( + ApplicationModel.defaultModel().getExtensionDirector(), "java.lang.String", Integer.class)); + Assertions.assertThrows( + IllegalStateException.class, + () -> MockInvoker.getMockObject( + ApplicationModel.defaultModel().getExtensionDirector(), + "java.io.Serializable", + Serializable.class)); } @Test @@ -156,11 +157,8 @@ class MockInvokerTest { Assertions.assertEquals("default", MockInvoker.normalizeMock("fail")); Assertions.assertEquals("default", MockInvoker.normalizeMock("force")); Assertions.assertEquals("default", MockInvoker.normalizeMock("true")); - Assertions.assertEquals("default", - MockInvoker.normalizeMock("default")); - Assertions.assertEquals("return null", - MockInvoker.normalizeMock("return")); - Assertions.assertEquals("return null", - MockInvoker.normalizeMock("return null")); + Assertions.assertEquals("default", MockInvoker.normalizeMock("default")); + Assertions.assertEquals("return null", MockInvoker.normalizeMock("return")); + Assertions.assertEquals("return null", MockInvoker.normalizeMock("return null")); } } diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/pom.xml b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/pom.xml index 37e9f143f3..ac2b0b9d64 100644 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/pom.xml +++ b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + - dubbo-plugin-proxy-bytebuddy - jar + dubbo-plugin-proxy-bytebuddy + jar - - - org.apache.dubbo - dubbo-rpc-api - ${project.version} - - - net.bytebuddy - byte-buddy - - + + + org.apache.dubbo + dubbo-rpc-api + ${project.version} + + + net.bytebuddy + byte-buddy + + diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyInterceptor.java b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyInterceptor.java index 6670af89b8..25d5311d2e 100644 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyInterceptor.java +++ b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyInterceptor.java @@ -16,14 +16,14 @@ */ package org.apache.dubbo.rpc.proxy.bytebuddy; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; + import net.bytebuddy.implementation.bind.annotation.AllArguments; import net.bytebuddy.implementation.bind.annotation.Origin; import net.bytebuddy.implementation.bind.annotation.RuntimeType; import net.bytebuddy.implementation.bind.annotation.This; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; - public class ByteBuddyInterceptor { private final InvocationHandler handler; @@ -33,8 +33,8 @@ public class ByteBuddyInterceptor { } @RuntimeType - public Object intercept(@This Object obj, @AllArguments Object[] allArguments, - @Origin Method method) throws Throwable { + public Object intercept(@This Object obj, @AllArguments Object[] allArguments, @Origin Method method) + throws Throwable { return handler.invoke(obj, method, allArguments); } } diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxy.java b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxy.java index ccc25b9df7..d414e542a1 100644 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxy.java +++ b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxy.java @@ -14,15 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.proxy.bytebuddy; -import net.bytebuddy.ByteBuddy; -import net.bytebuddy.description.ByteCodeElement; -import net.bytebuddy.implementation.MethodDelegation; -import net.bytebuddy.matcher.ElementMatcher; -import net.bytebuddy.matcher.ElementMatchers; - import java.lang.reflect.Constructor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; @@ -32,6 +25,12 @@ import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; +import net.bytebuddy.ByteBuddy; +import net.bytebuddy.description.ByteCodeElement; +import net.bytebuddy.implementation.MethodDelegation; +import net.bytebuddy.matcher.ElementMatcher; +import net.bytebuddy.matcher.ElementMatchers; + import static org.apache.dubbo.common.constants.CommonConstants.MAX_PROXY_COUNT; public class ByteBuddyProxy { @@ -89,17 +88,18 @@ public class ByteBuddyProxy { private static Class buildProxyClass(ClassLoader cl, Class[] ics, InvocationHandler handler) { ElementMatcher.Junction methodMatcher = Arrays.stream(ics) - .map(ElementMatchers::isDeclaredBy).reduce(ElementMatcher.Junction::or) - .orElse(ElementMatchers.none()).and(ElementMatchers - .not(ElementMatchers.isDeclaredBy(Object.class))); + .map(ElementMatchers::isDeclaredBy) + .reduce(ElementMatcher.Junction::or) + .orElse(ElementMatchers.none()) + .and(ElementMatchers.not(ElementMatchers.isDeclaredBy(Object.class))); return new ByteBuddy() - .subclass(Proxy.class) - .implement(ics) - .method(methodMatcher) - .intercept(MethodDelegation.to(new ByteBuddyInterceptor(handler))) - .make() - .load(cl) - .getLoaded(); + .subclass(Proxy.class) + .implement(ics) + .method(methodMatcher) + .intercept(MethodDelegation.to(new ByteBuddyInterceptor(handler))) + .make() + .load(cl) + .getLoaded(); } private static class CacheKey { diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyInvoker.java b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyInvoker.java index 2f5761c39e..9fd1778384 100644 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyInvoker.java +++ b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyInvoker.java @@ -24,16 +24,14 @@ class ByteBuddyProxyInvoker extends AbstractProxyInvoker { private final MethodInvoker methodInvoker; - private ByteBuddyProxyInvoker(T proxy, - Class type, - URL url, - MethodInvoker methodInvoker) { + private ByteBuddyProxyInvoker(T proxy, Class type, URL url, MethodInvoker methodInvoker) { super(proxy, type, url); this.methodInvoker = methodInvoker; } @Override - protected Object doInvoke(T instance, String methodName, Class[] parameterTypes, Object[] arguments) throws Throwable { + protected Object doInvoke(T instance, String methodName, Class[] parameterTypes, Object[] arguments) + throws Throwable { if ("getClass".equals(methodName)) { return instance.getClass(); } diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/AbstractProxyTest.java b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/AbstractProxyTest.java index 1703dfea20..09158b38df 100644 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/AbstractProxyTest.java +++ b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/AbstractProxyTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.proxy; import org.apache.dubbo.common.URL; @@ -26,11 +25,11 @@ import org.apache.dubbo.rpc.service.EchoService; import org.apache.dubbo.rpc.support.DemoService; import org.apache.dubbo.rpc.support.DemoServiceImpl; import org.apache.dubbo.rpc.support.MyInvoker; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.util.Arrays; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public abstract class AbstractProxyTest { @@ -50,13 +49,19 @@ public abstract class AbstractProxyTest { Assertions.assertTrue(Arrays.asList(proxy.getClass().getInterfaces()).contains(Destroyable.class)); Assertions.assertTrue(Arrays.asList(proxy.getClass().getInterfaces()).contains(EchoService.class)); - Assertions.assertEquals(invoker.invoke(new RpcInvocation("echo", DemoService.class.getName(), DemoService.class.getName() + ":dubbo", new Class[]{String.class}, new Object[]{"aa"})).getValue() - , proxy.echo("aa")); + Assertions.assertEquals( + invoker.invoke(new RpcInvocation( + "echo", + DemoService.class.getName(), + DemoService.class.getName() + ":dubbo", + new Class[] {String.class}, + new Object[] {"aa"})) + .getValue(), + proxy.echo("aa")); - Destroyable destroyable = (Destroyable)proxy; + Destroyable destroyable = (Destroyable) proxy; destroyable.$destroy(); Assertions.assertTrue(invoker.isDestroyed()); - } @Test @@ -69,9 +74,14 @@ public abstract class AbstractProxyTest { Assertions.assertEquals(invoker.getInterface(), DemoService.class); - Assertions.assertEquals(invoker.invoke(new RpcInvocation("echo", DemoService.class.getName(), DemoService.class.getName() + ":dubbo", new Class[]{String.class}, new Object[]{"aa"})).getValue(), + Assertions.assertEquals( + invoker.invoke(new RpcInvocation( + "echo", + DemoService.class.getName(), + DemoService.class.getName() + ":dubbo", + new Class[] {String.class}, + new Object[] {"aa"})) + .getValue(), origin.echo("aa")); - } - } diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyInterceptorTest.java b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyInterceptorTest.java index 1ac609d3c9..3ea668a532 100644 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyInterceptorTest.java +++ b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyInterceptorTest.java @@ -16,18 +16,18 @@ */ package org.apache.dubbo.rpc.proxy.bytebuddy; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + class ByteBuddyInterceptorTest { @AfterEach - public void after(){ + public void after() { Mockito.clearAllCaches(); } @@ -39,7 +39,7 @@ class ByteBuddyInterceptorTest { Proxy proxy = Mockito.mock(Proxy.class); Object[] args = new Object[0]; interceptor.intercept(proxy, args, method); - //'intercept' method will call 'invoke' method directly + // 'intercept' method will call 'invoke' method directly Mockito.verify(handler, Mockito.times(1)).invoke(proxy, method, args); } } diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactoryTest.java b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactoryTest.java index dc86d4b924..776dfa3d6c 100644 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactoryTest.java +++ b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactoryTest.java @@ -23,5 +23,4 @@ class ByteBuddyProxyFactoryTest extends AbstractProxyTest { static { AbstractProxyTest.factory = new ByteBuddyProxyFactory(); } - } diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyInvokerTest.java b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyInvokerTest.java index 2a11557295..6dd9c004a3 100644 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyInvokerTest.java +++ b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyInvokerTest.java @@ -18,6 +18,7 @@ package org.apache.dubbo.rpc.proxy.bytebuddy; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.proxy.RemoteService; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -28,11 +29,13 @@ class ByteBuddyProxyInvokerTest { void testNewInstance() throws Throwable { URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); RemoteService proxy = Mockito.mock(RemoteService.class); - ByteBuddyProxyInvoker invoker = ByteBuddyProxyInvoker.newInstance(proxy, RemoteService.class, url); - invoker.doInvoke(proxy, "sayHello", new Class[]{String.class}, new Object[]{"test"}); + ByteBuddyProxyInvoker invoker = + ByteBuddyProxyInvoker.newInstance(proxy, RemoteService.class, url); + invoker.doInvoke(proxy, "sayHello", new Class[] {String.class}, new Object[] {"test"}); Mockito.verify(proxy, Mockito.times(1)).sayHello("test"); - Assertions.assertThrows(IllegalArgumentException.class, - () -> invoker.doInvoke(proxy, "equals", new Class[]{String.class}, new Object[]{"test", "test2"})); + Assertions.assertThrows( + IllegalArgumentException.class, + () -> invoker.doInvoke(proxy, "equals", new Class[] {String.class}, new Object[] {"test", "test2"})); } } diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyTest.java b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyTest.java index 1e2295a0b8..9cf18e41d6 100644 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyTest.java +++ b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyTest.java @@ -18,11 +18,12 @@ package org.apache.dubbo.rpc.proxy.bytebuddy; import org.apache.dubbo.rpc.proxy.InvokerInvocationHandler; import org.apache.dubbo.rpc.proxy.RemoteService; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; import java.lang.reflect.Proxy; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.mockito.ArgumentMatchers.any; @@ -32,7 +33,7 @@ class ByteBuddyProxyTest { void testNewInstance() throws Throwable { ClassLoader cl = Thread.currentThread().getContextClassLoader(); InvokerInvocationHandler handler = Mockito.mock(InvokerInvocationHandler.class); - Object proxy = ByteBuddyProxy.newInstance(cl, new Class[]{RemoteService.class}, handler); + Object proxy = ByteBuddyProxy.newInstance(cl, new Class[] {RemoteService.class}, handler); assertInstanceOf(RemoteService.class, proxy); assertInstanceOf(Proxy.class, proxy); RemoteService remoteService = (RemoteService) proxy; diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/support/DemoServiceImpl.java b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/support/DemoServiceImpl.java index 10517401af..90fd7b1f84 100644 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/support/DemoServiceImpl.java +++ b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/support/DemoServiceImpl.java @@ -19,7 +19,6 @@ package org.apache.dubbo.rpc.support; /** * DemoServiceImpl */ - public class DemoServiceImpl implements DemoService { public String echo(String text) { return text; diff --git a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java index f2dbe07081..670a3f7885 100644 --- a/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java +++ b/dubbo-plugin/dubbo-plugin-proxy-bytebuddy/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java @@ -86,5 +86,4 @@ public class MyInvoker implements Invoker { public String toString() { return "MyInvoker.toString()"; } - } diff --git a/dubbo-plugin/dubbo-plugin-qos-trace/pom.xml b/dubbo-plugin/dubbo-plugin-qos-trace/pom.xml index 85b41090e5..7eea74506a 100644 --- a/dubbo-plugin/dubbo-plugin-qos-trace/pom.xml +++ b/dubbo-plugin/dubbo-plugin-qos-trace/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + - dubbo-plugin-qos-trace - jar + dubbo-plugin-qos-trace + jar - - - org.apache.dubbo - dubbo-cluster - ${project.version} - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - - + + + org.apache.dubbo + dubbo-cluster + ${project.version} + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + + diff --git a/dubbo-plugin/dubbo-plugin-qos-trace/src/main/java/org/apache/dubbo/qos/legacy/ChangeTelnetHandler.java b/dubbo-plugin/dubbo-plugin-qos-trace/src/main/java/org/apache/dubbo/qos/legacy/ChangeTelnetHandler.java index dd570a1518..b2adaf0592 100644 --- a/dubbo-plugin/dubbo-plugin-qos-trace/src/main/java/org/apache/dubbo/qos/legacy/ChangeTelnetHandler.java +++ b/dubbo-plugin/dubbo-plugin-qos-trace/src/main/java/org/apache/dubbo/qos/legacy/ChangeTelnetHandler.java @@ -55,12 +55,13 @@ public class ChangeTelnetHandler implements TelnetHandler { } if (found) { channel.setAttribute(SERVICE_KEY, message); - buf.append("Used the ").append(message).append(" as default.\r\nYou can cancel default service by command: cd /"); + buf.append("Used the ") + .append(message) + .append(" as default.\r\nYou can cancel default service by command: cd /"); } else { buf.append("No such service ").append(message); } } return buf.toString(); } - } diff --git a/dubbo-plugin/dubbo-plugin-qos-trace/src/main/java/org/apache/dubbo/qos/legacy/TraceTelnetHandler.java b/dubbo-plugin/dubbo-plugin-qos-trace/src/main/java/org/apache/dubbo/qos/legacy/TraceTelnetHandler.java index d4d6397dd1..b4d6b2a01a 100644 --- a/dubbo-plugin/dubbo-plugin-qos-trace/src/main/java/org/apache/dubbo/qos/legacy/TraceTelnetHandler.java +++ b/dubbo-plugin/dubbo-plugin-qos-trace/src/main/java/org/apache/dubbo/qos/legacy/TraceTelnetHandler.java @@ -38,8 +38,7 @@ public class TraceTelnetHandler implements TelnetHandler { @Override public String telnet(Channel channel, String message) { String service = (String) channel.getAttribute(ChangeTelnetHandler.SERVICE_KEY); - if ((StringUtils.isEmpty(service)) - && (StringUtils.isEmpty(message))) { + if ((StringUtils.isEmpty(service)) && (StringUtils.isEmpty(message))) { return "Please input service name, eg: \r\ntrace XxxService\r\ntrace XxxService xxxMethod\r\ntrace XxxService xxxMethod 10\r\nor \"cd XxxService\" firstly."; } String[] parts = message.split("\\s+"); @@ -50,7 +49,7 @@ public class TraceTelnetHandler implements TelnetHandler { service = parts.length > 0 ? parts[0] : null; method = parts.length > 1 ? parts[1] : null; times = parts.length > 2 ? parts[2] : "1"; - } else { //message like : xxxMethod, xxxMethod 10 + } else { // message like : xxxMethod, xxxMethod 10 method = parts.length > 0 ? parts[0] : null; times = parts.length > 1 ? parts[1] : "1"; } @@ -80,7 +79,8 @@ public class TraceTelnetHandler implements TelnetHandler { } } if (!found) { - return "No such method " + method + " in class " + invoker.getInterface().getName(); + return "No such method " + method + " in class " + + invoker.getInterface().getName(); } } TraceFilter.addTracer(invoker.getInterface(), method, channel, Integer.parseInt(times)); @@ -89,5 +89,4 @@ public class TraceTelnetHandler implements TelnetHandler { } return null; } - } diff --git a/dubbo-plugin/dubbo-plugin-qos-trace/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java b/dubbo-plugin/dubbo-plugin-qos-trace/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java index f26692e722..b856e8d57b 100644 --- a/dubbo-plugin/dubbo-plugin-qos-trace/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java +++ b/dubbo-plugin/dubbo-plugin-qos-trace/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java @@ -103,13 +103,16 @@ public class TraceFilter implements Filter { } count = c.getAndIncrement(); if (count < max) { - String prompt = channel.getUrl().getParameter(Constants.PROMPT_KEY, Constants.DEFAULT_PROMPT); - channel.send("\r\n" + RpcContext.getServiceContext().getRemoteAddress() + " -> " - + invoker.getInterface().getName() - + "." + RpcUtils.getMethodName(invocation) - + "(" + JsonUtils.toJson(invocation.getArguments()) + ")" + " -> " + JsonUtils.toJson(result.getValue()) - + "\r\nelapsed: " + (end - start) + " ms." - + "\r\n\r\n" + prompt); + String prompt = + channel.getUrl().getParameter(Constants.PROMPT_KEY, Constants.DEFAULT_PROMPT); + channel.send( + "\r\n" + RpcContext.getServiceContext().getRemoteAddress() + " -> " + + invoker.getInterface().getName() + + "." + RpcUtils.getMethodName(invocation) + + "(" + JsonUtils.toJson(invocation.getArguments()) + ")" + " -> " + + JsonUtils.toJson(result.getValue()) + + "\r\nelapsed: " + (end - start) + " ms." + + "\r\n\r\n" + prompt); } if (count >= max - 1) { channels.remove(channel); @@ -126,5 +129,4 @@ public class TraceFilter implements Filter { } return result; } - } diff --git a/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/qos/legacy/ChangeTelnetHandlerTest.java b/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/qos/legacy/ChangeTelnetHandlerTest.java index 8f62f49ad1..51d2fc993d 100644 --- a/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/qos/legacy/ChangeTelnetHandlerTest.java +++ b/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/qos/legacy/ChangeTelnetHandlerTest.java @@ -49,16 +49,15 @@ class ChangeTelnetHandlerTest { private static int portIncrease; @AfterAll - public static void tearDown() { - - } + public static void tearDown() {} @SuppressWarnings("unchecked") @BeforeEach public void setUp() { mockChannel = mock(Channel.class); mockInvoker = mock(Invoker.class); - given(mockChannel.getAttribute("telnet.service")).willReturn("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService"); + given(mockChannel.getAttribute("telnet.service")) + .willReturn("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService"); mockChannel.setAttribute("telnet.service", "DemoService"); givenLastCall(); mockChannel.setAttribute("telnet.service", "org.apache.dubbo.rpc.protocol.dubbo.support.DemoService"); @@ -71,9 +70,7 @@ class ChangeTelnetHandlerTest { given(mockInvoker.getUrl()).willReturn(URL.valueOf("dubbo://127.0.0.1:" + (20994 + portIncrease++) + "/demo")); } - private void givenLastCall() { - - } + private void givenLastCall() {} @AfterEach public void after() { @@ -83,22 +80,29 @@ class ChangeTelnetHandlerTest { @Test void testChangeSimpleName() throws RemotingException { - ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(DubboProtocol.NAME).export(mockInvoker); + ExtensionLoader.getExtensionLoader(Protocol.class) + .getExtension(DubboProtocol.NAME) + .export(mockInvoker); String result = change.telnet(mockChannel, "DemoService"); assertEquals("Used the DemoService as default.\r\nYou can cancel default service by command: cd /", result); } @Test void testChangeName() throws RemotingException { - ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(DubboProtocol.NAME).export(mockInvoker); + ExtensionLoader.getExtensionLoader(Protocol.class) + .getExtension(DubboProtocol.NAME) + .export(mockInvoker); String result = change.telnet(mockChannel, "org.apache.dubbo.qos.legacy.service.DemoService"); - assertEquals("Used the org.apache.dubbo.qos.legacy.service.DemoService as default.\r\nYou can cancel default service by command: cd /", + assertEquals( + "Used the org.apache.dubbo.qos.legacy.service.DemoService as default.\r\nYou can cancel default service by command: cd /", result); } @Test void testChangePath() throws RemotingException { - ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(DubboProtocol.NAME).export(mockInvoker); + ExtensionLoader.getExtensionLoader(Protocol.class) + .getExtension(DubboProtocol.NAME) + .export(mockInvoker); String result = change.telnet(mockChannel, "demo"); assertEquals("Used the demo as default.\r\nYou can cancel default service by command: cd /", result); } diff --git a/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/qos/legacy/ProtocolUtils.java b/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/qos/legacy/ProtocolUtils.java index c2a088f6ce..7b6cd2b27d 100644 --- a/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/qos/legacy/ProtocolUtils.java +++ b/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/qos/legacy/ProtocolUtils.java @@ -35,7 +35,8 @@ public class ProtocolUtils { public static T refer(Class type, URL url) { Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + ProxyFactory proxy = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); return proxy.getProxy(protocol.refer(type, url)); } @@ -45,7 +46,8 @@ public class ProtocolUtils { public static Exporter export(T instance, Class type, URL url) { Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + ProxyFactory proxy = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); return protocol.export(proxy.getInvoker(instance, type, url)); } diff --git a/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/qos/legacy/TraceTelnetHandlerTest.java b/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/qos/legacy/TraceTelnetHandlerTest.java index 8c0adeb65a..567d171fbe 100644 --- a/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/qos/legacy/TraceTelnetHandlerTest.java +++ b/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/qos/legacy/TraceTelnetHandlerTest.java @@ -27,15 +27,15 @@ import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; import org.apache.dubbo.rpc.protocol.dubbo.filter.TraceFilter; +import java.lang.reflect.Field; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.lang.reflect.Field; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; @@ -68,7 +68,9 @@ class TraceTelnetHandlerTest { String message = "org.apache.dubbo.qos.legacy.service.DemoService sayHello 1"; Class type = DemoService.class; - ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(DubboProtocol.NAME).export(mockInvoker); + ExtensionLoader.getExtensionLoader(Protocol.class) + .getExtension(DubboProtocol.NAME) + .export(mockInvoker); handler.telnet(mockChannel, message); String key = type.getName() + "." + method; @@ -82,4 +84,4 @@ class TraceTelnetHandlerTest { Assertions.assertTrue(channels.contains(mockChannel)); } -} \ No newline at end of file +} diff --git a/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/qos/legacy/channel/MockChannel.java b/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/qos/legacy/channel/MockChannel.java index 4eb09a30ed..6410aa475f 100644 --- a/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/qos/legacy/channel/MockChannel.java +++ b/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/qos/legacy/channel/MockChannel.java @@ -40,9 +40,7 @@ public class MockChannel implements Channel { private List receivedObjects = new LinkedList<>(); private CountDownLatch latch; - public MockChannel() { - - } + public MockChannel() {} public MockChannel(URL remoteUrl) { this.remoteUrl = remoteUrl; diff --git a/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/qos/legacy/service/DemoService.java b/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/qos/legacy/service/DemoService.java index dcdaf8c50a..00226cd9fa 100644 --- a/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/qos/legacy/service/DemoService.java +++ b/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/qos/legacy/service/DemoService.java @@ -19,7 +19,6 @@ package org.apache.dubbo.qos.legacy.service; /** * TestService */ - public interface DemoService { void sayHello(String name); } diff --git a/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/filter/MockChannel.java b/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/filter/MockChannel.java index f8df7e4749..4f21521f51 100644 --- a/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/filter/MockChannel.java +++ b/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/filter/MockChannel.java @@ -33,8 +33,7 @@ public class MockChannel implements Channel { private List receivedObjects = new LinkedList<>(); private URL url; - public MockChannel() { - } + public MockChannel() {} public MockChannel(URL url) { this.url = url; @@ -96,19 +95,13 @@ public class MockChannel implements Channel { } @Override - public void close() { - - } + public void close() {} @Override - public void close(int timeout) { - - } + public void close(int timeout) {} @Override - public void startClose() { - - } + public void startClose() {} @Override public boolean isClosed() { diff --git a/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilterTest.java b/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilterTest.java index 77418d81b4..f9a87c8274 100644 --- a/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilterTest.java +++ b/dubbo-plugin/dubbo-plugin-qos-trace/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilterTest.java @@ -24,17 +24,17 @@ import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.lang.reflect.Field; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -70,7 +70,8 @@ class TraceFilterTest { Field tracers = TraceFilter.class.getDeclaredField(TRACERS_FIELD_NAME); tracers.setAccessible(true); - ConcurrentHashMap> o = (ConcurrentHashMap>) tracers.get(new ConcurrentHashMap>()); + ConcurrentHashMap> o = + (ConcurrentHashMap>) tracers.get(new ConcurrentHashMap>()); Assertions.assertTrue(o.containsKey(key)); Set channels = o.get(key); @@ -117,7 +118,8 @@ class TraceFilterTest { filter.invoke(mockInvoker, mockInvocation); Field tracers = TraceFilter.class.getDeclaredField(TRACERS_FIELD_NAME); tracers.setAccessible(true); - ConcurrentHashMap> o = (ConcurrentHashMap>) tracers.get(new ConcurrentHashMap>()); + ConcurrentHashMap> o = + (ConcurrentHashMap>) tracers.get(new ConcurrentHashMap>()); Assertions.assertTrue(o.containsKey(key)); Set channels = o.get(key); Assertions.assertNotNull(channels); diff --git a/dubbo-plugin/dubbo-plugin-router-condition/pom.xml b/dubbo-plugin/dubbo-plugin-router-condition/pom.xml index 4a865c2772..8593e5e40b 100644 --- a/dubbo-plugin/dubbo-plugin-router-condition/pom.xml +++ b/dubbo-plugin/dubbo-plugin-router-condition/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + - dubbo-plugin-router-condition - jar + dubbo-plugin-router-condition + jar - - - org.apache.dubbo - dubbo-cluster - ${project.version} - - + + + org.apache.dubbo + dubbo-cluster + ${project.version} + + diff --git a/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouter.java b/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouter.java index ddbb1966e6..b89395ca69 100644 --- a/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouter.java +++ b/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouter.java @@ -84,7 +84,8 @@ public class ConditionStateRouter extends AbstractStateRouter { super(url); this.setForce(force); this.enabled = enabled; - matcherFactories = moduleModel.getExtensionLoader(ConditionMatcherFactory.class).getActivateExtensions(); + matcherFactories = + moduleModel.getExtensionLoader(ConditionMatcherFactory.class).getActivateExtensions(); if (enabled) { this.init(rule); } @@ -94,7 +95,8 @@ public class ConditionStateRouter extends AbstractStateRouter { super(url); this.setUrl(url); this.setForce(url.getParameter(FORCE_KEY, false)); - matcherFactories = moduleModel.getExtensionLoader(ConditionMatcherFactory.class).getActivateExtensions(); + matcherFactories = + moduleModel.getExtensionLoader(ConditionMatcherFactory.class).getActivateExtensions(); this.enabled = url.getParameter(ENABLED_KEY, true); if (enabled) { init(url.getParameterAndDecoded(RULE_KEY)); @@ -110,8 +112,10 @@ public class ConditionStateRouter extends AbstractStateRouter { int i = rule.indexOf("=>"); String whenRule = i < 0 ? null : rule.substring(0, i).trim(); String thenRule = i < 0 ? rule.trim() : rule.substring(i + 2).trim(); - Map when = StringUtils.isBlank(whenRule) || "true".equals(whenRule) ? new HashMap<>() : parseRule(whenRule); - Map then = StringUtils.isBlank(thenRule) || "false".equals(thenRule) ? null : parseRule(thenRule); + Map when = + StringUtils.isBlank(whenRule) || "true".equals(whenRule) ? new HashMap<>() : parseRule(whenRule); + Map then = + StringUtils.isBlank(thenRule) || "false".equals(thenRule) ? null : parseRule(thenRule); // NOTE: It should be determined on the business level whether the `When condition` can be empty or not. this.whenCondition = when; this.thenCondition = then; @@ -120,8 +124,7 @@ public class ConditionStateRouter extends AbstractStateRouter { } } - private Map parseRule(String rule) - throws ParseException { + private Map parseRule(String rule) throws ParseException { Map condition = new HashMap<>(); if (StringUtils.isBlank(rule)) { return condition; @@ -151,10 +154,12 @@ public class ConditionStateRouter extends AbstractStateRouter { // The Value in the KV part. else if ("=".equals(separator)) { if (matcherPair == null) { - throw new ParseException("Illegal route rule \"" - + rule + "\", The error char '" + separator - + "' at index " + matcher.start() + " before \"" - + content + "\".", matcher.start()); + throw new ParseException( + "Illegal route rule \"" + + rule + "\", The error char '" + separator + + "' at index " + matcher.start() + " before \"" + + content + "\".", + matcher.start()); } values = matcherPair.getMatches(); @@ -163,10 +168,12 @@ public class ConditionStateRouter extends AbstractStateRouter { // The Value in the KV part. else if ("!=".equals(separator)) { if (matcherPair == null) { - throw new ParseException("Illegal route rule \"" - + rule + "\", The error char '" + separator - + "' at index " + matcher.start() + " before \"" - + content + "\".", matcher.start()); + throw new ParseException( + "Illegal route rule \"" + + rule + "\", The error char '" + separator + + "' at index " + matcher.start() + " before \"" + + content + "\".", + matcher.start()); } values = matcherPair.getMismatches(); @@ -175,25 +182,34 @@ public class ConditionStateRouter extends AbstractStateRouter { // The Value in the KV part, if Value have more than one items. else if (",".equals(separator)) { // Should be separated by ',' if (values == null || values.isEmpty()) { - throw new ParseException("Illegal route rule \"" - + rule + "\", The error char '" + separator - + "' at index " + matcher.start() + " before \"" - + content + "\".", matcher.start()); + throw new ParseException( + "Illegal route rule \"" + + rule + "\", The error char '" + separator + + "' at index " + matcher.start() + " before \"" + + content + "\".", + matcher.start()); } values.add(content); } else { - throw new ParseException("Illegal route rule \"" + rule - + "\", The error char '" + separator + "' at index " - + matcher.start() + " before \"" + content + "\".", matcher.start()); + throw new ParseException( + "Illegal route rule \"" + rule + + "\", The error char '" + separator + "' at index " + + matcher.start() + " before \"" + content + "\".", + matcher.start()); } } return condition; } @Override - protected BitList> doRoute(BitList> invokers, URL url, Invocation invocation, - boolean needToPrintMessage, Holder> nodeHolder, - Holder messageHolder) throws RpcException { + protected BitList> doRoute( + BitList> invokers, + URL url, + Invocation invocation, + boolean needToPrintMessage, + Holder> nodeHolder, + Holder messageHolder) + throws RpcException { if (!enabled) { if (needToPrintMessage) { messageHolder.set("Directly return. Reason: ConditionRouter disabled."); @@ -215,7 +231,13 @@ public class ConditionStateRouter extends AbstractStateRouter { return invokers; } if (thenCondition == null) { - logger.warn(CLUSTER_CONDITIONAL_ROUTE_LIST_EMPTY,"condition state router thenCondition is empty","","The current consumer in the service blacklist. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey()); if (needToPrintMessage) { + logger.warn( + CLUSTER_CONDITIONAL_ROUTE_LIST_EMPTY, + "condition state router thenCondition is empty", + "", + "The current consumer in the service blacklist. consumer: " + NetUtils.getLocalHost() + + ", service: " + url.getServiceKey()); + if (needToPrintMessage) { messageHolder.set("Empty return. Reason: ThenCondition is empty."); } return BitList.emptyList(); @@ -229,14 +251,26 @@ public class ConditionStateRouter extends AbstractStateRouter { } return result; } else if (this.isForce()) { - logger.warn(CLUSTER_CONDITIONAL_ROUTE_LIST_EMPTY,"execute condition state router result list is empty. and force=true","","The route result is empty and force execute. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey() + ", router: " + url.getParameterAndDecoded(RULE_KEY)); + logger.warn( + CLUSTER_CONDITIONAL_ROUTE_LIST_EMPTY, + "execute condition state router result list is empty. and force=true", + "", + "The route result is empty and force execute. consumer: " + NetUtils.getLocalHost() + + ", service: " + url.getServiceKey() + ", router: " + + url.getParameterAndDecoded(RULE_KEY)); if (needToPrintMessage) { messageHolder.set("Empty return. Reason: Empty result from condition and condition is force."); } return result; } } catch (Throwable t) { - logger.error(CLUSTER_FAILED_EXEC_CONDITION_ROUTER,"execute condition state router exception","","Failed to execute condition router rule: " + getUrl() + ", invokers: " + invokers + ", cause: " + t.getMessage(),t); + logger.error( + CLUSTER_FAILED_EXEC_CONDITION_ROUTER, + "execute condition state router exception", + "", + "Failed to execute condition router rule: " + getUrl() + ", invokers: " + invokers + ", cause: " + + t.getMessage(), + t); } if (needToPrintMessage) { messageHolder.set("Directly return. Reason: Error occurred ( or result is empty )."); @@ -247,7 +281,7 @@ public class ConditionStateRouter extends AbstractStateRouter { @Override public boolean isRuntime() { // We always return true for previously defined Router, that is, old Router doesn't support cache anymore. -// return true; + // return true; return this.getUrl().getParameter(RUNTIME_KEY, false); } @@ -257,7 +291,10 @@ public class ConditionStateRouter extends AbstractStateRouter { return factory.createMatcher(key, moduleModel); } } - return moduleModel.getExtensionLoader(ConditionMatcherFactory.class).getExtension("param").createMatcher(key, moduleModel); + return moduleModel + .getExtensionLoader(ConditionMatcherFactory.class) + .getExtension("param") + .createMatcher(key, moduleModel); } boolean matchWhen(URL url, Invocation invocation) { @@ -276,7 +313,12 @@ public class ConditionStateRouter extends AbstractStateRouter { return doMatch(url, param, null, thenCondition, false); } - private boolean doMatch(URL url, URL param, Invocation invocation, Map conditions, boolean isWhenCondition) { + private boolean doMatch( + URL url, + URL param, + Invocation invocation, + Map conditions, + boolean isWhenCondition) { Map sample = url.toOriginalMap(); for (Map.Entry entry : conditions.entrySet()) { ConditionMatcher matchPair = entry.getValue(); diff --git a/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableStateRouter.java b/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableStateRouter.java index 0efbe0be39..575bd46282 100644 --- a/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableStateRouter.java +++ b/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableStateRouter.java @@ -50,7 +50,8 @@ public abstract class ListenableStateRouter extends AbstractStateRouter im public static final String NAME = "LISTENABLE_ROUTER"; public static final String RULE_SUFFIX = ".condition-router"; - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ListenableStateRouter.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ListenableStateRouter.class); private volatile ConditionRouterRule routerRule; private volatile List> conditionRouters = Collections.emptyList(); private final String ruleKey; @@ -65,8 +66,8 @@ public abstract class ListenableStateRouter extends AbstractStateRouter im @Override public synchronized void process(ConfigChangedEvent event) { if (logger.isInfoEnabled()) { - logger.info("Notification of condition rule, change type is: " + event.getChangeType() + - ", raw rule is:\n " + event.getContent()); + logger.info("Notification of condition rule, change type is: " + event.getChangeType() + ", raw rule is:\n " + + event.getContent()); } if (event.getChangeType().equals(ConfigChangeType.DELETED)) { @@ -77,18 +78,31 @@ public abstract class ListenableStateRouter extends AbstractStateRouter im routerRule = ConditionRuleParser.parse(event.getContent()); generateConditions(routerRule); } catch (Exception e) { - logger.error(CLUSTER_FAILED_RULE_PARSING,"Failed to parse the raw condition rule","","Failed to parse the raw condition rule and it will not take effect, please check " + - "if the condition rule matches with the template, the raw rule is:\n " + event.getContent(),e); + logger.error( + CLUSTER_FAILED_RULE_PARSING, + "Failed to parse the raw condition rule", + "", + "Failed to parse the raw condition rule and it will not take effect, please check " + + "if the condition rule matches with the template, the raw rule is:\n " + + event.getContent(), + e); } } } @Override - public BitList> doRoute(BitList> invokers, URL url, Invocation invocation, - boolean needToPrintMessage, Holder> nodeHolder, Holder messageHolder) throws RpcException { + public BitList> doRoute( + BitList> invokers, + URL url, + Invocation invocation, + boolean needToPrintMessage, + Holder> nodeHolder, + Holder messageHolder) + throws RpcException { if (CollectionUtils.isEmpty(invokers) || conditionRouters.size() == 0) { if (needToPrintMessage) { - messageHolder.set("Directly return. Reason: Invokers from previous router is empty or conditionRouters is empty."); + messageHolder.set( + "Directly return. Reason: Invokers from previous router is empty or conditionRouters is empty."); } return invokers; } @@ -123,9 +137,9 @@ public abstract class ListenableStateRouter extends AbstractStateRouter im private void generateConditions(ConditionRouterRule rule) { if (rule != null && rule.isValid()) { - this.conditionRouters = rule.getConditions() - .stream() - .map(condition -> new ConditionStateRouter(getUrl(), condition, rule.isForce(), rule.isEnabled())) + this.conditionRouters = rule.getConditions().stream() + .map(condition -> + new ConditionStateRouter(getUrl(), condition, rule.isForce(), rule.isEnabled())) .collect(Collectors.toList()); for (ConditionStateRouter conditionRouter : this.conditionRouters) { conditionRouter.setNextRouter(TailStateRouter.getInstance()); diff --git a/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppStateRouter.java b/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppStateRouter.java index b39b316766..09bf667895 100644 --- a/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppStateRouter.java +++ b/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppStateRouter.java @@ -33,7 +33,8 @@ import static org.apache.dubbo.common.utils.StringUtils.isEmpty; * Application level router, "application.condition-router" */ public class ProviderAppStateRouter extends ListenableStateRouter { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ListenableStateRouter.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ListenableStateRouter.class); public static final String NAME = "PROVIDER_APP_ROUTER"; private String application; private final String currentApplication; @@ -55,7 +56,11 @@ public class ProviderAppStateRouter extends ListenableStateRouter { // provider application is empty or equals with the current application if (isEmpty(providerApplication)) { - logger.warn(CLUSTER_TAG_ROUTE_EMPTY, "condition router get providerApplication is empty, will not subscribe to provider app rules.", "", ""); + logger.warn( + CLUSTER_TAG_ROUTE_EMPTY, + "condition router get providerApplication is empty, will not subscribe to provider app rules.", + "", + ""); return; } if (providerApplication.equals(currentApplication)) { diff --git a/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceStateRouterFactory.java b/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceStateRouterFactory.java index d5f3d6ca24..ecc536953b 100644 --- a/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceStateRouterFactory.java +++ b/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceStateRouterFactory.java @@ -34,5 +34,4 @@ public class ServiceStateRouterFactory extends CacheableStateRouterFactory { protected StateRouter createRouter(Class interfaceClass, URL url) { return new ServiceStateRouter(url); } - } diff --git a/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRouterRule.java b/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRouterRule.java index 0cfb8bdf4b..7d9c936c3f 100644 --- a/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRouterRule.java +++ b/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRouterRule.java @@ -34,15 +34,14 @@ public class ConditionRouterRule extends AbstractRouterRule { Object conditions = map.get(CONDITIONS_KEY); if (conditions != null && List.class.isAssignableFrom(conditions.getClass())) { - conditionRouterRule.setConditions(((List) conditions).stream() - .map(String::valueOf).collect(Collectors.toList())); + conditionRouterRule.setConditions( + ((List) conditions).stream().map(String::valueOf).collect(Collectors.toList())); } return conditionRouterRule; } - public ConditionRouterRule() { - } + public ConditionRouterRule() {} public List getConditions() { return conditions; diff --git a/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRuleParser.java b/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRuleParser.java index 699a18b90a..9aa80f908b 100644 --- a/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRuleParser.java +++ b/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRuleParser.java @@ -18,12 +18,12 @@ package org.apache.dubbo.rpc.cluster.router.condition.config.model; import org.apache.dubbo.common.utils.CollectionUtils; +import java.util.Map; + import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.SafeConstructor; -import java.util.Map; - /** * %YAML1.2 * @@ -51,5 +51,4 @@ public class ConditionRuleParser { return rule; } - } diff --git a/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/AbstractConditionMatcher.java b/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/AbstractConditionMatcher.java index db5cd94b95..992b42d087 100644 --- a/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/AbstractConditionMatcher.java +++ b/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/AbstractConditionMatcher.java @@ -38,7 +38,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAIL * provides the common match logics. */ public abstract class AbstractConditionMatcher implements ConditionMatcher { - public static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractConditionMatcher.class); + public static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(AbstractConditionMatcher.class); public static final String DOES_NOT_FOUND_VALUE = "dubbo_internal_not_found_argument_condition_value"; final Set matches = new HashSet<>(); final Set mismatches = new HashSet<>(); @@ -52,9 +53,10 @@ public abstract class AbstractConditionMatcher implements ConditionMatcher { this.valueMatchers = model.getExtensionLoader(ValuePattern.class).getActivateExtensions(); } - public static String getSampleValueFromUrl(String conditionKey, Map sample, URL param, Invocation invocation) { + public static String getSampleValueFromUrl( + String conditionKey, Map sample, URL param, Invocation invocation) { String sampleValue; - //get real invoked method name from invocation + // get real invoked method name from invocation if (invocation != null && (METHOD_KEY.equals(conditionKey) || METHODS_KEY.equals(conditionKey))) { sampleValue = RpcUtils.getMethodName(invocation); } else { @@ -67,7 +69,8 @@ public abstract class AbstractConditionMatcher implements ConditionMatcher { public boolean isMatch(Map sample, URL param, Invocation invocation, boolean isWhenCondition) { String value = getValue(sample, param, invocation); if (value == null) { - // if key does not present in whichever of url, invocation or attachment based on the matcher type, then return false. + // if key does not present in whichever of url, invocation or attachment based on the matcher type, then + // return false. return false; } @@ -90,7 +93,7 @@ public abstract class AbstractConditionMatcher implements ConditionMatcher { } if (!matches.isEmpty() && !mismatches.isEmpty()) { - //when both mismatches and matches contain the same value, then using mismatches first + // when both mismatches and matches contain the same value, then using mismatches first for (String mismatch : mismatches) { if (doPatternMatch(mismatch, value, param, invocation, isWhenCondition)) { return false; @@ -117,16 +120,23 @@ public abstract class AbstractConditionMatcher implements ConditionMatcher { } // range, equal or other methods - protected boolean doPatternMatch(String pattern, String value, URL url, Invocation invocation, boolean isWhenCondition) { + protected boolean doPatternMatch( + String pattern, String value, URL url, Invocation invocation, boolean isWhenCondition) { for (ValuePattern valueMatcher : valueMatchers) { if (valueMatcher.shouldMatch(pattern)) { return valueMatcher.match(pattern, value, url, invocation, isWhenCondition); } } // this should never happen. - logger.error(CLUSTER_FAILED_EXEC_CONDITION_ROUTER, "Executing condition rule value match expression error.", "pattern is " + pattern + ", value is " + value + ", condition type " + (isWhenCondition ? "when" : "then"), "There should at least has one ValueMatcher instance that applies to all patterns, will force to use wildcard matcher now."); + logger.error( + CLUSTER_FAILED_EXEC_CONDITION_ROUTER, + "Executing condition rule value match expression error.", + "pattern is " + pattern + ", value is " + value + ", condition type " + + (isWhenCondition ? "when" : "then"), + "There should at least has one ValueMatcher instance that applies to all patterns, will force to use wildcard matcher now."); - ValuePattern paramValueMatcher = model.getExtensionLoader(ValuePattern.class).getExtension("wildcard"); + ValuePattern paramValueMatcher = + model.getExtensionLoader(ValuePattern.class).getExtension("wildcard"); return paramValueMatcher.match(pattern, value, url, invocation, isWhenCondition); } @@ -135,5 +145,4 @@ public abstract class AbstractConditionMatcher implements ConditionMatcher { * This makes condition rule possible to check values in any place of a request. */ protected abstract String getValue(Map sample, URL url, Invocation invocation); - } diff --git a/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/argument/ArgumentConditionMatcher.java b/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/argument/ArgumentConditionMatcher.java index d66bff1f38..6fcf78246b 100644 --- a/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/argument/ArgumentConditionMatcher.java +++ b/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/argument/ArgumentConditionMatcher.java @@ -38,7 +38,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAIL */ @Activate public class ArgumentConditionMatcher extends AbstractConditionMatcher { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ArgumentConditionMatcher.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ArgumentConditionMatcher.class); private static final Pattern ARGUMENTS_PATTERN = Pattern.compile("arguments\\[([0-9]+)\\]"); public ArgumentConditionMatcher(String key, ModuleModel model) { @@ -56,16 +57,21 @@ public class ArgumentConditionMatcher extends AbstractConditionMatcher { return DOES_NOT_FOUND_VALUE; } - //extract the argument index + // extract the argument index int index = Integer.parseInt(matcher.group(1)); if (index < 0 || index > invocation.getArguments().length) { return DOES_NOT_FOUND_VALUE; } - //extract the argument value + // extract the argument value return String.valueOf(invocation.getArguments()[index]); } catch (Exception e) { - logger.warn(CLUSTER_FAILED_EXEC_CONDITION_ROUTER, "Parse argument match condition failed", "", "Invalid , will ignore., ", e); + logger.warn( + CLUSTER_FAILED_EXEC_CONDITION_ROUTER, + "Parse argument match condition failed", + "", + "Invalid , will ignore., ", + e); } return DOES_NOT_FOUND_VALUE; } diff --git a/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/attachment/AttachmentConditionMatcher.java b/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/attachment/AttachmentConditionMatcher.java index c7dc148100..60fd727e4f 100644 --- a/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/attachment/AttachmentConditionMatcher.java +++ b/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/attachment/AttachmentConditionMatcher.java @@ -38,7 +38,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAIL */ @Activate public class AttachmentConditionMatcher extends AbstractConditionMatcher { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AttachmentConditionMatcher.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(AttachmentConditionMatcher.class); private static final Pattern ATTACHMENTS_PATTERN = Pattern.compile("attachments\\[(.+)\\]"); public AttachmentConditionMatcher(String key, ModuleModel model) { @@ -56,20 +57,21 @@ public class AttachmentConditionMatcher extends AbstractConditionMatcher { return DOES_NOT_FOUND_VALUE; } - //extract the argument index + // extract the argument index String attachmentKey = matcher.group(1); if (StringUtils.isEmpty(attachmentKey)) { return DOES_NOT_FOUND_VALUE; } - //extract the argument value + // extract the argument value return invocation.getAttachment(attachmentKey); } catch (Exception e) { - logger.warn(CLUSTER_FAILED_EXEC_CONDITION_ROUTER, - "condition state router attachment match failed", - "", - "Invalid match condition: " + key, - e); + logger.warn( + CLUSTER_FAILED_EXEC_CONDITION_ROUTER, + "condition state router attachment match failed", + "", + "Invalid match condition: " + key, + e); } return DOES_NOT_FOUND_VALUE; } diff --git a/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/param/UrlParamConditionMatcher.java b/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/param/UrlParamConditionMatcher.java index b1a8d5ba58..23ae175381 100644 --- a/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/param/UrlParamConditionMatcher.java +++ b/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/param/UrlParamConditionMatcher.java @@ -37,5 +37,4 @@ public class UrlParamConditionMatcher extends AbstractConditionMatcher { protected String getValue(Map sample, URL url, Invocation invocation) { return getSampleValueFromUrl(key, sample, url, invocation); } - } diff --git a/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/pattern/range/RangeValuePattern.java b/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/pattern/range/RangeValuePattern.java index f876b3b377..5ed7e44903 100644 --- a/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/pattern/range/RangeValuePattern.java +++ b/dubbo-plugin/dubbo-plugin-router-condition/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/pattern/range/RangeValuePattern.java @@ -46,7 +46,11 @@ public class RangeValuePattern implements ValuePattern { String[] arr = pattern.split("~"); if (arr.length < 2) { - logger.error(CLUSTER_FAILED_EXEC_CONDITION_ROUTER, "", "", "Invalid condition rule " + pattern + " or value " + value + ", will ignore."); + logger.error( + CLUSTER_FAILED_EXEC_CONDITION_ROUTER, + "", + "", + "Invalid condition rule " + pattern + " or value " + value + ", will ignore."); return defaultValue; } @@ -75,7 +79,12 @@ public class RangeValuePattern implements ValuePattern { } } } catch (Exception e) { - logger.error(CLUSTER_FAILED_EXEC_CONDITION_ROUTER, "Parse integer error", "", "Invalid condition rule " + pattern + " or value " + value + ", will ignore.", e); + logger.error( + CLUSTER_FAILED_EXEC_CONDITION_ROUTER, + "Parse integer error", + "", + "Invalid condition rule " + pattern + " or value " + value + ", will ignore.", + e); return defaultValue; } diff --git a/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java b/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java index aad1d49e19..0e1a4b1b5e 100644 --- a/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java +++ b/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/directory/MockDirInvocation.java @@ -16,16 +16,16 @@ */ package org.apache.dubbo.rpc.cluster.directory; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; - import org.apache.dubbo.rpc.AttachmentsAdapter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.model.ServiceModel; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; + import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; @@ -70,11 +70,11 @@ class MockDirInvocation implements Invocation { } public Class[] getParameterTypes() { - return new Class[]{String.class}; + return new Class[] {String.class}; } public Object[] getArguments() { - return new Object[]{"aa"}; + return new Object[] {"aa"}; } public Map getAttachments() { @@ -103,7 +103,7 @@ class MockDirInvocation implements Invocation { @Override public void setAttachment(String key, Object value) { - setObjectAttachment(key, value); + setObjectAttachment(key, value); } @Override @@ -141,9 +141,7 @@ class MockDirInvocation implements Invocation { } @Override - public void setServiceModel(ServiceModel serviceModel) { - - } + public void setServiceModel(ServiceModel serviceModel) {} @Override public ServiceModel getServiceModel() { @@ -169,9 +167,7 @@ class MockDirInvocation implements Invocation { } @Override - public void addInvokedInvoker(Invoker invoker) { - - } + public void addInvokedInvoker(Invoker invoker) {} @Override public List> getInvokedInvokers() { @@ -186,5 +182,4 @@ class MockDirInvocation implements Invocation { } return result; } - } diff --git a/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java b/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java index 68ee46afb1..d18bb8fe66 100644 --- a/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java +++ b/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/directory/StaticDirectoryTest.java @@ -28,12 +28,12 @@ import org.apache.dubbo.rpc.cluster.router.state.BitList; import org.apache.dubbo.rpc.cluster.router.state.StateRouter; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY; /** @@ -48,20 +48,28 @@ class StaticDirectoryTest { @Test void testStaticDirectory() { - StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl(" => " + " host = " + NetUtils.getLocalHost())); + StateRouter router = new ConditionStateRouterFactory() + .getRouter(String.class, getRouteUrl(" => " + " host = " + NetUtils.getLocalHost())); List routers = new ArrayList(); routers.add(router); List> originInvokers = new ArrayList>(); - Invoker invoker1 = new MockInvoker(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"), true); - Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService"), true); - Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService"), true); + Invoker invoker1 = + new MockInvoker(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService"), true); + Invoker invoker2 = new MockInvoker( + URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService"), true); + Invoker invoker3 = new MockInvoker( + URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880/com.foo.BarService"), true); originInvokers.add(invoker1); originInvokers.add(invoker2); originInvokers.add(invoker3); BitList> invokers = new BitList<>(originInvokers); - - List> filteredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), new RpcInvocation(), false, new Holder<>()); + List> filteredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/com.foo.BarService"), + new RpcInvocation(), + false, + new Holder<>()); ApplicationModel.defaultModel().getBeanFactory().registerBean(MetricsDispatcher.class); StaticDirectory staticDirectory = new StaticDirectory<>(filteredInvokers); boolean isAvailable = staticDirectory.isAvailable(); diff --git a/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/router/ConfigConditionRouterTest.java b/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/router/ConfigConditionRouterTest.java index 8cc7f5b1d1..5290fc65a1 100644 --- a/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/router/ConfigConditionRouterTest.java +++ b/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/router/ConfigConditionRouterTest.java @@ -29,23 +29,22 @@ class ConfigConditionRouterTest { @BeforeEach public void init() { - client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", 60 * 1000, 60 * 1000, - new ExponentialBackoffRetry(1000, 3)); + client = CuratorFrameworkFactory.newClient( + "127.0.0.1:2181", 60 * 1000, 60 * 1000, new ExponentialBackoffRetry(1000, 3)); client.start(); } @Test void normalConditionRuleApplicationLevelTest() { - String serviceStr = "---\n" + - "scope: application\n" + - "force: true\n" + - "runtime: true\n" + - "enabled: true\n" + - "priority: 2\n" + - "key: demo-consumer\n" + - "conditions:\n" + - " - method=notExitMethod => \n" + - "..."; + String serviceStr = "---\n" + "scope: application\n" + + "force: true\n" + + "runtime: true\n" + + "enabled: true\n" + + "priority: 2\n" + + "key: demo-consumer\n" + + "conditions:\n" + + " - method=notExitMethod => \n" + + "..."; try { String servicePath = "/dubbo/config/demo-consumer/condition-router"; if (client.checkExists().forPath(servicePath) == null) { @@ -59,17 +58,16 @@ class ConfigConditionRouterTest { @Test void normalConditionRuleApplicationServiceLevelTest() { - String serviceStr = "---\n" + - "scope: application\n" + - "force: true\n" + - "runtime: false\n" + - "enabled: true\n" + - "priority: 2\n" + - "key: demo-consumer\n" + - "conditions:\n" + - " - interface=org.apache.dubbo.demo.DemoService&method=sayHello => host=30.5.120.37\n" + - " - method=routeMethod1 => host=30.5.120.37\n" + - "..."; + String serviceStr = "---\n" + "scope: application\n" + + "force: true\n" + + "runtime: false\n" + + "enabled: true\n" + + "priority: 2\n" + + "key: demo-consumer\n" + + "conditions:\n" + + " - interface=org.apache.dubbo.demo.DemoService&method=sayHello => host=30.5.120.37\n" + + " - method=routeMethod1 => host=30.5.120.37\n" + + "..."; try { String servicePath = "/dubbo/config/demo-consumer/condition-router"; if (client.checkExists().forPath(servicePath) == null) { @@ -83,18 +81,17 @@ class ConfigConditionRouterTest { @Test void normalConditionRuleServiceLevelTest() { - String serviceStr = "---\n" + - "scope: service\n" + - "force: true\n" + - "runtime: true\n" + - "enabled: true\n" + - "priority: 1\n" + - "key: org.apache.dubbo.demo.DemoService\n" + - "conditions:\n" + - " - method!=sayHello =>\n" + - " - method=routeMethod1 => address=30.5.120.37:20880\n" + - "..."; -// String serviceStr = ""; + String serviceStr = "---\n" + "scope: service\n" + + "force: true\n" + + "runtime: true\n" + + "enabled: true\n" + + "priority: 1\n" + + "key: org.apache.dubbo.demo.DemoService\n" + + "conditions:\n" + + " - method!=sayHello =>\n" + + " - method=routeMethod1 => address=30.5.120.37:20880\n" + + "..."; + // String serviceStr = ""; try { String servicePath = "/dubbo/config/org.apache.dubbo.demo.DemoService/condition-router"; if (client.checkExists().forPath(servicePath) == null) { @@ -108,14 +105,13 @@ class ConfigConditionRouterTest { @Test void abnormalNoruleConditionRuleTest() { - String serviceStr = "---\n" + - "scope: service\n" + - "force: true\n" + - "runtime: false\n" + - "enabled: true\n" + - "priority: 1\n" + - "key: org.apache.dubbo.demo.DemoService\n" + - "..."; + String serviceStr = "---\n" + "scope: service\n" + + "force: true\n" + + "runtime: false\n" + + "enabled: true\n" + + "priority: 1\n" + + "key: org.apache.dubbo.demo.DemoService\n" + + "..."; try { String servicePath = "/dubbo/config/org.apache.dubbo.demo.DemoService/condition-router"; if (client.checkExists().forPath(servicePath) == null) { diff --git a/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/router/MockInvoker.java b/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/router/MockInvoker.java index 11a87dcf09..7de1783028 100644 --- a/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/router/MockInvoker.java +++ b/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/router/MockInvoker.java @@ -26,8 +26,7 @@ public class MockInvoker implements Invoker { private boolean available = false; private URL url; - public MockInvoker() { - } + public MockInvoker() {} public MockInvoker(URL url) { super(); @@ -64,6 +63,5 @@ public class MockInvoker implements Invoker { } @Override - public void destroy() { - } + public void destroy() {} } diff --git a/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouterTest.java b/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouterTest.java index 4735e7970b..080f7584c9 100644 --- a/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouterTest.java +++ b/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouterTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.router.condition; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.Holder; import org.apache.dubbo.rpc.Invocation; @@ -26,14 +25,14 @@ import org.apache.dubbo.rpc.cluster.router.MockInvoker; import org.apache.dubbo.rpc.cluster.router.state.BitList; import org.apache.dubbo.rpc.cluster.router.state.StateRouter; +import java.util.ArrayList; +import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.ArrayList; -import java.util.List; - import static org.apache.dubbo.rpc.cluster.Constants.FORCE_KEY; import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY; @@ -42,12 +41,10 @@ class ConditionStateRouterTest { private URL SCRIPT_URL = URL.valueOf("condition://0.0.0.0/com.foo.BarService"); @BeforeAll - public static void setUpBeforeClass() throws Exception { - } + public static void setUpBeforeClass() throws Exception {} @BeforeEach - public void setUp() throws Exception { - } + public void setUp() throws Exception {} private URL getRouteUrl(String rule) { return SCRIPT_URL.addParameterAndEncoded(RULE_KEY, rule); @@ -57,44 +54,65 @@ class ConditionStateRouterTest { void testRoute_matchWhen() { Invocation invocation = new RpcInvocation(); - StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl(" => host = 1.2.3.4")); - boolean matchWhen = ((ConditionStateRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation); + StateRouter router = + new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl(" => host = 1.2.3.4")); + boolean matchWhen = ((ConditionStateRouter) router) + .matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation); Assertions.assertTrue(matchWhen); - router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4")); - matchWhen = ((ConditionStateRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation); + router = new ConditionStateRouterFactory() + .getRouter(String.class, getRouteUrl("host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4")); + matchWhen = ((ConditionStateRouter) router) + .matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation); Assertions.assertTrue(matchWhen); - router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = 2.2.2.2,1.1.1.1,3.3.3.3 & host !=1.1.1.1 => host = 1.2.3.4")); - matchWhen = ((ConditionStateRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation); + router = new ConditionStateRouterFactory() + .getRouter( + String.class, getRouteUrl("host = 2.2.2.2,1.1.1.1,3.3.3.3 & host !=1.1.1.1 => host = 1.2.3.4")); + matchWhen = ((ConditionStateRouter) router) + .matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation); Assertions.assertFalse(matchWhen); - router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host !=4.4.4.4 & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4")); - matchWhen = ((ConditionStateRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation); + router = new ConditionStateRouterFactory() + .getRouter( + String.class, getRouteUrl("host !=4.4.4.4 & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4")); + matchWhen = ((ConditionStateRouter) router) + .matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation); Assertions.assertTrue(matchWhen); - router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4")); - matchWhen = ((ConditionStateRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation); + router = new ConditionStateRouterFactory() + .getRouter( + String.class, getRouteUrl("host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4")); + matchWhen = ((ConditionStateRouter) router) + .matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation); Assertions.assertTrue(matchWhen); - router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.1 => host = 1.2.3.4")); - matchWhen = ((ConditionStateRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation); + router = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.1 => host = 1.2.3.4")); + matchWhen = ((ConditionStateRouter) router) + .matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation); Assertions.assertFalse(matchWhen); - router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.2 => host = 1.2.3.4")); - matchWhen = ((ConditionStateRouter) router).matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation); + router = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.2 => host = 1.2.3.4")); + matchWhen = ((ConditionStateRouter) router) + .matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService"), invocation); Assertions.assertTrue(matchWhen); } @Test void testRoute_matchFilter() { List> originInvokers = new ArrayList>(); - Invoker invoker1 = new MockInvoker(URL.valueOf( - "dubbo://10.20.3.3:20880/com.foo.BarService?serialization=fastjson")); - Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST - + ":20880/com.foo.BarService")); - Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST - + ":20880/com.foo.BarService")); + Invoker invoker1 = new MockInvoker( + URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService?serialization=fastjson")); + Invoker invoker2 = + new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker3 = + new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); originInvokers.add(invoker1); originInvokers.add(invoker2); originInvokers.add(invoker3); @@ -103,33 +121,73 @@ class ConditionStateRouterTest { System.err.println("The localhost address: " + invoker2.getUrl().getAddress()); System.err.println(invoker3.getUrl().getAddress()); - StateRouter router1 = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl( - "host = " + LOCAL_HOST + " => " + " host = 10.20.3.3").addParameter(FORCE_KEY, - String.valueOf(true))); - StateRouter router2 = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl( - "host = " + LOCAL_HOST + " => " + " host = 10.20.3.* & host != 10.20.3.3").addParameter( - FORCE_KEY, String.valueOf(true))); - StateRouter router3 = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl( - "host = " + LOCAL_HOST + " => " + " host = 10.20.3.3 & host != 10.20.3.3").addParameter( - FORCE_KEY, String.valueOf(true))); - StateRouter router4 = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl( - "host = " + LOCAL_HOST + " => " + " host = 10.20.3.2,10.20.3.3,10.20.3.4").addParameter( - FORCE_KEY, String.valueOf(true))); - StateRouter router5 = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl( - "host = " + LOCAL_HOST + " => " + " host != 10.20.3.3").addParameter(FORCE_KEY, - String.valueOf(true))); - StateRouter router6 = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl( - "host = " + LOCAL_HOST + " => " + " serialization = fastjson").addParameter( - FORCE_KEY, String.valueOf(true))); + StateRouter router1 = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 10.20.3.3") + .addParameter(FORCE_KEY, String.valueOf(true))); + StateRouter router2 = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 10.20.3.* & host != 10.20.3.3") + .addParameter(FORCE_KEY, String.valueOf(true))); + StateRouter router3 = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 10.20.3.3 & host != 10.20.3.3") + .addParameter(FORCE_KEY, String.valueOf(true))); + StateRouter router4 = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 10.20.3.2,10.20.3.3,10.20.3.4") + .addParameter(FORCE_KEY, String.valueOf(true))); + StateRouter router5 = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("host = " + LOCAL_HOST + " => " + " host != 10.20.3.3") + .addParameter(FORCE_KEY, String.valueOf(true))); + StateRouter router6 = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("host = " + LOCAL_HOST + " => " + " serialization = fastjson") + .addParameter(FORCE_KEY, String.valueOf(true))); - - - List> filteredInvokers1 = router1.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false, new Holder<>()); - List> filteredInvokers2 = router2.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false, new Holder<>()); - List> filteredInvokers3 = router3.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false, new Holder<>()); - List> filteredInvokers4 = router4.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false, new Holder<>()); - List> filteredInvokers5 = router5.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false, new Holder<>()); - List> filteredInvokers6 = router6.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false, new Holder<>()); + List> filteredInvokers1 = router1.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + new RpcInvocation(), + false, + new Holder<>()); + List> filteredInvokers2 = router2.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + new RpcInvocation(), + false, + new Holder<>()); + List> filteredInvokers3 = router3.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + new RpcInvocation(), + false, + new Holder<>()); + List> filteredInvokers4 = router4.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + new RpcInvocation(), + false, + new Holder<>()); + List> filteredInvokers5 = router5.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + new RpcInvocation(), + false, + new Holder<>()); + List> filteredInvokers6 = router6.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + new RpcInvocation(), + false, + new Holder<>()); Assertions.assertEquals(1, filteredInvokers1.size()); Assertions.assertEquals(0, filteredInvokers2.size()); Assertions.assertEquals(0, filteredInvokers3.size()); @@ -142,106 +200,146 @@ class ConditionStateRouterTest { void testRoute_methodRoute() { Invocation invocation = new RpcInvocation("getFoo", "com.foo.BarService", "", new Class[0], new Object[0]); // More than one methods, mismatch - StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("methods=getFoo => host = 1.2.3.4")); - boolean matchWhen = ((ConditionStateRouter) router).matchWhen( - URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=setFoo,getFoo,findFoo"), invocation); + StateRouter router = new ConditionStateRouterFactory() + .getRouter(String.class, getRouteUrl("methods=getFoo => host = 1.2.3.4")); + boolean matchWhen = ((ConditionStateRouter) router) + .matchWhen( + URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=setFoo,getFoo,findFoo"), invocation); Assertions.assertTrue(matchWhen); // Exactly one method, match - matchWhen = ((ConditionStateRouter) router).matchWhen( - URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=getFoo"), invocation); + matchWhen = ((ConditionStateRouter) router) + .matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=getFoo"), invocation); Assertions.assertTrue(matchWhen); // Method routing and Other condition routing can work together StateRouter router2 = new ConditionStateRouterFactory() .getRouter(String.class, getRouteUrl("methods=getFoo & host!=1.1.1.1 => host = 1.2.3.4")); - matchWhen = ((ConditionStateRouter) router2).matchWhen( - URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=getFoo"), invocation); + matchWhen = ((ConditionStateRouter) router2) + .matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=getFoo"), invocation); Assertions.assertFalse(matchWhen); StateRouter router3 = new ConditionStateRouterFactory() .getRouter(String.class, getRouteUrl("methods=getFoo & host=1.1.1.1 => host = 1.2.3.4")); - matchWhen = ((ConditionStateRouter) router3).matchWhen( - URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=getFoo"), invocation); + matchWhen = ((ConditionStateRouter) router3) + .matchWhen(URL.valueOf("consumer://1.1.1.1/com.foo.BarService?methods=getFoo"), invocation); Assertions.assertTrue(matchWhen); // Test filter condition List> originInvokers = new ArrayList>(); Invoker invoker1 = new MockInvoker(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService")); - Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST - + ":20880/com.foo.BarService")); - Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST - + ":20880/com.foo.BarService")); + Invoker invoker2 = + new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker3 = + new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); originInvokers.add(invoker1); originInvokers.add(invoker2); originInvokers.add(invoker3); BitList> invokers = new BitList<>(originInvokers); - StateRouter router4 = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl( - "host = " + LOCAL_HOST + " & methods = getFoo => " + " host = 10.20.3.3").addParameter( - FORCE_KEY, String.valueOf(true))); - List> filteredInvokers1 = router4.route(invokers.clone(), - URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation, false, new Holder<>()); + StateRouter router4 = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("host = " + LOCAL_HOST + " & methods = getFoo => " + " host = 10.20.3.3") + .addParameter(FORCE_KEY, String.valueOf(true))); + List> filteredInvokers1 = router4.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + invocation, + false, + new Holder<>()); Assertions.assertEquals(1, filteredInvokers1.size()); - StateRouter router5 = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl( - "host = " + LOCAL_HOST + " & methods = unvalidmethod => " + " host = 10.20.3.3") - .addParameter(FORCE_KEY, String.valueOf(true))); - List> filteredInvokers2 = router5.route(invokers.clone(), - URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation, false, new Holder<>()); + StateRouter router5 = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("host = " + LOCAL_HOST + " & methods = unvalidmethod => " + " host = 10.20.3.3") + .addParameter(FORCE_KEY, String.valueOf(true))); + List> filteredInvokers2 = router5.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + invocation, + false, + new Holder<>()); Assertions.assertEquals(3, filteredInvokers2.size()); // Request a non-exists method } @Test void testRoute_ReturnFalse() { - StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => false")); + StateRouter router = new ConditionStateRouterFactory() + .getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => false")); List> originInvokers = new ArrayList>(); originInvokers.add(new MockInvoker()); originInvokers.add(new MockInvoker()); originInvokers.add(new MockInvoker()); BitList> invokers = new BitList<>(originInvokers); - List> filteredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false, new Holder<>()); + List> filteredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + new RpcInvocation(), + false, + new Holder<>()); Assertions.assertEquals(0, filteredInvokers.size()); } @Test void testRoute_ReturnEmpty() { - StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => ")); + StateRouter router = + new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => ")); List> originInvokers = new ArrayList>(); originInvokers.add(new MockInvoker()); originInvokers.add(new MockInvoker()); originInvokers.add(new MockInvoker()); BitList> invokers = new BitList<>(originInvokers); - List> filteredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false, new Holder<>()); + List> filteredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + new RpcInvocation(), + false, + new Holder<>()); Assertions.assertEquals(0, filteredInvokers.size()); } @Test void testRoute_ReturnAll() { - StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => " + " host = " + LOCAL_HOST)); + StateRouter router = new ConditionStateRouterFactory() + .getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => " + " host = " + LOCAL_HOST)); List> originInvokers = new ArrayList>(); originInvokers.add(new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"))); originInvokers.add(new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"))); originInvokers.add(new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService"))); BitList> invokers = new BitList<>(originInvokers); - List> filteredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false, new Holder<>()); + List> filteredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + new RpcInvocation(), + false, + new Holder<>()); Assertions.assertEquals(invokers, filteredInvokers); } @Test void testRoute_HostFilter() { - StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => " + " host = " + LOCAL_HOST)); + StateRouter router = new ConditionStateRouterFactory() + .getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => " + " host = " + LOCAL_HOST)); List> originInvokers = new ArrayList>(); Invoker invoker1 = new MockInvoker(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService")); - Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); - Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker2 = + new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker3 = + new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); originInvokers.add(invoker1); originInvokers.add(invoker2); originInvokers.add(invoker3); BitList> invokers = new BitList<>(originInvokers); - List> filteredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false, new Holder<>()); + List> filteredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + new RpcInvocation(), + false, + new Holder<>()); Assertions.assertEquals(2, filteredInvokers.size()); Assertions.assertEquals(invoker2, filteredInvokers.get(0)); Assertions.assertEquals(invoker3, filteredInvokers.get(1)); @@ -249,17 +347,25 @@ class ConditionStateRouterTest { @Test void testRoute_Empty_HostFilter() { - StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl(" => " + " host = " + LOCAL_HOST)); + StateRouter router = new ConditionStateRouterFactory() + .getRouter(String.class, getRouteUrl(" => " + " host = " + LOCAL_HOST)); List> originInvokers = new ArrayList>(); Invoker invoker1 = new MockInvoker(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService")); - Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); - Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker2 = + new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker3 = + new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); originInvokers.add(invoker1); originInvokers.add(invoker2); originInvokers.add(invoker3); BitList> invokers = new BitList<>(originInvokers); - List> filteredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false, new Holder<>()); + List> filteredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + new RpcInvocation(), + false, + new Holder<>()); Assertions.assertEquals(2, filteredInvokers.size()); Assertions.assertEquals(invoker2, filteredInvokers.get(0)); Assertions.assertEquals(invoker3, filteredInvokers.get(1)); @@ -267,17 +373,25 @@ class ConditionStateRouterTest { @Test void testRoute_False_HostFilter() { - StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("true => " + " host = " + LOCAL_HOST)); + StateRouter router = new ConditionStateRouterFactory() + .getRouter(String.class, getRouteUrl("true => " + " host = " + LOCAL_HOST)); List> originInvokers = new ArrayList>(); Invoker invoker1 = new MockInvoker(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService")); - Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); - Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker2 = + new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker3 = + new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); originInvokers.add(invoker1); originInvokers.add(invoker2); originInvokers.add(invoker3); BitList> invokers = new BitList<>(originInvokers); - List> filteredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false, new Holder<>()); + List> filteredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + new RpcInvocation(), + false, + new Holder<>()); Assertions.assertEquals(2, filteredInvokers.size()); Assertions.assertEquals(invoker2, filteredInvokers.get(0)); Assertions.assertEquals(invoker3, filteredInvokers.get(1)); @@ -285,17 +399,25 @@ class ConditionStateRouterTest { @Test void testRoute_Placeholder() { - StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => " + " host = $host")); + StateRouter router = new ConditionStateRouterFactory() + .getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => " + " host = $host")); List> originInvokers = new ArrayList>(); Invoker invoker1 = new MockInvoker(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService")); - Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); - Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker2 = + new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker3 = + new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); originInvokers.add(invoker1); originInvokers.add(invoker2); originInvokers.add(invoker3); BitList> invokers = new BitList<>(originInvokers); - List> filteredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false, new Holder<>()); + List> filteredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + new RpcInvocation(), + false, + new Holder<>()); Assertions.assertEquals(2, filteredInvokers.size()); Assertions.assertEquals(invoker2, filteredInvokers.get(0)); Assertions.assertEquals(invoker3, filteredInvokers.get(1)); @@ -303,43 +425,68 @@ class ConditionStateRouterTest { @Test void testRoute_NoForce() { - StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 1.2.3.4")); + StateRouter router = new ConditionStateRouterFactory() + .getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 1.2.3.4")); List> originInvokers = new ArrayList>(); Invoker invoker1 = new MockInvoker(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService")); - Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); - Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker2 = + new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker3 = + new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); originInvokers.add(invoker1); originInvokers.add(invoker2); originInvokers.add(invoker3); BitList> invokers = new BitList<>(originInvokers); - List> filteredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false, new Holder<>()); + List> filteredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + new RpcInvocation(), + false, + new Holder<>()); Assertions.assertEquals(invokers, filteredInvokers); } @Test void testRoute_Force() { - StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 1.2.3.4").addParameter(FORCE_KEY, String.valueOf(true))); + StateRouter router = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("host = " + LOCAL_HOST + " => " + " host = 1.2.3.4") + .addParameter(FORCE_KEY, String.valueOf(true))); List> originInvokers = new ArrayList>(); Invoker invoker1 = new MockInvoker(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService")); - Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); - Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker2 = + new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker3 = + new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); originInvokers.add(invoker1); originInvokers.add(invoker2); originInvokers.add(invoker3); BitList> invokers = new BitList<>(originInvokers); - List> filteredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), new RpcInvocation(), false, new Holder<>()); + List> filteredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + new RpcInvocation(), + false, + new Holder<>()); Assertions.assertEquals(0, filteredInvokers.size()); } @Test void testRoute_Arguments() { - StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("arguments[0] = a " + " => " + " host = 1.2.3.4").addParameter(FORCE_KEY, String.valueOf(true))); + StateRouter router = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("arguments[0] = a " + " => " + " host = 1.2.3.4") + .addParameter(FORCE_KEY, String.valueOf(true))); List> originInvokers = new ArrayList<>(); Invoker invoker1 = new MockInvoker<>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService")); - Invoker invoker2 = new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); - Invoker invoker3 = new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker2 = + new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker3 = + new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); originInvokers.add(invoker1); originInvokers.add(invoker2); originInvokers.add(invoker3); @@ -347,104 +494,232 @@ class ConditionStateRouterTest { RpcInvocation invocation = new RpcInvocation(); String p = "a"; - invocation.setArguments(new Object[]{null}); - List> fileredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation, false, new Holder<>()); + invocation.setArguments(new Object[] {null}); + List> fileredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + invocation, + false, + new Holder<>()); Assertions.assertEquals(3, fileredInvokers.size()); - invocation.setArguments(new Object[]{p}); - fileredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation, false, new Holder<>()); + invocation.setArguments(new Object[] {p}); + fileredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + invocation, + false, + new Holder<>()); Assertions.assertEquals(0, fileredInvokers.size()); - router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("arguments = b " + " => " + " host = 1.2.3.4").addParameter(FORCE_KEY, String.valueOf(true))); - fileredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation, false, new Holder<>()); + router = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("arguments = b " + " => " + " host = 1.2.3.4") + .addParameter(FORCE_KEY, String.valueOf(true))); + fileredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + invocation, + false, + new Holder<>()); Assertions.assertEquals(3, fileredInvokers.size()); - router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("arguments[10].inner = a " + " => " + " host = 1.2.3.4").addParameter(FORCE_KEY, String.valueOf(true))); - fileredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation, false, new Holder<>()); + router = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("arguments[10].inner = a " + " => " + " host = 1.2.3.4") + .addParameter(FORCE_KEY, String.valueOf(true))); + fileredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + invocation, + false, + new Holder<>()); Assertions.assertEquals(3, fileredInvokers.size()); int integer = 1; - invocation.setArguments(new Object[]{integer}); - router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("arguments[0].inner = 1 " + " => " + " host = 1.2.3.4").addParameter(FORCE_KEY, String.valueOf(true))); - fileredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation, false, new Holder<>()); + invocation.setArguments(new Object[] {integer}); + router = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("arguments[0].inner = 1 " + " => " + " host = 1.2.3.4") + .addParameter(FORCE_KEY, String.valueOf(true))); + fileredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + invocation, + false, + new Holder<>()); Assertions.assertEquals(0, fileredInvokers.size()); } @Test void testRoute_Attachments() { - StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("attachments[foo] = a " + " => " + " host = 1.2.3.4").addParameter(FORCE_KEY, String.valueOf(true))); + StateRouter router = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("attachments[foo] = a " + " => " + " host = 1.2.3.4") + .addParameter(FORCE_KEY, String.valueOf(true))); List> originInvokers = new ArrayList<>(); - Invoker invoker1 = new MockInvoker<>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService?region=hangzhou")); - Invoker invoker2 = new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); - Invoker invoker3 = new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker1 = + new MockInvoker<>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService?region=hangzhou")); + Invoker invoker2 = + new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker3 = + new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); originInvokers.add(invoker1); originInvokers.add(invoker2); originInvokers.add(invoker3); BitList> invokers = new BitList<>(originInvokers); RpcInvocation invocation = new RpcInvocation(); - List> fileredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation, false, new Holder<>()); + List> fileredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + invocation, + false, + new Holder<>()); Assertions.assertEquals(3, fileredInvokers.size()); invocation.setAttachment("foo", "a"); - fileredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation, false, new Holder<>()); + fileredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + invocation, + false, + new Holder<>()); Assertions.assertEquals(0, fileredInvokers.size()); - router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("attachments = a " + " => " + " host = 1.2.3.4").addParameter(FORCE_KEY, String.valueOf(true))); - fileredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation, false, new Holder<>()); + router = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("attachments = a " + " => " + " host = 1.2.3.4") + .addParameter(FORCE_KEY, String.valueOf(true))); + fileredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + invocation, + false, + new Holder<>()); Assertions.assertEquals(3, fileredInvokers.size()); - router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("attachments[foo] = a " + " => " + " region = hangzhou").addParameter(FORCE_KEY, String.valueOf(true))); - fileredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation, false, new Holder<>()); + router = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("attachments[foo] = a " + " => " + " region = hangzhou") + .addParameter(FORCE_KEY, String.valueOf(true))); + fileredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + invocation, + false, + new Holder<>()); Assertions.assertEquals(1, fileredInvokers.size()); } @Test void testRoute_Range_Pattern() { - StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("attachments[user_id] = 1~100 " + " => " + " region=hangzhou").addParameter(FORCE_KEY, String.valueOf(true))); + StateRouter router = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("attachments[user_id] = 1~100 " + " => " + " region=hangzhou") + .addParameter(FORCE_KEY, String.valueOf(true))); List> originInvokers = new ArrayList<>(); - Invoker invoker1 = new MockInvoker<>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService?region=hangzhou")); - Invoker invoker2 = new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); - Invoker invoker3 = new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker1 = + new MockInvoker<>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService?region=hangzhou")); + Invoker invoker2 = + new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker3 = + new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); originInvokers.add(invoker1); originInvokers.add(invoker2); originInvokers.add(invoker3); BitList> invokers = new BitList<>(originInvokers); RpcInvocation invocation = new RpcInvocation(); - List> fileredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation, false, new Holder<>()); + List> fileredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + invocation, + false, + new Holder<>()); Assertions.assertEquals(3, fileredInvokers.size()); invocation.setAttachment("user_id", "80"); - fileredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation, false, new Holder<>()); + fileredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + invocation, + false, + new Holder<>()); Assertions.assertEquals(1, fileredInvokers.size()); invocation.setAttachment("user_id", "101"); - fileredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation, false, new Holder<>()); + fileredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + invocation, + false, + new Holder<>()); Assertions.assertEquals(3, fileredInvokers.size()); - router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("attachments[user_id] = ~100 " + " => " + " region = hangzhou").addParameter(FORCE_KEY, String.valueOf(true))); + router = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("attachments[user_id] = ~100 " + " => " + " region = hangzhou") + .addParameter(FORCE_KEY, String.valueOf(true))); invocation.setAttachment("user_id", "1"); - fileredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation, false, new Holder<>()); + fileredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + invocation, + false, + new Holder<>()); Assertions.assertEquals(1, fileredInvokers.size()); - router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("attachments[user_id] = ~100 " + " => " + " region = hangzhou").addParameter(FORCE_KEY, String.valueOf(true))); + router = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("attachments[user_id] = ~100 " + " => " + " region = hangzhou") + .addParameter(FORCE_KEY, String.valueOf(true))); invocation.setAttachment("user_id", "101"); - fileredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation, false, new Holder<>()); + fileredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + invocation, + false, + new Holder<>()); Assertions.assertEquals(3, fileredInvokers.size()); - router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("attachments[user_id] = ~100 " + " => " + " region = hangzhou").addParameter(FORCE_KEY, String.valueOf(true))); - fileredInvokers = router.route(invokers.clone(), URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), invocation, false, new Holder<>()); + router = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("attachments[user_id] = ~100 " + " => " + " region = hangzhou") + .addParameter(FORCE_KEY, String.valueOf(true))); + fileredInvokers = router.route( + invokers.clone(), + URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService"), + invocation, + false, + new Holder<>()); Assertions.assertEquals(3, fileredInvokers.size()); } @Test void testRoute_Key_Not_Exist() { - StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("when_key=a " + " => " + " not_exist_then_key = any_value").addParameter(FORCE_KEY, String.valueOf(true))); + StateRouter router = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("when_key=a " + " => " + " not_exist_then_key = any_value") + .addParameter(FORCE_KEY, String.valueOf(true))); List> originInvokers = new ArrayList<>(); - Invoker invoker1 = new MockInvoker<>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService?then_key=a")); - Invoker invoker2 = new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); - Invoker invoker3 = new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker1 = + new MockInvoker<>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService?then_key=a")); + Invoker invoker2 = + new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker3 = + new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); originInvokers.add(invoker1); originInvokers.add(invoker2); originInvokers.add(invoker3); @@ -455,7 +730,11 @@ class ConditionStateRouterTest { List> fileredInvokers = router.route(invokers.clone(), consumer, null, false, new Holder<>()); Assertions.assertEquals(0, fileredInvokers.size()); - router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("not_exist_when_key=a " + " => " + " then_key = a").addParameter(FORCE_KEY, String.valueOf(true))); + router = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("not_exist_when_key=a " + " => " + " then_key = a") + .addParameter(FORCE_KEY, String.valueOf(true))); fileredInvokers = router.route(invokers, consumer, null, false, new Holder<>()); Assertions.assertEquals(3, fileredInvokers.size()); } @@ -464,29 +743,38 @@ class ConditionStateRouterTest { void testRoute_Multiple_Conditions() { List> originInvokers = new ArrayList<>(); Invoker invoker1 = new MockInvoker<>(URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService")); - Invoker invoker2 = new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); - Invoker invoker3 = new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker2 = + new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); + Invoker invoker3 = + new MockInvoker<>(URL.valueOf("dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService")); originInvokers.add(invoker1); originInvokers.add(invoker2); originInvokers.add(invoker3); BitList> invokers = new BitList<>(originInvokers); - RpcInvocation invocation = new RpcInvocation(); String p = "a"; - invocation.setArguments(new Object[]{p}); + invocation.setArguments(new Object[] {p}); // all conditions match URL consumer1 = URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService?application=consumer_app"); - StateRouter router = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("application=consumer_app&arguments[0]=a" + " => " + " host = " + LOCAL_HOST).addParameter(FORCE_KEY, String.valueOf(true))); - List> fileredInvokers = router.route(invokers.clone(), consumer1, invocation, false, new Holder<>()); + StateRouter router = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("application=consumer_app&arguments[0]=a" + " => " + " host = " + LOCAL_HOST) + .addParameter(FORCE_KEY, String.valueOf(true))); + List> fileredInvokers = + router.route(invokers.clone(), consumer1, invocation, false, new Holder<>()); Assertions.assertEquals(2, fileredInvokers.size()); // one of the conditions does not match URL consume2 = URL.valueOf("consumer://" + LOCAL_HOST + "/com.foo.BarService?application=another_consumer_app"); - StateRouter router2 = new ConditionStateRouterFactory().getRouter(String.class, getRouteUrl("application=consumer_app&arguments[0]=a" + " => " + " host = " + LOCAL_HOST).addParameter(FORCE_KEY, String.valueOf(true))); + StateRouter router2 = new ConditionStateRouterFactory() + .getRouter( + String.class, + getRouteUrl("application=consumer_app&arguments[0]=a" + " => " + " host = " + LOCAL_HOST) + .addParameter(FORCE_KEY, String.valueOf(true))); fileredInvokers = router2.route(invokers.clone(), consume2, invocation, false, new Holder<>()); Assertions.assertEquals(3, fileredInvokers.size()); - } } diff --git a/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppConditionStateRouterTest.java b/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppConditionStateRouterTest.java index 975a78bceb..7348868954 100644 --- a/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppConditionStateRouterTest.java +++ b/dubbo-plugin/dubbo-plugin-router-condition/src/test/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppConditionStateRouterTest.java @@ -25,14 +25,14 @@ import org.apache.dubbo.rpc.cluster.governance.GovernanceRuleRepository; import org.apache.dubbo.rpc.cluster.router.MockInvoker; import org.apache.dubbo.rpc.cluster.router.state.BitList; +import java.util.ArrayList; +import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.ArrayList; -import java.util.List; - import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY; public class ProviderAppConditionStateRouterTest { @@ -41,17 +41,16 @@ public class ProviderAppConditionStateRouterTest { private static GovernanceRuleRepository ruleRepository; private URL url = URL.valueOf("consumer://1.1.1.1/com.foo.BarService"); - private String rawRule = "---\n" + - "configVersion: v3.0\n" + - "scope: application\n" + - "force: true\n" + - "runtime: false\n" + - "enabled: true\n" + - "priority: 1\n" + - "key: demo-provider\n" + - "conditions:\n" + - "- method=sayHello => region=hangzhou\n" + - "..."; + private String rawRule = "---\n" + "configVersion: v3.0\n" + + "scope: application\n" + + "force: true\n" + + "runtime: false\n" + + "enabled: true\n" + + "priority: 1\n" + + "key: demo-provider\n" + + "conditions:\n" + + "- method=sayHello => region=hangzhou\n" + + "..."; @BeforeAll public static void setUpBeforeClass() throws Exception { @@ -63,8 +62,9 @@ public class ProviderAppConditionStateRouterTest { ProviderAppStateRouter router = new ProviderAppStateRouter<>(url); router = Mockito.spy(router); Mockito.when(router.getRuleRepository()).thenReturn(ruleRepository); - Mockito.when(ruleRepository.getRule("demo-provider" + RULE_SUFFIX, DynamicConfiguration.DEFAULT_GROUP)).thenReturn(rawRule); -// Mockito.when(ruleRepository.addListener()).thenReturn(); + Mockito.when(ruleRepository.getRule("demo-provider" + RULE_SUFFIX, DynamicConfiguration.DEFAULT_GROUP)) + .thenReturn(rawRule); + // Mockito.when(ruleRepository.addListener()).thenReturn(); BitList> invokers = getInvokers(); router.notify(invokers); @@ -81,17 +81,16 @@ public class ProviderAppConditionStateRouterTest { private BitList> getInvokers() { List> originInvokers = new ArrayList>(); - Invoker invoker1 = new MockInvoker(URL.valueOf( - "dubbo://10.20.3.3:20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider")); + Invoker invoker1 = new MockInvoker( + URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider")); Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST - + ":20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider®ion=hangzhou")); - Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST - + ":20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider")); + + ":20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider®ion=hangzhou")); + Invoker invoker3 = new MockInvoker(URL.valueOf( + "dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider")); originInvokers.add(invoker1); originInvokers.add(invoker2); originInvokers.add(invoker3); BitList> invokers = new BitList<>(originInvokers); return invokers; } - } diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/pom.xml b/dubbo-plugin/dubbo-plugin-router-mesh/pom.xml index 5de51faabe..5c0442961f 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/pom.xml +++ b/dubbo-plugin/dubbo-plugin-router-mesh/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + - dubbo-plugin-router-mesh - jar + dubbo-plugin-router-mesh + jar - - - org.apache.dubbo - dubbo-cluster - ${project.version} - - + + + org.apache.dubbo + dubbo-cluster + ${project.version} + + diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/MeshScopeModelInitializer.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/MeshScopeModelInitializer.java index 84c24314ed..6753f9b8e4 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/MeshScopeModelInitializer.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/MeshScopeModelInitializer.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.router.mesh; - import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleManager; import org.apache.dubbo.rpc.model.ApplicationModel; @@ -26,12 +25,10 @@ import org.apache.dubbo.rpc.model.ScopeModelInitializer; public class MeshScopeModelInitializer implements ScopeModelInitializer { @Override - public void initializeFrameworkModel(FrameworkModel frameworkModel) { - } + public void initializeFrameworkModel(FrameworkModel frameworkModel) {} @Override - public void initializeApplicationModel(ApplicationModel applicationModel) { - } + public void initializeApplicationModel(ApplicationModel applicationModel) {} public void initializeModuleModel(ModuleModel moduleModel) { ScopeBeanFactory beanFactory = moduleModel.getBeanFactory(); diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshAppRuleListener.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshAppRuleListener.java index 955878735b..ef70b7806f 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshAppRuleListener.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshAppRuleListener.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.route; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; @@ -25,11 +24,6 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.rpc.cluster.router.mesh.util.MeshRuleDispatcher; import org.apache.dubbo.rpc.cluster.router.mesh.util.MeshRuleListener; -import org.yaml.snakeyaml.DumperOptions; -import org.yaml.snakeyaml.LoaderOptions; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.SafeConstructor; -import org.yaml.snakeyaml.representer.Representer; import java.text.MessageFormat; import java.util.HashMap; @@ -37,12 +31,17 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import org.yaml.snakeyaml.representer.Representer; + import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_RECEIVE_RULE; import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.METADATA_KEY; import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.NAME_KEY; import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.STANDARD_ROUTER_KEY; - public class MeshAppRuleListener implements ConfigurationListener { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MeshAppRuleListener.class); @@ -61,8 +60,7 @@ public class MeshAppRuleListener implements ConfigurationListener { @SuppressWarnings("unchecked") public void receiveConfigInfo(String configInfo) { if (logger.isDebugEnabled()) { - logger.debug(MessageFormat.format("[MeshAppRule] Received rule for app [{0}]: {1}.", - appName, configInfo)); + logger.debug(MessageFormat.format("[MeshAppRule] Received rule for app [{0}]: {1}.", appName, configInfo)); } try { Map>> groupMap = new HashMap<>(); @@ -78,19 +76,34 @@ public class MeshAppRuleListener implements ConfigurationListener { String ruleType = computeRuleType(resultMap); if (ruleType != null) { - groupMap.computeIfAbsent(ruleType, (k)-> new LinkedList<>()).add(resultMap); + groupMap.computeIfAbsent(ruleType, (k) -> new LinkedList<>()) + .add(resultMap); } else { - logger.error(CLUSTER_FAILED_RECEIVE_RULE,"receive mesh app route rule is invalid","","Unable to get rule type from raw rule. " + - "Probably the metadata.name is absent. App Name: " + appName + " RawRule: " + configInfo); + logger.error( + CLUSTER_FAILED_RECEIVE_RULE, + "receive mesh app route rule is invalid", + "", + "Unable to get rule type from raw rule. " + + "Probably the metadata.name is absent. App Name: " + appName + " RawRule: " + + configInfo); } } else { - logger.error(CLUSTER_FAILED_RECEIVE_RULE,"receive mesh app route rule is invalid","","Rule format is unacceptable. App Name: " + appName + " RawRule: " + configInfo); + logger.error( + CLUSTER_FAILED_RECEIVE_RULE, + "receive mesh app route rule is invalid", + "", + "Rule format is unacceptable. App Name: " + appName + " RawRule: " + configInfo); } } ruleMapHolder = groupMap; } catch (Exception e) { - logger.error(CLUSTER_FAILED_RECEIVE_RULE,"failed to receive mesh app route rule","","[MeshAppRule] parse failed: " + configInfo,e); + logger.error( + CLUSTER_FAILED_RECEIVE_RULE, + "failed to receive mesh app route rule", + "", + "[MeshAppRule] parse failed: " + configInfo, + e); } if (ruleMapHolder != null) { meshRuleDispatcher.post(ruleMapHolder); @@ -122,7 +135,6 @@ public class MeshAppRuleListener implements ConfigurationListener { meshRuleDispatcher.register(subscriber); } - public void unregister(MeshRuleListener subscriber) { meshRuleDispatcher.unregister(subscriber); } diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshEnvListener.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshEnvListener.java index 6d9853436e..4c70ec2675 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshEnvListener.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshEnvListener.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.route; /** diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCache.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCache.java index 097162e927..098b9bd4cf 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCache.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCache.java @@ -41,7 +41,11 @@ public class MeshRuleCache { private final Map>>> totalSubsetMap; private final BitList> unmatchedInvokers; - private MeshRuleCache(List appList, Map appToVDGroup, Map>>> totalSubsetMap, BitList> unmatchedInvokers) { + private MeshRuleCache( + List appList, + Map appToVDGroup, + Map>>> totalSubsetMap, + BitList> unmatchedInvokers) { this.appList = appList; this.appToVDGroup = appToVDGroup; this.totalSubsetMap = totalSubsetMap; @@ -83,7 +87,10 @@ public class MeshRuleCache { return !totalSubsetMap.isEmpty(); } - public static MeshRuleCache build(String protocolServiceKey, BitList> invokers, Map vsDestinationGroupMap) { + public static MeshRuleCache build( + String protocolServiceKey, + BitList> invokers, + Map vsDestinationGroupMap) { if (CollectionUtils.isNotEmptyMap(vsDestinationGroupMap)) { BitList> unmatchedInvokers = new BitList<>(invokers.getOriginList(), true); Map>>> totalSubsetMap = new HashMap<>(); @@ -99,7 +106,8 @@ public class MeshRuleCache { unmatchedInvokers.add(invoker); continue; } - Map>> subsetMap = totalSubsetMap.computeIfAbsent(remoteApplication, (k) -> new HashMap<>()); + Map>> subsetMap = + totalSubsetMap.computeIfAbsent(remoteApplication, (k) -> new HashMap<>()); boolean matched = false; for (DestinationRule destinationRule : vsDestinationGroup.getDestinationRuleList()) { @@ -107,7 +115,8 @@ public class MeshRuleCache { List subsetList = destinationRuleSpec.getSubsets(); for (Subset subset : subsetList) { String subsetName = subset.getName(); - List> subsetInvokers = subsetMap.computeIfAbsent(subsetName, (k) -> new BitList<>(invokers.getOriginList(), true)); + List> subsetInvokers = subsetMap.computeIfAbsent( + subsetName, (k) -> new BitList<>(invokers.getOriginList(), true)); Map labels = subset.getLabels(); if (isLabelMatch(invoker.getUrl(), protocolServiceKey, labels)) { @@ -121,17 +130,20 @@ public class MeshRuleCache { } } - return new MeshRuleCache<>(new LinkedList<>(vsDestinationGroupMap.keySet()), - Collections.unmodifiableMap(vsDestinationGroupMap), - Collections.unmodifiableMap(totalSubsetMap), - unmatchedInvokers); + return new MeshRuleCache<>( + new LinkedList<>(vsDestinationGroupMap.keySet()), + Collections.unmodifiableMap(vsDestinationGroupMap), + Collections.unmodifiableMap(totalSubsetMap), + unmatchedInvokers); } else { - return new MeshRuleCache(Collections.emptyList(), Collections.emptyMap(), Collections.emptyMap(), invokers); + return new MeshRuleCache( + Collections.emptyList(), Collections.emptyMap(), Collections.emptyMap(), invokers); } } public static MeshRuleCache emptyCache() { - return new MeshRuleCache<>(Collections.emptyList(), Collections.emptyMap(), Collections.emptyMap(), BitList.emptyList()); + return new MeshRuleCache<>( + Collections.emptyList(), Collections.emptyMap(), Collections.emptyMap(), BitList.emptyList()); } protected static boolean isLabelMatch(URL url, String protocolServiceKey, Map inputMap) { @@ -161,7 +173,10 @@ public class MeshRuleCache { return false; } MeshRuleCache ruleCache = (MeshRuleCache) o; - return Objects.equals(appList, ruleCache.appList) && Objects.equals(appToVDGroup, ruleCache.appToVDGroup) && Objects.equals(totalSubsetMap, ruleCache.totalSubsetMap) && Objects.equals(unmatchedInvokers, ruleCache.unmatchedInvokers); + return Objects.equals(appList, ruleCache.appList) + && Objects.equals(appToVDGroup, ruleCache.appToVDGroup) + && Objects.equals(totalSubsetMap, ruleCache.totalSubsetMap) + && Objects.equals(unmatchedInvokers, ruleCache.unmatchedInvokers); } @Override diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleManager.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleManager.java index ac494757fb..99a6656cb8 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleManager.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleManager.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.route; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; @@ -44,11 +43,12 @@ public class MeshRuleManager { public MeshRuleManager(ModuleModel moduleModel) { this.ruleRepository = moduleModel.getDefaultExtension(GovernanceRuleRepository.class); - Set envListenerFactories = moduleModel.getExtensionLoader(MeshEnvListenerFactory.class).getSupportedExtensionInstances(); + Set envListenerFactories = + moduleModel.getExtensionLoader(MeshEnvListenerFactory.class).getSupportedExtensionInstances(); this.envListeners = envListenerFactories.stream() - .map(MeshEnvListenerFactory::getListener) - .filter(Objects::nonNull) - .collect(Collectors.toSet()); + .map(MeshEnvListenerFactory::getListener) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); } private synchronized MeshAppRuleListener subscribeAppRule(String app) { @@ -64,7 +64,12 @@ public class MeshRuleManager { meshAppRuleListener.receiveConfigInfo(rawConfig); } } catch (Throwable throwable) { - logger.error(CLUSTER_FAILED_RECEIVE_RULE,"failed to get mesh app route rule","","get MeshRuleManager app rule failed.",throwable); + logger.error( + CLUSTER_FAILED_RECEIVE_RULE, + "failed to get mesh app route rule", + "", + "get MeshRuleManager app rule failed.", + throwable); } ruleRepository.addListener(appRuleDataId, DynamicConfiguration.DEFAULT_GROUP, meshAppRuleListener); @@ -93,7 +98,6 @@ public class MeshRuleManager { envListener.onUnSubscribe(app); } } - } public synchronized void register(String app, MeshRuleListener subscriber) { diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleRouter.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleRouter.java index 0d3d8b56dd..06d43e9432 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleRouter.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleRouter.java @@ -74,13 +74,20 @@ public abstract class MeshRuleRouter extends AbstractStateRouter implement super(url); sourcesLabels = Collections.unmodifiableMap(new HashMap<>(url.getParameters())); this.meshRuleManager = url.getOrDefaultModuleModel().getBeanFactory().getBean(MeshRuleManager.class); - this.tracingContextProviders = url.getOrDefaultModuleModel().getExtensionLoader(TracingContextProvider.class).getSupportedExtensionInstances(); + this.tracingContextProviders = url.getOrDefaultModuleModel() + .getExtensionLoader(TracingContextProvider.class) + .getSupportedExtensionInstances(); } @Override - protected BitList> doRoute(BitList> invokers, URL url, Invocation invocation, - boolean needToPrintMessage, Holder> nodeHolder, - Holder messageHolder) throws RpcException { + protected BitList> doRoute( + BitList> invokers, + URL url, + Invocation invocation, + boolean needToPrintMessage, + Holder> nodeHolder, + Holder messageHolder) + throws RpcException { MeshRuleCache ruleCache = this.meshRuleCache; if (!ruleCache.containsRule()) { if (needToPrintMessage) { @@ -96,7 +103,8 @@ public abstract class MeshRuleRouter extends AbstractStateRouter implement // loop each application for (String appName : ruleCache.getAppList()) { // find destination by invocation - List routeDestination = getDubboRouteDestination(ruleCache.getVsDestinationGroup(appName), invocation); + List routeDestination = + getDubboRouteDestination(ruleCache.getVsDestinationGroup(appName), invocation); if (routeDestination != null) { // aggregate target invokers String subset = randomSelectDestination(ruleCache, appName, routeDestination, invokers); @@ -104,7 +112,12 @@ public abstract class MeshRuleRouter extends AbstractStateRouter implement BitList> destination = meshRuleCache.getSubsetInvokers(appName, subset); result = result.or(destination); if (stringBuilder != null) { - stringBuilder.append("Match App: ").append(appName).append(" Subset: ").append(subset).append(' '); + stringBuilder + .append("Match App: ") + .append(appName) + .append(" Subset: ") + .append(subset) + .append(' '); } } } @@ -129,7 +142,8 @@ public abstract class MeshRuleRouter extends AbstractStateRouter implement /** * Select RouteDestination by Invocation */ - protected List getDubboRouteDestination(VsDestinationGroup vsDestinationGroup, Invocation invocation) { + protected List getDubboRouteDestination( + VsDestinationGroup vsDestinationGroup, Invocation invocation) { if (vsDestinationGroup != null) { List virtualServiceRuleList = vsDestinationGroup.getVirtualServiceRuleList(); if (CollectionUtils.isNotEmpty(virtualServiceRuleList)) { @@ -182,8 +196,8 @@ public abstract class MeshRuleRouter extends AbstractStateRouter implement return dubboRouteDetail.getRoute(); } - if (matchRequestList.stream().allMatch( - request -> request.isMatch(invocation, sourcesLabels, tracingContextProviders))) { + if (matchRequestList.stream() + .allMatch(request -> request.isMatch(invocation, sourcesLabels, tracingContextProviders))) { return dubboRouteDetail.getRoute(); } } @@ -195,7 +209,12 @@ public abstract class MeshRuleRouter extends AbstractStateRouter implement /** * Find out target invokers from RouteDestination */ - protected String randomSelectDestination(MeshRuleCache meshRuleCache, String appName, List routeDestination, BitList> availableInvokers) throws RpcException { + protected String randomSelectDestination( + MeshRuleCache meshRuleCache, + String appName, + List routeDestination, + BitList> availableInvokers) + throws RpcException { // randomly select one DubboRouteDestination from list by weight int totalWeight = 0; for (DubboRouteDestination dubboRouteDestination : routeDestination) { @@ -206,7 +225,8 @@ public abstract class MeshRuleRouter extends AbstractStateRouter implement target -= Math.max(destination.getWeight(), 1); if (target <= 0) { // match weight - String result = computeDestination(meshRuleCache, appName, destination.getDestination(), availableInvokers); + String result = + computeDestination(meshRuleCache, appName, destination.getDestination(), availableInvokers); if (result != null) { return result; } @@ -226,13 +246,19 @@ public abstract class MeshRuleRouter extends AbstractStateRouter implement /** * Compute Destination Subset */ - protected String computeDestination(MeshRuleCache meshRuleCache, String appName, DubboDestination dubboDestination, BitList> availableInvokers) throws RpcException { + protected String computeDestination( + MeshRuleCache meshRuleCache, + String appName, + DubboDestination dubboDestination, + BitList> availableInvokers) + throws RpcException { String subset = dubboDestination.getSubset(); do { BitList> result = meshRuleCache.getSubsetInvokers(appName, subset); - if (CollectionUtils.isNotEmpty(result) && !availableInvokers.clone().and(result).isEmpty()) { + if (CollectionUtils.isNotEmpty(result) + && !availableInvokers.clone().and(result).isEmpty()) { return subset; } @@ -309,7 +335,12 @@ public abstract class MeshRuleRouter extends AbstractStateRouter implement appToVDGroup.put(appName, vsDestinationGroup); } } catch (Throwable t) { - logger.error(CLUSTER_FAILED_RECEIVE_RULE,"failed to parse mesh route rule","","Error occurred when parsing rule component.",t); + logger.error( + CLUSTER_FAILED_RECEIVE_RULE, + "failed to parse mesh route rule", + "", + "Error occurred when parsing rule component.", + t); } computeSubset(appToVDGroup); @@ -323,7 +354,8 @@ public abstract class MeshRuleRouter extends AbstractStateRouter implement } protected void computeSubset(Map vsDestinationGroupMap) { - this.meshRuleCache = MeshRuleCache.build(getUrl().getProtocolServiceKey(), this.invokerList, vsDestinationGroupMap); + this.meshRuleCache = + MeshRuleCache.build(getUrl().getProtocolServiceKey(), this.invokerList, vsDestinationGroupMap); } @Override diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouterFactory.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouterFactory.java index 343f12c386..6c407bbb09 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouterFactory.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouterFactory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.route; import org.apache.dubbo.common.URL; @@ -22,7 +21,6 @@ import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.cluster.router.state.StateRouter; import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory; - @Activate(order = -50) public class StandardMeshRuleRouterFactory implements StateRouterFactory { @Override diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/BaseRule.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/BaseRule.java index 0c0b64efad..232467384b 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/BaseRule.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/BaseRule.java @@ -14,12 +14,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule; import java.util.Map; - public class BaseRule { private String apiVersion; private String kind; @@ -51,10 +49,9 @@ public class BaseRule { @Override public String toString() { - return "BaseRule{" + - "apiVersion='" + apiVersion + '\'' + - ", kind='" + kind + '\'' + - ", metadata=" + metadata + - '}'; + return "BaseRule{" + "apiVersion='" + + apiVersion + '\'' + ", kind='" + + kind + '\'' + ", metadata=" + + metadata + '}'; } } diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/VsDestinationGroup.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/VsDestinationGroup.java index 6b150d4d09..3bb18c5437 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/VsDestinationGroup.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/VsDestinationGroup.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule; import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.DestinationRule; @@ -23,7 +22,6 @@ import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.VirtualServi import java.util.LinkedList; import java.util.List; - public class VsDestinationGroup { private String appName; private List virtualServiceRuleList = new LinkedList<>(); diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/ConnectionPoolSettings.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/ConnectionPoolSettings.java index 32b7af9cd8..8fadc9bcde 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/ConnectionPoolSettings.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/ConnectionPoolSettings.java @@ -14,9 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.destination; - -public class ConnectionPoolSettings { -} +public class ConnectionPoolSettings {} diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/DestinationRule.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/DestinationRule.java index 42bc049455..b78caae766 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/DestinationRule.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/DestinationRule.java @@ -14,12 +14,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.destination; import org.apache.dubbo.rpc.cluster.router.mesh.rule.BaseRule; - public class DestinationRule extends BaseRule { private DestinationRuleSpec spec; @@ -33,9 +31,6 @@ public class DestinationRule extends BaseRule { @Override public String toString() { - return "DestinationRule{" + - "base=" + super.toString() + - ", spec=" + spec + - '}'; + return "DestinationRule{" + "base=" + super.toString() + ", spec=" + spec + '}'; } } diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/DestinationRuleSpec.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/DestinationRuleSpec.java index 57d8b063e6..ee9efd9121 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/DestinationRuleSpec.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/DestinationRuleSpec.java @@ -14,12 +14,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.destination; import java.util.List; - public class DestinationRuleSpec { private String host; private List subsets; @@ -51,10 +49,9 @@ public class DestinationRuleSpec { @Override public String toString() { - return "DestinationRuleSpec{" + - "host='" + host + '\'' + - ", subsets=" + subsets + - ", trafficPolicy=" + trafficPolicy + - '}'; + return "DestinationRuleSpec{" + "host='" + + host + '\'' + ", subsets=" + + subsets + ", trafficPolicy=" + + trafficPolicy + '}'; } } diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/Subset.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/Subset.java index 9438ec4dd8..dd0a995450 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/Subset.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/Subset.java @@ -14,12 +14,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.destination; import java.util.Map; - public class Subset { private String name; private Map labels; @@ -42,9 +40,6 @@ public class Subset { @Override public String toString() { - return "Subset{" + - "name='" + name + '\'' + - ", labels=" + labels + - '}'; + return "Subset{" + "name='" + name + '\'' + ", labels=" + labels + '}'; } } diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TCPSettings.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TCPSettings.java index 09dc93a8f0..9e1e12a737 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TCPSettings.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TCPSettings.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.destination; - public class TCPSettings { private int maxConnections; private int connectTimeout; diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TcpKeepalive.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TcpKeepalive.java index 3bc43c7342..5887f1c726 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TcpKeepalive.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TcpKeepalive.java @@ -14,13 +14,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.destination; - public class TcpKeepalive { private int probes; private int time; private int interval; - } diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TrafficPolicy.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TrafficPolicy.java index 7f771f0d76..402ff63a51 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TrafficPolicy.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TrafficPolicy.java @@ -14,12 +14,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.destination; import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.loadbalance.LoadBalancerSettings; - public class TrafficPolicy { private LoadBalancerSettings loadBalancer; @@ -33,8 +31,6 @@ public class TrafficPolicy { @Override public String toString() { - return "TrafficPolicy{" + - "loadBalancer=" + loadBalancer + - '}'; + return "TrafficPolicy{" + "loadBalancer=" + loadBalancer + '}'; } } diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/ConsistentHashLB.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/ConsistentHashLB.java index 213dfee9e1..95ad44e91e 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/ConsistentHashLB.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/ConsistentHashLB.java @@ -14,9 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.loadbalance; - -public class ConsistentHashLB { -} +public class ConsistentHashLB {} diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/LoadBalancerSettings.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/LoadBalancerSettings.java index 1f8b60ed4e..1be425328a 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/LoadBalancerSettings.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/LoadBalancerSettings.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.loadbalance; - public class LoadBalancerSettings { private SimpleLB simple; private ConsistentHashLB consistentHash; @@ -40,9 +38,6 @@ public class LoadBalancerSettings { @Override public String toString() { - return "LoadBalancerSettings{" + - "simple=" + simple + - ", consistentHash=" + consistentHash + - '}'; + return "LoadBalancerSettings{" + "simple=" + simple + ", consistentHash=" + consistentHash + '}'; } } diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/SimpleLB.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/SimpleLB.java index 003f1f6a90..8039408411 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/SimpleLB.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/SimpleLB.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.loadbalance; - public enum SimpleLB { ROUND_ROBIN, LEAST_CONN, diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboMatchRequest.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboMatchRequest.java index 8255a228ed..11ab9beb77 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboMatchRequest.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboMatchRequest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice; import org.apache.dubbo.rpc.Invocation; @@ -26,7 +25,6 @@ import org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider; import java.util.Map; import java.util.Set; - public class DubboMatchRequest { private String name; private DubboMethodMatch method; @@ -76,16 +74,16 @@ public class DubboMatchRequest { @Override public String toString() { - return "DubboMatchRequest{" + - "name='" + name + '\'' + - ", method=" + method + - ", sourceLabels=" + sourceLabels + - ", attachments=" + attachments + - ", headers=" + headers + - '}'; + return "DubboMatchRequest{" + "name='" + + name + '\'' + ", method=" + + method + ", sourceLabels=" + + sourceLabels + ", attachments=" + + attachments + ", headers=" + + headers + '}'; } - public boolean isMatch(Invocation invocation, Map sourceLabels, Set contextProviders) { + public boolean isMatch( + Invocation invocation, Map sourceLabels, Set contextProviders) { // Match method if (getMethod() != null) { if (!getMethod().isMatch(invocation)) { diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboRoute.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboRoute.java index d6bf12443c..530abcb006 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboRoute.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboRoute.java @@ -14,14 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice; import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.StringMatch; import java.util.List; - public class DubboRoute { private String name; private List services; @@ -53,10 +51,6 @@ public class DubboRoute { @Override public String toString() { - return "DubboRoute{" + - "name='" + name + '\'' + - ", services=" + services + - ", routedetail=" + routedetail + - '}'; + return "DubboRoute{" + "name='" + name + '\'' + ", services=" + services + ", routedetail=" + routedetail + '}'; } } diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboRouteDetail.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboRouteDetail.java index ce42591412..cad8c0f700 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboRouteDetail.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboRouteDetail.java @@ -14,14 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice; import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.destination.DubboRouteDestination; import java.util.List; - public class DubboRouteDetail { private String name; private List match; @@ -53,10 +51,6 @@ public class DubboRouteDetail { @Override public String toString() { - return "DubboRouteDetail{" + - "name='" + name + '\'' + - ", match=" + match + - ", route=" + route + - '}'; + return "DubboRouteDetail{" + "name='" + name + '\'' + ", match=" + match + ", route=" + route + '}'; } } diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/VirtualServiceRule.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/VirtualServiceRule.java index 8f5497a099..76c6204b0b 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/VirtualServiceRule.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/VirtualServiceRule.java @@ -14,12 +14,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice; import org.apache.dubbo.rpc.cluster.router.mesh.rule.BaseRule; - public class VirtualServiceRule extends BaseRule { private VirtualServiceSpec spec; @@ -33,9 +31,6 @@ public class VirtualServiceRule extends BaseRule { @Override public String toString() { - return "VirtualServiceRule{" + - "base=" + super.toString() + - ", spec=" + spec + - '}'; + return "VirtualServiceRule{" + "base=" + super.toString() + ", spec=" + spec + '}'; } } diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/VirtualServiceSpec.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/VirtualServiceSpec.java index 648fe3be40..69f13e9614 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/VirtualServiceSpec.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/VirtualServiceSpec.java @@ -14,12 +14,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice; import java.util.List; - public class VirtualServiceSpec { private List hosts; private List dubbo; @@ -42,9 +40,6 @@ public class VirtualServiceSpec { @Override public String toString() { - return "VirtualServiceSpec{" + - "hosts=" + hosts + - ", dubbo=" + dubbo + - '}'; + return "VirtualServiceSpec{" + "hosts=" + hosts + ", dubbo=" + dubbo + '}'; } } diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/destination/DubboDestination.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/destination/DubboDestination.java index c21a008790..a3945e0f36 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/destination/DubboDestination.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/destination/DubboDestination.java @@ -14,17 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.destination; - public class DubboDestination { private String host; private String subset; private int port; private DubboRouteDestination fallback; - public String getHost() { return host; } diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/destination/DubboRouteDestination.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/destination/DubboRouteDestination.java index b9588c40cf..3f0179a109 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/destination/DubboRouteDestination.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/destination/DubboRouteDestination.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.destination; - public class DubboRouteDestination { private DubboDestination destination; private int weight; diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboAttachmentMatch.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboAttachmentMatch.java index a6cb45d274..083df7cb5c 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboAttachmentMatch.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboAttachmentMatch.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match; import org.apache.dubbo.rpc.Invocation; @@ -23,7 +22,6 @@ import org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider; import java.util.Map; import java.util.Set; - public class DubboAttachmentMatch { private Map tracingContext; private Map dubboContext; @@ -49,7 +47,7 @@ public class DubboAttachmentMatch { if (dubboContext != null) { for (Map.Entry entry : dubboContext.entrySet()) { String key = entry.getKey(); - if(!entry.getValue().isMatch(invocation.getAttachment(key))) { + if (!entry.getValue().isMatch(invocation.getAttachment(key))) { return false; } } diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleDispatcher.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleDispatcher.java index 713c44bd1b..9592b776c7 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleDispatcher.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleDispatcher.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.util; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -31,7 +30,6 @@ import java.util.concurrent.ConcurrentMap; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_NO_RULE_LISTENER; - public class MeshRuleDispatcher { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MeshRuleDispatcher.class); @@ -59,7 +57,12 @@ public class MeshRuleDispatcher { listener.onRuleChange(appName, entry.getValue()); } } else { - logger.warn(CLUSTER_NO_RULE_LISTENER, "Receive mesh rule but none of listener has been registered", "", "Receive rule but none of listener has been registered. Maybe type not matched. Rule Type: " + ruleType); + logger.warn( + CLUSTER_NO_RULE_LISTENER, + "Receive mesh rule but none of listener has been registered", + "", + "Receive rule but none of listener has been registered. Maybe type not matched. Rule Type: " + + ruleType); } } // clear rule listener not being notified in this time @@ -78,7 +81,7 @@ public class MeshRuleDispatcher { return; } ConcurrentHashMapUtils.computeIfAbsent(listenerMap, listener.ruleSuffix(), (k) -> new ConcurrentHashSet<>()) - .add(listener); + .add(listener); } public synchronized void unregister(MeshRuleListener listener) { diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleListener.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleListener.java index ce4fa56b52..17f102babf 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleListener.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleListener.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.util; - import java.util.List; import java.util.Map; diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshAppRuleListenerTest.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshAppRuleListenerTest.java index afa2ae3241..07724fb9fb 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshAppRuleListenerTest.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshAppRuleListenerTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.route; import org.apache.dubbo.common.URL; @@ -22,6 +21,11 @@ import org.apache.dubbo.common.config.configcenter.ConfigChangeType; import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.rpc.cluster.router.mesh.util.MeshRuleListener; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -30,91 +34,79 @@ import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.SafeConstructor; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; - import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.MESH_RULE_DATA_ID_SUFFIX; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; - class MeshAppRuleListenerTest { - private final static String rule1 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + - "kind: DestinationRule\n" + - "metadata: { name: demo-route }\n" + - "spec:\n" + - " host: demo\n" + - " subsets:\n" + - " - labels: { env-sign: xxx, tag1: hello }\n" + - " name: isolation\n" + - " - labels: { env-sign: yyy }\n" + - " name: testing-trunk\n" + - " - labels: { env-sign: zzz }\n" + - " name: testing\n" + - " trafficPolicy:\n" + - " loadBalancer: { simple: ROUND_ROBIN }\n" + - "\n"; - private final static String rule2 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + - "kind: VirtualService\n" + - "metadata: { name: demo-route }\n" + - "spec:\n" + - " dubbo:\n" + - " - routedetail:\n" + - " - match:\n" + - " - sourceLabels: {trafficLabel: xxx}\n" + - " name: xxx-project\n" + - " route:\n" + - " - destination: {host: demo, subset: isolation}\n" + - " - match:\n" + - " - sourceLabels: {trafficLabel: testing-trunk}\n" + - " name: testing-trunk\n" + - " route:\n" + - " - destination: {host: demo, subset: testing-trunk}\n" + - " - name: testing\n" + - " route:\n" + - " - destination: {host: demo, subset: testing}\n" + - " services:\n" + - " - {regex: ccc}\n" + - " hosts: [demo]\n"; - private final static String rule3 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + - "kind: DestinationRule\n" + - "spec:\n" + - " host: demo\n" + - " subsets:\n" + - " - labels: { env-sign: xxx, tag1: hello }\n" + - " name: isolation\n" + - " - labels: { env-sign: yyy }\n" + - " name: testing-trunk\n" + - " - labels: { env-sign: zzz }\n" + - " name: testing\n" + - " trafficPolicy:\n" + - " loadBalancer: { simple: ROUND_ROBIN }\n"; - private final static String rule4 = "apiVersionservice.dubbo.apache.org/v1alpha1\n"; - private final static String rule5 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + - "kind: DestinationRule\n" + - "metadata: { name: demo-route.Type1 }\n" + - "spec:\n" + - " host: demo\n" + - "\n"; - private final static String rule6 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + - "kind: VirtualService\n" + - "metadata: { name: demo-route.Type1 }\n" + - "spec:\n" + - " hosts: [demo]\n"; - private final static String rule7 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + - "kind: DestinationRule\n" + - "metadata: { name: demo-route.Type2 }\n" + - "spec:\n" + - " host: demo\n" + - "\n"; - private final static String rule8 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + - "kind: VirtualService\n" + - "metadata: { name: demo-route.Type2 }\n" + - "spec:\n" + - " hosts: [demo]\n"; + private static final String rule1 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n" + + "metadata: { name: demo-route }\n" + + "spec:\n" + + " host: demo\n" + + " subsets:\n" + + " - labels: { env-sign: xxx, tag1: hello }\n" + + " name: isolation\n" + + " - labels: { env-sign: yyy }\n" + + " name: testing-trunk\n" + + " - labels: { env-sign: zzz }\n" + + " name: testing\n" + + " trafficPolicy:\n" + + " loadBalancer: { simple: ROUND_ROBIN }\n" + + "\n"; + private static final String rule2 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n" + + "metadata: { name: demo-route }\n" + + "spec:\n" + + " dubbo:\n" + + " - routedetail:\n" + + " - match:\n" + + " - sourceLabels: {trafficLabel: xxx}\n" + + " name: xxx-project\n" + + " route:\n" + + " - destination: {host: demo, subset: isolation}\n" + + " - match:\n" + + " - sourceLabels: {trafficLabel: testing-trunk}\n" + + " name: testing-trunk\n" + + " route:\n" + + " - destination: {host: demo, subset: testing-trunk}\n" + + " - name: testing\n" + + " route:\n" + + " - destination: {host: demo, subset: testing}\n" + + " services:\n" + + " - {regex: ccc}\n" + + " hosts: [demo]\n"; + private static final String rule3 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n" + + "spec:\n" + + " host: demo\n" + + " subsets:\n" + + " - labels: { env-sign: xxx, tag1: hello }\n" + + " name: isolation\n" + + " - labels: { env-sign: yyy }\n" + + " name: testing-trunk\n" + + " - labels: { env-sign: zzz }\n" + + " name: testing\n" + + " trafficPolicy:\n" + + " loadBalancer: { simple: ROUND_ROBIN }\n"; + private static final String rule4 = "apiVersionservice.dubbo.apache.org/v1alpha1\n"; + private static final String rule5 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n" + + "metadata: { name: demo-route.Type1 }\n" + + "spec:\n" + + " host: demo\n" + + "\n"; + private static final String rule6 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n" + + "metadata: { name: demo-route.Type1 }\n" + + "spec:\n" + + " hosts: [demo]\n"; + private static final String rule7 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n" + + "metadata: { name: demo-route.Type2 }\n" + + "spec:\n" + + " host: demo\n" + + "\n"; + private static final String rule8 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n" + + "metadata: { name: demo-route.Type2 }\n" + + "spec:\n" + + " hosts: [demo]\n"; @Test void testStandard() { @@ -151,10 +143,22 @@ class MeshAppRuleListenerTest { meshAppRuleListener.register(standardMeshRuleRouter1); - Assertions.assertEquals(1, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().get(MeshRuleConstants.STANDARD_ROUTER_KEY).size()); + Assertions.assertEquals( + 1, + meshAppRuleListener + .getMeshRuleDispatcher() + .getListenerMap() + .get(MeshRuleConstants.STANDARD_ROUTER_KEY) + .size()); meshAppRuleListener.receiveConfigInfo(rule1 + "---\n" + rule2); meshAppRuleListener.register(standardMeshRuleRouter2); - Assertions.assertEquals(2, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().get(MeshRuleConstants.STANDARD_ROUTER_KEY).size()); + Assertions.assertEquals( + 2, + meshAppRuleListener + .getMeshRuleDispatcher() + .getListenerMap() + .get(MeshRuleConstants.STANDARD_ROUTER_KEY) + .size()); ArgumentCaptor appCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor>> ruleCaptor = ArgumentCaptor.forClass(List.class); @@ -176,7 +180,6 @@ class MeshAppRuleListenerTest { Assertions.assertTrue(rulesReceived.contains(yaml.load(rule2))); Assertions.assertEquals("demo-route", appCaptor.getValue()); - } @Test @@ -188,16 +191,35 @@ class MeshAppRuleListenerTest { meshAppRuleListener.register(standardMeshRuleRouter1); - Assertions.assertEquals(1, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().get(MeshRuleConstants.STANDARD_ROUTER_KEY).size()); + Assertions.assertEquals( + 1, + meshAppRuleListener + .getMeshRuleDispatcher() + .getListenerMap() + .get(MeshRuleConstants.STANDARD_ROUTER_KEY) + .size()); meshAppRuleListener.receiveConfigInfo(rule1 + "---\n" + rule2); meshAppRuleListener.register(standardMeshRuleRouter2); - Assertions.assertEquals(2, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().get(MeshRuleConstants.STANDARD_ROUTER_KEY).size()); + Assertions.assertEquals( + 2, + meshAppRuleListener + .getMeshRuleDispatcher() + .getListenerMap() + .get(MeshRuleConstants.STANDARD_ROUTER_KEY) + .size()); meshAppRuleListener.unregister(standardMeshRuleRouter1); - Assertions.assertEquals(1, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().get(MeshRuleConstants.STANDARD_ROUTER_KEY).size()); + Assertions.assertEquals( + 1, + meshAppRuleListener + .getMeshRuleDispatcher() + .getListenerMap() + .get(MeshRuleConstants.STANDARD_ROUTER_KEY) + .size()); meshAppRuleListener.unregister(standardMeshRuleRouter2); - Assertions.assertEquals(0, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size()); + Assertions.assertEquals( + 0, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size()); } @Test @@ -207,8 +229,11 @@ class MeshAppRuleListenerTest { StandardMeshRuleRouter standardMeshRuleRouter = Mockito.spy(new StandardMeshRuleRouter(URL.valueOf(""))); meshAppRuleListener.register(standardMeshRuleRouter); - ConfigChangedEvent configChangedEvent = new ConfigChangedEvent("demo-route" + MESH_RULE_DATA_ID_SUFFIX, DynamicConfiguration.DEFAULT_GROUP, - rule1 + "---\n" + rule2, ConfigChangeType.ADDED); + ConfigChangedEvent configChangedEvent = new ConfigChangedEvent( + "demo-route" + MESH_RULE_DATA_ID_SUFFIX, + DynamicConfiguration.DEFAULT_GROUP, + rule1 + "---\n" + rule2, + ConfigChangeType.ADDED); meshAppRuleListener.process(configChangedEvent); @@ -223,8 +248,11 @@ class MeshAppRuleListenerTest { Assertions.assertTrue(rulesReceived.contains(yaml.load(rule1))); Assertions.assertTrue(rulesReceived.contains(yaml.load(rule2))); - configChangedEvent = new ConfigChangedEvent("demo-route" + MESH_RULE_DATA_ID_SUFFIX, DynamicConfiguration.DEFAULT_GROUP, - rule1 + "---\n" + rule2, ConfigChangeType.MODIFIED); + configChangedEvent = new ConfigChangedEvent( + "demo-route" + MESH_RULE_DATA_ID_SUFFIX, + DynamicConfiguration.DEFAULT_GROUP, + rule1 + "---\n" + rule2, + ConfigChangeType.MODIFIED); meshAppRuleListener.process(configChangedEvent); @@ -235,8 +263,11 @@ class MeshAppRuleListenerTest { Assertions.assertTrue(rulesReceived.contains(yaml.load(rule1))); Assertions.assertTrue(rulesReceived.contains(yaml.load(rule2))); - configChangedEvent = new ConfigChangedEvent("demo-route" + MESH_RULE_DATA_ID_SUFFIX, DynamicConfiguration.DEFAULT_GROUP, - "", ConfigChangeType.DELETED); + configChangedEvent = new ConfigChangedEvent( + "demo-route" + MESH_RULE_DATA_ID_SUFFIX, + DynamicConfiguration.DEFAULT_GROUP, + "", + ConfigChangeType.DELETED); meshAppRuleListener.process(configChangedEvent); verify(standardMeshRuleRouter, times(1)).clearRule("demo-route"); @@ -289,9 +320,7 @@ class MeshAppRuleListenerTest { } @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} @Override public String ruleSuffix() { @@ -310,9 +339,7 @@ class MeshAppRuleListenerTest { } @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} @Override public String ruleSuffix() { @@ -345,7 +372,8 @@ class MeshAppRuleListenerTest { meshAppRuleListener.register(listener2); meshAppRuleListener.register(listener4); - meshAppRuleListener.receiveConfigInfo(rule1 + "---\n" + rule2 + "---\n" + rule5 + "---\n" + rule6 + "---\n" + rule7 + "---\n" + rule8); + meshAppRuleListener.receiveConfigInfo( + rule1 + "---\n" + rule2 + "---\n" + rule5 + "---\n" + rule6 + "---\n" + rule7 + "---\n" + rule8); ArgumentCaptor appCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor>> ruleCaptor = ArgumentCaptor.forClass(List.class); diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCacheTest.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCacheTest.java index c44a126ba9..76409a9f90 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCacheTest.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCacheTest.java @@ -24,14 +24,15 @@ import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.DestinationRule import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.DestinationRuleSpec; import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.Subset; import org.apache.dubbo.rpc.cluster.router.state.BitList; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; @@ -40,7 +41,8 @@ import static org.mockito.Mockito.when; class MeshRuleCacheTest { private Invoker createInvoker(String app) { - URL url = URL.valueOf("dubbo://localhost/DemoInterface?" + (StringUtils.isEmpty(app) ? "" : "remote.application=" + app)); + URL url = URL.valueOf( + "dubbo://localhost/DemoInterface?" + (StringUtils.isEmpty(app) ? "" : "remote.application=" + app)); Invoker invoker = Mockito.mock(Invoker.class); when(invoker.getUrl()).thenReturn(url); return invoker; @@ -54,7 +56,6 @@ class MeshRuleCacheTest { when(url.getOriginalServiceParameter("test", "key3")).thenReturn("value3"); when(url.getOriginalServiceParameter("test", "key4")).thenReturn("value4"); - Map originMap = new HashMap<>(); originMap.put("key1", "value1"); @@ -70,13 +71,12 @@ class MeshRuleCacheTest { inputMap.put("key4", "value4"); assertTrue(MeshRuleCache.isLabelMatch(url, "test", inputMap)); - } - @Test void testBuild() { - BitList> invokers = new BitList<>(Arrays.asList(createInvoker(""), createInvoker("unknown"), createInvoker("app1"))); + BitList> invokers = + new BitList<>(Arrays.asList(createInvoker(""), createInvoker("unknown"), createInvoker("app1"))); Subset subset = new Subset(); subset.setName("TestSubset"); @@ -98,7 +98,8 @@ class MeshRuleCacheTest { assertEquals(3, cache.getUnmatchedInvokers().size()); assertEquals(0, cache.getSubsetInvokers("app1", "TestSubset").size()); - invokers = new BitList<>(Arrays.asList(createInvoker(""), createInvoker("unknown"), createInvoker("app1"), createInvoker("app2"))); + invokers = new BitList<>(Arrays.asList( + createInvoker(""), createInvoker("unknown"), createInvoker("app1"), createInvoker("app2"))); subset.setLabels(null); cache = MeshRuleCache.build("test", invokers, vsDestinationGroupMap); assertEquals(3, cache.getUnmatchedInvokers().size()); diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleManagerTest.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleManagerTest.java index 9bb33df7e0..b81b96706a 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleManagerTest.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleManagerTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.route; import org.apache.dubbo.common.extension.ExtensionLoader; @@ -22,6 +21,13 @@ import org.apache.dubbo.rpc.cluster.governance.GovernanceRuleRepository; import org.apache.dubbo.rpc.cluster.router.mesh.util.MeshRuleListener; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; + +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -30,12 +36,6 @@ import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.SafeConstructor; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; @@ -43,31 +43,25 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; - class MeshRuleManagerTest { - private final static String rule1 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + - "kind: DestinationRule\n" + - "metadata: { name: demo-route.Type1 }\n" + - "spec:\n" + - " host: demo\n" + - "\n"; - private final static String rule2 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + - "kind: VirtualService\n" + - "metadata: { name: demo-route.Type1 }\n" + - "spec:\n" + - " hosts: [demo]\n"; - private final static String rule3 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + - "kind: DestinationRule\n" + - "metadata: { name: demo-route.Type2 }\n" + - "spec:\n" + - " host: demo\n" + - "\n"; - private final static String rule4 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + - "kind: VirtualService\n" + - "metadata: { name: demo-route.Type2 }\n" + - "spec:\n" + - " hosts: [demo]\n"; - + private static final String rule1 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n" + + "metadata: { name: demo-route.Type1 }\n" + + "spec:\n" + + " host: demo\n" + + "\n"; + private static final String rule2 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n" + + "metadata: { name: demo-route.Type1 }\n" + + "spec:\n" + + " hosts: [demo]\n"; + private static final String rule3 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n" + + "metadata: { name: demo-route.Type2 }\n" + + "spec:\n" + + " host: demo\n" + + "\n"; + private static final String rule4 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n" + + "metadata: { name: demo-route.Type2 }\n" + + "spec:\n" + + " hosts: [demo]\n"; private ModuleModel originModule; private ModuleModel moduleModel; @@ -104,9 +98,7 @@ class MeshRuleManagerTest { } @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} @Override public String ruleSuffix() { @@ -119,9 +111,9 @@ class MeshRuleManagerTest { assertEquals(1, meshRuleManager.getAppRuleListeners().size()); verify(ruleRepository, times(1)).getRule("dubbo-demo.MESHAPPRULE", "dubbo", 5000L); - MeshAppRuleListener meshAppRuleListener = meshRuleManager.getAppRuleListeners().values().iterator().next(); - verify(ruleRepository, times(1)).addListener("dubbo-demo.MESHAPPRULE", "dubbo", - meshAppRuleListener); + MeshAppRuleListener meshAppRuleListener = + meshRuleManager.getAppRuleListeners().values().iterator().next(); + verify(ruleRepository, times(1)).addListener("dubbo-demo.MESHAPPRULE", "dubbo", meshAppRuleListener); meshRuleManager.register("dubbo-demo", meshRuleListener1); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); @@ -133,9 +125,7 @@ class MeshRuleManagerTest { } @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} @Override public String ruleSuffix() { @@ -144,17 +134,18 @@ class MeshRuleManagerTest { }; meshRuleManager.register("dubbo-demo", meshRuleListener2); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); - assertEquals(2, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size()); + assertEquals( + 2, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size()); meshRuleManager.unregister("dubbo-demo", meshRuleListener1); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); - assertEquals(1, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size()); + assertEquals( + 1, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size()); meshRuleManager.unregister("dubbo-demo", meshRuleListener2); assertEquals(0, meshRuleManager.getAppRuleListeners().size()); - verify(ruleRepository, times(1)).removeListener("dubbo-demo.MESHAPPRULE", "dubbo", - meshAppRuleListener); + verify(ruleRepository, times(1)).removeListener("dubbo-demo.MESHAPPRULE", "dubbo", meshAppRuleListener); } @Test @@ -174,9 +165,7 @@ class MeshRuleManagerTest { } @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} @Override public String ruleSuffix() { @@ -190,8 +179,15 @@ class MeshRuleManagerTest { assertEquals(1, meshRuleManager.getAppRuleListeners().size()); verify(ruleRepository, times(1)).getRule("dubbo-demo.MESHAPPRULE", "dubbo", 5000L); - verify(ruleRepository, times(1)).addListener("dubbo-demo.MESHAPPRULE", "dubbo", - meshRuleManager.getAppRuleListeners().values().iterator().next()); + verify(ruleRepository, times(1)) + .addListener( + "dubbo-demo.MESHAPPRULE", + "dubbo", + meshRuleManager + .getAppRuleListeners() + .values() + .iterator() + .next()); assertEquals(1, invokeTimes.get()); meshRuleManager.register("dubbo-demo", meshRuleListener); @@ -220,9 +216,7 @@ class MeshRuleManagerTest { } @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} @Override public String ruleSuffix() { @@ -237,17 +231,15 @@ class MeshRuleManagerTest { assertEquals(1, meshRuleManager.getAppRuleListeners().size()); verify(ruleRepository, times(1)).getRule("dubbo-demo.MESHAPPRULE", "dubbo", 5000L); - MeshAppRuleListener meshAppRuleListener = meshRuleManager.getAppRuleListeners().values().iterator().next(); - verify(ruleRepository, times(1)).addListener("dubbo-demo.MESHAPPRULE", "dubbo", - meshAppRuleListener); + MeshAppRuleListener meshAppRuleListener = + meshRuleManager.getAppRuleListeners().values().iterator().next(); + verify(ruleRepository, times(1)).addListener("dubbo-demo.MESHAPPRULE", "dubbo", meshAppRuleListener); - verify(meshEnvListener2, times(1)).onSubscribe("dubbo-demo", - meshAppRuleListener); + verify(meshEnvListener2, times(1)).onSubscribe("dubbo-demo", meshAppRuleListener); meshRuleManager.register("dubbo-demo", meshRuleListener1); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); - MeshRuleListener meshRuleListener2 = new MeshRuleListener() { @Override public void onRuleChange(String appName, List> rules) { @@ -255,9 +247,7 @@ class MeshRuleManagerTest { } @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} @Override public String ruleSuffix() { @@ -266,17 +256,18 @@ class MeshRuleManagerTest { }; meshRuleManager.register("dubbo-demo", meshRuleListener2); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); - assertEquals(2, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size()); + assertEquals( + 2, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size()); meshRuleManager.unregister("dubbo-demo", meshRuleListener1); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); - assertEquals(1, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size()); + assertEquals( + 1, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size()); meshRuleManager.unregister("dubbo-demo", meshRuleListener2); assertEquals(0, meshRuleManager.getAppRuleListeners().size()); - verify(ruleRepository, times(1)).removeListener("dubbo-demo.MESHAPPRULE", "dubbo", - meshAppRuleListener); + verify(ruleRepository, times(1)).removeListener("dubbo-demo.MESHAPPRULE", "dubbo", meshAppRuleListener); verify(meshEnvListener2, times(1)).onUnSubscribe("dubbo-demo"); } } diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleRouterTest.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleRouterTest.java index 055488d6d2..2cf9da4cf2 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleRouterTest.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleRouterTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.route; import org.apache.dubbo.common.URL; @@ -28,13 +27,6 @@ import org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider; import org.apache.dubbo.rpc.cluster.router.state.BitList; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; -import org.yaml.snakeyaml.LoaderOptions; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.SafeConstructor; import java.util.Arrays; import java.util.Collections; @@ -45,123 +37,126 @@ import java.util.List; import java.util.Map; import java.util.Set; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.SafeConstructor; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; - class MeshRuleRouterTest { - private final static String rule1 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + - "kind: DestinationRule\n" + - "metadata: { name: demo-route }\n" + - "spec:\n" + - " host: demo\n" + - " subsets:\n" + - " - labels: { env-sign: xxx, tag1: hello }\n" + - " name: isolation\n" + - " - labels: { env-sign: yyy }\n" + - " name: testing-trunk\n" + - " - labels: { env-sign: zzz }\n" + - " name: testing\n" + - " trafficPolicy:\n" + - " loadBalancer: { simple: ROUND_ROBIN }\n" + - "\n"; - private final static String rule2 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + - "kind: VirtualService\n" + - "metadata: { name: demo-route }\n" + - "spec:\n" + - " dubbo:\n" + - " - routedetail:\n" + - " - match:\n" + - " - attachments: \n" + - " dubboContext: {trafficLabel: {regex: xxx}}\n" + - " name: xxx-project\n" + - " route:\n" + - " - destination: {host: demo, subset: isolation}\n" + - " - match:\n" + - " - attachments: \n" + - " dubboContext: {trafficLabel: {regex: testing-trunk}}\n" + - " name: testing-trunk\n" + - " route:\n" + - " - destination:\n" + - " host: demo\n" + - " subset: testing-trunk\n" + - " fallback:\n" + - " host: demo\n" + - " subset: testing\n" + - " - name: testing\n" + - " route:\n" + - " - destination: {host: demo, subset: testing}\n" + - " services:\n" + - " - {regex: ccc}\n" + - " hosts: [demo]\n"; - private final static String rule3 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + - "kind: VirtualService\n" + - "metadata: { name: demo-route }\n" + - "spec:\n" + - " dubbo:\n" + - " - routedetail:\n" + - " - match:\n" + - " - attachments: \n" + - " dubboContext: {trafficLabel: {regex: xxx}}\n" + - " name: xxx-project\n" + - " route:\n" + - " - destination: {host: demo, subset: isolation}\n" + - " - match:\n" + - " - attachments: \n" + - " dubboContext: {trafficLabel: {regex: testing-trunk}}\n" + - " name: testing-trunk\n" + - " route:\n" + - " - destination:\n" + - " host: demo\n" + - " subset: testing-trunk\n" + - " fallback:\n" + - " host: demo\n" + - " subset: testing\n" + - " - match:\n" + - " - attachments: \n" + - " dubboContext: {trafficLabel: {regex: testing}}\n" + - " name: testing\n" + - " route:\n" + - " - destination: {host: demo, subset: testing}\n" + - " hosts: [demo]\n"; - private final static String rule4 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + - "kind: VirtualService\n" + - "metadata: { name: demo-route }\n" + - "spec:\n" + - " dubbo:\n" + - " - routedetail:\n" + - " - match:\n" + - " - attachments: \n" + - " dubboContext: {trafficLabel: {regex: xxx}}\n" + - " name: xxx-project\n" + - " route:\n" + - " - destination: {host: demo, subset: isolation}\n" + - " - match:\n" + - " - attachments: \n" + - " dubboContext: {trafficLabel: {regex: testing-trunk}}\n" + - " name: testing-trunk\n" + - " route:\n" + - " - destination:\n" + - " host: demo\n" + - " subset: testing-trunk\n" + - " fallback:\n" + - " destination:\n" + - " host: demo\n" + - " subset: testing\n" + - " - weight: 10\n" + - " destination:\n" + - " host: demo\n" + - " subset: isolation\n" + - " - match:\n" + - " - attachments: \n" + - " dubboContext: {trafficLabel: {regex: testing}}\n" + - " name: testing\n" + - " route:\n" + - " - destination: {host: demo, subset: testing}\n" + - " hosts: [demo]\n"; + private static final String rule1 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n" + + "metadata: { name: demo-route }\n" + + "spec:\n" + + " host: demo\n" + + " subsets:\n" + + " - labels: { env-sign: xxx, tag1: hello }\n" + + " name: isolation\n" + + " - labels: { env-sign: yyy }\n" + + " name: testing-trunk\n" + + " - labels: { env-sign: zzz }\n" + + " name: testing\n" + + " trafficPolicy:\n" + + " loadBalancer: { simple: ROUND_ROBIN }\n" + + "\n"; + private static final String rule2 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n" + + "metadata: { name: demo-route }\n" + + "spec:\n" + + " dubbo:\n" + + " - routedetail:\n" + + " - match:\n" + + " - attachments: \n" + + " dubboContext: {trafficLabel: {regex: xxx}}\n" + + " name: xxx-project\n" + + " route:\n" + + " - destination: {host: demo, subset: isolation}\n" + + " - match:\n" + + " - attachments: \n" + + " dubboContext: {trafficLabel: {regex: testing-trunk}}\n" + + " name: testing-trunk\n" + + " route:\n" + + " - destination:\n" + + " host: demo\n" + + " subset: testing-trunk\n" + + " fallback:\n" + + " host: demo\n" + + " subset: testing\n" + + " - name: testing\n" + + " route:\n" + + " - destination: {host: demo, subset: testing}\n" + + " services:\n" + + " - {regex: ccc}\n" + + " hosts: [demo]\n"; + private static final String rule3 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n" + + "metadata: { name: demo-route }\n" + + "spec:\n" + + " dubbo:\n" + + " - routedetail:\n" + + " - match:\n" + + " - attachments: \n" + + " dubboContext: {trafficLabel: {regex: xxx}}\n" + + " name: xxx-project\n" + + " route:\n" + + " - destination: {host: demo, subset: isolation}\n" + + " - match:\n" + + " - attachments: \n" + + " dubboContext: {trafficLabel: {regex: testing-trunk}}\n" + + " name: testing-trunk\n" + + " route:\n" + + " - destination:\n" + + " host: demo\n" + + " subset: testing-trunk\n" + + " fallback:\n" + + " host: demo\n" + + " subset: testing\n" + + " - match:\n" + + " - attachments: \n" + + " dubboContext: {trafficLabel: {regex: testing}}\n" + + " name: testing\n" + + " route:\n" + + " - destination: {host: demo, subset: testing}\n" + + " hosts: [demo]\n"; + private static final String rule4 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n" + + "metadata: { name: demo-route }\n" + + "spec:\n" + + " dubbo:\n" + + " - routedetail:\n" + + " - match:\n" + + " - attachments: \n" + + " dubboContext: {trafficLabel: {regex: xxx}}\n" + + " name: xxx-project\n" + + " route:\n" + + " - destination: {host: demo, subset: isolation}\n" + + " - match:\n" + + " - attachments: \n" + + " dubboContext: {trafficLabel: {regex: testing-trunk}}\n" + + " name: testing-trunk\n" + + " route:\n" + + " - destination:\n" + + " host: demo\n" + + " subset: testing-trunk\n" + + " fallback:\n" + + " destination:\n" + + " host: demo\n" + + " subset: testing\n" + + " - weight: 10\n" + + " destination:\n" + + " host: demo\n" + + " subset: isolation\n" + + " - match:\n" + + " - attachments: \n" + + " dubboContext: {trafficLabel: {regex: testing}}\n" + + " name: testing\n" + + " route:\n" + + " - destination: {host: demo, subset: testing}\n" + + " hosts: [demo]\n"; private ModuleModel originModel; private ModuleModel moduleModel; @@ -195,27 +190,29 @@ class MeshRuleRouterTest { } private Invoker createInvoker(String app) { - URL url = URL.valueOf("dubbo://localhost/DemoInterface?" + (StringUtils.isEmpty(app) ? "" : "remote.application=" + app)); + URL url = URL.valueOf( + "dubbo://localhost/DemoInterface?" + (StringUtils.isEmpty(app) ? "" : "remote.application=" + app)); Invoker invoker = Mockito.mock(Invoker.class); when(invoker.getUrl()).thenReturn(url); return invoker; } private Invoker createInvoker(Map parameters) { - URL url = URL.valueOf("dubbo://localhost/DemoInterface?remote.application=app1").addParameters(parameters); + URL url = URL.valueOf("dubbo://localhost/DemoInterface?remote.application=app1") + .addParameters(parameters); Invoker invoker = Mockito.mock(Invoker.class); when(invoker.getUrl()).thenReturn(url); return invoker; } - @Test void testNotify() { StandardMeshRuleRouter meshRuleRouter = new StandardMeshRuleRouter<>(url); meshRuleRouter.notify(null); assertEquals(0, meshRuleRouter.getRemoteAppName().size()); - BitList> invokers = new BitList<>(Arrays.asList(createInvoker(""), createInvoker("unknown"), createInvoker("app1"))); + BitList> invokers = + new BitList<>(Arrays.asList(createInvoker(""), createInvoker("unknown"), createInvoker("app1"))); meshRuleRouter.notify(invokers); @@ -264,7 +261,8 @@ class MeshRuleRouterTest { @Test void testRoute1() { StandardMeshRuleRouter meshRuleRouter = new StandardMeshRuleRouter<>(url); - BitList> invokers = new BitList<>(Arrays.asList(createInvoker(""), createInvoker("unknown"), createInvoker("app1"))); + BitList> invokers = + new BitList<>(Arrays.asList(createInvoker(""), createInvoker("unknown"), createInvoker("app1"))); assertEquals(invokers, meshRuleRouter.route(invokers.clone(), null, null, false, null)); Holder message = new Holder<>(); meshRuleRouter.doRoute(invokers.clone(), null, null, true, null, message); @@ -281,10 +279,12 @@ class MeshRuleRouterTest { rules.add(yaml.load(rule2)); meshRuleRouter.onRuleChange("app1", rules); - Invoker isolation = createInvoker(new HashMap() {{ - put("env-sign", "xxx"); - put("tag1", "hello"); - }}); + Invoker isolation = createInvoker(new HashMap() { + { + put("env-sign", "xxx"); + put("tag1", "hello"); + } + }); Invoker testingTrunk = createInvoker(Collections.singletonMap("env-sign", "yyy")); Invoker testing = createInvoker(Collections.singletonMap("env-sign", "zzz")); @@ -295,19 +295,43 @@ class MeshRuleRouterTest { rpcInvocation.setServiceName("ccc"); rpcInvocation.setAttachment("trafficLabel", "xxx"); - assertEquals(1, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null).size()); - assertEquals(isolation, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null).get(0)); + assertEquals( + 1, + meshRuleRouter + .route(invokers.clone(), null, rpcInvocation, false, null) + .size()); + assertEquals( + isolation, + meshRuleRouter + .route(invokers.clone(), null, rpcInvocation, false, null) + .get(0)); Holder message = new Holder<>(); meshRuleRouter.doRoute(invokers.clone(), null, rpcInvocation, true, null, message); assertEquals("Match App: app1 Subset: isolation ", message.get()); rpcInvocation.setAttachment("trafficLabel", "testing-trunk"); - assertEquals(1, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null).size()); - assertEquals(testingTrunk, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null).get(0)); + assertEquals( + 1, + meshRuleRouter + .route(invokers.clone(), null, rpcInvocation, false, null) + .size()); + assertEquals( + testingTrunk, + meshRuleRouter + .route(invokers.clone(), null, rpcInvocation, false, null) + .get(0)); rpcInvocation.setAttachment("trafficLabel", null); - assertEquals(1, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null).size()); - assertEquals(testing, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null).get(0)); + assertEquals( + 1, + meshRuleRouter + .route(invokers.clone(), null, rpcInvocation, false, null) + .size()); + assertEquals( + testing, + meshRuleRouter + .route(invokers.clone(), null, rpcInvocation, false, null) + .get(0)); rpcInvocation.setServiceName("aaa"); assertEquals(invokers, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null)); @@ -322,22 +346,54 @@ class MeshRuleRouterTest { rpcInvocation.setServiceName("ccc"); rpcInvocation.setAttachment("trafficLabel", "xxx"); - assertEquals(1, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null).size()); - assertEquals(isolation, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null).get(0)); + assertEquals( + 1, + meshRuleRouter + .route(invokers.clone(), null, rpcInvocation, false, null) + .size()); + assertEquals( + isolation, + meshRuleRouter + .route(invokers.clone(), null, rpcInvocation, false, null) + .get(0)); rpcInvocation.setAttachment("trafficLabel", "testing-trunk"); - assertEquals(1, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null).size()); - assertEquals(testingTrunk, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null).get(0)); + assertEquals( + 1, + meshRuleRouter + .route(invokers.clone(), null, rpcInvocation, false, null) + .size()); + assertEquals( + testingTrunk, + meshRuleRouter + .route(invokers.clone(), null, rpcInvocation, false, null) + .get(0)); rpcInvocation.setAttachment("trafficLabel", "testing"); - assertEquals(1, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null).size()); - assertEquals(testing, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null).get(0)); + assertEquals( + 1, + meshRuleRouter + .route(invokers.clone(), null, rpcInvocation, false, null) + .size()); + assertEquals( + testing, + meshRuleRouter + .route(invokers.clone(), null, rpcInvocation, false, null) + .get(0)); rpcInvocation.setServiceName("aaa"); - assertEquals(1, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null).size()); - assertEquals(testing, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null).get(0)); + assertEquals( + 1, + meshRuleRouter + .route(invokers.clone(), null, rpcInvocation, false, null) + .size()); + assertEquals( + testing, + meshRuleRouter + .route(invokers.clone(), null, rpcInvocation, false, null) + .get(0)); - rpcInvocation.setAttachment("trafficLabel",null); + rpcInvocation.setAttachment("trafficLabel", null); assertEquals(invokers, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null)); rules = new LinkedList<>(); @@ -362,15 +418,31 @@ class MeshRuleRouterTest { invokers.removeAll(Arrays.asList(isolation, testingTrunk)); for (int i = 0; i < 1000; i++) { - assertEquals(1, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null).size()); - assertEquals(testing, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null).get(0)); + assertEquals( + 1, + meshRuleRouter + .route(invokers.clone(), null, rpcInvocation, false, null) + .size()); + assertEquals( + testing, + meshRuleRouter + .route(invokers.clone(), null, rpcInvocation, false, null) + .get(0)); } meshRuleRouter.notify(invokers); for (int i = 0; i < 1000; i++) { - assertEquals(1, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null).size()); - assertEquals(testing, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null).get(0)); + assertEquals( + 1, + meshRuleRouter + .route(invokers.clone(), null, rpcInvocation, false, null) + .size()); + assertEquals( + testing, + meshRuleRouter + .route(invokers.clone(), null, rpcInvocation, false, null) + .get(0)); } Invoker mock = createInvoker(Collections.singletonMap("env-sign", "mock")); @@ -379,6 +451,5 @@ class MeshRuleRouterTest { meshRuleRouter.notify(invokers); invokers.removeAll(Arrays.asList(isolation, testingTrunk, testing)); assertEquals(invokers, meshRuleRouter.route(invokers.clone(), null, rpcInvocation, false, null)); - } } diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouterFactoryTest.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouterFactoryTest.java index 312e04872f..c134325a1c 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouterFactoryTest.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouterFactoryTest.java @@ -14,19 +14,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.route; import org.apache.dubbo.common.URL; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; - class StandardMeshRuleRouterFactoryTest { @Test void getRouter() { StandardMeshRuleRouterFactory ruleRouterFactory = new StandardMeshRuleRouterFactory(); - Assertions.assertTrue(ruleRouterFactory.getRouter(Object.class, URL.valueOf("")) instanceof StandardMeshRuleRouter); + Assertions.assertTrue( + ruleRouterFactory.getRouter(Object.class, URL.valueOf("")) instanceof StandardMeshRuleRouter); } } diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/DestinationRuleTest.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/DestinationRuleTest.java index ec4e50fb1d..4dd045156e 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/DestinationRuleTest.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/DestinationRuleTest.java @@ -14,47 +14,46 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule; import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.DestinationRule; import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.loadbalance.SimpleLB; import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.VirtualServiceRule; -import org.junit.jupiter.api.Test; -import org.yaml.snakeyaml.Yaml; import java.util.Map; +import org.junit.jupiter.api.Test; +import org.yaml.snakeyaml.Yaml; + import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.DESTINATION_RULE_KEY; import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.KIND_KEY; import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.VIRTUAL_SERVICE_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; - class DestinationRuleTest { @Test void parserTest() { Yaml yaml = new Yaml(); - DestinationRule destinationRule = yaml.loadAs(this.getClass().getClassLoader().getResourceAsStream("DestinationRuleTest.yaml"), DestinationRule.class); + DestinationRule destinationRule = yaml.loadAs( + this.getClass().getClassLoader().getResourceAsStream("DestinationRuleTest.yaml"), + DestinationRule.class); System.out.println(destinationRule); - -// apiVersion: service.dubbo.apache.org/v1alpha1 -// kind: DestinationRule -// metadata: { name: demo-route } -// spec: -// host: demo -// subsets: -// - labels: { env-sign: xxx,tag1: hello } -// name: isolation -// - labels: { env-sign: yyy } -// name: testing-trunk -// - labels: { env-sign: zzz } -// name: testing - + // apiVersion: service.dubbo.apache.org/v1alpha1 + // kind: DestinationRule + // metadata: { name: demo-route } + // spec: + // host: demo + // subsets: + // - labels: { env-sign: xxx,tag1: hello } + // name: isolation + // - labels: { env-sign: yyy } + // name: testing-trunk + // - labels: { env-sign: zzz } + // name: testing assertEquals("service.dubbo.apache.org/v1alpha1", destinationRule.getApiVersion()); assertEquals(DESTINATION_RULE_KEY, destinationRule.getKind()); @@ -63,30 +62,41 @@ class DestinationRuleTest { assertEquals(3, destinationRule.getSpec().getSubsets().size()); assertEquals("isolation", destinationRule.getSpec().getSubsets().get(0).getName()); - assertEquals(2, destinationRule.getSpec().getSubsets().get(0).getLabels().size()); - assertEquals("xxx", destinationRule.getSpec().getSubsets().get(0).getLabels().get("env-sign")); - assertEquals("hello", destinationRule.getSpec().getSubsets().get(0).getLabels().get("tag1")); - - - assertEquals("testing-trunk", destinationRule.getSpec().getSubsets().get(1).getName()); - assertEquals(1, destinationRule.getSpec().getSubsets().get(1).getLabels().size()); - assertEquals("yyy", destinationRule.getSpec().getSubsets().get(1).getLabels().get("env-sign")); + assertEquals( + 2, destinationRule.getSpec().getSubsets().get(0).getLabels().size()); + assertEquals( + "xxx", destinationRule.getSpec().getSubsets().get(0).getLabels().get("env-sign")); + assertEquals( + "hello", + destinationRule.getSpec().getSubsets().get(0).getLabels().get("tag1")); + assertEquals( + "testing-trunk", destinationRule.getSpec().getSubsets().get(1).getName()); + assertEquals( + 1, destinationRule.getSpec().getSubsets().get(1).getLabels().size()); + assertEquals( + "yyy", destinationRule.getSpec().getSubsets().get(1).getLabels().get("env-sign")); assertEquals("testing", destinationRule.getSpec().getSubsets().get(2).getName()); - assertEquals(1, destinationRule.getSpec().getSubsets().get(2).getLabels().size()); - assertEquals("zzz", destinationRule.getSpec().getSubsets().get(2).getLabels().get("env-sign")); + assertEquals( + 1, destinationRule.getSpec().getSubsets().get(2).getLabels().size()); + assertEquals( + "zzz", destinationRule.getSpec().getSubsets().get(2).getLabels().get("env-sign")); - assertEquals(SimpleLB.ROUND_ROBIN, destinationRule.getSpec().getTrafficPolicy().getLoadBalancer().getSimple()); - assertEquals(null, destinationRule.getSpec().getTrafficPolicy().getLoadBalancer().getConsistentHash()); + assertEquals( + SimpleLB.ROUND_ROBIN, + destinationRule.getSpec().getTrafficPolicy().getLoadBalancer().getSimple()); + assertEquals( + null, + destinationRule.getSpec().getTrafficPolicy().getLoadBalancer().getConsistentHash()); } - @Test void parserMultiRuleTest() { Yaml yaml = new Yaml(); Yaml yaml2 = new Yaml(); - Iterable objectIterable = yaml.loadAll(this.getClass().getClassLoader().getResourceAsStream("DestinationRuleTest2.yaml")); + Iterable objectIterable = + yaml.loadAll(this.getClass().getClassLoader().getResourceAsStream("DestinationRuleTest2.yaml")); for (Object result : objectIterable) { Map resultMap = (Map) result; @@ -101,5 +111,4 @@ class DestinationRuleTest { } } } - } diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/VirtualServiceRuleTest.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/VirtualServiceRuleTest.java index 45bebd8cdd..0239233002 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/VirtualServiceRuleTest.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/VirtualServiceRuleTest.java @@ -14,28 +14,29 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule; import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.DubboRoute; import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.DubboRouteDetail; import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.VirtualServiceRule; -import org.junit.jupiter.api.Test; -import org.yaml.snakeyaml.Yaml; import java.util.List; +import org.junit.jupiter.api.Test; +import org.yaml.snakeyaml.Yaml; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; - class VirtualServiceRuleTest { @Test void parserTest() { Yaml yaml = new Yaml(); - VirtualServiceRule virtualServiceRule = yaml.loadAs(this.getClass().getClassLoader().getResourceAsStream("VirtualServiceTest.yaml"), VirtualServiceRule.class); + VirtualServiceRule virtualServiceRule = yaml.loadAs( + this.getClass().getClassLoader().getResourceAsStream("VirtualServiceTest.yaml"), + VirtualServiceRule.class); System.out.println(virtualServiceRule); assertNotNull(virtualServiceRule); @@ -63,19 +64,31 @@ class VirtualServiceRuleTest { DubboRouteDetail thirdDubboRouteDetail = routedetail.get(2); assertEquals("xxx-project", firstDubboRouteDetail.getName()); - assertEquals("xxx", firstDubboRouteDetail.getMatch().get(0).getSourceLabels().get("trafficLabel")); - assertEquals("demo", firstDubboRouteDetail.getRoute().get(0).getDestination().getHost()); - assertEquals("isolation", firstDubboRouteDetail.getRoute().get(0).getDestination().getSubset()); + assertEquals( + "xxx", firstDubboRouteDetail.getMatch().get(0).getSourceLabels().get("trafficLabel")); + assertEquals( + "demo", firstDubboRouteDetail.getRoute().get(0).getDestination().getHost()); + assertEquals( + "isolation", + firstDubboRouteDetail.getRoute().get(0).getDestination().getSubset()); assertEquals("testing-trunk", secondDubboRouteDetail.getName()); - assertEquals("testing-trunk", secondDubboRouteDetail.getMatch().get(0).getSourceLabels().get("trafficLabel")); - assertEquals("demo", secondDubboRouteDetail.getRoute().get(0).getDestination().getHost()); - assertEquals("testing-trunk", secondDubboRouteDetail.getRoute().get(0).getDestination().getSubset()); + assertEquals( + "testing-trunk", + secondDubboRouteDetail.getMatch().get(0).getSourceLabels().get("trafficLabel")); + assertEquals( + "demo", + secondDubboRouteDetail.getRoute().get(0).getDestination().getHost()); + assertEquals( + "testing-trunk", + secondDubboRouteDetail.getRoute().get(0).getDestination().getSubset()); assertEquals("testing", thirdDubboRouteDetail.getName()); assertNull(thirdDubboRouteDetail.getMatch()); - assertEquals("demo", thirdDubboRouteDetail.getRoute().get(0).getDestination().getHost()); - assertEquals("testing", thirdDubboRouteDetail.getRoute().get(0).getDestination().getSubset()); + assertEquals( + "demo", thirdDubboRouteDetail.getRoute().get(0).getDestination().getHost()); + assertEquals( + "testing", + thirdDubboRouteDetail.getRoute().get(0).getDestination().getSubset()); } - } diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboMatchRequestTest.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboMatchRequestTest.java index 6219e245ba..02d512137e 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboMatchRequestTest.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboMatchRequestTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice; import org.apache.dubbo.rpc.RpcInvocation; @@ -22,16 +21,16 @@ import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.DubboA import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.DubboMethodMatch; import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.StringMatch; import org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider; -import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; - class DubboMatchRequestTest { @Test @@ -74,7 +73,6 @@ class DubboMatchRequestTest { assertTrue(dubboMatchRequest.isMatch(rpcInvocation, inputSourceLabelsMap, Collections.emptySet())); assertFalse(dubboMatchRequest.isMatch(rpcInvocation, inputSourceLabelsMap2, Collections.emptySet())); - // tracingContext DubboAttachmentMatch dubboAttachmentMatch = new DubboAttachmentMatch(); Map tracingContextMatchMap = new HashMap<>(); @@ -90,8 +88,8 @@ class DubboMatchRequestTest { invokeTracingContextMap.put("other", "other"); TracingContextProvider tracingContextProvider = (invocation, key) -> invokeTracingContextMap.get(key); - assertTrue(dubboMatchRequest.isMatch(rpcInvocation, inputSourceLabelsMap, Collections.singleton(tracingContextProvider))); - + assertTrue(dubboMatchRequest.isMatch( + rpcInvocation, inputSourceLabelsMap, Collections.singleton(tracingContextProvider))); Map invokeTracingContextMap2 = new HashMap<>(); invokeTracingContextMap2.put("name", "jack"); @@ -99,10 +97,10 @@ class DubboMatchRequestTest { invokeTracingContextMap2.put("other", "other"); TracingContextProvider tracingContextProvider2 = (invocation, key) -> invokeTracingContextMap2.get(key); - assertFalse(dubboMatchRequest.isMatch(rpcInvocation, inputSourceLabelsMap, Collections.singleton(tracingContextProvider2))); + assertFalse(dubboMatchRequest.isMatch( + rpcInvocation, inputSourceLabelsMap, Collections.singleton(tracingContextProvider2))); - - //dubbo context + // dubbo context dubboAttachmentMatch = new DubboAttachmentMatch(); Map eagleeyecontextMatchMap = new HashMap<>(); @@ -111,7 +109,6 @@ class DubboMatchRequestTest { eagleeyecontextMatchMap.put("name", nameMatch); dubboAttachmentMatch.setTracingContext(eagleeyecontextMatchMap); - Map dubboContextMatchMap = new HashMap<>(); StringMatch dpathMatch = new StringMatch(); dpathMatch.setExact("PRE"); @@ -120,18 +117,19 @@ class DubboMatchRequestTest { dubboMatchRequest.setAttachments(dubboAttachmentMatch); - Map invokeDubboContextMap = new HashMap<>(); invokeDubboContextMap.put("dpath", "PRE"); rpcInvocation.setAttachments(invokeDubboContextMap); TracingContextProvider tracingContextProvider3 = (invocation, key) -> invokeTracingContextMap.get(key); - assertTrue(dubboMatchRequest.isMatch(rpcInvocation, inputSourceLabelsMap, Collections.singleton(tracingContextProvider3))); + assertTrue(dubboMatchRequest.isMatch( + rpcInvocation, inputSourceLabelsMap, Collections.singleton(tracingContextProvider3))); Map invokeDubboContextMap2 = new HashMap<>(); invokeDubboContextMap.put("dpath", "other"); rpcInvocation.setAttachments(invokeDubboContextMap2); - assertFalse(dubboMatchRequest.isMatch(rpcInvocation, inputSourceLabelsMap, Collections.singleton(tracingContextProvider3))); + assertFalse(dubboMatchRequest.isMatch( + rpcInvocation, inputSourceLabelsMap, Collections.singleton(tracingContextProvider3))); } } diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboAttachmentMatchTest.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboAttachmentMatchTest.java index 2feceee193..bb4042ab9b 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboAttachmentMatchTest.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboAttachmentMatchTest.java @@ -14,24 +14,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match; - import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; - class DubboAttachmentMatchTest { @Test @@ -44,7 +42,6 @@ class DubboAttachmentMatchTest { nameMatch.setExact("qinliujie"); dubbocontextMatchMap.put("name", nameMatch); - StringMatch machineGroupMatch = new StringMatch(); machineGroupMatch.setExact("test_host"); dubbocontextMatchMap.put("machineGroup", machineGroupMatch); @@ -61,7 +58,6 @@ class DubboAttachmentMatchTest { assertTrue(dubboAttachmentMatch.isMatch(rpcInvocation, Collections.emptySet())); - Map invokeDubboContextMap2 = new HashMap<>(); invokeDubboContextMap2.put("name", "jack"); invokeDubboContextMap2.put("machineGroup", "test_host"); @@ -72,7 +68,6 @@ class DubboAttachmentMatchTest { assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation2, Collections.emptySet())); - Map invokeDubboContextMap3 = new HashMap<>(); invokeDubboContextMap3.put("name", "qinliujie"); invokeDubboContextMap3.put("machineGroup", "my_host"); @@ -84,7 +79,6 @@ class DubboAttachmentMatchTest { assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation3, Collections.emptySet())); } - @Test void tracingContextMatch() { DubboAttachmentMatch dubboAttachmentMatch = new DubboAttachmentMatch(); @@ -107,7 +101,8 @@ class DubboAttachmentMatchTest { invokeEagleEyeContextMap.put("other", "other"); TracingContextProvider tracingContextProvider = (invocation, key) -> invokeEagleEyeContextMap.get(key); - assertTrue(dubboAttachmentMatch.isMatch(Mockito.mock(Invocation.class), Collections.singleton(tracingContextProvider))); + assertTrue(dubboAttachmentMatch.isMatch( + Mockito.mock(Invocation.class), Collections.singleton(tracingContextProvider))); Map invokeTracingContextMap2 = new HashMap<>(); invokeTracingContextMap2.put("name", "jack"); @@ -115,8 +110,8 @@ class DubboAttachmentMatchTest { invokeTracingContextMap2.put("other", "other"); TracingContextProvider tracingContextProvider2 = (invocation, key) -> invokeTracingContextMap2.get(key); - assertFalse(dubboAttachmentMatch.isMatch(Mockito.mock(Invocation.class), Collections.singleton(tracingContextProvider2))); - + assertFalse(dubboAttachmentMatch.isMatch( + Mockito.mock(Invocation.class), Collections.singleton(tracingContextProvider2))); Map invokeEagleEyeContextMap3 = new HashMap<>(); invokeEagleEyeContextMap3.put("name", "qinliujie"); @@ -124,10 +119,10 @@ class DubboAttachmentMatchTest { invokeEagleEyeContextMap3.put("other", "other"); TracingContextProvider tracingContextProvider3 = (invocation, key) -> invokeEagleEyeContextMap3.get(key); - assertFalse(dubboAttachmentMatch.isMatch(Mockito.mock(Invocation.class), Collections.singleton(tracingContextProvider3))); + assertFalse(dubboAttachmentMatch.isMatch( + Mockito.mock(Invocation.class), Collections.singleton(tracingContextProvider3))); } - @Test void contextMatch() { DubboAttachmentMatch dubboAttachmentMatch = new DubboAttachmentMatch(); @@ -157,7 +152,6 @@ class DubboAttachmentMatchTest { rpcInvocation.setAttachments(invokeDubboContextMap); assertTrue(dubboAttachmentMatch.isMatch(rpcInvocation, Collections.singleton(tracingContextProvider))); - Map invokeTracingContextMap1 = new HashMap<>(); invokeTracingContextMap1.put("name", "jack"); invokeTracingContextMap1.put("machineGroup", "test_host"); @@ -168,7 +162,6 @@ class DubboAttachmentMatchTest { rpcInvocation1.setAttachments(invokeDubboContextMap); assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation1, Collections.singleton(tracingContextProvider1))); - Map invokeDubboContextMap1 = new HashMap<>(); invokeDubboContextMap1.put("dpath", "PRE-2"); @@ -177,13 +170,11 @@ class DubboAttachmentMatchTest { rpcInvocation2.setAttachments(invokeDubboContextMap1); assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation2, Collections.singleton(tracingContextProvider2))); - TracingContextProvider tracingContextProvider3 = (invocation, key) -> invokeTracingContextMap1.get(key); RpcInvocation rpcInvocation3 = new RpcInvocation(); rpcInvocation3.setAttachments(invokeDubboContextMap1); assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation3, Collections.singleton(tracingContextProvider3))); - Map invokeTracingContextMap2 = new HashMap<>(); invokeTracingContextMap2.put("machineGroup", "test_host"); invokeTracingContextMap2.put("other", "other"); @@ -199,11 +190,9 @@ class DubboAttachmentMatchTest { rpcInvocation5.setAttachments(invokeDubboContextMap2); assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation5, Collections.singleton(tracingContextProvider5))); - TracingContextProvider tracingContextProvider6 = (invocation, key) -> invokeTracingContextMap2.get(key); RpcInvocation rpcInvocation6 = new RpcInvocation(); rpcInvocation5.setAttachments(invokeDubboContextMap2); assertFalse(dubboAttachmentMatch.isMatch(rpcInvocation6, Collections.singleton(tracingContextProvider6))); - } } diff --git a/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleDispatcherTest.java b/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleDispatcherTest.java index 5f548c7efd..e37b744990 100644 --- a/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleDispatcherTest.java +++ b/dubbo-plugin/dubbo-plugin-router-mesh/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleDispatcherTest.java @@ -14,18 +14,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.mesh.util; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class MeshRuleDispatcherTest { @Test @@ -50,9 +49,7 @@ class MeshRuleDispatcherTest { } @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} @Override public String ruleSuffix() { @@ -69,9 +66,7 @@ class MeshRuleDispatcherTest { } @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} @Override public String ruleSuffix() { @@ -112,13 +107,10 @@ class MeshRuleDispatcherTest { MeshRuleListener listener1 = new MeshRuleListener() { @Override - public void onRuleChange(String appName, List> rules) { - } + public void onRuleChange(String appName, List> rules) {} @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} @Override public String ruleSuffix() { @@ -129,7 +121,8 @@ class MeshRuleDispatcherTest { meshRuleDispatcher.register(listener1); meshRuleDispatcher.register(listener1); - Assertions.assertEquals(1, meshRuleDispatcher.getListenerMap().get("Type1").size()); + Assertions.assertEquals( + 1, meshRuleDispatcher.getListenerMap().get("Type1").size()); Assertions.assertTrue(meshRuleDispatcher.getListenerMap().get("Type1").contains(listener1)); } @@ -139,13 +132,10 @@ class MeshRuleDispatcherTest { MeshRuleListener listener1 = new MeshRuleListener() { @Override - public void onRuleChange(String appName, List> rules) { - } + public void onRuleChange(String appName, List> rules) {} @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} @Override public String ruleSuffix() { @@ -155,13 +145,10 @@ class MeshRuleDispatcherTest { MeshRuleListener listener2 = new MeshRuleListener() { @Override - public void onRuleChange(String appName, List> rules) { - } + public void onRuleChange(String appName, List> rules) {} @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} @Override public String ruleSuffix() { @@ -171,13 +158,10 @@ class MeshRuleDispatcherTest { MeshRuleListener listener3 = new MeshRuleListener() { @Override - public void onRuleChange(String appName, List> rules) { - } + public void onRuleChange(String appName, List> rules) {} @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} @Override public String ruleSuffix() { @@ -189,21 +173,26 @@ class MeshRuleDispatcherTest { meshRuleDispatcher.register(listener2); meshRuleDispatcher.register(listener3); - Assertions.assertEquals(2, meshRuleDispatcher.getListenerMap().get("Type1").size()); + Assertions.assertEquals( + 2, meshRuleDispatcher.getListenerMap().get("Type1").size()); Assertions.assertTrue(meshRuleDispatcher.getListenerMap().get("Type1").contains(listener1)); Assertions.assertTrue(meshRuleDispatcher.getListenerMap().get("Type1").contains(listener2)); - Assertions.assertEquals(1, meshRuleDispatcher.getListenerMap().get("Type2").size()); + Assertions.assertEquals( + 1, meshRuleDispatcher.getListenerMap().get("Type2").size()); Assertions.assertTrue(meshRuleDispatcher.getListenerMap().get("Type2").contains(listener3)); meshRuleDispatcher.unregister(listener1); - Assertions.assertEquals(1, meshRuleDispatcher.getListenerMap().get("Type1").size()); + Assertions.assertEquals( + 1, meshRuleDispatcher.getListenerMap().get("Type1").size()); Assertions.assertTrue(meshRuleDispatcher.getListenerMap().get("Type1").contains(listener2)); - Assertions.assertEquals(1, meshRuleDispatcher.getListenerMap().get("Type2").size()); + Assertions.assertEquals( + 1, meshRuleDispatcher.getListenerMap().get("Type2").size()); Assertions.assertTrue(meshRuleDispatcher.getListenerMap().get("Type2").contains(listener3)); meshRuleDispatcher.unregister(listener2); Assertions.assertNull(meshRuleDispatcher.getListenerMap().get("Type1")); - Assertions.assertEquals(1, meshRuleDispatcher.getListenerMap().get("Type2").size()); + Assertions.assertEquals( + 1, meshRuleDispatcher.getListenerMap().get("Type2").size()); Assertions.assertTrue(meshRuleDispatcher.getListenerMap().get("Type2").contains(listener3)); meshRuleDispatcher.unregister(listener3); diff --git a/dubbo-plugin/dubbo-plugin-router-script/pom.xml b/dubbo-plugin/dubbo-plugin-router-script/pom.xml index ac9888a5f0..17163c52c8 100644 --- a/dubbo-plugin/dubbo-plugin-router-script/pom.xml +++ b/dubbo-plugin/dubbo-plugin-router-script/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + - dubbo-plugin-router-script - jar + dubbo-plugin-router-script + jar - - - org.apache.dubbo - dubbo-cluster - ${project.version} - - + + + org.apache.dubbo + dubbo-cluster + ${project.version} + + diff --git a/dubbo-plugin/dubbo-plugin-router-script/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileStateRouterFactory.java b/dubbo-plugin/dubbo-plugin-router-script/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileStateRouterFactory.java index 5e037a9a6f..cab3968aa1 100644 --- a/dubbo-plugin/dubbo-plugin-router-script/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileStateRouterFactory.java +++ b/dubbo-plugin/dubbo-plugin-router-script/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileStateRouterFactory.java @@ -46,7 +46,9 @@ public class FileStateRouterFactory implements StateRouterFactory { try { // Transform File URL into Script Route URL, and Load // file:///d:/path/to/route.js?router=script ==> script:///d:/path/to/route.js?type=js&rule= - String protocol = url.getParameter(ROUTER_KEY, ScriptStateRouterFactory.NAME); // Replace original protocol (maybe 'file') with 'script' + String protocol = url.getParameter( + ROUTER_KEY, + ScriptStateRouterFactory.NAME); // Replace original protocol (maybe 'file') with 'script' String type = null; // Use file suffix to config script type, e.g., js, groovy ... String path = url.getPath(); if (path != null) { @@ -71,5 +73,4 @@ public class FileStateRouterFactory implements StateRouterFactory { throw new IllegalStateException(e.getMessage(), e); } } - } diff --git a/dubbo-plugin/dubbo-plugin-router-script/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouter.java b/dubbo-plugin/dubbo-plugin-router-script/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouter.java index d0f918094a..19baa1ab46 100644 --- a/dubbo-plugin/dubbo-plugin-router-script/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouter.java +++ b/dubbo-plugin/dubbo-plugin-router-script/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouter.java @@ -37,6 +37,7 @@ import javax.script.CompiledScript; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; + import java.security.AccessControlContext; import java.security.AccessController; import java.security.CodeSource; @@ -77,12 +78,12 @@ public class ScriptStateRouter extends AbstractStateRouter { private AccessControlContext accessControlContext; { - //Just give permission of reflect to access member. + // Just give permission of reflect to access member. Permissions perms = new Permissions(); perms.add(new RuntimePermission("accessDeclaredMembers")); // Cast to Certificate[] required because of ambiguity: ProtectionDomain domain = new ProtectionDomain(new CodeSource(null, (Certificate[]) null), perms); - accessControlContext = new AccessControlContext(new ProtectionDomain[]{domain}); + accessControlContext = new AccessControlContext(new ProtectionDomain[] {domain}); } public ScriptStateRouter(URL url) { @@ -95,8 +96,13 @@ public class ScriptStateRouter extends AbstractStateRouter { Compilable compilable = (Compilable) engine; function = compilable.compile(rule); } catch (ScriptException e) { - logger.error(CLUSTER_SCRIPT_EXCEPTION, "script route rule invalid", "", "script route error, rule has been ignored. rule: " + rule + - ", url: " + RpcContext.getServiceContext().getUrl(), e); + logger.error( + CLUSTER_SCRIPT_EXCEPTION, + "script route rule invalid", + "", + "script route error, rule has been ignored. rule: " + rule + ", url: " + + RpcContext.getServiceContext().getUrl(), + e); } } @@ -127,7 +133,14 @@ public class ScriptStateRouter extends AbstractStateRouter { } @Override - protected BitList> doRoute(BitList> invokers, URL url, Invocation invocation, boolean needToPrintMessage, Holder> nodeHolder, Holder messageHolder) throws RpcException { + protected BitList> doRoute( + BitList> invokers, + URL url, + Invocation invocation, + boolean needToPrintMessage, + Holder> nodeHolder, + Holder messageHolder) + throws RpcException { if (engine == null || function == null) { if (needToPrintMessage) { messageHolder.set("Directly Return. Reason: engine or function is null"); @@ -135,15 +148,25 @@ public class ScriptStateRouter extends AbstractStateRouter { return invokers; } Bindings bindings = createBindings(invokers, invocation); - return getRoutedInvokers(invokers, AccessController.doPrivileged((PrivilegedAction) () -> { - try { - return function.eval(bindings); - } catch (ScriptException e) { - logger.error(CLUSTER_SCRIPT_EXCEPTION, "Scriptrouter exec script error", "", "Script route error, rule has been ignored. rule: " + rule + ", method:" + - RpcUtils.getMethodName(invocation) + ", url: " + RpcContext.getContext().getUrl(), e); - return invokers; - } - }, accessControlContext)); + return getRoutedInvokers( + invokers, + AccessController.doPrivileged( + (PrivilegedAction) () -> { + try { + return function.eval(bindings); + } catch (ScriptException e) { + logger.error( + CLUSTER_SCRIPT_EXCEPTION, + "Scriptrouter exec script error", + "", + "Script route error, rule has been ignored. rule: " + rule + ", method:" + + RpcUtils.getMethodName(invocation) + ", url: " + + RpcContext.getContext().getUrl(), + e); + return invokers; + } + }, + accessControlContext)); } /** @@ -155,7 +178,8 @@ public class ScriptStateRouter extends AbstractStateRouter { if (obj instanceof Invoker[]) { result.retainAll(Arrays.asList((Invoker[]) obj)); } else if (obj instanceof Object[]) { - result.retainAll(Arrays.stream((Object[]) obj).map(item -> (Invoker) item).collect(Collectors.toList())); + result.retainAll( + Arrays.stream((Object[]) obj).map(item -> (Invoker) item).collect(Collectors.toList())); } else { result.retainAll((List>) obj); } @@ -183,5 +207,4 @@ public class ScriptStateRouter extends AbstractStateRouter { public boolean isForce() { return this.getUrl().getParameter(FORCE_KEY, false); } - } diff --git a/dubbo-plugin/dubbo-plugin-router-script/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterFactory.java b/dubbo-plugin/dubbo-plugin-router-script/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterFactory.java index 43bcd3067f..1849dcb4c8 100644 --- a/dubbo-plugin/dubbo-plugin-router-script/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterFactory.java +++ b/dubbo-plugin/dubbo-plugin-router-script/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterFactory.java @@ -41,5 +41,4 @@ public class ScriptStateRouterFactory implements StateRouterFactory { public StateRouter getRouter(Class interfaceClass, URL url) { return new ScriptStateRouter<>(url); } - } diff --git a/dubbo-plugin/dubbo-plugin-router-script/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptStateRouter.java b/dubbo-plugin/dubbo-plugin-router-script/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptStateRouter.java index 8b158e31fd..e872a7ea3f 100644 --- a/dubbo-plugin/dubbo-plugin-router-script/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptStateRouter.java +++ b/dubbo-plugin/dubbo-plugin-router-script/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptStateRouter.java @@ -45,7 +45,8 @@ import static org.apache.dubbo.rpc.cluster.Constants.RUNTIME_KEY; import static org.apache.dubbo.rpc.cluster.Constants.TYPE_KEY; public class AppScriptStateRouter extends AbstractStateRouter implements ConfigurationListener { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AppScriptStateRouter.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(AppScriptStateRouter.class); private static final String RULE_SUFFIX = ".script-router"; private ScriptRule scriptRule; @@ -57,15 +58,19 @@ public class AppScriptStateRouter extends AbstractStateRouter implements C } @Override - protected BitList> doRoute(BitList> invokers, - URL url, - Invocation invocation, - boolean needToPrintMessage, - Holder> routerSnapshotNodeHolder, - Holder messageHolder) throws RpcException { + protected BitList> doRoute( + BitList> invokers, + URL url, + Invocation invocation, + boolean needToPrintMessage, + Holder> routerSnapshotNodeHolder, + Holder messageHolder) + throws RpcException { if (scriptRouter == null || !scriptRule.isValid() || !scriptRule.isEnabled()) { if (needToPrintMessage) { - messageHolder.set("Directly return from script router. Reason: Invokers from previous router is empty or script is not enabled. Script rule is: " + (scriptRule == null ? "null" : scriptRule.getRawRule())); + messageHolder.set( + "Directly return from script router. Reason: Invokers from previous router is empty or script is not enabled. Script rule is: " + + (scriptRule == null ? "null" : scriptRule.getRawRule())); } return invokers; } @@ -82,8 +87,8 @@ public class AppScriptStateRouter extends AbstractStateRouter implements C @Override public synchronized void process(ConfigChangedEvent event) { if (logger.isDebugEnabled()) { - logger.debug("Notification of script rule change, type is: " + event.getChangeType() + ", raw rule is:\n " + - event.getContent()); + logger.debug("Notification of script rule change, type is: " + event.getChangeType() + ", raw rule is:\n " + + event.getContent()); } try { @@ -91,16 +96,22 @@ public class AppScriptStateRouter extends AbstractStateRouter implements C this.scriptRule = null; } else { this.scriptRule = ScriptRule.parse(event.getContent()); - URL scriptUrl = getUrl() - .addParameter(TYPE_KEY, isEmpty(scriptRule.getType()) ? DEFAULT_SCRIPT_TYPE_KEY : scriptRule.getType()) - .addParameterAndEncoded(RULE_KEY, scriptRule.getScript()) - .addParameter(FORCE_KEY, scriptRule.isForce()) - .addParameter(RUNTIME_KEY, scriptRule.isRuntime()); + URL scriptUrl = getUrl().addParameter( + TYPE_KEY, + isEmpty(scriptRule.getType()) ? DEFAULT_SCRIPT_TYPE_KEY : scriptRule.getType()) + .addParameterAndEncoded(RULE_KEY, scriptRule.getScript()) + .addParameter(FORCE_KEY, scriptRule.isForce()) + .addParameter(RUNTIME_KEY, scriptRule.isRuntime()); scriptRouter = new ScriptStateRouter<>(scriptUrl); } } catch (Exception e) { - logger.error(CLUSTER_TAG_ROUTE_INVALID, "Failed to parse the raw tag router rule", "", "Failed to parse the raw tag router rule and it will not take effect, please check if the " + - "rule matches with the template, the raw rule is:\n ", e); + logger.error( + CLUSTER_TAG_ROUTE_INVALID, + "Failed to parse the raw tag router rule", + "", + "Failed to parse the raw tag router rule and it will not take effect, please check if the " + + "rule matches with the template, the raw rule is:\n ", + e); } } @@ -115,8 +126,12 @@ public class AppScriptStateRouter extends AbstractStateRouter implements C String providerApplication = url.getRemoteApplication(); if (isEmpty(providerApplication)) { - logger.error(CLUSTER_TAG_ROUTE_EMPTY, "tag router get providerApplication is empty", "", "TagRouter must getConfig from or subscribe to a specific application, but the application " + - "in this TagRouter is not specified."); + logger.error( + CLUSTER_TAG_ROUTE_EMPTY, + "tag router get providerApplication is empty", + "", + "TagRouter must getConfig from or subscribe to a specific application, but the application " + + "in this TagRouter is not specified."); return; } diff --git a/dubbo-plugin/dubbo-plugin-router-script/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/model/ScriptRule.java b/dubbo-plugin/dubbo-plugin-router-script/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/model/ScriptRule.java index 1ee885e456..b181d140b4 100644 --- a/dubbo-plugin/dubbo-plugin-router-script/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/model/ScriptRule.java +++ b/dubbo-plugin/dubbo-plugin-router-script/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/model/ScriptRule.java @@ -18,12 +18,12 @@ package org.apache.dubbo.rpc.cluster.router.script.config.model; import org.apache.dubbo.rpc.cluster.router.AbstractRouterRule; +import java.util.Map; + import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.SafeConstructor; -import java.util.Map; - public class ScriptRule extends AbstractRouterRule { private static final String TYPE_KEY = "type"; private static final String SCRIPT_KEY = "script"; diff --git a/dubbo-plugin/dubbo-plugin-router-script/src/test/java/org/apache/dubbo/rpc/cluster/router/MockInvoker.java b/dubbo-plugin/dubbo-plugin-router-script/src/test/java/org/apache/dubbo/rpc/cluster/router/MockInvoker.java index 11a87dcf09..7de1783028 100644 --- a/dubbo-plugin/dubbo-plugin-router-script/src/test/java/org/apache/dubbo/rpc/cluster/router/MockInvoker.java +++ b/dubbo-plugin/dubbo-plugin-router-script/src/test/java/org/apache/dubbo/rpc/cluster/router/MockInvoker.java @@ -26,8 +26,7 @@ public class MockInvoker implements Invoker { private boolean available = false; private URL url; - public MockInvoker() { - } + public MockInvoker() {} public MockInvoker(URL url) { super(); @@ -64,6 +63,5 @@ public class MockInvoker implements Invoker { } @Override - public void destroy() { - } + public void destroy() {} } diff --git a/dubbo-plugin/dubbo-plugin-router-script/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java b/dubbo-plugin/dubbo-plugin-router-script/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java index b025e8f8e9..e2aff97136 100644 --- a/dubbo-plugin/dubbo-plugin-router-script/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java +++ b/dubbo-plugin/dubbo-plugin-router-script/src/test/java/org/apache/dubbo/rpc/cluster/router/file/FileRouterEngineTest.java @@ -33,16 +33,17 @@ import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory; import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker; import org.apache.dubbo.rpc.model.ApplicationModel; +import javax.script.ScriptEngineManager; + +import java.util.ArrayList; +import java.util.List; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.script.ScriptEngineManager; -import java.util.ArrayList; -import java.util.List; - import static org.apache.dubbo.common.constants.CommonConstants.ENABLE_CONNECTIVITY_VALIDATION; import static org.apache.dubbo.rpc.cluster.Constants.RUNTIME_KEY; import static org.mockito.BDDMockito.given; @@ -57,7 +58,8 @@ class FileRouterEngineTest { Invocation invocation; StaticDirectory dic; Result result = new AppResponse(); - private StateRouterFactory routerFactory = ExtensionLoader.getExtensionLoader(StateRouterFactory.class).getAdaptiveExtension(); + private StateRouterFactory routerFactory = + ExtensionLoader.getExtensionLoader(StateRouterFactory.class).getAdaptiveExtension(); @BeforeAll public static void setUpBeforeClass() throws Exception { @@ -85,8 +87,7 @@ class FileRouterEngineTest { initInvokers(url, true, false); initDic(url); - MockClusterInvoker sinvoker = new MockClusterInvoker( - dic, url); + MockClusterInvoker sinvoker = new MockClusterInvoker(dic, url); for (int i = 0; i < 100; i++) { sinvoker.invoke(invocation); Invoker invoker = sinvoker.getSelectedInvoker(); @@ -102,8 +103,7 @@ class FileRouterEngineTest { initInvokers(url); initDic(url); - MockClusterInvoker sinvoker = new MockClusterInvoker( - dic, url); + MockClusterInvoker sinvoker = new MockClusterInvoker(dic, url); for (int i = 0; i < 100; i++) { sinvoker.invoke(invocation); Invoker invoker = sinvoker.getSelectedInvoker(); @@ -120,8 +120,7 @@ class FileRouterEngineTest { initInvokers(url, true, true); initDic(url); - MockClusterInvoker sinvoker = new MockClusterInvoker( - dic, url); + MockClusterInvoker sinvoker = new MockClusterInvoker(dic, url); for (int i = 0; i < 100; i++) { sinvoker.invoke(invocation); Invoker invoker = sinvoker.getSelectedInvoker(); @@ -132,8 +131,7 @@ class FileRouterEngineTest { initInvocation("method2"); initInvokers(url, true, true); initDic(url); - MockClusterInvoker sinvoker = new MockClusterInvoker( - dic, url); + MockClusterInvoker sinvoker = new MockClusterInvoker(dic, url); for (int i = 0; i < 100; i++) { sinvoker.invoke(invocation); Invoker invoker = sinvoker.getSelectedInvoker(); @@ -143,7 +141,10 @@ class FileRouterEngineTest { } private URL initUrl(String filename) { - filename = getClass().getClassLoader().getResource(getClass().getPackage().getName().replace('.', '/') + "/" + filename).toString(); + filename = getClass() + .getClassLoader() + .getResource(getClass().getPackage().getName().replace('.', '/') + "/" + filename) + .toString(); URL url = URL.valueOf(filename); url = url.addParameter(RUNTIME_KEY, true); return url; @@ -172,10 +173,13 @@ class FileRouterEngineTest { private void initDic(URL url) { // FIXME: this exposes the design flaw in RouterChain - URL dicInitUrl = URL.valueOf("consumer://localhost:20880/org.apache.dubbo.rpc.cluster.router.file.FileRouterEngineTest?application=FileRouterEngineTest"); + URL dicInitUrl = URL.valueOf( + "consumer://localhost:20880/org.apache.dubbo.rpc.cluster.router.file.FileRouterEngineTest?application=FileRouterEngineTest"); dic = new StaticDirectory<>(dicInitUrl, invokers); dic.buildRouterChain(); - dic.getRouterChain().getCurrentChain().setHeadStateRouter(routerFactory.getRouter(FileRouterEngineTest.class, url)); + dic.getRouterChain() + .getCurrentChain() + .setHeadStateRouter(routerFactory.getRouter(FileRouterEngineTest.class, url)); } static class MockClusterInvoker extends AbstractClusterInvoker { @@ -190,8 +194,8 @@ class FileRouterEngineTest { } @Override - protected Result doInvoke(Invocation invocation, List> invokers, - LoadBalance loadbalance) throws RpcException { + protected Result doInvoke(Invocation invocation, List> invokers, LoadBalance loadbalance) + throws RpcException { Invoker invoker = select(loadbalance, invocation, invokers, null); selectedInvoker = invoker; return null; diff --git a/dubbo-plugin/dubbo-plugin-router-script/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterTest.java b/dubbo-plugin/dubbo-plugin-router-script/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterTest.java index 2254ec51cc..51982cec4a 100644 --- a/dubbo-plugin/dubbo-plugin-router-script/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterTest.java +++ b/dubbo-plugin/dubbo-plugin-router-script/src/test/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.router.script; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.Holder; import org.apache.dubbo.rpc.Invoker; @@ -25,6 +24,9 @@ import org.apache.dubbo.rpc.cluster.router.MockInvoker; import org.apache.dubbo.rpc.cluster.router.state.BitList; import org.apache.dubbo.rpc.cluster.router.state.StateRouter; +import java.util.ArrayList; +import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; @@ -32,9 +34,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.DisabledForJreRange; import org.junit.jupiter.api.condition.JRE; -import java.util.ArrayList; -import java.util.List; - import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY; @DisabledForJreRange(min = JRE.JAVA_16) @@ -43,12 +42,10 @@ class ScriptStateRouterTest { private URL SCRIPT_URL = URL.valueOf("script://javascript?type=javascript"); @BeforeAll - public static void setUpBeforeClass() throws Exception { - } + public static void setUpBeforeClass() throws Exception {} @BeforeEach - public void setUp() throws Exception { - } + public void setUp() throws Exception {} private URL getRouteUrl(String rule) { return SCRIPT_URL.addParameterAndEncoded(RULE_KEY, rule); @@ -56,26 +53,27 @@ class ScriptStateRouterTest { @Test void testRouteReturnAll() { - StateRouter router = new ScriptStateRouterFactory().getRouter(String.class, getRouteUrl("function route(op1,op2){return op1} route(invokers)")); + StateRouter router = new ScriptStateRouterFactory() + .getRouter(String.class, getRouteUrl("function route(op1,op2){return op1} route(invokers)")); List> originInvokers = new ArrayList>(); originInvokers.add(new MockInvoker()); originInvokers.add(new MockInvoker()); originInvokers.add(new MockInvoker()); BitList> invokers = new BitList<>(originInvokers); - List> filteredInvokers = router.route(invokers.clone(), invokers.get(0).getUrl(), new RpcInvocation(), false, new Holder<>()); + List> filteredInvokers = + router.route(invokers.clone(), invokers.get(0).getUrl(), new RpcInvocation(), false, new Holder<>()); Assertions.assertEquals(invokers, filteredInvokers); } @Test void testRoutePickInvokers() { - String rule = "var result = new java.util.ArrayList(invokers.size());" + - "for (i=0;i> invokers = new BitList<>(originInvokers); - List> filteredInvokers = router.route(invokers.clone(), invokers.get(0).getUrl(), new RpcInvocation(), false, new Holder<>()); + List> filteredInvokers = + router.route(invokers.clone(), invokers.get(0).getUrl(), new RpcInvocation(), false, new Holder<>()); Assertions.assertEquals(2, filteredInvokers.size()); Assertions.assertEquals(invoker2, filteredInvokers.get(0)); Assertions.assertEquals(invoker3, filteredInvokers.get(1)); @@ -97,29 +96,33 @@ class ScriptStateRouterTest { @Test void testRouteHostFilter() { List> originInvokers = new ArrayList>(); - MockInvoker invoker1 = new MockInvoker(URL.valueOf("dubbo://10.134.108.1:20880/com.dubbo.HelloService")); - MockInvoker invoker2 = new MockInvoker(URL.valueOf("dubbo://10.134.108.2:20880/com.dubbo.HelloService")); - MockInvoker invoker3 = new MockInvoker(URL.valueOf("dubbo://10.134.108.3:20880/com.dubbo.HelloService")); + MockInvoker invoker1 = + new MockInvoker(URL.valueOf("dubbo://10.134.108.1:20880/com.dubbo.HelloService")); + MockInvoker invoker2 = + new MockInvoker(URL.valueOf("dubbo://10.134.108.2:20880/com.dubbo.HelloService")); + MockInvoker invoker3 = + new MockInvoker(URL.valueOf("dubbo://10.134.108.3:20880/com.dubbo.HelloService")); originInvokers.add(invoker1); originInvokers.add(invoker2); originInvokers.add(invoker3); BitList> invokers = new BitList<>(originInvokers); - String script = "function route(invokers, invocation, context){ " + - " var result = new java.util.ArrayList(invokers.size()); " + - " var targetHost = new java.util.ArrayList(); " + - " targetHost.add(\"10.134.108.2\"); " + - " for (var i = 0; i < invokers.length; i++) { " + - " if(targetHost.contains(invokers[i].getUrl().getHost())){ " + - " result.add(invokers[i]); " + - " } " + - " } " + - " return result; " + - "} " + - "route(invokers, invocation, context) "; + String script = "function route(invokers, invocation, context){ " + + " var result = new java.util.ArrayList(invokers.size()); " + + " var targetHost = new java.util.ArrayList(); " + + " targetHost.add(\"10.134.108.2\"); " + + " for (var i = 0; i < invokers.length; i++) { " + + " if(targetHost.contains(invokers[i].getUrl().getHost())){ " + + " result.add(invokers[i]); " + + " } " + + " } " + + " return result; " + + "} " + + "route(invokers, invocation, context) "; StateRouter router = new ScriptStateRouterFactory().getRouter(String.class, getRouteUrl(script)); - List> routeResult = router.route(invokers.clone(), invokers.get(0).getUrl(), new RpcInvocation(), false, new Holder<>()); + List> routeResult = + router.route(invokers.clone(), invokers.get(0).getUrl(), new RpcInvocation(), false, new Holder<>()); Assertions.assertEquals(1, routeResult.size()); Assertions.assertEquals(invoker2, routeResult.get(0)); } @@ -127,9 +130,12 @@ class ScriptStateRouterTest { @Test void testRoute_throwException() { List> originInvokers = new ArrayList>(); - MockInvoker invoker1 = new MockInvoker(URL.valueOf("dubbo://10.134.108.1:20880/com.dubbo.HelloService")); - MockInvoker invoker2 = new MockInvoker(URL.valueOf("dubbo://10.134.108.2:20880/com.dubbo.HelloService")); - MockInvoker invoker3 = new MockInvoker(URL.valueOf("dubbo://10.134.108.3:20880/com.dubbo.HelloService")); + MockInvoker invoker1 = + new MockInvoker(URL.valueOf("dubbo://10.134.108.1:20880/com.dubbo.HelloService")); + MockInvoker invoker2 = + new MockInvoker(URL.valueOf("dubbo://10.134.108.2:20880/com.dubbo.HelloService")); + MockInvoker invoker3 = + new MockInvoker(URL.valueOf("dubbo://10.134.108.3:20880/com.dubbo.HelloService")); originInvokers.add(invoker1); originInvokers.add(invoker2); originInvokers.add(invoker3); @@ -137,7 +143,8 @@ class ScriptStateRouterTest { String script = "/"; StateRouter router = new ScriptStateRouterFactory().getRouter(String.class, getRouteUrl(script)); - List> routeResult = router.route(invokers.clone(), invokers.get(0).getUrl(), new RpcInvocation(), false, new Holder<>()); + List> routeResult = + router.route(invokers.clone(), invokers.get(0).getUrl(), new RpcInvocation(), false, new Holder<>()); Assertions.assertEquals(3, routeResult.size()); } } diff --git a/dubbo-plugin/dubbo-plugin-router-script/src/test/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptStateRouterTest.java b/dubbo-plugin/dubbo-plugin-router-script/src/test/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptStateRouterTest.java index 00e59d5ff8..36aba171ce 100644 --- a/dubbo-plugin/dubbo-plugin-router-script/src/test/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptStateRouterTest.java +++ b/dubbo-plugin/dubbo-plugin-router-script/src/test/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptStateRouterTest.java @@ -25,6 +25,9 @@ import org.apache.dubbo.rpc.cluster.governance.GovernanceRuleRepository; import org.apache.dubbo.rpc.cluster.router.MockInvoker; import org.apache.dubbo.rpc.cluster.router.state.BitList; +import java.util.ArrayList; +import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -32,9 +35,6 @@ import org.junit.jupiter.api.condition.DisabledForJreRange; import org.junit.jupiter.api.condition.JRE; import org.mockito.Mockito; -import java.util.ArrayList; -import java.util.List; - import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY; @DisabledForJreRange(min = JRE.JAVA_16) @@ -44,21 +44,20 @@ public class AppScriptStateRouterTest { private static GovernanceRuleRepository ruleRepository; private URL url = URL.valueOf("dubbo://1.1.1.1/com.foo.BarService"); - private String rawRule = "---\n" + - "configVersion: v3.0\n" + - "key: demo-provider\n" + - "type: javascript\n" + - "script: |\n" + - " (function route(invokers,invocation,context) {\n" + - " var result = new java.util.ArrayList(invokers.size());\n" + - " for (i = 0; i < invokers.size(); i ++) {\n" + - " if (\"10.20.3.3\".equals(invokers.get(i).getUrl().getHost())) {\n" + - " result.add(invokers.get(i));\n" + - " }\n" + - " }\n" + - " return result;\n" + - " } (invokers, invocation, context)); // 表示立即执行方法\n" + - "..."; + private String rawRule = "---\n" + "configVersion: v3.0\n" + + "key: demo-provider\n" + + "type: javascript\n" + + "script: |\n" + + " (function route(invokers,invocation,context) {\n" + + " var result = new java.util.ArrayList(invokers.size());\n" + + " for (i = 0; i < invokers.size(); i ++) {\n" + + " if (\"10.20.3.3\".equals(invokers.get(i).getUrl().getHost())) {\n" + + " result.add(invokers.get(i));\n" + + " }\n" + + " }\n" + + " return result;\n" + + " } (invokers, invocation, context)); // 表示立即执行方法\n" + + "..."; @BeforeAll public static void setUpBeforeClass() throws Exception { @@ -70,8 +69,9 @@ public class AppScriptStateRouterTest { AppScriptStateRouter router = new AppScriptStateRouter<>(url); router = Mockito.spy(router); Mockito.when(router.getRuleRepository()).thenReturn(ruleRepository); - Mockito.when(ruleRepository.getRule("demo-provider" + RULE_SUFFIX, DynamicConfiguration.DEFAULT_GROUP)).thenReturn(rawRule); -// Mockito.when(ruleRepository.addListener()).thenReturn(); + Mockito.when(ruleRepository.getRule("demo-provider" + RULE_SUFFIX, DynamicConfiguration.DEFAULT_GROUP)) + .thenReturn(rawRule); + // Mockito.when(ruleRepository.addListener()).thenReturn(); BitList> invokers = getInvokers(); router.notify(invokers); @@ -84,17 +84,16 @@ public class AppScriptStateRouterTest { private BitList> getInvokers() { List> originInvokers = new ArrayList>(); - Invoker invoker1 = new MockInvoker(URL.valueOf( - "dubbo://10.20.3.3:20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider")); - Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST - + ":20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider")); - Invoker invoker3 = new MockInvoker(URL.valueOf("dubbo://" + LOCAL_HOST - + ":20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider")); + Invoker invoker1 = new MockInvoker( + URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider")); + Invoker invoker2 = new MockInvoker(URL.valueOf( + "dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider")); + Invoker invoker3 = new MockInvoker(URL.valueOf( + "dubbo://" + LOCAL_HOST + ":20880/com.foo.BarService?" + REMOTE_APPLICATION_KEY + "=demo-provider")); originInvokers.add(invoker1); originInvokers.add(invoker2); originInvokers.add(invoker3); BitList> invokers = new BitList<>(originInvokers); return invokers; } - } diff --git a/dubbo-plugin/dubbo-plugin-router-tag/pom.xml b/dubbo-plugin/dubbo-plugin-router-tag/pom.xml index a1fcf282ab..513e771086 100644 --- a/dubbo-plugin/dubbo-plugin-router-tag/pom.xml +++ b/dubbo-plugin/dubbo-plugin-router-tag/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + - dubbo-plugin-router-tag - jar + dubbo-plugin-router-tag + jar - - - org.apache.dubbo - dubbo-cluster - ${project.version} - - + + + org.apache.dubbo + dubbo-cluster + ${project.version} + + diff --git a/dubbo-plugin/dubbo-plugin-router-tag/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouter.java b/dubbo-plugin/dubbo-plugin-router-tag/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouter.java index f6e7d9dc33..cacb941b16 100644 --- a/dubbo-plugin/dubbo-plugin-router-tag/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouter.java +++ b/dubbo-plugin/dubbo-plugin-router-tag/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouter.java @@ -66,8 +66,8 @@ public class TagStateRouter extends AbstractStateRouter implements Configu @Override public synchronized void process(ConfigChangedEvent event) { if (logger.isInfoEnabled()) { - logger.info("Notification of tag rule, change type is: " + event.getChangeType() + ", raw rule is:\n " + - event.getContent()); + logger.info("Notification of tag rule, change type is: " + event.getChangeType() + ", raw rule is:\n " + + event.getContent()); } try { @@ -79,13 +79,25 @@ public class TagStateRouter extends AbstractStateRouter implements Configu this.tagRouterRule = rule; } } catch (Exception e) { - logger.error(CLUSTER_TAG_ROUTE_INVALID,"Failed to parse the raw tag router rule","","Failed to parse the raw tag router rule and it will not take effect, please check if the " + - "rule matches with the template, the raw rule is:\n ",e); + logger.error( + CLUSTER_TAG_ROUTE_INVALID, + "Failed to parse the raw tag router rule", + "", + "Failed to parse the raw tag router rule and it will not take effect, please check if the " + + "rule matches with the template, the raw rule is:\n ", + e); } } @Override - public BitList> doRoute(BitList> invokers, URL url, Invocation invocation, boolean needToPrintMessage, Holder> nodeHolder, Holder messageHolder) throws RpcException { + public BitList> doRoute( + BitList> invokers, + URL url, + Invocation invocation, + boolean needToPrintMessage, + Holder> nodeHolder, + Holder messageHolder) + throws RpcException { if (CollectionUtils.isEmpty(invokers)) { if (needToPrintMessage) { messageHolder.set("Directly Return. Reason: Invokers from previous router is empty."); @@ -103,8 +115,9 @@ public class TagStateRouter extends AbstractStateRouter implements Configu } BitList> result = invokers; - String tag = StringUtils.isEmpty(invocation.getAttachment(TAG_KEY)) ? url.getParameter(TAG_KEY) : - invocation.getAttachment(TAG_KEY); + String tag = StringUtils.isEmpty(invocation.getAttachment(TAG_KEY)) + ? url.getParameter(TAG_KEY) + : invocation.getAttachment(TAG_KEY); // if we are requesting for a Provider with a specific tag if (StringUtils.isNotEmpty(tag)) { @@ -116,33 +129,35 @@ public class TagStateRouter extends AbstractStateRouter implements Configu // if result is not null OR it's null but force=true, return result directly if (CollectionUtils.isNotEmpty(result) || tagRouterRuleCopy.isForce()) { if (needToPrintMessage) { - messageHolder.set("Use tag " + tag + " to route. Reason: result is not null OR it's null but force=true"); + messageHolder.set( + "Use tag " + tag + " to route. Reason: result is not null OR it's null but force=true"); } return result; } } else { // dynamic tag group doesn't have any item about the requested app OR it's null after filtered by // dynamic tag group but force=false. check static tag - result = filterInvoker(invokers, invoker -> tag.equals(invoker.getUrl().getParameter(TAG_KEY))); + result = filterInvoker( + invokers, invoker -> tag.equals(invoker.getUrl().getParameter(TAG_KEY))); } // If there's no tagged providers that can match the current tagged request. force.tag is set by default // to false, which means it will invoke any providers without a tag unless it's explicitly disallowed. if (CollectionUtils.isNotEmpty(result) || isForceUseTag(invocation)) { if (needToPrintMessage) { - messageHolder.set("Use tag " + tag + " to route. Reason: result is not empty or ForceUseTag key is true in invocation"); + messageHolder.set("Use tag " + tag + + " to route. Reason: result is not empty or ForceUseTag key is true in invocation"); } return result; } // FAILOVER: return all Providers without any tags. else { BitList> tmp = filterInvoker( - invokers, - invoker -> addressNotMatches(invoker.getUrl(), tagRouterRuleCopy.getAddresses()) - ); + invokers, invoker -> addressNotMatches(invoker.getUrl(), tagRouterRuleCopy.getAddresses())); if (needToPrintMessage) { messageHolder.set("FAILOVER: return all Providers without any tags"); } - return filterInvoker(tmp, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(TAG_KEY))); + return filterInvoker( + tmp, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(TAG_KEY))); } } else { // List addresses = tagRouterRule.filter(providerApp); @@ -187,16 +202,21 @@ public class TagStateRouter extends AbstractStateRouter implements Configu private BitList> filterUsingStaticTag(BitList> invokers, URL url, Invocation invocation) { BitList> result; // Dynamic param - String tag = StringUtils.isEmpty(invocation.getAttachment(TAG_KEY)) ? url.getParameter(TAG_KEY) : - invocation.getAttachment(TAG_KEY); + String tag = StringUtils.isEmpty(invocation.getAttachment(TAG_KEY)) + ? url.getParameter(TAG_KEY) + : invocation.getAttachment(TAG_KEY); // Tag request if (!StringUtils.isEmpty(tag)) { - result = filterInvoker(invokers, invoker -> tag.equals(invoker.getUrl().getParameter(TAG_KEY))); + result = filterInvoker( + invokers, invoker -> tag.equals(invoker.getUrl().getParameter(TAG_KEY))); if (CollectionUtils.isEmpty(result) && !isForceUseTag(invocation)) { - result = filterInvoker(invokers, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(TAG_KEY))); + result = filterInvoker( + invokers, + invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(TAG_KEY))); } } else { - result = filterInvoker(invokers, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(TAG_KEY))); + result = filterInvoker( + invokers, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(TAG_KEY))); } return result; } @@ -213,7 +233,8 @@ public class TagStateRouter extends AbstractStateRouter implements Configu } private boolean isForceUseTag(Invocation invocation) { - return Boolean.parseBoolean(invocation.getAttachment(FORCE_USE_TAG, this.getUrl().getParameter(FORCE_USE_TAG, "false"))); + return Boolean.parseBoolean( + invocation.getAttachment(FORCE_USE_TAG, this.getUrl().getParameter(FORCE_USE_TAG, "false"))); } private BitList> filterInvoker(BitList> invokers, Predicate> predicate) { @@ -245,7 +266,12 @@ public class TagStateRouter extends AbstractStateRouter implements Configu return true; } } catch (Exception e) { - logger.error(CLUSTER_TAG_ROUTE_INVALID, "tag route address is invalid", "", "The format of ip address is invalid in tag route. Address :" + address, e); + logger.error( + CLUSTER_TAG_ROUTE_INVALID, + "tag route address is invalid", + "", + "The format of ip address is invalid in tag route. Address :" + address, + e); } } return false; @@ -267,8 +293,12 @@ public class TagStateRouter extends AbstractStateRouter implements Configu String providerApplication = url.getRemoteApplication(); if (StringUtils.isEmpty(providerApplication)) { - logger.error(CLUSTER_TAG_ROUTE_EMPTY,"tag router get providerApplication is empty","","TagRouter must getConfig from or subscribe to a specific application, but the application " + - "in this TagRouter is not specified."); + logger.error( + CLUSTER_TAG_ROUTE_EMPTY, + "tag router get providerApplication is empty", + "", + "TagRouter must getConfig from or subscribe to a specific application, but the application " + + "in this TagRouter is not specified."); return; } @@ -324,7 +354,8 @@ public class TagStateRouter extends AbstractStateRouter implements Configu * @param tagSelector eg: beta|team1|partner1 * @return */ - public static Set selectAddressByTagLevel(Map> tagAddresses, String tagSelector, boolean isForce) { + public static Set selectAddressByTagLevel( + Map> tagAddresses, String tagSelector, boolean isForce) { if (isForce || StringUtils.isNotContains(tagSelector, TAG_SEPERATOR)) { return tagAddresses.get(tagSelector); } @@ -338,5 +369,4 @@ public class TagStateRouter extends AbstractStateRouter implements Configu } return null; } - } diff --git a/dubbo-plugin/dubbo-plugin-router-tag/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/Tag.java b/dubbo-plugin/dubbo-plugin-router-tag/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/Tag.java index 13c94d7911..3af1dea3fb 100644 --- a/dubbo-plugin/dubbo-plugin-router-tag/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/Tag.java +++ b/dubbo-plugin/dubbo-plugin-router-tag/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/Tag.java @@ -41,22 +41,35 @@ public class Tag { if (version != null && version.startsWith(RULE_VERSION_V30)) { if (map.get("match") != null) { - tag.setMatch(((List>) map.get("match")).stream().map((objectMap) -> { - try { - return PojoUtils.mapToPojo(objectMap, ParamMatch.class); - } catch (ReflectiveOperationException e) { - logger.error(CLUSTER_FAILED_RULE_PARSING, " Failed to parse tag rule ", String.valueOf(objectMap), "Error occurred when parsing rule component.", e); - } - return null; - }).collect(Collectors.toList())); + tag.setMatch(((List>) map.get("match")) + .stream() + .map((objectMap) -> { + try { + return PojoUtils.mapToPojo(objectMap, ParamMatch.class); + } catch (ReflectiveOperationException e) { + logger.error( + CLUSTER_FAILED_RULE_PARSING, + " Failed to parse tag rule ", + String.valueOf(objectMap), + "Error occurred when parsing rule component.", + e); + } + return null; + }) + .collect(Collectors.toList())); } else { - logger.warn(CLUSTER_FAILED_RULE_PARSING, "", String.valueOf(map), "It's recommended to use 'match' instead of 'addresses' for v3.0 tag rule."); + logger.warn( + CLUSTER_FAILED_RULE_PARSING, + "", + String.valueOf(map), + "It's recommended to use 'match' instead of 'addresses' for v3.0 tag rule."); } } Object addresses = map.get("addresses"); if (addresses != null && List.class.isAssignableFrom(addresses.getClass())) { - tag.setAddresses(((List) addresses).stream().map(String::valueOf).collect(Collectors.toList())); + tag.setAddresses( + ((List) addresses).stream().map(String::valueOf).collect(Collectors.toList())); } return tag; @@ -85,5 +98,4 @@ public class Tag { public void setMatch(List match) { this.match = match; } - } diff --git a/dubbo-plugin/dubbo-plugin-router-tag/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRouterRule.java b/dubbo-plugin/dubbo-plugin-router-tag/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRouterRule.java index f938a7e800..5060d3c6bb 100644 --- a/dubbo-plugin/dubbo-plugin-router-tag/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRouterRule.java +++ b/dubbo-plugin/dubbo-plugin-router-tag/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRouterRule.java @@ -60,8 +60,10 @@ public class TagRouterRule extends AbstractRouterRule { Object tags = map.get(TAGS_KEY); if (tags != null && List.class.isAssignableFrom(tags.getClass())) { - tagRouterRule.setTags(((List>) tags).stream() - .map(objMap -> Tag.parseFromMap(objMap, tagRouterRule.getVersion())).collect(Collectors.toList())); + tagRouterRule.setTags(((List>) tags) + .stream() + .map(objMap -> Tag.parseFromMap(objMap, tagRouterRule.getVersion())) + .collect(Collectors.toList())); } return tagRouterRule; @@ -75,45 +77,49 @@ public class TagRouterRule extends AbstractRouterRule { BitList> invokers = router.getInvokers(); // for tags with 'addresses` field set and 'match' field not set - tags.stream().filter(tag -> CollectionUtils.isNotEmpty(tag.getAddresses())).forEach(tag -> { - tagnameToAddresses.put(tag.getName(), new HashSet<>(tag.getAddresses())); - tag.getAddresses().forEach(addr -> { - Set tagNames = addressToTagnames.computeIfAbsent(addr, k -> new HashSet<>()); - tagNames.add(tag.getName()); - }); - }); + tags.stream() + .filter(tag -> CollectionUtils.isNotEmpty(tag.getAddresses())) + .forEach(tag -> { + tagnameToAddresses.put(tag.getName(), new HashSet<>(tag.getAddresses())); + tag.getAddresses().forEach(addr -> { + Set tagNames = addressToTagnames.computeIfAbsent(addr, k -> new HashSet<>()); + tagNames.add(tag.getName()); + }); + }); if (this.getVersion() != null && this.getVersion().startsWith(RULE_VERSION_V30)) { // for tags with 'match` field set and 'addresses' field not set if (CollectionUtils.isNotEmpty(invokers)) { - tags.stream().filter(tag -> CollectionUtils.isEmpty(tag.getAddresses())).forEach(tag -> { - Set addresses = new HashSet<>(); - List paramMatchers = tag.getMatch(); - invokers.forEach(invoker -> { - boolean isMatch = true; - for (ParamMatch matcher : paramMatchers) { - if (!matcher.isMatch(invoker.getUrl().getOriginalParameter(matcher.getKey()))) { - isMatch = false; - break; + tags.stream() + .filter(tag -> CollectionUtils.isEmpty(tag.getAddresses())) + .forEach(tag -> { + Set addresses = new HashSet<>(); + List paramMatchers = tag.getMatch(); + invokers.forEach(invoker -> { + boolean isMatch = true; + for (ParamMatch matcher : paramMatchers) { + if (!matcher.isMatch(invoker.getUrl().getOriginalParameter(matcher.getKey()))) { + isMatch = false; + break; + } + } + if (isMatch) { + addresses.add(invoker.getUrl().getAddress()); + } + }); + if (CollectionUtils.isNotEmpty(addresses)) { // null means tag not set + tagnameToAddresses.put(tag.getName(), addresses); } - } - if (isMatch) { - addresses.add(invoker.getUrl().getAddress()); - } - }); - if (CollectionUtils.isNotEmpty(addresses)) {// null means tag not set - tagnameToAddresses.put(tag.getName(), addresses); - } - }); + }); } } } public Set getAddresses() { return tagnameToAddresses.entrySet().stream() - .filter(entry -> CollectionUtils.isNotEmpty(entry.getValue())) - .flatMap(entry -> entry.getValue().stream()) - .collect(Collectors.toSet()); + .filter(entry -> CollectionUtils.isNotEmpty(entry.getValue())) + .flatMap(entry -> entry.getValue().stream()) + .collect(Collectors.toSet()); } public List getTagNames() { @@ -124,7 +130,6 @@ public class TagRouterRule extends AbstractRouterRule { return addressToTagnames; } - public Map> getTagnameToAddresses() { return tagnameToAddresses; } diff --git a/dubbo-plugin/dubbo-plugin-router-tag/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRuleParser.java b/dubbo-plugin/dubbo-plugin-router-tag/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRuleParser.java index 5c9712acc8..3c78112bcb 100644 --- a/dubbo-plugin/dubbo-plugin-router-tag/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRuleParser.java +++ b/dubbo-plugin/dubbo-plugin-router-tag/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRuleParser.java @@ -18,12 +18,12 @@ package org.apache.dubbo.rpc.cluster.router.tag.model; import org.apache.dubbo.common.utils.CollectionUtils; +import java.util.Map; + import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.SafeConstructor; -import java.util.Map; - /** * Parse raw rule into structured tag rule */ diff --git a/dubbo-plugin/dubbo-plugin-router-tag/src/test/java/org/apache/dubbo/rpc/cluster/router/MockInvoker.java b/dubbo-plugin/dubbo-plugin-router-tag/src/test/java/org/apache/dubbo/rpc/cluster/router/MockInvoker.java index 11a87dcf09..7de1783028 100644 --- a/dubbo-plugin/dubbo-plugin-router-tag/src/test/java/org/apache/dubbo/rpc/cluster/router/MockInvoker.java +++ b/dubbo-plugin/dubbo-plugin-router-tag/src/test/java/org/apache/dubbo/rpc/cluster/router/MockInvoker.java @@ -26,8 +26,7 @@ public class MockInvoker implements Invoker { private boolean available = false; private URL url; - public MockInvoker() { - } + public MockInvoker() {} public MockInvoker(URL url) { super(); @@ -64,6 +63,5 @@ public class MockInvoker implements Invoker { } @Override - public void destroy() { - } + public void destroy() {} } diff --git a/dubbo-plugin/dubbo-plugin-router-tag/src/test/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouterTest.java b/dubbo-plugin/dubbo-plugin-router-tag/src/test/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouterTest.java index 6477c09b6c..79b34c6823 100644 --- a/dubbo-plugin/dubbo-plugin-router-tag/src/test/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouterTest.java +++ b/dubbo-plugin/dubbo-plugin-router-tag/src/test/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouterTest.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.tag; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.common.utils.Holder; @@ -31,18 +29,18 @@ import org.apache.dubbo.rpc.cluster.router.tag.model.TagRuleParser; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; -import com.google.common.collect.Sets; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; +import com.google.common.collect.Sets; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY; import static org.mockito.Mockito.when; @@ -60,7 +58,6 @@ class TagStateRouterTest { ScopeBeanFactory beanFactory = Mockito.spy(originBeanFactory); when(moduleModel.getBeanFactory()).thenReturn(beanFactory); - url = URL.valueOf("test://localhost/DemoInterface").setScopeModel(moduleModel); } @@ -70,7 +67,8 @@ class TagStateRouterTest { List> originInvokers = new ArrayList<>(); - URL url1 = URL.valueOf("test://127.0.0.1:7777/DemoInterface?dubbo.tag=tag2").setScopeModel(moduleModel); + URL url1 = URL.valueOf("test://127.0.0.1:7777/DemoInterface?dubbo.tag=tag2") + .setScopeModel(moduleModel); URL url2 = URL.valueOf("test://127.0.0.1:7778/DemoInterface").setScopeModel(moduleModel); URL url3 = URL.valueOf("test://127.0.0.1:7779/DemoInterface").setScopeModel(moduleModel); Invoker invoker1 = new MockInvoker<>(url1, true); @@ -83,7 +81,8 @@ class TagStateRouterTest { RpcInvocation invocation = new RpcInvocation(); invocation.setAttachment(TAG_KEY, "tag2"); - List> filteredInvokers = router.route(invokers.clone(), invokers.get(0).getUrl(), invocation, false, new Holder<>()); + List> filteredInvokers = + router.route(invokers.clone(), invokers.get(0).getUrl(), invocation, false, new Holder<>()); Assertions.assertEquals(1, filteredInvokers.size()); Assertions.assertEquals(invoker1, filteredInvokers.get(0)); } @@ -95,9 +94,12 @@ class TagStateRouterTest { List> originInvokers = new ArrayList<>(); - URL url1 = URL.valueOf("test://127.0.0.1:7777/DemoInterface?application=foo&dubbo.tag=tag2&match_key=value").setScopeModel(moduleModel); - URL url2 = URL.valueOf("test://127.0.0.1:7778/DemoInterface?application=foo&match_key=value").setScopeModel(moduleModel); - URL url3 = URL.valueOf("test://127.0.0.1:7779/DemoInterface?application=foo").setScopeModel(moduleModel); + URL url1 = URL.valueOf("test://127.0.0.1:7777/DemoInterface?application=foo&dubbo.tag=tag2&match_key=value") + .setScopeModel(moduleModel); + URL url2 = URL.valueOf("test://127.0.0.1:7778/DemoInterface?application=foo&match_key=value") + .setScopeModel(moduleModel); + URL url3 = URL.valueOf("test://127.0.0.1:7779/DemoInterface?application=foo") + .setScopeModel(moduleModel); Invoker invoker1 = new MockInvoker<>(url1, true); Invoker invoker2 = new MockInvoker<>(url2, true); Invoker invoker3 = new MockInvoker<>(url3, true); @@ -112,9 +114,10 @@ class TagStateRouterTest { Mockito.when(router.getInvokers()).thenReturn(invokers); rule.init(router); router.setTagRouterRule(rule); - List> filteredInvokers = router.route(invokers, invokers.get(0).getUrl(), invocation, false, new Holder<>()); + List> filteredInvokers = + router.route(invokers, invokers.get(0).getUrl(), invocation, false, new Holder<>()); Assertions.assertEquals(2, filteredInvokers.size()); -// Assertions.(invoker1, filteredInvokers.get(0)); + // Assertions.(invoker1, filteredInvokers.get(0)); } /** @@ -127,22 +130,21 @@ class TagStateRouterTest { */ @Test void tagRouterRuleParseTest() { - String tagRouterRuleConfig = "---\n" + - "force: false\n" + - "runtime: true\n" + - "enabled: false\n" + - "priority: 1\n" + - "key: demo-provider\n" + - "tags:\n" + - " - name: tag1\n" + - " addresses: null\n" + - " - name: tag2\n" + - " addresses: [\"30.5.120.37:20880\"]\n" + - " - name: tag3\n" + - " addresses: []\n" + - " - name: tag4\n" + - " addresses: ~\n" + - "..."; + String tagRouterRuleConfig = "---\n" + "force: false\n" + + "runtime: true\n" + + "enabled: false\n" + + "priority: 1\n" + + "key: demo-provider\n" + + "tags:\n" + + " - name: tag1\n" + + " addresses: null\n" + + " - name: tag2\n" + + " addresses: [\"30.5.120.37:20880\"]\n" + + " - name: tag3\n" + + " addresses: []\n" + + " - name: tag4\n" + + " addresses: ~\n" + + "..."; TagRouterRule tagRouterRule = TagRuleParser.parse(tagRouterRuleConfig); TagStateRouter router = Mockito.mock(TagStateRouter.class); @@ -165,46 +167,44 @@ class TagStateRouterTest { assert tagRouterRule.getAddresses().size() == 1; } - @Test void tagRouterRuleParseTestV3() { - String tagRouterRuleConfig = "---\n" + - "configVersion: v3.0\n" + - "force: false\n" + - "runtime: true\n" + - "enabled: true\n" + - "priority: 1\n" + - "key: demo-provider\n" + - "tags:\n" + - " - name: tag1\n" + - " match:\n" + - " - key: match_key1\n" + - " value:\n" + - " exact: value1\n" + - " - name: tag2\n" + - " addresses:\n" + - " - \"10.20.3.3:20880\"\n" + - " - \"10.20.3.4:20880\"\n" + - " match:\n" + - " - key: match_key2\n" + - " value:\n" + - " exact: value2\n" + - " - name: tag3\n" + - " match:\n" + - " - key: match_key2\n" + - " value:\n" + - " exact: value2\n" + - " - name: tag4\n" + - " match:\n" + - " - key: not_exist\n" + - " value:\n" + - " exact: not_exist\n" + - " - name: tag5\n" + - " match:\n" + - " - key: match_key2\n" + - " value:\n" + - " wildcard: \"*\"\n" + - "..."; + String tagRouterRuleConfig = "---\n" + "configVersion: v3.0\n" + + "force: false\n" + + "runtime: true\n" + + "enabled: true\n" + + "priority: 1\n" + + "key: demo-provider\n" + + "tags:\n" + + " - name: tag1\n" + + " match:\n" + + " - key: match_key1\n" + + " value:\n" + + " exact: value1\n" + + " - name: tag2\n" + + " addresses:\n" + + " - \"10.20.3.3:20880\"\n" + + " - \"10.20.3.4:20880\"\n" + + " match:\n" + + " - key: match_key2\n" + + " value:\n" + + " exact: value2\n" + + " - name: tag3\n" + + " match:\n" + + " - key: match_key2\n" + + " value:\n" + + " exact: value2\n" + + " - name: tag4\n" + + " match:\n" + + " - key: not_exist\n" + + " value:\n" + + " exact: not_exist\n" + + " - name: tag5\n" + + " match:\n" + + " - key: match_key2\n" + + " value:\n" + + " wildcard: \"*\"\n" + + "..."; TagRouterRule tagRouterRule = TagRuleParser.parse(tagRouterRuleConfig); TagStateRouter router = Mockito.mock(TagStateRouter.class); @@ -226,14 +226,14 @@ class TagStateRouterTest { assert tagRouterRule.getTagnameToAddresses().get("tag3").size() == 1; assert tagRouterRule.getTagnameToAddresses().get("tag5").size() == 1; assert tagRouterRule.getTagnameToAddresses().get("tag4") == null; - } public BitList> getInvokers() { List> originInvokers = new ArrayList>(); - Invoker invoker1 = new MockInvoker(URL.valueOf( - "dubbo://10.20.3.3:20880/com.foo.BarService?match_key1=value1&match_key2=value2")); - Invoker invoker2 = new MockInvoker(URL.valueOf("dubbo://10.20.3.4:20880/com.foo.BarService?match_key1=value1")); + Invoker invoker1 = new MockInvoker( + URL.valueOf("dubbo://10.20.3.3:20880/com.foo.BarService?match_key1=value1&match_key2=value2")); + Invoker invoker2 = + new MockInvoker(URL.valueOf("dubbo://10.20.3.4:20880/com.foo.BarService?match_key1=value1")); originInvokers.add(invoker1); originInvokers.add(invoker2); BitList> invokers = new BitList<>(originInvokers); @@ -241,20 +241,19 @@ class TagStateRouterTest { } private TagRouterRule getTagRule() { - String tagRouterRuleConfig = "---\n" + - "configVersion: v3.0\n" + - "force: false\n" + - "runtime: true\n" + - "enabled: true\n" + - "priority: 1\n" + - "key: demo-provider\n" + - "tags:\n" + - " - name: tag2\n" + - " match:\n" + - " - key: match_key\n" + - " value:\n" + - " exact: value\n" + - "..."; + String tagRouterRuleConfig = "---\n" + "configVersion: v3.0\n" + + "force: false\n" + + "runtime: true\n" + + "enabled: true\n" + + "priority: 1\n" + + "key: demo-provider\n" + + "tags:\n" + + " - name: tag2\n" + + " match:\n" + + " - key: match_key\n" + + " value:\n" + + " exact: value\n" + + "..."; TagRouterRule tagRouterRule = TagRuleParser.parse(tagRouterRuleConfig); return tagRouterRule; @@ -289,8 +288,6 @@ class TagStateRouterTest { Assertions.assertEquals(address1, TagStateRouter.selectAddressByTagLevel(tagAddresses, tagSelector, false)); tagSelector = "beta|team1|partner2"; Assertions.assertEquals(address2, TagStateRouter.selectAddressByTagLevel(tagAddresses, tagSelector, false)); - - } @Test @@ -301,5 +298,4 @@ class TagStateRouterTest { Set selectedAddresses = TagStateRouter.selectAddressByTagLevel(tagAddresses, "beta", true); Assertions.assertEquals(addresses, selectedAddresses); } - } diff --git a/dubbo-plugin/dubbo-plugin-token/pom.xml b/dubbo-plugin/dubbo-plugin-token/pom.xml index 378c26a2c8..b122c2a9e4 100644 --- a/dubbo-plugin/dubbo-plugin-token/pom.xml +++ b/dubbo-plugin/dubbo-plugin-token/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + - dubbo-plugin-token - jar + dubbo-plugin-token + jar - - - org.apache.dubbo - dubbo-cluster - ${project.version} - - - org.apache.dubbo - dubbo-config-api - ${project.version} - - + + + org.apache.dubbo + dubbo-cluster + ${project.version} + + + org.apache.dubbo + dubbo-config-api + ${project.version} + + diff --git a/dubbo-plugin/dubbo-plugin-token/src/main/java/org/apache/dubbo/rpc/filter/TokenFilter.java b/dubbo-plugin/dubbo-plugin-token/src/main/java/org/apache/dubbo/rpc/filter/TokenFilter.java index f00dae649d..219080941f 100644 --- a/dubbo-plugin/dubbo-plugin-token/src/main/java/org/apache/dubbo/rpc/filter/TokenFilter.java +++ b/dubbo-plugin/dubbo-plugin-token/src/main/java/org/apache/dubbo/rpc/filter/TokenFilter.java @@ -39,19 +39,19 @@ import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; public class TokenFilter implements Filter { @Override - public Result invoke(Invoker invoker, Invocation inv) - throws RpcException { + public Result invoke(Invoker invoker, Invocation inv) throws RpcException { String token = invoker.getUrl().getParameter(TOKEN_KEY); if (ConfigUtils.isNotEmpty(token)) { Class serviceType = invoker.getInterface(); String remoteToken = (String) inv.getObjectAttachmentWithoutConvert(TOKEN_KEY); if (!token.equals(remoteToken)) { - throw new RpcException("Invalid token! Forbid invoke remote service " + serviceType + " method " + RpcUtils.getMethodName(inv) + - "() from consumer " + RpcContext.getServiceContext().getRemoteHost() + " to provider " + - RpcContext.getServiceContext().getLocalHost()+ ", consumer incorrect token is " + remoteToken); + throw new RpcException("Invalid token! Forbid invoke remote service " + serviceType + " method " + + RpcUtils.getMethodName(inv) + "() from consumer " + + RpcContext.getServiceContext().getRemoteHost() + " to provider " + + RpcContext.getServiceContext().getLocalHost() + + ", consumer incorrect token is " + remoteToken); } } return invoker.invoke(inv); } - } diff --git a/dubbo-plugin/dubbo-plugin-token/src/main/java/org/apache/dubbo/rpc/filter/TokenHeaderFilter.java b/dubbo-plugin/dubbo-plugin-token/src/main/java/org/apache/dubbo/rpc/filter/TokenHeaderFilter.java index 583e91d4cc..c8d8c6e1da 100644 --- a/dubbo-plugin/dubbo-plugin-token/src/main/java/org/apache/dubbo/rpc/filter/TokenHeaderFilter.java +++ b/dubbo-plugin/dubbo-plugin-token/src/main/java/org/apache/dubbo/rpc/filter/TokenHeaderFilter.java @@ -37,9 +37,13 @@ public class TokenHeaderFilter implements HeaderFilter { Class serviceType = invoker.getInterface(); String remoteToken = (String) invocation.getObjectAttachmentWithoutConvert(TOKEN_KEY); if (!token.equals(remoteToken)) { - throw new RpcException(FORBIDDEN_EXCEPTION, "Forbid invoke remote service " + serviceType + " method " + RpcUtils.getMethodName(invocation) + - "() from consumer " + RpcContext.getServiceContext().getRemoteHost() + " to provider " + - RpcContext.getServiceContext().getLocalHost() + ", consumer incorrect token is " + remoteToken); + throw new RpcException( + FORBIDDEN_EXCEPTION, + "Forbid invoke remote service " + serviceType + " method " + RpcUtils.getMethodName(invocation) + + "() from consumer " + + RpcContext.getServiceContext().getRemoteHost() + " to provider " + + RpcContext.getServiceContext().getLocalHost() + + ", consumer incorrect token is " + remoteToken); } } return invocation; diff --git a/dubbo-plugin/dubbo-plugin-token/src/test/java/org/apache/dubbo/rpc/filter/TokenFilterTest.java b/dubbo-plugin/dubbo-plugin-token/src/test/java/org/apache/dubbo/rpc/filter/TokenFilterTest.java index e9007ea821..a53f4ef01e 100644 --- a/dubbo-plugin/dubbo-plugin-token/src/test/java/org/apache/dubbo/rpc/filter/TokenFilterTest.java +++ b/dubbo-plugin/dubbo-plugin-token/src/test/java/org/apache/dubbo/rpc/filter/TokenFilterTest.java @@ -23,13 +23,13 @@ import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; +import java.util.HashMap; +import java.util.Map; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.HashMap; -import java.util.Map; - import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @@ -89,4 +89,3 @@ class TokenFilterTest { }); } } - diff --git a/dubbo-plugin/dubbo-plugin-tps/pom.xml b/dubbo-plugin/dubbo-plugin-tps/pom.xml index cd8649c22b..d2e92340f8 100644 --- a/dubbo-plugin/dubbo-plugin-tps/pom.xml +++ b/dubbo-plugin/dubbo-plugin-tps/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + - dubbo-plugin-tps - jar + dubbo-plugin-tps + jar - - - org.apache.dubbo - dubbo-cluster - ${project.version} - - - org.apache.dubbo - dubbo-config-api - ${project.version} - - + + + org.apache.dubbo + dubbo-cluster + ${project.version} + + + org.apache.dubbo + dubbo-config-api + ${project.version} + + diff --git a/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java b/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java index 6123b5ba10..2912b5e627 100644 --- a/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java +++ b/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java @@ -67,11 +67,14 @@ public class ActiveLimitFilter implements Filter, Filter.Listener { long elapsed = System.currentTimeMillis() - start; remain = timeout - elapsed; if (remain <= 0) { - throw new RpcException(RpcException.LIMIT_EXCEEDED_EXCEPTION, - "Waiting concurrent invoke timeout in client-side for service: " + - invoker.getInterface().getName() + ", method: " + RpcUtils.getMethodName(invocation) + - ", elapsed: " + elapsed + ", timeout: " + timeout + ". concurrent invokes: " + - rpcStatus.getActive() + ". max concurrent invoke limit: " + max); + throw new RpcException( + RpcException.LIMIT_EXCEEDED_EXCEPTION, + "Waiting concurrent invoke timeout in client-side for service: " + + invoker.getInterface().getName() + + ", method: " + RpcUtils.getMethodName(invocation) + ", elapsed: " + + elapsed + ", timeout: " + timeout + ". concurrent invokes: " + + rpcStatus.getActive() + + ". max concurrent invoke limit: " + max); } } } diff --git a/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java b/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java index e77e512f3e..28df4ed9cf 100644 --- a/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java +++ b/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java @@ -32,7 +32,6 @@ import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE_ASYNC; import static org.apache.dubbo.rpc.Constants.EXECUTES_KEY; - /** * The maximum parallel execution request count per method per service for the provider.If the max configured * executes is set to 10 and if invoke request where it is already 10 then it will throw exception. It @@ -49,10 +48,11 @@ public class ExecuteLimitFilter implements Filter, Filter.Listener { String methodName = RpcUtils.getMethodName(invocation); int max = url.getMethodParameter(methodName, EXECUTES_KEY, 0); if (!RpcStatus.beginCount(url, methodName, max)) { - throw new RpcException(RpcException.LIMIT_EXCEEDED_EXCEPTION, - "Failed to invoke method " + RpcUtils.getMethodName(invocation) + " in provider " + - url + ", cause: The service using threads greater than limited."); + throw new RpcException( + RpcException.LIMIT_EXCEEDED_EXCEPTION, + "Failed to invoke method " + RpcUtils.getMethodName(invocation) + " in provider " + url + + ", cause: The service using threads greater than limited."); } invocation.put(EXECUTE_LIMIT_FILTER_START_TIME, System.currentTimeMillis()); @@ -84,10 +84,11 @@ public class ExecuteLimitFilter implements Filter, Filter.Listener { } private String getRealMethodName(Invoker invoker, Invocation invocation) { - if ((invocation.getMethodName().equals($INVOKE) || invocation.getMethodName().equals($INVOKE_ASYNC)) - && invocation.getArguments() != null - && invocation.getArguments().length == 3 - && !GenericService.class.isAssignableFrom(invoker.getInterface())) { + if ((invocation.getMethodName().equals($INVOKE) + || invocation.getMethodName().equals($INVOKE_ASYNC)) + && invocation.getArguments() != null + && invocation.getArguments().length == 3 + && !GenericService.class.isAssignableFrom(invoker.getInterface())) { return ((String) invocation.getArguments()[0]).trim(); } return invocation.getMethodName(); diff --git a/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/TpsLimitFilter.java b/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/TpsLimitFilter.java index b3eaae5d57..8ec1a8482d 100644 --- a/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/TpsLimitFilter.java +++ b/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/TpsLimitFilter.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.filter; import org.apache.dubbo.common.constants.CommonConstants; @@ -47,12 +46,13 @@ public class TpsLimitFilter implements Filter { public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { if (!tpsLimiter.isAllowable(invoker.getUrl(), invocation)) { - return AsyncRpcResult.newDefaultAsyncResult(new RpcException("Failed to invoke service " + - invoker.getInterface().getName() + "." + RpcUtils.getMethodName(invocation) + " because exceed max service tps.") - , invocation); + return AsyncRpcResult.newDefaultAsyncResult( + new RpcException( + "Failed to invoke service " + invoker.getInterface().getName() + "." + + RpcUtils.getMethodName(invocation) + " because exceed max service tps."), + invocation); } return invoker.invoke(invocation); } - } diff --git a/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiter.java b/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiter.java index 9d638c0278..0410d70c50 100644 --- a/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiter.java +++ b/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiter.java @@ -40,7 +40,8 @@ public class DefaultTPSLimiter implements TPSLimiter { @Override public boolean isAllowable(URL url, Invocation invocation) { int rate = url.getMethodParameter(RpcUtils.getMethodName(invocation), TPS_LIMIT_RATE_KEY, -1); - long interval = url.getMethodParameter(RpcUtils.getMethodName(invocation), TPS_LIMIT_INTERVAL_KEY, DEFAULT_TPS_LIMIT_INTERVAL); + long interval = url.getMethodParameter( + RpcUtils.getMethodName(invocation), TPS_LIMIT_INTERVAL_KEY, DEFAULT_TPS_LIMIT_INTERVAL); String serviceKey = url.getServiceKey(); if (rate > 0) { StatItem statItem = stats.get(serviceKey); @@ -48,7 +49,7 @@ public class DefaultTPSLimiter implements TPSLimiter { stats.putIfAbsent(serviceKey, new StatItem(serviceKey, rate, interval)); statItem = stats.get(serviceKey); } else { - //rate or interval has changed, rebuild + // rate or interval has changed, rebuild if (statItem.getRate() != rate || statItem.getInterval() != interval) { stats.put(serviceKey, new StatItem(serviceKey, rate, interval)); statItem = stats.get(serviceKey); @@ -64,5 +65,4 @@ public class DefaultTPSLimiter implements TPSLimiter { return true; } - } diff --git a/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/tps/StatItem.java b/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/tps/StatItem.java index 144ce497c0..768a0bac49 100644 --- a/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/tps/StatItem.java +++ b/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/tps/StatItem.java @@ -57,12 +57,10 @@ class StatItem { return interval; } - public int getRate() { return rate; } - long getLastResetTime() { return lastResetTime.get(); } @@ -73,10 +71,6 @@ class StatItem { @Override public String toString() { - return "StatItem " + - "[name=" + name + ", " + - "rate = " + rate + ", " + - "interval = " + interval + ']'; + return "StatItem " + "[name=" + name + ", " + "rate = " + rate + ", " + "interval = " + interval + ']'; } - } diff --git a/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/tps/TPSLimiter.java b/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/tps/TPSLimiter.java index f104eb12c3..5a4f706cf0 100644 --- a/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/tps/TPSLimiter.java +++ b/dubbo-plugin/dubbo-plugin-tps/src/main/java/org/apache/dubbo/rpc/filter/tps/TPSLimiter.java @@ -37,5 +37,4 @@ public interface TPSLimiter { * @return true allow the current invocation, otherwise, return false */ boolean isAllowable(URL url, Invocation invocation); - } diff --git a/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/filter/ActiveLimitFilterTest.java b/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/filter/ActiveLimitFilterTest.java index a2c4ddf5a7..ca17f8fce0 100644 --- a/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/filter/ActiveLimitFilterTest.java +++ b/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/filter/ActiveLimitFilterTest.java @@ -27,12 +27,12 @@ import org.apache.dubbo.rpc.support.MockInvocation; import org.apache.dubbo.rpc.support.MyInvoker; import org.apache.dubbo.rpc.support.RuntimeExceptionInvoker; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.fail; @@ -106,7 +106,8 @@ class ActiveLimitFilterTest { AtomicInteger count = new AtomicInteger(0); final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch latchBlocking = new CountDownLatch(totalThread); - URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&actives=" + maxActives + "&timeout=" + timeout); + URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&actives=" + maxActives + + "&timeout=" + timeout); final Invoker invoker = new BlockMyInvoker(url, blockTime); final Invocation invocation = new MockInvocation(); RpcStatus.removeStatus(url); @@ -155,7 +156,8 @@ class ActiveLimitFilterTest { AtomicInteger count = new AtomicInteger(0); final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch latchBlocking = new CountDownLatch(totalThread); - URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&actives=" + maxActives + "&timeout=" + timeout); + URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&actives=" + maxActives + + "&timeout=" + timeout); final Invoker invoker = new BlockMyInvoker(url, blockTime); final Invocation invocation = new MockInvocation(); for (int i = 0; i < totalThread; i++) { @@ -204,7 +206,10 @@ class ActiveLimitFilterTest { int beforeExceptionActiveCount = count.getActive(); activeLimitFilter.invoke(invoker, invocation); int afterExceptionActiveCount = count.getActive(); - assertEquals(beforeExceptionActiveCount, afterExceptionActiveCount, "After exception active count should be same"); + assertEquals( + beforeExceptionActiveCount, + afterExceptionActiveCount, + "After exception active count should be same"); }); } @@ -220,7 +225,10 @@ class ActiveLimitFilterTest { } catch (RuntimeException ex) { activeLimitFilter.onError(ex, invoker, invocation); int afterExceptionActiveCount = count.getActive(); - assertEquals(beforeExceptionActiveCount, afterExceptionActiveCount, "After exception active count should be same"); + assertEquals( + beforeExceptionActiveCount, + afterExceptionActiveCount, + "After exception active count should be same"); } } } diff --git a/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilterTest.java b/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilterTest.java index 2f0f3b5faf..97c7229897 100644 --- a/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilterTest.java +++ b/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilterTest.java @@ -26,13 +26,13 @@ import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.RpcStatus; import org.apache.dubbo.rpc.support.BlockMyInvoker; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicInteger; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicInteger; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; @@ -58,7 +58,8 @@ class ExecuteLimitFilterTest { void testExecuteLimitInvoke() { Invoker invoker = Mockito.mock(Invoker.class); when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result")); - when(invoker.getUrl()).thenReturn(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&executes=10")); + when(invoker.getUrl()) + .thenReturn(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&executes=10")); Invocation invocation = Mockito.mock(Invocation.class); when(invocation.getMethodName()).thenReturn("testExecuteLimitInvoke"); @@ -70,8 +71,7 @@ class ExecuteLimitFilterTest { @Test void testExecuteLimitInvokeWithException() { Invoker invoker = Mockito.mock(Invoker.class); - doThrow(new RpcException()) - .when(invoker).invoke(any(Invocation.class)); + doThrow(new RpcException()).when(invoker).invoke(any(Invocation.class)); URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&executes=10"); when(invoker.getUrl()).thenReturn(url); @@ -85,7 +85,8 @@ class ExecuteLimitFilterTest { Assertions.assertTrue(e instanceof RpcException); executeLimitFilter.onError(e, invoker, invocation); } - Assertions.assertEquals(1, RpcStatus.getStatus(url, invocation.getMethodName()).getFailed()); + Assertions.assertEquals( + 1, RpcStatus.getStatus(url, invocation.getMethodName()).getFailed()); RpcStatus.removeStatus(url, invocation.getMethodName()); } diff --git a/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiterTest.java b/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiterTest.java index bcfdf265de..188631f8dc 100644 --- a/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiterTest.java +++ b/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiterTest.java @@ -20,13 +20,13 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.support.MockInvocation; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.rpc.Constants.TPS_LIMIT_INTERVAL_KEY; import static org.apache.dubbo.rpc.Constants.TPS_LIMIT_RATE_KEY; @@ -115,12 +115,12 @@ class DefaultTPSLimiterTest { CountDownLatch startLatch = new CountDownLatch(1); for (int i = 0; i < threadNum; i++) { taskList.add(new Task(defaultTPSLimiter, url, invocation, startLatch, stopLatch)); - } startLatch.countDown(); stopLatch.await(); - Assertions.assertEquals(taskList.stream().map(Task::getCount).reduce(Integer::sum).get(), 100); + Assertions.assertEquals( + taskList.stream().map(Task::getCount).reduce(Integer::sum).get(), 100); } static class Task implements Runnable { @@ -131,7 +131,12 @@ class DefaultTPSLimiterTest { private final CountDownLatch stopLatch; private int count; - public Task(DefaultTPSLimiter defaultTPSLimiter, URL url, Invocation invocation, CountDownLatch startLatch, CountDownLatch stopLatch) { + public Task( + DefaultTPSLimiter defaultTPSLimiter, + URL url, + Invocation invocation, + CountDownLatch startLatch, + CountDownLatch stopLatch) { this.defaultTPSLimiter = defaultTPSLimiter; this.url = url; this.invocation = invocation; diff --git a/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/filter/tps/StatItemTest.java b/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/filter/tps/StatItemTest.java index c820c3a2ae..79a65bf661 100644 --- a/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/filter/tps/StatItemTest.java +++ b/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/filter/tps/StatItemTest.java @@ -16,14 +16,14 @@ */ package org.apache.dubbo.rpc.filter.tps; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -70,15 +70,14 @@ class StatItemTest { CountDownLatch startLatch = new CountDownLatch(1); for (int i = 0; i < threadNum; i++) { taskList.add(new Task(statItem, startLatch, stopLatch)); - } startLatch.countDown(); stopLatch.await(); - Assertions.assertEquals(taskList.stream().map(Task::getCount).reduce(Integer::sum).get(), 100); + Assertions.assertEquals( + taskList.stream().map(Task::getCount).reduce(Integer::sum).get(), 100); } - static class Task implements Runnable { private final StatItem statItem; private final CountDownLatch startLatch; diff --git a/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/filter/tps/TpsLimitFilterTest.java b/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/filter/tps/TpsLimitFilterTest.java index a91aa25eae..5b7a59c606 100644 --- a/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/filter/tps/TpsLimitFilterTest.java +++ b/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/filter/tps/TpsLimitFilterTest.java @@ -24,6 +24,7 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.filter.TpsLimitFilter; import org.apache.dubbo.rpc.support.MockInvocation; import org.apache.dubbo.rpc.support.MyInvoker; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -59,9 +60,7 @@ class TpsLimitFilterTest { assertTrue(re.hasException()); throw re.getException(); } - } }); - } } diff --git a/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java b/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java index ae8a69cc5d..ffcabd8d47 100644 --- a/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java +++ b/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java @@ -68,11 +68,11 @@ public class MockInvocation extends RpcInvocation { } public Class[] getParameterTypes() { - return new Class[]{String.class}; + return new Class[] {String.class}; } public Object[] getArguments() { - return new Object[]{"aa"}; + return new Object[] {"aa"}; } public Map getAttachments() { @@ -119,9 +119,7 @@ public class MockInvocation extends RpcInvocation { } @Override - public void setServiceModel(ServiceModel serviceModel) { - - } + public void setServiceModel(ServiceModel serviceModel) {} @Override public ServiceModel getServiceModel() { @@ -164,5 +162,4 @@ public class MockInvocation extends RpcInvocation { } return result; } - } diff --git a/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java b/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java index f2dbe07081..670a3f7885 100644 --- a/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java +++ b/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java @@ -86,5 +86,4 @@ public class MyInvoker implements Invoker { public String toString() { return "MyInvoker.toString()"; } - } diff --git a/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/support/RuntimeExceptionInvoker.java b/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/support/RuntimeExceptionInvoker.java index 63d497f9aa..46006ac1b7 100644 --- a/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/support/RuntimeExceptionInvoker.java +++ b/dubbo-plugin/dubbo-plugin-tps/src/test/java/org/apache/dubbo/rpc/support/RuntimeExceptionInvoker.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.support; import org.apache.dubbo.common.URL; diff --git a/dubbo-plugin/dubbo-qos-api/pom.xml b/dubbo-plugin/dubbo-qos-api/pom.xml index 0e16ca8a17..37395a8bdc 100644 --- a/dubbo-plugin/dubbo-qos-api/pom.xml +++ b/dubbo-plugin/dubbo-qos-api/pom.xml @@ -1,3 +1,4 @@ + - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - 4.0.0 + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + - dubbo-qos-api - dubbo-qos-api + dubbo-qos-api + dubbo-qos-api - - UTF-8 - false - + + UTF-8 + false + - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - - - org.apache.dubbo - dubbo-common - ${project.version} - - + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + + + org.apache.dubbo + dubbo-common + ${project.version} + + diff --git a/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/Cmd.java b/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/Cmd.java index ad890d3c81..c7c680461f 100644 --- a/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/Cmd.java +++ b/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/Cmd.java @@ -62,5 +62,4 @@ public @interface Cmd { * @return command permission level */ PermissionLevel requiredPermissionLevel() default PermissionLevel.PROTECTED; - } diff --git a/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/CommandContext.java b/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/CommandContext.java index 3c9351d9ba..bb8b3332e0 100644 --- a/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/CommandContext.java +++ b/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/CommandContext.java @@ -16,12 +16,12 @@ */ package org.apache.dubbo.qos.api; -import io.netty.channel.Channel; - import java.util.Arrays; import java.util.Objects; import java.util.Optional; +import io.netty.channel.Channel; + public class CommandContext { private String commandName; @@ -99,20 +99,25 @@ public class CommandContext { return qosConfiguration; } - public boolean isAllowAnonymousAccess(){ + public boolean isAllowAnonymousAccess() { return this.qosConfiguration.isAllowAnonymousAccess(); } @Override public String toString() { - return "CommandContext{" + - "commandName='" + commandName + '\'' + - ", args=" + Arrays.toString(args) + - ", remote=" + Optional.ofNullable(remote).map(Channel::remoteAddress).map(Objects::toString).orElse("unknown") + - ", local=" + Optional.ofNullable(remote).map(Channel::localAddress).map(Objects::toString).orElse("unknown") + - ", isHttp=" + isHttp + - ", httpCode=" + httpCode + - ", qosConfiguration=" + qosConfiguration + - '}'; + return "CommandContext{" + "commandName='" + + commandName + '\'' + ", args=" + + Arrays.toString(args) + ", remote=" + + Optional.ofNullable(remote) + .map(Channel::remoteAddress) + .map(Objects::toString) + .orElse("unknown") + ", local=" + + Optional.ofNullable(remote) + .map(Channel::localAddress) + .map(Objects::toString) + .orElse("unknown") + ", isHttp=" + + isHttp + ", httpCode=" + + httpCode + ", qosConfiguration=" + + qosConfiguration + '}'; } } diff --git a/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/PermissionLevel.java b/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/PermissionLevel.java index 0d97638673..e76f6801b9 100644 --- a/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/PermissionLevel.java +++ b/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/PermissionLevel.java @@ -39,7 +39,6 @@ public enum PermissionLevel { * It is the reserved anonymous permission level, can not access any command */ NONE(Integer.MIN_VALUE), - ; private final int level; @@ -55,13 +54,14 @@ public enum PermissionLevel { public static PermissionLevel from(String permissionLevel) { if (StringUtils.isNumber(permissionLevel)) { return Arrays.stream(values()) - .filter(p -> String.valueOf(p.getLevel()).equals(permissionLevel.trim())) - .findFirst() - .orElse(PUBLIC); + .filter(p -> String.valueOf(p.getLevel()).equals(permissionLevel.trim())) + .findFirst() + .orElse(PUBLIC); } return Arrays.stream(values()) - .filter(p -> p.name().equalsIgnoreCase(String.valueOf(permissionLevel).trim())) - .findFirst() - .orElse(PUBLIC); + .filter(p -> p.name() + .equalsIgnoreCase(String.valueOf(permissionLevel).trim())) + .findFirst() + .orElse(PUBLIC); } } diff --git a/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/QosConfiguration.java b/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/QosConfiguration.java index 69f9b10e19..580c88381e 100644 --- a/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/QosConfiguration.java +++ b/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/QosConfiguration.java @@ -33,7 +33,8 @@ public class QosConfiguration { private Predicate acceptForeignIpWhitelistPredicate; - // this permission level for anonymous access, it will ignore the acceptForeignIp and acceptForeignIpWhitelist configurations + // this permission level for anonymous access, it will ignore the acceptForeignIp and acceptForeignIpWhitelist + // configurations // Access permission depends on the config anonymousAccessPermissionLevel and the cmd required permission level // the default value is Cmd.PermissionLevel.PUBLIC, can only access PUBLIC level cmd private PermissionLevel anonymousAccessPermissionLevel = PermissionLevel.PUBLIC; @@ -41,8 +42,7 @@ public class QosConfiguration { // the allow commands for anonymous access, the delimiter is colon(,) private String anonymousAllowCommands; - private QosConfiguration() { - } + private QosConfiguration() {} public QosConfiguration(Builder builder) { this.welcome = builder.getWelcome(); @@ -56,18 +56,19 @@ public class QosConfiguration { private void buildPredicate() { if (StringUtils.isNotEmpty(acceptForeignIpWhitelist)) { this.acceptForeignIpWhitelistPredicate = Arrays.stream(acceptForeignIpWhitelist.split(",")) - .map(String::trim) - .filter(StringUtils::isNotEmpty) - .map(foreignIpPattern -> (Predicate) foreignIp -> { - try { - // hard code port to -1 - return NetUtils.matchIpExpression(foreignIpPattern, foreignIp, -1); - } catch (UnknownHostException ignore) { - // ignore illegal CIDR specification - } - return false; - }) - .reduce(Predicate::or).orElse(s -> false); + .map(String::trim) + .filter(StringUtils::isNotEmpty) + .map(foreignIpPattern -> (Predicate) foreignIp -> { + try { + // hard code port to -1 + return NetUtils.matchIpExpression(foreignIpPattern, foreignIp, -1); + } catch (UnknownHostException ignore) { + // ignore illegal CIDR specification + } + return false; + }) + .reduce(Predicate::or) + .orElse(s -> false); } else { this.acceptForeignIpWhitelistPredicate = foreignIp -> false; } @@ -105,7 +106,6 @@ public class QosConfiguration { return new Builder(); } - public static class Builder { private String welcome; private boolean acceptForeignIp; @@ -113,8 +113,7 @@ public class QosConfiguration { private PermissionLevel anonymousAccessPermissionLevel = PermissionLevel.PUBLIC; private String anonymousAllowCommands; - private Builder() { - } + private Builder() {} public Builder welcome(String welcome) { this.welcome = welcome; diff --git a/dubbo-plugin/dubbo-qos/pom.xml b/dubbo-plugin/dubbo-qos/pom.xml index 8bbcd0d435..1be8f4c034 100644 --- a/dubbo-plugin/dubbo-qos/pom.xml +++ b/dubbo-plugin/dubbo-qos/pom.xml @@ -1,3 +1,4 @@ + - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - 4.0.0 + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + - dubbo-qos - jar + dubbo-qos + jar - dubbo-qos + dubbo-qos - - UTF-8 - false - + + UTF-8 + false + - - - org.apache.dubbo - dubbo-common - ${project.version} - - - org.apache.dubbo - dubbo-registry-api - ${project.version} - - - org.apache.dubbo - dubbo-config-api - ${project.version} - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - + + + org.apache.dubbo + dubbo-common + ${project.version} + + + org.apache.dubbo + dubbo-registry-api + ${project.version} + + + org.apache.dubbo + dubbo-config-api + ${project.version} + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.version} + - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.parent.version} - - - org.apache.dubbo - dubbo-qos-api - ${project.version} - - - org.apache.dubbo - dubbo-native - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-default - ${project.version} - - + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.parent.version} + + + org.apache.dubbo + dubbo-qos-api + ${project.version} + + + org.apache.dubbo + dubbo-native + ${project.parent.version} + + + org.apache.dubbo + dubbo-metrics-default + ${project.version} + + diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/QosScopeModelInitializer.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/QosScopeModelInitializer.java index 5dcbd6f6f4..58125556ba 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/QosScopeModelInitializer.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/QosScopeModelInitializer.java @@ -33,12 +33,8 @@ public class QosScopeModelInitializer implements ScopeModelInitializer { } @Override - public void initializeApplicationModel(ApplicationModel applicationModel) { - - } + public void initializeApplicationModel(ApplicationModel applicationModel) {} @Override - public void initializeModuleModel(ModuleModel moduleModel) { - - } + public void initializeModuleModel(ModuleModel moduleModel) {} } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/aot/QosReflectionTypeDescriberRegistrar.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/aot/QosReflectionTypeDescriberRegistrar.java index 4d2170df4f..8dd30e6dd6 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/aot/QosReflectionTypeDescriberRegistrar.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/aot/QosReflectionTypeDescriberRegistrar.java @@ -29,7 +29,6 @@ import java.util.HashSet; import java.util.List; import java.util.Set; - public class QosReflectionTypeDescriberRegistrar implements ReflectionTypeDescriberRegistrar { @Override @@ -45,6 +44,7 @@ public class QosReflectionTypeDescriberRegistrar implements ReflectionTypeDescri private TypeDescriber buildTypeDescriberWithPublicMethod(Class cl) { Set memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.INVOKE_PUBLIC_METHODS); - return new TypeDescriber(cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); + return new TypeDescriber( + cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/DefaultCommandExecutor.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/DefaultCommandExecutor.java index 441381941d..b959577602 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/DefaultCommandExecutor.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/DefaultCommandExecutor.java @@ -16,13 +16,12 @@ */ package org.apache.dubbo.qos.command; -import io.netty.channel.Channel; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.qos.api.BaseCommand; +import org.apache.dubbo.qos.api.Cmd; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.PermissionLevel; -import org.apache.dubbo.qos.api.Cmd; import org.apache.dubbo.qos.command.exception.NoSuchCommandException; import org.apache.dubbo.qos.command.exception.PermissionDenyException; import org.apache.dubbo.qos.common.QosConstants; @@ -34,8 +33,10 @@ import java.util.Arrays; import java.util.Objects; import java.util.Optional; +import io.netty.channel.Channel; + public class DefaultCommandExecutor implements CommandExecutor { - private final static Logger logger = LoggerFactory.getLogger(DefaultCommandExecutor.class); + private static final Logger logger = LoggerFactory.getLogger(DefaultCommandExecutor.class); private final FrameworkModel frameworkModel; public DefaultCommandExecutor(FrameworkModel frameworkModel) { @@ -45,20 +46,23 @@ public class DefaultCommandExecutor implements CommandExecutor { @Override public String execute(CommandContext commandContext) throws NoSuchCommandException, PermissionDenyException { String remoteAddress = Optional.ofNullable(commandContext.getRemote()) - .map(Channel::remoteAddress).map(Objects::toString).orElse("unknown"); + .map(Channel::remoteAddress) + .map(Objects::toString) + .orElse("unknown"); - logger.info("[Dubbo QoS] Command Process start. Command: " + commandContext.getCommandName() + - ", Args: " + Arrays.toString(commandContext.getArgs()) + ", Remote Address: " + remoteAddress); + logger.info("[Dubbo QoS] Command Process start. Command: " + commandContext.getCommandName() + ", Args: " + + Arrays.toString(commandContext.getArgs()) + ", Remote Address: " + remoteAddress); BaseCommand command = null; try { - command = frameworkModel.getExtensionLoader(BaseCommand.class).getExtension(commandContext.getCommandName()); + command = + frameworkModel.getExtensionLoader(BaseCommand.class).getExtension(commandContext.getCommandName()); } catch (Throwable throwable) { - //can't find command + // can't find command } if (command == null) { - logger.info("[Dubbo QoS] Command Not found. Command: " + commandContext.getCommandName() + - ", Remote Address: " + remoteAddress); + logger.info("[Dubbo QoS] Command Not found. Command: " + commandContext.getCommandName() + + ", Remote Address: " + remoteAddress); throw new NoSuchCommandException(commandContext.getCommandName()); } @@ -66,18 +70,22 @@ public class DefaultCommandExecutor implements CommandExecutor { if (commandContext.isAllowAnonymousAccess()) { PermissionChecker permissionChecker = DefaultAnonymousAccessPermissionChecker.INSTANCE; try { - permissionChecker = frameworkModel.getExtensionLoader(PermissionChecker.class).getExtension(QosConstants.QOS_PERMISSION_CHECKER); + permissionChecker = frameworkModel + .getExtensionLoader(PermissionChecker.class) + .getExtension(QosConstants.QOS_PERMISSION_CHECKER); } catch (Throwable throwable) { - //can't find valid custom permissionChecker + // can't find valid custom permissionChecker } final Cmd cmd = command.getClass().getAnnotation(Cmd.class); final PermissionLevel cmdRequiredPermissionLevel = cmd.requiredPermissionLevel(); if (!permissionChecker.access(commandContext, cmdRequiredPermissionLevel)) { - logger.info("[Dubbo QoS] Command Deny to access. Command: " + commandContext.getCommandName() + - ", Args: " + Arrays.toString(commandContext.getArgs()) + ", Required Permission Level: " + cmdRequiredPermissionLevel + - ", Remote Address: " + remoteAddress); + logger.info( + "[Dubbo QoS] Command Deny to access. Command: " + commandContext.getCommandName() + ", Args: " + + Arrays.toString(commandContext.getArgs()) + ", Required Permission Level: " + + cmdRequiredPermissionLevel + ", Remote Address: " + + remoteAddress); throw new PermissionDenyException(commandContext.getCommandName()); } } @@ -85,15 +93,18 @@ public class DefaultCommandExecutor implements CommandExecutor { try { String result = command.execute(commandContext, commandContext.getArgs()); if (command.logResult()) { - logger.info("[Dubbo QoS] Command Process success. Command: " + commandContext.getCommandName() + - ", Args: " + Arrays.toString(commandContext.getArgs()) + ", Result: " + result + - ", Remote Address: " + remoteAddress); + logger.info("[Dubbo QoS] Command Process success. Command: " + commandContext.getCommandName() + + ", Args: " + + Arrays.toString(commandContext.getArgs()) + ", Result: " + result + ", Remote Address: " + + remoteAddress); } return result; } catch (Throwable t) { - logger.info("[Dubbo QoS] Command Process Failed. Command: " + commandContext.getCommandName() + - ", Args: " + Arrays.toString(commandContext.getArgs()) + - ", Remote Address: " + remoteAddress, t); + logger.info( + "[Dubbo QoS] Command Process Failed. Command: " + commandContext.getCommandName() + ", Args: " + + Arrays.toString(commandContext.getArgs()) + ", Remote Address: " + + remoteAddress, + t); throw t; } } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/decoder/HttpCommandDecoder.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/decoder/HttpCommandDecoder.java index e111e48fab..77e7fa8928 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/decoder/HttpCommandDecoder.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/decoder/HttpCommandDecoder.java @@ -16,12 +16,6 @@ */ package org.apache.dubbo.qos.command.decoder; -import io.netty.handler.codec.http.HttpMethod; -import io.netty.handler.codec.http.HttpRequest; -import io.netty.handler.codec.http.QueryStringDecoder; -import io.netty.handler.codec.http.multipart.Attribute; -import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder; -import io.netty.handler.codec.http.multipart.InterfaceHttpData; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.command.CommandContextFactory; @@ -29,6 +23,13 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; +import io.netty.handler.codec.http.HttpMethod; +import io.netty.handler.codec.http.HttpRequest; +import io.netty.handler.codec.http.QueryStringDecoder; +import io.netty.handler.codec.http.multipart.Attribute; +import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder; +import io.netty.handler.codec.http.multipart.InterfaceHttpData; + public class HttpCommandDecoder { public static CommandContext decode(HttpRequest request) { CommandContext commandContext = null; @@ -46,10 +47,12 @@ public class HttpCommandDecoder { commandContext.setHttp(true); } else { List valueList = new ArrayList(); - for (List values : queryStringDecoder.parameters().values()) { + for (List values : + queryStringDecoder.parameters().values()) { valueList.addAll(values); } - commandContext = CommandContextFactory.newInstance(name, valueList.toArray(new String[]{}), true); + commandContext = + CommandContextFactory.newInstance(name, valueList.toArray(new String[] {}), true); } } else if (request.method() == HttpMethod.POST) { HttpPostRequestDecoder httpPostRequestDecoder = new HttpPostRequestDecoder(request); @@ -68,18 +71,18 @@ public class HttpCommandDecoder { commandContext = CommandContextFactory.newInstance(name); commandContext.setHttp(true); } else { - commandContext = CommandContextFactory.newInstance(name, valueList.toArray(new String[]{}), true); + commandContext = + CommandContextFactory.newInstance(name, valueList.toArray(new String[] {}), true); } } } else if (array.length == 3) { String name = array[1]; String appName = array[2]; if (request.method() == HttpMethod.GET) { - commandContext = CommandContextFactory.newInstance(name, new String[]{appName}, true); + commandContext = CommandContextFactory.newInstance(name, new String[] {appName}, true); commandContext.setHttp(true); } } - } return commandContext; diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/decoder/TelnetCommandDecoder.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/decoder/TelnetCommandDecoder.java index a43220f752..371aafc24f 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/decoder/TelnetCommandDecoder.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/decoder/TelnetCommandDecoder.java @@ -20,7 +20,6 @@ import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.command.CommandContextFactory; - public class TelnetCommandDecoder { public static final CommandContext decode(String str) { CommandContext commandContext = null; @@ -34,7 +33,7 @@ public class TelnetCommandDecoder { if (name.equals("invoke") && array.length > 2) { targetArgs = reBuildInvokeCmdArgs(str); } - commandContext = CommandContextFactory.newInstance( name, targetArgs,false); + commandContext = CommandContextFactory.newInstance(name, targetArgs, false); commandContext.setOriginRequest(str); } } @@ -45,5 +44,4 @@ public class TelnetCommandDecoder { private static String[] reBuildInvokeCmdArgs(String cmd) { return new String[] {cmd.substring(cmd.indexOf(" ") + 1).trim()}; } - } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/BaseOffline.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/BaseOffline.java index 0e21d2c429..292d0005a2 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/BaseOffline.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/BaseOffline.java @@ -69,20 +69,24 @@ public class BaseOffline implements BaseCommand { public boolean offline(String servicePattern) { boolean hasService = false; - ExecutorService executorService = Executors.newFixedThreadPool(Math.min(Runtime.getRuntime().availableProcessors(), 4), new NamedThreadFactory("Dubbo-Offline")); + ExecutorService executorService = Executors.newFixedThreadPool( + Math.min(Runtime.getRuntime().availableProcessors(), 4), new NamedThreadFactory("Dubbo-Offline")); try { List> futures = new LinkedList<>(); Collection providerModelList = serviceRepository.allProviderModels(); for (ProviderModel providerModel : providerModelList) { ServiceMetadata metadata = providerModel.getServiceMetadata(); - if (metadata.getServiceKey().matches(servicePattern) || metadata.getDisplayServiceKey().matches(servicePattern)) { + if (metadata.getServiceKey().matches(servicePattern) + || metadata.getDisplayServiceKey().matches(servicePattern)) { hasService = true; List statedUrls = providerModel.getStatedUrl(); for (ProviderModel.RegisterStatedURL statedURL : statedUrls) { if (statedURL.isRegistered()) { - futures.add(CompletableFuture.runAsync(() -> { - doUnexport(statedURL); - }, executorService)); + futures.add(CompletableFuture.runAsync( + () -> { + doUnexport(statedURL); + }, + executorService)); } } } @@ -100,8 +104,11 @@ public class BaseOffline implements BaseCommand { } protected void doUnexport(ProviderModel.RegisterStatedURL statedURL) { - RegistryFactory registryFactory = - statedURL.getRegistryUrl().getOrDefaultApplicationModel().getExtensionLoader(RegistryFactory.class).getAdaptiveExtension(); + RegistryFactory registryFactory = statedURL + .getRegistryUrl() + .getOrDefaultApplicationModel() + .getExtensionLoader(RegistryFactory.class) + .getAdaptiveExtension(); Registry registry = registryFactory.getRegistry(statedURL.getRegistryUrl()); registry.unregister(statedURL.getProviderUrl()); statedURL.setRegistered(false); diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/BaseOnline.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/BaseOnline.java index 62e85b74bc..51551c0e7e 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/BaseOnline.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/BaseOnline.java @@ -61,7 +61,8 @@ public class BaseOnline implements BaseCommand { Collection providerModelList = serviceRepository.allProviderModels(); for (ProviderModel providerModel : providerModelList) { ServiceMetadata metadata = providerModel.getServiceMetadata(); - if (metadata.getServiceKey().matches(servicePattern) || metadata.getDisplayServiceKey().matches(servicePattern)) { + if (metadata.getServiceKey().matches(servicePattern) + || metadata.getDisplayServiceKey().matches(servicePattern)) { hasService = true; List statedUrls = providerModel.getStatedUrl(); for (ProviderModel.RegisterStatedURL statedURL : statedUrls) { @@ -80,8 +81,11 @@ public class BaseOnline implements BaseCommand { } protected void doExport(ProviderModel.RegisterStatedURL statedURL) { - RegistryFactory registryFactory = - statedURL.getRegistryUrl().getOrDefaultApplicationModel().getExtensionLoader(RegistryFactory.class).getAdaptiveExtension(); + RegistryFactory registryFactory = statedURL + .getRegistryUrl() + .getOrDefaultApplicationModel() + .getExtensionLoader(RegistryFactory.class) + .getAdaptiveExtension(); Registry registry = registryFactory.getRegistry(statedURL.getRegistryUrl()); registry.register(statedURL.getProviderUrl()); statedURL.setRegistered(true); diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/ChangeTelnet.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/ChangeTelnet.java index 0862823973..e16d7e41b6 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/ChangeTelnet.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/ChangeTelnet.java @@ -18,8 +18,8 @@ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; @@ -27,9 +27,10 @@ import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; import io.netty.channel.Channel; import io.netty.util.AttributeKey; -@Cmd(name = "cd", summary = "Change default service.", example = { - "cd [service]" -}) +@Cmd( + name = "cd", + summary = "Change default service.", + example = {"cd [service]"}) public class ChangeTelnet implements BaseCommand { public static final AttributeKey SERVICE_KEY = AttributeKey.valueOf("telnet.service"); @@ -56,15 +57,17 @@ public class ChangeTelnet implements BaseCommand { boolean found = false; for (Exporter exporter : dubboProtocol.getExporters()) { if (message.equals(exporter.getInvoker().getInterface().getSimpleName()) - || message.equals(exporter.getInvoker().getInterface().getName()) - || message.equals(exporter.getInvoker().getUrl().getPath())) { + || message.equals(exporter.getInvoker().getInterface().getName()) + || message.equals(exporter.getInvoker().getUrl().getPath())) { found = true; break; } } if (found) { channel.attr(SERVICE_KEY).set(message); - buf.append("Used the ").append(message).append(" as default.\r\nYou can cancel default service by command: cd /"); + buf.append("Used the ") + .append(message) + .append(" as default.\r\nYou can cancel default service by command: cd /"); } else { buf.append("No such service ").append(message); } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/CountTelnet.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/CountTelnet.java index ef8538f87b..9d89c98306 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/CountTelnet.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/CountTelnet.java @@ -19,8 +19,8 @@ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.telnet.support.TelnetUtils; import org.apache.dubbo.remoting.utils.PayloadDropper; @@ -30,20 +30,21 @@ import org.apache.dubbo.rpc.RpcStatus; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; -import io.netty.channel.Channel; -import io.netty.channel.ChannelFuture; - import java.lang.reflect.Method; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; +import io.netty.channel.Channel; +import io.netty.channel.ChannelFuture; + import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.qos.server.handler.QosProcessHandler.PROMPT; -@Cmd(name = "count", summary = "Count the service.", example = { - "count [service] [method] [times]" -}) +@Cmd( + name = "count", + summary = "Count the service.", + example = {"count [service] [method] [times]"}) public class CountTelnet implements BaseCommand { private final DubboProtocol dubboProtocol; @@ -55,8 +56,7 @@ public class CountTelnet implements BaseCommand { public String execute(CommandContext commandContext, String[] args) { Channel channel = commandContext.getRemote(); String service = channel.attr(ChangeTelnet.SERVICE_KEY).get(); - if ((service == null || service.length() == 0) - && (args == null || args.length == 0)) { + if ((service == null || service.length() == 0) && (args == null || args.length == 0)) { return "Please input service name, eg: \r\ncount XxxService\r\ncount XxxService xxxMethod\r\ncount XxxService xxxMethod 10\r\nor \"cd XxxService\" firstly."; } StringBuilder buf = new StringBuilder(); @@ -84,8 +84,8 @@ public class CountTelnet implements BaseCommand { Invoker invoker = null; for (Exporter exporter : dubboProtocol.getExporters()) { if (service.equals(exporter.getInvoker().getInterface().getSimpleName()) - || service.equals(exporter.getInvoker().getInterface().getName()) - || service.equals(exporter.getInvoker().getUrl().getPath())) { + || service.equals(exporter.getInvoker().getInterface().getName()) + || service.equals(exporter.getInvoker().getUrl().getPath())) { invoker = exporter.getInvoker(); break; } @@ -94,26 +94,28 @@ public class CountTelnet implements BaseCommand { if (t > 0) { final String mtd = method; final Invoker inv = invoker; - Thread thread = new Thread(() -> { - for (int i = 0; i < t; i++) { - String result = count(inv, mtd); - try { - send(channel, "\r\n" + result); - } catch (RemotingException e1) { - return; - } - if (i < t - 1) { - try { - Thread.sleep(1000); - } catch (InterruptedException ignored) { + Thread thread = new Thread( + () -> { + for (int i = 0; i < t; i++) { + String result = count(inv, mtd); + try { + send(channel, "\r\n" + result); + } catch (RemotingException e1) { + return; + } + if (i < t - 1) { + try { + Thread.sleep(1000); + } catch (InterruptedException ignored) { + } + } } - } - } - try { - send(channel, "\r\n" + PROMPT); - } catch (RemotingException ignored) { - } - }, "TelnetCount"); + try { + send(channel, "\r\n" + PROMPT); + } catch (RemotingException ignored) { + } + }, + "TelnetCount"); thread.setDaemon(true); thread.start(); } @@ -134,11 +136,19 @@ public class CountTelnet implements BaseCommand { throw cause; } } catch (Throwable e) { - throw new RemotingException((InetSocketAddress) channel.localAddress(), (InetSocketAddress) channel.remoteAddress(), "Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to " + channel.remoteAddress().toString() + ", cause: " + e.getMessage(), e); + throw new RemotingException( + (InetSocketAddress) channel.localAddress(), + (InetSocketAddress) channel.remoteAddress(), + "Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to " + + channel.remoteAddress().toString() + ", cause: " + e.getMessage(), + e); } if (!success) { - throw new RemotingException((InetSocketAddress) channel.localAddress(), (InetSocketAddress) channel.remoteAddress(), "Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to " + channel.remoteAddress().toString() - + "in timeout(" + timeout + "ms) limit"); + throw new RemotingException( + (InetSocketAddress) channel.localAddress(), + (InetSocketAddress) channel.remoteAddress(), + "Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to " + + channel.remoteAddress().toString() + "in timeout(" + timeout + "ms) limit"); } } @@ -169,7 +179,8 @@ public class CountTelnet implements BaseCommand { RpcStatus count = RpcStatus.getStatus(url, method); table.add(createRow(method, count)); } else { - return "No such method " + method + " in class " + invoker.getInterface().getName(); + return "No such method " + method + " in class " + + invoker.getInterface().getName(); } } return TelnetUtils.toTable(header, table); diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DefaultMetricsReporterCmd.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DefaultMetricsReporterCmd.java index ceb4d5756b..2d630f7230 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DefaultMetricsReporterCmd.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DefaultMetricsReporterCmd.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.utils.JsonUtils; @@ -82,7 +81,8 @@ public class DefaultMetricsReporterCmd implements BaseCommand { private String specifySingleApplication(String appName, List models, String metricsName) { Optional modelOptional = models.stream() - .filter(applicationModel -> appName.equals(applicationModel.getApplicationName())).findFirst(); + .filter(applicationModel -> appName.equals(applicationModel.getApplicationName())) + .findFirst(); if (modelOptional.isPresent()) { return getResponseByApplication(modelOptional.get(), metricsName); } else { @@ -108,7 +108,6 @@ public class DefaultMetricsReporterCmd implements BaseCommand { return response; } - private static long getLineNumber(String content) { LineNumberReader lnr = new LineNumberReader(new CharArrayReader(content.toCharArray())); try { diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableDetailProfiler.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableDetailProfiler.java index 058349e018..5383ec3038 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableDetailProfiler.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableDetailProfiler.java @@ -20,14 +20,15 @@ import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.profiler.ProfilerSwitch; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PROFILER_DISABLED; @Cmd(name = "disableDetailProfiler", summary = "Disable Dubbo Invocation Profiler.") public class DisableDetailProfiler implements BaseCommand { - private final static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DisableDetailProfiler.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(DisableDetailProfiler.class); @Override public String execute(CommandContext commandContext, String[] args) { diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableRouterSnapshot.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableRouterSnapshot.java index 61f6acd5b6..edb9655d2c 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableRouterSnapshot.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableRouterSnapshot.java @@ -17,16 +17,17 @@ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.rpc.cluster.router.RouterSnapshotSwitcher; import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ServiceMetadata; -@Cmd(name = "disableRouterSnapshot", - summary = "Disable Dubbo Invocation Level Router Snapshot Print", - example = "disableRouterSnapshot xx.xx.xxx.service") +@Cmd( + name = "disableRouterSnapshot", + summary = "Disable Dubbo Invocation Level Router Snapshot Print", + example = "disableRouterSnapshot xx.xx.xxx.service") public class DisableRouterSnapshot implements BaseCommand { private final RouterSnapshotSwitcher routerSnapshotSwitcher; private final FrameworkModel frameworkModel; @@ -46,7 +47,8 @@ public class DisableRouterSnapshot implements BaseCommand { for (ConsumerModel consumerModel : frameworkModel.getServiceRepository().allConsumerModels()) { try { ServiceMetadata metadata = consumerModel.getServiceMetadata(); - if (metadata.getServiceKey().matches(servicePattern) || metadata.getDisplayServiceKey().matches(servicePattern)) { + if (metadata.getServiceKey().matches(servicePattern) + || metadata.getDisplayServiceKey().matches(servicePattern)) { routerSnapshotSwitcher.removeEnabledService(metadata.getServiceKey()); count += 1; } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableSimpleProfiler.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableSimpleProfiler.java index 3aace5d25c..b8dfa9c9fb 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableSimpleProfiler.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableSimpleProfiler.java @@ -20,14 +20,15 @@ import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.profiler.ProfilerSwitch; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PROFILER_DISABLED; @Cmd(name = "disableSimpleProfiler", summary = "Disable Dubbo Invocation Profiler.") public class DisableSimpleProfiler implements BaseCommand { - private final static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DisableSimpleProfiler.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(DisableSimpleProfiler.class); @Override public String execute(CommandContext commandContext, String[] args) { diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableDetailProfiler.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableDetailProfiler.java index f6dac6e3ec..09f47294b8 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableDetailProfiler.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableDetailProfiler.java @@ -20,14 +20,15 @@ import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.profiler.ProfilerSwitch; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PROFILER_ENABLED; @Cmd(name = "enableDetailProfiler", summary = "Enable Dubbo Invocation Profiler.") public class EnableDetailProfiler implements BaseCommand { - private final static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(EnableDetailProfiler.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(EnableDetailProfiler.class); @Override public String execute(CommandContext commandContext, String[] args) { diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableRouterSnapshot.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableRouterSnapshot.java index 47b58ee12c..80ea67581b 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableRouterSnapshot.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableRouterSnapshot.java @@ -17,16 +17,17 @@ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.rpc.cluster.router.RouterSnapshotSwitcher; import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ServiceMetadata; -@Cmd(name = "enableRouterSnapshot", - summary = "Enable Dubbo Invocation Level Router Snapshot Print", - example = "enableRouterSnapshot xx.xx.xxx.service") +@Cmd( + name = "enableRouterSnapshot", + summary = "Enable Dubbo Invocation Level Router Snapshot Print", + example = "enableRouterSnapshot xx.xx.xxx.service") public class EnableRouterSnapshot implements BaseCommand { private final RouterSnapshotSwitcher routerSnapshotSwitcher; private final FrameworkModel frameworkModel; @@ -46,7 +47,8 @@ public class EnableRouterSnapshot implements BaseCommand { for (ConsumerModel consumerModel : frameworkModel.getServiceRepository().allConsumerModels()) { try { ServiceMetadata metadata = consumerModel.getServiceMetadata(); - if (metadata.getServiceKey().matches(servicePattern) || metadata.getDisplayServiceKey().matches(servicePattern)) { + if (metadata.getServiceKey().matches(servicePattern) + || metadata.getDisplayServiceKey().matches(servicePattern)) { routerSnapshotSwitcher.addEnabledService(metadata.getServiceKey()); count += 1; } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableSimpleProfiler.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableSimpleProfiler.java index 2d93efda24..5c3ddedb73 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableSimpleProfiler.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableSimpleProfiler.java @@ -20,14 +20,15 @@ import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.profiler.ProfilerSwitch; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PROFILER_ENABLED; @Cmd(name = "enableSimpleProfiler", summary = "Enable Dubbo Invocation Profiler.") public class EnableSimpleProfiler implements BaseCommand { - private final static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(EnableSimpleProfiler.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(EnableSimpleProfiler.class); @Override public String execute(CommandContext commandContext, String[] args) { diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetAddress.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetAddress.java index 8be7fbd9f2..dd466612d8 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetAddress.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetAddress.java @@ -40,10 +40,11 @@ import java.util.List; import java.util.Map; import java.util.Optional; -@Cmd(name = "getAddress", - summary = "Get service available address ", - example = {"getAddress com.example.DemoService", "getAddress group/com.example.DemoService"}, - requiredPermissionLevel = PermissionLevel.PRIVATE) +@Cmd( + name = "getAddress", + summary = "Get service available address ", + example = {"getAddress com.example.DemoService", "getAddress group/com.example.DemoService"}, + requiredPermissionLevel = PermissionLevel.PRIVATE) public class GetAddress implements BaseCommand { public final FrameworkServiceRepository serviceRepository; @@ -76,14 +77,18 @@ public class GetAddress implements BaseCommand { } } - private static void appendConsumer(StringBuilder plainOutput, Map jsonOutput, ConsumerModel consumerModel) { - plainOutput.append("ConsumerModel: ") - .append(consumerModel.getServiceKey()) - .append("@") - .append(Integer.toHexString(System.identityHashCode(consumerModel))) - .append("\n\n"); + private static void appendConsumer( + StringBuilder plainOutput, Map jsonOutput, ConsumerModel consumerModel) { + plainOutput + .append("ConsumerModel: ") + .append(consumerModel.getServiceKey()) + .append("@") + .append(Integer.toHexString(System.identityHashCode(consumerModel))) + .append("\n\n"); Map consumerMap = new HashMap<>(); - jsonOutput.put(consumerModel.getServiceKey() + "@" + Integer.toHexString(System.identityHashCode(consumerModel)), consumerMap); + jsonOutput.put( + consumerModel.getServiceKey() + "@" + Integer.toHexString(System.identityHashCode(consumerModel)), + consumerMap); Object object = consumerModel.getServiceMetadata().getAttribute(CommonConstants.CURRENT_CLUSTER_INVOKER_KEY); Map> invokerMap; @@ -95,21 +100,20 @@ public class GetAddress implements BaseCommand { } } - private static void appendInvokers(StringBuilder plainOutput, Map consumerMap, Map.Entry> entry) { + private static void appendInvokers( + StringBuilder plainOutput, + Map consumerMap, + Map.Entry> entry) { URL registryUrl = entry.getKey().getUrl(); - plainOutput.append("Registry: ") - .append(registryUrl) - .append("\n"); + plainOutput.append("Registry: ").append(registryUrl).append("\n"); Map registryMap = new HashMap<>(); consumerMap.put(registryUrl.toString(), registryMap); MigrationInvoker migrationInvoker = entry.getValue(); MigrationStep migrationStep = migrationInvoker.getMigrationStep(); - plainOutput.append("MigrationStep: ") - .append(migrationStep) - .append("\n\n"); + plainOutput.append("MigrationStep: ").append(migrationStep).append("\n\n"); registryMap.put("MigrationStep", migrationStep); Map invokersMap = new HashMap<>(); @@ -124,99 +128,100 @@ public class GetAddress implements BaseCommand { RpcContext.getServiceContext().setConsumerUrl(originConsumerUrl); } - private static void appendAppLevel(StringBuilder plainOutput, MigrationInvoker migrationInvoker, Map invokersMap) { + private static void appendAppLevel( + StringBuilder plainOutput, MigrationInvoker migrationInvoker, Map invokersMap) { Map appMap = new HashMap<>(); invokersMap.put("Application-Level", appMap); Optional.ofNullable(migrationInvoker.getServiceDiscoveryInvoker()) - .ifPresent(i -> plainOutput.append("Application-Level: \n")); + .ifPresent(i -> plainOutput.append("Application-Level: \n")); Optional.ofNullable(migrationInvoker.getServiceDiscoveryInvoker()) - .map(ClusterInvoker::getDirectory) - .map(Directory::getAllInvokers) - .ifPresent(invokers -> { - List invokerUrls = new LinkedList<>(); - plainOutput.append("All Invokers: \n"); - for (org.apache.dubbo.rpc.Invoker invoker : invokers) { - invokerUrls.add(invoker.getUrl().toFullString()); - plainOutput.append(invoker.getUrl().toFullString()).append("\n"); - } - plainOutput.append("\n"); - appMap.put("All", invokerUrls); - }); + .map(ClusterInvoker::getDirectory) + .map(Directory::getAllInvokers) + .ifPresent(invokers -> { + List invokerUrls = new LinkedList<>(); + plainOutput.append("All Invokers: \n"); + for (org.apache.dubbo.rpc.Invoker invoker : invokers) { + invokerUrls.add(invoker.getUrl().toFullString()); + plainOutput.append(invoker.getUrl().toFullString()).append("\n"); + } + plainOutput.append("\n"); + appMap.put("All", invokerUrls); + }); Optional.ofNullable(migrationInvoker.getServiceDiscoveryInvoker()) - .map(ClusterInvoker::getDirectory) - .map(s -> (AbstractDirectory) s) - .map(AbstractDirectory::getValidInvokers) - .ifPresent(invokers -> { - List invokerUrls = new LinkedList<>(); - plainOutput.append("Valid Invokers: \n"); - for (org.apache.dubbo.rpc.Invoker invoker : invokers) { - invokerUrls.add(invoker.getUrl().toFullString()); - plainOutput.append(invoker.getUrl().toFullString()).append("\n"); - } - plainOutput.append("\n"); - appMap.put("Valid", invokerUrls); - }); + .map(ClusterInvoker::getDirectory) + .map(s -> (AbstractDirectory) s) + .map(AbstractDirectory::getValidInvokers) + .ifPresent(invokers -> { + List invokerUrls = new LinkedList<>(); + plainOutput.append("Valid Invokers: \n"); + for (org.apache.dubbo.rpc.Invoker invoker : invokers) { + invokerUrls.add(invoker.getUrl().toFullString()); + plainOutput.append(invoker.getUrl().toFullString()).append("\n"); + } + plainOutput.append("\n"); + appMap.put("Valid", invokerUrls); + }); Optional.ofNullable(migrationInvoker.getServiceDiscoveryInvoker()) - .map(ClusterInvoker::getDirectory) - .map(s -> (AbstractDirectory) s) - .map(AbstractDirectory::getDisabledInvokers) - .ifPresent(invokers -> { - List invokerUrls = new LinkedList<>(); - plainOutput.append("Disabled Invokers: \n"); - for (org.apache.dubbo.rpc.Invoker invoker : invokers) { - invokerUrls.add(invoker.getUrl().toFullString()); - plainOutput.append(invoker.getUrl().toFullString()).append("\n"); - } - plainOutput.append("\n"); - appMap.put("Disabled", invokerUrls); - }); + .map(ClusterInvoker::getDirectory) + .map(s -> (AbstractDirectory) s) + .map(AbstractDirectory::getDisabledInvokers) + .ifPresent(invokers -> { + List invokerUrls = new LinkedList<>(); + plainOutput.append("Disabled Invokers: \n"); + for (org.apache.dubbo.rpc.Invoker invoker : invokers) { + invokerUrls.add(invoker.getUrl().toFullString()); + plainOutput.append(invoker.getUrl().toFullString()).append("\n"); + } + plainOutput.append("\n"); + appMap.put("Disabled", invokerUrls); + }); } - private static void appendInterfaceLevel(StringBuilder plainOutput, MigrationInvoker migrationInvoker, Map invokersMap) { + private static void appendInterfaceLevel( + StringBuilder plainOutput, MigrationInvoker migrationInvoker, Map invokersMap) { Map interfaceMap = new HashMap<>(); invokersMap.put("Interface-Level", interfaceMap); + Optional.ofNullable(migrationInvoker.getInvoker()).ifPresent(i -> plainOutput.append("Interface-Level: \n")); Optional.ofNullable(migrationInvoker.getInvoker()) - .ifPresent(i -> plainOutput.append("Interface-Level: \n")); + .map(ClusterInvoker::getDirectory) + .map(Directory::getAllInvokers) + .ifPresent(invokers -> { + List invokerUrls = new LinkedList<>(); + plainOutput.append("All Invokers: \n"); + for (org.apache.dubbo.rpc.Invoker invoker : invokers) { + invokerUrls.add(invoker.getUrl().toFullString()); + plainOutput.append(invoker.getUrl().toFullString()).append("\n"); + } + plainOutput.append("\n"); + interfaceMap.put("All", invokerUrls); + }); Optional.ofNullable(migrationInvoker.getInvoker()) - .map(ClusterInvoker::getDirectory) - .map(Directory::getAllInvokers) - .ifPresent(invokers -> { - List invokerUrls = new LinkedList<>(); - plainOutput.append("All Invokers: \n"); - for (org.apache.dubbo.rpc.Invoker invoker : invokers) { - invokerUrls.add(invoker.getUrl().toFullString()); - plainOutput.append(invoker.getUrl().toFullString()).append("\n"); - } - plainOutput.append("\n"); - interfaceMap.put("All", invokerUrls); - }); + .map(ClusterInvoker::getDirectory) + .map(s -> (AbstractDirectory) s) + .map(AbstractDirectory::getValidInvokers) + .ifPresent(invokers -> { + List invokerUrls = new LinkedList<>(); + plainOutput.append("Valid Invokers: \n"); + for (org.apache.dubbo.rpc.Invoker invoker : invokers) { + invokerUrls.add(invoker.getUrl().toFullString()); + plainOutput.append(invoker.getUrl().toFullString()).append("\n"); + } + plainOutput.append("\n"); + interfaceMap.put("Valid", invokerUrls); + }); Optional.ofNullable(migrationInvoker.getInvoker()) - .map(ClusterInvoker::getDirectory) - .map(s -> (AbstractDirectory) s) - .map(AbstractDirectory::getValidInvokers) - .ifPresent(invokers -> { - List invokerUrls = new LinkedList<>(); - plainOutput.append("Valid Invokers: \n"); - for (org.apache.dubbo.rpc.Invoker invoker : invokers) { - invokerUrls.add(invoker.getUrl().toFullString()); - plainOutput.append(invoker.getUrl().toFullString()).append("\n"); - } - plainOutput.append("\n"); - interfaceMap.put("Valid", invokerUrls); - }); - Optional.ofNullable(migrationInvoker.getInvoker()) - .map(ClusterInvoker::getDirectory) - .map(s -> (AbstractDirectory) s) - .map(AbstractDirectory::getDisabledInvokers) - .ifPresent(invokers -> { - List invokerUrls = new LinkedList<>(); - plainOutput.append("Disabled Invokers: \n"); - for (org.apache.dubbo.rpc.Invoker invoker : invokers) { - invokerUrls.add(invoker.getUrl().toFullString()); - plainOutput.append(invoker.getUrl().toFullString()).append("\n"); - } - plainOutput.append("\n"); - interfaceMap.put("Disabled", invokerUrls); - }); + .map(ClusterInvoker::getDirectory) + .map(s -> (AbstractDirectory) s) + .map(AbstractDirectory::getDisabledInvokers) + .ifPresent(invokers -> { + List invokerUrls = new LinkedList<>(); + plainOutput.append("Disabled Invokers: \n"); + for (org.apache.dubbo.rpc.Invoker invoker : invokers) { + invokerUrls.add(invoker.getUrl().toFullString()); + plainOutput.append(invoker.getUrl().toFullString()).append("\n"); + } + plainOutput.append("\n"); + interfaceMap.put("Disabled", invokerUrls); + }); } } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetConfig.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetConfig.java index 74f08ba729..a3025147df 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetConfig.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetConfig.java @@ -34,8 +34,8 @@ import org.apache.dubbo.config.TracingConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.config.context.ModuleConfigManager; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.PermissionLevel; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; @@ -46,10 +46,11 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; -@Cmd(name = "getConfig", - summary = "Get current running config.", - example = {"getConfig ReferenceConfig com.example.DemoService", "getConfig ApplicationConfig"}, - requiredPermissionLevel = PermissionLevel.PRIVATE) +@Cmd( + name = "getConfig", + summary = "Get current running config.", + example = {"getConfig ReferenceConfig com.example.DemoService", "getConfig ApplicationConfig"}, + requiredPermissionLevel = PermissionLevel.PRIVATE) public class GetConfig implements BaseCommand { private final FrameworkModel frameworkModel; @@ -76,9 +77,10 @@ public class GetConfig implements BaseCommand { for (ApplicationModel applicationModel : frameworkModel.getApplicationModels()) { Map applicationMap = new HashMap<>(); frameworkMap.put(applicationModel.getDesc(), applicationMap); - plainOutput.append("ApplicationModel: ") - .append(applicationModel.getDesc()) - .append("\n"); + plainOutput + .append("ApplicationModel: ") + .append(applicationModel.getDesc()) + .append("\n"); ConfigManager configManager = applicationModel.getApplicationConfigManager(); @@ -86,9 +88,15 @@ public class GetConfig implements BaseCommand { } } - private static void appendApplicationConfigs(String[] args, StringBuilder plainOutput, ApplicationModel applicationModel, Map applicationMap, ConfigManager configManager) { + private static void appendApplicationConfigs( + String[] args, + StringBuilder plainOutput, + ApplicationModel applicationModel, + Map applicationMap, + ConfigManager configManager) { Optional applicationConfig = configManager.getApplication(); - applicationConfig.ifPresent(config -> appendConfig("ApplicationConfig", config.getName(), config, plainOutput, applicationMap, args)); + applicationConfig.ifPresent(config -> + appendConfig("ApplicationConfig", config.getName(), config, plainOutput, applicationMap, args)); for (ProtocolConfig protocol : configManager.getProtocols()) { appendConfigs("ProtocolConfig", protocol.getName(), protocol, plainOutput, applicationMap, args); @@ -99,7 +107,8 @@ public class GetConfig implements BaseCommand { } for (MetadataReportConfig metadataConfig : configManager.getMetadataConfigs()) { - appendConfigs("MetadataReportConfig", metadataConfig.getId(), metadataConfig, plainOutput, applicationMap, args); + appendConfigs( + "MetadataReportConfig", metadataConfig.getId(), metadataConfig, plainOutput, applicationMap, args); } for (ConfigCenterConfig configCenter : configManager.getConfigCenters()) { @@ -107,23 +116,25 @@ public class GetConfig implements BaseCommand { } Optional metricsConfig = configManager.getMetrics(); - metricsConfig.ifPresent(config -> appendConfig("MetricsConfig", config.getId(), config, plainOutput, applicationMap, args)); + metricsConfig.ifPresent( + config -> appendConfig("MetricsConfig", config.getId(), config, plainOutput, applicationMap, args)); Optional tracingConfig = configManager.getTracing(); - tracingConfig.ifPresent(config -> appendConfig("TracingConfig", config.getId(), config, plainOutput, applicationMap, args)); + tracingConfig.ifPresent( + config -> appendConfig("TracingConfig", config.getId(), config, plainOutput, applicationMap, args)); Optional monitorConfig = configManager.getMonitor(); - monitorConfig.ifPresent(config -> appendConfig("MonitorConfig", config.getId(), config, plainOutput, applicationMap, args)); + monitorConfig.ifPresent( + config -> appendConfig("MonitorConfig", config.getId(), config, plainOutput, applicationMap, args)); Optional sslConfig = configManager.getSsl(); - sslConfig.ifPresent(config -> appendConfig("SslConfig", config.getId(), config, plainOutput, applicationMap, args)); + sslConfig.ifPresent( + config -> appendConfig("SslConfig", config.getId(), config, plainOutput, applicationMap, args)); for (ModuleModel moduleModel : applicationModel.getModuleModels()) { Map moduleMap = new HashMap<>(); applicationMap.put(moduleModel.getDesc(), moduleMap); - plainOutput.append("ModuleModel: ") - .append(moduleModel.getDesc()) - .append("\n"); + plainOutput.append("ModuleModel: ").append(moduleModel.getDesc()).append("\n"); ModuleConfigManager moduleConfigManager = moduleModel.getConfigManager(); @@ -131,7 +142,11 @@ public class GetConfig implements BaseCommand { } } - private static void appendModuleConfigs(String[] args, StringBuilder plainOutput, Map moduleMap, ModuleConfigManager moduleConfigManager) { + private static void appendModuleConfigs( + String[] args, + StringBuilder plainOutput, + Map moduleMap, + ModuleConfigManager moduleConfigManager) { for (ProviderConfig provider : moduleConfigManager.getProviders()) { appendConfigs("ProviderConfig", provider.getId(), provider, plainOutput, moduleMap, args); } @@ -141,7 +156,8 @@ public class GetConfig implements BaseCommand { } Optional moduleConfig = moduleConfigManager.getModule(); - moduleConfig.ifPresent(config -> appendConfig("ModuleConfig", config.getId(), config, plainOutput, moduleMap, args)); + moduleConfig.ifPresent( + config -> appendConfig("ModuleConfig", config.getId(), config, plainOutput, moduleMap, args)); for (ServiceConfigBase service : moduleConfigManager.getServices()) { appendConfigs("ServiceConfig", service.getUniqueServiceName(), service, plainOutput, moduleMap, args); @@ -153,31 +169,38 @@ public class GetConfig implements BaseCommand { } @SuppressWarnings("unchecked") - private static void appendConfigs(String type, String id, Object config, StringBuilder plainOutput, Map map, String[] args) { + private static void appendConfigs( + String type, String id, Object config, StringBuilder plainOutput, Map map, String[] args) { if (!isMatch(type, id, args)) { return; } - plainOutput.append(type).append(": ") - .append(id) - .append("\n") - .append(config) - .append("\n\n"); + plainOutput + .append(type) + .append(": ") + .append(id) + .append("\n") + .append(config) + .append("\n\n"); - Map typeMap = (Map) map.computeIfAbsent(type, k -> new HashMap()); + Map typeMap = + (Map) map.computeIfAbsent(type, k -> new HashMap()); typeMap.put(id, config); } - private static void appendConfig(String type, String id, Object config, StringBuilder plainOutput, Map map, String[] args) { + private static void appendConfig( + String type, String id, Object config, StringBuilder plainOutput, Map map, String[] args) { if (!isMatch(type, id, args)) { return; } - plainOutput.append(type).append(": ") - .append(id) - .append("\n") - .append(config) - .append("\n\n"); + plainOutput + .append(type) + .append(": ") + .append(id) + .append("\n") + .append(config) + .append("\n\n"); map.put(type, config); } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetEnabledRouterSnapshot.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetEnabledRouterSnapshot.java index a71be3cdba..826cfaa6b3 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetEnabledRouterSnapshot.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetEnabledRouterSnapshot.java @@ -17,13 +17,14 @@ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.rpc.cluster.router.RouterSnapshotSwitcher; import org.apache.dubbo.rpc.model.FrameworkModel; -@Cmd(name = "getEnabledRouterSnapshot", - summary = "Get enabled Dubbo invocation level router snapshot print service list") +@Cmd( + name = "getEnabledRouterSnapshot", + summary = "Get enabled Dubbo invocation level router snapshot print service list") public class GetEnabledRouterSnapshot implements BaseCommand { private final RouterSnapshotSwitcher routerSnapshotSwitcher; diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetRecentRouterSnapshot.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetRecentRouterSnapshot.java index 57bd6c058b..8177ad3289 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetRecentRouterSnapshot.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetRecentRouterSnapshot.java @@ -17,8 +17,8 @@ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.rpc.cluster.router.RouterSnapshotSwitcher; import org.apache.dubbo.rpc.model.FrameworkModel; @@ -26,8 +26,7 @@ import java.util.Arrays; import java.util.Objects; import java.util.stream.Collectors; -@Cmd(name = "getRecentRouterSnapshot", - summary = "Get recent (32) router snapshot message") +@Cmd(name = "getRecentRouterSnapshot", summary = "Get recent (32) router snapshot message") public class GetRecentRouterSnapshot implements BaseCommand { private final RouterSnapshotSwitcher routerSnapshotSwitcher; @@ -38,6 +37,9 @@ public class GetRecentRouterSnapshot implements BaseCommand { @Override public String execute(CommandContext commandContext, String[] args) { - return Arrays.stream(routerSnapshotSwitcher.cloneSnapshot()).filter(Objects::nonNull).sorted().collect(Collectors.joining("\n\n")); + return Arrays.stream(routerSnapshotSwitcher.cloneSnapshot()) + .filter(Objects::nonNull) + .sorted() + .collect(Collectors.joining("\n\n")); } } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetRouterSnapshot.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetRouterSnapshot.java index 46d5bef84b..5857f49df5 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetRouterSnapshot.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetRouterSnapshot.java @@ -18,8 +18,8 @@ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.client.migration.MigrationInvoker; import org.apache.dubbo.rpc.cluster.Directory; @@ -31,7 +31,10 @@ import org.apache.dubbo.rpc.model.ServiceMetadata; import java.util.Map; -@Cmd(name = "getRouterSnapshot", summary = "Get State Router Snapshot.", example = "getRouterSnapshot xx.xx.xxx.service") +@Cmd( + name = "getRouterSnapshot", + summary = "Get State Router Snapshot.", + example = "getRouterSnapshot xx.xx.xxx.service") public class GetRouterSnapshot implements BaseCommand { private final FrameworkModel frameworkModel; @@ -49,21 +52,32 @@ public class GetRouterSnapshot implements BaseCommand { for (ConsumerModel consumerModel : frameworkModel.getServiceRepository().allConsumerModels()) { try { ServiceMetadata metadata = consumerModel.getServiceMetadata(); - if (metadata.getServiceKey().matches(servicePattern) || metadata.getDisplayServiceKey().matches(servicePattern)) { + if (metadata.getServiceKey().matches(servicePattern) + || metadata.getDisplayServiceKey().matches(servicePattern)) { Object object = metadata.getAttribute(CommonConstants.CURRENT_CLUSTER_INVOKER_KEY); Map> invokerMap; if (object instanceof Map) { invokerMap = (Map>) object; for (Map.Entry> invokerEntry : invokerMap.entrySet()) { Directory directory = invokerEntry.getValue().getDirectory(); - StateRouter headStateRouter = directory.getRouterChain().getHeadStateRouter(); - stringBuilder.append(metadata.getServiceKey()).append('@').append(Integer.toHexString(System.identityHashCode(metadata))) - .append("\n") - .append("[ All Invokers:").append(directory.getAllInvokers().size()).append(" ] ") - .append("[ Valid Invokers: ").append(((AbstractDirectory)directory).getValidInvokers().size()).append(" ]\n") - .append("\n") - .append(headStateRouter.buildSnapshot()) - .append("\n\n"); + StateRouter headStateRouter = + directory.getRouterChain().getHeadStateRouter(); + stringBuilder + .append(metadata.getServiceKey()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(metadata))) + .append("\n") + .append("[ All Invokers:") + .append(directory.getAllInvokers().size()) + .append(" ] ") + .append("[ Valid Invokers: ") + .append(((AbstractDirectory) directory) + .getValidInvokers() + .size()) + .append(" ]\n") + .append("\n") + .append(headStateRouter.buildSnapshot()) + .append("\n\n"); } } } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GracefulShutdown.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GracefulShutdown.java index f21e6473f8..fe330d2df0 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GracefulShutdown.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GracefulShutdown.java @@ -22,10 +22,11 @@ import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.PermissionLevel; import org.apache.dubbo.rpc.model.FrameworkModel; -@Cmd(name = "gracefulShutdown", - summary = "Gracefully shutdown servers", - example = {"gracefulShutdown"}, - requiredPermissionLevel = PermissionLevel.PRIVATE) +@Cmd( + name = "gracefulShutdown", + summary = "Gracefully shutdown servers", + example = {"gracefulShutdown"}, + requiredPermissionLevel = PermissionLevel.PRIVATE) public class GracefulShutdown implements BaseCommand { private final Offline offline; private final FrameworkModel frameworkModel; @@ -38,7 +39,7 @@ public class GracefulShutdown implements BaseCommand { @Override public String execute(CommandContext commandContext, String[] args) { for (org.apache.dubbo.rpc.GracefulShutdown gracefulShutdown : - org.apache.dubbo.rpc.GracefulShutdown.getGracefulShutdowns(frameworkModel)) { + org.apache.dubbo.rpc.GracefulShutdown.getGracefulShutdowns(frameworkModel)) { gracefulShutdown.readonly(); } offline.execute(commandContext, new String[0]); diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Help.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Help.java index 60365cd665..25e6c7752c 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Help.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Help.java @@ -18,8 +18,8 @@ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.command.util.CommandHelper; import org.apache.dubbo.qos.textui.TTable; import org.apache.dubbo.rpc.model.FrameworkModel; @@ -30,10 +30,10 @@ import java.util.List; import java.util.Map; import java.util.WeakHashMap; -@Cmd(name = "help", summary = "help command", example = { - "help", - "help online" -}) +@Cmd( + name = "help", + summary = "help command", + example = {"help", "help online"}) public class Help implements BaseCommand { private final CommandHelper commandHelper; @@ -55,7 +55,6 @@ public class Help implements BaseCommand { } } - private String commandHelp(String commandName) { if (!commandHelper.hasCommand(commandName)) { @@ -65,9 +64,8 @@ public class Help implements BaseCommand { Class clazz = commandHelper.getCommandClass(commandName); final Cmd cmd = clazz.getAnnotation(Cmd.class); - final TTable tTable = new TTable(new TTable.ColumnDefine[]{ - new TTable.ColumnDefine(TTable.Align.RIGHT), - new TTable.ColumnDefine(80, false, TTable.Align.LEFT) + final TTable tTable = new TTable(new TTable.ColumnDefine[] { + new TTable.ColumnDefine(TTable.Align.RIGHT), new TTable.ColumnDefine(80, false, TTable.Align.LEFT) }); tTable.addRow("COMMAND NAME", commandName); @@ -92,9 +90,8 @@ public class Help implements BaseCommand { */ private String mainHelp() { - final TTable tTable = new TTable(new TTable.ColumnDefine[]{ - new TTable.ColumnDefine(TTable.Align.RIGHT), - new TTable.ColumnDefine(80, false, TTable.Align.LEFT) + final TTable tTable = new TTable(new TTable.ColumnDefine[] { + new TTable.ColumnDefine(TTable.Align.RIGHT), new TTable.ColumnDefine(80, false, TTable.Align.LEFT) }); final List> classes = commandHelper.getAllCommandClass(); @@ -107,7 +104,6 @@ public class Help implements BaseCommand { final Integer o2s = o2.getAnnotation(Cmd.class).sort(); return o1s.compareTo(o2s); } - }); for (Class clazz : classes) { @@ -115,7 +111,6 @@ public class Help implements BaseCommand { final Cmd cmd = clazz.getAnnotation(Cmd.class); tTable.addRow(cmd.name(), cmd.summary()); } - } return tTable.padding(1).rendering(); diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/InvokeTelnet.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/InvokeTelnet.java index 3e7400ff05..5abc2f1045 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/InvokeTelnet.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/InvokeTelnet.java @@ -22,8 +22,8 @@ import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.AsyncContext; import org.apache.dubbo.rpc.AsyncContextImpl; @@ -32,9 +32,6 @@ import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.MethodDescriptor; import org.apache.dubbo.rpc.model.ProviderModel; -import io.netty.channel.Channel; -import io.netty.util.AttributeKey; - import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; @@ -43,16 +40,21 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; +import io.netty.channel.Channel; +import io.netty.util.AttributeKey; + import static org.apache.dubbo.common.utils.PojoUtils.realize; -@Cmd(name = "invoke", summary = "Invoke the service method.", example = { - "invoke IHelloService.sayHello(\"xxxx\")", - "invoke sayHello(\"xxxx\")" -}) +@Cmd( + name = "invoke", + summary = "Invoke the service method.", + example = {"invoke IHelloService.sayHello(\"xxxx\")", "invoke sayHello(\"xxxx\")"}) public class InvokeTelnet implements BaseCommand { public static final AttributeKey INVOKE_MESSAGE_KEY = AttributeKey.valueOf("telnet.invoke.method.message"); - public static final AttributeKey> INVOKE_METHOD_LIST_KEY = AttributeKey.valueOf("telnet.invoke.method.list"); - public static final AttributeKey INVOKE_METHOD_PROVIDER_KEY = AttributeKey.valueOf("telnet.invoke.method.provider"); + public static final AttributeKey> INVOKE_METHOD_LIST_KEY = + AttributeKey.valueOf("telnet.invoke.method.list"); + public static final AttributeKey INVOKE_METHOD_PROVIDER_KEY = + AttributeKey.valueOf("telnet.invoke.method.provider"); private final FrameworkModel frameworkModel; @@ -63,12 +65,14 @@ public class InvokeTelnet implements BaseCommand { @Override public String execute(CommandContext commandContext, String[] args) { if (ArrayUtils.isEmpty(args)) { - return "Please input method name, eg: \r\ninvoke xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\n" + - "invoke XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\n" + - "invoke com.xxx.XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})"; + return "Please input method name, eg: \r\ninvoke xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\n" + + "invoke XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\n" + + "invoke com.xxx.XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})"; } Channel channel = commandContext.getRemote(); - String service = channel.attr(ChangeTelnet.SERVICE_KEY) != null ? channel.attr(ChangeTelnet.SERVICE_KEY).get() : null; + String service = channel.attr(ChangeTelnet.SERVICE_KEY) != null + ? channel.attr(ChangeTelnet.SERVICE_KEY).get() + : null; String message = args[0]; int i = message.indexOf("("); @@ -86,8 +90,8 @@ public class InvokeTelnet implements BaseCommand { } if (StringUtils.isEmpty(service)) { - return "If you want to invoke like [invoke sayHello(\"xxxx\")], please execute cd command first," + - " or you can execute it like [invoke IHelloService.sayHello(\"xxxx\")]"; + return "If you want to invoke like [invoke sayHello(\"xxxx\")], please execute cd command first," + + " or you can execute it like [invoke IHelloService.sayHello(\"xxxx\")]"; } List list; @@ -123,7 +127,7 @@ public class InvokeTelnet implements BaseCommand { } if (matchMethods.size() == 1) { invokeMethod = matchMethods.get(0); - } else { //exist overridden method + } else { // exist overridden method channel.attr(INVOKE_METHOD_PROVIDER_KEY).set(provider); channel.attr(INVOKE_METHOD_LIST_KEY).set(matchMethods); channel.attr(INVOKE_MESSAGE_KEY).set(message); @@ -135,7 +139,6 @@ public class InvokeTelnet implements BaseCommand { } } - if (!StringUtils.isEmpty(service)) { buf.append("Use default service ").append(service).append('.'); } @@ -144,12 +147,15 @@ public class InvokeTelnet implements BaseCommand { return buf.toString(); } if (invokeMethod == null) { - buf.append("\r\nNo such method ").append(method).append(" in service ").append(service); + buf.append("\r\nNo such method ") + .append(method) + .append(" in service ") + .append(service); return buf.toString(); } try { - Object[] array = realize(list.toArray(), invokeMethod.getParameterTypes(), - invokeMethod.getGenericParameterTypes()); + Object[] array = + realize(list.toArray(), invokeMethod.getParameterTypes(), invokeMethod.getGenericParameterTypes()); long start = System.currentTimeMillis(); AppResponse result = new AppResponse(); try { @@ -158,7 +164,8 @@ public class InvokeTelnet implements BaseCommand { if (RpcContext.getServerAttachment().isAsyncStarted()) { AsyncContext asyncContext = RpcContext.getServerAttachment().getAsyncContext(); if (asyncContext instanceof AsyncContextImpl) { - CompletableFuture internalFuture = ((AsyncContextImpl) asyncContext).getInternalFuture(); + CompletableFuture internalFuture = + ((AsyncContextImpl) asyncContext).getInternalFuture(); result.setValue(internalFuture.get()); setValueDone = true; } @@ -186,15 +193,15 @@ public class InvokeTelnet implements BaseCommand { return buf.toString(); } - private boolean isServiceMatch(String service, ProviderModel provider) { return provider.getServiceKey().equalsIgnoreCase(service) - || provider.getServiceInterfaceClass().getSimpleName().equalsIgnoreCase(service) - || provider.getServiceInterfaceClass().getName().equalsIgnoreCase(service) - || StringUtils.isEmpty(service); + || provider.getServiceInterfaceClass().getSimpleName().equalsIgnoreCase(service) + || provider.getServiceInterfaceClass().getName().equalsIgnoreCase(service) + || StringUtils.isEmpty(service); } - private List findSameSignatureMethod(Set methods, String lookupMethodName, List args) { + private List findSameSignatureMethod( + Set methods, String lookupMethodName, List args) { List sameSignatureMethods = new ArrayList<>(); for (MethodDescriptor model : methods) { Method method = model.getMethod(); diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Live.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Live.java index cebd23f2b7..e02f6df76b 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Live.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Live.java @@ -20,8 +20,8 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.PermissionLevel; import org.apache.dubbo.qos.probe.LivenessProbe; import org.apache.dubbo.rpc.model.FrameworkModel; @@ -40,18 +40,18 @@ public class Live implements BaseCommand { @Override public String execute(CommandContext commandContext, String[] args) { - String config = frameworkModel.getApplicationModels() - .stream() - .map(applicationModel -> applicationModel.getApplicationConfigManager().getApplication()) - .map(o -> o.orElse(null)) - .filter(Objects::nonNull) - .map(ApplicationConfig::getLivenessProbe) - .filter(Objects::nonNull) - .collect(Collectors.joining(",")); - URL url = URL.valueOf("application://") - .addParameter(CommonConstants.QOS_LIVE_PROBE_EXTENSION, config); - List livenessProbes = frameworkModel.getExtensionLoader(LivenessProbe.class) - .getActivateExtension(url, CommonConstants.QOS_LIVE_PROBE_EXTENSION); + String config = frameworkModel.getApplicationModels().stream() + .map(applicationModel -> + applicationModel.getApplicationConfigManager().getApplication()) + .map(o -> o.orElse(null)) + .filter(Objects::nonNull) + .map(ApplicationConfig::getLivenessProbe) + .filter(Objects::nonNull) + .collect(Collectors.joining(",")); + URL url = URL.valueOf("application://").addParameter(CommonConstants.QOS_LIVE_PROBE_EXTENSION, config); + List livenessProbes = frameworkModel + .getExtensionLoader(LivenessProbe.class) + .getActivateExtension(url, CommonConstants.QOS_LIVE_PROBE_EXTENSION); if (!livenessProbes.isEmpty()) { for (LivenessProbe livenessProbe : livenessProbes) { if (!livenessProbe.check()) { diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/LoggerInfo.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/LoggerInfo.java index 13a14875e2..e9404ee304 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/LoggerInfo.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/LoggerInfo.java @@ -19,19 +19,22 @@ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; -@Cmd(name = "loggerInfo", summary = "Print logger info", example = { - "loggerInfo" -}) +@Cmd( + name = "loggerInfo", + summary = "Print logger info", + example = {"loggerInfo"}) public class LoggerInfo implements BaseCommand { @Override public String execute(CommandContext commandContext, String[] args) { - String availableAdapters = String.join(", ", LoggerFactory.getAvailableAdapter().toArray(new String[0])); + String availableAdapters = + String.join(", ", LoggerFactory.getAvailableAdapter().toArray(new String[0])); String currentAdapter = LoggerFactory.getCurrentAdapter(); Level level = LoggerFactory.getLevel(); - return "Available logger adapters: [" + availableAdapters + "]. Current Adapter: [" + currentAdapter + "]. Log level: " + level.name(); + return "Available logger adapters: [" + availableAdapters + "]. Current Adapter: [" + currentAdapter + + "]. Log level: " + level.name(); } } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Ls.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Ls.java index bc1d18178a..b9043ecc5c 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Ls.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Ls.java @@ -17,8 +17,8 @@ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.command.util.ServiceCheckUtils; import org.apache.dubbo.qos.textui.TTable; import org.apache.dubbo.rpc.model.ConsumerModel; @@ -27,9 +27,10 @@ import org.apache.dubbo.rpc.model.ProviderModel; import java.util.Collection; -@Cmd(name = "ls", summary = "ls service", example = { - "ls" -}) +@Cmd( + name = "ls", + summary = "ls service", + example = {"ls"}) public class Ls implements BaseCommand { private final FrameworkModel frameworkModel; @@ -49,20 +50,22 @@ public class Ls implements BaseCommand { public String listProvider() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("As Provider side:" + System.lineSeparator()); - Collection providerModelList = frameworkModel.getServiceRepository().allProviderModels(); + Collection providerModelList = + frameworkModel.getServiceRepository().allProviderModels(); - TTable tTable = new TTable(new TTable.ColumnDefine[]{ - new TTable.ColumnDefine(TTable.Align.MIDDLE), - new TTable.ColumnDefine(TTable.Align.MIDDLE) + TTable tTable = new TTable(new TTable.ColumnDefine[] { + new TTable.ColumnDefine(TTable.Align.MIDDLE), new TTable.ColumnDefine(TTable.Align.MIDDLE) }); - //Header + // Header tTable.addRow("Provider Service Name", "PUB"); - //Content + // Content for (ProviderModel providerModel : providerModelList) { if (providerModel.getModuleModel().isInternal()) { - tTable.addRow("DubboInternal - " + providerModel.getServiceKey(), ServiceCheckUtils.getRegisterStatus(providerModel)); + tTable.addRow( + "DubboInternal - " + providerModel.getServiceKey(), + ServiceCheckUtils.getRegisterStatus(providerModel)); } else { tTable.addRow(providerModel.getServiceKey(), ServiceCheckUtils.getRegisterStatus(providerModel)); } @@ -75,18 +78,18 @@ public class Ls implements BaseCommand { public String listConsumer() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("As Consumer side:" + System.lineSeparator()); - Collection consumerModelList = frameworkModel.getServiceRepository().allConsumerModels(); + Collection consumerModelList = + frameworkModel.getServiceRepository().allConsumerModels(); - TTable tTable = new TTable(new TTable.ColumnDefine[]{ - new TTable.ColumnDefine(TTable.Align.MIDDLE), - new TTable.ColumnDefine(TTable.Align.MIDDLE) + TTable tTable = new TTable(new TTable.ColumnDefine[] { + new TTable.ColumnDefine(TTable.Align.MIDDLE), new TTable.ColumnDefine(TTable.Align.MIDDLE) }); - //Header + // Header tTable.addRow("Consumer Service Name", "NUM"); - //Content - //TODO to calculate consumerAddressNum + // Content + // TODO to calculate consumerAddressNum for (ConsumerModel consumerModel : consumerModelList) { tTable.addRow(consumerModel.getServiceKey(), ServiceCheckUtils.getConsumerAddressNum(consumerModel)); } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Offline.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Offline.java index 3ad503e63c..6b679b47f2 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Offline.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Offline.java @@ -20,10 +20,10 @@ import org.apache.dubbo.qos.api.Cmd; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ProviderModel; -@Cmd(name = "offline", summary = "offline dubbo", example = { - "offline dubbo", - "offline xx.xx.xxx.service" -}) +@Cmd( + name = "offline", + summary = "offline dubbo", + example = {"offline dubbo", "offline xx.xx.xxx.service"}) public class Offline extends BaseOffline { public Offline(FrameworkModel frameworkModel) { diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OfflineApp.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OfflineApp.java index 57303a0def..441e838d04 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OfflineApp.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OfflineApp.java @@ -21,10 +21,10 @@ import org.apache.dubbo.qos.api.Cmd; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ProviderModel; -@Cmd(name = "offlineApp", summary = "offline app addresses", example = { - "offlineApp", - "offlineApp xx.xx.xxx.service" -}) +@Cmd( + name = "offlineApp", + summary = "offline app addresses", + example = {"offlineApp", "offlineApp xx.xx.xxx.service"}) public class OfflineApp extends BaseOffline { public OfflineApp(FrameworkModel frameworkModel) { diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OfflineInterface.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OfflineInterface.java index e98abab82f..9a37353d51 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OfflineInterface.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OfflineInterface.java @@ -21,10 +21,10 @@ import org.apache.dubbo.qos.api.Cmd; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ProviderModel; -@Cmd(name = "offlineInterface", summary = "offline dubbo", example = { - "offlineInterface dubbo", - "offlineInterface xx.xx.xxx.service" -}) +@Cmd( + name = "offlineInterface", + summary = "offline dubbo", + example = {"offlineInterface dubbo", "offlineInterface xx.xx.xxx.service"}) public class OfflineInterface extends BaseOffline { public OfflineInterface(FrameworkModel frameworkModel) { super(frameworkModel); diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Online.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Online.java index 5fab71e847..328e30b07c 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Online.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Online.java @@ -19,10 +19,10 @@ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.qos.api.Cmd; import org.apache.dubbo.rpc.model.FrameworkModel; -@Cmd(name = "online", summary = "online app addresses", example = { - "online dubbo", - "online xx.xx.xxx.service" -}) +@Cmd( + name = "online", + summary = "online app addresses", + example = {"online dubbo", "online xx.xx.xxx.service"}) public class Online extends BaseOnline { public Online(FrameworkModel frameworkModel) { super(frameworkModel); diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OnlineApp.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OnlineApp.java index 540e7279d6..3dfbf355ba 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OnlineApp.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OnlineApp.java @@ -16,16 +16,15 @@ */ package org.apache.dubbo.qos.command.impl; - import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.qos.api.Cmd; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ProviderModel; -@Cmd(name = "onlineApp", summary = "online app addresses", example = { - "onlineApp", - "onlineApp xx.xx.xxx.service" -}) +@Cmd( + name = "onlineApp", + summary = "online app addresses", + example = {"onlineApp", "onlineApp xx.xx.xxx.service"}) public class OnlineApp extends BaseOnline { public OnlineApp(FrameworkModel frameworkModel) { super(frameworkModel); diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OnlineInterface.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OnlineInterface.java index a46b116379..35dd3e01c7 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OnlineInterface.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OnlineInterface.java @@ -21,10 +21,10 @@ import org.apache.dubbo.qos.api.Cmd; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ProviderModel; -@Cmd(name = "onlineInterface", summary = "online dubbo", example = { - "onlineInterface dubbo", - "onlineInterface xx.xx.xxx.service" -}) +@Cmd( + name = "onlineInterface", + summary = "online dubbo", + example = {"onlineInterface dubbo", "onlineInterface xx.xx.xxx.service"}) public class OnlineInterface extends BaseOnline { public OnlineInterface(FrameworkModel frameworkModel) { super(frameworkModel); diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PortTelnet.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PortTelnet.java index 5a2299410d..e4231eb8e2 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PortTelnet.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PortTelnet.java @@ -18,8 +18,8 @@ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeServer; import org.apache.dubbo.rpc.ProtocolServer; @@ -28,9 +28,10 @@ import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; import java.util.Collection; -@Cmd(name = "ps", summary = "Print server ports and connections.", example = { - "ps -l [port]", "ps", "ps -l", "ps -l 20880" -}) +@Cmd( + name = "ps", + summary = "Print server ports and connections.", + example = {"ps -l [port]", "ps", "ps -l", "ps -l 20880"}) public class PortTelnet implements BaseCommand { private final DubboProtocol dubboProtocol; @@ -61,7 +62,9 @@ public class PortTelnet implements BaseCommand { buf.append("\r\n"); } if (detail) { - buf.append(server.getUrl().getProtocol()).append("://").append(server.getUrl().getAddress()); + buf.append(server.getUrl().getProtocol()) + .append("://") + .append(server.getUrl().getAddress()); } else { buf.append(server.getUrl().getPort()); } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PublishMetadata.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PublishMetadata.java index 30075490a7..f583c7768d 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PublishMetadata.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PublishMetadata.java @@ -21,8 +21,8 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; @@ -32,10 +32,10 @@ import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_PARAMETER_FORMAT_ERROR; -@Cmd(name = "publishMetadata", summary = "update service metadata and service instance", example = { - "publishMetadata", - "publishMetadata 5" -}) +@Cmd( + name = "publishMetadata", + summary = "update service metadata and service instance", + example = {"publishMetadata", "publishMetadata 5"}) public class PublishMetadata implements BaseCommand { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PublishMetadata.class); private final FrameworkModel frameworkModel; @@ -54,21 +54,35 @@ public class PublishMetadata implements BaseCommand { for (ApplicationModel applicationModel : applicationModels) { if (ArrayUtils.isEmpty(args)) { ServiceInstanceMetadataUtils.refreshMetadataAndInstance(applicationModel); - stringBuilder.append("publish metadata succeeded. App:").append(applicationModel.getApplicationName()).append("\n"); + stringBuilder + .append("publish metadata succeeded. App:") + .append(applicationModel.getApplicationName()) + .append("\n"); } else { try { int delay = Integer.parseInt(args[0]); - FrameworkExecutorRepository frameworkExecutorRepository = applicationModel.getFrameworkModel().getBeanFactory().getBean(FrameworkExecutorRepository.class); - frameworkExecutorRepository.nextScheduledExecutor() - .schedule(() -> ServiceInstanceMetadataUtils.refreshMetadataAndInstance(applicationModel), delay, TimeUnit.SECONDS); + FrameworkExecutorRepository frameworkExecutorRepository = applicationModel + .getFrameworkModel() + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class); + frameworkExecutorRepository + .nextScheduledExecutor() + .schedule( + () -> ServiceInstanceMetadataUtils.refreshMetadataAndInstance(applicationModel), + delay, + TimeUnit.SECONDS); } catch (NumberFormatException e) { logger.error(CONFIG_PARAMETER_FORMAT_ERROR, "", "", "Wrong delay param", e); return "publishMetadata failed! Wrong delay param!"; } - stringBuilder.append("publish task submitted, will publish in ").append(args[0]).append(" seconds. App:").append(applicationModel.getApplicationName()).append("\n"); + stringBuilder + .append("publish task submitted, will publish in ") + .append(args[0]) + .append(" seconds. App:") + .append(applicationModel.getApplicationName()) + .append("\n"); } } return stringBuilder.toString(); } - } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PwdTelnet.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PwdTelnet.java index 06d4a0a38b..f93ebfdd41 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PwdTelnet.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PwdTelnet.java @@ -18,21 +18,23 @@ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import java.util.Arrays; -@Cmd(name = "pwd", summary = "Print working default service.", example = { - "pwd" -}) +@Cmd( + name = "pwd", + summary = "Print working default service.", + example = {"pwd"}) public class PwdTelnet implements BaseCommand { @Override public String execute(CommandContext commandContext, String[] args) { if (args.length > 0) { return "Unsupported parameter " + Arrays.toString(args) + " for pwd."; } - String service = commandContext.getRemote().attr(ChangeTelnet.SERVICE_KEY).get(); + String service = + commandContext.getRemote().attr(ChangeTelnet.SERVICE_KEY).get(); StringBuilder buf = new StringBuilder(); if (StringUtils.isEmpty(service)) { buf.append('/'); diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Quit.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Quit.java index 793bcc744d..3bac6a06d3 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Quit.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Quit.java @@ -17,8 +17,8 @@ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.PermissionLevel; import org.apache.dubbo.qos.common.QosConstants; diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Ready.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Ready.java index ca1eecf470..c745c4f005 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Ready.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Ready.java @@ -20,8 +20,8 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.PermissionLevel; import org.apache.dubbo.qos.probe.ReadinessProbe; import org.apache.dubbo.rpc.model.FrameworkModel; @@ -40,18 +40,18 @@ public class Ready implements BaseCommand { @Override public String execute(CommandContext commandContext, String[] args) { - String config = frameworkModel.getApplicationModels() - .stream() - .map(applicationModel -> applicationModel.getApplicationConfigManager().getApplication()) - .map(o -> o.orElse(null)) - .filter(Objects::nonNull) - .map(ApplicationConfig::getReadinessProbe) - .filter(Objects::nonNull) - .collect(Collectors.joining(",")); + String config = frameworkModel.getApplicationModels().stream() + .map(applicationModel -> + applicationModel.getApplicationConfigManager().getApplication()) + .map(o -> o.orElse(null)) + .filter(Objects::nonNull) + .map(ApplicationConfig::getReadinessProbe) + .filter(Objects::nonNull) + .collect(Collectors.joining(",")); - URL url = URL.valueOf("application://") - .addParameter(CommonConstants.QOS_READY_PROBE_EXTENSION, config); - List readinessProbes = frameworkModel.getExtensionLoader(ReadinessProbe.class) + URL url = URL.valueOf("application://").addParameter(CommonConstants.QOS_READY_PROBE_EXTENSION, config); + List readinessProbes = frameworkModel + .getExtensionLoader(ReadinessProbe.class) .getActivateExtension(url, CommonConstants.QOS_READY_PROBE_EXTENSION); if (!readinessProbes.isEmpty()) { for (ReadinessProbe readinessProbe : readinessProbes) { @@ -66,5 +66,4 @@ public class Ready implements BaseCommand { commandContext.setHttpCode(200); return "true"; } - } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SelectTelnet.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SelectTelnet.java index 9d7ca8cdea..069ad0c7de 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SelectTelnet.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SelectTelnet.java @@ -20,19 +20,20 @@ import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.rpc.model.FrameworkModel; -import io.netty.channel.Channel; -import io.netty.util.AttributeKey; - import java.lang.reflect.Method; import java.util.List; -@Cmd(name = "select", summary = "Select the index of the method you want to invoke", example = { - "select [index]" -}) +import io.netty.channel.Channel; +import io.netty.util.AttributeKey; + +@Cmd( + name = "select", + summary = "Select the index of the method you want to invoke", + example = {"select [index]"}) public class SelectTelnet implements BaseCommand { public static final AttributeKey SELECT_KEY = AttributeKey.valueOf("telnet.select"); public static final AttributeKey SELECT_METHOD_KEY = AttributeKey.valueOf("telnet.select.method"); @@ -50,17 +51,20 @@ public class SelectTelnet implements BaseCommand { } Channel channel = commandContext.getRemote(); String message = args[0]; - List methodList = channel.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).get(); + List methodList = + channel.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).get(); if (CollectionUtils.isEmpty(methodList)) { return "Please use the invoke command first."; } - if (!StringUtils.isNumber(message) || Integer.parseInt(message) < 1 || Integer.parseInt(message) > methodList.size()) { + if (!StringUtils.isNumber(message) + || Integer.parseInt(message) < 1 + || Integer.parseInt(message) > methodList.size()) { return "Illegal index ,please input select 1~" + methodList.size(); } Method method = methodList.get(Integer.parseInt(message) - 1); channel.attr(SELECT_METHOD_KEY).set(method); channel.attr(SELECT_KEY).set(Boolean.TRUE); String invokeMessage = channel.attr(InvokeTelnet.INVOKE_MESSAGE_KEY).get(); - return invokeTelnet.execute(commandContext, new String[]{invokeMessage}); + return invokeTelnet.execute(commandContext, new String[] {invokeMessage}); } } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SerializeCheckStatus.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SerializeCheckStatus.java index 9c8ac498a0..2405c6dae3 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SerializeCheckStatus.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SerializeCheckStatus.java @@ -16,18 +16,18 @@ */ package org.apache.dubbo.qos.command.impl; +import org.apache.dubbo.common.utils.JsonUtils; +import org.apache.dubbo.qos.api.BaseCommand; +import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; +import org.apache.dubbo.qos.command.util.SerializeCheckUtils; +import org.apache.dubbo.rpc.model.FrameworkModel; + import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; -import org.apache.dubbo.common.utils.JsonUtils; -import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; -import org.apache.dubbo.qos.api.Cmd; -import org.apache.dubbo.qos.command.util.SerializeCheckUtils; -import org.apache.dubbo.rpc.model.FrameworkModel; - -@Cmd(name = "serializeCheckStatus",summary = "get serialize check status") +@Cmd(name = "serializeCheckStatus", summary = "get serialize check status") public class SerializeCheckStatus implements BaseCommand { private final SerializeCheckUtils serializeCheckUtils; @@ -47,14 +47,15 @@ public class SerializeCheckStatus implements BaseCommand { return JsonUtils.toJson(result); } else { - return "CheckStatus: " + serializeCheckUtils.getStatus() + "\n\n" + - "CheckSerializable: " + serializeCheckUtils.isCheckSerializable() + "\n\n" + - "AllowedPrefix:" + "\n" + - serializeCheckUtils.getAllowedList().stream().sorted().collect(Collectors.joining("\n")) + - "\n\n" + - "DisAllowedPrefix:" + "\n" + - serializeCheckUtils.getDisAllowedList().stream().sorted().collect(Collectors.joining("\n")) + - "\n\n"; + return "CheckStatus: " + serializeCheckUtils.getStatus() + "\n\n" + "CheckSerializable: " + + serializeCheckUtils.isCheckSerializable() + "\n\n" + "AllowedPrefix:" + + "\n" + + serializeCheckUtils.getAllowedList().stream().sorted().collect(Collectors.joining("\n")) + + "\n\n" + + "DisAllowedPrefix:" + + "\n" + + serializeCheckUtils.getDisAllowedList().stream().sorted().collect(Collectors.joining("\n")) + + "\n\n"; } } } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SerializeWarnedClasses.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SerializeWarnedClasses.java index a3668d78a4..ae797dd6bd 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SerializeWarnedClasses.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SerializeWarnedClasses.java @@ -16,18 +16,18 @@ */ package org.apache.dubbo.qos.command.impl; +import org.apache.dubbo.common.utils.JsonUtils; +import org.apache.dubbo.qos.api.BaseCommand; +import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; +import org.apache.dubbo.qos.command.util.SerializeCheckUtils; +import org.apache.dubbo.rpc.model.FrameworkModel; + import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; -import org.apache.dubbo.common.utils.JsonUtils; -import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; -import org.apache.dubbo.qos.api.Cmd; -import org.apache.dubbo.qos.command.util.SerializeCheckUtils; -import org.apache.dubbo.rpc.model.FrameworkModel; - -@Cmd(name = "serializeWarnedClasses",summary = "get serialize warned classes") +@Cmd(name = "serializeWarnedClasses", summary = "get serialize warned classes") public class SerializeWarnedClasses implements BaseCommand { private final SerializeCheckUtils serializeCheckUtils; @@ -43,9 +43,9 @@ public class SerializeWarnedClasses implements BaseCommand { result.put("warnedClasses", serializeCheckUtils.getWarnedClasses()); return JsonUtils.toJson(result); } else { - return "WarnedClasses: \n" + - serializeCheckUtils.getWarnedClasses().stream().sorted().collect(Collectors.joining("\n")) + - "\n\n"; + return "WarnedClasses: \n" + + serializeCheckUtils.getWarnedClasses().stream().sorted().collect(Collectors.joining("\n")) + + "\n\n"; } } } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SetProfilerWarnPercent.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SetProfilerWarnPercent.java index f71fba40c8..0a8478e3be 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SetProfilerWarnPercent.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SetProfilerWarnPercent.java @@ -20,14 +20,18 @@ import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.profiler.ProfilerSwitch; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PROFILER_WARN_PERCENT; -@Cmd(name = "setProfilerWarnPercent", example = "setProfilerWarnPercent 0.75", summary = "Disable Dubbo Invocation Profiler.") +@Cmd( + name = "setProfilerWarnPercent", + example = "setProfilerWarnPercent 0.75", + summary = "Disable Dubbo Invocation Profiler.") public class SetProfilerWarnPercent implements BaseCommand { - private final static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SetProfilerWarnPercent.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(SetProfilerWarnPercent.class); @Override public String execute(CommandContext commandContext, String[] args) { @@ -35,7 +39,8 @@ public class SetProfilerWarnPercent implements BaseCommand { return "args error. example: setProfilerWarnPercent 0.75"; } ProfilerSwitch.setWarnPercent(Double.parseDouble(args[0])); - logger.warn(QOS_PROFILER_WARN_PERCENT, "", "", "Dubbo Invocation Profiler warn percent has been set to " + args[0]); + logger.warn( + QOS_PROFILER_WARN_PERCENT, "", "", "Dubbo Invocation Profiler warn percent has been set to " + args[0]); return "OK"; } } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/ShutdownTelnet.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/ShutdownTelnet.java index 07089481e7..96a80aaad4 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/ShutdownTelnet.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/ShutdownTelnet.java @@ -18,17 +18,18 @@ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.ArrayList; import java.util.List; -@Cmd(name = "shutdown", summary = "Shutdown Dubbo Application.", example = { - "shutdown -t " -}) +@Cmd( + name = "shutdown", + summary = "Shutdown Dubbo Application.", + example = {"shutdown -t "}) public class ShutdownTelnet implements BaseCommand { private final FrameworkModel frameworkModel; @@ -62,8 +63,8 @@ public class ShutdownTelnet implements BaseCommand { applicationModel.destroy(); } // TODO change to ApplicationDeployer.destroy() or ApplicationModel.destroy() -// DubboShutdownHook.getDubboShutdownHook().unregister(); -// DubboShutdownHook.getDubboShutdownHook().doDestroy(); + // DubboShutdownHook.getDubboShutdownHook().unregister(); + // DubboShutdownHook.getDubboShutdownHook().doDestroy(); long end = System.currentTimeMillis(); buf.append("Application has shutdown successfully"); buf.append("\r\nelapsed: "); diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Startup.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Startup.java index ce3f7f1ca4..8459e819a6 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Startup.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Startup.java @@ -20,8 +20,8 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.PermissionLevel; import org.apache.dubbo.qos.probe.StartupProbe; import org.apache.dubbo.rpc.model.FrameworkModel; @@ -41,18 +41,18 @@ public class Startup implements BaseCommand { @Override public String execute(CommandContext commandContext, String[] args) { - String config = frameworkModel.getApplicationModels() - .stream() - .map(applicationModel -> applicationModel.getApplicationConfigManager().getApplication()) - .map(o -> o.orElse(null)) - .filter(Objects::nonNull) - .map(ApplicationConfig::getStartupProbe) - .filter(Objects::nonNull) - .collect(Collectors.joining(",")); + String config = frameworkModel.getApplicationModels().stream() + .map(applicationModel -> + applicationModel.getApplicationConfigManager().getApplication()) + .map(o -> o.orElse(null)) + .filter(Objects::nonNull) + .map(ApplicationConfig::getStartupProbe) + .filter(Objects::nonNull) + .collect(Collectors.joining(",")); - URL url = URL.valueOf("application://") - .addParameter(CommonConstants.QOS_STARTUP_PROBE_EXTENSION, config); - List startupProbes = frameworkModel.getExtensionLoader(StartupProbe.class) + URL url = URL.valueOf("application://").addParameter(CommonConstants.QOS_STARTUP_PROBE_EXTENSION, config); + List startupProbes = frameworkModel + .getExtensionLoader(StartupProbe.class) .getActivateExtension(url, CommonConstants.QOS_STARTUP_PROBE_EXTENSION); if (!startupProbes.isEmpty()) { for (StartupProbe startupProbe : startupProbes) { diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SwitchLogLevel.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SwitchLogLevel.java index f65fe01e6e..887c2c1a51 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SwitchLogLevel.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SwitchLogLevel.java @@ -19,14 +19,15 @@ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import java.util.Locale; -@Cmd(name = "switchLogLevel", summary = "Switch log level", example = { - "switchLogLevel info" -}) +@Cmd( + name = "switchLogLevel", + summary = "Switch log level", + example = {"switchLogLevel info"}) public class SwitchLogLevel implements BaseCommand { @Override public String execute(CommandContext commandContext, String[] args) { diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SwitchLogger.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SwitchLogger.java index bae3d44de9..89b283a6eb 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SwitchLogger.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SwitchLogger.java @@ -19,13 +19,14 @@ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.rpc.model.FrameworkModel; -@Cmd(name = "switchLogger", summary = "Switch logger", example = { - "switchLogger slf4j" -}) +@Cmd( + name = "switchLogger", + summary = "Switch logger", + example = {"switchLogger slf4j"}) public class SwitchLogger implements BaseCommand { private final FrameworkModel frameworkModel; diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Version.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Version.java index 907702d1cc..8231e5eb7a 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Version.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Version.java @@ -17,12 +17,13 @@ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; -@Cmd(name = "version", summary = "version command(show dubbo version)", example = { - "version" -}) +@Cmd( + name = "version", + summary = "version command(show dubbo version)", + example = {"version"}) public class Version implements BaseCommand { @Override @@ -33,5 +34,4 @@ public class Version implements BaseCommand { versionDescBuilder.append('\"'); return versionDescBuilder.toString(); } - } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/CommandHelper.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/CommandHelper.java index 926a462b61..faad6041de 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/CommandHelper.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/CommandHelper.java @@ -41,25 +41,28 @@ public class CommandHelper { } return command != null; - } public List> getAllCommandClass() { - final Set commandList = frameworkModel.getExtensionLoader(BaseCommand.class).getSupportedExtensions(); + final Set commandList = + frameworkModel.getExtensionLoader(BaseCommand.class).getSupportedExtensions(); final List> classes = new ArrayList>(); for (String commandName : commandList) { - BaseCommand command = frameworkModel.getExtensionLoader(BaseCommand.class).getExtension(commandName); + BaseCommand command = + frameworkModel.getExtensionLoader(BaseCommand.class).getExtension(commandName); classes.add(command.getClass()); } return classes; } - public Class getCommandClass(String commandName) { if (hasCommand(commandName)) { - return frameworkModel.getExtensionLoader(BaseCommand.class).getExtension(commandName).getClass(); + return frameworkModel + .getExtensionLoader(BaseCommand.class) + .getExtension(commandName) + .getClass(); } else { return null; } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/SerializeCheckUtils.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/SerializeCheckUtils.java index 91f34a55e9..0125e36027 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/SerializeCheckUtils.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/SerializeCheckUtils.java @@ -16,14 +16,14 @@ */ package org.apache.dubbo.qos.command.util; -import java.util.Collections; -import java.util.Set; - import org.apache.dubbo.common.utils.AllowClassNotifyListener; import org.apache.dubbo.common.utils.SerializeCheckStatus; import org.apache.dubbo.common.utils.SerializeSecurityManager; import org.apache.dubbo.rpc.model.FrameworkModel; +import java.util.Collections; +import java.util.Set; + public class SerializeCheckUtils implements AllowClassNotifyListener { private final SerializeSecurityManager manager; private volatile Set allowedList = Collections.emptySet(); diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/ServiceCheckUtils.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/ServiceCheckUtils.java index c876c0ccdb..749271c63d 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/ServiceCheckUtils.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/ServiceCheckUtils.java @@ -41,9 +41,12 @@ public class ServiceCheckUtils { for (ProviderModel.RegisterStatedURL registerStatedURL : providerModel.getStatedUrl()) { URL registryUrl = registerStatedURL.getRegistryUrl(); boolean isServiceDiscovery = UrlUtils.isServiceDiscoveryURL(registryUrl); - String protocol = isServiceDiscovery ? registryUrl.getParameter(RegistryConstants.REGISTRY_KEY) : registryUrl.getProtocol(); + String protocol = isServiceDiscovery + ? registryUrl.getParameter(RegistryConstants.REGISTRY_KEY) + : registryUrl.getProtocol(); // e.g. zookeeper-A(Y) - statuses.add(protocol + "-" + (isServiceDiscovery ? "A" : "I") + "(" + (registerStatedURL.isRegistered() ? "Y" : "N") + ")"); + statuses.add(protocol + "-" + (isServiceDiscovery ? "A" : "I") + "(" + + (registerStatedURL.isRegistered() ? "Y" : "N") + ")"); } // e.g. zookeeper-A(Y)/zookeeper-I(Y) return String.join("/", statuses.toArray(new String[0])); @@ -59,21 +62,23 @@ public class ServiceCheckUtils { for (Map.Entry> entry : invokerMap.entrySet()) { URL registryUrl = entry.getKey().getUrl(); boolean isServiceDiscovery = UrlUtils.isServiceDiscoveryURL(registryUrl); - String protocol = isServiceDiscovery ? registryUrl.getParameter(RegistryConstants.REGISTRY_KEY) : registryUrl.getProtocol(); + String protocol = isServiceDiscovery + ? registryUrl.getParameter(RegistryConstants.REGISTRY_KEY) + : registryUrl.getProtocol(); MigrationInvoker migrationInvoker = entry.getValue(); MigrationStep migrationStep = migrationInvoker.getMigrationStep(); String interfaceSize = Optional.ofNullable(migrationInvoker.getInvoker()) - .map(ClusterInvoker::getDirectory) - .map(Directory::getAllInvokers) - .map(List::size) - .map(String::valueOf) - .orElse("-"); + .map(ClusterInvoker::getDirectory) + .map(Directory::getAllInvokers) + .map(List::size) + .map(String::valueOf) + .orElse("-"); String applicationSize = Optional.ofNullable(migrationInvoker.getServiceDiscoveryInvoker()) - .map(ClusterInvoker::getDirectory) - .map(Directory::getAllInvokers) - .map(List::size) - .map(String::valueOf) - .orElse("-"); + .map(ClusterInvoker::getDirectory) + .map(Directory::getAllInvokers) + .map(List::size) + .map(String::valueOf) + .orElse("-"); String step; String size; switch (migrationStep) { diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/common/QosConstants.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/common/QosConstants.java index 96bd786693..73f84dacbc 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/common/QosConstants.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/common/QosConstants.java @@ -24,5 +24,4 @@ public interface QosConstants { String CLOSE = "close!"; String QOS_PERMISSION_CHECKER = "qosPermissionChecker"; - } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/legacy/LogTelnetHandler.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/legacy/LogTelnetHandler.java index 958c3696c9..6cfcdc0fa2 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/legacy/LogTelnetHandler.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/legacy/LogTelnetHandler.java @@ -55,7 +55,7 @@ public class LogTelnetHandler implements TelnetHandler { int showLogLength = Integer.parseInt(str[0]); if (file != null && file.exists()) { - try(FileInputStream fis = new FileInputStream(file)) { + try (FileInputStream fis = new FileInputStream(file)) { FileChannel filechannel = fis.getChannel(); size = filechannel.size(); ByteBuffer bb; @@ -68,12 +68,15 @@ public class LogTelnetHandler implements TelnetHandler { filechannel.read(bb, pos); } bb.flip(); - String content = new String(bb.array()).replace("<", "<") - .replace(">", ">").replace("\n", "

"); + String content = new String(bb.array()) + .replace("<", "<") + .replace(">", ">") + .replace("\n", "

"); buf.append("\r\ncontent:").append(content); - buf.append("\r\nmodified:").append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") - .format(new Date(file.lastModified()))); + buf.append("\r\nmodified:") + .append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") + .format(new Date(file.lastModified()))); buf.append("\r\nsize:").append(size).append("\r\n"); } catch (Exception e) { buf.append(e.getMessage()); @@ -83,9 +86,10 @@ public class LogTelnetHandler implements TelnetHandler { } } } - buf.append("\r\nCURRENT LOG LEVEL:").append(LoggerFactory.getLevel()).append("\r\nCURRENT LOG APPENDER:") + buf.append("\r\nCURRENT LOG LEVEL:") + .append(LoggerFactory.getLevel()) + .append("\r\nCURRENT LOG APPENDER:") .append(file == null ? "console" : file.getAbsolutePath()); return buf.toString(); } - } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/permission/DefaultAnonymousAccessPermissionChecker.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/permission/DefaultAnonymousAccessPermissionChecker.java index 61736f2247..d3644e338c 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/permission/DefaultAnonymousAccessPermissionChecker.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/permission/DefaultAnonymousAccessPermissionChecker.java @@ -21,31 +21,32 @@ import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.PermissionLevel; import org.apache.dubbo.qos.api.QosConfiguration; -import io.netty.channel.Channel; - import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.Arrays; import java.util.Optional; +import io.netty.channel.Channel; + public class DefaultAnonymousAccessPermissionChecker implements PermissionChecker { - public static final DefaultAnonymousAccessPermissionChecker INSTANCE = new DefaultAnonymousAccessPermissionChecker(); + public static final DefaultAnonymousAccessPermissionChecker INSTANCE = + new DefaultAnonymousAccessPermissionChecker(); @Override public boolean access(CommandContext commandContext, PermissionLevel defaultCmdRequiredPermissionLevel) { final InetAddress inetAddress = Optional.ofNullable(commandContext.getRemote()) - .map(Channel::remoteAddress) - .map(InetSocketAddress.class::cast) - .map(InetSocketAddress::getAddress) - .orElse(null); + .map(Channel::remoteAddress) + .map(InetSocketAddress.class::cast) + .map(InetSocketAddress::getAddress) + .orElse(null); QosConfiguration qosConfiguration = commandContext.getQosConfiguration(); String anonymousAllowCommands = qosConfiguration.getAnonymousAllowCommands(); - if (StringUtils.isNotEmpty(anonymousAllowCommands) && - Arrays.stream(anonymousAllowCommands.split(",")) - .filter(StringUtils::isNotEmpty) - .map(String::trim) - .anyMatch(cmd -> cmd.equals(commandContext.getCommandName()))) { + if (StringUtils.isNotEmpty(anonymousAllowCommands) + && Arrays.stream(anonymousAllowCommands.split(",")) + .filter(StringUtils::isNotEmpty) + .map(String::trim) + .anyMatch(cmd -> cmd.equals(commandContext.getCommandName()))) { return true; } @@ -54,9 +55,8 @@ public class DefaultAnonymousAccessPermissionChecker implements PermissionChecke // Local has private permission if (inetAddress != null && inetAddress.isLoopbackAddress()) { currentLevel = PermissionLevel.PRIVATE; - } else if (inetAddress != null && - qosConfiguration.getAcceptForeignIpWhitelistPredicate() - .test(inetAddress.getHostAddress())) { + } else if (inetAddress != null + && qosConfiguration.getAcceptForeignIpWhitelistPredicate().test(inetAddress.getHostAddress())) { currentLevel = PermissionLevel.PROTECTED; } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/impl/DeployerReadinessProbe.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/impl/DeployerReadinessProbe.java index 9f848b2e89..4121c399a7 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/impl/DeployerReadinessProbe.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/impl/DeployerReadinessProbe.java @@ -47,5 +47,4 @@ public class DeployerReadinessProbe implements ReadinessProbe { } return true; } - } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/impl/ProviderReadinessProbe.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/impl/ProviderReadinessProbe.java index 653d2b9e35..2a5afacf46 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/impl/ProviderReadinessProbe.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/impl/ProviderReadinessProbe.java @@ -51,9 +51,9 @@ public class ProviderReadinessProbe implements ReadinessProbe { continue; } hasService = true; - anyOnline = anyOnline || - providerModel.getStatedUrl().isEmpty() || - providerModel.getStatedUrl().stream().anyMatch(ProviderModel.RegisterStatedURL::isRegistered); + anyOnline = anyOnline + || providerModel.getStatedUrl().isEmpty() + || providerModel.getStatedUrl().stream().anyMatch(ProviderModel.RegisterStatedURL::isRegistered); } // no service => check pass diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/protocol/QosProtocolWrapper.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/protocol/QosProtocolWrapper.java index a39e555706..d33ad30792 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/protocol/QosProtocolWrapper.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/protocol/QosProtocolWrapper.java @@ -106,9 +106,9 @@ public class QosProtocolWrapper implements Protocol, ScopeModelAware { boolean qosEnable = url.getParameter(QOS_ENABLE, true); if (!qosEnable) { - logger.info("qos won't be started because it is disabled. " + - "Please check dubbo.application.qos.enable is configured either in system property, " + - "dubbo.properties or XML/spring-boot configuration."); + logger.info("qos won't be started because it is disabled. " + + "Please check dubbo.application.qos.enable is configured either in system property, " + + "dubbo.properties or XML/spring-boot configuration."); return; } @@ -116,7 +116,8 @@ public class QosProtocolWrapper implements Protocol, ScopeModelAware { int port = url.getParameter(QOS_PORT, QosConstants.DEFAULT_PORT); boolean acceptForeignIp = Boolean.parseBoolean(url.getParameter(ACCEPT_FOREIGN_IP, "false")); String acceptForeignIpWhitelist = url.getParameter(ACCEPT_FOREIGN_IP_WHITELIST, StringUtils.EMPTY_STRING); - String anonymousAccessPermissionLevel = url.getParameter(ANONYMOUS_ACCESS_PERMISSION_LEVEL, PermissionLevel.PUBLIC.name()); + String anonymousAccessPermissionLevel = + url.getParameter(ANONYMOUS_ACCESS_PERMISSION_LEVEL, PermissionLevel.PUBLIC.name()); String anonymousAllowCommands = url.getParameter(ANONYMOUS_ACCESS_ALLOW_COMMANDS, StringUtils.EMPTY_STRING); Server server = frameworkModel.getBeanFactory().getBean(Server.class); diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/DubboLogo.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/DubboLogo.java index 9ef98b37a1..e640e65501 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/DubboLogo.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/DubboLogo.java @@ -18,8 +18,8 @@ package org.apache.dubbo.qos.server; public class DubboLogo { public static final String DUBBO = - " ___ __ __ ___ ___ ____ " + System.lineSeparator() + - " / _ \\ / / / // _ ) / _ ) / __ \\ " + System.lineSeparator() + - " / // // /_/ // _ |/ _ |/ /_/ / " + System.lineSeparator() + - "/____/ \\____//____//____/ \\____/ " + System.lineSeparator(); + " ___ __ __ ___ ___ ____ " + System.lineSeparator() + " / _ \\ / / / // _ ) / _ ) / __ \\ " + + System.lineSeparator() + " / // // /_/ // _ |/ _ |/ /_/ / " + + System.lineSeparator() + "/____/ \\____//____//____/ \\____/ " + + System.lineSeparator(); } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/Server.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/Server.java index 12c02ccea7..c7db1f3b74 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/Server.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/Server.java @@ -24,6 +24,8 @@ import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.qos.server.handler.QosProcessHandler; import org.apache.dubbo.rpc.model.FrameworkModel; +import java.util.concurrent.atomic.AtomicBoolean; + import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; @@ -33,8 +35,6 @@ import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.util.concurrent.DefaultThreadFactory; -import java.util.concurrent.atomic.AtomicBoolean; - /** * A server serves for both telnet access and http access *
    @@ -102,15 +102,16 @@ public class Server { @Override protected void initChannel(Channel ch) throws Exception { - ch.pipeline().addLast(new QosProcessHandler(frameworkModel, - QosConfiguration.builder() - .welcome(welcome) - .acceptForeignIp(acceptForeignIp) - .acceptForeignIpWhitelist(acceptForeignIpWhitelist) - .anonymousAccessPermissionLevel(anonymousAccessPermissionLevel) - .anonymousAllowCommands(anonymousAllowCommands) - .build() - )); + ch.pipeline() + .addLast(new QosProcessHandler( + frameworkModel, + QosConfiguration.builder() + .welcome(welcome) + .acceptForeignIp(acceptForeignIp) + .acceptForeignIpWhitelist(acceptForeignIpWhitelist) + .anonymousAccessPermissionLevel(anonymousAccessPermissionLevel) + .anonymousAllowCommands(anonymousAllowCommands) + .build())); } }); try { diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/ForeignHostPermitHandler.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/ForeignHostPermitHandler.java index b9e86242a3..b33803a988 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/ForeignHostPermitHandler.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/ForeignHostPermitHandler.java @@ -16,14 +16,14 @@ */ package org.apache.dubbo.qos.server.handler; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.util.function.Predicate; - import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.qos.common.QosConstants; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.util.function.Predicate; + import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; @@ -72,9 +72,9 @@ public class ForeignHostPermitHandler extends ChannelHandlerAdapter { return; } - - ByteBuf cb = Unpooled.wrappedBuffer((QosConstants.BR_STR + "Foreign Ip Not Permitted, Consider Config It In Whitelist." - + QosConstants.BR_STR).getBytes()); + ByteBuf cb = Unpooled.wrappedBuffer((QosConstants.BR_STR + + "Foreign Ip Not Permitted, Consider Config It In Whitelist." + QosConstants.BR_STR) + .getBytes()); ctx.writeAndFlush(cb).addListener(ChannelFutureListener.CLOSE); } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/HttpProcessHandler.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/HttpProcessHandler.java index ef2ec861dd..d23a4acd3a 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/HttpProcessHandler.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/HttpProcessHandler.java @@ -19,12 +19,12 @@ package org.apache.dubbo.qos.server.handler; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.qos.api.CommandContext; +import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.qos.command.CommandExecutor; import org.apache.dubbo.qos.command.DefaultCommandExecutor; +import org.apache.dubbo.qos.command.decoder.HttpCommandDecoder; import org.apache.dubbo.qos.command.exception.NoSuchCommandException; import org.apache.dubbo.qos.command.exception.PermissionDenyException; -import org.apache.dubbo.qos.command.decoder.HttpCommandDecoder; -import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.rpc.model.FrameworkModel; import io.netty.buffer.Unpooled; @@ -40,8 +40,8 @@ import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_COMMAND_NOT_FOUND; -import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_UNEXPECTED_EXCEPTION; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PERMISSION_DENY_EXCEPTION; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_UNEXPECTED_EXCEPTION; /** * Parse HttpRequest for uri and parameters @@ -67,8 +67,8 @@ public class HttpProcessHandler extends SimpleChannelInboundHandler } private static FullHttpResponse http(int httpCode, String result) { - FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(httpCode) - , Unpooled.wrappedBuffer(result.getBytes())); + FullHttpResponse response = new DefaultFullHttpResponse( + HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(httpCode), Unpooled.wrappedBuffer(result.getBytes())); HttpHeaders httpHeaders = response.headers(); httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, "text/plain"); httpHeaders.set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); @@ -76,7 +76,8 @@ public class HttpProcessHandler extends SimpleChannelInboundHandler } private static FullHttpResponse http(int httpCode) { - FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(httpCode)); + FullHttpResponse response = + new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(httpCode)); HttpHeaders httpHeaders = response.headers(); httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, "text/plain"); httpHeaders.set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); @@ -104,15 +105,24 @@ public class HttpProcessHandler extends SimpleChannelInboundHandler FullHttpResponse response = http(404); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } catch (PermissionDenyException ex) { - log.error(QOS_PERMISSION_DENY_EXCEPTION, "", "", "permission deny to access command: " + commandContext, ex); + log.error( + QOS_PERMISSION_DENY_EXCEPTION, + "", + "", + "permission deny to access command: " + commandContext, + ex); FullHttpResponse response = http(403); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } catch (Exception qosEx) { - log.error(QOS_UNEXPECTED_EXCEPTION, "", "", "execute commandContext: " + commandContext + " got exception", qosEx); + log.error( + QOS_UNEXPECTED_EXCEPTION, + "", + "", + "execute commandContext: " + commandContext + " got exception", + qosEx); FullHttpResponse response = http(500, qosEx.getMessage()); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } } } - } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/QosProcessHandler.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/QosProcessHandler.java index 40739f8022..93b9f1d663 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/QosProcessHandler.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/QosProcessHandler.java @@ -20,6 +20,9 @@ import org.apache.dubbo.common.utils.ExecutorUtil; import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.rpc.model.FrameworkModel; +import java.util.List; +import java.util.concurrent.TimeUnit; + import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; @@ -35,9 +38,6 @@ import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.CharsetUtil; import io.netty.util.concurrent.ScheduledFuture; -import java.util.List; -import java.util.concurrent.TimeUnit; - public class QosProcessHandler extends ByteToMessageDecoder { private ScheduledFuture welcomeFuture; @@ -55,13 +55,17 @@ public class QosProcessHandler extends ByteToMessageDecoder { @Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { - welcomeFuture = ctx.executor().schedule(() -> { - final String welcome = qosConfiguration.getWelcome(); - if (welcome != null) { - ctx.write(Unpooled.wrappedBuffer(welcome.getBytes())); - ctx.writeAndFlush(Unpooled.wrappedBuffer(PROMPT.getBytes())); - } - }, 500, TimeUnit.MILLISECONDS); + welcomeFuture = ctx.executor() + .schedule( + () -> { + final String welcome = qosConfiguration.getWelcome(); + if (welcome != null) { + ctx.write(Unpooled.wrappedBuffer(welcome.getBytes())); + ctx.writeAndFlush(Unpooled.wrappedBuffer(PROMPT.getBytes())); + } + }, + 500, + TimeUnit.MILLISECONDS); } @Override diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/TelnetIdleEventHandler.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/TelnetIdleEventHandler.java index c12f738d59..8927d8cd74 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/TelnetIdleEventHandler.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/TelnetIdleEventHandler.java @@ -38,5 +38,4 @@ public class TelnetIdleEventHandler extends ChannelDuplexHandler { super.userEventTriggered(ctx, evt); } } - } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/TelnetProcessHandler.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/TelnetProcessHandler.java index e2b240cc48..3759e80634 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/TelnetProcessHandler.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/TelnetProcessHandler.java @@ -20,13 +20,13 @@ import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.qos.api.CommandContext; +import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.qos.command.CommandExecutor; import org.apache.dubbo.qos.command.DefaultCommandExecutor; +import org.apache.dubbo.qos.command.decoder.TelnetCommandDecoder; import org.apache.dubbo.qos.command.exception.NoSuchCommandException; import org.apache.dubbo.qos.command.exception.PermissionDenyException; -import org.apache.dubbo.qos.command.decoder.TelnetCommandDecoder; import org.apache.dubbo.qos.common.QosConstants; -import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.rpc.model.FrameworkModel; import io.netty.channel.ChannelFutureListener; @@ -34,8 +34,8 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_COMMAND_NOT_FOUND; -import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_UNEXPECTED_EXCEPTION; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PERMISSION_DENY_EXCEPTION; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_UNEXPECTED_EXCEPTION; /** * Telnet process handler @@ -76,11 +76,17 @@ public class TelnetProcessHandler extends SimpleChannelInboundHandler { } catch (PermissionDenyException ex) { ctx.writeAndFlush(msg + " :permission deny"); ctx.writeAndFlush(QosConstants.BR_STR + QosProcessHandler.PROMPT); - log.error(QOS_PERMISSION_DENY_EXCEPTION, "", "", "permission deny to access command " + commandContext, ex); + log.error( + QOS_PERMISSION_DENY_EXCEPTION, + "", + "", + "permission deny to access command " + commandContext, + ex); } catch (Exception ex) { ctx.writeAndFlush(msg + " :fail to execute commandContext by " + ex.getMessage()); ctx.writeAndFlush(QosConstants.BR_STR + QosProcessHandler.PROMPT); - log.error(QOS_UNEXPECTED_EXCEPTION, "", "", "execute commandContext got exception " + commandContext, ex); + log.error( + QOS_UNEXPECTED_EXCEPTION, "", "", "execute commandContext got exception " + commandContext, ex); } } } @@ -88,5 +94,4 @@ public class TelnetProcessHandler extends SimpleChannelInboundHandler { private String getByeLabel() { return "BYE!\n"; } - } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TComponent.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TComponent.java index 12aca73c12..3af0cdd2d4 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TComponent.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TComponent.java @@ -25,5 +25,4 @@ public interface TComponent { * render */ String rendering(); - } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TKv.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TKv.java index 483b3f63db..7deed67717 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TKv.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TKv.java @@ -28,21 +28,19 @@ public class TKv implements TComponent { private final TTable tTable; public TKv() { - this.tTable = new TTable(new TTable.ColumnDefine[]{ - new TTable.ColumnDefine(TTable.Align.RIGHT), - new TTable.ColumnDefine(TTable.Align.RIGHT), - new TTable.ColumnDefine(TTable.Align.LEFT) - }) + this.tTable = new TTable(new TTable.ColumnDefine[] { + new TTable.ColumnDefine(TTable.Align.RIGHT), + new TTable.ColumnDefine(TTable.Align.RIGHT), + new TTable.ColumnDefine(TTable.Align.LEFT) + }) .padding(0); this.tTable.getBorder().set(TTable.Border.BORDER_NON); } public TKv(TTable.ColumnDefine keyColumnDefine, TTable.ColumnDefine valueColumnDefine) { - this.tTable = new TTable(new TTable.ColumnDefine[]{ - keyColumnDefine, - new TTable.ColumnDefine(TTable.Align.RIGHT), - valueColumnDefine - }) + this.tTable = new TTable(new TTable.ColumnDefine[] { + keyColumnDefine, new TTable.ColumnDefine(TTable.Align.RIGHT), valueColumnDefine + }) .padding(0); this.tTable.getBorder().set(TTable.Border.BORDER_NON); } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TLadder.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TLadder.java index 0f0ef480fc..f89996d0ef 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TLadder.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TLadder.java @@ -37,7 +37,6 @@ public class TLadder implements TComponent { private final List items = new LinkedList(); - @Override public String rendering() { final StringBuilder ladderSB = new StringBuilder(); @@ -46,22 +45,18 @@ public class TLadder implements TComponent { // no separator is required for the first item if (deep == 0) { - ladderSB - .append(item) - .append(System.lineSeparator()); + ladderSB.append(item).append(System.lineSeparator()); } // need separator for others else { - ladderSB - .append(repeat(STEP_CHAR, deep * INDENT_STEP)) + ladderSB.append(repeat(STEP_CHAR, deep * INDENT_STEP)) .append(LADDER_CHAR) .append(item) .append(System.lineSeparator()); } deep++; - } return ladderSB.toString(); } @@ -73,5 +68,4 @@ public class TLadder implements TComponent { items.add(item); return this; } - } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTable.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTable.java index b3bd54450a..f96e857184 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTable.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTable.java @@ -44,9 +44,7 @@ public class TTable implements TComponent { private int padding; public TTable(ColumnDefine[] columnDefineArray) { - this.columnDefineArray = null == columnDefineArray - ? new ColumnDefine[0] - : columnDefineArray; + this.columnDefineArray = null == columnDefineArray ? new ColumnDefine[0] : columnDefineArray; } public TTable(int columnNum) { @@ -56,7 +54,6 @@ public class TTable implements TComponent { } } - @Override public String rendering() { final StringBuilder tableSB = new StringBuilder(); @@ -74,34 +71,27 @@ public class TTable implements TComponent { final boolean isLastRow = rowIndex == rowCount - 1; // print first separation line - if (isFirstRow - && border.has(Border.BORDER_OUTER_TOP)) { + if (isFirstRow && border.has(Border.BORDER_OUTER_TOP)) { tableSB.append(drawSeparationLine(widthCacheArray)).append(System.lineSeparator()); } // print inner separation lines - if (!isFirstRow - && border.has(Border.BORDER_INNER_H)) { + if (!isFirstRow && border.has(Border.BORDER_INNER_H)) { tableSB.append(drawSeparationLine(widthCacheArray)).append(System.lineSeparator()); } // draw one line tableSB.append(drawRow(widthCacheArray, rowIndex)); - // print ending separation line - if (isLastRow - && border.has(Border.BORDER_OUTER_BOTTOM)) { + if (isLastRow && border.has(Border.BORDER_OUTER_BOTTOM)) { tableSB.append(drawSeparationLine(widthCacheArray)).append(System.lineSeparator()); } - } - return tableSB.toString(); } - private String drawRow(int[] widthCacheArray, int rowIndex) { final StringBuilder rowSB = new StringBuilder(); @@ -115,23 +105,19 @@ public class TTable implements TComponent { for (int colIndex = 0; colIndex < getColumnCount(); colIndex++) { - final int width = widthCacheArray[colIndex]; final boolean isFirstColOfRow = colIndex == 0; final boolean isLastColOfRow = colIndex == widthCacheArray.length - 1; final String borderChar; - if (isFirstColOfRow - && border.has(Border.BORDER_OUTER_LEFT)) { + if (isFirstColOfRow && border.has(Border.BORDER_OUTER_LEFT)) { borderChar = "|"; - } else if (!isFirstColOfRow - && border.has(Border.BORDER_INNER_V)) { + } else if (!isFirstColOfRow && border.has(Border.BORDER_INNER_V)) { borderChar = "|"; } else { borderChar = EMPTY_STRING; } - if (null == scannerArray[colIndex]) { scannerArray[colIndex] = new Scanner( new StringReader(wrap(getData(rowIndex, columnDefineArray[colIndex]), width))); @@ -159,7 +145,6 @@ public class TTable implements TComponent { } segmentSB.append(System.lineSeparator()); } - } if (hasNextLine) { @@ -176,13 +161,10 @@ public class TTable implements TComponent { } } } - } private String getData(int rowIndex, ColumnDefine columnDefine) { - return columnDefine.getRowCount() <= rowIndex - ? EMPTY_STRING - : columnDefine.rows.get(rowIndex); + return columnDefine.getRowCount() <= rowIndex ? EMPTY_STRING : columnDefine.rows.get(rowIndex); } private String getDataFormat(ColumnDefine columnDefine, int width, String data) { @@ -245,23 +227,19 @@ public class TTable implements TComponent { final boolean isFirstCol = colIndex == 0; final boolean isLastCol = colIndex == lastCol; - if (isFirstCol - && border.has(Border.BORDER_OUTER_LEFT)) { + if (isFirstCol && border.has(Border.BORDER_OUTER_LEFT)) { separationLineSB.append('+'); } - if (!isFirstCol - && border.has(Border.BORDER_INNER_V)) { + if (!isFirstCol && border.has(Border.BORDER_INNER_V)) { separationLineSB.append('+'); } separationLineSB.append(repeat("-", width + 2 * padding)); - if (isLastCol - && border.has(Border.BORDER_OUTER_RIGHT)) { + if (isLastCol && border.has(Border.BORDER_OUTER_RIGHT)) { separationLineSB.append('+'); } - } return separationLineSB.toString(); } @@ -274,8 +252,7 @@ public class TTable implements TComponent { if (null != columnDataArray) { for (int index = 0; index < columnDefineArray.length; index++) { final ColumnDefine columnDefine = columnDefineArray[index]; - if (index < columnDataArray.length - && null != columnDataArray[index]) { + if (index < columnDataArray.length && null != columnDataArray[index]) { columnDefine.rows.add(replaceTab(columnDataArray[index].toString())); } else { columnDefine.rows.add(EMPTY_STRING); @@ -286,7 +263,6 @@ public class TTable implements TComponent { return this; } - /** * alignment */ @@ -376,7 +352,6 @@ public class TTable implements TComponent { public int getRowCount() { return rows.size(); } - } /** @@ -398,7 +373,6 @@ public class TTable implements TComponent { return columnDefineArray.length; } - /** * replace tab to four spaces * @@ -476,7 +450,8 @@ public class TTable implements TComponent { /** * outer border */ - public static final int BORDER_OUTER = BORDER_OUTER_TOP | BORDER_OUTER_BOTTOM | BORDER_OUTER_LEFT | BORDER_OUTER_RIGHT; + public static final int BORDER_OUTER = + BORDER_OUTER_TOP | BORDER_OUTER_BOTTOM | BORDER_OUTER_LEFT | BORDER_OUTER_RIGHT; /** * inner border @@ -533,10 +508,8 @@ public class TTable implements TComponent { public Border remove(int border) { return set(get() ^ border); } - } - public static String wrap(String string, int width) { final StringBuilder sb = new StringBuilder(); final char[] buffer = string.toCharArray(); @@ -558,9 +531,7 @@ public class TTable implements TComponent { } sb.append(c); - } return sb.toString(); } - } diff --git a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTree.java b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTree.java index 274d0be8d7..6b599da45a 100644 --- a/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTree.java +++ b/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTree.java @@ -45,14 +45,12 @@ public class TTree implements TComponent { // current node private Node current; - public TTree(boolean isPrintCost, String title) { this.root = new Node(title).markBegin().markEnd(); this.current = root; this.isPrintCost = isPrintCost; } - @Override public String rendering() { @@ -71,9 +69,10 @@ public class TTree implements TComponent { if (hasChild) { treeSB.append('+'); } - if (isPrintCost - && !node.isRoot()) { - final String costPrefix = String.format("[%s,%sms]", (node.endTimestamp - root.beginTimestamp), (node.endTimestamp - node.beginTimestamp)); + if (isPrintCost && !node.isRoot()) { + final String costPrefix = String.format( + "[%s,%sms]", + (node.endTimestamp - root.beginTimestamp), (node.endTimestamp - node.beginTimestamp)); costPrefixLength = length(costPrefix); treeSB.append(costPrefix); } @@ -94,9 +93,7 @@ public class TTree implements TComponent { } } } - } - }); return treeSB.toString(); @@ -112,13 +109,7 @@ public class TTree implements TComponent { for (int index = 0; index < size; index++) { final boolean isLastFlag = index == size - 1; final String currentPrefix = isLast ? prefix + STEP_EMPTY_BOARD : prefix + STEP_HAS_BOARD; - recursive( - deep + 1, - isLastFlag, - currentPrefix, - node.children.get(index), - callback - ); + recursive(deep + 1, isLastFlag, currentPrefix, node.children.get(index), callback); } } } @@ -172,7 +163,6 @@ public class TTree implements TComponent { return this; } - /** * tree node */ @@ -250,17 +240,13 @@ public class TTree implements TComponent { endTimestamp = currentTimeMillis(); return this; } - } - /** * callback interface for recursive visit */ private interface Callback { void callback(int deep, boolean isLast, String prefix, Node node); - } - } diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/CommandContextFactoryTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/CommandContextFactoryTest.java index 31ae32f3d7..fd75d83e84 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/CommandContextFactoryTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/CommandContextFactoryTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,10 +14,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.qos.command; import org.apache.dubbo.qos.api.CommandContext; + import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; @@ -30,7 +30,7 @@ class CommandContextFactoryTest { void testNewInstance() { CommandContext context = CommandContextFactory.newInstance("test"); assertThat(context.getCommandName(), equalTo("test")); - context = CommandContextFactory.newInstance("command", new String[]{"hello"}, true); + context = CommandContextFactory.newInstance("command", new String[] {"hello"}, true); assertThat(context.getCommandName(), equalTo("command")); assertThat(context.getArgs(), Matchers.arrayContaining("hello")); assertTrue(context.isHttp()); diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/CommandContextTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/CommandContextTest.java index 13d2cce945..a3ae96b5b9 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/CommandContextTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/CommandContextTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,11 +14,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.qos.command; -import io.netty.channel.Channel; import org.apache.dubbo.qos.api.CommandContext; + +import io.netty.channel.Channel; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -32,7 +32,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; class CommandContextTest { @Test void test() { - CommandContext context = new CommandContext("test", new String[]{"hello"}, true); + CommandContext context = new CommandContext("test", new String[] {"hello"}, true); Object request = new Object(); context.setOriginRequest(request); Channel channel = Mockito.mock(Channel.class); @@ -46,7 +46,7 @@ class CommandContextTest { context = new CommandContext("command"); context.setRemote(channel); context.setOriginRequest(request); - context.setArgs(new String[]{"world"}); + context.setArgs(new String[] {"world"}); context.setHttp(false); assertThat(context.getCommandName(), equalTo("command")); assertThat(context.getArgs(), arrayContaining("world")); diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/DefaultCommandExecutorTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/DefaultCommandExecutorTest.java index aa2d727f24..24305ce972 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/DefaultCommandExecutorTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/DefaultCommandExecutorTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.qos.command; import org.apache.dubbo.qos.api.CommandContext; @@ -22,6 +21,7 @@ import org.apache.dubbo.qos.api.PermissionLevel; import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.qos.command.exception.NoSuchCommandException; import org.apache.dubbo.rpc.model.FrameworkModel; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -40,10 +40,11 @@ class DefaultCommandExecutorTest { @Test void testExecute2() throws Exception { DefaultCommandExecutor executor = new DefaultCommandExecutor(FrameworkModel.defaultModel()); - final CommandContext commandContext = CommandContextFactory.newInstance("greeting", new String[]{"dubbo"}, false); + final CommandContext commandContext = + CommandContextFactory.newInstance("greeting", new String[] {"dubbo"}, false); commandContext.setQosConfiguration(QosConfiguration.builder() - .anonymousAccessPermissionLevel(PermissionLevel.PROTECTED.name()) - .build()); + .anonymousAccessPermissionLevel(PermissionLevel.PROTECTED.name()) + .build()); String result = executor.execute(commandContext); assertThat(result, equalTo("greeting dubbo")); } @@ -51,7 +52,7 @@ class DefaultCommandExecutorTest { @Test void shouldNotThrowPermissionDenyException_GivenPermissionConfigAndMatchDefaultPUBLICCmdPermissionLevel() { DefaultCommandExecutor executor = new DefaultCommandExecutor(FrameworkModel.defaultModel()); - final CommandContext commandContext = CommandContextFactory.newInstance("live", new String[]{"dubbo"}, false); + final CommandContext commandContext = CommandContextFactory.newInstance("live", new String[] {"dubbo"}, false); commandContext.setQosConfiguration(QosConfiguration.builder().build()); Assertions.assertDoesNotThrow(() -> executor.execute(commandContext)); } @@ -59,9 +60,10 @@ class DefaultCommandExecutorTest { @Test void shouldNotThrowPermissionDenyException_GivenPermissionConfigAndNotMatchCmdPermissionLevel() { DefaultCommandExecutor executor = new DefaultCommandExecutor(FrameworkModel.defaultModel()); - final CommandContext commandContext = CommandContextFactory.newInstance("live", new String[]{"dubbo"}, false); + final CommandContext commandContext = CommandContextFactory.newInstance("live", new String[] {"dubbo"}, false); // 1 PROTECTED - commandContext.setQosConfiguration(QosConfiguration.builder().anonymousAccessPermissionLevel("1").build()); + commandContext.setQosConfiguration( + QosConfiguration.builder().anonymousAccessPermissionLevel("1").build()); Assertions.assertDoesNotThrow(() -> executor.execute(commandContext)); } } diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/GreetingCommand.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/GreetingCommand.java index 6ad804bfc6..9780dfb642 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/GreetingCommand.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/GreetingCommand.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -14,16 +14,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.qos.command; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.qos.api.BaseCommand; -import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.Cmd; +import org.apache.dubbo.qos.api.CommandContext; - -@Cmd(name = "greeting", summary = "greeting message", example = {"greeting dubbo",}) +@Cmd( + name = "greeting", + summary = "greeting message", + example = { + "greeting dubbo", + }) public class GreetingCommand implements BaseCommand { @Override public String execute(CommandContext commandContext, String[] args) { diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/decoder/HttpCommandDecoderTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/decoder/HttpCommandDecoderTest.java index 58100090e4..a0a8dc9bf9 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/decoder/HttpCommandDecoderTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/decoder/HttpCommandDecoderTest.java @@ -18,6 +18,8 @@ package org.apache.dubbo.qos.command.decoder; import org.apache.dubbo.qos.api.CommandContext; +import java.nio.charset.StandardCharsets; + import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.FullHttpRequest; @@ -26,8 +28,6 @@ import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequest; import org.junit.jupiter.api.Test; -import java.nio.charset.StandardCharsets; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.arrayContaining; import static org.hamcrest.Matchers.equalTo; diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ChangeTelnetTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ChangeTelnetTest.java index b761a62aeb..6a8b67531d 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ChangeTelnetTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ChangeTelnetTest.java @@ -66,7 +66,8 @@ class ChangeTelnetTest { mockChannel = mock(Channel.class); mockInvoker = mock(Invoker.class); - given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)).willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); + given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) + .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); mockChannel.attr(ChangeTelnet.SERVICE_KEY).set("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService"); given(mockCommandContext.getRemote()).willReturn(mockChannel); given(mockInvoker.getInterface()).willReturn(DemoService.class); @@ -81,23 +82,31 @@ class ChangeTelnetTest { @Test void testChangeSimpleName() { - ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(DubboProtocol.NAME).export(mockInvoker); - String result = change.execute(mockCommandContext, new String[]{"DemoService"}); + ExtensionLoader.getExtensionLoader(Protocol.class) + .getExtension(DubboProtocol.NAME) + .export(mockInvoker); + String result = change.execute(mockCommandContext, new String[] {"DemoService"}); assertEquals("Used the DemoService as default.\r\nYou can cancel default service by command: cd /", result); } @Test void testChangeName() { - ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(DubboProtocol.NAME).export(mockInvoker); - String result = change.execute(mockCommandContext, new String[]{"org.apache.dubbo.qos.legacy.service.DemoService"}); - assertEquals("Used the org.apache.dubbo.qos.legacy.service.DemoService as default.\r\nYou can cancel default service by command: cd /", - result); + ExtensionLoader.getExtensionLoader(Protocol.class) + .getExtension(DubboProtocol.NAME) + .export(mockInvoker); + String result = + change.execute(mockCommandContext, new String[] {"org.apache.dubbo.qos.legacy.service.DemoService"}); + assertEquals( + "Used the org.apache.dubbo.qos.legacy.service.DemoService as default.\r\nYou can cancel default service by command: cd /", + result); } @Test void testChangePath() { - ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(DubboProtocol.NAME).export(mockInvoker); - String result = change.execute(mockCommandContext, new String[]{"demo"}); + ExtensionLoader.getExtensionLoader(Protocol.class) + .getExtension(DubboProtocol.NAME) + .export(mockInvoker); + String result = change.execute(mockCommandContext, new String[] {"demo"}); assertEquals("Used the demo as default.\r\nYou can cancel default service by command: cd /", result); } @@ -109,19 +118,19 @@ class ChangeTelnetTest { @Test void testChangeServiceNotExport() { - String result = change.execute(mockCommandContext, new String[]{"demo"}); + String result = change.execute(mockCommandContext, new String[] {"demo"}); assertEquals("No such service demo", result); } @Test void testChangeCancel() { - String result = change.execute(mockCommandContext, new String[]{".."}); + String result = change.execute(mockCommandContext, new String[] {".."}); assertEquals("Cancelled default service org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.", result); } @Test void testChangeCancel2() { - String result = change.execute(mockCommandContext, new String[]{"/"}); + String result = change.execute(mockCommandContext, new String[] {"/"}); assertEquals("Cancelled default service org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.", result); } } diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/CountTelnetTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/CountTelnetTest.java index 6e32cb3dd4..0777e39546 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/CountTelnetTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/CountTelnetTest.java @@ -29,14 +29,14 @@ import org.apache.dubbo.rpc.RpcStatus; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.LinkedList; import java.util.List; import java.util.concurrent.CountDownLatch; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.BDDMockito.given; @@ -64,7 +64,6 @@ class CountTelnetTest { given(mockCommandContext.getRemote()).willReturn(mockChannel); given(mockInvoker.getInterface()).willReturn(DemoService.class); given(mockInvoker.getUrl()).willReturn(url); - } @AfterEach @@ -77,9 +76,11 @@ class CountTelnetTest { @Test void test() throws Exception { String methodName = "sayHello"; - String[] args = new String[]{"org.apache.dubbo.qos.legacy.service.DemoService", "sayHello", "1"}; + String[] args = new String[] {"org.apache.dubbo.qos.legacy.service.DemoService", "sayHello", "1"}; - ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(DubboProtocol.NAME).export(mockInvoker); + ExtensionLoader.getExtensionLoader(Protocol.class) + .getExtension(DubboProtocol.NAME) + .export(mockInvoker); RpcStatus.beginCount(url, methodName); RpcStatus.endCount(url, methodName, 10L, true); count.execute(mockCommandContext, args); @@ -90,12 +91,11 @@ class CountTelnetTest { sb.append(o.toString()); } - assertThat(sb.toString(), containsString(buildTable(methodName, - 10, 10, "1", "0", "0"))); + assertThat(sb.toString(), containsString(buildTable(methodName, 10, 10, "1", "0", "0"))); } - public static String buildTable(String methodName, long averageElapsed, - long maxElapsed, String total, String failed, String active) { + public static String buildTable( + String methodName, long averageElapsed, long maxElapsed, String total, String failed, String active) { List header = new LinkedList<>(); header.add("method"); header.add("total"); @@ -117,5 +117,4 @@ class CountTelnetTest { return TelnetUtils.toTable(header, table); } - } diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/GetConfigTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/GetConfigTest.java index 77dbf92695..0d1c2edd19 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/GetConfigTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/GetConfigTest.java @@ -40,14 +40,16 @@ import org.junit.jupiter.api.Test; class GetConfigTest { @Test - void testAll(){ + void testAll() { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel1 = frameworkModel.newApplication(); applicationModel1.getApplicationConfigManager().setApplication(new ApplicationConfig("app1")); applicationModel1.getApplicationConfigManager().addProtocol(new ProtocolConfig("dubbo", 12345)); applicationModel1.getApplicationConfigManager().addRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181")); - applicationModel1.getApplicationConfigManager().addMetadataReport(new MetadataReportConfig("zookeeper://127.0.0.1:2181")); + applicationModel1 + .getApplicationConfigManager() + .addMetadataReport(new MetadataReportConfig("zookeeper://127.0.0.1:2181")); ConfigCenterConfig configCenterConfig = new ConfigCenterConfig(); configCenterConfig.setAddress("zookeeper://127.0.0.1:2181"); applicationModel1.getApplicationConfigManager().addConfigCenter(configCenterConfig); @@ -73,14 +75,16 @@ class GetConfigTest { } @Test - void testFilter1(){ + void testFilter1() { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel1 = frameworkModel.newApplication(); applicationModel1.getApplicationConfigManager().setApplication(new ApplicationConfig("app1")); applicationModel1.getApplicationConfigManager().addProtocol(new ProtocolConfig("dubbo", 12345)); applicationModel1.getApplicationConfigManager().addRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181")); - applicationModel1.getApplicationConfigManager().addMetadataReport(new MetadataReportConfig("zookeeper://127.0.0.1:2181")); + applicationModel1 + .getApplicationConfigManager() + .addMetadataReport(new MetadataReportConfig("zookeeper://127.0.0.1:2181")); ConfigCenterConfig configCenterConfig = new ConfigCenterConfig(); configCenterConfig.setAddress("zookeeper://127.0.0.1:2181"); applicationModel1.getApplicationConfigManager().addConfigCenter(configCenterConfig); @@ -102,18 +106,21 @@ class GetConfigTest { CommandContext commandContext = new CommandContext("getConfig"); commandContext.setHttp(true); - Assertions.assertNotNull(new GetConfig(frameworkModel).execute(commandContext, new String[]{"ApplicationConfig"})); + Assertions.assertNotNull( + new GetConfig(frameworkModel).execute(commandContext, new String[] {"ApplicationConfig"})); } @Test - void testFilter2(){ + void testFilter2() { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel1 = frameworkModel.newApplication(); applicationModel1.getApplicationConfigManager().setApplication(new ApplicationConfig("app1")); applicationModel1.getApplicationConfigManager().addProtocol(new ProtocolConfig("dubbo", 12345)); applicationModel1.getApplicationConfigManager().addRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181")); - applicationModel1.getApplicationConfigManager().addMetadataReport(new MetadataReportConfig("zookeeper://127.0.0.1:2181")); + applicationModel1 + .getApplicationConfigManager() + .addMetadataReport(new MetadataReportConfig("zookeeper://127.0.0.1:2181")); ConfigCenterConfig configCenterConfig = new ConfigCenterConfig(); configCenterConfig.setAddress("zookeeper://127.0.0.1:2181"); applicationModel1.getApplicationConfigManager().addConfigCenter(configCenterConfig); @@ -135,6 +142,7 @@ class GetConfigTest { CommandContext commandContext = new CommandContext("getConfig"); commandContext.setHttp(true); - Assertions.assertNotNull(new GetConfig(frameworkModel).execute(commandContext, new String[]{"ProtocolConfig", "dubbo"})); + Assertions.assertNotNull( + new GetConfig(frameworkModel).execute(commandContext, new String[] {"ProtocolConfig", "dubbo"})); } } diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/HelpTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/HelpTest.java index e5db43ec08..913a252e9d 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/HelpTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/HelpTest.java @@ -41,7 +41,7 @@ class HelpTest { @Test void testGreeting() { Help help = new Help(FrameworkModel.defaultModel()); - String output = help.execute(Mockito.mock(CommandContext.class), new String[]{"greeting"}); + String output = help.execute(Mockito.mock(CommandContext.class), new String[] {"greeting"}); assertThat(output, containsString("COMMAND NAME")); assertThat(output, containsString("greeting")); assertThat(output, containsString("EXAMPLE")); diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/InvokeTelnetTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/InvokeTelnetTest.java index bb534ae6a2..84b0cc076a 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/InvokeTelnetTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/InvokeTelnetTest.java @@ -71,19 +71,21 @@ class InvokeTelnetTest { @Test void testInvokeWithoutServicePrefixAndWithoutDefaultService() throws RemotingException { registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); - String result = invoke.execute(mockCommandContext, new String[]{"echo(\"ok\")"}); - assertTrue(result.contains("If you want to invoke like [invoke sayHello(\"xxxx\")], please execute cd command first," + - " or you can execute it like [invoke IHelloService.sayHello(\"xxxx\")]")); + String result = invoke.execute(mockCommandContext, new String[] {"echo(\"ok\")"}); + assertTrue(result.contains( + "If you want to invoke like [invoke sayHello(\"xxxx\")], please execute cd command first," + + " or you can execute it like [invoke IHelloService.sayHello(\"xxxx\")]")); } @Test void testInvokeDefaultService() throws RemotingException { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName()); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null); - given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)).willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); + given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) + .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY)); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); - String result = invoke.execute(mockCommandContext, new String[]{"echo(\"ok\")"}); + String result = invoke.execute(mockCommandContext, new String[] {"echo(\"ok\")"}); assertTrue(result.contains("result: \"ok\"")); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove(); @@ -94,11 +96,12 @@ class InvokeTelnetTest { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(null); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null); - given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)).willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); + given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) + .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY)); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); - String result = invoke.execute(mockCommandContext, new String[]{"DemoService.echo(\"ok\")"}); + String result = invoke.execute(mockCommandContext, new String[] {"DemoService.echo(\"ok\")"}); assertTrue(result.contains("result: \"ok\"")); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove(); @@ -108,12 +111,13 @@ class InvokeTelnetTest { void testInvokeByPassingNullValue() { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName()); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null); - given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)).willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); + given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) + .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY)); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); try { - invoke.execute(mockCommandContext, new String[]{"sayHello(null)"}); + invoke.execute(mockCommandContext, new String[] {"sayHello(null)"}); } catch (Exception ex) { assertTrue(ex instanceof NullPointerException); } @@ -127,12 +131,13 @@ class InvokeTelnetTest { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName()); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null); - given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)).willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); + given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) + .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY)); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); - String result = invoke.execute(mockCommandContext, new String[]{"getType(\"High\")"}); + String result = invoke.execute(mockCommandContext, new String[] {"getType(\"High\")"}); assertTrue(result.contains("result: \"High\"")); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove(); @@ -142,13 +147,15 @@ class InvokeTelnetTest { void testOverriddenMethodWithSpecifyParamType() throws RemotingException { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName()); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null); - given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)).willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); + given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) + .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY)); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); - String result = invoke.execute(mockCommandContext, - new String[]{"getPerson({\"name\":\"zhangsan\",\"age\":12,\"class\":\"org.apache.dubbo.qos.legacy.service.Person\"})"}); + String result = invoke.execute(mockCommandContext, new String[] { + "getPerson({\"name\":\"zhangsan\",\"age\":12,\"class\":\"org.apache.dubbo.qos.legacy.service.Person\"})" + }); assertTrue(result.contains("result: 12")); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); @@ -164,22 +171,28 @@ class InvokeTelnetTest { defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).set(null); defaultAttributeMap.attr(InvokeTelnet.INVOKE_MESSAGE_KEY).set(null); - given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)).willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); + given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) + .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY)); - given(mockChannel.attr(SelectTelnet.SELECT_METHOD_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_METHOD_KEY)); - given(mockChannel.attr(InvokeTelnet.INVOKE_METHOD_PROVIDER_KEY)).willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_PROVIDER_KEY)); - given(mockChannel.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)).willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)); - given(mockChannel.attr(InvokeTelnet.INVOKE_MESSAGE_KEY)).willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_MESSAGE_KEY)); + given(mockChannel.attr(SelectTelnet.SELECT_METHOD_KEY)) + .willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_METHOD_KEY)); + given(mockChannel.attr(InvokeTelnet.INVOKE_METHOD_PROVIDER_KEY)) + .willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_PROVIDER_KEY)); + given(mockChannel.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)) + .willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)); + given(mockChannel.attr(InvokeTelnet.INVOKE_MESSAGE_KEY)) + .willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_MESSAGE_KEY)); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); String param = "{\"name\":\"Dubbo\",\"age\":8}"; - String result = invoke.execute(mockCommandContext, new String[]{"getPerson(" + param + ")"}); - assertTrue(result.contains("Please use the select command to select the method you want to invoke. eg: select 1")); - result = select.execute(mockCommandContext, new String[]{"1"}); - //result dependent on method order. + String result = invoke.execute(mockCommandContext, new String[] {"getPerson(" + param + ")"}); + assertTrue( + result.contains("Please use the select command to select the method you want to invoke. eg: select 1")); + result = select.execute(mockCommandContext, new String[] {"1"}); + // result dependent on method order. assertTrue(result.contains("result: 8") || result.contains("result: \"Dubbo\"")); - result = select.execute(mockCommandContext, new String[]{"2"}); + result = select.execute(mockCommandContext, new String[] {"2"}); assertTrue(result.contains("result: 8") || result.contains("result: \"Dubbo\"")); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); @@ -195,13 +208,14 @@ class InvokeTelnetTest { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName()); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null); - given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)).willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); + given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) + .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY)); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); String param = "{1:\"Dubbo\",2:\"test\"}"; - String result = invoke.execute(mockCommandContext, new String[]{"getMap(" + param + ")"}); + String result = invoke.execute(mockCommandContext, new String[] {"getMap(" + param + ")"}); assertTrue(result.contains("result: {1:\"Dubbo\",2:\"test\"}")); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); @@ -213,13 +227,14 @@ class InvokeTelnetTest { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName()); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null); - given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)).willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); + given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) + .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY)); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); String param = "{\"name\":\"Dubbo\",\"age\":8},{\"name\":\"Apache\",\"age\":20}"; - String result = invoke.execute(mockCommandContext, new String[]{"getPerson(" + param + ")"}); + String result = invoke.execute(mockCommandContext, new String[] {"getPerson(" + param + ")"}); assertTrue(result.contains("result: 28")); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); @@ -231,12 +246,14 @@ class InvokeTelnetTest { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(null); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null); - given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)).willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); + given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) + .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY)); String result = invoke.execute(mockCommandContext, new String[0]); - assertEquals("Please input method name, eg: \r\ninvoke xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\ninvoke XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\ninvoke com.xxx.XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})", - result); + assertEquals( + "Please input method name, eg: \r\ninvoke xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\ninvoke XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\ninvoke com.xxx.XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})", + result); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove(); @@ -247,10 +264,11 @@ class InvokeTelnetTest { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(null); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null); - given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)).willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); + given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) + .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY)); - String result = invoke.execute(mockCommandContext, new String[]{"("}); + String result = invoke.execute(mockCommandContext, new String[] {"("}); assertEquals("Invalid parameters, format: service.method(args)", result); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); @@ -259,12 +277,6 @@ class InvokeTelnetTest { private void registerProvider(String key, Object impl, Class interfaceClass) { ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass); - repository.registerProvider( - key, - impl, - serviceDescriptor, - null, - null - ); + repository.registerProvider(key, impl, serviceDescriptor, null, null); } } diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/LsTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/LsTest.java index 6cb56e4259..369008d7c0 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/LsTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/LsTest.java @@ -29,14 +29,14 @@ import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.model.ServiceMetadata; +import java.util.HashMap; +import java.util.Map; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.HashMap; -import java.util.Map; - class LsTest { private FrameworkModel frameworkModel; private ModuleServiceRepository repository; @@ -60,18 +60,18 @@ class LsTest { String result = ls.execute(Mockito.mock(CommandContext.class), new String[0]); System.out.println(result); /** - As Provider side: - +--------------------------------+---+ - | Provider Service Name |PUB| - +--------------------------------+---+ - |org.apache.dubbo.qos.DemoService| N | - +--------------------------------+---+ - As Consumer side: - +--------------------------------+---+ - | Consumer Service Name |NUM| - +--------------------------------+---+ - |org.apache.dubbo.qos.DemoService| 0 | - +--------------------------------+---+ + * As Provider side: + * +--------------------------------+---+ + * | Provider Service Name |PUB| + * +--------------------------------+---+ + * |org.apache.dubbo.qos.DemoService| N | + * +--------------------------------+---+ + * As Consumer side: + * +--------------------------------+---+ + * | Consumer Service Name |NUM| + * +--------------------------------+---+ + * |org.apache.dubbo.qos.DemoService| 0 | + * +--------------------------------+---+ */ } @@ -80,11 +80,12 @@ class LsTest { ServiceMetadata serviceMetadata = new ServiceMetadata(); serviceMetadata.setServiceKey(DemoService.class.getName()); ProviderModel providerModel = new ProviderModel( - DemoService.class.getName(), - new DemoServiceImpl(), - serviceDescriptor, - null, - serviceMetadata, ClassUtils.getClassLoader(DemoService.class)); + DemoService.class.getName(), + new DemoServiceImpl(), + serviceDescriptor, + null, + serviceMetadata, + ClassUtils.getClassLoader(DemoService.class)); repository.registerProvider(providerModel); } @@ -96,8 +97,12 @@ class LsTest { serviceMetadata.setServiceKey(DemoService.class.getName()); Map methodConfigs = new HashMap<>(); ConsumerModel consumerModel = new ConsumerModel( - serviceMetadata.getServiceKey(), null, serviceDescriptor, - serviceMetadata, methodConfigs, referenceConfig.getInterfaceClassLoader()); + serviceMetadata.getServiceKey(), + null, + serviceDescriptor, + serviceMetadata, + methodConfigs, + referenceConfig.getInterfaceClassLoader()); repository.registerConsumer(consumerModel); } } diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/OfflineTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/OfflineTest.java index 7196e36e38..c523dc9205 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/OfflineTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/OfflineTest.java @@ -63,24 +63,23 @@ class OfflineTest { @Test void testExecute() { Offline offline = new Offline(frameworkModel); - String result = offline.execute(mock(CommandContext.class), new String[]{DemoService.class.getName()}); + String result = offline.execute(mock(CommandContext.class), new String[] {DemoService.class.getName()}); Assertions.assertEquals(result, "OK"); Assertions.assertFalse(registerStatedURL.isRegistered()); OfflineInterface offlineInterface = new OfflineInterface(frameworkModel); registerStatedURL.setRegistered(true); - result = offlineInterface.execute(mock(CommandContext.class), new String[]{DemoService.class.getName()}); + result = offlineInterface.execute(mock(CommandContext.class), new String[] {DemoService.class.getName()}); Assertions.assertEquals(result, "OK"); Assertions.assertFalse(registerStatedURL.isRegistered()); registerStatedURL.setRegistered(true); registerStatedURL.setRegistryUrl(URL.valueOf("test://127.0.0.1:2181/" + RegistryService.class.getName()) - .addParameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE)); + .addParameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE)); OfflineApp offlineApp = new OfflineApp(frameworkModel); - result = offlineApp.execute(mock(CommandContext.class), new String[]{DemoService.class.getName()}); + result = offlineApp.execute(mock(CommandContext.class), new String[] {DemoService.class.getName()}); Assertions.assertEquals(result, "OK"); Assertions.assertFalse(registerStatedURL.isRegistered()); - } private void registerProvider() { @@ -88,16 +87,16 @@ class OfflineTest { ServiceMetadata serviceMetadata = new ServiceMetadata(); serviceMetadata.setServiceKey(DemoService.class.getName()); ProviderModel providerModel = new ProviderModel( - DemoService.class.getName(), - new DemoServiceImpl(), - serviceDescriptor, - serviceMetadata, ClassUtils.getClassLoader(DemoService.class)); + DemoService.class.getName(), + new DemoServiceImpl(), + serviceDescriptor, + serviceMetadata, + ClassUtils.getClassLoader(DemoService.class)); registerStatedURL = new ProviderModel.RegisterStatedURL( - URL.valueOf("dubbo://127.0.0.1:20880/" + DemoService.class.getName()), - URL.valueOf("test://127.0.0.1:2181/" + RegistryService.class.getName()), - true); - providerModel.addStatedUrl(registerStatedURL - ); + URL.valueOf("dubbo://127.0.0.1:20880/" + DemoService.class.getName()), + URL.valueOf("test://127.0.0.1:2181/" + RegistryService.class.getName()), + true); + providerModel.addStatedUrl(registerStatedURL); repository.registerProvider(providerModel); } } diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/OnlineTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/OnlineTest.java index ef13b34b1d..27f60e8834 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/OnlineTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/OnlineTest.java @@ -63,24 +63,23 @@ class OnlineTest { @Test void testExecute() { Online online = new Online(frameworkModel); - String result = online.execute(mock(CommandContext.class), new String[]{DemoService.class.getName()}); + String result = online.execute(mock(CommandContext.class), new String[] {DemoService.class.getName()}); Assertions.assertEquals(result, "OK"); Assertions.assertTrue(registerStatedURL.isRegistered()); OnlineInterface onlineInterface = new OnlineInterface(frameworkModel); registerStatedURL.setRegistered(false); - result = onlineInterface.execute(mock(CommandContext.class), new String[]{DemoService.class.getName()}); + result = onlineInterface.execute(mock(CommandContext.class), new String[] {DemoService.class.getName()}); Assertions.assertEquals(result, "OK"); Assertions.assertTrue(registerStatedURL.isRegistered()); registerStatedURL.setRegistered(false); registerStatedURL.setRegistryUrl(URL.valueOf("test://127.0.0.1:2181/" + RegistryService.class.getName()) - .addParameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE)); + .addParameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE)); OnlineApp onlineApp = new OnlineApp(frameworkModel); - result = onlineApp.execute(mock(CommandContext.class), new String[]{DemoService.class.getName()}); + result = onlineApp.execute(mock(CommandContext.class), new String[] {DemoService.class.getName()}); Assertions.assertEquals(result, "OK"); Assertions.assertTrue(registerStatedURL.isRegistered()); - } private void registerProvider() { @@ -88,16 +87,16 @@ class OnlineTest { ServiceMetadata serviceMetadata = new ServiceMetadata(); serviceMetadata.setServiceKey(DemoService.class.getName()); ProviderModel providerModel = new ProviderModel( - DemoService.class.getName(), - new DemoServiceImpl(), - serviceDescriptor, - serviceMetadata, ClassUtils.getClassLoader(DemoService.class)); + DemoService.class.getName(), + new DemoServiceImpl(), + serviceDescriptor, + serviceMetadata, + ClassUtils.getClassLoader(DemoService.class)); registerStatedURL = new ProviderModel.RegisterStatedURL( - URL.valueOf("dubbo://127.0.0.1:20880/" + DemoService.class.getName()), - URL.valueOf("test://127.0.0.1:2181/" + RegistryService.class.getName()), - false); - providerModel.addStatedUrl(registerStatedURL - ); + URL.valueOf("dubbo://127.0.0.1:20880/" + DemoService.class.getName()), + URL.valueOf("test://127.0.0.1:2181/" + RegistryService.class.getName()), + false); + providerModel.addStatedUrl(registerStatedURL); repository.registerProvider(providerModel); } } diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/PortTelnetTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/PortTelnetTest.java index 72bd1f71e5..ac4fee23ac 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/PortTelnetTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/PortTelnetTest.java @@ -57,7 +57,10 @@ class PortTelnetTest { given(mockInvoker.getInterface()).willReturn(DemoService.class); given(mockInvoker.getUrl()).willReturn(URL.valueOf("dubbo://127.0.0.1:" + availablePort + "/demo")); - frameworkModel.getExtensionLoader(Protocol.class).getExtension(DubboProtocol.NAME).export(mockInvoker); + frameworkModel + .getExtensionLoader(Protocol.class) + .getExtension(DubboProtocol.NAME) + .export(mockInvoker); } @AfterEach @@ -75,7 +78,7 @@ class PortTelnetTest { ExchangeClient client1 = Exchangers.connect("dubbo://127.0.0.1:" + availablePort + "/demo"); ExchangeClient client2 = Exchangers.connect("dubbo://127.0.0.1:" + availablePort + "/demo"); Thread.sleep(100); - String result = port.execute(mockCommandContext, new String[]{"-l", availablePort + ""}); + String result = port.execute(mockCommandContext, new String[] {"-l", availablePort + ""}); String client1Addr = client1.getLocalAddress().toString(); String client2Addr = client2.getLocalAddress().toString(); System.out.printf("Result: %s %n", result); @@ -87,7 +90,7 @@ class PortTelnetTest { @Test void testListDetail() throws RemotingException { - String result = port.execute(mockCommandContext, new String[]{"-l"}); + String result = port.execute(mockCommandContext, new String[] {"-l"}); assertEquals("dubbo://127.0.0.1:" + availablePort + "", result); } @@ -99,13 +102,13 @@ class PortTelnetTest { @Test void testErrorMessage() throws RemotingException { - String result = port.execute(mockCommandContext, new String[]{"a"}); + String result = port.execute(mockCommandContext, new String[] {"a"}); assertEquals("Illegal port a, must be integer.", result); } @Test void testNoPort() throws RemotingException { - String result = port.execute(mockCommandContext, new String[]{"-l", "20880"}); + String result = port.execute(mockCommandContext, new String[] {"-l", "20880"}); assertEquals("No such port 20880", result); } } diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/PublishMetadataTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/PublishMetadataTest.java index ebd54524df..e4e621b650 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/PublishMetadataTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/PublishMetadataTest.java @@ -37,7 +37,6 @@ class PublishMetadataTest { ApplicationModel applicationModel = frameworkModel.newApplication(); applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("APP_" + i)); } - } @AfterEach @@ -50,22 +49,20 @@ class PublishMetadataTest { PublishMetadata publishMetadata = new PublishMetadata(frameworkModel); String result = publishMetadata.execute(Mockito.mock(CommandContext.class), new String[0]); - String expectResult = "publish metadata succeeded. App:APP_0\n" + - "publish metadata succeeded. App:APP_1\n" + - "publish metadata succeeded. App:APP_2\n"; + String expectResult = "publish metadata succeeded. App:APP_0\n" + "publish metadata succeeded. App:APP_1\n" + + "publish metadata succeeded. App:APP_2\n"; Assertions.assertEquals(result, expectResult); // delay 5s - result = publishMetadata.execute(Mockito.mock(CommandContext.class), new String[]{"5"}); - expectResult = "publish task submitted, will publish in 5 seconds. App:APP_0\n" + - "publish task submitted, will publish in 5 seconds. App:APP_1\n" + - "publish task submitted, will publish in 5 seconds. App:APP_2\n"; + result = publishMetadata.execute(Mockito.mock(CommandContext.class), new String[] {"5"}); + expectResult = "publish task submitted, will publish in 5 seconds. App:APP_0\n" + + "publish task submitted, will publish in 5 seconds. App:APP_1\n" + + "publish task submitted, will publish in 5 seconds. App:APP_2\n"; Assertions.assertEquals(result, expectResult); // wrong delay param - result = publishMetadata.execute(Mockito.mock(CommandContext.class), new String[]{"A"}); + result = publishMetadata.execute(Mockito.mock(CommandContext.class), new String[] {"A"}); expectResult = "publishMetadata failed! Wrong delay param!"; Assertions.assertEquals(result, expectResult); - } } diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/PwdTelnetTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/PwdTelnetTest.java index 21ca70c9f2..e8ab984a31 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/PwdTelnetTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/PwdTelnetTest.java @@ -44,7 +44,8 @@ class PwdTelnetTest { mockChannel = mock(Channel.class); mockCommandContext = mock(CommandContext.class); given(mockCommandContext.getRemote()).willReturn(mockChannel); - given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)).willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); + given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) + .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); } @AfterEach @@ -56,7 +57,9 @@ class PwdTelnetTest { @Test void testService() throws RemotingException { - defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService"); + defaultAttributeMap + .attr(ChangeTelnet.SERVICE_KEY) + .set("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService"); String result = pwdTelnet.execute(mockCommandContext, new String[0]); assertEquals("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService", result); } @@ -71,7 +74,7 @@ class PwdTelnetTest { @Test void testMessageError() throws RemotingException { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(null); - String result = pwdTelnet.execute(mockCommandContext, new String[]{"test"}); + String result = pwdTelnet.execute(mockCommandContext, new String[] {"test"}); assertEquals("Unsupported parameter [test] for pwd.", result); } } diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ReadyTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ReadyTest.java index 01152d9ef3..0be0567b12 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ReadyTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ReadyTest.java @@ -31,16 +31,16 @@ import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.FrameworkServiceRepository; import org.apache.dubbo.rpc.model.ModuleModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + class ReadyTest { private FrameworkModel frameworkModel; @@ -68,11 +68,10 @@ class ReadyTest { ExtensionLoader loader = Mockito.mock(ExtensionLoader.class); Mockito.when(frameworkModel.getExtensionLoader(ReadinessProbe.class)).thenReturn(loader); URL url = URL.valueOf("application://").addParameter(CommonConstants.QOS_READY_PROBE_EXTENSION, ""); - List readinessProbes = Arrays.asList( - new DeployerReadinessProbe(frameworkModel), - new ProviderReadinessProbe(frameworkModel) - ); - Mockito.when(loader.getActivateExtension(url, CommonConstants.QOS_READY_PROBE_EXTENSION)).thenReturn(readinessProbes); + List readinessProbes = + Arrays.asList(new DeployerReadinessProbe(frameworkModel), new ProviderReadinessProbe(frameworkModel)); + Mockito.when(loader.getActivateExtension(url, CommonConstants.QOS_READY_PROBE_EXTENSION)) + .thenReturn(readinessProbes); } @Test diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/SelectTelnetTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/SelectTelnetTest.java index b18b6ebfd7..0138eed714 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/SelectTelnetTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/SelectTelnetTest.java @@ -27,16 +27,16 @@ import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleServiceRepository; import org.apache.dubbo.rpc.model.ServiceDescriptor; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + import io.netty.channel.Channel; import io.netty.util.DefaultAttributeMap; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -82,12 +82,14 @@ class SelectTelnetTest { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName()); defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).set(null); - given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)).willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); - given(mockChannel.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)).willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)); + given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) + .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); + given(mockChannel.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)) + .willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); - String result = select.execute(mockCommandContext, new String[]{"1"}); + String result = select.execute(mockCommandContext, new String[] {"1"}); assertTrue(result.contains("Please use the invoke command first.")); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); @@ -99,18 +101,20 @@ class SelectTelnetTest { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName()); defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).set(methods); - given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)).willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); - given(mockChannel.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)).willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)); + given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) + .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); + given(mockChannel.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)) + .willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); - String result = select.execute(mockCommandContext, new String[]{"index"}); + String result = select.execute(mockCommandContext, new String[] {"index"}); assertTrue(result.contains("Illegal index ,please input select 1")); - result = select.execute(mockCommandContext, new String[]{"0"}); + result = select.execute(mockCommandContext, new String[] {"0"}); assertTrue(result.contains("Illegal index ,please input select 1")); - result = select.execute(mockCommandContext, new String[]{"1000"}); + result = select.execute(mockCommandContext, new String[] {"1000"}); assertTrue(result.contains("Illegal index ,please input select 1")); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); @@ -122,8 +126,10 @@ class SelectTelnetTest { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName()); defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).set(methods); - given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)).willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); - given(mockChannel.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)).willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)); + given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) + .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); + given(mockChannel.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)) + .willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); @@ -136,12 +142,6 @@ class SelectTelnetTest { private void registerProvider(String key, Object impl, Class interfaceClass) { ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass); - repository.registerProvider( - key, - impl, - serviceDescriptor, - null, - null - ); + repository.registerProvider(key, impl, serviceDescriptor, null, null); } } diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/SerializeCheckStatusTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/SerializeCheckStatusTest.java index 162c7a8040..3ef5d01ab6 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/SerializeCheckStatusTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/SerializeCheckStatusTest.java @@ -38,29 +38,45 @@ class SerializeCheckStatusTest { CommandContext commandContext2 = Mockito.mock(CommandContext.class); Mockito.when(commandContext2.isHttp()).thenReturn(true); - Assertions.assertFalse(serializeCheckStatus.execute(commandContext1, null).contains("Test1234")); - Assertions.assertFalse(serializeCheckStatus.execute(commandContext2, null).contains("Test1234")); + Assertions.assertFalse( + serializeCheckStatus.execute(commandContext1, null).contains("Test1234")); + Assertions.assertFalse( + serializeCheckStatus.execute(commandContext2, null).contains("Test1234")); ssm.addToAllowed("Test1234"); - Assertions.assertTrue(serializeCheckStatus.execute(commandContext1, null).contains("Test1234")); - Assertions.assertTrue(serializeCheckStatus.execute(commandContext2, null).contains("Test1234")); + Assertions.assertTrue( + serializeCheckStatus.execute(commandContext1, null).contains("Test1234")); + Assertions.assertTrue( + serializeCheckStatus.execute(commandContext2, null).contains("Test1234")); - Assertions.assertFalse(serializeCheckStatus.execute(commandContext1, null).contains("Test4321")); - Assertions.assertFalse(serializeCheckStatus.execute(commandContext2, null).contains("Test4321")); + Assertions.assertFalse( + serializeCheckStatus.execute(commandContext1, null).contains("Test4321")); + Assertions.assertFalse( + serializeCheckStatus.execute(commandContext2, null).contains("Test4321")); ssm.addToDisAllowed("Test4321"); - Assertions.assertTrue(serializeCheckStatus.execute(commandContext1, null).contains("Test4321")); - Assertions.assertTrue(serializeCheckStatus.execute(commandContext2, null).contains("Test4321")); + Assertions.assertTrue( + serializeCheckStatus.execute(commandContext1, null).contains("Test4321")); + Assertions.assertTrue( + serializeCheckStatus.execute(commandContext2, null).contains("Test4321")); - Assertions.assertFalse(serializeCheckStatus.execute(commandContext1, null).contains("CheckSerializable: false")); - Assertions.assertFalse(serializeCheckStatus.execute(commandContext2, null).contains("\"checkSerializable\":false")); + Assertions.assertFalse( + serializeCheckStatus.execute(commandContext1, null).contains("CheckSerializable: false")); + Assertions.assertFalse( + serializeCheckStatus.execute(commandContext2, null).contains("\"checkSerializable\":false")); ssm.setCheckSerializable(false); - Assertions.assertTrue(serializeCheckStatus.execute(commandContext1, null).contains("CheckSerializable: false")); - Assertions.assertTrue(serializeCheckStatus.execute(commandContext2, null).contains("\"checkSerializable\":false")); + Assertions.assertTrue( + serializeCheckStatus.execute(commandContext1, null).contains("CheckSerializable: false")); + Assertions.assertTrue( + serializeCheckStatus.execute(commandContext2, null).contains("\"checkSerializable\":false")); - Assertions.assertFalse(serializeCheckStatus.execute(commandContext1, null).contains("CheckStatus: DISABLE")); - Assertions.assertFalse(serializeCheckStatus.execute(commandContext2, null).contains("\"checkStatus\":\"DISABLE\"")); + Assertions.assertFalse( + serializeCheckStatus.execute(commandContext1, null).contains("CheckStatus: DISABLE")); + Assertions.assertFalse( + serializeCheckStatus.execute(commandContext2, null).contains("\"checkStatus\":\"DISABLE\"")); ssm.setCheckStatus(org.apache.dubbo.common.utils.SerializeCheckStatus.DISABLE); - Assertions.assertTrue(serializeCheckStatus.execute(commandContext1, null).contains("CheckStatus: DISABLE")); - Assertions.assertTrue(serializeCheckStatus.execute(commandContext2, null).contains("\"checkStatus\":\"DISABLE\"")); + Assertions.assertTrue( + serializeCheckStatus.execute(commandContext1, null).contains("CheckStatus: DISABLE")); + Assertions.assertTrue( + serializeCheckStatus.execute(commandContext2, null).contains("\"checkStatus\":\"DISABLE\"")); frameworkModel.destroy(); } diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/SerializeWarnedClassesTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/SerializeWarnedClassesTest.java index 91b88a5113..9c2b5cfdb7 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/SerializeWarnedClassesTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/SerializeWarnedClassesTest.java @@ -38,19 +38,26 @@ class SerializeWarnedClassesTest { CommandContext commandContext2 = Mockito.mock(CommandContext.class); Mockito.when(commandContext2.isHttp()).thenReturn(true); - Assertions.assertFalse(serializeWarnedClasses.execute(commandContext1, null).contains("Test1234")); - Assertions.assertFalse(serializeWarnedClasses.execute(commandContext2, null).contains("Test1234")); + Assertions.assertFalse( + serializeWarnedClasses.execute(commandContext1, null).contains("Test1234")); + Assertions.assertFalse( + serializeWarnedClasses.execute(commandContext2, null).contains("Test1234")); ssm.getWarnedClasses().add("Test1234"); - Assertions.assertTrue(serializeWarnedClasses.execute(commandContext1, null).contains("Test1234")); - Assertions.assertTrue(serializeWarnedClasses.execute(commandContext2, null).contains("Test1234")); + Assertions.assertTrue( + serializeWarnedClasses.execute(commandContext1, null).contains("Test1234")); + Assertions.assertTrue( + serializeWarnedClasses.execute(commandContext2, null).contains("Test1234")); - Assertions.assertFalse(serializeWarnedClasses.execute(commandContext1, null).contains("Test4321")); - Assertions.assertFalse(serializeWarnedClasses.execute(commandContext2, null).contains("Test4321")); + Assertions.assertFalse( + serializeWarnedClasses.execute(commandContext1, null).contains("Test4321")); + Assertions.assertFalse( + serializeWarnedClasses.execute(commandContext2, null).contains("Test4321")); ssm.getWarnedClasses().add("Test4321"); - Assertions.assertTrue(serializeWarnedClasses.execute(commandContext1, null).contains("Test4321")); - Assertions.assertTrue(serializeWarnedClasses.execute(commandContext2, null).contains("Test4321")); + Assertions.assertTrue( + serializeWarnedClasses.execute(commandContext1, null).contains("Test4321")); + Assertions.assertTrue( + serializeWarnedClasses.execute(commandContext2, null).contains("Test4321")); frameworkModel.destroy(); } - } diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ShutdownTelnetTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ShutdownTelnetTest.java index 7d93525da2..25fb868c5d 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ShutdownTelnetTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ShutdownTelnetTest.java @@ -61,7 +61,7 @@ class ShutdownTelnetTest { void testInvokeWithTimeParameter() throws RemotingException { int sleepTime = 2000; long start = System.currentTimeMillis(); - String result = shutdown.execute(mockCommandContext, new String[]{"-t", "" + sleepTime}); + String result = shutdown.execute(mockCommandContext, new String[] {"-t", "" + sleepTime}); long end = System.currentTimeMillis(); assertTrue(result.contains("Application has shutdown successfully"), result); assertTrue((end - start) >= sleepTime, "sleepTime: " + sleepTime + ", execTime: " + (end - start)); diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/StartupTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/StartupTest.java index 0676e0ab19..b653e1d265 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/StartupTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/StartupTest.java @@ -29,15 +29,15 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; - class StartupTest { private FrameworkModel frameworkModel; private ModuleDeployer moduleDeployer; @@ -60,10 +60,9 @@ class StartupTest { ExtensionLoader loader = Mockito.mock(ExtensionLoader.class); Mockito.when(frameworkModel.getExtensionLoader(StartupProbe.class)).thenReturn(loader); URL url = URL.valueOf("application://").addParameter(CommonConstants.QOS_STARTUP_PROBE_EXTENSION, ""); - List readinessProbes = Arrays.asList( - new DeployerStartupProbe(frameworkModel) - ); - Mockito.when(loader.getActivateExtension(url, CommonConstants.QOS_STARTUP_PROBE_EXTENSION)).thenReturn(readinessProbes); + List readinessProbes = Arrays.asList(new DeployerStartupProbe(frameworkModel)); + Mockito.when(loader.getActivateExtension(url, CommonConstants.QOS_STARTUP_PROBE_EXTENSION)) + .thenReturn(readinessProbes); } @Test diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/channel/MockNettyChannel.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/channel/MockNettyChannel.java index 38a7b0c47e..c58ecaa56f 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/channel/MockNettyChannel.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/channel/MockNettyChannel.java @@ -18,6 +18,15 @@ package org.apache.dubbo.qos.command.impl.channel; import org.apache.dubbo.common.URL; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + import io.netty.buffer.ByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelConfig; @@ -35,15 +44,6 @@ import io.netty.util.DefaultAttributeMap; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - public class MockNettyChannel implements Channel { InetSocketAddress localAddress; @@ -52,7 +52,7 @@ public class MockNettyChannel implements Channel { private List receivedObjects = new LinkedList<>(); public static final String ERROR_WHEN_SEND = "error_when_send"; private CountDownLatch latch; - private AttributeMap attributeMap = new DefaultAttributeMap(); + private AttributeMap attributeMap = new DefaultAttributeMap(); public MockNettyChannel(URL remoteUrl, CountDownLatch latch) { this.remoteUrl = remoteUrl; @@ -222,7 +222,8 @@ public class MockNettyChannel implements Channel { } @Override - public Void get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + public Void get(long timeout, TimeUnit unit) + throws InterruptedException, ExecutionException, TimeoutException { return null; } }; diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/CommandHelperTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/CommandHelperTest.java index d5b82d1134..b2443ec9bf 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/CommandHelperTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/CommandHelperTest.java @@ -59,11 +59,11 @@ import org.apache.dubbo.qos.command.impl.SwitchLogger; import org.apache.dubbo.qos.command.impl.Version; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.junit.jupiter.api.Test; - import java.util.LinkedList; import java.util.List; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/ServiceCheckUtilsTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/ServiceCheckUtilsTest.java index 90cbc0f769..268ee97b4b 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/ServiceCheckUtilsTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/ServiceCheckUtilsTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.qos.command.util; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.NetUtils; @@ -34,14 +33,14 @@ import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.model.ServiceMetadata; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + import static org.junit.jupiter.api.Assertions.assertEquals; /** @@ -49,7 +48,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; */ class ServiceCheckUtilsTest { - private final ModuleServiceRepository repository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); + private final ModuleServiceRepository repository = + ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); @Test void testIsRegistered() { @@ -62,14 +62,17 @@ class ServiceCheckUtilsTest { ServiceDescriptor serviceDescriptor = repository.registerService(DemoService.class); ProviderModel providerModel = new ProviderModel( - url.getServiceKey(), - demoServiceImpl, - serviceDescriptor, - new ServiceMetadata(), ClassUtils.getClassLoader(DemoService.class)); + url.getServiceKey(), + demoServiceImpl, + serviceDescriptor, + new ServiceMetadata(), + ClassUtils.getClassLoader(DemoService.class)); repository.registerProvider(providerModel); - String url1 = "service-discovery-registry://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?application=dubbo-demo-api-provider&dubbo=2.0.2&pid=66099®istry=zookeeper×tamp=1654588337653"; - String url2 = "zookeeper://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?application=dubbo-demo-api-provider&dubbo=2.0.2&pid=66099×tamp=1654588337653"; + String url1 = + "service-discovery-registry://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?application=dubbo-demo-api-provider&dubbo=2.0.2&pid=66099®istry=zookeeper×tamp=1654588337653"; + String url2 = + "zookeeper://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?application=dubbo-demo-api-provider&dubbo=2.0.2&pid=66099×tamp=1654588337653"; providerModel.getStatedUrl().add(new ProviderModel.RegisterStatedURL(url, URL.valueOf(url1), true)); providerModel.getStatedUrl().add(new ProviderModel.RegisterStatedURL(url, URL.valueOf(url2), false)); @@ -81,9 +84,12 @@ class ServiceCheckUtilsTest { ConsumerModel consumerModel = Mockito.mock(ConsumerModel.class); ServiceMetadata serviceMetadata = Mockito.mock(ServiceMetadata.class); Mockito.when(consumerModel.getServiceMetadata()).thenReturn(serviceMetadata); - String registry1 = "service-discovery-registry://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?application=dubbo-demo-api-provider&dubbo=2.0.2&pid=66099®istry=zookeeper×tamp=1654588337653"; - String registry2 = "zookeeper://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?application=dubbo-demo-api-provider&dubbo=2.0.2&pid=66099×tamp=1654588337653"; - String registry3 = "nacos://127.0.0.1:8848/org.apache.dubbo.registry.RegistryService?application=dubbo-demo-api-provider&dubbo=2.0.2&pid=66099×tamp=1654588337653"; + String registry1 = + "service-discovery-registry://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?application=dubbo-demo-api-provider&dubbo=2.0.2&pid=66099®istry=zookeeper×tamp=1654588337653"; + String registry2 = + "zookeeper://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?application=dubbo-demo-api-provider&dubbo=2.0.2&pid=66099×tamp=1654588337653"; + String registry3 = + "nacos://127.0.0.1:8848/org.apache.dubbo.registry.RegistryService?application=dubbo-demo-api-provider&dubbo=2.0.2&pid=66099×tamp=1654588337653"; Map> invokerMap = new LinkedHashMap<>(); { Registry registry = Mockito.mock(Registry.class); @@ -140,8 +146,8 @@ class ServiceCheckUtilsTest { Mockito.when(serviceMetadata.getAttribute("currentClusterInvoker")).thenReturn(invokerMap); - assertEquals("zookeeper-A(5)/zookeeper-AF(I-10,A-0)/nacos-I(10)", ServiceCheckUtils.getConsumerAddressNum(consumerModel)); + assertEquals( + "zookeeper-A(5)/zookeeper-AF(I-10,A-0)/nacos-I(10)", + ServiceCheckUtils.getConsumerAddressNum(consumerModel)); } - - -} \ No newline at end of file +} diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/LogTelnetHandlerTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/LogTelnetHandlerTest.java index 2bd4561a33..c3559f7e99 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/LogTelnetHandlerTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/LogTelnetHandlerTest.java @@ -50,5 +50,4 @@ class LogTelnetHandlerTest { String result = log.telnet(mockChannel, "100"); assertTrue(result.contains("CURRENT LOG APPENDER")); } - -} \ No newline at end of file +} diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/CustomArgument.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/CustomArgument.java index cb1114d7cc..3c54f5daa7 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/CustomArgument.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/CustomArgument.java @@ -18,15 +18,13 @@ package org.apache.dubbo.qos.legacy.service; import java.io.Serializable; - @SuppressWarnings("serial") public class CustomArgument implements Serializable { Type type; String name; - public CustomArgument() { - } + public CustomArgument() {} public CustomArgument(Type type, String name) { super(); diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/DemoService.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/DemoService.java index 3950380256..dea474c244 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/DemoService.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/DemoService.java @@ -19,11 +19,9 @@ package org.apache.dubbo.qos.legacy.service; import java.util.Map; import java.util.Set; - /** * TestService */ - public interface DemoService { void sayHello(String name); diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/DemoServiceImpl.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/DemoServiceImpl.java index 466e193acd..1b862ae88f 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/DemoServiceImpl.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/DemoServiceImpl.java @@ -50,25 +50,23 @@ public class DemoServiceImpl implements DemoService { } public int getSize(String[] strs) { - if (strs == null) - return -1; + if (strs == null) return -1; return strs.length; } public int getSize(Object[] os) { - if (os == null) - return -1; + if (os == null) return -1; return os.length; } public Object invoke(String service, String method) throws Exception { - System.out.println("RpcContext.getServerAttachment().getRemoteHost()=" + RpcContext.getServiceContext().getRemoteHost()); + System.out.println("RpcContext.getServerAttachment().getRemoteHost()=" + + RpcContext.getServiceContext().getRemoteHost()); return service + ":" + method; } public Type enumlength(Type... types) { - if (types.length == 0) - return Type.Lower; + if (types.length == 0) return Type.Lower; return types[0]; } @@ -96,8 +94,7 @@ public class DemoServiceImpl implements DemoService { return map == null ? null : map.keySet(); } - public void nonSerializedParameter(NonSerialized ns) { - } + public void nonSerializedParameter(NonSerialized ns) {} public NonSerialized returnNonSerialized() { return new NonSerialized(); diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/Man.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/Man.java index 09154632c2..838fe0a953 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/Man.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/Man.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.qos.legacy.service; - import java.io.Serializable; /** diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/NonSerialized.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/NonSerialized.java index ff61e57970..c054877166 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/NonSerialized.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/NonSerialized.java @@ -19,6 +19,4 @@ package org.apache.dubbo.qos.legacy.service; /** * NonSerialized */ -public class NonSerialized { - -} +public class NonSerialized {} diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/Type.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/Type.java index 9588c9a8c0..c41aa89a43 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/Type.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/Type.java @@ -17,5 +17,7 @@ package org.apache.dubbo.qos.legacy.service; public enum Type { - High, Normal, Lower + High, + Normal, + Lower } diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/DemoException.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/DemoException.java index c719be8d50..04c3d82648 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/DemoException.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/DemoException.java @@ -38,5 +38,4 @@ public class DemoException extends Exception { public DemoException(Throwable cause) { super(cause); } - } diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/DemoService.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/DemoService.java index 67d9988e43..ae057f30c7 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/DemoService.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/DemoService.java @@ -18,7 +18,6 @@ package org.apache.dubbo.qos.legacy.service.generic; import java.util.List; - /** * DemoService */ @@ -31,5 +30,4 @@ public interface DemoService { List getUsers(List users); int echo(int i); - } diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/DemoServiceImpl.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/DemoServiceImpl.java index 37d8f4ea23..f6d85e3c9c 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/DemoServiceImpl.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/DemoServiceImpl.java @@ -27,7 +27,6 @@ public class DemoServiceImpl implements DemoService { return "say:" + name; } - public void throwDemoException() throws DemoException { throw new DemoException("DemoServiceImpl"); } @@ -39,5 +38,4 @@ public class DemoServiceImpl implements DemoService { public int echo(int i) { return i; } - } diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/GenericServiceTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/GenericServiceTest.java index 5de484b373..e2fd02664f 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/GenericServiceTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/GenericServiceTest.java @@ -31,10 +31,6 @@ import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.rpc.service.GenericException; import org.apache.dubbo.rpc.service.GenericService; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayList; @@ -43,6 +39,10 @@ import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_BEAN; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; @@ -58,8 +58,7 @@ class GenericServiceTest { service.setInterface(DemoService.class.getName()); service.setRef(new GenericService() { - public Object $invoke(String method, String[] parameterTypes, Object[] args) - throws GenericException { + public Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException { if ("sayName".equals(method)) { return "Generic " + args[0]; } @@ -136,7 +135,8 @@ class GenericServiceTest { user.put("class", "org.apache.dubbo.config.api.User"); user.put("name", "actual.provider"); users.add(user); - users = (List>) genericService.$invoke("getUsers", new String[]{List.class.getName()}, new Object[]{users}); + users = (List>) + genericService.$invoke("getUsers", new String[] {List.class.getName()}, new Object[] {users}); Assertions.assertEquals(1, users.size()); Assertions.assertEquals("actual.provider", users.get(0).get("name")); @@ -171,13 +171,20 @@ class GenericServiceTest { String name = "kimi"; ByteArrayOutputStream bos = new ByteArrayOutputStream(512); ExtensionLoader.getExtensionLoader(Serialization.class) - .getExtension("nativejava").serialize(null, bos).writeObject(name); + .getExtension("nativejava") + .serialize(null, bos) + .writeObject(name); byte[] arg = bos.toByteArray(); - Object obj = genericService.$invoke("sayName", new String[]{String.class.getName()}, new Object[]{arg}); + Object obj = genericService.$invoke("sayName", new String[] {String.class.getName()}, new Object[] {arg}); Assertions.assertTrue(obj instanceof byte[]); byte[] result = (byte[]) obj; - Assertions.assertEquals(ref.sayName(name), ExtensionLoader.getExtensionLoader(Serialization.class) - .getExtension("nativejava").deserialize(null, new ByteArrayInputStream(result)).readObject().toString()); + Assertions.assertEquals( + ref.sayName(name), + ExtensionLoader.getExtensionLoader(Serialization.class) + .getExtension("nativejava") + .deserialize(null, new ByteArrayInputStream(result)) + .readObject() + .toString()); // getUsers List users = new ArrayList(); @@ -186,13 +193,15 @@ class GenericServiceTest { users.add(user); bos = new ByteArrayOutputStream(512); ExtensionLoader.getExtensionLoader(Serialization.class) - .getExtension("nativejava").serialize(null, bos).writeObject(users); - obj = genericService.$invoke("getUsers", - new String[]{List.class.getName()}, - new Object[]{bos.toByteArray()}); + .getExtension("nativejava") + .serialize(null, bos) + .writeObject(users); + obj = genericService.$invoke( + "getUsers", new String[] {List.class.getName()}, new Object[] {bos.toByteArray()}); Assertions.assertTrue(obj instanceof byte[]); result = (byte[]) obj; - Assertions.assertEquals(users, + Assertions.assertEquals( + users, ExtensionLoader.getExtensionLoader(Serialization.class) .getExtension("nativejava") .deserialize(null, new ByteArrayInputStream(result)) @@ -200,11 +209,14 @@ class GenericServiceTest { // echo(int) bos = new ByteArrayOutputStream(512); - ExtensionLoader.getExtensionLoader(Serialization.class).getExtension("nativejava") - .serialize(null, bos).writeObject(Integer.MAX_VALUE); - obj = genericService.$invoke("echo", new String[]{int.class.getName()}, new Object[]{bos.toByteArray()}); + ExtensionLoader.getExtensionLoader(Serialization.class) + .getExtension("nativejava") + .serialize(null, bos) + .writeObject(Integer.MAX_VALUE); + obj = genericService.$invoke("echo", new String[] {int.class.getName()}, new Object[] {bos.toByteArray()}); Assertions.assertTrue(obj instanceof byte[]); - Assertions.assertEquals(Integer.MAX_VALUE, + Assertions.assertEquals( + Integer.MAX_VALUE, ExtensionLoader.getExtensionLoader(Serialization.class) .getExtension("nativejava") .deserialize(null, new ByteArrayInputStream((byte[]) obj)) @@ -242,14 +254,18 @@ class GenericServiceTest { user.setName("zhangsan"); List users = new ArrayList(); users.add(user); - Object result = genericService.$invoke("getUsers", new String[]{ReflectUtils.getName(List.class)}, new Object[]{JavaBeanSerializeUtil.serialize(users, JavaBeanAccessor.METHOD)}); + Object result = + genericService.$invoke("getUsers", new String[] {ReflectUtils.getName(List.class)}, new Object[] { + JavaBeanSerializeUtil.serialize(users, JavaBeanAccessor.METHOD) + }); Assertions.assertTrue(result instanceof JavaBeanDescriptor); JavaBeanDescriptor descriptor = (JavaBeanDescriptor) result; Assertions.assertTrue(descriptor.isCollectionType()); Assertions.assertEquals(1, descriptor.propertySize()); descriptor = (JavaBeanDescriptor) descriptor.getProperty(0); Assertions.assertTrue(descriptor.isBeanType()); - Assertions.assertEquals(user.getName(), ((JavaBeanDescriptor) descriptor.getProperty("name")).getPrimitiveProperty()); + Assertions.assertEquals( + user.getName(), ((JavaBeanDescriptor) descriptor.getProperty("name")).getPrimitiveProperty()); } finally { bootstrap.stop(); } @@ -316,7 +332,8 @@ class GenericServiceTest { descriptor = (JavaBeanDescriptor) descriptor.getProperty(0); Assertions.assertTrue(descriptor.isBeanType()); Assertions.assertEquals(User.class.getName(), descriptor.getClassName()); - Assertions.assertEquals(user.getName(), ((JavaBeanDescriptor) descriptor.getProperty("name")).getPrimitiveProperty()); + Assertions.assertEquals( + user.getName(), ((JavaBeanDescriptor) descriptor.getProperty("name")).getPrimitiveProperty()); Assertions.assertNull(demoService.sayName("zhangsan")); } finally { bootstrap.stop(); @@ -331,5 +348,4 @@ class GenericServiceTest { Object[] arguments; } - -} \ No newline at end of file +} diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/User.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/User.java index 8cb7a59eb3..f0c7ffd2ad 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/User.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/User.java @@ -27,8 +27,7 @@ public class User implements Serializable { private String name; - public User() { - } + public User() {} public User(String name) { this.name = name; @@ -61,5 +60,4 @@ public class User implements Serializable { } return false; } - } diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/permission/DefaultAnonymousAccessPermissionCheckerTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/permission/DefaultAnonymousAccessPermissionCheckerTest.java index eef2013fde..9524b1fa40 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/permission/DefaultAnonymousAccessPermissionCheckerTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/permission/DefaultAnonymousAccessPermissionCheckerTest.java @@ -20,15 +20,15 @@ import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.PermissionLevel; import org.apache.dubbo.qos.api.QosConfiguration; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.UnknownHostException; + import io.netty.channel.Channel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.UnknownHostException; - class DefaultAnonymousAccessPermissionCheckerTest { @Test void testPermission() throws UnknownHostException { diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/protocol/QosProtocolWrapperTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/protocol/QosProtocolWrapperTest.java index f3b0def49c..f6a19e4b5c 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/protocol/QosProtocolWrapperTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/protocol/QosProtocolWrapperTest.java @@ -109,7 +109,7 @@ class QosProtocolWrapperTest { @Test void testMultiProtocol() throws Exception { - //tri protocol start first, acceptForeignIp = true + // tri protocol start first, acceptForeignIp = true triWrapper.export(triInvoker); assertThat(server.isStarted(), is(true)); assertThat(server.getHost(), is("localhost")); @@ -117,7 +117,7 @@ class QosProtocolWrapperTest { assertThat(server.isAcceptForeignIp(), is(true)); verify(triProtocol).export(triInvoker); - //next registry protocol server still acceptForeignIp=true even though wrapper invoker url set false + // next registry protocol server still acceptForeignIp=true even though wrapper invoker url set false wrapper.export(invoker); assertThat(server.isStarted(), is(true)); assertThat(server.getHost(), is("localhost")); diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/ForeignHostPermitHandlerTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/ForeignHostPermitHandlerTest.java index 574d1171d1..f8a193535e 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/ForeignHostPermitHandlerTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/ForeignHostPermitHandlerTest.java @@ -16,20 +16,21 @@ */ package org.apache.dubbo.qos.server.handler; +import org.apache.dubbo.common.utils.StringUtils; +import org.apache.dubbo.qos.api.PermissionLevel; +import org.apache.dubbo.qos.api.QosConfiguration; + +import java.net.InetAddress; +import java.net.InetSocketAddress; + import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.qos.api.PermissionLevel; -import org.apache.dubbo.qos.api.QosConfiguration; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; -import java.net.InetAddress; -import java.net.InetSocketAddress; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.mockito.ArgumentMatchers.any; @@ -50,17 +51,17 @@ class ForeignHostPermitHandlerTest { when(channel.remoteAddress()).thenReturn(address); ChannelFuture future = mock(ChannelFuture.class); when(context.writeAndFlush(any(ByteBuf.class))).thenReturn(future); - ForeignHostPermitHandler handler = new ForeignHostPermitHandler( - QosConfiguration.builder() + ForeignHostPermitHandler handler = new ForeignHostPermitHandler(QosConfiguration.builder() .acceptForeignIp(false) .acceptForeignIpWhitelist(StringUtils.EMPTY_STRING) .anonymousAccessPermissionLevel(PermissionLevel.NONE.name()) - .build() - ); + .build()); handler.handlerAdded(context); ArgumentCaptor captor = ArgumentCaptor.forClass(ByteBuf.class); verify(context).writeAndFlush(captor.capture()); - assertThat(new String(captor.getValue().array()), containsString("Foreign Ip Not Permitted, Consider Config It In Whitelist")); + assertThat( + new String(captor.getValue().array()), + containsString("Foreign Ip Not Permitted, Consider Config It In Whitelist")); verify(future).addListener(ChannelFutureListener.CLOSE); } @@ -76,18 +77,18 @@ class ForeignHostPermitHandlerTest { when(channel.remoteAddress()).thenReturn(address); ChannelFuture future = mock(ChannelFuture.class); when(context.writeAndFlush(any(ByteBuf.class))).thenReturn(future); - ForeignHostPermitHandler handler = new ForeignHostPermitHandler( - QosConfiguration.builder() + ForeignHostPermitHandler handler = new ForeignHostPermitHandler(QosConfiguration.builder() .acceptForeignIp(false) .acceptForeignIpWhitelist("175.23.44.1 , 192.168.1.192/26") .anonymousAccessPermissionLevel(PermissionLevel.NONE.name()) - .build() - ); + .build()); handler.handlerAdded(context); ArgumentCaptor captor = ArgumentCaptor.forClass(ByteBuf.class); verify(context).writeAndFlush(captor.capture()); - assertThat(new String(captor.getValue().array()), containsString("Foreign Ip Not Permitted, Consider Config It In Whitelist")); + assertThat( + new String(captor.getValue().array()), + containsString("Foreign Ip Not Permitted, Consider Config It In Whitelist")); verify(future).addListener(ChannelFutureListener.CLOSE); } @@ -102,12 +103,10 @@ class ForeignHostPermitHandlerTest { InetSocketAddress address = new InetSocketAddress(addr, 12345); when(channel.remoteAddress()).thenReturn(address); - ForeignHostPermitHandler handler = new ForeignHostPermitHandler( - QosConfiguration.builder() + ForeignHostPermitHandler handler = new ForeignHostPermitHandler(QosConfiguration.builder() .acceptForeignIp(false) .acceptForeignIpWhitelist("175.23.44.1, 192.168.1.192/26 ") - .build() - ); + .build()); handler.handlerAdded(context); verify(context, never()).writeAndFlush(any()); } @@ -123,30 +122,27 @@ class ForeignHostPermitHandlerTest { InetSocketAddress address = new InetSocketAddress(addr, 12345); when(channel.remoteAddress()).thenReturn(address); - ForeignHostPermitHandler handler = new ForeignHostPermitHandler( - QosConfiguration.builder() + ForeignHostPermitHandler handler = new ForeignHostPermitHandler(QosConfiguration.builder() .acceptForeignIp(false) .acceptForeignIpWhitelist("175.23.44.1, 192.168.1.192/26") - .build() - ); + .build()); handler.handlerAdded(context); verify(context, never()).writeAndFlush(any()); } @Test - void shouldNotShowIpNotPermittedMsg_GivenAcceptForeignIpFalseAndNotMatchWhiteListAndPermissionConfig() throws Exception { + void shouldNotShowIpNotPermittedMsg_GivenAcceptForeignIpFalseAndNotMatchWhiteListAndPermissionConfig() + throws Exception { ChannelHandlerContext context = mock(ChannelHandlerContext.class); Channel channel = mock(Channel.class); when(context.channel()).thenReturn(channel); ChannelFuture future = mock(ChannelFuture.class); when(context.writeAndFlush(any(ByteBuf.class))).thenReturn(future); - ForeignHostPermitHandler handler = new ForeignHostPermitHandler( - QosConfiguration.builder() + ForeignHostPermitHandler handler = new ForeignHostPermitHandler(QosConfiguration.builder() .acceptForeignIp(false) .acceptForeignIpWhitelist("175.23.44.1 , 192.168.1.192/26") .anonymousAccessPermissionLevel(PermissionLevel.PROTECTED.name()) - .build() - ); + .build()); handler.handlerAdded(context); verify(future, never()).addListener(ChannelFutureListener.CLOSE); diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/HttpProcessHandlerTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/HttpProcessHandlerTest.java index 7afb2becab..9919557e81 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/HttpProcessHandlerTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/HttpProcessHandlerTest.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.qos.server.handler; -import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.qos.api.PermissionLevel; +import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.rpc.model.FrameworkModel; import io.netty.channel.ChannelFuture; @@ -45,7 +45,8 @@ class HttpProcessHandlerTest { when(context.writeAndFlush(any(FullHttpResponse.class))).thenReturn(future); HttpRequest message = Mockito.mock(HttpRequest.class); when(message.uri()).thenReturn("test"); - HttpProcessHandler handler = new HttpProcessHandler(FrameworkModel.defaultModel(), QosConfiguration.builder().build()); + HttpProcessHandler handler = new HttpProcessHandler( + FrameworkModel.defaultModel(), QosConfiguration.builder().build()); handler.channelRead0(context, message); verify(future).addListener(ChannelFutureListener.CLOSE); ArgumentCaptor captor = ArgumentCaptor.forClass(FullHttpResponse.class); @@ -62,10 +63,11 @@ class HttpProcessHandlerTest { HttpRequest message = Mockito.mock(HttpRequest.class); when(message.uri()).thenReturn("localhost:80/greeting"); when(message.method()).thenReturn(HttpMethod.GET); - HttpProcessHandler handler = new HttpProcessHandler(FrameworkModel.defaultModel(), - QosConfiguration.builder() - .anonymousAccessPermissionLevel(PermissionLevel.NONE.name()) - .build()); + HttpProcessHandler handler = new HttpProcessHandler( + FrameworkModel.defaultModel(), + QosConfiguration.builder() + .anonymousAccessPermissionLevel(PermissionLevel.NONE.name()) + .build()); handler.channelRead0(context, message); verify(future).addListener(ChannelFutureListener.CLOSE); ArgumentCaptor captor = ArgumentCaptor.forClass(FullHttpResponse.class); @@ -82,10 +84,11 @@ class HttpProcessHandlerTest { HttpRequest message = Mockito.mock(HttpRequest.class); when(message.uri()).thenReturn("localhost:80/test"); when(message.method()).thenReturn(HttpMethod.GET); - HttpProcessHandler handler = new HttpProcessHandler(FrameworkModel.defaultModel(), - QosConfiguration.builder() - .anonymousAccessPermissionLevel(PermissionLevel.NONE.name()) - .build()); + HttpProcessHandler handler = new HttpProcessHandler( + FrameworkModel.defaultModel(), + QosConfiguration.builder() + .anonymousAccessPermissionLevel(PermissionLevel.NONE.name()) + .build()); handler.channelRead0(context, message); verify(future).addListener(ChannelFutureListener.CLOSE); ArgumentCaptor captor = ArgumentCaptor.forClass(FullHttpResponse.class); diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/QosProcessHandlerTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/QosProcessHandlerTest.java index 487496e019..9a27ea8472 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/QosProcessHandlerTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/QosProcessHandlerTest.java @@ -20,6 +20,8 @@ import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.rpc.model.FrameworkModel; +import java.util.Collections; + import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; @@ -32,8 +34,6 @@ import io.netty.handler.codec.string.StringEncoder; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.Collections; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; @@ -44,13 +44,13 @@ class QosProcessHandlerTest { ChannelHandlerContext context = Mockito.mock(ChannelHandlerContext.class); ChannelPipeline pipeline = Mockito.mock(ChannelPipeline.class); Mockito.when(context.pipeline()).thenReturn(pipeline); - QosProcessHandler handler = new QosProcessHandler(FrameworkModel.defaultModel(), - QosConfiguration.builder() - .welcome("welcome") - .acceptForeignIp(false) - .acceptForeignIpWhitelist(StringUtils.EMPTY_STRING) - .build() - ); + QosProcessHandler handler = new QosProcessHandler( + FrameworkModel.defaultModel(), + QosConfiguration.builder() + .welcome("welcome") + .acceptForeignIp(false) + .acceptForeignIpWhitelist(StringUtils.EMPTY_STRING) + .build()); handler.decode(context, buf, Collections.emptyList()); verify(pipeline).addLast(any(HttpServerCodec.class)); verify(pipeline).addLast(any(HttpObjectAggregator.class)); @@ -64,13 +64,13 @@ class QosProcessHandlerTest { ChannelHandlerContext context = Mockito.mock(ChannelHandlerContext.class); ChannelPipeline pipeline = Mockito.mock(ChannelPipeline.class); Mockito.when(context.pipeline()).thenReturn(pipeline); - QosProcessHandler handler = new QosProcessHandler(FrameworkModel.defaultModel(), - QosConfiguration.builder() - .welcome("welcome") - .acceptForeignIp(false) - .acceptForeignIpWhitelist(StringUtils.EMPTY_STRING) - .build() - ); + QosProcessHandler handler = new QosProcessHandler( + FrameworkModel.defaultModel(), + QosConfiguration.builder() + .welcome("welcome") + .acceptForeignIp(false) + .acceptForeignIpWhitelist(StringUtils.EMPTY_STRING) + .build()); handler.decode(context, buf, Collections.emptyList()); verify(pipeline).addLast(any(LineBasedFrameDecoder.class)); verify(pipeline).addLast(any(StringDecoder.class)); @@ -78,6 +78,4 @@ class QosProcessHandlerTest { verify(pipeline).addLast(any(TelnetProcessHandler.class)); verify(pipeline).remove(handler); } - - } diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/TelnetProcessHandlerTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/TelnetProcessHandlerTest.java index 045bcd3942..e3bd8b8b28 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/TelnetProcessHandlerTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/TelnetProcessHandlerTest.java @@ -16,8 +16,8 @@ */ package org.apache.dubbo.qos.server.handler; -import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.qos.api.PermissionLevel; +import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.rpc.model.FrameworkModel; import io.netty.channel.ChannelFuture; @@ -38,10 +38,11 @@ class TelnetProcessHandlerTest { @Test void testPrompt() throws Exception { ChannelHandlerContext context = mock(ChannelHandlerContext.class); - TelnetProcessHandler handler = new TelnetProcessHandler(FrameworkModel.defaultModel(), - QosConfiguration.builder() - .anonymousAccessPermissionLevel(PermissionLevel.NONE.name()) - .build()); + TelnetProcessHandler handler = new TelnetProcessHandler( + FrameworkModel.defaultModel(), + QosConfiguration.builder() + .anonymousAccessPermissionLevel(PermissionLevel.NONE.name()) + .build()); handler.channelRead0(context, ""); verify(context).writeAndFlush(QosProcessHandler.PROMPT); } @@ -49,7 +50,8 @@ class TelnetProcessHandlerTest { @Test void testBye() throws Exception { ChannelHandlerContext context = mock(ChannelHandlerContext.class); - TelnetProcessHandler handler = new TelnetProcessHandler(FrameworkModel.defaultModel(), QosConfiguration.builder().build()); + TelnetProcessHandler handler = new TelnetProcessHandler( + FrameworkModel.defaultModel(), QosConfiguration.builder().build()); ChannelFuture future = mock(ChannelFuture.class); when(context.writeAndFlush("BYE!\n")).thenReturn(future); handler.channelRead0(context, "quit"); @@ -59,7 +61,8 @@ class TelnetProcessHandlerTest { @Test void testUnknownCommand() throws Exception { ChannelHandlerContext context = mock(ChannelHandlerContext.class); - TelnetProcessHandler handler = new TelnetProcessHandler(FrameworkModel.defaultModel(), QosConfiguration.builder().build()); + TelnetProcessHandler handler = new TelnetProcessHandler( + FrameworkModel.defaultModel(), QosConfiguration.builder().build()); handler.channelRead0(context, "unknown"); ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); verify(context, Mockito.atLeastOnce()).writeAndFlush(captor.capture()); @@ -69,10 +72,11 @@ class TelnetProcessHandlerTest { @Test void testGreeting() throws Exception { ChannelHandlerContext context = mock(ChannelHandlerContext.class); - TelnetProcessHandler handler = new TelnetProcessHandler(FrameworkModel.defaultModel(), - QosConfiguration.builder() - .anonymousAccessPermissionLevel(PermissionLevel.NONE.name()) - .build()); + TelnetProcessHandler handler = new TelnetProcessHandler( + FrameworkModel.defaultModel(), + QosConfiguration.builder() + .anonymousAccessPermissionLevel(PermissionLevel.NONE.name()) + .build()); handler.channelRead0(context, "greeting"); ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); verify(context).writeAndFlush(captor.capture()); diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TKvTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TKvTest.java index dc9d5d60ba..d90bbf2e58 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TKvTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TKvTest.java @@ -24,14 +24,14 @@ import static org.hamcrest.Matchers.containsString; class TKvTest { @Test void test1() { - TKv tKv = new TKv(new TTable.ColumnDefine(TTable.Align.RIGHT), new TTable.ColumnDefine(10, false, TTable.Align.LEFT)); + TKv tKv = new TKv( + new TTable.ColumnDefine(TTable.Align.RIGHT), new TTable.ColumnDefine(10, false, TTable.Align.LEFT)); tKv.add("KEY-1", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); tKv.add("KEY-2", "1234567890"); tKv.add("KEY-3", "1234567890"); - TTable tTable = new TTable(new TTable.ColumnDefine[]{ - new TTable.ColumnDefine(), - new TTable.ColumnDefine(20, false, TTable.Align.LEFT) + TTable tTable = new TTable(new TTable.ColumnDefine[] { + new TTable.ColumnDefine(), new TTable.ColumnDefine(20, false, TTable.Align.LEFT) }); String kv = tKv.rendering(); @@ -57,4 +57,4 @@ class TKvTest { assertThat(kv, containsString("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); System.out.println(kv); } -} \ No newline at end of file +} diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TLadderTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TLadderTest.java index 319f84379b..e181924d95 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TLadderTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TLadderTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -30,11 +30,11 @@ class TLadderTest { ladder.addItem("3"); ladder.addItem("4"); String result = ladder.rendering(); - String expected = "1" + System.lineSeparator() + - " `-2" + System.lineSeparator() + - " `-3" + System.lineSeparator() + - " `-4" + System.lineSeparator(); + String expected = "1" + System.lineSeparator() + " `-2" + + System.lineSeparator() + " `-3" + + System.lineSeparator() + " `-4" + + System.lineSeparator(); assertThat(result, equalTo(expected)); System.out.println(result); } -} \ No newline at end of file +} diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TTableTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TTableTest.java index 7a83be62f4..e40b086ff7 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TTableTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TTableTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -28,28 +28,28 @@ class TTableTest { table.addRow(1, "one", "uno", "un"); table.addRow(2, "two", "dos", "deux"); String result = table.rendering(); - String expected = "+-+---+---+----+" + System.lineSeparator() + - "|1|one|uno|un |" + System.lineSeparator() + - "+-+---+---+----+" + System.lineSeparator() + - "|2|two|dos|deux|" + System.lineSeparator() + - "+-+---+---+----+" + System.lineSeparator(); + String expected = "+-+---+---+----+" + System.lineSeparator() + "|1|one|uno|un |" + + System.lineSeparator() + "+-+---+---+----+" + + System.lineSeparator() + "|2|two|dos|deux|" + + System.lineSeparator() + "+-+---+---+----+" + + System.lineSeparator(); assertThat(result, equalTo(expected)); System.out.println(result); } @Test void test2() throws Exception { - TTable table = new TTable(new TTable.ColumnDefine[]{ - new TTable.ColumnDefine(5, true, TTable.Align.LEFT), - new TTable.ColumnDefine(10, false, TTable.Align.MIDDLE), - new TTable.ColumnDefine(10, false, TTable.Align.RIGHT) + TTable table = new TTable(new TTable.ColumnDefine[] { + new TTable.ColumnDefine(5, true, TTable.Align.LEFT), + new TTable.ColumnDefine(10, false, TTable.Align.MIDDLE), + new TTable.ColumnDefine(10, false, TTable.Align.RIGHT) }); table.addRow(1, "abcde", "ABCDE"); String result = table.rendering(); - String expected = "+-+----------+----------+" + System.lineSeparator() + - "|1| abcde | ABCDE|" + System.lineSeparator() + - "+-+----------+----------+" + System.lineSeparator(); + String expected = "+-+----------+----------+" + System.lineSeparator() + "|1| abcde | ABCDE|" + + System.lineSeparator() + "+-+----------+----------+" + + System.lineSeparator(); assertThat(result, equalTo(expected)); System.out.println(result); } -} \ No newline at end of file +} diff --git a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TTreeTest.java b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TTreeTest.java index d990d244ee..081740876e 100644 --- a/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TTreeTest.java +++ b/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TTreeTest.java @@ -6,7 +6,7 @@ * (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 + * 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, @@ -29,14 +29,13 @@ class TTreeTest { tree.begin("two").begin("TWO").end().begin("2").end().end(); tree.begin("three").end(); String result = tree.rendering(); - String expected = "`---+root\n" + - " +---+one\n" + - " | `---ONE\n" + - " +---+two\n" + - " | +---TWO\n" + - " | `---2\n" + - " `---three\n"; + String expected = "`---+root\n" + " +---+one\n" + + " | `---ONE\n" + + " +---+two\n" + + " | +---TWO\n" + + " | `---2\n" + + " `---three\n"; assertThat(result, equalTo(expected)); System.out.println(result); } -} \ No newline at end of file +} diff --git a/dubbo-plugin/dubbo-reactive/pom.xml b/dubbo-plugin/dubbo-reactive/pom.xml index 9ac35a68a8..f32cbe921e 100644 --- a/dubbo-plugin/dubbo-reactive/pom.xml +++ b/dubbo-plugin/dubbo-reactive/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + - dubbo-reactive - jar + dubbo-reactive + jar - - false - + + false + - - - org.apache.dubbo - dubbo-rpc-triple - ${project.version} - - - org.reactivestreams - reactive-streams - - - io.projectreactor - reactor-core - - + + + org.apache.dubbo + dubbo-rpc-triple + ${project.version} + + + org.reactivestreams + reactive-streams + + + io.projectreactor + reactor-core + + diff --git a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/AbstractTripleReactorPublisher.java b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/AbstractTripleReactorPublisher.java index 0328c59d8f..70d7028a00 100644 --- a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/AbstractTripleReactorPublisher.java +++ b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/AbstractTripleReactorPublisher.java @@ -14,24 +14,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.reactive; import org.apache.dubbo.rpc.protocol.tri.CancelableStreamObserver; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; -import org.reactivestreams.Publisher; -import org.reactivestreams.Subscriber; -import org.reactivestreams.Subscription; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; +import org.reactivestreams.Publisher; +import org.reactivestreams.Subscriber; +import org.reactivestreams.Subscription; + /** * The middle layer between {@link org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver} and Reactive API.

    * 1. passing the data received by CallStreamObserver to Reactive consumer
    * 2. passing the request of Reactive API to CallStreamObserver */ -public abstract class AbstractTripleReactorPublisher extends CancelableStreamObserver implements Publisher, Subscription { +public abstract class AbstractTripleReactorPublisher extends CancelableStreamObserver + implements Publisher, Subscription { private boolean canRequest; @@ -59,8 +60,7 @@ public abstract class AbstractTripleReactorPublisher extends CancelableStream private final AtomicBoolean CALLED_SHUT_DOWN_HOOK = new AtomicBoolean(); - public AbstractTripleReactorPublisher() { - } + public AbstractTripleReactorPublisher() {} public AbstractTripleReactorPublisher(Consumer> onSubscribe, Runnable shutdownHook) { this.onSubscribe = onSubscribe; diff --git a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/AbstractTripleReactorSubscriber.java b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/AbstractTripleReactorSubscriber.java index 96fa64866c..86db857582 100644 --- a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/AbstractTripleReactorSubscriber.java +++ b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/AbstractTripleReactorSubscriber.java @@ -14,17 +14,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.reactive; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; + +import java.util.concurrent.atomic.AtomicBoolean; + import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import reactor.core.CoreSubscriber; import reactor.util.annotation.NonNull; -import java.util.concurrent.atomic.AtomicBoolean; - /** * The middle layer between {@link org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver} and Reactive API.
    * Passing the data from Reactive producer to CallStreamObserver. diff --git a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ClientTripleReactorPublisher.java b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ClientTripleReactorPublisher.java index 1233dd8a54..2ae9022804 100644 --- a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ClientTripleReactorPublisher.java +++ b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ClientTripleReactorPublisher.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.reactive; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; @@ -30,8 +29,7 @@ import java.util.function.Consumer; */ public class ClientTripleReactorPublisher extends AbstractTripleReactorPublisher { - public ClientTripleReactorPublisher() { - } + public ClientTripleReactorPublisher() {} public ClientTripleReactorPublisher(Consumer> onSubscribe, Runnable shutdownHook) { super(onSubscribe, shutdownHook); diff --git a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ClientTripleReactorSubscriber.java b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ClientTripleReactorSubscriber.java index 7d59244d3d..cc4f0de86f 100644 --- a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ClientTripleReactorSubscriber.java +++ b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ClientTripleReactorSubscriber.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.reactive; import org.apache.dubbo.rpc.protocol.tri.observer.ClientCallToObserverAdapter; diff --git a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ServerTripleReactorPublisher.java b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ServerTripleReactorPublisher.java index 8f5382e169..c5b9336741 100644 --- a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ServerTripleReactorPublisher.java +++ b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ServerTripleReactorPublisher.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.reactive; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; diff --git a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ServerTripleReactorSubscriber.java b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ServerTripleReactorSubscriber.java index 1e8ef5e37f..ce4206b2b6 100644 --- a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ServerTripleReactorSubscriber.java +++ b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ServerTripleReactorSubscriber.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.reactive; import org.apache.dubbo.rpc.CancellationContext; diff --git a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/calls/ReactorClientCalls.java b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/calls/ReactorClientCalls.java index c23e9874b9..dfe55003f3 100644 --- a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/calls/ReactorClientCalls.java +++ b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/calls/ReactorClientCalls.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.reactive.calls; import org.apache.dubbo.common.stream.StreamObserver; @@ -24,6 +23,7 @@ import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.model.StubMethodDescriptor; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; import org.apache.dubbo.rpc.stub.StubInvocationUtil; + import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -32,8 +32,7 @@ import reactor.core.publisher.Mono; */ public final class ReactorClientCalls { - private ReactorClientCalls() { - } + private ReactorClientCalls() {} /** * Implements a unary -> unary call as Mono -> Mono @@ -43,29 +42,28 @@ public final class ReactorClientCalls { * @param methodDescriptor the method descriptor * @return the mono with response */ - public static Mono oneToOne(Invoker invoker, - Mono monoRequest, - StubMethodDescriptor methodDescriptor) { + public static Mono oneToOne( + Invoker invoker, Mono monoRequest, StubMethodDescriptor methodDescriptor) { try { return Mono.create(emitter -> monoRequest.subscribe( - request -> StubInvocationUtil.unaryCall(invoker, methodDescriptor, request, new StreamObserver() { - @Override - public void onNext(TResponse tResponse) { - emitter.success(tResponse); - } + request -> StubInvocationUtil.unaryCall( + invoker, methodDescriptor, request, new StreamObserver() { + @Override + public void onNext(TResponse tResponse) { + emitter.success(tResponse); + } - @Override - public void onError(Throwable throwable) { - emitter.error(throwable); - } + @Override + public void onError(Throwable throwable) { + emitter.error(throwable); + } - @Override - public void onCompleted() { - // Do nothing - } - }), - emitter::error - )); + @Override + public void onCompleted() { + // Do nothing + } + }), + emitter::error)); } catch (Throwable throwable) { return Mono.error(throwable); } @@ -79,16 +77,14 @@ public final class ReactorClientCalls { * @param methodDescriptor the method descriptor * @return the flux with response */ - public static Flux oneToMany(Invoker invoker, - Mono monoRequest, - StubMethodDescriptor methodDescriptor) { + public static Flux oneToMany( + Invoker invoker, Mono monoRequest, StubMethodDescriptor methodDescriptor) { try { - return monoRequest - .flatMapMany(request -> { - ClientTripleReactorPublisher clientPublisher = new ClientTripleReactorPublisher<>(); - StubInvocationUtil.serverStreamCall(invoker, methodDescriptor, request, clientPublisher); - return clientPublisher; - }); + return monoRequest.flatMapMany(request -> { + ClientTripleReactorPublisher clientPublisher = new ClientTripleReactorPublisher<>(); + StubInvocationUtil.serverStreamCall(invoker, methodDescriptor, request, clientPublisher); + return clientPublisher; + }); } catch (Throwable throwable) { return Flux.error(throwable); } @@ -102,16 +98,16 @@ public final class ReactorClientCalls { * @param methodDescriptor the method descriptor * @return the mono with response */ - public static Mono manyToOne(Invoker invoker, - Flux requestFlux, - StubMethodDescriptor methodDescriptor) { + public static Mono manyToOne( + Invoker invoker, Flux requestFlux, StubMethodDescriptor methodDescriptor) { try { - ClientTripleReactorSubscriber clientSubscriber = requestFlux.subscribeWith(new ClientTripleReactorSubscriber<>()); + ClientTripleReactorSubscriber clientSubscriber = + requestFlux.subscribeWith(new ClientTripleReactorSubscriber<>()); ClientTripleReactorPublisher clientPublisher = new ClientTripleReactorPublisher<>( - s -> clientSubscriber.subscribe((CallStreamObserver) s), - clientSubscriber::cancel); - return Mono.from(clientPublisher).doOnSubscribe(dummy -> - StubInvocationUtil.biOrClientStreamCall(invoker, methodDescriptor, clientPublisher)); + s -> clientSubscriber.subscribe((CallStreamObserver) s), clientSubscriber::cancel); + return Mono.from(clientPublisher) + .doOnSubscribe(dummy -> + StubInvocationUtil.biOrClientStreamCall(invoker, methodDescriptor, clientPublisher)); } catch (Throwable throwable) { return Mono.error(throwable); } @@ -125,19 +121,18 @@ public final class ReactorClientCalls { * @param methodDescriptor the method descriptor * @return the flux with response */ - public static Flux manyToMany(Invoker invoker, - Flux requestFlux, - StubMethodDescriptor methodDescriptor) { + public static Flux manyToMany( + Invoker invoker, Flux requestFlux, StubMethodDescriptor methodDescriptor) { try { - ClientTripleReactorSubscriber clientSubscriber = requestFlux.subscribeWith(new ClientTripleReactorSubscriber<>()); + ClientTripleReactorSubscriber clientSubscriber = + requestFlux.subscribeWith(new ClientTripleReactorSubscriber<>()); ClientTripleReactorPublisher clientPublisher = new ClientTripleReactorPublisher<>( - s -> clientSubscriber.subscribe((CallStreamObserver) s), - clientSubscriber::cancel); - return Flux.from(clientPublisher).doOnSubscribe(dummy -> - StubInvocationUtil.biOrClientStreamCall(invoker, methodDescriptor, clientPublisher)); + s -> clientSubscriber.subscribe((CallStreamObserver) s), clientSubscriber::cancel); + return Flux.from(clientPublisher) + .doOnSubscribe(dummy -> + StubInvocationUtil.biOrClientStreamCall(invoker, methodDescriptor, clientPublisher)); } catch (Throwable throwable) { return Flux.error(throwable); } } - } diff --git a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/calls/ReactorServerCalls.java b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/calls/ReactorServerCalls.java index e9ce9bd41d..b514bfaf44 100644 --- a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/calls/ReactorServerCalls.java +++ b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/calls/ReactorServerCalls.java @@ -14,26 +14,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.reactive.calls; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.reactive.ServerTripleReactorPublisher; import org.apache.dubbo.reactive.ServerTripleReactorSubscriber; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; import java.util.concurrent.CompletableFuture; import java.util.function.Function; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + /** * A collection of methods to convert server-side stream calls to Reactor calls. */ public final class ReactorServerCalls { - private ReactorServerCalls() { - } + private ReactorServerCalls() {} /** * Implements a unary -> unary call as Mono -> Mono @@ -42,19 +41,16 @@ public final class ReactorServerCalls { * @param responseObserver response StreamObserver * @param func service implementation */ - public static void oneToOne(T request, - StreamObserver responseObserver, - Function, Mono> func) { + public static void oneToOne(T request, StreamObserver responseObserver, Function, Mono> func) { func.apply(Mono.just(request)).subscribe(res -> { - CompletableFuture.completedFuture(res) - .whenComplete((r, t) -> { - if (t != null) { - responseObserver.onError(t); - } else { - responseObserver.onNext(r); - responseObserver.onCompleted(); - } - }); + CompletableFuture.completedFuture(res).whenComplete((r, t) -> { + if (t != null) { + responseObserver.onError(t); + } else { + responseObserver.onNext(r); + responseObserver.onCompleted(); + } + }); }); } @@ -65,9 +61,8 @@ public final class ReactorServerCalls { * @param responseObserver response StreamObserver * @param func service implementation */ - public static void oneToMany(T request, - StreamObserver responseObserver, - Function, Flux> func) { + public static void oneToMany( + T request, StreamObserver responseObserver, Function, Flux> func) { try { Flux response = func.apply(Mono.just(request)); ServerTripleReactorSubscriber subscriber = response.subscribeWith(new ServerTripleReactorSubscriber<>()); @@ -84,25 +79,26 @@ public final class ReactorServerCalls { * @param func service implementation * @return request StreamObserver */ - public static StreamObserver manyToOne(StreamObserver responseObserver, - Function, Mono> func) { - ServerTripleReactorPublisher serverPublisher = new ServerTripleReactorPublisher((CallStreamObserver) responseObserver); + public static StreamObserver manyToOne( + StreamObserver responseObserver, Function, Mono> func) { + ServerTripleReactorPublisher serverPublisher = + new ServerTripleReactorPublisher((CallStreamObserver) responseObserver); try { Mono responseMono = func.apply(Flux.from(serverPublisher)); - responseMono.subscribe(value -> { - // Don't try to respond if the server has already canceled the request - if (!serverPublisher.isCancelled()) { - responseObserver.onNext(value); - } - }, - throwable -> { - // Don't try to respond if the server has already canceled the request - if (!serverPublisher.isCancelled()) { - responseObserver.onError(throwable); - } - }, - responseObserver::onCompleted - ); + responseMono.subscribe( + value -> { + // Don't try to respond if the server has already canceled the request + if (!serverPublisher.isCancelled()) { + responseObserver.onNext(value); + } + }, + throwable -> { + // Don't try to respond if the server has already canceled the request + if (!serverPublisher.isCancelled()) { + responseObserver.onError(throwable); + } + }, + responseObserver::onCompleted); serverPublisher.startRequest(); } catch (Throwable throwable) { responseObserver.onError(throwable); @@ -117,13 +113,15 @@ public final class ReactorServerCalls { * @param func service implementation * @return request StreamObserver */ - public static StreamObserver manyToMany(StreamObserver responseObserver, - Function, Flux> func) { + public static StreamObserver manyToMany( + StreamObserver responseObserver, Function, Flux> func) { // responseObserver is also a subscription of publisher, we can use it to request more data - ServerTripleReactorPublisher serverPublisher = new ServerTripleReactorPublisher((CallStreamObserver) responseObserver); + ServerTripleReactorPublisher serverPublisher = + new ServerTripleReactorPublisher((CallStreamObserver) responseObserver); try { Flux responseFlux = func.apply(Flux.from(serverPublisher)); - ServerTripleReactorSubscriber serverSubscriber = responseFlux.subscribeWith(new ServerTripleReactorSubscriber<>()); + ServerTripleReactorSubscriber serverSubscriber = + responseFlux.subscribeWith(new ServerTripleReactorSubscriber<>()); serverSubscriber.subscribe((CallStreamObserver) responseObserver); serverPublisher.startRequest(); } catch (Throwable throwable) { diff --git a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/ManyToManyMethodHandler.java b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/ManyToManyMethodHandler.java index 72f9b50905..6c14436249 100644 --- a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/ManyToManyMethodHandler.java +++ b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/ManyToManyMethodHandler.java @@ -14,18 +14,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.reactive.handler; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.reactive.calls.ReactorServerCalls; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; import org.apache.dubbo.rpc.stub.StubMethodHandler; -import reactor.core.publisher.Flux; import java.util.concurrent.CompletableFuture; import java.util.function.Function; +import reactor.core.publisher.Flux; + /** * The handler of ManyToMany() method for stub invocation. */ diff --git a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/ManyToOneMethodHandler.java b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/ManyToOneMethodHandler.java index d74a9ab118..f82a6a614b 100644 --- a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/ManyToOneMethodHandler.java +++ b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/ManyToOneMethodHandler.java @@ -14,19 +14,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.reactive.handler; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.reactive.calls.ReactorServerCalls; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; import org.apache.dubbo.rpc.stub.StubMethodHandler; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; import java.util.concurrent.CompletableFuture; import java.util.function.Function; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + /** * The handler of ManyToOne() method for stub invocation. */ diff --git a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/OneToManyMethodHandler.java b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/OneToManyMethodHandler.java index a672c5b852..b5b0534fff 100644 --- a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/OneToManyMethodHandler.java +++ b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/OneToManyMethodHandler.java @@ -14,18 +14,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.reactive.handler; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.reactive.calls.ReactorServerCalls; import org.apache.dubbo.rpc.stub.StubMethodHandler; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; import java.util.concurrent.CompletableFuture; import java.util.function.Function; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + /** * The handler of OneToMany() method for stub invocation. */ diff --git a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/OneToOneMethodHandler.java b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/OneToOneMethodHandler.java index f20a3ece5e..7cf32a2dba 100644 --- a/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/OneToOneMethodHandler.java +++ b/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/OneToOneMethodHandler.java @@ -14,18 +14,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.reactive.handler; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.reactive.calls.ReactorServerCalls; import org.apache.dubbo.rpc.stub.FutureToObserverAdaptor; import org.apache.dubbo.rpc.stub.StubMethodHandler; -import reactor.core.publisher.Mono; import java.util.concurrent.CompletableFuture; import java.util.function.Function; +import reactor.core.publisher.Mono; + /** * The handler of OneToOne() method for stub invocation. */ diff --git a/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/CreateObserverAdapter.java b/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/CreateObserverAdapter.java index 1f979efc78..99f44c7cc5 100644 --- a/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/CreateObserverAdapter.java +++ b/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/CreateObserverAdapter.java @@ -14,15 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.reactive; import org.apache.dubbo.rpc.protocol.tri.observer.ServerCallToObserverAdapter; -import org.mockito.Mockito; - import java.util.concurrent.atomic.AtomicInteger; +import org.mockito.Mockito; + import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; @@ -41,13 +40,9 @@ public class CreateObserverAdapter { errorCounter = new AtomicInteger(); responseObserver = Mockito.mock(ServerCallToObserverAdapter.class); - doAnswer(o -> nextCounter.incrementAndGet()) - .when(responseObserver).onNext(anyString()); - doAnswer(o -> completeCounter.incrementAndGet()) - .when(responseObserver).onCompleted(); - doAnswer(o -> errorCounter.incrementAndGet()) - .when(responseObserver).onError(any(Throwable.class)); - + doAnswer(o -> nextCounter.incrementAndGet()).when(responseObserver).onNext(anyString()); + doAnswer(o -> completeCounter.incrementAndGet()).when(responseObserver).onCompleted(); + doAnswer(o -> errorCounter.incrementAndGet()).when(responseObserver).onError(any(Throwable.class)); } public AtomicInteger getCompleteCounter() { diff --git a/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/ManyToManyMethodHandlerTest.java b/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/ManyToManyMethodHandlerTest.java index 42276cdd8b..ddad0dd86f 100644 --- a/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/ManyToManyMethodHandlerTest.java +++ b/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/ManyToManyMethodHandlerTest.java @@ -14,18 +14,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.reactive; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.reactive.handler.ManyToManyMethodHandler; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + /** * Unit test for ManyToManyMethodHandler */ @@ -34,9 +33,9 @@ public final class ManyToManyMethodHandlerTest { void testInvoke() throws ExecutionException, InterruptedException { CreateObserverAdapter creator = new CreateObserverAdapter(); - ManyToManyMethodHandler handler = new ManyToManyMethodHandler<>(requestFlux -> - requestFlux.map(r -> r + "0")); - CompletableFuture> future = handler.invoke(new Object[]{creator.getResponseObserver()}); + ManyToManyMethodHandler handler = + new ManyToManyMethodHandler<>(requestFlux -> requestFlux.map(r -> r + "0")); + CompletableFuture> future = handler.invoke(new Object[] {creator.getResponseObserver()}); StreamObserver requestObserver = future.get(); for (int i = 0; i < 10; i++) { requestObserver.onNext(String.valueOf(i)); diff --git a/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/ManyToOneMethodHandlerTest.java b/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/ManyToOneMethodHandlerTest.java index e1c8fd3122..693d4cce62 100644 --- a/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/ManyToOneMethodHandlerTest.java +++ b/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/ManyToOneMethodHandlerTest.java @@ -14,23 +14,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.reactive; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.reactive.handler.ManyToOneMethodHandler; -import org.apache.dubbo.rpc.protocol.tri.observer.ServerCallToObserverAdapter; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.atomic.AtomicInteger; - -import static org.mockito.ArgumentMatchers.any; - /** * Unit test for ManyToOneMethodHandler */ @@ -43,8 +38,8 @@ public final class ManyToOneMethodHandlerTest { void init() throws ExecutionException, InterruptedException { creator = new CreateObserverAdapter(); ManyToOneMethodHandler handler = new ManyToOneMethodHandler<>(requestFlux -> - requestFlux.map(Integer::valueOf).reduce(Integer::sum).map(String::valueOf)); - CompletableFuture> future = handler.invoke(new Object[]{creator.getResponseObserver()}); + requestFlux.map(Integer::valueOf).reduce(Integer::sum).map(String::valueOf)); + CompletableFuture> future = handler.invoke(new Object[] {creator.getResponseObserver()}); requestObserver = future.get(); } diff --git a/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/OneToManyMethodHandlerTest.java b/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/OneToManyMethodHandlerTest.java index 2fbba77633..e81e0a77c7 100644 --- a/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/OneToManyMethodHandlerTest.java +++ b/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/OneToManyMethodHandlerTest.java @@ -14,22 +14,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.reactive; import org.apache.dubbo.reactive.handler.OneToManyMethodHandler; -import org.apache.dubbo.rpc.protocol.tri.observer.ServerCallToObserverAdapter; + +import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import reactor.core.publisher.Flux; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.atomic.AtomicInteger; - -import static org.mockito.ArgumentMatchers.any; - /** * Unit test for OneToManyMethodHandler */ @@ -45,9 +40,9 @@ public final class OneToManyMethodHandlerTest { @Test void testInvoke() { String request = "1,2,3,4,5,6,7"; - OneToManyMethodHandler handler = new OneToManyMethodHandler<>(requestMono -> - requestMono.flatMapMany(r -> Flux.fromArray(r.split(",")))); - CompletableFuture future = handler.invoke(new Object[]{request, creator.getResponseObserver()}); + OneToManyMethodHandler handler = + new OneToManyMethodHandler<>(requestMono -> requestMono.flatMapMany(r -> Flux.fromArray(r.split(",")))); + CompletableFuture future = handler.invoke(new Object[] {request, creator.getResponseObserver()}); Assertions.assertTrue(future.isDone()); Assertions.assertEquals(7, creator.getNextCounter().get()); Assertions.assertEquals(0, creator.getErrorCounter().get()); @@ -57,17 +52,17 @@ public final class OneToManyMethodHandlerTest { @Test void testError() { String request = "1,2,3,4,5,6,7"; - OneToManyMethodHandler handler = new OneToManyMethodHandler<>(requestMono -> - Flux.create(emitter -> { - for (int i = 0; i < 10; i++) { - if (i == 6) { - emitter.error(new Throwable()); - } else { - emitter.next(String.valueOf(i)); + OneToManyMethodHandler handler = + new OneToManyMethodHandler<>(requestMono -> Flux.create(emitter -> { + for (int i = 0; i < 10; i++) { + if (i == 6) { + emitter.error(new Throwable()); + } else { + emitter.next(String.valueOf(i)); + } } - } - })); - CompletableFuture future = handler.invoke(new Object[]{request, creator.getResponseObserver()}); + })); + CompletableFuture future = handler.invoke(new Object[] {request, creator.getResponseObserver()}); Assertions.assertTrue(future.isDone()); Assertions.assertEquals(6, creator.getNextCounter().get()); Assertions.assertEquals(1, creator.getErrorCounter().get()); diff --git a/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/OneToOneMethodHandlerTest.java b/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/OneToOneMethodHandlerTest.java index 22e1d42ec5..8e3753aa62 100644 --- a/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/OneToOneMethodHandlerTest.java +++ b/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/OneToOneMethodHandlerTest.java @@ -14,16 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.reactive; import org.apache.dubbo.reactive.handler.OneToOneMethodHandler; -import org.junit.jupiter.api.Test; - import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; /** @@ -34,9 +33,9 @@ public final class OneToOneMethodHandlerTest { @Test void testInvoke() throws ExecutionException, InterruptedException { String request = "request"; - OneToOneMethodHandler handler = new OneToOneMethodHandler<>(requestMono -> - requestMono.map(r -> r + "Test")); - CompletableFuture future = handler.invoke(new Object[]{request}); + OneToOneMethodHandler handler = + new OneToOneMethodHandler<>(requestMono -> requestMono.map(r -> r + "Test")); + CompletableFuture future = handler.invoke(new Object[] {request}); assertEquals("requestTest", future.get()); } } diff --git a/dubbo-plugin/dubbo-security/pom.xml b/dubbo-plugin/dubbo-security/pom.xml index 783ee16ddc..bcc16b68ea 100644 --- a/dubbo-plugin/dubbo-security/pom.xml +++ b/dubbo-plugin/dubbo-security/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + - - false - + dubbo-security + jar - dubbo-security - jar + + false + - - - - org.apache.dubbo - dubbo-rpc-api - ${project.version} - - - org.apache.dubbo - dubbo-rpc-triple - ${project.version} - + + + + org.apache.dubbo + dubbo-rpc-api + ${project.version} + + + org.apache.dubbo + dubbo-rpc-triple + ${project.version} + - - org.apache.dubbo - dubbo-common - ${project.version} - - + + org.apache.dubbo + dubbo-common + ${project.version} + + - - io.grpc - grpc-protobuf - - - io.grpc - grpc-stub - - - io.grpc - grpc-netty-shaded - + + io.grpc + grpc-protobuf + + + io.grpc + grpc-stub + + + io.grpc + grpc-netty-shaded + - - com.google.protobuf - protobuf-java - - - com.google.protobuf - protobuf-java-util - + + com.google.protobuf + protobuf-java + + + com.google.protobuf + protobuf-java-util + - - org.bouncycastle - bcprov-jdk15on - - - org.bouncycastle - bcpkix-jdk15on - - - org.bouncycastle - bcprov-ext-jdk15on - + + org.bouncycastle + bcprov-jdk15on + + + org.bouncycastle + bcpkix-jdk15on + + + org.bouncycastle + bcprov-ext-jdk15on + - - - org.apache.dubbo - dubbo-config-api - ${project.version} - test - - + + + org.apache.dubbo + dubbo-config-api + ${project.version} + test + + - - - - kr.motd.maven - os-maven-plugin - 1.7.1 - - - - - org.xolstice.maven.plugins - protobuf-maven-plugin - ${maven_protobuf_plugin_version} - - com.google.protobuf:protoc:${protobuf-protoc_version}:exe:${os.detected.classifier} - grpc-java - io.grpc:protoc-gen-grpc-java:${grpc_version}:exe:${os.detected.classifier} - - - - - compile - compile-custom - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - true - - - - + + + + org.xolstice.maven.plugins + protobuf-maven-plugin + ${maven_protobuf_plugin_version} + + com.google.protobuf:protoc:${protobuf-protoc_version}:exe:${os.detected.classifier} + grpc-java + io.grpc:protoc-gen-grpc-java:${grpc_version}:exe:${os.detected.classifier} + + + + + compile + compile-custom + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + + true + + + + + + kr.motd.maven + os-maven-plugin + 1.7.1 + + + diff --git a/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertConfig.java b/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertConfig.java index 8759823e6c..1e572676a7 100644 --- a/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertConfig.java +++ b/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertConfig.java @@ -35,7 +35,8 @@ public class CertConfig { this(remoteAddress, envType, caCertPath, oidcTokenPath, DEFAULT_REFRESH_INTERVAL); } - public CertConfig(String remoteAddress, String envType, String caCertPath, String oidcTokenPath, int refreshInterval) { + public CertConfig( + String remoteAddress, String envType, String caCertPath, String oidcTokenPath, int refreshInterval) { this.remoteAddress = remoteAddress; this.envType = envType; this.caCertPath = caCertPath; @@ -72,7 +73,10 @@ public class CertConfig { return false; } CertConfig that = (CertConfig) o; - return Objects.equals(remoteAddress, that.remoteAddress) && Objects.equals(envType, that.envType) && Objects.equals(caCertPath, that.caCertPath) && Objects.equals(oidcTokenPath, that.oidcTokenPath); + return Objects.equals(remoteAddress, that.remoteAddress) + && Objects.equals(envType, that.envType) + && Objects.equals(caCertPath, that.caCertPath) + && Objects.equals(oidcTokenPath, that.oidcTokenPath); } @Override diff --git a/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertDeployerListener.java b/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertDeployerListener.java index 2ed9be0e76..13ba78e41e 100644 --- a/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertDeployerListener.java +++ b/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertDeployerListener.java @@ -25,32 +25,29 @@ import java.util.Objects; public class CertDeployerListener implements ApplicationDeployListener { private final DubboCertManager dubboCertManager; - public CertDeployerListener(FrameworkModel frameworkModel) { dubboCertManager = frameworkModel.getBeanFactory().getBean(DubboCertManager.class); } @Override - public void onInitialize(ApplicationModel scopeModel) { - - } + public void onInitialize(ApplicationModel scopeModel) {} @Override public void onStarting(ApplicationModel scopeModel) { scopeModel.getApplicationConfigManager().getSsl().ifPresent(sslConfig -> { if (Objects.nonNull(sslConfig.getCaAddress()) && dubboCertManager != null) { - CertConfig certConfig = new CertConfig(sslConfig.getCaAddress(), - sslConfig.getEnvType(), - sslConfig.getCaCertPath(), - sslConfig.getOidcTokenPath()); + CertConfig certConfig = new CertConfig( + sslConfig.getCaAddress(), + sslConfig.getEnvType(), + sslConfig.getCaCertPath(), + sslConfig.getOidcTokenPath()); dubboCertManager.connect(certConfig); } }); } @Override - public void onStarted(ApplicationModel scopeModel) { - } + public void onStarted(ApplicationModel scopeModel) {} @Override public void onStopping(ApplicationModel scopeModel) { @@ -60,9 +57,7 @@ public class CertDeployerListener implements ApplicationDeployListener { } @Override - public void onStopped(ApplicationModel scopeModel) { - - } + public void onStopped(ApplicationModel scopeModel) {} @Override public void onFailure(ApplicationModel scopeModel, Throwable cause) { diff --git a/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertPair.java b/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertPair.java index 719f2ef84d..e78ca91898 100644 --- a/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertPair.java +++ b/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertPair.java @@ -60,7 +60,10 @@ public class CertPair { return false; } CertPair certPair = (CertPair) o; - return expireTime == certPair.expireTime && Objects.equals(privateKey, certPair.privateKey) && Objects.equals(certificate, certPair.certificate) && Objects.equals(trustCerts, certPair.trustCerts); + return expireTime == certPair.expireTime + && Objects.equals(privateKey, certPair.privateKey) + && Objects.equals(certificate, certPair.certificate) + && Objects.equals(trustCerts, certPair.trustCerts); } @Override diff --git a/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertScopeModelInitializer.java b/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertScopeModelInitializer.java index 42ffa1d703..ccf9be4bd8 100644 --- a/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertScopeModelInitializer.java +++ b/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertScopeModelInitializer.java @@ -43,12 +43,8 @@ public class CertScopeModelInitializer implements ScopeModelInitializer { } @Override - public void initializeApplicationModel(ApplicationModel applicationModel) { - - } + public void initializeApplicationModel(ApplicationModel applicationModel) {} @Override - public void initializeModuleModel(ModuleModel moduleModel) { - - } + public void initializeModuleModel(ModuleModel moduleModel) {} } diff --git a/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/DubboCertManager.java b/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/DubboCertManager.java index 3fcb7fb80a..bddef4a094 100644 --- a/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/DubboCertManager.java +++ b/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/DubboCertManager.java @@ -27,20 +27,6 @@ import org.apache.dubbo.common.utils.IOUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.model.FrameworkModel; -import io.grpc.Channel; -import io.grpc.Metadata; -import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; -import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; -import io.grpc.netty.shaded.io.netty.handler.ssl.util.InsecureTrustManagerFactory; -import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.openssl.jcajce.JcaPEMWriter; -import org.bouncycastle.operator.ContentSigner; -import org.bouncycastle.operator.OperatorCreationException; -import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; -import org.bouncycastle.pkcs.PKCS10CertificationRequest; -import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder; -import org.bouncycastle.util.io.pem.PemObject; - import java.io.File; import java.io.FileReader; import java.io.IOException; @@ -55,6 +41,20 @@ import java.security.spec.ECGenParameterSpec; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import io.grpc.Channel; +import io.grpc.Metadata; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.util.InsecureTrustManagerFactory; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.openssl.jcajce.JcaPEMWriter; +import org.bouncycastle.operator.ContentSigner; +import org.bouncycastle.operator.OperatorCreationException; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.bouncycastle.pkcs.PKCS10CertificationRequest; +import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder; +import org.bouncycastle.util.io.pem.PemObject; + import static io.grpc.stub.MetadataUtils.newAttachHeadersInterceptor; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_SSL_CERT_GENERATE_FAILED; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_SSL_CONNECT_INSECURE; @@ -100,7 +100,8 @@ public class DubboCertManager { // No remote address configured, return return; } - if (StringUtils.isNotEmpty(certConfig.getEnvType()) && !"Kubernetes".equalsIgnoreCase(certConfig.getEnvType())) { + if (StringUtils.isNotEmpty(certConfig.getEnvType()) + && !"Kubernetes".equalsIgnoreCase(certConfig.getEnvType())) { throw new IllegalArgumentException("Only support Kubernetes env now."); } // Create gRPC connection @@ -118,9 +119,15 @@ public class DubboCertManager { * Create task to refresh cert pair for current Dubbo instance */ protected void scheduleRefresh() { - FrameworkExecutorRepository repository = frameworkModel.getBeanFactory().getBean(FrameworkExecutorRepository.class); - refreshFuture = repository.getSharedScheduledExecutor().scheduleAtFixedRate(this::generateCert, - certConfig.getRefreshInterval(), certConfig.getRefreshInterval(), TimeUnit.MILLISECONDS); + FrameworkExecutorRepository repository = + frameworkModel.getBeanFactory().getBean(FrameworkExecutorRepository.class); + refreshFuture = repository + .getSharedScheduledExecutor() + .scheduleAtFixedRate( + this::generateCert, + certConfig.getRefreshInterval(), + certConfig.getRefreshInterval(), + TimeUnit.MILLISECONDS); } /** @@ -131,23 +138,26 @@ public class DubboCertManager { protected void connect0(CertConfig certConfig) { String caCertPath = certConfig.getCaCertPath(); String remoteAddress = certConfig.getRemoteAddress(); - logger.info("Try to connect to Dubbo Cert Authority server: " + remoteAddress + ", caCertPath: " + remoteAddress); + logger.info( + "Try to connect to Dubbo Cert Authority server: " + remoteAddress + ", caCertPath: " + remoteAddress); try { if (StringUtils.isNotEmpty(caCertPath)) { channel = NettyChannelBuilder.forTarget(remoteAddress) - .sslContext( - GrpcSslContexts.forClient() - .trustManager(new File(caCertPath)) - .build()) - .build(); + .sslContext(GrpcSslContexts.forClient() + .trustManager(new File(caCertPath)) + .build()) + .build(); } else { - logger.warn(CONFIG_SSL_CONNECT_INSECURE, "", "", - "No caCertPath is provided, will use insecure connection."); + logger.warn( + CONFIG_SSL_CONNECT_INSECURE, + "", + "", + "No caCertPath is provided, will use insecure connection."); channel = NettyChannelBuilder.forTarget(remoteAddress) - .sslContext(GrpcSslContexts.forClient() - .trustManager(InsecureTrustManagerFactory.INSTANCE) - .build()) - .build(); + .sslContext(GrpcSslContexts.forClient() + .trustManager(InsecureTrustManagerFactory.INSTANCE) + .build()) + .build(); } } catch (Exception e) { logger.error(LoggerCodeConstants.CONFIG_SSL_PATH_LOAD_FAILED, "", "", "Failed to load SSL cert file.", e); @@ -181,7 +191,11 @@ public class DubboCertManager { if (certFromRemote != null) { certPair = certFromRemote; } else { - logger.error(CONFIG_SSL_CERT_GENERATE_FAILED, "", "", "Generate Cert from Dubbo Certificate Authority failed."); + logger.error( + CONFIG_SSL_CERT_GENERATE_FAILED, + "", + "", + "Generate Cert from Dubbo Certificate Authority failed."); } } catch (Exception e) { logger.error(REGISTRY_FAILED_GENERATE_CERT_ISTIO, "", "", "Generate Cert from Istio failed.", e); @@ -205,47 +219,64 @@ public class DubboCertManager { } if (keyPair == null) { - logger.error(CONFIG_SSL_CERT_GENERATE_FAILED, "", "", "Generate Key failed. Please check if your system support."); + logger.error( + CONFIG_SSL_CERT_GENERATE_FAILED, + "", + "", + "Generate Key failed. Please check if your system support."); return null; } String csr = generateCsr(keyPair); - DubboCertificateServiceGrpc.DubboCertificateServiceBlockingStub stub = DubboCertificateServiceGrpc.newBlockingStub(channel); + DubboCertificateServiceGrpc.DubboCertificateServiceBlockingStub stub = + DubboCertificateServiceGrpc.newBlockingStub(channel); stub = setHeaderIfNeed(stub); String privateKeyPem = generatePrivatePemKey(keyPair); DubboCertificateResponse certificateResponse = stub.createCertificate(generateRequest(csr)); if (certificateResponse == null || !certificateResponse.getSuccess()) { - logger.error(CONFIG_SSL_CERT_GENERATE_FAILED, "", "", "Failed to generate cert from Dubbo Certificate Authority. " + - "Message: " + (certificateResponse == null ? "null" : certificateResponse.getMessage())); + logger.error( + CONFIG_SSL_CERT_GENERATE_FAILED, + "", + "", + "Failed to generate cert from Dubbo Certificate Authority. " + "Message: " + + (certificateResponse == null ? "null" : certificateResponse.getMessage())); return null; } - logger.info("Successfully generate cert from Dubbo Certificate Authority. Cert expire time: " + certificateResponse.getExpireTime()); + logger.info("Successfully generate cert from Dubbo Certificate Authority. Cert expire time: " + + certificateResponse.getExpireTime()); - return new CertPair(privateKeyPem, - certificateResponse.getCertPem(), - String.join("\n", certificateResponse.getTrustCertsList()), - certificateResponse.getExpireTime()); + return new CertPair( + privateKeyPem, + certificateResponse.getCertPem(), + String.join("\n", certificateResponse.getTrustCertsList()), + certificateResponse.getExpireTime()); } - private DubboCertificateServiceGrpc.DubboCertificateServiceBlockingStub setHeaderIfNeed(DubboCertificateServiceGrpc.DubboCertificateServiceBlockingStub stub) throws IOException { + private DubboCertificateServiceGrpc.DubboCertificateServiceBlockingStub setHeaderIfNeed( + DubboCertificateServiceGrpc.DubboCertificateServiceBlockingStub stub) throws IOException { String oidcTokenPath = certConfig.getOidcTokenPath(); if (StringUtils.isNotEmpty(oidcTokenPath)) { Metadata header = new Metadata(); Metadata.Key key = Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER); - header.put(key, "Bearer " + - IOUtils.read(new FileReader(oidcTokenPath)) - .replace("\n", "") - .replace("\t", "") - .replace("\r", "") - .trim()); + header.put( + key, + "Bearer " + + IOUtils.read(new FileReader(oidcTokenPath)) + .replace("\n", "") + .replace("\t", "") + .replace("\r", "") + .trim()); stub = stub.withInterceptors(newAttachHeadersInterceptor(header)); logger.info("Use oidc token from " + oidcTokenPath + " to connect to Dubbo Certificate Authority."); } else { - logger.warn(CONFIG_SSL_CONNECT_INSECURE, "", "", - "Use insecure connection to connect to Dubbo Certificate Authority. Reason: No oidc token is provided."); + logger.warn( + CONFIG_SSL_CONNECT_INSECURE, + "", + "", + "Use insecure connection to connect to Dubbo Certificate Authority. Reason: No oidc token is provided."); } return stub; } @@ -266,7 +297,12 @@ public class DubboCertManager { ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA").build(keypair.getPrivate()); keyPair = new KeyPair(publicKey, privateKey, signer); } catch (NoSuchAlgorithmException | OperatorCreationException e) { - logger.error(CONFIG_SSL_CERT_GENERATE_FAILED, "", "", "Generate Key with SHA256WithRSA algorithm failed. Please check if your system support.", e); + logger.error( + CONFIG_SSL_CERT_GENERATE_FAILED, + "", + "", + "Generate Key with SHA256WithRSA algorithm failed. Please check if your system support.", + e); } return keyPair; } @@ -288,14 +324,22 @@ public class DubboCertManager { ContentSigner signer = new JcaContentSignerBuilder("SHA256withECDSA").build(privateKey); keyPair = new KeyPair(publicKey, privateKey, signer); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | OperatorCreationException e) { - logger.error(CONFIG_SSL_CERT_GENERATE_FAILED, "", "", "Generate Key with secp256r1 algorithm failed. Please check if your system support. " - + "Will attempt to generate with RSA2048.", e); + logger.error( + CONFIG_SSL_CERT_GENERATE_FAILED, + "", + "", + "Generate Key with secp256r1 algorithm failed. Please check if your system support. " + + "Will attempt to generate with RSA2048.", + e); } return keyPair; } private DubboCertificateRequest generateRequest(String csr) { - return DubboCertificateRequest.newBuilder().setCsr(csr).setType("CONNECTION").build(); + return DubboCertificateRequest.newBuilder() + .setCsr(csr) + .setType("CONNECTION") + .build(); } /** @@ -340,8 +384,8 @@ public class DubboCertManager { */ private String generateCsr(KeyPair keyPair) throws IOException { PKCS10CertificationRequest request = new JcaPKCS10CertificationRequestBuilder( - new X500Name("O=" + "cluster.domain"), keyPair.getPublicKey()) - .build(keyPair.getSigner()); + new X500Name("O=" + "cluster.domain"), keyPair.getPublicKey()) + .build(keyPair.getSigner()); String csr = generatePemKey("CERTIFICATE REQUEST", request.getEncoded()); diff --git a/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/DubboCertProvider.java b/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/DubboCertProvider.java index df2dfded25..808e50e1ce 100644 --- a/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/DubboCertProvider.java +++ b/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/DubboCertProvider.java @@ -30,7 +30,6 @@ import java.nio.charset.StandardCharsets; public class DubboCertProvider implements CertProvider { private final DubboCertManager dubboCertManager; - public DubboCertProvider(FrameworkModel frameworkModel) { dubboCertManager = frameworkModel.getBeanFactory().getBean(DubboCertManager.class); } @@ -46,9 +45,11 @@ public class DubboCertProvider implements CertProvider { if (certPair == null) { return null; } - return new ProviderCert(certPair.getCertificate().getBytes(StandardCharsets.UTF_8), - certPair.getPrivateKey().getBytes(StandardCharsets.UTF_8), - certPair.getTrustCerts().getBytes(StandardCharsets.UTF_8), AuthPolicy.NONE); + return new ProviderCert( + certPair.getCertificate().getBytes(StandardCharsets.UTF_8), + certPair.getPrivateKey().getBytes(StandardCharsets.UTF_8), + certPair.getTrustCerts().getBytes(StandardCharsets.UTF_8), + AuthPolicy.NONE); } @Override @@ -57,8 +58,9 @@ public class DubboCertProvider implements CertProvider { if (certPair == null) { return null; } - return new Cert(certPair.getCertificate().getBytes(StandardCharsets.UTF_8), - certPair.getPrivateKey().getBytes(StandardCharsets.UTF_8), - certPair.getTrustCerts().getBytes(StandardCharsets.UTF_8)); + return new Cert( + certPair.getCertificate().getBytes(StandardCharsets.UTF_8), + certPair.getPrivateKey().getBytes(StandardCharsets.UTF_8), + certPair.getTrustCerts().getBytes(StandardCharsets.UTF_8)); } } diff --git a/dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security/cert/CertDeployerListenerTest.java b/dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security/cert/CertDeployerListenerTest.java index ce6a5fa665..2fcfb19145 100644 --- a/dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security/cert/CertDeployerListenerTest.java +++ b/dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security/cert/CertDeployerListenerTest.java @@ -23,28 +23,27 @@ import org.apache.dubbo.config.SslConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; +import java.util.concurrent.atomic.AtomicReference; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.mockito.MockedConstruction; import org.mockito.Mockito; -import java.util.concurrent.atomic.AtomicReference; - class CertDeployerListenerTest { @Test void testEmpty1() { AtomicReference reference = new AtomicReference<>(); try (MockedConstruction construction = - Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { - reference.set(mock); - })) { + Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { + reference.set(mock); + })) { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test")); applicationModel.getDeployer().start(); - Mockito.verify(reference.get(), Mockito.times(0)) - .connect(Mockito.any()); + Mockito.verify(reference.get(), Mockito.times(0)).connect(Mockito.any()); applicationModel.getDeployer().stop(); Mockito.verify(reference.get(), Mockito.atLeast(1)).disConnect(); frameworkModel.destroy(); @@ -55,16 +54,15 @@ class CertDeployerListenerTest { void testEmpty2() { AtomicReference reference = new AtomicReference<>(); try (MockedConstruction construction = - Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { - reference.set(mock); - })) { + Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { + reference.set(mock); + })) { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test")); applicationModel.getApplicationConfigManager().setSsl(new SslConfig()); applicationModel.getDeployer().start(); - Mockito.verify(reference.get(), Mockito.times(0)) - .connect(Mockito.any()); + Mockito.verify(reference.get(), Mockito.times(0)).connect(Mockito.any()); applicationModel.getDeployer().stop(); Mockito.verify(reference.get(), Mockito.atLeast(1)).disConnect(); frameworkModel.destroy(); @@ -75,9 +73,9 @@ class CertDeployerListenerTest { void testCreate() { AtomicReference reference = new AtomicReference<>(); try (MockedConstruction construction = - Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { - reference.set(mock); - })) { + Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { + reference.set(mock); + })) { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test")); @@ -86,11 +84,9 @@ class CertDeployerListenerTest { applicationModel.getApplicationConfigManager().setSsl(sslConfig); applicationModel.getDeployer().start(); - Mockito.verify(reference.get(), Mockito.times(1)) - .connect(Mockito.any()); + Mockito.verify(reference.get(), Mockito.times(1)).connect(Mockito.any()); applicationModel.getDeployer().stop(); - Mockito.verify(reference.get(), Mockito.atLeast(1)) - .disConnect(); + Mockito.verify(reference.get(), Mockito.atLeast(1)).disConnect(); frameworkModel.destroy(); } } @@ -99,9 +95,9 @@ class CertDeployerListenerTest { void testFailure() { AtomicReference reference = new AtomicReference<>(); try (MockedConstruction construction = - Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { - reference.set(mock); - })) { + Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { + reference.set(mock); + })) { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test")); @@ -112,10 +108,8 @@ class CertDeployerListenerTest { ApplicationDeployer deployer = applicationModel.getDeployer(); Assertions.assertThrows(IllegalArgumentException.class, deployer::start); - Mockito.verify(reference.get(), Mockito.times(1)) - .connect(Mockito.any()); - Mockito.verify(reference.get(), Mockito.atLeast(1)) - .disConnect(); + Mockito.verify(reference.get(), Mockito.times(1)).connect(Mockito.any()); + Mockito.verify(reference.get(), Mockito.atLeast(1)).disConnect(); frameworkModel.destroy(); } } @@ -134,9 +128,9 @@ class CertDeployerListenerTest { }; Thread.currentThread().setContextClassLoader(newClassLoader); try (MockedConstruction construction = - Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { - // ignore - })) { + Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { + // ignore + })) { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test")); @@ -166,9 +160,9 @@ class CertDeployerListenerTest { }; Thread.currentThread().setContextClassLoader(newClassLoader); try (MockedConstruction construction = - Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { - // ignore - })) { + Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { + // ignore + })) { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test")); @@ -188,9 +182,9 @@ class CertDeployerListenerTest { void testParams1() { AtomicReference reference = new AtomicReference<>(); try (MockedConstruction construction = - Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { - reference.set(mock); - })) { + Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { + reference.set(mock); + })) { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test")); @@ -203,10 +197,9 @@ class CertDeployerListenerTest { applicationModel.getDeployer().start(); Mockito.verify(reference.get(), Mockito.times(1)) - .connect(new CertConfig("127.0.0.1:30060", "test", "certs/ca.crt", "token")); + .connect(new CertConfig("127.0.0.1:30060", "test", "certs/ca.crt", "token")); applicationModel.getDeployer().stop(); - Mockito.verify(reference.get(), Mockito.atLeast(1)) - .disConnect(); + Mockito.verify(reference.get(), Mockito.atLeast(1)).disConnect(); frameworkModel.destroy(); } } @@ -216,9 +209,9 @@ class CertDeployerListenerTest { void testParams2() { AtomicReference reference = new AtomicReference<>(); try (MockedConstruction construction = - Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { - reference.set(mock); - })) { + Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { + reference.set(mock); + })) { System.setProperty("dubbo.ssl.ca-address", "127.0.0.1:30060"); System.setProperty("dubbo.ssl.ca-cert-path", "certs/ca.crt"); System.setProperty("dubbo.ssl.oidc-token-path", "token"); @@ -229,7 +222,7 @@ class CertDeployerListenerTest { applicationModel.getDeployer().start(); Mockito.verify(reference.get(), Mockito.times(1)) - .connect(new CertConfig("127.0.0.1:30060", "test", "certs/ca.crt", "token")); + .connect(new CertConfig("127.0.0.1:30060", "test", "certs/ca.crt", "token")); applicationModel.getDeployer().stop(); Mockito.verify(reference.get(), Mockito.atLeast(1)).disConnect(); frameworkModel.destroy(); diff --git a/dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security/cert/DubboCertManagerTest.java b/dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security/cert/DubboCertManagerTest.java index a25c9d330c..bb07578af1 100644 --- a/dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security/cert/DubboCertManagerTest.java +++ b/dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security/cert/DubboCertManagerTest.java @@ -20,18 +20,18 @@ import org.apache.dubbo.auth.v1alpha1.DubboCertificateResponse; import org.apache.dubbo.auth.v1alpha1.DubboCertificateServiceGrpc; import org.apache.dubbo.rpc.model.FrameworkModel; -import io.grpc.Channel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.mockito.MockedStatic; -import org.mockito.Mockito; - import java.io.IOException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import io.grpc.Channel; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + import static org.awaitility.Awaitility.await; import static org.mockito.Answers.CALLS_REAL_METHODS; @@ -52,32 +52,36 @@ class DubboCertManagerTest { } @Override - protected void scheduleRefresh() { - - } + protected void scheduleRefresh() {} }; certManager.connect(new CertConfig("127.0.0.1:30060", null, "caCertPath", "oidc")); Assertions.assertEquals(new CertConfig("127.0.0.1:30060", null, "caCertPath", "oidc"), certManager.certConfig); certManager.connect(new CertConfig("127.0.0.1:30060", "Kubernetes", "caCertPath", "oidc123")); - Assertions.assertEquals(new CertConfig("127.0.0.1:30060", "Kubernetes", "caCertPath", "oidc123"), certManager.certConfig); + Assertions.assertEquals( + new CertConfig("127.0.0.1:30060", "Kubernetes", "caCertPath", "oidc123"), certManager.certConfig); certManager.connect(new CertConfig("127.0.0.1:30060", "kubernetes", "caCertPath", "oidc345")); - Assertions.assertEquals(new CertConfig("127.0.0.1:30060", "kubernetes", "caCertPath", "oidc345"), certManager.certConfig); + Assertions.assertEquals( + new CertConfig("127.0.0.1:30060", "kubernetes", "caCertPath", "oidc345"), certManager.certConfig); CertConfig certConfig = new CertConfig("127.0.0.1:30060", "vm", "caCertPath", "oidc"); Assertions.assertThrows(IllegalArgumentException.class, () -> certManager.connect(certConfig)); - Assertions.assertEquals(new CertConfig("127.0.0.1:30060", "kubernetes", "caCertPath", "oidc345"), certManager.certConfig); + Assertions.assertEquals( + new CertConfig("127.0.0.1:30060", "kubernetes", "caCertPath", "oidc345"), certManager.certConfig); certManager.connect(null); - Assertions.assertEquals(new CertConfig("127.0.0.1:30060", "kubernetes", "caCertPath", "oidc345"), certManager.certConfig); + Assertions.assertEquals( + new CertConfig("127.0.0.1:30060", "kubernetes", "caCertPath", "oidc345"), certManager.certConfig); certManager.connect(new CertConfig(null, null, null, null)); - Assertions.assertEquals(new CertConfig("127.0.0.1:30060", "kubernetes", "caCertPath", "oidc345"), certManager.certConfig); + Assertions.assertEquals( + new CertConfig("127.0.0.1:30060", "kubernetes", "caCertPath", "oidc345"), certManager.certConfig); certManager.channel = Mockito.mock(Channel.class); certManager.connect(new CertConfig("error", null, "error", "error")); - Assertions.assertEquals(new CertConfig("127.0.0.1:30060", "kubernetes", "caCertPath", "oidc345"), certManager.certConfig); + Assertions.assertEquals( + new CertConfig("127.0.0.1:30060", "kubernetes", "caCertPath", "oidc345"), certManager.certConfig); frameworkModel.destroy(); } @@ -119,7 +123,8 @@ class DubboCertManagerTest { void testConnect2() { FrameworkModel frameworkModel = new FrameworkModel(); DubboCertManager certManager = new DubboCertManager(frameworkModel); - String file = this.getClass().getClassLoader().getResource("certs/ca.crt").getFile(); + String file = + this.getClass().getClassLoader().getResource("certs/ca.crt").getFile(); CertConfig certConfig = new CertConfig("127.0.0.1:30062", null, file, null); certManager.connect0(certConfig); Assertions.assertNotNull(certManager.channel); @@ -132,7 +137,10 @@ class DubboCertManagerTest { void testConnect3() { FrameworkModel frameworkModel = new FrameworkModel(); DubboCertManager certManager = new DubboCertManager(frameworkModel); - String file = this.getClass().getClassLoader().getResource("certs/broken-ca.crt").getFile(); + String file = this.getClass() + .getClassLoader() + .getResource("certs/broken-ca.crt") + .getFile(); CertConfig certConfig = new CertConfig("127.0.0.1:30062", null, file, null); Assertions.assertThrows(RuntimeException.class, () -> certManager.connect0(certConfig)); @@ -149,7 +157,6 @@ class DubboCertManagerTest { Assertions.assertNull(certManager.refreshFuture); Mockito.verify(scheduledFuture, Mockito.times(1)).cancel(true); - certManager.channel = Mockito.mock(Channel.class); certManager.disConnect(); Assertions.assertNull(certManager.channel); @@ -231,10 +238,10 @@ class DubboCertManagerTest { Assertions.assertNotNull(keyPair.getSigner()); } - @Test void testRefreshCert() throws IOException { - try (MockedStatic managerMock = Mockito.mockStatic(DubboCertManager.class, CALLS_REAL_METHODS)) { + try (MockedStatic managerMock = + Mockito.mockStatic(DubboCertManager.class, CALLS_REAL_METHODS)) { FrameworkModel frameworkModel = new FrameworkModel(); DubboCertManager certManager = new DubboCertManager(frameworkModel); managerMock.when(DubboCertManager::signWithEcdsa).thenReturn(null); @@ -245,29 +252,37 @@ class DubboCertManagerTest { managerMock.when(DubboCertManager::signWithEcdsa).thenCallRealMethod(); certManager.channel = Mockito.mock(Channel.class); - try (MockedStatic mockGrpc = Mockito.mockStatic(DubboCertificateServiceGrpc.class, CALLS_REAL_METHODS)) { - DubboCertificateServiceGrpc.DubboCertificateServiceBlockingStub stub = Mockito.mock(DubboCertificateServiceGrpc.DubboCertificateServiceBlockingStub.class); - mockGrpc.when(() -> DubboCertificateServiceGrpc.newBlockingStub(Mockito.any(Channel.class))).thenReturn(stub); - Mockito.when(stub.createCertificate(Mockito.any())).thenReturn( - DubboCertificateResponse.newBuilder() - .setSuccess(false).build()); + try (MockedStatic mockGrpc = + Mockito.mockStatic(DubboCertificateServiceGrpc.class, CALLS_REAL_METHODS)) { + DubboCertificateServiceGrpc.DubboCertificateServiceBlockingStub stub = + Mockito.mock(DubboCertificateServiceGrpc.DubboCertificateServiceBlockingStub.class); + mockGrpc.when(() -> DubboCertificateServiceGrpc.newBlockingStub(Mockito.any(Channel.class))) + .thenReturn(stub); + Mockito.when(stub.createCertificate(Mockito.any())) + .thenReturn(DubboCertificateResponse.newBuilder() + .setSuccess(false) + .build()); certManager.certConfig = new CertConfig(null, null, null, null); Assertions.assertNull(certManager.refreshCert()); - String file = this.getClass().getClassLoader().getResource("certs/token").getFile(); + String file = this.getClass() + .getClassLoader() + .getResource("certs/token") + .getFile(); Mockito.when(stub.withInterceptors(Mockito.any())).thenReturn(stub); certManager.certConfig = new CertConfig(null, null, null, file); Assertions.assertNull(certManager.refreshCert()); Mockito.verify(stub, Mockito.times(1)).withInterceptors(Mockito.any()); - Mockito.when(stub.createCertificate(Mockito.any())).thenReturn( - DubboCertificateResponse.newBuilder() - .setSuccess(true) - .setCertPem("certPem") - .addTrustCerts("trustCerts") - .setExpireTime(123456).build()); + Mockito.when(stub.createCertificate(Mockito.any())) + .thenReturn(DubboCertificateResponse.newBuilder() + .setSuccess(true) + .setCertPem("certPem") + .addTrustCerts("trustCerts") + .setExpireTime(123456) + .build()); CertPair certPair = certManager.refreshCert(); Assertions.assertNotNull(certPair); Assertions.assertEquals("certPem", certPair.getCertificate()); diff --git a/dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security/cert/DubboCertProviderTest.java b/dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security/cert/DubboCertProviderTest.java index e022473ee4..5be5f3a242 100644 --- a/dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security/cert/DubboCertProviderTest.java +++ b/dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security/cert/DubboCertProviderTest.java @@ -21,21 +21,21 @@ import org.apache.dubbo.common.ssl.Cert; import org.apache.dubbo.common.ssl.ProviderCert; import org.apache.dubbo.rpc.model.FrameworkModel; +import java.util.concurrent.atomic.AtomicReference; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.MockedConstruction; import org.mockito.Mockito; -import java.util.concurrent.atomic.AtomicReference; - class DubboCertProviderTest { @Test void testEnable() { AtomicReference reference = new AtomicReference<>(); try (MockedConstruction construction = - Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { - reference.set(mock); - })) { + Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { + reference.set(mock); + })) { FrameworkModel frameworkModel = new FrameworkModel(); DubboCertProvider provider = new DubboCertProvider(frameworkModel); @@ -63,9 +63,9 @@ class DubboCertProviderTest { }; Thread.currentThread().setContextClassLoader(newClassLoader); try (MockedConstruction construction = - Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { - // ignore - })) { + Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { + // ignore + })) { FrameworkModel frameworkModel = new FrameworkModel(); DubboCertProvider provider = new DubboCertProvider(frameworkModel); @@ -90,9 +90,9 @@ class DubboCertProviderTest { }; Thread.currentThread().setContextClassLoader(newClassLoader); try (MockedConstruction construction = - Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { - // ignore - })) { + Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { + // ignore + })) { FrameworkModel frameworkModel = new FrameworkModel(); DubboCertProvider provider = new DubboCertProvider(frameworkModel); @@ -107,9 +107,9 @@ class DubboCertProviderTest { void getProviderConnectionConfigTest() { AtomicReference reference = new AtomicReference<>(); try (MockedConstruction construction = - Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { - reference.set(mock); - })) { + Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { + reference.set(mock); + })) { FrameworkModel frameworkModel = new FrameworkModel(); DubboCertProvider provider = new DubboCertProvider(frameworkModel); Assertions.assertNull(provider.getProviderConnectionConfig(null)); @@ -130,9 +130,9 @@ class DubboCertProviderTest { void getConsumerConnectionConfigTest() { AtomicReference reference = new AtomicReference<>(); try (MockedConstruction construction = - Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { - reference.set(mock); - })) { + Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> { + reference.set(mock); + })) { FrameworkModel frameworkModel = new FrameworkModel(); DubboCertProvider provider = new DubboCertProvider(frameworkModel); Assertions.assertNull(provider.getConsumerConnectionConfig(null)); diff --git a/dubbo-plugin/dubbo-spring-security/pom.xml b/dubbo-plugin/dubbo-spring-security/pom.xml index a9d0588836..5bb4688fbe 100644 --- a/dubbo-plugin/dubbo-spring-security/pom.xml +++ b/dubbo-plugin/dubbo-spring-security/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-plugin - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-plugin + ${revision} + ../pom.xml + - - false - + dubbo-spring-security + jar - dubbo-spring-security - jar + + false + - - - - org.apache.dubbo - dubbo-rpc-api - ${project.version} - + + + + org.apache.dubbo + dubbo-rpc-api + ${project.version} + - - org.apache.dubbo - dubbo-common - ${project.version} - + + org.apache.dubbo + dubbo-common + ${project.version} + - - org.apache.dubbo - dubbo-cluster - ${project.parent.version} - - + + org.apache.dubbo + dubbo-cluster + ${project.parent.version} + + - - - org.springframework.security - spring-security-core - + + + org.springframework.security + spring-security-core + - - org.springframework.security - spring-security-oauth2-client - true - test - + + org.springframework.security + spring-security-oauth2-client + test + true + - + - - - com.fasterxml.jackson.core - jackson-core - + + + com.fasterxml.jackson.core + jackson-core + - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + - - com.fasterxml.jackson.core - jackson-databind - - + + com.fasterxml.jackson.core + jackson-databind + + - + diff --git a/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/AuthenticationExceptionTranslatorFilter.java b/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/AuthenticationExceptionTranslatorFilter.java index e3a246d2bc..6999931d08 100644 --- a/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/AuthenticationExceptionTranslatorFilter.java +++ b/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/AuthenticationExceptionTranslatorFilter.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.spring.security.filter; import org.apache.dubbo.common.constants.CommonConstants; @@ -35,12 +34,18 @@ import static org.apache.dubbo.spring.security.utils.SecurityNames.OBJECT_MAPPER import static org.apache.dubbo.spring.security.utils.SecurityNames.SECURITY_CONTEXT_HOLDER_CLASS_NAME; import static org.apache.dubbo.spring.security.utils.SecurityNames.SIMPLE_MODULE_CLASS_NAME; -@Activate(group = CommonConstants.PROVIDER, order = Integer.MAX_VALUE, onClass = { - SECURITY_CONTEXT_HOLDER_CLASS_NAME, CORE_JACKSON_2_MODULE_CLASS_NAME, OBJECT_MAPPER_CLASS_NAME, - JAVA_TIME_MODULE_CLASS_NAME, SIMPLE_MODULE_CLASS_NAME}) +@Activate( + group = CommonConstants.PROVIDER, + order = Integer.MAX_VALUE, + onClass = { + SECURITY_CONTEXT_HOLDER_CLASS_NAME, + CORE_JACKSON_2_MODULE_CLASS_NAME, + OBJECT_MAPPER_CLASS_NAME, + JAVA_TIME_MODULE_CLASS_NAME, + SIMPLE_MODULE_CLASS_NAME + }) public class AuthenticationExceptionTranslatorFilter implements Filter, Filter.Listener { - @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { return invoker.invoke(invocation); @@ -58,16 +63,13 @@ public class AuthenticationExceptionTranslatorFilter implements Filter, Filter.L } @Override - public void onError(Throwable t, Invoker invoker, Invocation invocation) { - } + public void onError(Throwable t, Invoker invoker, Invocation invocation) {} private boolean isTranslate(Result result) { Throwable exception = result.getException(); return result.hasException() - && (exception instanceof AuthenticationException || exception instanceof AccessDeniedException); - + && (exception instanceof AuthenticationException || exception instanceof AccessDeniedException); } - } diff --git a/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/ContextHolderAuthenticationPrepareFilter.java b/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/ContextHolderAuthenticationPrepareFilter.java index c71ef982f5..ec1bdb9099 100644 --- a/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/ContextHolderAuthenticationPrepareFilter.java +++ b/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/ContextHolderAuthenticationPrepareFilter.java @@ -40,9 +40,16 @@ import static org.apache.dubbo.spring.security.utils.SecurityNames.OBJECT_MAPPER import static org.apache.dubbo.spring.security.utils.SecurityNames.SECURITY_CONTEXT_HOLDER_CLASS_NAME; import static org.apache.dubbo.spring.security.utils.SecurityNames.SIMPLE_MODULE_CLASS_NAME; -@Activate(group = CommonConstants.CONSUMER, order = -10000, onClass = { - SECURITY_CONTEXT_HOLDER_CLASS_NAME, CORE_JACKSON_2_MODULE_CLASS_NAME, OBJECT_MAPPER_CLASS_NAME, - JAVA_TIME_MODULE_CLASS_NAME, SIMPLE_MODULE_CLASS_NAME}) +@Activate( + group = CommonConstants.CONSUMER, + order = -10000, + onClass = { + SECURITY_CONTEXT_HOLDER_CLASS_NAME, + CORE_JACKSON_2_MODULE_CLASS_NAME, + OBJECT_MAPPER_CLASS_NAME, + JAVA_TIME_MODULE_CLASS_NAME, + SIMPLE_MODULE_CLASS_NAME + }) public class ContextHolderAuthenticationPrepareFilter implements ClusterFilter { private final Logger logger = LoggerFactory.getLogger(getClass()); diff --git a/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/ContextHolderAuthenticationResolverFilter.java b/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/ContextHolderAuthenticationResolverFilter.java index ff8a4fbea7..0183938b54 100644 --- a/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/ContextHolderAuthenticationResolverFilter.java +++ b/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/ContextHolderAuthenticationResolverFilter.java @@ -37,9 +37,16 @@ import static org.apache.dubbo.spring.security.utils.SecurityNames.OBJECT_MAPPER import static org.apache.dubbo.spring.security.utils.SecurityNames.SECURITY_CONTEXT_HOLDER_CLASS_NAME; import static org.apache.dubbo.spring.security.utils.SecurityNames.SIMPLE_MODULE_CLASS_NAME; -@Activate(group = CommonConstants.PROVIDER, order = -10000, onClass = { - SECURITY_CONTEXT_HOLDER_CLASS_NAME, CORE_JACKSON_2_MODULE_CLASS_NAME, OBJECT_MAPPER_CLASS_NAME, - JAVA_TIME_MODULE_CLASS_NAME, SIMPLE_MODULE_CLASS_NAME}) +@Activate( + group = CommonConstants.PROVIDER, + order = -10000, + onClass = { + SECURITY_CONTEXT_HOLDER_CLASS_NAME, + CORE_JACKSON_2_MODULE_CLASS_NAME, + OBJECT_MAPPER_CLASS_NAME, + JAVA_TIME_MODULE_CLASS_NAME, + SIMPLE_MODULE_CLASS_NAME + }) public class ContextHolderAuthenticationResolverFilter implements Filter { private final ObjectMapperCodec mapper; @@ -72,5 +79,4 @@ public class ContextHolderAuthenticationResolverFilter implements Filter { SecurityContextHolder.getContext().setAuthentication(authentication); } - } diff --git a/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/ContextHolderParametersSelectedTransferFilter.java b/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/ContextHolderParametersSelectedTransferFilter.java index 7d81ca4c86..853398f009 100644 --- a/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/ContextHolderParametersSelectedTransferFilter.java +++ b/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/ContextHolderParametersSelectedTransferFilter.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.spring.security.filter; import org.apache.dubbo.common.constants.CommonConstants; @@ -32,7 +31,7 @@ import java.util.Objects; import static org.apache.dubbo.spring.security.utils.SecurityNames.SECURITY_AUTHENTICATION_CONTEXT_KEY; @Activate(group = CommonConstants.CONSUMER, order = -1) -public class ContextHolderParametersSelectedTransferFilter implements ClusterFilter{ +public class ContextHolderParametersSelectedTransferFilter implements ClusterFilter { @Override public Result invoke(Invoker invoker, Invocation invocation) { @@ -42,12 +41,12 @@ public class ContextHolderParametersSelectedTransferFilter implements ClusterFil } private void setSecurityContextIfExists(Invocation invocation) { - Map resultMap = RpcContext.getServerAttachment().getObjectAttachments(); + Map resultMap = RpcContext.getServerAttachment().getObjectAttachments(); Object authentication = resultMap.get(SECURITY_AUTHENTICATION_CONTEXT_KEY); if (Objects.isNull(authentication)) { - return ; + return; } invocation.setObjectAttachment(SecurityNames.SECURITY_AUTHENTICATION_CONTEXT_KEY, authentication); diff --git a/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/jackson/ObjectMapperCodec.java b/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/jackson/ObjectMapperCodec.java index 97d1048bba..e70aeaeb9e 100644 --- a/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/jackson/ObjectMapperCodec.java +++ b/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/jackson/ObjectMapperCodec.java @@ -14,23 +14,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.spring.security.jackson; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.module.SimpleModule; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.apache.dubbo.common.constants.LoggerCodeConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.StringUtils; -import org.springframework.security.jackson2.CoreJackson2Module; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.springframework.security.jackson2.CoreJackson2Module; + public class ObjectMapperCodec { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ObjectMapperCodec.class); @@ -50,7 +50,12 @@ public class ObjectMapperCodec { return mapper.readValue(bytes, clazz); } catch (Exception exception) { - logger.warn(LoggerCodeConstants.COMMON_JSON_CONVERT_EXCEPTION, "objectMapper! deserialize error, you can try to customize the ObjectMapperCodecCustomer.","","", exception); + logger.warn( + LoggerCodeConstants.COMMON_JSON_CONVERT_EXCEPTION, + "objectMapper! deserialize error, you can try to customize the ObjectMapperCodecCustomer.", + "", + "", + exception); } return null; } @@ -72,8 +77,12 @@ public class ObjectMapperCodec { return mapper.writeValueAsString(object); } catch (Exception ex) { - logger.warn(LoggerCodeConstants.COMMON_JSON_CONVERT_EXCEPTION, "objectMapper! serialize error, you can try to customize the ObjectMapperCodecCustomer.","","", ex); - + logger.warn( + LoggerCodeConstants.COMMON_JSON_CONVERT_EXCEPTION, + "objectMapper! serialize error, you can try to customize the ObjectMapperCodecCustomer.", + "", + "", + ex); } return null; } @@ -93,8 +102,10 @@ public class ObjectMapperCodec { mapper.registerModule(new JavaTimeModule()); List jacksonModuleClassNameList = new ArrayList<>(); - jacksonModuleClassNameList.add("org.springframework.security.oauth2.server.authorization.jackson2.OAuth2AuthorizationServerJackson2Module"); - jacksonModuleClassNameList.add("org.springframework.security.oauth2.client.jackson2.OAuth2ClientJackson2Module"); + jacksonModuleClassNameList.add( + "org.springframework.security.oauth2.server.authorization.jackson2.OAuth2AuthorizationServerJackson2Module"); + jacksonModuleClassNameList.add( + "org.springframework.security.oauth2.client.jackson2.OAuth2ClientJackson2Module"); jacksonModuleClassNameList.add("org.springframework.security.web.server.jackson2.WebServerJackson2Module"); jacksonModuleClassNameList.add("com.fasterxml.jackson.module.paramnames.ParameterNamesModule"); jacksonModuleClassNameList.add("org.springframework.security.web.jackson2.WebServletJackson2Module"); @@ -102,19 +113,19 @@ public class ObjectMapperCodec { jacksonModuleClassNameList.add("org.springframework.boot.jackson.JsonMixinModule"); jacksonModuleClassNameList.add("org.springframework.security.ldap.jackson2.LdapJackson2Module"); loadModuleIfPresent(jacksonModuleClassNameList); - } private void loadModuleIfPresent(List jacksonModuleClassNameList) { for (String moduleClassName : jacksonModuleClassNameList) { try { - SimpleModule objectMapperModule = (SimpleModule) ClassUtils.forName(moduleClassName, - ObjectMapperCodec.class.getClassLoader()).getDeclaredConstructor().newInstance(); + SimpleModule objectMapperModule = + (SimpleModule) ClassUtils.forName(moduleClassName, ObjectMapperCodec.class.getClassLoader()) + .getDeclaredConstructor() + .newInstance(); mapper.registerModule(objectMapperModule); } catch (Throwable ex) { } } } - } diff --git a/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/jackson/ObjectMapperCodecCustomer.java b/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/jackson/ObjectMapperCodecCustomer.java index 2674172fe5..15335e44b4 100644 --- a/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/jackson/ObjectMapperCodecCustomer.java +++ b/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/jackson/ObjectMapperCodecCustomer.java @@ -14,8 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.spring.security.jackson; + import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; @@ -23,5 +23,4 @@ import org.apache.dubbo.common.extension.SPI; public interface ObjectMapperCodecCustomer { void customize(ObjectMapperCodec objectMapperCodec); - } diff --git a/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/model/SecurityScopeModelInitializer.java b/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/model/SecurityScopeModelInitializer.java index d87a90cd83..1a9531d563 100644 --- a/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/model/SecurityScopeModelInitializer.java +++ b/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/model/SecurityScopeModelInitializer.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.spring.security.model; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; @@ -36,8 +35,14 @@ import static org.apache.dubbo.spring.security.utils.SecurityNames.OBJECT_MAPPER import static org.apache.dubbo.spring.security.utils.SecurityNames.SECURITY_CONTEXT_HOLDER_CLASS_NAME; import static org.apache.dubbo.spring.security.utils.SecurityNames.SIMPLE_MODULE_CLASS_NAME; -@Activate(onClass = {SECURITY_CONTEXT_HOLDER_CLASS_NAME, CORE_JACKSON_2_MODULE_CLASS_NAME, OBJECT_MAPPER_CLASS_NAME, - JAVA_TIME_MODULE_CLASS_NAME, SIMPLE_MODULE_CLASS_NAME}) +@Activate( + onClass = { + SECURITY_CONTEXT_HOLDER_CLASS_NAME, + CORE_JACKSON_2_MODULE_CLASS_NAME, + OBJECT_MAPPER_CLASS_NAME, + JAVA_TIME_MODULE_CLASS_NAME, + SIMPLE_MODULE_CLASS_NAME + }) public class SecurityScopeModelInitializer implements ScopeModelInitializer { private final Logger logger = LoggerFactory.getLogger(getClass()); @@ -49,7 +54,9 @@ public class SecurityScopeModelInitializer implements ScopeModelInitializer { try { ObjectMapperCodec objectMapperCodec = new ObjectMapperCodec(); - Set objectMapperCodecCustomerList = frameworkModel.getExtensionLoader(ObjectMapperCodecCustomer.class).getSupportedExtensionInstances(); + Set objectMapperCodecCustomerList = frameworkModel + .getExtensionLoader(ObjectMapperCodecCustomer.class) + .getSupportedExtensionInstances(); for (ObjectMapperCodecCustomer objectMapperCodecCustomer : objectMapperCodecCustomerList) { objectMapperCodecCustomer.customize(objectMapperCodec); @@ -57,18 +64,15 @@ public class SecurityScopeModelInitializer implements ScopeModelInitializer { beanFactory.registerBean(objectMapperCodec); } catch (Throwable t) { - logger.info("Failed to initialize ObjectMapperCodecCustomer and spring security related features are disabled.", t); + logger.info( + "Failed to initialize ObjectMapperCodecCustomer and spring security related features are disabled.", + t); } } @Override - public void initializeApplicationModel(ApplicationModel applicationModel) { - } + public void initializeApplicationModel(ApplicationModel applicationModel) {} @Override - public void initializeModuleModel(ModuleModel moduleModel) { - - - } - + public void initializeModuleModel(ModuleModel moduleModel) {} } diff --git a/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/utils/SecurityNames.java b/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/utils/SecurityNames.java index f40adf4822..b9d62c2eef 100644 --- a/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/utils/SecurityNames.java +++ b/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/utils/SecurityNames.java @@ -14,19 +14,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.spring.security.utils; -final public class SecurityNames { +public final class SecurityNames { public static final String SECURITY_AUTHENTICATION_CONTEXT_KEY = "security_authentication_context"; - public static final String SECURITY_CONTEXT_HOLDER_CLASS_NAME = "org.springframework.security.core.context.SecurityContextHolder"; - public static final String CORE_JACKSON_2_MODULE_CLASS_NAME = "org.springframework.security.jackson2.CoreJackson2Module"; + public static final String SECURITY_CONTEXT_HOLDER_CLASS_NAME = + "org.springframework.security.core.context.SecurityContextHolder"; + public static final String CORE_JACKSON_2_MODULE_CLASS_NAME = + "org.springframework.security.jackson2.CoreJackson2Module"; public static final String OBJECT_MAPPER_CLASS_NAME = "com.fasterxml.jackson.databind.ObjectMapper"; public static final String JAVA_TIME_MODULE_CLASS_NAME = "com.fasterxml.jackson.datatype.jsr310.JavaTimeModule"; public static final String SIMPLE_MODULE_CLASS_NAME = "com.fasterxml.jackson.databind.module.SimpleModule"; private SecurityNames() {} - } diff --git a/dubbo-plugin/dubbo-spring-security/src/test/java/org/apache/dubbo/spring/security/jackson/ObjectMapperCodecTest.java b/dubbo-plugin/dubbo-spring-security/src/test/java/org/apache/dubbo/spring/security/jackson/ObjectMapperCodecTest.java index 67d1368a11..ea2d613ec6 100644 --- a/dubbo-plugin/dubbo-spring-security/src/test/java/org/apache/dubbo/spring/security/jackson/ObjectMapperCodecTest.java +++ b/dubbo-plugin/dubbo-spring-security/src/test/java/org/apache/dubbo/spring/security/jackson/ObjectMapperCodecTest.java @@ -14,9 +14,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.spring.security.jackson; +import java.time.Duration; +import java.time.Instant; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; @@ -25,9 +27,6 @@ import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.ClientAuthenticationMethod; import org.springframework.security.oauth2.core.OAuth2AccessToken; -import java.time.Duration; -import java.time.Instant; - public class ObjectMapperCodecTest { private ObjectMapperCodec mapper = new ObjectMapperCodec(); @@ -35,38 +34,40 @@ public class ObjectMapperCodecTest { @Test public void testOAuth2AuthorizedClientCodec() { ClientRegistration clientRegistration = clientRegistration().build(); - OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, "principal-name", noScopes()); + OAuth2AuthorizedClient authorizedClient = + new OAuth2AuthorizedClient(clientRegistration, "principal-name", noScopes()); String content = mapper.serialize(authorizedClient); - OAuth2AuthorizedClient deserialize = mapper.deserialize(content.getBytes(), - OAuth2AuthorizedClient.class); + OAuth2AuthorizedClient deserialize = mapper.deserialize(content.getBytes(), OAuth2AuthorizedClient.class); Assertions.assertNotNull(deserialize); } - public static ClientRegistration.Builder clientRegistration() { // @formatter:off return ClientRegistration.withRegistrationId("registration-id") - .redirectUri("http://localhost/uua/oauth2/code/{registrationId}") - .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) - .scope("read:user") - .authorizationUri("https://example.com/login/oauth/authorize") - .tokenUri("https://example.com/login/oauth/access_token") - .jwkSetUri("https://example.com/oauth2/jwk") - .issuerUri("https://example.com") - .userInfoUri("https://api.example.com/user") - .userNameAttributeName("id") - .clientName("Client Name") - .clientId("client-id") - .clientSecret("client-secret"); + .redirectUri("http://localhost/uua/oauth2/code/{registrationId}") + .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .scope("read:user") + .authorizationUri("https://example.com/login/oauth/authorize") + .tokenUri("https://example.com/login/oauth/access_token") + .jwkSetUri("https://example.com/oauth2/jwk") + .issuerUri("https://example.com") + .userInfoUri("https://api.example.com/user") + .userNameAttributeName("id") + .clientName("Client Name") + .clientId("client-id") + .clientSecret("client-secret"); // @formatter:on } public static OAuth2AccessToken noScopes() { - return new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "no-scopes", Instant.now(), - Instant.now().plus(Duration.ofDays(1))); + return new OAuth2AccessToken( + OAuth2AccessToken.TokenType.BEARER, + "no-scopes", + Instant.now(), + Instant.now().plus(Duration.ofDays(1))); } } diff --git a/dubbo-plugin/pom.xml b/dubbo-plugin/pom.xml index c72f37aaa7..ed36a48083 100644 --- a/dubbo-plugin/pom.xml +++ b/dubbo-plugin/pom.xml @@ -1,3 +1,4 @@ + - - org.apache.dubbo - dubbo-parent - ${revision} - ../pom.xml - - 4.0.0 + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + - dubbo-plugin - pom + dubbo-plugin + pom - dubbo-plugin - The registry module of dubbo project - - dubbo-qos - dubbo-auth - dubbo-reactive - dubbo-security - dubbo-spring-security - dubbo-qos-api - dubbo-plugin-cluster-mergeable - dubbo-native - dubbo-compiler - dubbo-plugin-mock - dubbo-plugin-router-script - dubbo-plugin-router-mesh - dubbo-plugin-router-condition - dubbo-plugin-router-tag - dubbo-plugin-loadbalance-adaptive - dubbo-plugin-access-log - dubbo-plugin-tps - dubbo-plugin-token - dubbo-plugin-generic-invoke - dubbo-plugin-context - dubbo-plugin-classloader-filter - dubbo-plugin-proxy-bytebuddy - dubbo-plugin-qos-trace - dubbo-filter-cache - dubbo-filter-validation - - - false - + dubbo-plugin + The registry module of dubbo project + + dubbo-qos + dubbo-auth + dubbo-reactive + dubbo-security + dubbo-spring-security + dubbo-qos-api + dubbo-plugin-cluster-mergeable + dubbo-native + dubbo-compiler + dubbo-plugin-mock + dubbo-plugin-router-script + dubbo-plugin-router-mesh + dubbo-plugin-router-condition + dubbo-plugin-router-tag + dubbo-plugin-loadbalance-adaptive + dubbo-plugin-access-log + dubbo-plugin-tps + dubbo-plugin-token + dubbo-plugin-generic-invoke + dubbo-plugin-context + dubbo-plugin-classloader-filter + dubbo-plugin-proxy-bytebuddy + dubbo-plugin-qos-trace + dubbo-filter-cache + dubbo-filter-validation + + + false + - - - org.apache.dubbo - dubbo-test-check - ${project.parent.version} - test - - - org.slf4j - slf4j-log4j12 - test - - + + + org.apache.dubbo + dubbo-test-check + ${project.parent.version} + test + + + org.slf4j + slf4j-log4j12 + test + + - - - loom - - [21,) - - - dubbo-plugin-loom - - - - release - - dubbo-plugin-loom - - - + + + loom + + [21,) + + + dubbo-plugin-loom + + + + release + + dubbo-plugin-loom + + + diff --git a/dubbo-registry/dubbo-registry-api/pom.xml b/dubbo-registry/dubbo-registry-api/pom.xml index dd5a180f01..244db28d0a 100644 --- a/dubbo-registry/dubbo-registry-api/pom.xml +++ b/dubbo-registry/dubbo-registry-api/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - org.apache.dubbo - dubbo-registry - ${revision} - ../pom.xml - - dubbo-registry-api - jar - ${project.artifactId} - The registry module of dubbo project - - false - - + + 4.0.0 + + org.apache.dubbo + dubbo-registry + ${revision} + ../pom.xml + + dubbo-registry-api + jar + ${project.artifactId} + The registry module of dubbo project + + false + + - - org.apache.dubbo - dubbo-common - ${project.parent.version} - + + org.apache.dubbo + dubbo-common + ${project.parent.version} + - - org.apache.dubbo - dubbo-cluster - ${project.parent.version} - - - org.apache.dubbo - dubbo-container-api - ${project.parent.version} - - - org.eclipse.jetty - jetty-server - - - org.eclipse.jetty - jetty-servlet - - - + + org.apache.dubbo + dubbo-cluster + ${project.parent.version} + + + org.apache.dubbo + dubbo-container-api + ${project.parent.version} + + + org.eclipse.jetty + jetty-server + + + org.eclipse.jetty + jetty-servlet + + + - - org.apache.dubbo - dubbo-metadata-api - ${project.parent.version} - + + org.apache.dubbo + dubbo-metadata-api + ${project.parent.version} + - - org.apache.curator - curator-framework - test - - - org.apache.curator - curator-recipes - test - - - org.apache.zookeeper - zookeeper - test - - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - compile - - - org.apache.dubbo - dubbo-metrics-default - ${project.parent.version} - compile - - - org.apache.dubbo - dubbo-metrics-metadata - ${project.parent.version} - compile - + + org.apache.curator + curator-framework + test + + + org.apache.curator + curator-recipes + test + + + org.apache.zookeeper + zookeeper + test + + + org.apache.dubbo + dubbo-metrics-api + ${project.parent.version} + compile + + + org.apache.dubbo + dubbo-metrics-default + ${project.parent.version} + compile + + + org.apache.dubbo + dubbo-metrics-metadata + ${project.parent.version} + compile + - - org.apache.dubbo - dubbo-metrics-registry - ${project.parent.version} - compile - + + org.apache.dubbo + dubbo-metrics-registry + ${project.parent.version} + compile + - - org.apache.dubbo - dubbo-native - ${project.parent.version} - + + org.apache.dubbo + dubbo-native + ${project.parent.version} + - - org.apache.dubbo - dubbo-plugin-cluster-mergeable - ${project.parent.version} - test - + + org.apache.dubbo + dubbo-plugin-cluster-mergeable + ${project.parent.version} + test + - - org.slf4j - slf4j-log4j12 - test - - + + org.slf4j + slf4j-log4j12 + test + + diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Constants.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Constants.java index 18eba314c8..f72b23e167 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Constants.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/Constants.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.registry; public interface Constants { @@ -118,7 +117,7 @@ public interface Constants { */ String MIGRATION_RULE_KEY = "key"; - String MIGRATION_RULE_STEP_KEY ="step"; + String MIGRATION_RULE_STEP_KEY = "step"; String MIGRATION_RULE_THRESHOLD_KEY = "threshold"; @@ -134,7 +133,7 @@ public interface Constants { String USER_HOME = "user.home"; - String DUBBO_REGISTRY = "/.dubbo/dubbo-registry-"; + String DUBBO_REGISTRY = "/.dubbo/dubbo-registry-"; String CACHE = ".cache"; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/ListenerRegistryWrapper.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/ListenerRegistryWrapper.java index 55418c99ae..936cc6433a 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/ListenerRegistryWrapper.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/ListenerRegistryWrapper.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.registry; import org.apache.dubbo.common.URL; @@ -29,12 +28,12 @@ import java.util.function.Consumer; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; public class ListenerRegistryWrapper implements Registry { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ListenerRegistryWrapper.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ListenerRegistryWrapper.class); private final Registry registry; private final List listeners; - public ListenerRegistryWrapper(Registry registry, List listeners) { this.registry = registry; this.listeners = listeners; @@ -92,14 +91,12 @@ public class ListenerRegistryWrapper implements Registry { } } - @Override public void unsubscribe(URL url, NotifyListener listener) { try { registry.unsubscribe(url, listener); } finally { listenerEvent(serviceListener -> serviceListener.onUnsubscribe(url, registry)); - } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/NotifyListener.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/NotifyListener.java index 08f1a1aa2a..30fbd0cf18 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/NotifyListener.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/NotifyListener.java @@ -42,8 +42,7 @@ public interface NotifyListener { */ void notify(List urls); - default void addServiceListener(ServiceInstancesChangedListener instanceListener) { - } + default void addServiceListener(ServiceInstancesChangedListener instanceListener) {} default ServiceInstancesChangedListener getServiceListener() { return null; @@ -52,5 +51,4 @@ public interface NotifyListener { default URL getConsumerUrl() { return null; } - } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryFactory.java index 8ed918aae5..5c3669170e 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryFactory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryFactory.java @@ -47,5 +47,4 @@ public interface RegistryFactory { */ @Adaptive({PROTOCOL_KEY}) Registry getRegistry(URL url); - } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryFactoryWrapper.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryFactoryWrapper.java index 6fe365d970..9071375917 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryFactoryWrapper.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryFactoryWrapper.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.registry; import org.apache.dubbo.common.URL; @@ -30,8 +29,10 @@ public class RegistryFactoryWrapper implements RegistryFactory { @Override public Registry getRegistry(URL url) { - return new ListenerRegistryWrapper(registryFactory.getRegistry(url), - Collections.unmodifiableList(url.getOrDefaultApplicationModel().getExtensionLoader(RegistryServiceListener.class) + return new ListenerRegistryWrapper( + registryFactory.getRegistry(url), + Collections.unmodifiableList(url.getOrDefaultApplicationModel() + .getExtensionLoader(RegistryServiceListener.class) .getActivateExtension(url, "registry.listeners"))); } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryNotifier.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryNotifier.java index ae60b913fa..d399e6c504 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryNotifier.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryNotifier.java @@ -54,8 +54,11 @@ public abstract class RegistryNotifier { this.url = registryUrl; this.delayTime = delayTime; if (scheduler == null) { - this.scheduler = registryUrl.getOrDefaultFrameworkModel().getBeanFactory() - .getBean(FrameworkExecutorRepository.class).getRegistryNotificationExecutor(); + this.scheduler = registryUrl + .getOrDefaultFrameworkModel() + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class) + .getRegistryNotificationExecutor(); } else { this.scheduler = scheduler; } @@ -73,7 +76,11 @@ public abstract class RegistryNotifier { // when the scheduler is shutdown, no notification is sent if (scheduler.isShutdown()) { if (logger.isWarnEnabled()) { - logger.warn(COMMON_FAILED_NOTIFY_EVENT, "", "", "Notification scheduler is off, no notifications are sent. Registry URL: " + url); + logger.warn( + COMMON_FAILED_NOTIFY_EVENT, + "", + "", + "Notification scheduler is off, no notifications are sent. Registry URL: " + url); } return; } else if (delay) { @@ -132,5 +139,4 @@ public abstract class RegistryNotifier { } } } - } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryScopeModelInitializer.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryScopeModelInitializer.java index a33ab61ecd..3c60a08cba 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryScopeModelInitializer.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryScopeModelInitializer.java @@ -40,7 +40,5 @@ public class RegistryScopeModelInitializer implements ScopeModelInitializer { } @Override - public void initializeModuleModel(ModuleModel moduleModel) { - - } + public void initializeModuleModel(ModuleModel moduleModel) {} } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryService.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryService.java index 66d0c91267..5093c6e719 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryService.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryService.java @@ -90,5 +90,4 @@ public interface RegistryService { * @see org.apache.dubbo.registry.NotifyListener#notify(List) */ List lookup(URL url); - } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryServiceListener.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryServiceListener.java index 283d7ee7e6..4c51492667 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryServiceListener.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/RegistryServiceListener.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.registry; import org.apache.dubbo.common.URL; @@ -22,20 +21,11 @@ import org.apache.dubbo.common.extension.SPI; @SPI public interface RegistryServiceListener { - default void onRegister(URL url, Registry registry) { + default void onRegister(URL url, Registry registry) {} - } + default void onUnregister(URL url, Registry registry) {} + default void onSubscribe(URL url, Registry registry) {} - default void onUnregister(URL url, Registry registry) { - - } - - default void onSubscribe(URL url, Registry registry) { - - } - - default void onUnsubscribe(URL url, Registry registry) { - - } + default void onUnsubscribe(URL url, Registry registry) {} } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/aot/RegistryReflectionTypeDescriberRegistrar.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/aot/RegistryReflectionTypeDescriberRegistrar.java index 94d8a635f7..8179e04165 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/aot/RegistryReflectionTypeDescriberRegistrar.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/aot/RegistryReflectionTypeDescriberRegistrar.java @@ -26,7 +26,6 @@ import java.util.HashSet; import java.util.List; import java.util.Set; - public class RegistryReflectionTypeDescriberRegistrar implements ReflectionTypeDescriberRegistrar { @Override @@ -41,6 +40,7 @@ public class RegistryReflectionTypeDescriberRegistrar implements ReflectionTypeD Set memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.INVOKE_PUBLIC_METHODS); memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); - return new TypeDescriber(cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); + return new TypeDescriber( + cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java index b3b771c20e..341d8926f8 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java @@ -82,7 +82,8 @@ public abstract class AbstractServiceDiscovery implements ServiceDiscovery { public AbstractServiceDiscovery(ApplicationModel applicationModel, URL registryURL) { this(applicationModel, applicationModel.getApplicationName(), registryURL); - MetadataReportInstance metadataReportInstance = applicationModel.getBeanFactory().getBean(MetadataReportInstance.class); + MetadataReportInstance metadataReportInstance = + applicationModel.getBeanFactory().getBean(MetadataReportInstance.class); metadataType = metadataReportInstance.getMetadataType(); this.metadataReport = metadataReportInstance.getMetadataReport(registryURL.getParameter(REGISTRY_CLUSTER_KEY)); } @@ -97,36 +98,51 @@ public abstract class AbstractServiceDiscovery implements ServiceDiscovery { this.registryURL = registryURL; this.metadataInfo = new MetadataInfo(serviceName); boolean localCacheEnabled = registryURL.getParameter(REGISTRY_LOCAL_FILE_CACHE_ENABLED, true); - this.metaCacheManager = new MetaCacheManager(localCacheEnabled, getCacheNameSuffix(), - applicationModel.getFrameworkModel().getBeanFactory() - .getBean(FrameworkExecutorRepository.class).getCacheRefreshingScheduledExecutor()); - int metadataInfoCacheExpireTime = registryURL.getParameter(METADATA_INFO_CACHE_EXPIRE_KEY, DEFAULT_METADATA_INFO_CACHE_EXPIRE); - int metadataInfoCacheSize = registryURL.getParameter(METADATA_INFO_CACHE_SIZE_KEY, DEFAULT_METADATA_INFO_CACHE_SIZE); - this.refreshCacheFuture = applicationModel.getFrameworkModel().getBeanFactory() - .getBean(FrameworkExecutorRepository.class).getSharedScheduledExecutor() - .scheduleAtFixedRate(() -> { - try { - while (metadataInfos.size() > metadataInfoCacheSize) { - AtomicReference oldestRevision = new AtomicReference<>(); - AtomicReference oldestStat = new AtomicReference<>(); - metadataInfos.forEach((k, v) -> { - if (System.currentTimeMillis() - v.getUpdateTime() > metadataInfoCacheExpireTime && - (oldestStat.get() == null || oldestStat.get().getUpdateTime() > v.getUpdateTime())) { - oldestRevision.set(k); - oldestStat.set(v); + this.metaCacheManager = new MetaCacheManager( + localCacheEnabled, + getCacheNameSuffix(), + applicationModel + .getFrameworkModel() + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class) + .getCacheRefreshingScheduledExecutor()); + int metadataInfoCacheExpireTime = + registryURL.getParameter(METADATA_INFO_CACHE_EXPIRE_KEY, DEFAULT_METADATA_INFO_CACHE_EXPIRE); + int metadataInfoCacheSize = + registryURL.getParameter(METADATA_INFO_CACHE_SIZE_KEY, DEFAULT_METADATA_INFO_CACHE_SIZE); + this.refreshCacheFuture = applicationModel + .getFrameworkModel() + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class) + .getSharedScheduledExecutor() + .scheduleAtFixedRate( + () -> { + try { + while (metadataInfos.size() > metadataInfoCacheSize) { + AtomicReference oldestRevision = new AtomicReference<>(); + AtomicReference oldestStat = new AtomicReference<>(); + metadataInfos.forEach((k, v) -> { + if (System.currentTimeMillis() - v.getUpdateTime() > metadataInfoCacheExpireTime + && (oldestStat.get() == null + || oldestStat.get().getUpdateTime() > v.getUpdateTime())) { + oldestRevision.set(k); + oldestStat.set(v); + } + }); + if (oldestStat.get() != null) { + metadataInfos.remove(oldestRevision.get(), oldestStat.get()); + } } - }); - if (oldestStat.get() != null) { - metadataInfos.remove(oldestRevision.get(), oldestStat.get()); + } catch (Throwable t) { + logger.error( + INTERNAL_ERROR, "", "", "Error occurred when clean up metadata info cache.", t); } - } - } catch (Throwable t) { - logger.error(INTERNAL_ERROR, "", "", "Error occurred when clean up metadata info cache.", t); - } - }, metadataInfoCacheExpireTime / 2, metadataInfoCacheExpireTime / 2, TimeUnit.MILLISECONDS); + }, + metadataInfoCacheExpireTime / 2, + metadataInfoCacheExpireTime / 2, + TimeUnit.MILLISECONDS); } - @Override public synchronized void register() throws RuntimeException { if (isDestroy) { @@ -165,10 +181,13 @@ public abstract class AbstractServiceDiscovery implements ServiceDiscovery { return; } ServiceInstance oldServiceInstance = this.serviceInstance; - DefaultServiceInstance newServiceInstance = new DefaultServiceInstance((DefaultServiceInstance) oldServiceInstance); + DefaultServiceInstance newServiceInstance = + new DefaultServiceInstance((DefaultServiceInstance) oldServiceInstance); boolean revisionUpdated = calOrUpdateInstanceRevision(newServiceInstance); if (revisionUpdated) { - logger.info(String.format("Metadata of instance changed, updating instance with revision %s.", newServiceInstance.getServiceMetadata().getRevision())); + logger.info(String.format( + "Metadata of instance changed, updating instance with revision %s.", + newServiceInstance.getServiceMetadata().getRevision())); doUpdate(oldServiceInstance, newServiceInstance); this.serviceInstance = newServiceInstance; } @@ -180,7 +199,7 @@ public abstract class AbstractServiceDiscovery implements ServiceDiscovery { return; } // fixme, this metadata info might still being shared by other instances -// unReportMetadata(this.metadataInfo); + // unReportMetadata(this.metadataInfo); if (!isValidInstance(this.serviceInstance)) { return; } @@ -225,16 +244,15 @@ public abstract class AbstractServiceDiscovery implements ServiceDiscovery { int triedTimes = 0; while (triedTimes < 3) { - metadata = MetricsEventBus.post(MetadataEvent.toSubscribeEvent(applicationModel), - () -> MetadataUtils.getRemoteMetadata(revision, instances, metadataReport), - result -> result != MetadataInfo.EMPTY - ); + metadata = MetricsEventBus.post( + MetadataEvent.toSubscribeEvent(applicationModel), + () -> MetadataUtils.getRemoteMetadata(revision, instances, metadataReport), + result -> result != MetadataInfo.EMPTY); - - if (metadata != MetadataInfo.EMPTY) {// succeeded + if (metadata != MetadataInfo.EMPTY) { // succeeded metadata.init(); break; - } else {// failed + } else { // failed if (triedTimes > 0) { if (logger.isDebugEnabled()) { logger.debug("Retry the " + triedTimes + " times to get metadata for revision=" + revision); @@ -249,7 +267,11 @@ public abstract class AbstractServiceDiscovery implements ServiceDiscovery { } if (metadata == MetadataInfo.EMPTY) { - logger.error(REGISTRY_FAILED_LOAD_METADATA, "", "", "Failed to get metadata for revision after 3 retries, revision=" + revision); + logger.error( + REGISTRY_FAILED_LOAD_METADATA, + "", + "", + "Failed to get metadata for revision after 3 retries, revision=" + revision); } else { metaCacheManager.put(revision, metadata); } @@ -297,7 +319,8 @@ public abstract class AbstractServiceDiscovery implements ServiceDiscovery { @Override public List lookup(URL url) { - throw new UnsupportedOperationException("Service discovery implementation does not support lookup of url list."); + throw new UnsupportedOperationException( + "Service discovery implementation does not support lookup of url list."); } /** @@ -356,14 +379,14 @@ public abstract class AbstractServiceDiscovery implements ServiceDiscovery { return; } if (metadataReport != null) { - SubscriberMetadataIdentifier identifier = new SubscriberMetadataIdentifier(serviceName, metadataInfo.getRevision()); - if ((DEFAULT_METADATA_STORAGE_TYPE.equals(metadataType) && metadataReport.shouldReportMetadata()) || REMOTE_METADATA_STORAGE_TYPE.equals(metadataType)) { - MetricsEventBus.post(MetadataEvent.toPushEvent(applicationModel), - () -> - { - metadataReport.publishAppMetadata(identifier, metadataInfo); - return null; - }); + SubscriberMetadataIdentifier identifier = + new SubscriberMetadataIdentifier(serviceName, metadataInfo.getRevision()); + if ((DEFAULT_METADATA_STORAGE_TYPE.equals(metadataType) && metadataReport.shouldReportMetadata()) + || REMOTE_METADATA_STORAGE_TYPE.equals(metadataType)) { + MetricsEventBus.post(MetadataEvent.toPushEvent(applicationModel), () -> { + metadataReport.publishAppMetadata(identifier, metadataInfo); + return null; + }); } } MetadataInfo clonedMetadataInfo = metadataInfo.clone(); @@ -372,8 +395,10 @@ public abstract class AbstractServiceDiscovery implements ServiceDiscovery { protected void unReportMetadata(MetadataInfo metadataInfo) { if (metadataReport != null) { - SubscriberMetadataIdentifier identifier = new SubscriberMetadataIdentifier(serviceName, metadataInfo.getRevision()); - if ((DEFAULT_METADATA_STORAGE_TYPE.equals(metadataType) && metadataReport.shouldReportMetadata()) || REMOTE_METADATA_STORAGE_TYPE.equals(metadataType)) { + SubscriberMetadataIdentifier identifier = + new SubscriberMetadataIdentifier(serviceName, metadataInfo.getRevision()); + if ((DEFAULT_METADATA_STORAGE_TYPE.equals(metadataType) && metadataReport.shouldReportMetadata()) + || REMOTE_METADATA_STORAGE_TYPE.equals(metadataType)) { metadataReport.unPublishAppMetadata(identifier, metadataInfo); } } @@ -386,7 +411,8 @@ public abstract class AbstractServiceDiscovery implements ServiceDiscovery { name = name.substring(0, i); } StringBuilder stringBuilder = new StringBuilder(128); - Optional application = applicationModel.getApplicationConfigManager().getApplication(); + Optional application = + applicationModel.getApplicationConfigManager().getApplication(); if (application.isPresent()) { stringBuilder.append(application.get().getName()); stringBuilder.append("."); diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscoveryFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscoveryFactory.java index 469a507510..ae90f36d75 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscoveryFactory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscoveryFactory.java @@ -59,5 +59,4 @@ public abstract class AbstractServiceDiscoveryFactory implements ServiceDiscover } protected abstract ServiceDiscovery createDiscovery(URL registryURL); - } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceInstance.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceInstance.java index 266615de54..191636e19a 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceInstance.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceInstance.java @@ -70,12 +70,12 @@ public class DefaultServiceInstance implements ServiceInstance { * extendParams can be more flexible, but one single property uses less space */ private transient Map extendParams; + private transient List endpoints; private transient ApplicationModel applicationModel; private transient Map instanceAddressURL = new ConcurrentHashMap<>(); - public DefaultServiceInstance() { - } + public DefaultServiceInstance() {} public DefaultServiceInstance(DefaultServiceInstance other) { this.serviceName = other.serviceName; @@ -111,7 +111,6 @@ public class DefaultServiceInstance implements ServiceInstance { this.rawAddress = rawAddress; } - public void setServiceName(String serviceName) { this.serviceName = serviceName; } @@ -292,8 +291,8 @@ public class DefaultServiceInstance implements ServiceInstance { @Override public InstanceAddressURL toURL(String protocol) { - return instanceAddressURL.computeIfAbsent(protocol, - key -> new InstanceAddressURL(this, serviceMetadata, protocol)); + return instanceAddressURL.computeIfAbsent( + protocol, key -> new InstanceAddressURL(this, serviceMetadata, protocol)); } @Override @@ -305,9 +304,9 @@ public class DefaultServiceInstance implements ServiceInstance { return false; } DefaultServiceInstance that = (DefaultServiceInstance) o; - boolean equals = Objects.equals(getServiceName(), that.getServiceName()) && - Objects.equals(getHost(), that.getHost()) && - Objects.equals(getPort(), that.getPort()); + boolean equals = Objects.equals(getServiceName(), that.getServiceName()) + && Objects.equals(getHost(), that.getHost()) + && Objects.equals(getPort(), that.getPort()); for (Map.Entry entry : this.getMetadata().entrySet()) { if (entry.getKey().equals(EXPORTED_SERVICES_REVISION_PROPERTY_NAME)) { continue; @@ -329,7 +328,8 @@ public class DefaultServiceInstance implements ServiceInstance { if (entry.getKey().equals(EXPORTED_SERVICES_REVISION_PROPERTY_NAME)) { continue; } - result = 31 * result + (entry.getValue() == null ? 0 : entry.getValue().hashCode()); + result = 31 * result + + (entry.getValue() == null ? 0 : entry.getValue().hashCode()); } return result; } @@ -340,22 +340,20 @@ public class DefaultServiceInstance implements ServiceInstance { } public String toFullString() { - return "DefaultServiceInstance{" + - "serviceName='" + serviceName + '\'' + - ", host='" + host + '\'' + - ", port=" + port + - ", enabled=" + enabled + - ", healthy=" + healthy + - ", metadata=" + metadata + - '}'; + return "DefaultServiceInstance{" + "serviceName='" + + serviceName + '\'' + ", host='" + + host + '\'' + ", port=" + + port + ", enabled=" + + enabled + ", healthy=" + + healthy + ", metadata=" + + metadata + '}'; } public static class Endpoint { int port; String protocol; - public Endpoint() { - } + public Endpoint() {} public Endpoint(int port, String protocol) { this.port = port; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/FileSystemServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/FileSystemServiceDiscovery.java deleted file mode 100644 index d1d46e1e55..0000000000 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/FileSystemServiceDiscovery.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.dubbo.registry.client; -// -//import com.alibaba.fastjson.JSON; -//import org.apache.commons.io.FileUtils; -//import org.apache.dubbo.common.URL; -//import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; -//import org.apache.dubbo.common.config.configcenter.file.FileSystemDynamicConfiguration; -//import org.apache.dubbo.common.lang.ShutdownHookCallbacks; -//import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; -//import org.apache.dubbo.common.logger.LoggerFactory; -//import org.apache.dubbo.common.utils.StringUtils; -// -//import java.io.File; -//import java.io.IOException; -//import java.nio.channels.FileChannel; -//import java.nio.channels.FileLock; -//import java.nio.file.LinkOption; -//import java.nio.file.Path; -//import java.nio.file.StandardOpenOption; -//import java.util.List; -//import java.util.Map; -//import java.util.Set; -//import java.util.concurrent.ConcurrentHashMap; -//import java.util.stream.Collectors; -// -//import static com.alibaba.fastjson.JSON.toJSONString; -//import static java.lang.String.format; -//import static java.nio.channels.FileChannel.open; -//import static org.apache.dubbo.common.config.configcenter.DynamicConfiguration.DEFAULT_GROUP; -//import static org.apache.dubbo.common.config.configcenter.file.FileSystemDynamicConfiguration.CONFIG_CENTER_DIR_PARAM_NAME; -// -///** -// * File System {@link ServiceDiscovery} implementation -// * -// * @see FileSystemDynamicConfiguration -// * @since 2.7.5 -// */ -//public class FileSystemServiceDiscovery extends AbstractServiceDiscovery { -// -// private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); -// -// private final Map fileLocksCache = new ConcurrentHashMap<>(); -// -// private FileSystemDynamicConfiguration dynamicConfiguration; -// -// public FileSystemServiceDiscovery(String serviceName) { -// super(serviceName); -// } -// -// @Override -// public void doInitialize(URL registryURL) throws Exception { -// dynamicConfiguration = createDynamicConfiguration(registryURL); -// registerDubboShutdownHook(); -// registerListener(); -// } -// -// private void registerDubboShutdownHook() { -// serviceInstance.getApplicationModel().getBeanFactory().getBean(ShutdownHookCallbacks.class) -// .addCallback(this::destroy); -// } -// -// private void registerListener() { -// getServices().forEach(serviceName -> { -// dynamicConfiguration.getConfigKeys(DEFAULT_GROUP).forEach(serviceInstanceId -> { -// dynamicConfiguration.addListener(serviceInstanceId, serviceName, this::onConfigChanged); -// }); -// }); -// } -// -// public void onConfigChanged(ConfigChangedEvent event) { -// -// } -// -// @Override -// public void doDestroy() throws Exception { -// dynamicConfiguration.close(); -// releaseAndRemoveRegistrationFiles(); -// } -// -// private void releaseAndRemoveRegistrationFiles() { -// fileLocksCache.keySet().forEach(file -> { -// releaseFileLock(file); -// removeFile(file); -// }); -// } -// -// private void removeFile(File file) { -// FileUtils.deleteQuietly(file); -// } -// -// private String getServiceInstanceId(ServiceInstance serviceInstance) { -// String id = serviceInstance.getAddress(); -// if (StringUtils.isBlank(id)) { -// return serviceInstance.getHost() + "." + serviceInstance.getPort(); -// } -// return id; -// } -// -// private String getServiceName(ServiceInstance serviceInstance) { -// return serviceInstance.getServiceName(); -// } -// -// @Override -// public List getInstances(String serviceName) { -// return dynamicConfiguration.getConfigKeys(DEFAULT_GROUP) -// .stream() -// .map(serviceInstanceId -> dynamicConfiguration.getConfig(serviceInstanceId, serviceName)) -// .map(content -> JSON.parseObject(content, DefaultServiceInstance.class)) -// .collect(Collectors.toList()); -// } -// -// @Override -// public URL getUrl() { -// return null; -// } -// -// -// @Override -// public void doRegister(ServiceInstance serviceInstance) throws RuntimeException { -// this.serviceInstance = serviceInstance; -// String serviceInstanceId = getServiceInstanceId(serviceInstance); -// String serviceName = getServiceName(serviceInstance); -// String content = toJSONString(serviceInstance); -// if (dynamicConfiguration.publishConfig(serviceInstanceId, serviceName, content)) { -// lockFile(serviceInstanceId, serviceName); -// } -// } -// -// private void lockFile(String serviceInstanceId, String serviceName) { -// File serviceInstanceFile = serviceInstanceFile(serviceInstanceId, serviceName); -// Path serviceInstanceFilePath = serviceInstanceFile.toPath(); -// -// fileLocksCache.computeIfAbsent(serviceInstanceFile, file -> { -// FileLock fileLock = null; -// try { -// FileChannel fileChannel = open(serviceInstanceFilePath, StandardOpenOption.READ, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS); -// fileLock = fileChannel.tryLock(); -// } catch (IOException e) { -// if (logger.isErrorEnabled()) { -// logger.error(e.getMessage(), e); -// } -// } -// if (fileLock != null) { -// if (logger.isInfoEnabled()) { -// logger.info(format("%s has been locked", serviceInstanceFilePath.toAbsolutePath())); -// } -// } -// return fileLock; -// }); -// } -// -// @Override -// public void doUnregister() throws RuntimeException { -// String key = getServiceInstanceId(serviceInstance); -// String group = getServiceName(serviceInstance); -// releaseFileLock(key, group); -// dynamicConfiguration.removeConfig(key, group); -// } -// -// private void releaseFileLock(String serviceInstanceId, String serviceName) { -// File serviceInstanceFile = serviceInstanceFile(serviceInstanceId, serviceName); -// releaseFileLock(serviceInstanceFile); -// } -// -// private void releaseFileLock(File serviceInstanceFile) { -// fileLocksCache.computeIfPresent(serviceInstanceFile, (f, fileLock) -> { -// releaseFileLock(fileLock); -// if (logger.isInfoEnabled()) { -// logger.info(format("The file[%s] has been released", serviceInstanceFile.getAbsolutePath())); -// } -// return null; -// }); -// } -// -// private void releaseFileLock(FileLock fileLock) { -// try (FileChannel fileChannel = fileLock.channel()) { -// fileLock.release(); -// } catch (IOException e) { -// if (logger.isErrorEnabled()) { -// logger.error(e.getMessage(), e); -// } -// } -// } -// -// private File serviceInstanceFile(String serviceInstanceId, String serviceName) { -// return dynamicConfiguration.configFile(serviceInstanceId, serviceName); -// } -// -// @Override -// public Set getServices() { -// return dynamicConfiguration.getConfigGroups(); -// } -// -// private static FileSystemDynamicConfiguration createDynamicConfiguration(URL connectionURL) { -// String path = System.getProperty("user.home") + File.separator + ".dubbo" + File.separator + "registry"; -// return new FileSystemDynamicConfiguration(connectionURL.addParameter(CONFIG_CENTER_DIR_PARAM_NAME, path)); -// } -//} diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/InstanceAddressURL.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/InstanceAddressURL.java index d418030d6b..8cb2ff9935 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/InstanceAddressURL.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/InstanceAddressURL.java @@ -50,7 +50,7 @@ public class InstanceAddressURL extends URL { private final MetadataInfo metadataInfo; // cached numbers - private volatile transient Set providerFirstParams; + private transient volatile Set providerFirstParams; // one instance address url serves only one protocol. private final transient String protocol; @@ -58,20 +58,13 @@ public class InstanceAddressURL extends URL { this(null, null, null); } - public InstanceAddressURL( - ServiceInstance instance, - MetadataInfo metadataInfo - ) { + public InstanceAddressURL(ServiceInstance instance, MetadataInfo metadataInfo) { this.instance = instance; this.metadataInfo = metadataInfo; this.protocol = DUBBO; } - public InstanceAddressURL( - ServiceInstance instance, - MetadataInfo metadataInfo, - String protocol - ) { + public InstanceAddressURL(ServiceInstance instance, MetadataInfo metadataInfo, String protocol) { this.instance = instance; this.metadataInfo = metadataInfo; this.protocol = protocol; @@ -126,22 +119,26 @@ public class InstanceAddressURL extends URL { @Override public URL setProtocol(String protocol) { - return new ServiceConfigURL(protocol, getUsername(), getPassword(), getHost(), getPort(), getPath(), getParameters(), attributes); + return new ServiceConfigURL( + protocol, getUsername(), getPassword(), getHost(), getPort(), getPath(), getParameters(), attributes); } @Override public URL setHost(String host) { - return new ServiceConfigURL(getProtocol(), getUsername(), getPassword(), host, getPort(), getPath(), getParameters(), attributes); + return new ServiceConfigURL( + getProtocol(), getUsername(), getPassword(), host, getPort(), getPath(), getParameters(), attributes); } @Override public URL setPort(int port) { - return new ServiceConfigURL(getProtocol(), getUsername(), getPassword(), getHost(), port, getPath(), getParameters(), attributes); + return new ServiceConfigURL( + getProtocol(), getUsername(), getPassword(), getHost(), port, getPath(), getParameters(), attributes); } @Override public URL setPath(String path) { - return new ServiceConfigURL(getProtocol(), getUsername(), getPassword(), getHost(), getPort(), path, getParameters(), attributes); + return new ServiceConfigURL( + getProtocol(), getUsername(), getPassword(), getHost(), getPort(), path, getParameters(), attributes); } @Override @@ -429,7 +426,8 @@ public class InstanceAddressURL extends URL { @Override public Map getOriginalServiceParameters(String protocolServiceKey) { Map instanceParams = getInstance().getAllParams(); - Map metadataParams = (metadataInfo == null ? new HashMap<>() : metadataInfo.getParameters(protocolServiceKey)); + Map metadataParams = + (metadataInfo == null ? new HashMap<>() : metadataInfo.getParameters(protocolServiceKey)); int i = instanceParams == null ? 0 : instanceParams.size(); int j = metadataParams == null ? 0 : metadataParams.size(); Map params = new HashMap<>((int) ((i + j) / 0.75) + 1); @@ -443,7 +441,6 @@ public class InstanceAddressURL extends URL { return params; } - /** * Avoid calling this method in RPC call. * @@ -452,7 +449,8 @@ public class InstanceAddressURL extends URL { @Override public Map getServiceParameters(String protocolServiceKey) { Map instanceParams = getInstance().getAllParams(); - Map metadataParams = (metadataInfo == null ? new HashMap<>() : metadataInfo.getParameters(protocolServiceKey)); + Map metadataParams = + (metadataInfo == null ? new HashMap<>() : metadataInfo.getParameters(protocolServiceKey)); int i = instanceParams == null ? 0 : instanceParams.size(); int j = metadataParams == null ? 0 : metadataParams.size(); Map params = new HashMap<>((int) ((i + j) / 0.75) + 1); @@ -626,8 +624,8 @@ public class InstanceAddressURL extends URL { @Override public ScopeModel getScopeModel() { return Optional.ofNullable(RpcContext.getServiceContext().getConsumerUrl()) - .map(URL::getScopeModel) - .orElse(super.getScopeModel()); + .map(URL::getScopeModel) + .orElse(super.getScopeModel()); } @Override diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/NopServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/NopServiceDiscovery.java index 2df58f9b19..c5f23b6ca5 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/NopServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/NopServiceDiscovery.java @@ -32,19 +32,13 @@ public class NopServiceDiscovery extends AbstractServiceDiscovery { } @Override - public void doRegister(ServiceInstance serviceInstance) throws RuntimeException { - - } + public void doRegister(ServiceInstance serviceInstance) throws RuntimeException {} @Override - public void doUnregister(ServiceInstance serviceInstance) { - - } + public void doUnregister(ServiceInstance serviceInstance) {} @Override - public void doDestroy() throws Exception { - - } + public void doDestroy() throws Exception {} @Override public Set getServices() { diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/OverrideInstanceAddressURL.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/OverrideInstanceAddressURL.java index 4791dceab4..5a15892c03 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/OverrideInstanceAddressURL.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/OverrideInstanceAddressURL.java @@ -128,34 +128,33 @@ public class OverrideInstanceAddressURL extends InstanceAddressURL { @Override public String getServiceMethodParameter(String protocolServiceKey, String method, String key) { String overrideParam = overrideParams.getMethodParameter(method, key); - return StringUtils.isNotEmpty(overrideParam) ? - overrideParam : - originUrl.getServiceMethodParameter(protocolServiceKey, method, key); + return StringUtils.isNotEmpty(overrideParam) + ? overrideParam + : originUrl.getServiceMethodParameter(protocolServiceKey, method, key); } @Override public String getMethodParameter(String method, String key) { String overrideParam = overrideParams.getMethodParameter(method, key); - return StringUtils.isNotEmpty(overrideParam) ? - overrideParam : - originUrl.getMethodParameter(method, key); + return StringUtils.isNotEmpty(overrideParam) ? overrideParam : originUrl.getMethodParameter(method, key); } @Override public boolean hasServiceMethodParameter(String protocolServiceKey, String method, String key) { - return StringUtils.isNotEmpty(overrideParams.getMethodParameter(method, key)) || - originUrl.hasServiceMethodParameter(protocolServiceKey, method, key); + return StringUtils.isNotEmpty(overrideParams.getMethodParameter(method, key)) + || originUrl.hasServiceMethodParameter(protocolServiceKey, method, key); } @Override public boolean hasMethodParameter(String method, String key) { - return StringUtils.isNotEmpty(overrideParams.getMethodParameter(method, key)) || - originUrl.hasMethodParameter(method, key); + return StringUtils.isNotEmpty(overrideParams.getMethodParameter(method, key)) + || originUrl.hasMethodParameter(method, key); } @Override public boolean hasServiceMethodParameter(String protocolServiceKey, String method) { - return overrideParams.hasMethodParameter(method) || originUrl.hasServiceMethodParameter(protocolServiceKey, method); + return overrideParams.hasMethodParameter(method) + || originUrl.hasServiceMethodParameter(protocolServiceKey, method); } @Override @@ -311,6 +310,7 @@ public class OverrideInstanceAddressURL extends InstanceAddressURL { // create a new object from the deserialized one return new OverrideInstanceAddressURL(this.originUrl, this.overrideParams); } + @Override protected OverrideInstanceAddressURL newURL(URLAddress urlAddress, URLParam urlParam) { return new OverrideInstanceAddressURL(originUrl, overrideParams); diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ReflectionBasedServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ReflectionBasedServiceDiscovery.java index d6f37d6f0f..dfb5e18ea4 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ReflectionBasedServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ReflectionBasedServiceDiscovery.java @@ -16,19 +16,6 @@ */ package org.apache.dubbo.registry.client; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -52,6 +39,19 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ScopeModelUtil; import org.apache.dubbo.rpc.service.Destroyable; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_NOTIFY_EVENT; public class ReflectionBasedServiceDiscovery extends AbstractServiceDiscovery { @@ -62,7 +62,8 @@ public class ReflectionBasedServiceDiscovery extends AbstractServiceDiscovery { * Echo check if consumer is still work * echo task may take a lot of time when consumer offline, create a new ScheduledThreadPool */ - private final ScheduledExecutorService echoCheckExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Dubbo-Registry-EchoCheck-Consumer")); + private final ScheduledExecutorService echoCheckExecutor = + Executors.newScheduledThreadPool(1, new NamedThreadFactory("Dubbo-Registry-EchoCheck-Consumer")); // =================================== Provider side =================================== // /** @@ -103,33 +104,39 @@ public class ReflectionBasedServiceDiscovery extends AbstractServiceDiscovery { public ReflectionBasedServiceDiscovery(ApplicationModel applicationModel, URL registryURL) { super(applicationModel, registryURL); - long echoPollingCycle = registryURL.getParameter(Constants.ECHO_POLLING_CYCLE_KEY, Constants.DEFAULT_ECHO_POLLING_CYCLE); + long echoPollingCycle = + registryURL.getParameter(Constants.ECHO_POLLING_CYCLE_KEY, Constants.DEFAULT_ECHO_POLLING_CYCLE); this.metadataService = applicationModel.getBeanFactory().getOrRegisterBean(MetadataServiceDelegation.class); // Echo check: test if consumer is offline, remove MetadataChangeListener, // reduce the probability of failure when metadata update - echoCheckExecutor.scheduleAtFixedRate(() -> { - Map listenerMap = metadataService.getInstanceMetadataChangedListenerMap(); - Iterator> iterator = listenerMap.entrySet().iterator(); + echoCheckExecutor.scheduleAtFixedRate( + () -> { + Map listenerMap = + metadataService.getInstanceMetadataChangedListenerMap(); + Iterator> iterator = + listenerMap.entrySet().iterator(); - while (iterator.hasNext()) { - Map.Entry entry = iterator.next(); - try { - entry.getValue().echo(CommonConstants.DUBBO); - } catch (RpcException e) { - if (logger.isInfoEnabled()) { - logger.info("Send echo message to consumer error. Possible cause: consumer is offline."); + while (iterator.hasNext()) { + Map.Entry entry = iterator.next(); + try { + entry.getValue().echo(CommonConstants.DUBBO); + } catch (RpcException e) { + if (logger.isInfoEnabled()) { + logger.info( + "Send echo message to consumer error. Possible cause: consumer is offline."); + } + iterator.remove(); + } } - iterator.remove(); - } - } - }, echoPollingCycle, echoPollingCycle, TimeUnit.MILLISECONDS); + }, + echoPollingCycle, + echoPollingCycle, + TimeUnit.MILLISECONDS); } - public void doInitialize(URL registryURL) { - - } + public void doInitialize(URL registryURL) {} @Override public void doDestroy() throws Exception { @@ -154,8 +161,10 @@ public class ReflectionBasedServiceDiscovery extends AbstractServiceDiscovery { metadataService.exportInstanceMetadata(metadataString); // notify to consumer - Map listenerMap = metadataService.getInstanceMetadataChangedListenerMap(); - Iterator> iterator = listenerMap.entrySet().iterator(); + Map listenerMap = + metadataService.getInstanceMetadataChangedListenerMap(); + Iterator> iterator = + listenerMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = iterator.next(); @@ -165,8 +174,11 @@ public class ReflectionBasedServiceDiscovery extends AbstractServiceDiscovery { // 1-7 - Failed to notify registry event. // The updating of metadata to consumer is a type of registry event. - logger.warn(REGISTRY_FAILED_NOTIFY_EVENT, "consumer is offline", "", - "Notify to consumer error, removing listener."); + logger.warn( + REGISTRY_FAILED_NOTIFY_EVENT, + "consumer is offline", + "", + "Notify to consumer error, removing listener."); // remove listener if consumer is offline iterator.remove(); @@ -201,36 +213,39 @@ public class ReflectionBasedServiceDiscovery extends AbstractServiceDiscovery { // refer from MetadataUtils, this proxy is different from the one used to refer exportedURL MetadataService metadataService = getMetadataServiceProxy(serviceInstance); - String consumerId = ScopeModelUtil.getApplicationModel(registryURL.getScopeModel()).getApplicationName() + NetUtils.getLocalHost(); - String metadata = metadataService.getAndListenInstanceMetadata( - consumerId, metadataString -> { - if (logger.isDebugEnabled()) { - logger.debug("Receive callback: " + metadataString + serviceInstance); - } - if (StringUtils.isEmpty(metadataString)) { - // provider is shutdown - metadataMap.remove(hostId); - } else { - metadataMap.put(hostId, metadataString); - } - }); + String consumerId = ScopeModelUtil.getApplicationModel(registryURL.getScopeModel()) + .getApplicationName() + + NetUtils.getLocalHost(); + String metadata = metadataService.getAndListenInstanceMetadata(consumerId, metadataString -> { + if (logger.isDebugEnabled()) { + logger.debug("Receive callback: " + metadataString + serviceInstance); + } + if (StringUtils.isEmpty(metadataString)) { + // provider is shutdown + metadataMap.remove(hostId); + } else { + metadataMap.put(hostId, metadataString); + } + }); metadataMap.put(hostId, metadata); serviceInstance.setMetadata(JsonUtils.toJavaObject(metadata, Map.class)); } } - public final void notifyListener(String serviceName, ServiceInstancesChangedListener listener, List instances) { + public final void notifyListener( + String serviceName, ServiceInstancesChangedListener listener, List instances) { String serviceInstanceRevision = RevisionResolver.calRevision(JsonUtils.toJson(instances)); boolean changed = !serviceInstanceRevision.equalsIgnoreCase( - serviceInstanceRevisionMap.put(serviceName, serviceInstanceRevision)); + serviceInstanceRevisionMap.put(serviceName, serviceInstanceRevision)); if (logger.isDebugEnabled()) { - logger.debug("Service changed event received (possibly because of DNS polling). " + - "Service Instance changed: " + changed + " Service Name: " + serviceName); + logger.debug("Service changed event received (possibly because of DNS polling). " + + "Service Instance changed: " + changed + " Service Name: " + serviceName); } if (changed) { - List oldServiceInstances = cachedServiceInstances.getOrDefault(serviceName, new LinkedList<>()); + List oldServiceInstances = + cachedServiceInstances.getOrDefault(serviceName, new LinkedList<>()); // remove expired invoker Set allServiceInstances = new HashSet<>(oldServiceInstances.size() + instances.size()); @@ -257,12 +272,14 @@ public class ReflectionBasedServiceDiscovery extends AbstractServiceDiscovery { } private String computeKey(ServiceInstance serviceInstance) { - return serviceInstance.getServiceName() + "##" + serviceInstance.getAddress() + "##" + - ServiceInstanceMetadataUtils.getExportedServicesRevision(serviceInstance); + return serviceInstance.getServiceName() + "##" + serviceInstance.getAddress() + "##" + + ServiceInstanceMetadataUtils.getExportedServicesRevision(serviceInstance); } private synchronized MetadataService getMetadataServiceProxy(ServiceInstance instance) { - return ConcurrentHashMapUtils.computeIfAbsent(metadataServiceProxies, computeKey(instance), k -> MetadataUtils.referProxy(instance).getProxy()); + return ConcurrentHashMapUtils.computeIfAbsent( + metadataServiceProxies, computeKey(instance), k -> MetadataUtils.referProxy(instance) + .getProxy()); } private synchronized void destroyMetadataServiceProxy(ServiceInstance instance) { diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/RegistryClusterIdentifier.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/RegistryClusterIdentifier.java index f6132eac05..7cffb2dd97 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/RegistryClusterIdentifier.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/RegistryClusterIdentifier.java @@ -30,8 +30,8 @@ public interface RegistryClusterIdentifier { String consumerKey(URL url); static RegistryClusterIdentifier getExtension(URL url) { - ExtensionLoader loader - = ScopeModelUtil.getExtensionLoader(RegistryClusterIdentifier.class, url.getScopeModel()); + ExtensionLoader loader = + ScopeModelUtil.getExtensionLoader(RegistryClusterIdentifier.class, url.getScopeModel()); return loader.getExtension(url.getParameter(REGISTRY_CLUSTER_TYPE_KEY, "default")); } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscovery.java index 9f9cc984d5..a891121ea7 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscovery.java @@ -16,9 +16,6 @@ */ package org.apache.dubbo.registry.client; -import java.util.List; -import java.util.Set; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.lang.Prioritized; import org.apache.dubbo.common.utils.CollectionUtils; @@ -26,6 +23,9 @@ import org.apache.dubbo.metadata.MetadataInfo; import org.apache.dubbo.registry.RegistryService; import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; +import java.util.List; +import java.util.Set; + import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_DELAY_NOTIFICATION_KEY; /** @@ -49,8 +49,7 @@ public interface ServiceDiscovery extends RegistryService, Prioritized { List getInstances(String serviceName) throws NullPointerException; default void addServiceInstancesChangedListener(ServiceInstancesChangedListener listener) - throws NullPointerException, IllegalArgumentException { - } + throws NullPointerException, IllegalArgumentException {} /** * unsubscribe to instance change event. @@ -59,8 +58,7 @@ public interface ServiceDiscovery extends RegistryService, Prioritized { * @throws IllegalArgumentException */ default void removeServiceInstancesChangedListener(ServiceInstancesChangedListener listener) - throws IllegalArgumentException { - } + throws IllegalArgumentException {} default ServiceInstancesChangedListener createListener(Set serviceNames) { return new ServiceInstancesChangedListener(serviceNames, this); @@ -107,7 +105,6 @@ public interface ServiceDiscovery extends RegistryService, Prioritized { * * @return The description. */ - @Override String toString(); } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryFactory.java index 21680951e8..d02c902d02 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryFactory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryFactory.java @@ -47,7 +47,8 @@ public interface ServiceDiscoveryFactory { */ static ServiceDiscoveryFactory getExtension(URL registryURL) { String protocol = registryURL.getProtocol(); - ExtensionLoader loader = registryURL.getOrDefaultApplicationModel().getExtensionLoader(ServiceDiscoveryFactory.class); + ExtensionLoader loader = + registryURL.getOrDefaultApplicationModel().getExtensionLoader(ServiceDiscoveryFactory.class); return loader.getOrDefaultExtension(protocol); } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistry.java index cbc5d41088..b86afee87d 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistry.java @@ -92,12 +92,14 @@ public class ServiceDiscoveryRegistry extends FailbackRegistry { public ServiceDiscoveryRegistry(URL registryURL, ApplicationModel applicationModel) { super(registryURL); this.serviceDiscovery = createServiceDiscovery(registryURL); - this.serviceNameMapping = (AbstractServiceNameMapping) ServiceNameMapping.getDefaultExtension(registryURL.getScopeModel()); + this.serviceNameMapping = + (AbstractServiceNameMapping) ServiceNameMapping.getDefaultExtension(registryURL.getScopeModel()); super.applicationModel = applicationModel; } // Currently, for test purpose - protected ServiceDiscoveryRegistry(URL registryURL, ServiceDiscovery serviceDiscovery, ServiceNameMapping serviceNameMapping) { + protected ServiceDiscoveryRegistry( + URL registryURL, ServiceDiscovery serviceDiscovery, ServiceNameMapping serviceNameMapping) { super(registryURL); this.serviceDiscovery = serviceDiscovery; this.serviceNameMapping = (AbstractServiceNameMapping) serviceNameMapping; @@ -114,8 +116,9 @@ public class ServiceDiscoveryRegistry extends FailbackRegistry { * @return non-null */ protected ServiceDiscovery createServiceDiscovery(URL registryURL) { - return getServiceDiscovery(registryURL.addParameter(INTERFACE_KEY, ServiceDiscovery.class.getName()) - .removeParameter(REGISTRY_TYPE_KEY)); + return getServiceDiscovery(registryURL + .addParameter(INTERFACE_KEY, ServiceDiscovery.class.getName()) + .removeParameter(REGISTRY_TYPE_KEY)); } /** @@ -142,7 +145,8 @@ public class ServiceDiscoveryRegistry extends FailbackRegistry { } if (!acceptable(providerURL)) { - logger.info("URL " + providerURL + " will not be registered to Registry. Registry " + this.getUrl() + " does not accept service of this protocol type."); + logger.info("URL " + providerURL + " will not be registered to Registry. Registry " + this.getUrl() + + " does not accept service of this protocol type."); return false; } @@ -201,7 +205,6 @@ public class ServiceDiscoveryRegistry extends FailbackRegistry { String key = ServiceNameMapping.buildMappingKey(url); - if (mappingByUrl == null) { Lock mappingLock = serviceNameMapping.getMappingLock(key); try { @@ -211,18 +214,27 @@ public class ServiceDiscoveryRegistry extends FailbackRegistry { MappingListener mappingListener = new DefaultMappingListener(url, mappingByUrl, listener); mappingByUrl = serviceNameMapping.getAndListen(this.getUrl(), url, mappingListener); synchronized (mappingListeners) { - mappingListeners.computeIfAbsent(url.getProtocolServiceKey(), (k) -> new ConcurrentHashSet<>()) - .add(mappingListener); + mappingListeners + .computeIfAbsent(url.getProtocolServiceKey(), (k) -> new ConcurrentHashSet<>()) + .add(mappingListener); } } catch (Exception e) { - logger.warn(INTERNAL_ERROR, "", "", "Cannot find app mapping for service " + url.getServiceInterface() + ", will not migrate.", e); + logger.warn( + INTERNAL_ERROR, + "", + "", + "Cannot find app mapping for service " + url.getServiceInterface() + ", will not migrate.", + e); } if (CollectionUtils.isEmpty(mappingByUrl)) { - logger.info("No interface-apps mapping found in local cache, stop subscribing, will automatically wait for mapping listener callback: " + url); -// if (check) { -// throw new IllegalStateException("Should has at least one way to know which services this interface belongs to, subscription url: " + url); -// } + logger.info( + "No interface-apps mapping found in local cache, stop subscribing, will automatically wait for mapping listener callback: " + + url); + // if (check) { + // throw new IllegalStateException("Should has at least one way to know which + // services this interface belongs to, subscription url: " + url); + // } return; } } finally { @@ -260,10 +272,9 @@ public class ServiceDiscoveryRegistry extends FailbackRegistry { Set keyedListeners = mappingListeners.get(protocolServiceKey); if (keyedListeners != null) { List matched = keyedListeners.stream() - .filter(mappingListener -> - mappingListener instanceof DefaultMappingListener - && (Objects.equals(((DefaultMappingListener) mappingListener).getListener(), listener))) - .collect(Collectors.toList()); + .filter(mappingListener -> mappingListener instanceof DefaultMappingListener + && (Objects.equals(((DefaultMappingListener) mappingListener).getListener(), listener))) + .collect(Collectors.toList()); for (MappingListener mappingListener : matched) { serviceNameMapping.stopListen(url, mappingListener); keyedListeners.remove(mappingListener); @@ -300,7 +311,7 @@ public class ServiceDiscoveryRegistry extends FailbackRegistry { @Override public boolean isAvailable() { - //serviceDiscovery isAvailable has a default method, which can be used as a reference when implementing + // serviceDiscovery isAvailable has a default method, which can be used as a reference when implementing return serviceDiscovery.isAvailable(); } @@ -327,7 +338,8 @@ public class ServiceDiscoveryRegistry extends FailbackRegistry { serviceNames = toTreeSet(serviceNames); String serviceNamesKey = toStringKeys(serviceNames); String serviceKey = url.getServiceKey(); - logger.info(String.format("Trying to subscribe from apps %s for service key %s, ", serviceNamesKey, serviceKey)); + logger.info( + String.format("Trying to subscribe from apps %s for service key %s, ", serviceNamesKey, serviceKey)); // register ServiceInstancesChangedListener Lock appSubscriptionLock = getAppSubscription(serviceNamesKey); @@ -339,7 +351,8 @@ public class ServiceDiscoveryRegistry extends FailbackRegistry { for (String serviceName : serviceNames) { List serviceInstances = serviceDiscovery.getInstances(serviceName); if (CollectionUtils.isNotEmpty(serviceInstances)) { - serviceInstancesChangedListener.onEvent(new ServiceInstancesChangedEvent(serviceName, serviceInstances)); + serviceInstancesChangedListener.onEvent( + new ServiceInstancesChangedEvent(serviceName, serviceInstances)); } } serviceListeners.put(serviceNamesKey, serviceInstancesChangedListener); @@ -350,14 +363,16 @@ public class ServiceDiscoveryRegistry extends FailbackRegistry { serviceInstancesChangedListener.addListenerAndNotify(url, listener); ServiceInstancesChangedListener finalServiceInstancesChangedListener = serviceInstancesChangedListener; - String serviceDiscoveryName = url.getParameter(RegistryConstants.REGISTRY_CLUSTER_KEY, url.getProtocol()); + String serviceDiscoveryName = + url.getParameter(RegistryConstants.REGISTRY_CLUSTER_KEY, url.getProtocol()); - MetricsEventBus.post(RegistryEvent.toSsEvent(url.getApplicationModel(), serviceKey, Collections.singletonList(serviceDiscoveryName)), - () -> { - serviceDiscovery.addServiceInstancesChangedListener(finalServiceInstancesChangedListener); - return null; - } - ); + MetricsEventBus.post( + RegistryEvent.toSsEvent( + url.getApplicationModel(), serviceKey, Collections.singletonList(serviceDiscoveryName)), + () -> { + serviceDiscovery.addServiceInstancesChangedListener(finalServiceInstancesChangedListener); + return null; + }); } else { logger.info(String.format("Listener of %s has been destroyed by another thread.", serviceNamesKey)); serviceListeners.remove(serviceNamesKey); @@ -399,7 +414,11 @@ public class ServiceDiscoveryRegistry extends FailbackRegistry { logger.info("Received mapping notification from meta server, " + event); if (stopped) { - logger.warn(INTERNAL_ERROR, "", "", "Listener has been stopped, ignore mapping notification, check why listener is not removed."); + logger.warn( + INTERNAL_ERROR, + "", + "", + "Listener has been stopped, ignore mapping notification, check why listener is not removed."); return; } Set newApps = event.getApps(); @@ -409,7 +428,8 @@ public class ServiceDiscoveryRegistry extends FailbackRegistry { return; } - logger.info("Mapping of service " + event.getServiceKey() + "changed from " + tempOldApps + " to " + newApps); + logger.info( + "Mapping of service " + event.getServiceKey() + "changed from " + tempOldApps + " to " + newApps); Lock mappingLock = serviceNameMapping.getMappingLock(event.getServiceKey()); try { @@ -425,7 +445,8 @@ public class ServiceDiscoveryRegistry extends FailbackRegistry { if (!tempOldApps.contains(newAppName)) { serviceNameMapping.removeCachedMapping(ServiceNameMapping.buildMappingKey(url)); serviceNameMapping.putCachedMapping(ServiceNameMapping.buildMappingKey(url), newApps); - // old instance listener related to old app list that needs to be destroyed after subscribe refresh. + // old instance listener related to old app list that needs to be destroyed after subscribe + // refresh. ServiceInstancesChangedListener oldListener = listener.getServiceListener(); if (oldListener != null) { String appKey = toStringKeys(toTreeSet(tempOldApps)); diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryDirectory.java index fe0d1be634..4304cf2a27 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryDirectory.java @@ -87,13 +87,15 @@ import static org.apache.dubbo.registry.Constants.CONFIGURATORS_SUFFIX; import static org.apache.dubbo.rpc.model.ScopeModelUtil.getModuleModel; public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ServiceDiscoveryRegistryDirectory.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ServiceDiscoveryRegistryDirectory.class); /** * instance address to invoker mapping. * The initial value is null and the midway may be assigned to null, please use the local variable reference */ private volatile Map> urlInvokerMap; + private volatile ReferenceConfigurationListener referenceConfigurationListener; private volatile boolean enableConfigurationListen = true; private volatile List originalUrls = null; @@ -107,12 +109,15 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { super(serviceType, url); moduleModel = getModuleModel(url.getScopeModel()); - Set providerFirstParams = url.getOrDefaultApplicationModel().getExtensionLoader(ProviderFirstParams.class).getSupportedExtensionInstances(); + Set providerFirstParams = url.getOrDefaultApplicationModel() + .getExtensionLoader(ProviderFirstParams.class) + .getSupportedExtensionInstances(); if (CollectionUtils.isEmpty(providerFirstParams)) { this.providerFirstParams = null; } else { if (providerFirstParams.size() == 1) { - this.providerFirstParams = Collections.unmodifiableSet(providerFirstParams.iterator().next().params()); + this.providerFirstParams = Collections.unmodifiableSet( + providerFirstParams.iterator().next().params()); } else { Set params = new HashSet<>(); for (ProviderFirstParams paramsFilter : providerFirstParams) { @@ -126,13 +131,19 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { } String protocol = consumerUrl.getParameter(PROTOCOL_KEY, consumerUrl.getProtocol()); - consumerProtocolServiceKey = new ProtocolServiceKey(consumerUrl.getServiceInterface(), consumerUrl.getVersion(), consumerUrl.getGroup(), - !CommonConstants.CONSUMER.equals(protocol) ? protocol : null); + consumerProtocolServiceKey = new ProtocolServiceKey( + consumerUrl.getServiceInterface(), + consumerUrl.getVersion(), + consumerUrl.getGroup(), + !CommonConstants.CONSUMER.equals(protocol) ? protocol : null); } @Override public void subscribe(URL url) { - if (moduleModel.modelEnvironment().getConfiguration().convert(Boolean.class, Constants.ENABLE_CONFIGURATION_LISTEN, true)) { + if (moduleModel + .modelEnvironment() + .getConfiguration() + .convert(Boolean.class, Constants.ENABLE_CONFIGURATION_LISTEN, true)) { enableConfigurationListen = true; getConsumerConfigurationListener(moduleModel).addNotifyListener(this); referenceConfigurationListener = new ReferenceConfigurationListener(this.moduleModel, this, url); @@ -143,15 +154,20 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { } private ConsumerConfigurationListener getConsumerConfigurationListener(ModuleModel moduleModel) { - return moduleModel.getBeanFactory().getOrRegisterBean(ConsumerConfigurationListener.class, - type -> new ConsumerConfigurationListener(moduleModel)); + return moduleModel + .getBeanFactory() + .getOrRegisterBean( + ConsumerConfigurationListener.class, type -> new ConsumerConfigurationListener(moduleModel)); } @Override public void unSubscribe(URL url) { super.unSubscribe(url); this.originalUrls = null; - if (moduleModel.modelEnvironment().getConfiguration().convert(Boolean.class, Constants.ENABLE_CONFIGURATION_LISTEN, true)) { + if (moduleModel + .modelEnvironment() + .getConfiguration() + .convert(Boolean.class, Constants.ENABLE_CONFIGURATION_LISTEN, true)) { getConsumerConfigurationListener(moduleModel).removeNotifyListener(this); referenceConfigurationListener.stop(); } @@ -160,7 +176,10 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { @Override public void destroy() { super.destroy(); - if (moduleModel.modelEnvironment().getConfiguration().convert(Boolean.class, Constants.ENABLE_CONFIGURATION_LISTEN, true)) { + if (moduleModel + .modelEnvironment() + .getConfiguration() + .convert(Boolean.class, Constants.ENABLE_CONFIGURATION_LISTEN, true)) { getConsumerConfigurationListener(moduleModel).removeNotifyListener(this); referenceConfigurationListener.stop(); } @@ -168,7 +187,8 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { @Override public void buildRouterChain(URL url) { - this.setRouterChain(RouterChain.buildChain(getInterface(), url.addParameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE))); + this.setRouterChain( + RouterChain.buildChain(getInterface(), url.addParameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE))); } @Override @@ -180,8 +200,10 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { RpcServiceContext.getServiceContext().setConsumerUrl(getConsumerUrl()); // 3.x added for extend URL address - ExtensionLoader addressListenerExtensionLoader = getUrl().getOrDefaultModuleModel().getExtensionLoader(AddressListener.class); - List supportedListeners = addressListenerExtensionLoader.getActivateExtension(getUrl(), (String[]) null); + ExtensionLoader addressListenerExtensionLoader = + getUrl().getOrDefaultModuleModel().getExtensionLoader(AddressListener.class); + List supportedListeners = + addressListenerExtensionLoader.getActivateExtension(getUrl(), (String[]) null); if (supportedListeners != null && !supportedListeners.isEmpty()) { for (AddressListener addressListener : supportedListeners) { instanceUrls = addressListener.notify(instanceUrls, getConsumerUrl(), this); @@ -199,10 +221,10 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { refreshInvoker(instanceUrls); } - protected URL overrideDirectoryWithConfigurator(URL url) { // override url with configurator from "app-name.configurators" - url = overrideWithConfigurators(getConsumerConfigurationListener(moduleModel).getConfigurators(), url); + url = overrideWithConfigurators( + getConsumerConfigurationListener(moduleModel).getConfigurators(), url); // override url with configurator from configurators from "service-name.configurators" if (referenceConfigurationListener != null) { @@ -221,18 +243,19 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { String appName = interfaceAddressURL.getApplication(); String side = interfaceAddressURL.getSide(); overriddenURL = URLBuilder.from(interfaceAddressURL) - .clearParameters() - .addParameter(APPLICATION_KEY, appName) - .addParameter(SIDE_KEY, side).build(); + .clearParameters() + .addParameter(APPLICATION_KEY, appName) + .addParameter(SIDE_KEY, side) + .build(); } for (Configurator configurator : configurators) { overriddenURL = configurator.configure(overriddenURL); } url = new DubboServiceAddressURL( - interfaceAddressURL.getUrlAddress(), - interfaceAddressURL.getUrlParam(), - interfaceAddressURL.getConsumerURL(), - (ServiceConfigURL) overriddenURL); + interfaceAddressURL.getUrlAddress(), + interfaceAddressURL.getUrlParam(), + interfaceAddressURL.getConsumerURL(), + (ServiceConfigURL) overriddenURL); } else { for (Configurator configurator : configurators) { url = configurator.configure(url); @@ -244,7 +267,8 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { protected InstanceAddressURL overrideWithConfigurator(InstanceAddressURL providerUrl) { // override url with configurator from "app-name.configurators" - providerUrl = overrideWithConfigurators(getConsumerConfigurationListener(moduleModel).getConfigurators(), providerUrl); + providerUrl = overrideWithConfigurators( + getConsumerConfigurationListener(moduleModel).getConfigurators(), providerUrl); // override url with configurator from configurators from "service-name.configurators" if (referenceConfigurationListener != null) { @@ -260,10 +284,12 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { OverrideInstanceAddressURL overrideInstanceAddressURL = new OverrideInstanceAddressURL(url); if (overrideQueryMap != null) { // override app-level configs - overrideInstanceAddressURL = (OverrideInstanceAddressURL) overrideInstanceAddressURL.addParameters(overrideQueryMap); + overrideInstanceAddressURL = + (OverrideInstanceAddressURL) overrideInstanceAddressURL.addParameters(overrideQueryMap); } for (Configurator configurator : configurators) { - overrideInstanceAddressURL = (OverrideInstanceAddressURL) configurator.configure(overrideInstanceAddressURL); + overrideInstanceAddressURL = + (OverrideInstanceAddressURL) configurator.configure(overrideInstanceAddressURL); } return overrideInstanceAddressURL; } @@ -282,8 +308,10 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { */ @Override public boolean isNotificationReceived() { - return serviceListener == null || serviceListener.isDestroyed() - || serviceListener.getAllInstances().size() == serviceListener.getServiceNames().size(); + return serviceListener == null + || serviceListener.isDestroyed() + || serviceListener.getAllInstances().size() + == serviceListener.getServiceNames().size(); } private void refreshInvoker(List invokerUrls) { @@ -291,36 +319,58 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { this.originalUrls = invokerUrls; if (invokerUrls.size() == 1 && EMPTY_PROTOCOL.equals(invokerUrls.get(0).getProtocol())) { - logger.warn(PROTOCOL_UNSUPPORTED, "", "", String.format("Received url with EMPTY protocol from registry %s, will clear all available addresses.", this)); - refreshRouter(BitList.emptyList(), () -> - this.forbidden = true // Forbid to access - ); + logger.warn( + PROTOCOL_UNSUPPORTED, + "", + "", + String.format( + "Received url with EMPTY protocol from registry %s, will clear all available addresses.", + this)); + refreshRouter( + BitList.emptyList(), () -> this.forbidden = true // Forbid to access + ); destroyAllInvokers(); // Close all invokers } else { this.forbidden = false; // Allow accessing if (CollectionUtils.isEmpty(invokerUrls)) { - logger.warn(PROTOCOL_UNSUPPORTED, "", "", String.format("Received empty url list from registry %s, will ignore for protection purpose.", this)); + logger.warn( + PROTOCOL_UNSUPPORTED, + "", + "", + String.format( + "Received empty url list from registry %s, will ignore for protection purpose.", this)); return; } - // use local reference to avoid NPE as this.urlInvokerMap will be set null concurrently at destroyAllInvokers(). + // use local reference to avoid NPE as this.urlInvokerMap will be set null concurrently at + // destroyAllInvokers(). Map> localUrlInvokerMap = this.urlInvokerMap; // can't use local reference as oldUrlInvokerMap's mappings might be removed directly at toInvokers(). Map> oldUrlInvokerMap = null; if (localUrlInvokerMap != null) { - // the initial capacity should be set greater than the maximum number of entries divided by the load factor to avoid resizing. - oldUrlInvokerMap = new LinkedHashMap<>(Math.round(1 + localUrlInvokerMap.size() / DEFAULT_HASHMAP_LOAD_FACTOR)); + // the initial capacity should be set greater than the maximum number of entries divided by the load + // factor to avoid resizing. + oldUrlInvokerMap = + new LinkedHashMap<>(Math.round(1 + localUrlInvokerMap.size() / DEFAULT_HASHMAP_LOAD_FACTOR)); localUrlInvokerMap.forEach(oldUrlInvokerMap::put); } - Map> newUrlInvokerMap = toInvokers(oldUrlInvokerMap, invokerUrls);// Translate url list to Invoker map + Map> newUrlInvokerMap = + toInvokers(oldUrlInvokerMap, invokerUrls); // Translate url list to Invoker map logger.info(String.format("Refreshed invoker size %s from registry %s", newUrlInvokerMap.size(), this)); if (CollectionUtils.isEmptyMap(newUrlInvokerMap)) { - logger.error(PROTOCOL_UNSUPPORTED, "", "", "Unsupported protocol.", new IllegalStateException(String.format("Cannot create invokers from url address list (total %s)", invokerUrls.size()))); + logger.error( + PROTOCOL_UNSUPPORTED, + "", + "", + "Unsupported protocol.", + new IllegalStateException(String.format( + "Cannot create invokers from url address list (total %s)", invokerUrls.size()))); return; } List> newInvokers = Collections.unmodifiableList(new ArrayList<>(newUrlInvokerMap.values())); - BitList> finalInvokers = multiGroup ? new BitList<>(toMergeInvokerList(newInvokers)) : new BitList<>(newInvokers); + BitList> finalInvokers = + multiGroup ? new BitList<>(toMergeInvokerList(newInvokers)) : new BitList<>(newInvokers); // pre-route and build cache refreshRouter(finalInvokers.clone(), () -> this.setInvokers(finalInvokers)); this.urlInvokerMap = newUrlInvokerMap; @@ -337,13 +387,13 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { // notify invokers refreshed this.invokersChanged(); - logger.info("Received invokers changed event from registry. " + - "Registry type: instance. " + - "Service Key: " + getConsumerUrl().getServiceKey() + ". " + - "Urls Size : " + invokerUrls.size() + ". " + - "Invokers Size : " + getInvokers().size() + ". " + - "Available Size: " + getValidInvokers().size() + ". " + - "Available Invokers : " + joinValidInvokerAddresses()); + logger.info("Received invokers changed event from registry. " + "Registry type: instance. " + + "Service Key: " + + getConsumerUrl().getServiceKey() + ". " + "Urls Size : " + + invokerUrls.size() + ". " + "Invokers Size : " + + getInvokers().size() + ". " + "Available Size: " + + getValidInvokers().size() + ". " + "Available Invokers : " + + joinValidInvokerAddresses()); } /** @@ -354,8 +404,10 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { * @param urls * @return invokers */ - private Map> toInvokers(Map> oldUrlInvokerMap, List urls) { - Map> newUrlInvokerMap = new ConcurrentHashMap<>(urls == null ? 1 : (int) (urls.size() / 0.75f + 1)); + private Map> toInvokers( + Map> oldUrlInvokerMap, List urls) { + Map> newUrlInvokerMap = + new ConcurrentHashMap<>(urls == null ? 1 : (int) (urls.size() / 0.75f + 1)); if (urls == null || urls.isEmpty()) { return newUrlInvokerMap; } @@ -365,15 +417,24 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { if (EMPTY_PROTOCOL.equals(instanceAddressURL.getProtocol())) { continue; } - if (!getUrl().getOrDefaultFrameworkModel().getExtensionLoader(Protocol.class).hasExtension(instanceAddressURL.getProtocol())) { + if (!getUrl().getOrDefaultFrameworkModel() + .getExtensionLoader(Protocol.class) + .hasExtension(instanceAddressURL.getProtocol())) { // 4-1 - Unsupported protocol - logger.error(PROTOCOL_UNSUPPORTED, "protocol extension does not installed", "", "Unsupported protocol.", - new IllegalStateException("Unsupported protocol " + instanceAddressURL.getProtocol() + - " in notified url: " + instanceAddressURL + " from registry " + getUrl().getAddress() + - " to consumer " + NetUtils.getLocalHost() + ", supported protocol: " + - getUrl().getOrDefaultFrameworkModel().getExtensionLoader(Protocol.class).getSupportedExtensions())); + logger.error( + PROTOCOL_UNSUPPORTED, + "protocol extension does not installed", + "", + "Unsupported protocol.", + new IllegalStateException("Unsupported protocol " + instanceAddressURL.getProtocol() + + " in notified url: " + + instanceAddressURL + " from registry " + getUrl().getAddress() + " to consumer " + + NetUtils.getLocalHost() + ", supported protocol: " + + getUrl().getOrDefaultFrameworkModel() + .getExtensionLoader(Protocol.class) + .getSupportedExtensions())); continue; } @@ -387,29 +448,38 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { // filter all the service available (version wildcard, group wildcard, protocol wildcard) int port = instanceAddressURL.getPort(); - List matchedProtocolServiceKeys = instanceAddressURL.getMetadataInfo() - .getMatchedServiceInfos(consumerProtocolServiceKey) - .stream() - .filter(serviceInfo -> serviceInfo.getPort() <= 0 || serviceInfo.getPort() == port) - // special filter for extra protocols. - .filter(serviceInfo -> { - if (StringUtils.isNotEmpty(consumerProtocolServiceKey.getProtocol())) {// if consumer side protocol is specified, use all the protocols we got in hand now directly - return true; - } else {// if consumer side protocol is not specified, remove all extra protocols - return StringUtils.isEmpty(serviceInfo.getParameter(IS_EXTRA)); - } - }) - .map(MetadataInfo.ServiceInfo::getProtocolServiceKey) - .collect(Collectors.toList()); + List matchedProtocolServiceKeys = + instanceAddressURL.getMetadataInfo().getMatchedServiceInfos(consumerProtocolServiceKey).stream() + .filter(serviceInfo -> serviceInfo.getPort() <= 0 || serviceInfo.getPort() == port) + // special filter for extra protocols. + .filter(serviceInfo -> { + if (StringUtils.isNotEmpty( + consumerProtocolServiceKey + .getProtocol())) { // if consumer side protocol is specified, use all + // the protocols we got in hand now directly + return true; + } else { // if consumer side protocol is not specified, remove all extra protocols + return StringUtils.isEmpty(serviceInfo.getParameter(IS_EXTRA)); + } + }) + .map(MetadataInfo.ServiceInfo::getProtocolServiceKey) + .collect(Collectors.toList()); // see org.apache.dubbo.common.ProtocolServiceKey.isSameWith // check if needed to override the consumer url - boolean shouldWrap = matchedProtocolServiceKeys.size() != 1 || !consumerProtocolServiceKey.isSameWith(matchedProtocolServiceKeys.get(0)); + boolean shouldWrap = matchedProtocolServiceKeys.size() != 1 + || !consumerProtocolServiceKey.isSameWith(matchedProtocolServiceKeys.get(0)); for (ProtocolServiceKey matchedProtocolServiceKey : matchedProtocolServiceKeys) { - ProtocolServiceKeyWithAddress protocolServiceKeyWithAddress = new ProtocolServiceKeyWithAddress(matchedProtocolServiceKey, instanceAddressURL.getAddress()); - Invoker invoker = oldUrlInvokerMap == null ? null : oldUrlInvokerMap.get(protocolServiceKeyWithAddress); - if (invoker == null || urlChanged(invoker, instanceAddressURL, matchedProtocolServiceKey)) { // Not in the cache, refer again + ProtocolServiceKeyWithAddress protocolServiceKeyWithAddress = + new ProtocolServiceKeyWithAddress(matchedProtocolServiceKey, instanceAddressURL.getAddress()); + Invoker invoker = + oldUrlInvokerMap == null ? null : oldUrlInvokerMap.get(protocolServiceKeyWithAddress); + if (invoker == null + || urlChanged( + invoker, + instanceAddressURL, + matchedProtocolServiceKey)) { // Not in the cache, refer again try { boolean enabled; if (instanceAddressURL.hasParameter(DISABLED_KEY)) { @@ -419,18 +489,28 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { } if (enabled) { if (shouldWrap) { - URL newConsumerUrl = ConcurrentHashMapUtils.computeIfAbsent(customizedConsumerUrlMap, matchedProtocolServiceKey, - k -> consumerUrl.setProtocol(k.getProtocol()) - .addParameter(CommonConstants.GROUP_KEY, k.getGroup()) - .addParameter(CommonConstants.VERSION_KEY, k.getVersion())); + URL newConsumerUrl = ConcurrentHashMapUtils.computeIfAbsent( + customizedConsumerUrlMap, matchedProtocolServiceKey, k -> consumerUrl + .setProtocol(k.getProtocol()) + .addParameter(CommonConstants.GROUP_KEY, k.getGroup()) + .addParameter(CommonConstants.VERSION_KEY, k.getVersion())); RpcContext.getServiceContext().setConsumerUrl(newConsumerUrl); - invoker = new InstanceWrappedInvoker<>(protocol.refer(serviceType, instanceAddressURL), newConsumerUrl, matchedProtocolServiceKey); + invoker = new InstanceWrappedInvoker<>( + protocol.refer(serviceType, instanceAddressURL), + newConsumerUrl, + matchedProtocolServiceKey); } else { invoker = protocol.refer(serviceType, instanceAddressURL); } } } catch (Throwable t) { - logger.error(PROTOCOL_FAILED_REFER_INVOKER, "", "", "Failed to refer invoker for interface:" + serviceType + ",url:(" + instanceAddressURL + ")" + t.getMessage(), t); + logger.error( + PROTOCOL_FAILED_REFER_INVOKER, + "", + "", + "Failed to refer invoker for interface:" + serviceType + ",url:(" + instanceAddressURL + + ")" + t.getMessage(), + t); } if (invoker != null) { // Put new invoker in cache newUrlInvokerMap.put(protocolServiceKeyWithAddress, invoker); @@ -456,13 +536,16 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { // sub-class changed return true; } else { - if (!((OverrideInstanceAddressURL) oldURL).getOverrideParams().equals(((OverrideInstanceAddressURL) newURL).getOverrideParams())) { + if (!((OverrideInstanceAddressURL) oldURL) + .getOverrideParams() + .equals(((OverrideInstanceAddressURL) newURL).getOverrideParams())) { return true; } } } - MetadataInfo.ServiceInfo oldServiceInfo = oldURL.getMetadataInfo().getValidServiceInfo(protocolServiceKey.toString()); + MetadataInfo.ServiceInfo oldServiceInfo = + oldURL.getMetadataInfo().getValidServiceInfo(protocolServiceKey.toString()); if (null == oldServiceInfo) { return false; } @@ -504,7 +587,12 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { try { invoker.destroy(); } catch (Throwable t) { - logger.warn(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", "Failed to destroy service " + serviceKey + " to provider " + invoker.getUrl(), t); + logger.warn( + PROTOCOL_FAILED_DESTROY_INVOKER, + "", + "", + "Failed to destroy service " + serviceKey + " to provider " + invoker.getUrl(), + t); } } localUrlInvokerMap.clear(); @@ -517,9 +605,11 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { @Override protected Map getDirectoryMeta() { String registryKey = Optional.ofNullable(getRegistry()) - .map(Registry::getUrl) - .map(url -> url.getParameter(RegistryConstants.REGISTRY_CLUSTER_KEY, url.getParameter(RegistryConstants.REGISTRY_KEY, url.getProtocol()))) - .orElse("unknown"); + .map(Registry::getUrl) + .map(url -> url.getParameter( + RegistryConstants.REGISTRY_CLUSTER_KEY, + url.getParameter(RegistryConstants.REGISTRY_KEY, url.getProtocol()))) + .orElse("unknown"); Map metas = new HashMap<>(); metas.put(REGISTRY_KEY, registryKey); metas.put(REGISTER_MODE_KEY, INSTANCE_REGISTER_MODE); @@ -533,7 +623,9 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { * @param oldUrlInvokerMap * @param newUrlInvokerMap */ - private void destroyUnusedInvokers(Map> oldUrlInvokerMap, Map> newUrlInvokerMap) { + private void destroyUnusedInvokers( + Map> oldUrlInvokerMap, + Map> newUrlInvokerMap) { if (newUrlInvokerMap == null || newUrlInvokerMap.size() == 0) { destroyAllInvokers(); return; @@ -552,7 +644,12 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { logger.debug("destroy invoker[" + invoker.getUrl() + "] success. "); } } catch (Exception e) { - logger.warn(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", "destroy invoker[" + invoker.getUrl() + "]failed." + e.getMessage(), e); + logger.warn( + PROTOCOL_FAILED_DESTROY_INVOKER, + "", + "", + "destroy invoker[" + invoker.getUrl() + "]failed." + e.getMessage(), + e); } } } @@ -563,7 +660,8 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { private final ServiceDiscoveryRegistryDirectory directory; private final URL url; - ReferenceConfigurationListener(ModuleModel moduleModel, ServiceDiscoveryRegistryDirectory directory, URL url) { + ReferenceConfigurationListener( + ModuleModel moduleModel, ServiceDiscoveryRegistryDirectory directory, URL url) { super(moduleModel); this.directory = directory; this.url = url; @@ -624,7 +722,11 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { private final String address; public ProtocolServiceKeyWithAddress(ProtocolServiceKey protocolServiceKey, String address) { - super(protocolServiceKey.getInterfaceName(), protocolServiceKey.getVersion(), protocolServiceKey.getGroup(), protocolServiceKey.getProtocol()); + super( + protocolServiceKey.getInterfaceName(), + protocolServiceKey.getVersion(), + protocolServiceKey.getGroup(), + protocolServiceKey.getProtocol()); this.address = address; } @@ -658,7 +760,8 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { private final URL newConsumerUrl; private final ProtocolServiceKey protocolServiceKey; - public InstanceWrappedInvoker(Invoker originInvoker, URL newConsumerUrl, ProtocolServiceKey protocolServiceKey) { + public InstanceWrappedInvoker( + Invoker originInvoker, URL newConsumerUrl, ProtocolServiceKey protocolServiceKey) { this.originInvoker = originInvoker; this.newConsumerUrl = newConsumerUrl; this.protocolServiceKey = protocolServiceKey; @@ -674,11 +777,18 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { // override consumer url with real protocol service key RpcContext.getServiceContext().setConsumerUrl(newConsumerUrl); // recreate invocation due to the protocol service key changed - RpcInvocation copiedInvocation = new RpcInvocation(invocation.getTargetServiceUniqueName(), - invocation.getServiceModel(), invocation.getMethodName(), invocation.getServiceName(), protocolServiceKey.toString(), - invocation.getParameterTypes(), invocation.getArguments(), invocation.getObjectAttachments(), - invocation.getInvoker(), invocation.getAttributes(), - invocation instanceof RpcInvocation ? ((RpcInvocation) invocation).getInvokeMode() : null); + RpcInvocation copiedInvocation = new RpcInvocation( + invocation.getTargetServiceUniqueName(), + invocation.getServiceModel(), + invocation.getMethodName(), + invocation.getServiceName(), + protocolServiceKey.toString(), + invocation.getParameterTypes(), + invocation.getArguments(), + invocation.getObjectAttachments(), + invocation.getInvoker(), + invocation.getAttributes(), + invocation instanceof RpcInvocation ? ((RpcInvocation) invocation).getInvokeMode() : null); copiedInvocation.setObjectAttachment(CommonConstants.GROUP_KEY, protocolServiceKey.getGroup()); copiedInvocation.setObjectAttachment(CommonConstants.VERSION_KEY, protocolServiceKey.getVersion()); return originInvoker.invoke(copiedInvocation); @@ -705,10 +815,12 @@ public class ServiceDiscoveryRegistryDirectory extends DynamicDirectory { @Override public String toString() { - return "ServiceDiscoveryRegistryDirectory(" + - "registry: " + getUrl().getAddress() + - ", subscribed key: " + (serviceListener == null || CollectionUtils.isEmpty(serviceListener.getServiceNames()) - ? getConsumerUrl().getServiceKey() : serviceListener.getServiceNames().toString()) + - ")-" + super.toString(); + return "ServiceDiscoveryRegistryDirectory(" + "registry: " + + getUrl().getAddress() + ", subscribed key: " + + (serviceListener == null || CollectionUtils.isEmpty(serviceListener.getServiceNames()) + ? getConsumerUrl().getServiceKey() + : serviceListener.getServiceNames().toString()) + + ")-" + + super.toString(); } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryFactory.java index def02318b0..477df606ad 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryFactory.java @@ -39,5 +39,4 @@ public class ServiceDiscoveryRegistryFactory extends AbstractRegistryFactory { } return new ServiceDiscoveryRegistry(url, applicationModel); } - } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstance.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstance.java index 9f9aaaa860..6ccd7b281f 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstance.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstance.java @@ -138,5 +138,4 @@ public interface ServiceInstance extends Serializable { void setServiceMetadata(MetadataInfo serviceMetadata); InstanceAddressURL toURL(String protocol); - } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RetryServiceInstancesChangedEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RetryServiceInstancesChangedEvent.java index 9172fafb4b..6275433178 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RetryServiceInstancesChangedEvent.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RetryServiceInstancesChangedEvent.java @@ -26,7 +26,7 @@ public class RetryServiceInstancesChangedEvent extends ServiceInstancesChangedEv private volatile long failureRecordTime; public RetryServiceInstancesChangedEvent(String serviceName) { - super(serviceName, Collections.emptyList());// instance list has been stored by ServiceInstancesChangedListener + super(serviceName, Collections.emptyList()); // instance list has been stored by ServiceInstancesChangedListener this.failureRecordTime = System.currentTimeMillis(); } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancesChangedEvent.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancesChangedEvent.java index 2b6b2e375a..897093089f 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancesChangedEvent.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancesChangedEvent.java @@ -58,12 +58,10 @@ public class ServiceInstancesChangedEvent { return serviceName; } - /** * @return all {@link ServiceInstance service instances} */ public List getServiceInstances() { return serviceInstances; } - } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListener.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListener.java index 61d04072f3..ba5e7ac803 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListener.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListener.java @@ -72,7 +72,8 @@ import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataU */ public class ServiceInstancesChangedListener { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ServiceInstancesChangedListener.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ServiceInstancesChangedListener.class); protected final Set serviceNames; protected final ServiceDiscovery serviceDiscovery; @@ -98,9 +99,17 @@ public class ServiceInstancesChangedListener { this.allInstances = new HashMap<>(); this.serviceUrls = new HashMap<>(); retryPermission = new Semaphore(1); - ApplicationModel applicationModel = ScopeModelUtil.getApplicationModel(serviceDiscovery == null || serviceDiscovery.getUrl() == null ? null : serviceDiscovery.getUrl().getScopeModel()); - this.scheduler = applicationModel.getBeanFactory().getBean(FrameworkExecutorRepository.class).getMetadataRetryExecutor(); - this.serviceInstanceNotificationCustomizers = applicationModel.getExtensionLoader(ServiceInstanceNotificationCustomizer.class).getSupportedExtensionInstances(); + ApplicationModel applicationModel = ScopeModelUtil.getApplicationModel( + serviceDiscovery == null || serviceDiscovery.getUrl() == null + ? null + : serviceDiscovery.getUrl().getScopeModel()); + this.scheduler = applicationModel + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class) + .getMetadataRetryExecutor(); + this.serviceInstanceNotificationCustomizers = applicationModel + .getExtensionLoader(ServiceInstanceNotificationCustomizer.class) + .getSupportedExtensionInstances(); this.applicationModel = applicationModel; } @@ -144,7 +153,8 @@ public class ServiceInstancesChangedListener { } continue; } - List subInstances = revisionToInstances.computeIfAbsent(revision, r -> new LinkedList<>()); + List subInstances = + revisionToInstances.computeIfAbsent(revision, r -> new LinkedList<>()); subInstances.add(instance); } } @@ -155,11 +165,11 @@ public class ServiceInstancesChangedListener { List subInstances = entry.getValue(); MetadataInfo metadata = subInstances.stream() - .map(ServiceInstance::getServiceMetadata) - .filter(Objects::nonNull) - .filter(m -> revision.equals(m.getRevision())) - .findFirst() - .orElseGet(() -> serviceDiscovery.getRemoteMetadata(revision, subInstances)); + .map(ServiceInstance::getServiceMetadata) + .filter(Objects::nonNull) + .filter(m -> revision.equals(m.getRevision())) + .findFirst() + .orElseGet(() -> serviceDiscovery.getRemoteMetadata(revision, subInstances)); parseMetadata(revision, metadata, localServiceToRevisions); // update metadata into each instance, in case new instance created. @@ -172,7 +182,7 @@ public class ServiceInstancesChangedListener { } int emptyNum = hasEmptyMetadata(revisionToInstances); - if (emptyNum != 0) {// retry every 10 seconds + if (emptyNum != 0) { // retry every 10 seconds hasEmptyMetadata = true; if (retryPermission.tryAcquire()) { if (retryFuture != null && !retryFuture.isDone()) { @@ -180,18 +190,29 @@ public class ServiceInstancesChangedListener { retryFuture.cancel(true); } try { - retryFuture = scheduler.schedule(new AddressRefreshRetryTask(retryPermission, event.getServiceName()), 10_000L, TimeUnit.MILLISECONDS); + retryFuture = scheduler.schedule( + new AddressRefreshRetryTask(retryPermission, event.getServiceName()), + 10_000L, + TimeUnit.MILLISECONDS); } catch (Exception e) { - logger.error(INTERNAL_ERROR, "unknown error in registry module", "", "Error submitting async retry task."); + logger.error( + INTERNAL_ERROR, + "unknown error in registry module", + "", + "Error submitting async retry task."); } - logger.warn(INTERNAL_ERROR, "unknown error in registry module", "", "Address refresh try task submitted"); + logger.warn( + INTERNAL_ERROR, "unknown error in registry module", "", "Address refresh try task submitted"); } // return if all metadata is empty, this notification will not take effect. if (emptyNum == revisionToInstances.size()) { // 1-17 - Address refresh failed. - logger.error(REGISTRY_FAILED_REFRESH_ADDRESS, "metadata Server failure", "", - "Address refresh failed because of Metadata Server failure, wait for retry or new address refresh event."); + logger.error( + REGISTRY_FAILED_REFRESH_ADDRESS, + "metadata Server failure", + "", + "Address refresh failed because of Metadata Server failure, wait for retry or new address refresh event."); return; } @@ -204,11 +225,17 @@ public class ServiceInstancesChangedListener { ServiceInfo serviceInfo = entry.getKey(); Set revisions = entry.getValue(); - Map, Object>> portToRevisions = protocolRevisionsToUrls.computeIfAbsent(serviceInfo.getProtocol(), k -> new HashMap<>()); - Map, Object> revisionsToUrls = portToRevisions.computeIfAbsent(serviceInfo.getPort(), k -> new HashMap<>()); - Object urls = revisionsToUrls.computeIfAbsent(revisions, k -> getServiceUrlsCache(revisionToInstances, revisions, serviceInfo.getProtocol(), serviceInfo.getPort())); + Map, Object>> portToRevisions = + protocolRevisionsToUrls.computeIfAbsent(serviceInfo.getProtocol(), k -> new HashMap<>()); + Map, Object> revisionsToUrls = + portToRevisions.computeIfAbsent(serviceInfo.getPort(), k -> new HashMap<>()); + Object urls = revisionsToUrls.computeIfAbsent( + revisions, + k -> getServiceUrlsCache( + revisionToInstances, revisions, serviceInfo.getProtocol(), serviceInfo.getPort())); - List list = newServiceUrls.computeIfAbsent(serviceInfo.getPath(), k -> new LinkedList<>()); + List list = + newServiceUrls.computeIfAbsent(serviceInfo.getPath(), k -> new LinkedList<>()); list.add(new ProtocolServiceKeyWithUrls(serviceInfo.getProtocolServiceKey(), (List) urls)); } @@ -221,10 +248,14 @@ public class ServiceInstancesChangedListener { return; } - Set notifyListeners = this.listeners.computeIfAbsent(url.getServiceKey(), _k -> new ConcurrentHashSet<>()); + Set notifyListeners = + this.listeners.computeIfAbsent(url.getServiceKey(), _k -> new ConcurrentHashSet<>()); String protocol = listener.getConsumerUrl().getParameter(PROTOCOL_KEY, url.getProtocol()); - ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey(url.getServiceInterface(), url.getVersion(), url.getGroup(), - !CommonConstants.CONSUMER.equals(protocol) ? protocol : null); + ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey( + url.getServiceInterface(), + url.getVersion(), + url.getGroup(), + !CommonConstants.CONSUMER.equals(protocol) ? protocol : null); NotifyListenerWithKey listenerWithKey = new NotifyListenerWithKey(protocolServiceKey, listener); notifyListeners.add(listenerWithKey); @@ -232,7 +263,9 @@ public class ServiceInstancesChangedListener { List urls = getAddresses(protocolServiceKey, listener.getConsumerUrl()); if (CollectionUtils.isNotEmpty(urls)) { - logger.info(String.format("Notify serviceKey: %s, listener: %s with %s urls on subscription", protocolServiceKey, listener, urls.size())); + logger.info(String.format( + "Notify serviceKey: %s, listener: %s with %s urls on subscription", + protocolServiceKey, listener, urls.size())); listener.notify(urls); } } @@ -282,9 +315,18 @@ public class ServiceInstancesChangedListener { protected boolean isRetryAndExpired(ServiceInstancesChangedEvent event) { if (event instanceof RetryServiceInstancesChangedEvent) { RetryServiceInstancesChangedEvent retryEvent = (RetryServiceInstancesChangedEvent) event; - logger.warn(INTERNAL_ERROR, "unknown error in registry module", "", "Received address refresh retry event, " + retryEvent.getFailureRecordTime()); + logger.warn( + INTERNAL_ERROR, + "unknown error in registry module", + "", + "Received address refresh retry event, " + retryEvent.getFailureRecordTime()); if (retryEvent.getFailureRecordTime() < lastRefreshTime && !hasEmptyMetadata) { - logger.warn(INTERNAL_ERROR, "unknown error in registry module", "", "Ignore retry event, event time: " + retryEvent.getFailureRecordTime() + ", last refresh time: " + lastRefreshTime); + logger.warn( + INTERNAL_ERROR, + "unknown error in registry module", + "", + "Ignore retry event, event time: " + retryEvent.getFailureRecordTime() + ", last refresh time: " + + lastRefreshTime); return true; } logger.warn(INTERNAL_ERROR, "unknown error in registry module", "", "Retrying address notification..."); @@ -299,7 +341,8 @@ public class ServiceInstancesChangedListener { String appName = event.getServiceName(); List appInstances = event.getServiceInstances(); logger.info("Received instance notification, serviceName: " + appName + ", instances: " + appInstances.size()); - for (ServiceInstanceNotificationCustomizer serviceInstanceNotificationCustomizer : serviceInstanceNotificationCustomizers) { + for (ServiceInstanceNotificationCustomizer serviceInstanceNotificationCustomizer : + serviceInstanceNotificationCustomizers) { serviceInstanceNotificationCustomizer.customize(appInstances); } allInstances.put(appName, appInstances); @@ -320,7 +363,8 @@ public class ServiceInstancesChangedListener { StringBuilder builder = new StringBuilder(); int emptyMetadataNum = 0; for (Map.Entry> entry : revisionToInstances.entrySet()) { - DefaultServiceInstance serviceInstance = (DefaultServiceInstance) entry.getValue().get(0); + DefaultServiceInstance serviceInstance = + (DefaultServiceInstance) entry.getValue().get(0); if (serviceInstance == null || serviceInstance.getServiceMetadata() == MetadataInfo.EMPTY) { emptyMetadataNum++; } @@ -330,7 +374,10 @@ public class ServiceInstancesChangedListener { } if (emptyMetadataNum > 0) { - builder.insert(0, emptyMetadataNum + "/" + revisionToInstances.size() + " revisions failed to get metadata from remote: "); + builder.insert( + 0, + emptyMetadataNum + "/" + revisionToInstances.size() + + " revisions failed to get metadata from remote: "); logger.error(INTERNAL_ERROR, "unknown error in registry module", "", builder.toString()); } else { builder.insert(0, revisionToInstances.size() + " unique working revisions: "); @@ -339,7 +386,8 @@ public class ServiceInstancesChangedListener { return emptyMetadataNum; } - protected Map> parseMetadata(String revision, MetadataInfo metadata, Map> localServiceToRevisions) { + protected Map> parseMetadata( + String revision, MetadataInfo metadata, Map> localServiceToRevisions) { Map serviceInfos = metadata.getServices(); for (Map.Entry entry : serviceInfos.entrySet()) { Set set = localServiceToRevisions.computeIfAbsent(entry.getValue(), _k -> new TreeSet<>()); @@ -349,7 +397,8 @@ public class ServiceInstancesChangedListener { return localServiceToRevisions; } - protected Object getServiceUrlsCache(Map> revisionToInstances, Set revisions, String protocol, int port) { + protected Object getServiceUrlsCache( + Map> revisionToInstances, Set revisions, String protocol, int port) { List urls = new ArrayList<>(); for (String r : revisions) { for (ServiceInstance i : revisionToInstances.get(r)) { @@ -357,7 +406,10 @@ public class ServiceInstancesChangedListener { if (i.getPort() == port) { urls.add(i.toURL(protocol).setScopeModel(i.getApplicationModel())); } else { - urls.add(((DefaultServiceInstance) i).copyFrom(port).toURL(protocol).setScopeModel(i.getApplicationModel())); + urls.add(((DefaultServiceInstance) i) + .copyFrom(port) + .toURL(protocol) + .setScopeModel(i.getApplicationModel())); } continue; } @@ -376,11 +428,13 @@ public class ServiceInstancesChangedListener { } protected List getAddresses(ProtocolServiceKey protocolServiceKey, URL consumerURL) { - List protocolServiceKeyWithUrlsList = serviceUrls.get(protocolServiceKey.getInterfaceName()); + List protocolServiceKeyWithUrlsList = + serviceUrls.get(protocolServiceKey.getInterfaceName()); List urls = new ArrayList<>(); if (protocolServiceKeyWithUrlsList != null) { for (ProtocolServiceKeyWithUrls protocolServiceKeyWithUrls : protocolServiceKeyWithUrlsList) { - if (ProtocolServiceKey.Matcher.isMatch(protocolServiceKey, protocolServiceKeyWithUrls.getProtocolServiceKey())) { + if (ProtocolServiceKey.Matcher.isMatch( + protocolServiceKey, protocolServiceKeyWithUrls.getProtocolServiceKey())) { urls.addAll(protocolServiceKeyWithUrls.getUrls()); } } @@ -398,29 +452,29 @@ public class ServiceInstancesChangedListener { */ protected void notifyAddressChanged() { - MetricsEventBus.post(RegistryEvent.toNotifyEvent(applicationModel), - () -> { - Map lastNumMap = new HashMap<>(); - // 1 different services - listeners.forEach((serviceKey, listenerSet) -> { - // 2 multiple subscription listener of the same service - for (NotifyListenerWithKey listenerWithKey : listenerSet) { - NotifyListener notifyListener = listenerWithKey.getNotifyListener(); - - List urls = toUrlsWithEmpty(getAddresses(listenerWithKey.getProtocolServiceKey(), notifyListener.getConsumerUrl())); - logger.info("Notify service " + listenerWithKey.getProtocolServiceKey() + " with urls " + urls.size()); - notifyListener.notify(urls); - lastNumMap.put(serviceKey, urls.size()); - } - }); - return lastNumMap; - } - ); + MetricsEventBus.post(RegistryEvent.toNotifyEvent(applicationModel), () -> { + Map lastNumMap = new HashMap<>(); + // 1 different services + listeners.forEach((serviceKey, listenerSet) -> { + // 2 multiple subscription listener of the same service + for (NotifyListenerWithKey listenerWithKey : listenerSet) { + NotifyListener notifyListener = listenerWithKey.getNotifyListener(); + List urls = toUrlsWithEmpty( + getAddresses(listenerWithKey.getProtocolServiceKey(), notifyListener.getConsumerUrl())); + logger.info( + "Notify service " + listenerWithKey.getProtocolServiceKey() + " with urls " + urls.size()); + notifyListener.notify(urls); + lastNumMap.put(serviceKey, urls.size()); + } + }); + return lastNumMap; + }); } protected List toUrlsWithEmpty(List urls) { - boolean emptyProtectionEnabled = serviceDiscovery.getUrl().getParameter(ENABLE_EMPTY_PROTECTION_KEY, DEFAULT_ENABLE_EMPTY_PROTECTION); + boolean emptyProtectionEnabled = + serviceDiscovery.getUrl().getParameter(ENABLE_EMPTY_PROTECTION_KEY, DEFAULT_ENABLE_EMPTY_PROTECTION); if (!emptyProtectionEnabled && urls == null) { urls = new ArrayList<>(); } else if (emptyProtectionEnabled && urls == null) { @@ -429,7 +483,9 @@ public class ServiceInstancesChangedListener { if (CollectionUtils.isEmpty(urls) && !emptyProtectionEnabled) { // notice that the service of this.url may not be the same as notify listener. - URL empty = URLBuilder.from(serviceDiscovery.getUrl()).setProtocol(EMPTY_PROTOCOL).build(); + URL empty = URLBuilder.from(serviceDiscovery.getUrl()) + .setProtocol(EMPTY_PROTOCOL) + .build(); urls.add(empty); } return urls; @@ -516,7 +572,8 @@ public class ServiceInstancesChangedListener { return false; } NotifyListenerWithKey that = (NotifyListenerWithKey) o; - return Objects.equals(protocolServiceKey, that.protocolServiceKey) && Objects.equals(notifyListener, that.notifyListener); + return Objects.equals(protocolServiceKey, that.protocolServiceKey) + && Objects.equals(notifyListener, that.notifyListener); } @Override diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceDelegation.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceDelegation.java index b9440f02c5..7069d7a04a 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceDelegation.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceDelegation.java @@ -16,18 +16,6 @@ */ package org.apache.dubbo.registry.client.metadata; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -40,6 +28,18 @@ import org.apache.dubbo.registry.client.ServiceDiscovery; import org.apache.dubbo.registry.support.RegistryManager; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + import static java.util.Collections.emptySortedSet; import static java.util.Collections.unmodifiableSortedSet; import static org.apache.dubbo.common.URL.buildKey; @@ -55,7 +55,8 @@ public class MetadataServiceDelegation implements MetadataService, Disposable { private final ApplicationModel applicationModel; private final RegistryManager registryManager; - private ConcurrentMap instanceMetadataChangedListenerMap = new ConcurrentHashMap<>(); + private ConcurrentMap instanceMetadataChangedListenerMap = + new ConcurrentHashMap<>(); private URL url; // works only for DNS service discovery private String instanceMetadata; @@ -219,8 +220,8 @@ public class MetadataServiceDelegation implements MetadataService, Disposable { return instanceMetadata; } - private SortedSet getServiceURLs(Map> exportedServiceURLs, String serviceKey, - String protocol) { + private SortedSet getServiceURLs( + Map> exportedServiceURLs, String serviceKey, String protocol) { SortedSet serviceURLs = exportedServiceURLs.get(serviceKey); @@ -233,15 +234,12 @@ public class MetadataServiceDelegation implements MetadataService, Disposable { private boolean isAcceptableProtocol(String protocol, URL url) { return protocol == null - || protocol.equals(url.getParameter(PROTOCOL_KEY)) - || protocol.equals(url.getProtocol()); + || protocol.equals(url.getParameter(PROTOCOL_KEY)) + || protocol.equals(url.getProtocol()); } @Override - public void destroy() { - - } - + public void destroy() {} static class URLComparator implements Comparator { diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceNameMapping.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceNameMapping.java index 3da0d20df1..62322d820b 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceNameMapping.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceNameMapping.java @@ -50,7 +50,8 @@ public class MetadataServiceNameMapping extends AbstractServiceNameMapping { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); - private static final List IGNORED_SERVICE_INTERFACES = Collections.singletonList(MetadataService.class.getName()); + private static final List IGNORED_SERVICE_INTERFACES = + Collections.singletonList(MetadataService.class.getName()); private final int casRetryTimes; private final int casRetryWaitTime; @@ -59,13 +60,16 @@ public class MetadataServiceNameMapping extends AbstractServiceNameMapping { public MetadataServiceNameMapping(ApplicationModel applicationModel) { super(applicationModel); metadataReportInstance = applicationModel.getBeanFactory().getBean(MetadataReportInstance.class); - casRetryTimes = ConfigurationUtils.getGlobalConfiguration(applicationModel).getInt(CAS_RETRY_TIMES_KEY, DEFAULT_CAS_RETRY_TIMES); - casRetryWaitTime = ConfigurationUtils.getGlobalConfiguration(applicationModel).getInt(CAS_RETRY_WAIT_TIME_KEY, DEFAULT_CAS_RETRY_WAIT_TIME); + casRetryTimes = ConfigurationUtils.getGlobalConfiguration(applicationModel) + .getInt(CAS_RETRY_TIMES_KEY, DEFAULT_CAS_RETRY_TIMES); + casRetryWaitTime = ConfigurationUtils.getGlobalConfiguration(applicationModel) + .getInt(CAS_RETRY_WAIT_TIME_KEY, DEFAULT_CAS_RETRY_WAIT_TIME); } @Override public boolean hasValidMetadataCenter() { - return !CollectionUtils.isEmpty(applicationModel.getApplicationConfigManager().getMetadataConfigs()); + return !CollectionUtils.isEmpty( + applicationModel.getApplicationConfigManager().getMetadataConfigs()); } /** @@ -73,8 +77,10 @@ public class MetadataServiceNameMapping extends AbstractServiceNameMapping { */ @Override public boolean map(URL url) { - if (CollectionUtils.isEmpty(applicationModel.getApplicationConfigManager().getMetadataConfigs())) { - logger.warn(COMMON_PROPERTY_TYPE_MISMATCH, "", "", "No valid metadata config center found for mapping report."); + if (CollectionUtils.isEmpty( + applicationModel.getApplicationConfigManager().getMetadataConfigs())) { + logger.warn( + COMMON_PROPERTY_TYPE_MISMATCH, "", "", "No valid metadata config center found for mapping report."); return false; } String serviceInterface = url.getServiceInterface(); @@ -83,7 +89,8 @@ public class MetadataServiceNameMapping extends AbstractServiceNameMapping { } boolean result = true; - for (Map.Entry entry : metadataReportInstance.getMetadataReports(true).entrySet()) { + for (Map.Entry entry : + metadataReportInstance.getMetadataReports(true).entrySet()) { MetadataReport metadataReport = entry.getValue(); String appName = applicationModel.getApplicationName(); try { @@ -113,16 +120,18 @@ public class MetadataServiceNameMapping extends AbstractServiceNameMapping { } newConfigContent = oldConfigContent + COMMA_SEPARATOR + appName; } - succeeded = metadataReport.registerServiceAppMapping(serviceInterface, DEFAULT_MAPPING_GROUP, newConfigContent, configItem.getTicket()); + succeeded = metadataReport.registerServiceAppMapping( + serviceInterface, DEFAULT_MAPPING_GROUP, newConfigContent, configItem.getTicket()); if (!succeeded) { int waitTime = ThreadLocalRandom.current().nextInt(casRetryWaitTime); - logger.info("Failed to publish service name mapping to metadata center by cas operation. " + - "Times: " + currentRetryTimes + ". " + - "Next retry delay: " + waitTime + ". " + - "Service Interface: " + serviceInterface + ". " + - "Origin Content: " + oldConfigContent + ". " + - "Ticket: " + configItem.getTicket() + ". " + - "Excepted context: " + newConfigContent); + logger.info("Failed to publish service name mapping to metadata center by cas operation. " + + "Times: " + + currentRetryTimes + ". " + "Next retry delay: " + + waitTime + ". " + "Service Interface: " + + serviceInterface + ". " + "Origin Content: " + + oldConfigContent + ". " + "Ticket: " + + configItem.getTicket() + ". " + "Excepted context: " + + newConfigContent); Thread.sleep(waitTime); } } while (!succeeded && currentRetryTimes++ <= casRetryTimes); @@ -132,7 +141,12 @@ public class MetadataServiceNameMapping extends AbstractServiceNameMapping { } } catch (Exception e) { result = false; - logger.warn(INTERNAL_ERROR, "unknown error in registry module", "", "Failed registering mapping to remote." + metadataReport, e); + logger.warn( + INTERNAL_ERROR, + "unknown error in registry module", + "", + "Failed registering mapping to remote." + metadataReport, + e); } } @@ -153,7 +167,8 @@ public class MetadataServiceNameMapping extends AbstractServiceNameMapping { @Override public Set getAndListen(URL url, MappingListener mappingListener) { String serviceInterface = url.getServiceInterface(); - // randomly pick one metadata report is ok for it's guaranteed all metadata report will have the same mapping data. + // randomly pick one metadata report is ok for it's guaranteed all metadata report will have the same mapping + // data. String registryCluster = getRegistryCluster(url); MetadataReport metadataReport = metadataReportInstance.getMetadataReport(registryCluster); if (metadataReport == null) { @@ -165,7 +180,8 @@ public class MetadataServiceNameMapping extends AbstractServiceNameMapping { @Override protected void removeListener(URL url, MappingListener mappingListener) { String serviceInterface = url.getServiceInterface(); - // randomly pick one metadata report is ok for it's guaranteed each metadata report will have the same mapping content. + // randomly pick one metadata report is ok for it's guaranteed each metadata report will have the same mapping + // content. String registryCluster = getRegistryCluster(url); MetadataReport metadataReport = metadataReportInstance.getMetadataReport(registryCluster); if (metadataReport == null) { diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataUtils.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataUtils.java index 398f5cc55f..e75e133d9a 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataUtils.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataUtils.java @@ -57,9 +57,11 @@ import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataU public class MetadataUtils { public static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MetadataUtils.class); - public static void publishServiceDefinition(URL url, ServiceDescriptor serviceDescriptor, ApplicationModel applicationModel) { + public static void publishServiceDefinition( + URL url, ServiceDescriptor serviceDescriptor, ApplicationModel applicationModel) { if (getMetadataReports(applicationModel).size() == 0) { - String msg = "Remote Metadata Report Server is not provided or unavailable, will stop registering service definition to remote center!"; + String msg = + "Remote Metadata Report Server is not provided or unavailable, will stop registering service definition to remote center!"; logger.warn(REGISTRY_FAILED_LOAD_METADATA, "", "", msg); return; } @@ -72,49 +74,51 @@ public class MetadataUtils { if (StringUtils.isNotEmpty(serviceKey) && serviceDefinition != null) { serviceDefinition.setParameters(url.getParameters()); - for (Map.Entry entry : getMetadataReports(applicationModel).entrySet()) { + for (Map.Entry entry : + getMetadataReports(applicationModel).entrySet()) { MetadataReport metadataReport = entry.getValue(); if (!metadataReport.shouldReportDefinition()) { logger.info("Report of service definition is disabled for " + entry.getKey()); continue; } metadataReport.storeProviderMetadata( - new MetadataIdentifier( - url.getServiceInterface(), - url.getVersion() == null ? "" : url.getVersion(), - url.getGroup() == null ? "" : url.getGroup(), - PROVIDER_SIDE, - applicationModel.getApplicationName()) - , serviceDefinition); + new MetadataIdentifier( + url.getServiceInterface(), + url.getVersion() == null ? "" : url.getVersion(), + url.getGroup() == null ? "" : url.getGroup(), + PROVIDER_SIDE, + applicationModel.getApplicationName()), + serviceDefinition); } } } else { - for (Map.Entry entry : getMetadataReports(applicationModel).entrySet()) { + for (Map.Entry entry : + getMetadataReports(applicationModel).entrySet()) { MetadataReport metadataReport = entry.getValue(); if (!metadataReport.shouldReportDefinition()) { logger.info("Report of service definition is disabled for " + entry.getKey()); continue; } metadataReport.storeConsumerMetadata( - new MetadataIdentifier( - url.getServiceInterface(), - url.getVersion() == null ? "" : url.getVersion(), - url.getGroup() == null ? "" : url.getGroup(), - CONSUMER_SIDE, - applicationModel.getApplicationName()), - url.getParameters()); + new MetadataIdentifier( + url.getServiceInterface(), + url.getVersion() == null ? "" : url.getVersion(), + url.getGroup() == null ? "" : url.getGroup(), + CONSUMER_SIDE, + applicationModel.getApplicationName()), + url.getParameters()); } } } catch (Exception e) { - //ignore error + // ignore error logger.error(REGISTRY_FAILED_CREATE_INSTANCE, "", "", "publish service definition metadata error.", e); } } public static ProxyHolder referProxy(ServiceInstance instance) { MetadataServiceURLBuilder builder; - ExtensionLoader loader = instance.getApplicationModel() - .getExtensionLoader(MetadataServiceURLBuilder.class); + ExtensionLoader loader = + instance.getApplicationModel().getExtensionLoader(MetadataServiceURLBuilder.class); Map metadata = instance.getMetadata(); // METADATA_SERVICE_URLS_PROPERTY_NAME is a unique key exists only on instances of spring-cloud-alibaba. @@ -127,8 +131,8 @@ public class MetadataUtils { List urls = builder.build(instance); if (CollectionUtils.isEmpty(urls)) { - throw new IllegalStateException("Introspection service discovery mode is enabled " - + instance + ", but no metadata service can build from it."); + throw new IllegalStateException("Introspection service discovery mode is enabled " + instance + + ", but no metadata service can build from it."); } URL url = urls.get(0); @@ -136,7 +140,8 @@ public class MetadataUtils { // Simply rely on the first metadata url, as stated in MetadataServiceURLBuilder. ApplicationModel applicationModel = instance.getApplicationModel(); ModuleModel internalModel = applicationModel.getInternalModule(); - ConsumerModel consumerModel = applicationModel.getInternalModule().registerInternalConsumer(MetadataService.class, url); + ConsumerModel consumerModel = + applicationModel.getInternalModule().registerInternalConsumer(MetadataService.class, url); Protocol protocol = applicationModel.getExtensionLoader(Protocol.class).getExtension(url.getProtocol(), false); @@ -148,7 +153,8 @@ public class MetadataUtils { Invoker invoker = protocol.refer(MetadataService.class, url); - ProxyFactory proxyFactory = applicationModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + ProxyFactory proxyFactory = + applicationModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); MetadataService metadataService = proxyFactory.getProxy(invoker); @@ -160,7 +166,8 @@ public class MetadataUtils { return new ProxyHolder(consumerModel, metadataService, internalModel); } - public static MetadataInfo getRemoteMetadata(String revision, List instances, MetadataReport metadataReport) { + public static MetadataInfo getRemoteMetadata( + String revision, List instances, MetadataReport metadataReport) { ServiceInstance instance = selectInstance(instances); String metadataType = ServiceInstanceMetadataUtils.getMetadataStorageType(instance); MetadataInfo metadataInfo; @@ -175,13 +182,21 @@ public class MetadataUtils { ProxyHolder proxyHolder = null; try { proxyHolder = MetadataUtils.referProxy(instance); - metadataInfo = proxyHolder.getProxy().getMetadataInfo(ServiceInstanceMetadataUtils.getExportedServicesRevision(instance)); + metadataInfo = proxyHolder + .getProxy() + .getMetadataInfo(ServiceInstanceMetadataUtils.getExportedServicesRevision(instance)); } finally { MetadataUtils.destroyProxy(proxyHolder); } } } catch (Exception e) { - logger.error(REGISTRY_FAILED_LOAD_METADATA, "", "", "Failed to get app metadata for revision " + revision + " for type " + metadataType + " from instance " + instance.getAddress(), e); + logger.error( + REGISTRY_FAILED_LOAD_METADATA, + "", + "", + "Failed to get app metadata for revision " + revision + " for type " + metadataType + + " from instance " + instance.getAddress(), + e); metadataInfo = null; } @@ -214,7 +229,10 @@ public class MetadataUtils { } private static Map getMetadataReports(ApplicationModel applicationModel) { - return applicationModel.getBeanFactory().getBean(MetadataReportInstance.class).getMetadataReports(false); + return applicationModel + .getBeanFactory() + .getBean(MetadataReportInstance.class) + .getMetadataReports(false); } private static ServiceInstance selectInstance(List instances) { @@ -254,5 +272,4 @@ public class MetadataUtils { return internalModel; } } - } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ProtocolPortsMetadataCustomizer.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ProtocolPortsMetadataCustomizer.java index 3a4e0ec76f..3e66da4e03 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ProtocolPortsMetadataCustomizer.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ProtocolPortsMetadataCustomizer.java @@ -40,7 +40,9 @@ import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataU * @since 2.7.5 */ public class ProtocolPortsMetadataCustomizer implements ServiceInstanceCustomizer { - private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(ProtocolPortsMetadataCustomizer.class); + private static final ErrorTypeAwareLogger LOGGER = + LoggerFactory.getErrorTypeAwareLogger(ProtocolPortsMetadataCustomizer.class); + @Override public void customize(ServiceInstance serviceInstance, ApplicationModel applicationModel) { MetadataInfo metadataInfo = serviceInstance.getServiceMetadata(); @@ -56,13 +58,18 @@ public class ProtocolPortsMetadataCustomizer implements ServiceInstanceCustomize Integer oldPort = protocols.get(protocol); int newPort = url.getPort(); if (oldPort != null && oldPort != newPort) { - LOGGER.warn(LoggerCodeConstants.PROTOCOL_INCORRECT_PARAMETER_VALUES, "the protocol is listening multiple ports", "", "Same protocol " + "[" + protocol + "]" + " listens on different ports " + "[" + oldPort + "," + newPort + "]" + " will override with each other" + - ". The port [" + oldPort + "] is overridden with port [" + newPort + "]."); + LOGGER.warn( + LoggerCodeConstants.PROTOCOL_INCORRECT_PARAMETER_VALUES, + "the protocol is listening multiple ports", + "", + "Same protocol " + "[" + protocol + "]" + " listens on different ports " + "[" + oldPort + "," + + newPort + "]" + " will override with each other" + ". The port [" + oldPort + + "] is overridden with port [" + newPort + "]."); } protocols.put(protocol, newPort); }); - if (protocols.size() > 0) {// set endpoints only for multi-protocol scenario + if (protocols.size() > 0) { // set endpoints only for multi-protocol scenario setEndpoints(serviceInstance, protocols); } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceHostPortCustomizer.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceHostPortCustomizer.java index e7c20e3bff..e8542ceab1 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceHostPortCustomizer.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceHostPortCustomizer.java @@ -34,8 +34,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAI * The {@link ServiceInstanceCustomizer} to customize the {@link ServiceInstance#getPort() port} of service instance. */ public class ServiceInstanceHostPortCustomizer implements ServiceInstanceCustomizer { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ServiceInstanceHostPortCustomizer.class); - + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ServiceInstanceHostPortCustomizer.class); @Override public void customize(ServiceInstance serviceInstance, ApplicationModel applicationModel) { @@ -62,15 +62,18 @@ public class ServiceInstanceHostPortCustomizer implements ServiceInstanceCustomi break; } } - + if (host == null || port == -1) { // 4-2 - Can't find an instance URL using the default preferredProtocol. - logger.warn(PROTOCOL_FAILED_INIT_SERIALIZATION_OPTIMIZER, "typo in preferred protocol", "", - "Can't find an instance URL using the default preferredProtocol \"" + preferredProtocol + "\", " + - "falling back to the strategy that pick the first found protocol. " + - "Please try modifying the config of dubbo.application.protocol"); + logger.warn( + PROTOCOL_FAILED_INIT_SERIALIZATION_OPTIMIZER, + "typo in preferred protocol", + "", + "Can't find an instance URL using the default preferredProtocol \"" + preferredProtocol + + "\", " + "falling back to the strategy that pick the first found protocol. " + + "Please try modifying the config of dubbo.application.protocol"); URL url = urls.iterator().next(); host = url.getHost(); @@ -81,7 +84,7 @@ public class ServiceInstanceHostPortCustomizer implements ServiceInstanceCustomi host = url.getHost(); port = url.getPort(); } - + if (serviceInstance instanceof DefaultServiceInstance) { DefaultServiceInstance instance = (DefaultServiceInstance) serviceInstance; instance.setHost(host); diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataCustomizer.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataCustomizer.java index b4eeb944da..853ea6cf39 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataCustomizer.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataCustomizer.java @@ -59,7 +59,8 @@ public class ServiceInstanceMetadataCustomizer implements ServiceInstanceCustomi // try to load instance params that do not appear in service urls // TODO, duplicate snippet in ApplicationConfig Map extraParameters = Collections.emptyMap(); - Set adapters = applicationModel.getExtensionLoader(InfraAdapter.class).getSupportedExtensionInstances(); + Set adapters = + applicationModel.getExtensionLoader(InfraAdapter.class).getSupportedExtensionInstances(); if (CollectionUtils.isNotEmpty(adapters)) { Map inputParameters = new HashMap<>(); inputParameters.put(APPLICATION_KEY, applicationModel.getApplicationName()); diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtils.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtils.java index 9604fd8350..bc26aad59f 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtils.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtils.java @@ -64,7 +64,8 @@ import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY; * @since 2.7.5 */ public class ServiceInstanceMetadataUtils { - private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(ServiceInstanceMetadataUtils.class); + private static final ErrorTypeAwareLogger LOGGER = + LoggerFactory.getErrorTypeAwareLogger(ServiceInstanceMetadataUtils.class); /** * The prefix of {@link MetadataService} : "dubbo.metadata-service." @@ -127,9 +128,9 @@ public class ServiceInstanceMetadataUtils { */ public static String getExportedServicesRevision(ServiceInstance serviceInstance) { return Optional.ofNullable(serviceInstance.getServiceMetadata()) - .map(MetadataInfo::getRevision) - .filter(StringUtils::isNotEmpty) - .orElse(serviceInstance.getMetadata(EXPORTED_SERVICES_REVISION_PROPERTY_NAME)); + .map(MetadataInfo::getRevision) + .filter(StringUtils::isNotEmpty) + .orElse(serviceInstance.getMetadata(EXPORTED_SERVICES_REVISION_PROPERTY_NAME)); } /** @@ -210,21 +211,24 @@ public class ServiceInstanceMetadataUtils { LOGGER.info("Start registering instance address to registry."); List serviceDiscoveries = registryManager.getServiceDiscoveries(); for (ServiceDiscovery serviceDiscovery : serviceDiscoveries) { - MetricsEventBus.post(RegistryEvent.toRegisterEvent(applicationModel, - Collections.singletonList(getServiceDiscoveryName(serviceDiscovery))), - () -> { - // register service instance - serviceDiscoveries.forEach(ServiceDiscovery::register); - return null; - } - ); + MetricsEventBus.post( + RegistryEvent.toRegisterEvent( + applicationModel, Collections.singletonList(getServiceDiscoveryName(serviceDiscovery))), + () -> { + // register service instance + serviceDiscoveries.forEach(ServiceDiscovery::register); + return null; + }); } } } private static String getServiceDiscoveryName(ServiceDiscovery serviceDiscovery) { - return serviceDiscovery.getUrl().getParameter(RegistryConstants.REGISTRY_CLUSTER_KEY, - serviceDiscovery.getUrl().getParameter(REGISTRY_KEY)); + return serviceDiscovery + .getUrl() + .getParameter( + RegistryConstants.REGISTRY_CLUSTER_KEY, + serviceDiscovery.getUrl().getParameter(REGISTRY_KEY)); } public static void refreshMetadataAndInstance(ApplicationModel applicationModel) { @@ -246,7 +250,7 @@ public class ServiceInstanceMetadataUtils { public static void customizeInstance(ServiceInstance instance, ApplicationModel applicationModel) { ExtensionLoader loader = - instance.getOrDefaultApplicationModel().getExtensionLoader(ServiceInstanceCustomizer.class); + instance.getOrDefaultApplicationModel().getExtensionLoader(ServiceInstanceCustomizer.class); // FIXME, sort customizer before apply loader.getSupportedExtensionInstances().forEach(customizer -> { // customize @@ -272,5 +276,4 @@ public class ServiceInstanceMetadataUtils { } } } - } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/SpringCloudServiceInstanceNotificationCustomizer.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/SpringCloudServiceInstanceNotificationCustomizer.java index 750eb6e6e9..e0509b0a37 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/SpringCloudServiceInstanceNotificationCustomizer.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/SpringCloudServiceInstanceNotificationCustomizer.java @@ -32,24 +32,37 @@ public class SpringCloudServiceInstanceNotificationCustomizer implements Service return; } - if (!serviceInstance.stream().allMatch(instance -> "SPRING_CLOUD".equals(instance.getMetadata("preserved.register.source")))) { + if (!serviceInstance.stream() + .allMatch(instance -> "SPRING_CLOUD".equals(instance.getMetadata("preserved.register.source")))) { return; } for (ServiceInstance instance : serviceInstance) { - MetadataInfo.ServiceInfo serviceInfo = new MetadataInfo.ServiceInfo("*", "*", "*", "rest", instance.getPort(), "*", new HashMap<>()); - String revision = "SPRING_CLOUD-" + instance.getServiceName() + "-" + instance.getAddress() + "-" + instance.getPort(); - MetadataInfo metadataInfo = new MetadataInfo(instance.getServiceName(), revision, new ConcurrentHashMap<>(Collections.singletonMap("*", serviceInfo))) { - @Override - public List getMatchedServiceInfos(ProtocolServiceKey consumerProtocolServiceKey) { - getServices().putIfAbsent(consumerProtocolServiceKey.getServiceKeyString(), - new MetadataInfo.ServiceInfo(consumerProtocolServiceKey.getInterfaceName(), - consumerProtocolServiceKey.getGroup(), consumerProtocolServiceKey.getVersion(), - consumerProtocolServiceKey.getProtocol(), instance.getPort(), consumerProtocolServiceKey.getInterfaceName(), new HashMap<>())); - return super.getMatchedServiceInfos(consumerProtocolServiceKey); - } - }; - + MetadataInfo.ServiceInfo serviceInfo = + new MetadataInfo.ServiceInfo("*", "*", "*", "rest", instance.getPort(), "*", new HashMap<>()); + String revision = "SPRING_CLOUD-" + instance.getServiceName() + "-" + instance.getAddress() + "-" + + instance.getPort(); + MetadataInfo metadataInfo = + new MetadataInfo( + instance.getServiceName(), + revision, + new ConcurrentHashMap<>(Collections.singletonMap("*", serviceInfo))) { + @Override + public List getMatchedServiceInfos(ProtocolServiceKey consumerProtocolServiceKey) { + getServices() + .putIfAbsent( + consumerProtocolServiceKey.getServiceKeyString(), + new MetadataInfo.ServiceInfo( + consumerProtocolServiceKey.getInterfaceName(), + consumerProtocolServiceKey.getGroup(), + consumerProtocolServiceKey.getVersion(), + consumerProtocolServiceKey.getProtocol(), + instance.getPort(), + consumerProtocolServiceKey.getInterfaceName(), + new HashMap<>())); + return super.getMatchedServiceInfos(consumerProtocolServiceKey); + } + }; instance.setServiceMetadata(metadataInfo); } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/StandardMetadataServiceURLBuilder.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/StandardMetadataServiceURLBuilder.java index 2aae71f30e..b77bb1020e 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/StandardMetadataServiceURLBuilder.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/StandardMetadataServiceURLBuilder.java @@ -102,16 +102,19 @@ public class StandardMetadataServiceURLBuilder implements MetadataServiceURLBuil String protocol = params.get(PROTOCOL_KEY); int port = Integer.parseInt(params.get(PORT_KEY)); URLBuilder urlBuilder = new URLBuilder() - .setHost(host) - .setPort(port) - .setProtocol(protocol) - .setPath(MetadataService.class.getName()) - .addParameter(TIMEOUT_KEY, ConfigurationUtils.get(applicationModel, METADATA_PROXY_TIMEOUT_KEY, DEFAULT_METADATA_TIMEOUT_VALUE)) - .addParameter(CONNECTIONS_KEY, 1) - .addParameter(THREADPOOL_KEY, "cached") - .addParameter(THREADS_KEY, "100") - .addParameter(CORE_THREADS_KEY, "2") - .addParameter(RETRIES_KEY, 0); + .setHost(host) + .setPort(port) + .setProtocol(protocol) + .setPath(MetadataService.class.getName()) + .addParameter( + TIMEOUT_KEY, + ConfigurationUtils.get( + applicationModel, METADATA_PROXY_TIMEOUT_KEY, DEFAULT_METADATA_TIMEOUT_VALUE)) + .addParameter(CONNECTIONS_KEY, 1) + .addParameter(THREADPOOL_KEY, "cached") + .addParameter(THREADS_KEY, "100") + .addParameter(CORE_THREADS_KEY, "2") + .addParameter(RETRIES_KEY, 0); // add parameters params.forEach(urlBuilder::addParameter); @@ -128,9 +131,12 @@ public class StandardMetadataServiceURLBuilder implements MetadataServiceURLBuil // 1-18 - Metadata Service Port should be specified for consumer. - logger.warn(REGISTRY_MISSING_METADATA_CONFIG_PORT, "missing configuration of metadata service port", "", - "Metadata Service Port is not provided. Since DNS is not able to negotiate the metadata port " + - "between Provider and Consumer, Dubbo will try using instance port as the default metadata port."); + logger.warn( + REGISTRY_MISSING_METADATA_CONFIG_PORT, + "missing configuration of metadata service port", + "", + "Metadata Service Port is not provided. Since DNS is not able to negotiate the metadata port " + + "between Provider and Consumer, Dubbo will try using instance port as the default metadata port."); port = instancePort; } @@ -139,15 +145,20 @@ public class StandardMetadataServiceURLBuilder implements MetadataServiceURLBuil // 1-18 - Metadata Service Port should be specified for consumer. - String message = "Metadata Service Port should be specified for consumer. " + - "Please set dubbo.application.metadataServicePort and " + - "make sure it has been set on provider side. " + - "ServiceName: " + serviceName + " Host: " + host; + String message = "Metadata Service Port should be specified for consumer. " + + "Please set dubbo.application.metadataServicePort and " + + "make sure it has been set on provider side. " + + "ServiceName: " + + serviceName + " Host: " + host; IllegalStateException illegalStateException = new IllegalStateException(message); - logger.error(REGISTRY_MISSING_METADATA_CONFIG_PORT, "missing configuration of metadata service port", "", - message, illegalStateException); + logger.error( + REGISTRY_MISSING_METADATA_CONFIG_PORT, + "missing configuration of metadata service port", + "", + message, + illegalStateException); throw illegalStateException; } @@ -157,7 +168,10 @@ public class StandardMetadataServiceURLBuilder implements MetadataServiceURLBuil .setPort(port) .setProtocol(DUBBO_PROTOCOL) .setPath(MetadataService.class.getName()) - .addParameter(TIMEOUT_KEY, ConfigurationUtils.get(applicationModel, METADATA_PROXY_TIMEOUT_KEY, DEFAULT_METADATA_TIMEOUT_VALUE)) + .addParameter( + TIMEOUT_KEY, + ConfigurationUtils.get( + applicationModel, METADATA_PROXY_TIMEOUT_KEY, DEFAULT_METADATA_TIMEOUT_VALUE)) .addParameter(Constants.RECONNECT_KEY, false) .addParameter(SIDE_KEY, CONSUMER) .addParameter(GROUP_KEY, serviceName) diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/DefaultMigrationAddressComparator.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/DefaultMigrationAddressComparator.java index 72a5b590e4..1a23048837 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/DefaultMigrationAddressComparator.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/DefaultMigrationAddressComparator.java @@ -34,7 +34,8 @@ import java.util.concurrent.ConcurrentMap; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_PROPERTY_TYPE_MISMATCH; public class DefaultMigrationAddressComparator implements MigrationAddressComparator { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DefaultMigrationAddressComparator.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(DefaultMigrationAddressComparator.class); private static final String MIGRATION_THRESHOLD = "dubbo.application.migration.threshold"; private static final String DEFAULT_THRESHOLD_STRING = "0.0"; private static final float DEFAULT_THREAD = 0f; @@ -46,7 +47,8 @@ public class DefaultMigrationAddressComparator implements MigrationAddressCompar @Override public boolean shouldMigrate(ClusterInvoker newInvoker, ClusterInvoker oldInvoker, MigrationRule rule) { - Map migrationData = ConcurrentHashMapUtils.computeIfAbsent(serviceMigrationData, oldInvoker.getUrl().getDisplayServiceKey(), _k -> new ConcurrentHashMap<>()); + Map migrationData = ConcurrentHashMapUtils.computeIfAbsent( + serviceMigrationData, oldInvoker.getUrl().getDisplayServiceKey(), _k -> new ConcurrentHashMap<>()); if (!newInvoker.hasProxyInvokers()) { migrationData.put(OLD_ADDRESS_SIZE, getAddressSize(oldInvoker)); @@ -72,7 +74,10 @@ public class DefaultMigrationAddressComparator implements MigrationAddressCompar if (configuredThreshold != null && configuredThreshold >= 0) { rawThreshold = String.valueOf(configuredThreshold); } - rawThreshold = StringUtils.isNotEmpty(rawThreshold) ? rawThreshold : ConfigurationUtils.getCachedDynamicProperty(newInvoker.getUrl().getScopeModel(), MIGRATION_THRESHOLD, DEFAULT_THRESHOLD_STRING); + rawThreshold = StringUtils.isNotEmpty(rawThreshold) + ? rawThreshold + : ConfigurationUtils.getCachedDynamicProperty( + newInvoker.getUrl().getScopeModel(), MIGRATION_THRESHOLD, DEFAULT_THRESHOLD_STRING); float threshold; try { threshold = Float.parseFloat(rawThreshold); @@ -81,7 +86,8 @@ public class DefaultMigrationAddressComparator implements MigrationAddressCompar threshold = DEFAULT_THREAD; } - logger.info("serviceKey:" + oldInvoker.getUrl().getServiceKey() + " Instance address size " + newAddressSize + ", interface address size " + oldAddressSize + ", threshold " + threshold); + logger.info("serviceKey:" + oldInvoker.getUrl().getServiceKey() + " Instance address size " + newAddressSize + + ", interface address size " + oldAddressSize + ", threshold " + threshold); if (newAddressSize != 0 && oldAddressSize == 0) { return true; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationInvoker.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationInvoker.java index c4662966e8..a0a6b614f7 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationInvoker.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationInvoker.java @@ -68,24 +68,26 @@ public class MigrationInvoker implements MigrationClusterInvoker { private volatile MigrationRule rule; private volatile int promotion = 100; - public MigrationInvoker(RegistryProtocol registryProtocol, - Cluster cluster, - Registry registry, - Class type, - URL url, - URL consumerUrl) { + public MigrationInvoker( + RegistryProtocol registryProtocol, + Cluster cluster, + Registry registry, + Class type, + URL url, + URL consumerUrl) { this(null, null, registryProtocol, cluster, registry, type, url, consumerUrl); } @SuppressWarnings("unchecked") - public MigrationInvoker(ClusterInvoker invoker, - ClusterInvoker serviceDiscoveryInvoker, - RegistryProtocol registryProtocol, - Cluster cluster, - Registry registry, - Class type, - URL url, - URL consumerUrl) { + public MigrationInvoker( + ClusterInvoker invoker, + ClusterInvoker serviceDiscoveryInvoker, + RegistryProtocol registryProtocol, + Cluster cluster, + Registry registry, + Class type, + URL url, + URL consumerUrl) { this.invoker = invoker; this.serviceDiscoveryInvoker = serviceDiscoveryInvoker; this.registryProtocol = registryProtocol; @@ -95,10 +97,12 @@ public class MigrationInvoker implements MigrationClusterInvoker { this.url = url; this.consumerUrl = consumerUrl; this.consumerModel = (ConsumerModel) consumerUrl.getServiceModel(); - this.reportService = consumerUrl.getOrDefaultApplicationModel().getBeanFactory().getBean(FrameworkStatusReportService.class); + this.reportService = + consumerUrl.getOrDefaultApplicationModel().getBeanFactory().getBean(FrameworkStatusReportService.class); if (consumerModel != null) { - Object object = consumerModel.getServiceMetadata().getAttribute(CommonConstants.CURRENT_CLUSTER_INVOKER_KEY); + Object object = + consumerModel.getServiceMetadata().getAttribute(CommonConstants.CURRENT_CLUSTER_INVOKER_KEY); Map> invokerMap; if (object instanceof Map) { invokerMap = (Map>) object; @@ -184,10 +188,13 @@ public class MigrationInvoker implements MigrationClusterInvoker { return true; } - Set detectors = ScopeModelUtil.getApplicationModel(consumerUrl == null ? null : consumerUrl.getScopeModel()) - .getExtensionLoader(MigrationAddressComparator.class).getSupportedExtensionInstances(); + Set detectors = ScopeModelUtil.getApplicationModel( + consumerUrl == null ? null : consumerUrl.getScopeModel()) + .getExtensionLoader(MigrationAddressComparator.class) + .getSupportedExtensionInstances(); if (CollectionUtils.isNotEmpty(detectors)) { - if (detectors.stream().allMatch(comparator -> comparator.shouldMigrate(invoker, serviceDiscoveryInvoker, newRule))) { + if (detectors.stream() + .allMatch(comparator -> comparator.shouldMigrate(invoker, serviceDiscoveryInvoker, newRule))) { this.currentAvailableInvoker = invoker; this.destroyServiceDiscoveryInvoker(); return true; @@ -222,10 +229,13 @@ public class MigrationInvoker implements MigrationClusterInvoker { return true; } - Set detectors = ScopeModelUtil.getApplicationModel(consumerUrl == null ? null : consumerUrl.getScopeModel()) - .getExtensionLoader(MigrationAddressComparator.class).getSupportedExtensionInstances(); + Set detectors = ScopeModelUtil.getApplicationModel( + consumerUrl == null ? null : consumerUrl.getScopeModel()) + .getExtensionLoader(MigrationAddressComparator.class) + .getSupportedExtensionInstances(); if (CollectionUtils.isNotEmpty(detectors)) { - if (detectors.stream().allMatch(comparator -> comparator.shouldMigrate(serviceDiscoveryInvoker, invoker, newRule))) { + if (detectors.stream() + .allMatch(comparator -> comparator.shouldMigrate(serviceDiscoveryInvoker, invoker, newRule))) { this.currentAvailableInvoker = serviceDiscoveryInvoker; this.destroyInterfaceInvoker(); return true; @@ -315,8 +325,9 @@ public class MigrationInvoker implements MigrationClusterInvoker { @Override public boolean isAvailable() { return currentAvailableInvoker != null - ? currentAvailableInvoker.isAvailable() - : (invoker != null && invoker.isAvailable()) || (serviceDiscoveryInvoker != null && serviceDiscoveryInvoker.isAvailable()); + ? currentAvailableInvoker.isAvailable() + : (invoker != null && invoker.isAvailable()) + || (serviceDiscoveryInvoker != null && serviceDiscoveryInvoker.isAvailable()); } @SuppressWarnings("unchecked") @@ -332,13 +343,17 @@ public class MigrationInvoker implements MigrationClusterInvoker { serviceDiscoveryInvoker.destroy(); } if (consumerModel != null) { - Object object = consumerModel.getServiceMetadata().getAttribute(CommonConstants.CURRENT_CLUSTER_INVOKER_KEY); + Object object = + consumerModel.getServiceMetadata().getAttribute(CommonConstants.CURRENT_CLUSTER_INVOKER_KEY); Map> invokerMap; if (object instanceof Map) { invokerMap = (Map>) object; invokerMap.remove(registry); if (invokerMap.isEmpty()) { - consumerModel.getServiceMetadata().getAttributeMap().remove(CommonConstants.CURRENT_CLUSTER_INVOKER_KEY); + consumerModel + .getServiceMetadata() + .getAttributeMap() + .remove(CommonConstants.CURRENT_CLUSTER_INVOKER_KEY); } } } @@ -384,8 +399,9 @@ public class MigrationInvoker implements MigrationClusterInvoker { @Override public boolean isDestroyed() { return currentAvailableInvoker != null - ? currentAvailableInvoker.isDestroyed() - : (invoker == null || invoker.isDestroyed()) && (serviceDiscoveryInvoker == null || serviceDiscoveryInvoker.isDestroyed()); + ? currentAvailableInvoker.isDestroyed() + : (invoker == null || invoker.isDestroyed()) + && (serviceDiscoveryInvoker == null || serviceDiscoveryInvoker.isDestroyed()); } @Override @@ -420,7 +436,9 @@ public class MigrationInvoker implements MigrationClusterInvoker { } if (serviceDiscoveryInvoker != null && !serviceDiscoveryInvoker.isDestroyed()) { if (logger.isInfoEnabled()) { - logger.info("Destroying instance address invokers, will not listen for address changes until re-subscribed, " + type.getName()); + logger.info( + "Destroying instance address invokers, will not listen for address changes until re-subscribed, " + + type.getName()); } serviceDiscoveryInvoker.destroy(); serviceDiscoveryInvoker = null; @@ -442,8 +460,8 @@ public class MigrationInvoker implements MigrationClusterInvoker { setListener(serviceDiscoveryInvoker, () -> { latch.countDown(); if (reportService.hasReporter()) { - reportService.reportConsumptionStatus( - reportService.createConsumptionReport(consumerUrl.getServiceInterface(), consumerUrl.getVersion(), consumerUrl.getGroup(), "app")); + reportService.reportConsumptionStatus(reportService.createConsumptionReport( + consumerUrl.getServiceInterface(), consumerUrl.getVersion(), consumerUrl.getGroup(), "app")); } if (step == APPLICATION_FIRST) { calcPreferredInvoker(rule); @@ -466,8 +484,11 @@ public class MigrationInvoker implements MigrationClusterInvoker { setListener(invoker, () -> { latch.countDown(); if (reportService.hasReporter()) { - reportService.reportConsumptionStatus( - reportService.createConsumptionReport(consumerUrl.getServiceInterface(), consumerUrl.getVersion(), consumerUrl.getGroup(), "interface")); + reportService.reportConsumptionStatus(reportService.createConsumptionReport( + consumerUrl.getServiceInterface(), + consumerUrl.getVersion(), + consumerUrl.getGroup(), + "interface")); } if (step == APPLICATION_FIRST) { calcPreferredInvoker(rule); @@ -479,12 +500,16 @@ public class MigrationInvoker implements MigrationClusterInvoker { if (serviceDiscoveryInvoker == null || invoker == null) { return; } - Set detectors = ScopeModelUtil.getApplicationModel(consumerUrl == null ? null : consumerUrl.getScopeModel()) - .getExtensionLoader(MigrationAddressComparator.class).getSupportedExtensionInstances(); + Set detectors = ScopeModelUtil.getApplicationModel( + consumerUrl == null ? null : consumerUrl.getScopeModel()) + .getExtensionLoader(MigrationAddressComparator.class) + .getSupportedExtensionInstances(); if (CollectionUtils.isNotEmpty(detectors)) { // pick preferred invoker // the real invoker choice in invocation will be affected by promotion - if (detectors.stream().allMatch(comparator -> comparator.shouldMigrate(serviceDiscoveryInvoker, invoker, migrationRule))) { + if (detectors.stream() + .allMatch( + comparator -> comparator.shouldMigrate(serviceDiscoveryInvoker, invoker, migrationRule))) { this.currentAvailableInvoker = serviceDiscoveryInvoker; } else { this.currentAvailableInvoker = invoker; @@ -498,7 +523,9 @@ public class MigrationInvoker implements MigrationClusterInvoker { } if (invoker != null && !invoker.isDestroyed()) { if (logger.isInfoEnabled()) { - logger.info("Destroying interface address invokers, will not listen for address changes until re-subscribed, " + type.getName()); + logger.info( + "Destroying interface address invokers, will not listen for address changes until re-subscribed, " + + type.getName()); } invoker.destroy(); invoker = null; @@ -547,10 +574,9 @@ public class MigrationInvoker implements MigrationClusterInvoker { @Override public String toString() { - return "MigrationInvoker{" + - "serviceKey=" + consumerUrl.getServiceKey() + - ", invoker=" + decideInvoker() + - ", step=" + step + - '}'; + return "MigrationInvoker{" + "serviceKey=" + + consumerUrl.getServiceKey() + ", invoker=" + + decideInvoker() + ", step=" + + step + '}'; } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleHandler.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleHandler.java index 920e1d65c2..ccf2dd8cd6 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleHandler.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleHandler.java @@ -23,12 +23,13 @@ import org.apache.dubbo.common.status.reporter.FrameworkStatusReportService; import org.apache.dubbo.registry.client.migration.model.MigrationRule; import org.apache.dubbo.registry.client.migration.model.MigrationStep; -import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_NO_PARAMETERS_URL; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_NO_PARAMETERS_URL; public class MigrationRuleHandler { public static final String DUBBO_SERVICEDISCOVERY_MIGRATION = "dubbo.application.migration.step"; - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MigrationRuleHandler.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(MigrationRuleHandler.class); private final MigrationClusterInvoker migrationInvoker; private volatile MigrationStep currentStep; @@ -54,7 +55,8 @@ public class MigrationRuleHandler { step = rule.getStep(consumerURL); threshold = rule.getThreshold(consumerURL); } catch (Exception e) { - logger.error(REGISTRY_NO_PARAMETERS_URL, "", "", "Failed to get step and threshold info from rule: " + rule, e); + logger.error( + REGISTRY_NO_PARAMETERS_URL, "", "", "Failed to get step and threshold info from rule: " + rule, e); } if (refreshInvoker(step, threshold, rule)) { @@ -85,12 +87,17 @@ public class MigrationRuleHandler { if (success) { setCurrentStepAndThreshold(step, threshold); - logger.info("Succeed Migrated to " + step + " mode. Service Name: " + consumerURL.getDisplayServiceKey()); + logger.info( + "Succeed Migrated to " + step + " mode. Service Name: " + consumerURL.getDisplayServiceKey()); report(step, originStep, "true"); } else { // migrate failed, do not save new step and rule - logger.warn(INTERNAL_ERROR, "unknown error in registry module", "", "Migrate to " + step + " mode failed. Probably not satisfy the threshold you set " - + threshold + ". Please try re-publish configuration if you still after check."); + logger.warn( + INTERNAL_ERROR, + "unknown error in registry module", + "", + "Migrate to " + step + " mode failed. Probably not satisfy the threshold you set " + threshold + + ". Please try re-publish configuration if you still after check."); report(step, originStep, "false"); } @@ -102,12 +109,16 @@ public class MigrationRuleHandler { private void report(MigrationStep step, MigrationStep originStep, String success) { FrameworkStatusReportService reportService = - consumerURL.getOrDefaultApplicationModel().getBeanFactory().getBean(FrameworkStatusReportService.class); + consumerURL.getOrDefaultApplicationModel().getBeanFactory().getBean(FrameworkStatusReportService.class); if (reportService.hasReporter()) { - reportService.reportMigrationStepStatus( - reportService.createMigrationStepReport(consumerURL.getServiceInterface(), consumerURL.getVersion(), - consumerURL.getGroup(), String.valueOf(originStep), String.valueOf(step), success)); + reportService.reportMigrationStepStatus(reportService.createMigrationStepReport( + consumerURL.getServiceInterface(), + consumerURL.getVersion(), + consumerURL.getGroup(), + String.valueOf(originStep), + String.valueOf(step), + success)); } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleListener.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleListener.java index de6abfd39b..cd4cf2816c 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleListener.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleListener.java @@ -69,7 +69,8 @@ import static org.apache.dubbo.common.constants.RegistryConstants.INIT; */ @Activate public class MigrationRuleListener implements RegistryProtocolListener, ConfigurationListener { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MigrationRuleListener.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(MigrationRuleListener.class); private static final String DUBBO_SERVICEDISCOVERY_MIGRATION = "DUBBO_SERVICEDISCOVERY_MIGRATION"; private static final String MIGRATION_DELAY_KEY = "dubbo.application.migration.delay"; private static final int MIGRATION_DEFAULT_DELAY_TIME = 60000; @@ -79,7 +80,8 @@ public class MigrationRuleListener implements RegistryProtocolListener, Configur protected final LinkedBlockingQueue ruleQueue = new LinkedBlockingQueue<>(); private final AtomicBoolean executorSubmit = new AtomicBoolean(false); - private final ExecutorService ruleManageExecutor = Executors.newFixedThreadPool(1, new NamedThreadFactory("Dubbo-Migration-Listener")); + private final ExecutorService ruleManageExecutor = + Executors.newFixedThreadPool(1, new NamedThreadFactory("Dubbo-Migration-Listener")); protected ScheduledFuture localRuleMigrationFuture; protected Future ruleMigrationFuture; @@ -97,10 +99,12 @@ public class MigrationRuleListener implements RegistryProtocolListener, Configur private void init() { this.ruleKey = moduleModel.getApplicationModel().getApplicationName() + ".migration"; - this.configuration = moduleModel.modelEnvironment().getDynamicConfiguration().orElse(null); + this.configuration = + moduleModel.modelEnvironment().getDynamicConfiguration().orElse(null); if (this.configuration != null) { - logger.info("Listening for migration rules on dataId " + ruleKey + ", group " + DUBBO_SERVICEDISCOVERY_MIGRATION); + logger.info("Listening for migration rules on dataId " + ruleKey + ", group " + + DUBBO_SERVICEDISCOVERY_MIGRATION); configuration.addListener(ruleKey, DUBBO_SERVICEDISCOVERY_MIGRATION, this); String rawRule = configuration.getConfig(ruleKey, DUBBO_SERVICEDISCOVERY_MIGRATION); @@ -110,20 +114,31 @@ public class MigrationRuleListener implements RegistryProtocolListener, Configur setRawRule(rawRule); } else { if (logger.isWarnEnabled()) { - logger.warn(REGISTRY_EMPTY_ADDRESS, "", "", "Using default configuration rule because config center is not configured!"); + logger.warn( + REGISTRY_EMPTY_ADDRESS, + "", + "", + "Using default configuration rule because config center is not configured!"); } setRawRule(INIT); } String localRawRule = moduleModel.modelEnvironment().getLocalMigrationRule(); if (!StringUtils.isEmpty(localRawRule)) { - localRuleMigrationFuture = moduleModel.getApplicationModel().getFrameworkModel().getBeanFactory() - .getBean(FrameworkExecutorRepository.class).getSharedScheduledExecutor() - .schedule(() -> { - if (this.rawRule.equals(INIT)) { - this.process(new ConfigChangedEvent(null, null, localRawRule)); - } - }, getDelay(), TimeUnit.MILLISECONDS); + localRuleMigrationFuture = moduleModel + .getApplicationModel() + .getFrameworkModel() + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class) + .getSharedScheduledExecutor() + .schedule( + () -> { + if (this.rawRule.equals(INIT)) { + this.process(new ConfigChangedEvent(null, null, localRawRule)); + } + }, + getDelay(), + TimeUnit.MILLISECONDS); } } @@ -148,12 +163,17 @@ public class MigrationRuleListener implements RegistryProtocolListener, Configur if (StringUtils.isEmpty(rawRule)) { // fail back to startup status rawRule = INIT; - //logger.warn(COMMON_PROPERTY_TYPE_MISMATCH, "", "", "Received empty migration rule, will ignore."); + // logger.warn(COMMON_PROPERTY_TYPE_MISMATCH, "", "", "Received empty migration rule, will ignore."); } try { ruleQueue.put(rawRule); } catch (InterruptedException e) { - logger.error(COMMON_THREAD_INTERRUPTED_EXCEPTION, "", "", "Put rawRule to rule management queue failed. rawRule: " + rawRule, e); + logger.error( + COMMON_THREAD_INTERRUPTED_EXCEPTION, + "", + "", + "Put rawRule to rule management queue failed. rawRule: " + rawRule, + e); } if (executorSubmit.compareAndSet(false, true)) { @@ -166,7 +186,8 @@ public class MigrationRuleListener implements RegistryProtocolListener, Configur Thread.sleep(1000); } } catch (InterruptedException e) { - logger.error(COMMON_THREAD_INTERRUPTED_EXCEPTION, "", "", "Poll Rule from config center failed.", e); + logger.error( + COMMON_THREAD_INTERRUPTED_EXCEPTION, "", "", "Poll Rule from config center failed.", e); } if (StringUtils.isEmpty(rule)) { continue; @@ -187,7 +208,8 @@ public class MigrationRuleListener implements RegistryProtocolListener, Configur ExecutorService executorService = null; try { - executorService = Executors.newFixedThreadPool(Math.min(handlers.size(), 100), new NamedThreadFactory("Dubbo-Invoker-Migrate")); + executorService = Executors.newFixedThreadPool( + Math.min(handlers.size(), 100), new NamedThreadFactory("Dubbo-Invoker-Migrate")); List> migrationFutures = new ArrayList<>(handlers.size()); for (MigrationRuleHandler handler : handlers.values()) { Future future = executorService.submit(() -> handler.doMigrate(this.rule)); @@ -198,13 +220,27 @@ public class MigrationRuleListener implements RegistryProtocolListener, Configur try { future.get(); } catch (InterruptedException ie) { - logger.warn(INTERNAL_ERROR, "unknown error in registry module", "", "Interrupted while waiting for migration async task to finish."); + logger.warn( + INTERNAL_ERROR, + "unknown error in registry module", + "", + "Interrupted while waiting for migration async task to finish."); } catch (ExecutionException ee) { - logger.error(INTERNAL_ERROR, "unknown error in registry module", "", "Migration async task failed.", ee.getCause()); + logger.error( + INTERNAL_ERROR, + "unknown error in registry module", + "", + "Migration async task failed.", + ee.getCause()); } } } catch (Throwable t) { - logger.error(INTERNAL_ERROR, "unknown error in registry module", "", "Error occurred when migration.", t); + logger.error( + INTERNAL_ERROR, + "unknown error in registry module", + "", + "Error occurred when migration.", + t); } finally { if (executorService != null) { executorService.shutdown(); @@ -235,16 +271,16 @@ public class MigrationRuleListener implements RegistryProtocolListener, Configur } @Override - public void onExport(RegistryProtocol registryProtocol, Exporter exporter) { - - } + public void onExport(RegistryProtocol registryProtocol, Exporter exporter) {} @Override - public void onRefer(RegistryProtocol registryProtocol, ClusterInvoker invoker, URL consumerUrl, URL registryURL) { - MigrationRuleHandler migrationRuleHandler = ConcurrentHashMapUtils.computeIfAbsent(handlers, (MigrationInvoker) invoker, _key -> { - ((MigrationInvoker) invoker).setMigrationRuleListener(this); - return new MigrationRuleHandler<>((MigrationInvoker) invoker, consumerUrl); - }); + public void onRefer( + RegistryProtocol registryProtocol, ClusterInvoker invoker, URL consumerUrl, URL registryURL) { + MigrationRuleHandler migrationRuleHandler = + ConcurrentHashMapUtils.computeIfAbsent(handlers, (MigrationInvoker) invoker, _key -> { + ((MigrationInvoker) invoker).setMigrationRuleListener(this); + return new MigrationRuleHandler<>((MigrationInvoker) invoker, consumerUrl); + }); migrationRuleHandler.doMigrate(rule); } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/ServiceDiscoveryMigrationInvoker.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/ServiceDiscoveryMigrationInvoker.java index b48c79cd22..bc35f401df 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/ServiceDiscoveryMigrationInvoker.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/ServiceDiscoveryMigrationInvoker.java @@ -31,9 +31,16 @@ import org.apache.dubbo.rpc.cluster.ClusterInvoker; import java.util.concurrent.CountDownLatch; public class ServiceDiscoveryMigrationInvoker extends MigrationInvoker { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ServiceDiscoveryMigrationInvoker.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ServiceDiscoveryMigrationInvoker.class); - public ServiceDiscoveryMigrationInvoker(RegistryProtocol registryProtocol, Cluster cluster, Registry registry, Class type, URL url, URL consumerUrl) { + public ServiceDiscoveryMigrationInvoker( + RegistryProtocol registryProtocol, + Cluster cluster, + Registry registry, + Class type, + URL url, + URL consumerUrl) { super(registryProtocol, cluster, registry, type, url, consumerUrl); } @@ -63,7 +70,8 @@ public class ServiceDiscoveryMigrationInvoker extends MigrationInvoker { public Result invoke(Invocation invocation) throws RpcException { ClusterInvoker invoker = getServiceDiscoveryInvoker(); if (invoker == null) { - throw new IllegalStateException("There's no service discovery invoker available for service " + invocation.getServiceName()); + throw new IllegalStateException( + "There's no service discovery invoker available for service " + invocation.getServiceName()); } return invoker.invoke(invocation); } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/model/MigrationRule.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/model/MigrationRule.java index 846cfba368..c8a7e68f98 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/model/MigrationRule.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/model/MigrationRule.java @@ -22,11 +22,6 @@ import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.metadata.ServiceNameMapping; -import org.yaml.snakeyaml.LoaderOptions; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.Constructor; -import org.yaml.snakeyaml.constructor.SafeConstructor; - import java.util.HashMap; import java.util.List; import java.util.Map; @@ -35,6 +30,11 @@ import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; +import org.yaml.snakeyaml.constructor.SafeConstructor; + import static org.apache.dubbo.registry.Constants.MIGRATION_DELAY_KEY; import static org.apache.dubbo.registry.Constants.MIGRATION_FORCE_KEY; import static org.apache.dubbo.registry.Constants.MIGRATION_PROMOTION_KEY; @@ -127,21 +127,20 @@ public class MigrationRule { Object interfaces = map.get(MIGRATION_RULE_INTERFACES_KEY); if (interfaces != null && List.class.isAssignableFrom(interfaces.getClass())) { - migrationRule.setInterfaces(((List>) interfaces).stream() - .map(SubMigrationRule::parseFromMap).collect(Collectors.toList())); + migrationRule.setInterfaces(((List>) interfaces) + .stream().map(SubMigrationRule::parseFromMap).collect(Collectors.toList())); } Object applications = map.get(MIGRATION_RULE_APPLICATIONS_KEY); if (applications != null && List.class.isAssignableFrom(applications.getClass())) { - migrationRule.setApplications(((List>) applications).stream() - .map(SubMigrationRule::parseFromMap).collect(Collectors.toList())); + migrationRule.setApplications(((List>) applications) + .stream().map(SubMigrationRule::parseFromMap).collect(Collectors.toList())); } return migrationRule; } - public MigrationRule() { - } + public MigrationRule() {} public MigrationRule(String key) { this.key = key; @@ -166,18 +165,22 @@ public class MigrationRule { */ if (step == null) { // initial step : APPLICATION_FIRST - return Enum.valueOf(MigrationStep.class, - consumerURL.getParameter(MIGRATION_STEP_KEY, getDefaultStep(consumerURL, MigrationStep.APPLICATION_FIRST.name()))); + return Enum.valueOf( + MigrationStep.class, + consumerURL.getParameter( + MIGRATION_STEP_KEY, getDefaultStep(consumerURL, MigrationStep.APPLICATION_FIRST.name()))); } return step; } private String getDefaultStep(URL consumerURL, String defaultStep) { - String globalDefaultStep = ConfigurationUtils.getCachedDynamicProperty(consumerURL.getScopeModel(), DUBBO_SERVICEDISCOVERY_MIGRATION, null); + String globalDefaultStep = ConfigurationUtils.getCachedDynamicProperty( + consumerURL.getScopeModel(), DUBBO_SERVICEDISCOVERY_MIGRATION, null); if (StringUtils.isEmpty(globalDefaultStep)) { // check 'dubbo.application.service-discovery.migration' for compatibility - globalDefaultStep = ConfigurationUtils.getCachedDynamicProperty(consumerURL.getScopeModel(), "dubbo.application.service-discovery.migration", defaultStep); + globalDefaultStep = ConfigurationUtils.getCachedDynamicProperty( + consumerURL.getScopeModel(), "dubbo.application.service-discovery.migration", defaultStep); } return globalDefaultStep; } @@ -336,11 +339,30 @@ public class MigrationRule { return false; } MigrationRule that = (MigrationRule) o; - return Objects.equals(key, that.key) && step == that.step && Objects.equals(threshold, that.threshold) && Objects.equals(proportion, that.proportion) && Objects.equals(delay, that.delay) && Objects.equals(force, that.force) && Objects.equals(interfaces, that.interfaces) && Objects.equals(applications, that.applications) && Objects.equals(interfaceRules, that.interfaceRules) && Objects.equals(applicationRules, that.applicationRules); + return Objects.equals(key, that.key) + && step == that.step + && Objects.equals(threshold, that.threshold) + && Objects.equals(proportion, that.proportion) + && Objects.equals(delay, that.delay) + && Objects.equals(force, that.force) + && Objects.equals(interfaces, that.interfaces) + && Objects.equals(applications, that.applications) + && Objects.equals(interfaceRules, that.interfaceRules) + && Objects.equals(applicationRules, that.applicationRules); } @Override public int hashCode() { - return Objects.hash(key, step, threshold, proportion, delay, force, interfaces, applications, interfaceRules, applicationRules); + return Objects.hash( + key, + step, + threshold, + proportion, + delay, + force, + interfaces, + applications, + interfaceRules, + applicationRules); } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/model/SubMigrationRule.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/model/SubMigrationRule.java index cbc2b62c02..6650bc2988 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/model/SubMigrationRule.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/model/SubMigrationRule.java @@ -64,7 +64,7 @@ public class SubMigrationRule { return interfaceMigrationRule; } - public SubMigrationRule(){} + public SubMigrationRule() {} public SubMigrationRule(String serviceKey, MigrationStep step, Float threshold, Integer proportion) { this.serviceKey = serviceKey; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java index 5d01197275..8c6b0ca799 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/AbstractConfiguratorListener.java @@ -46,7 +46,8 @@ import static org.apache.dubbo.rpc.cluster.Constants.TYPE_KEY; * AbstractConfiguratorListener */ public abstract class AbstractConfiguratorListener implements ConfigurationListener { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractConfiguratorListener.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(AbstractConfiguratorListener.class); protected List configurators = Collections.emptyList(); protected GovernanceRuleRepository ruleRepository; @@ -57,7 +58,8 @@ public abstract class AbstractConfiguratorListener implements ConfigurationListe public AbstractConfiguratorListener(ModuleModel moduleModel) { this.moduleModel = moduleModel; - ruleRepository = moduleModel.getExtensionLoader(GovernanceRuleRepository.class).getDefaultExtension(); + ruleRepository = + moduleModel.getExtensionLoader(GovernanceRuleRepository.class).getDefaultExtension(); initSecurityKey(); } @@ -86,8 +88,8 @@ public abstract class AbstractConfiguratorListener implements ConfigurationListe @Override public void process(ConfigChangedEvent event) { if (logger.isInfoEnabled()) { - logger.info("Notification of overriding rule, change type is: " + event.getChangeType() + - ", raw config content is:\n " + event.getContent()); + logger.info("Notification of overriding rule, change type is: " + event.getChangeType() + + ", raw config content is:\n " + event.getContent()); } if (event.getChangeType().equals(ConfigChangeType.DELETED)) { @@ -110,16 +112,19 @@ public abstract class AbstractConfiguratorListener implements ConfigurationListe } catch (Exception e) { // 1-14 - Failed to parse raw dynamic config. - logger.warn(REGISTRY_FAILED_PARSE_DYNAMIC_CONFIG, "", "", - "Failed to parse raw dynamic config and it will not take effect, the raw config is: " - + rawConfig + ", cause: " + e.getMessage()); + logger.warn( + REGISTRY_FAILED_PARSE_DYNAMIC_CONFIG, + "", + "", + "Failed to parse raw dynamic config and it will not take effect, the raw config is: " + rawConfig + + ", cause: " + e.getMessage()); return false; } List safeUrls = urls.stream() - .map(url -> url.removeParameters(securityKey)) - .map(url -> url.setScopeModel(moduleModel)) - .collect(Collectors.toList()); + .map(url -> url.removeParameters(securityKey)) + .map(url -> url.setScopeModel(moduleModel)) + .collect(Collectors.toList()); configurators = Configurator.toConfigurators(safeUrls).orElse(configurators); return true; } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/DynamicDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/DynamicDirectory.java index 1f57e972d7..87a1871067 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/DynamicDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/DynamicDirectory.java @@ -57,7 +57,6 @@ import static org.apache.dubbo.registry.Constants.SIMPLIFIED_KEY; import static org.apache.dubbo.registry.integration.InterfaceCompatibleRegistryProtocol.DEFAULT_REGISTER_CONSUMER_KEYS; import static org.apache.dubbo.remoting.Constants.CHECK_KEY; - /** * DynamicDirectory */ @@ -83,6 +82,7 @@ public abstract class DynamicDirectory extends AbstractDirectory implement * Initialization at construction time, assertion not null, and always assign non-null value */ protected volatile URL directoryUrl; + protected final boolean multiGroup; /** @@ -94,6 +94,7 @@ public abstract class DynamicDirectory extends AbstractDirectory implement * Initialization at the time of injection, the assertion is not null */ protected Registry registry; + protected volatile boolean forbidden = false; protected boolean shouldRegister; protected boolean shouldSimplified; @@ -102,6 +103,7 @@ public abstract class DynamicDirectory extends AbstractDirectory implement * Initialization at construction time, assertion not null, and always assign not null value */ protected volatile URL subscribeUrl; + protected volatile URL registeredConsumerUrl; /** @@ -123,7 +125,6 @@ public abstract class DynamicDirectory extends AbstractDirectory implement private volatile InvokersChangedListener invokersChangedListener; private volatile boolean invokersChanged; - public DynamicDirectory(Class serviceType, URL url) { super(url, true); @@ -150,7 +151,8 @@ public abstract class DynamicDirectory extends AbstractDirectory implement String group = directoryUrl.getGroup(""); this.multiGroup = group != null && (ANY_VALUE.equals(group) || group.contains(",")); - this.shouldFailFast = Boolean.parseBoolean(ConfigurationUtils.getProperty(moduleModel, Constants.SHOULD_FAIL_FAST_KEY, "true")); + this.shouldFailFast = Boolean.parseBoolean( + ConfigurationUtils.getProperty(moduleModel, Constants.SHOULD_FAIL_FAST_KEY, "true")); } @Override @@ -190,14 +192,17 @@ public abstract class DynamicDirectory extends AbstractDirectory implement } @Override - public List> doList(SingleRouterChain singleRouterChain, - BitList> invokers, Invocation invocation) { + public List> doList( + SingleRouterChain singleRouterChain, BitList> invokers, Invocation invocation) { if (forbidden && shouldFailFast) { // 1. No service provider 2. Service providers are disabled - throw new RpcException(RpcException.FORBIDDEN_EXCEPTION, "No provider available from registry " + - this + " for service " + getConsumerUrl().getServiceKey() + " on consumer " + - NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion() + - ", please check status of providers(disabled, not registered or in blacklist)."); + throw new RpcException( + RpcException.FORBIDDEN_EXCEPTION, + "No provider available from registry " + this + + " for service " + getConsumerUrl().getServiceKey() + " on consumer " + + NetUtils.getLocalHost() + + " use dubbo version " + Version.getVersion() + + ", please check status of providers(disabled, not registered or in blacklist)."); } if (multiGroup) { @@ -210,8 +215,12 @@ public abstract class DynamicDirectory extends AbstractDirectory implement return result == null ? BitList.emptyList() : result; } catch (Throwable t) { // 2-1 - Failed to execute routing. - logger.error(CLUSTER_FAILED_SITE_SELECTION, "", "", - "Failed to execute router: " + getUrl() + ", cause: " + t.getMessage(), t); + logger.error( + CLUSTER_FAILED_SITE_SELECTION, + "", + "", + "Failed to execute router: " + getUrl() + ", cause: " + t.getMessage(), + t); return BitList.emptyList(); } @@ -270,11 +279,11 @@ public abstract class DynamicDirectory extends AbstractDirectory implement public void setRegisteredConsumerUrl(URL url) { if (!shouldSimplified) { - this.registeredConsumerUrl = url.addParameters(CATEGORY_KEY, CONSUMERS_CATEGORY, CHECK_KEY, - String.valueOf(false)); + this.registeredConsumerUrl = + url.addParameters(CATEGORY_KEY, CONSUMERS_CATEGORY, CHECK_KEY, String.valueOf(false)); } else { - this.registeredConsumerUrl = URL.valueOf(url, DEFAULT_REGISTER_CONSUMER_KEYS, null).addParameters( - CATEGORY_KEY, CONSUMERS_CATEGORY, CHECK_KEY, String.valueOf(false)); + this.registeredConsumerUrl = URL.valueOf(url, DEFAULT_REGISTER_CONSUMER_KEYS, null) + .addParameters(CATEGORY_KEY, CONSUMERS_CATEGORY, CHECK_KEY, String.valueOf(false)); } } @@ -310,8 +319,12 @@ public abstract class DynamicDirectory extends AbstractDirectory implement } } catch (Throwable t) { // 1-8: Failed to unregister / unsubscribe url on destroy. - logger.warn(REGISTRY_FAILED_DESTROY_UNREGISTER_URL, "", "", - "unexpected error when unregister service " + serviceKey + " from registry: " + registry.getUrl(), t); + logger.warn( + REGISTRY_FAILED_DESTROY_UNREGISTER_URL, + "", + "", + "unexpected error when unregister service " + serviceKey + " from registry: " + registry.getUrl(), + t); } // unsubscribe. @@ -321,12 +334,18 @@ public abstract class DynamicDirectory extends AbstractDirectory implement } } catch (Throwable t) { // 1-8: Failed to unregister / unsubscribe url on destroy. - logger.warn(REGISTRY_FAILED_DESTROY_UNREGISTER_URL, "", "", - "unexpected error when unsubscribe service " + serviceKey + " from registry: " + registry.getUrl(), t); + logger.warn( + REGISTRY_FAILED_DESTROY_UNREGISTER_URL, + "", + "", + "unexpected error when unsubscribe service " + serviceKey + " from registry: " + registry.getUrl(), + t); } - ExtensionLoader addressListenerExtensionLoader = getUrl().getOrDefaultModuleModel().getExtensionLoader(AddressListener.class); - List supportedListeners = addressListenerExtensionLoader.getActivateExtension(getUrl(), (String[]) null); + ExtensionLoader addressListenerExtensionLoader = + getUrl().getOrDefaultModuleModel().getExtensionLoader(AddressListener.class); + List supportedListeners = + addressListenerExtensionLoader.getActivateExtension(getUrl(), (String[]) null); if (CollectionUtils.isNotEmpty(supportedListeners)) { for (AddressListener addressListener : supportedListeners) { addressListener.destroy(getConsumerUrl(), this); @@ -338,8 +357,7 @@ public abstract class DynamicDirectory extends AbstractDirectory implement destroyAllInvokers(); } catch (Throwable t) { // 1-15 - Failed to destroy service. - logger.warn(REGISTRY_FAILED_DESTROY_SERVICE, "", "", - "Failed to destroy service " + serviceKey, t); + logger.warn(REGISTRY_FAILED_DESTROY_SERVICE, "", "", "Failed to destroy service " + serviceKey, t); } routerChain.destroy(); invokersChangedListener = null; @@ -355,8 +373,7 @@ public abstract class DynamicDirectory extends AbstractDirectory implement destroyAllInvokers(); } catch (Throwable t) { // 1-15 - Failed to destroy service. - logger.warn(REGISTRY_FAILED_DESTROY_SERVICE, "", "", - "Failed to destroy service " + serviceKey, t); + logger.warn(REGISTRY_FAILED_DESTROY_SERVICE, "", "", "Failed to destroy service " + serviceKey, t); } } @@ -384,5 +401,4 @@ public abstract class DynamicDirectory extends AbstractDirectory implement protected abstract void destroyAllInvokers(); protected abstract void refreshOverrideAndInvoker(List urls); - } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/ExporterFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/ExporterFactory.java index 5eebc1bcaa..f9d89ebf1a 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/ExporterFactory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/ExporterFactory.java @@ -26,14 +26,13 @@ public class ExporterFactory { private final Map> exporters = new ConcurrentHashMap<>(); protected ReferenceCountExporter createExporter(String providerKey, Callable> exporterProducer) { - return exporters.computeIfAbsent(providerKey, - key -> { - try { - return new ReferenceCountExporter<>(exporterProducer.call(), key, this); - } catch (Exception e) { - throw new RuntimeException(e); - } - }); + return exporters.computeIfAbsent(providerKey, key -> { + try { + return new ReferenceCountExporter<>(exporterProducer.call(), key, this); + } catch (Exception e) { + throw new RuntimeException(e); + } + }); } protected void remove(String key, ReferenceCountExporter exporter) { diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/InterfaceCompatibleRegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/InterfaceCompatibleRegistryProtocol.java index 674747474f..ba3e936d16 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/InterfaceCompatibleRegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/InterfaceCompatibleRegistryProtocol.java @@ -59,16 +59,22 @@ public class InterfaceCompatibleRegistryProtocol extends RegistryProtocol { } @Override - public ClusterInvoker getServiceDiscoveryInvoker(Cluster cluster, Registry registry, Class type, URL url) { + public ClusterInvoker getServiceDiscoveryInvoker( + Cluster cluster, Registry registry, Class type, URL url) { registry = getRegistry(super.getRegistryUrl(url)); DynamicDirectory directory = new ServiceDiscoveryRegistryDirectory<>(type, url); return doCreateInvoker(directory, cluster, registry, type); } @Override - protected ClusterInvoker getMigrationInvoker(RegistryProtocol registryProtocol, Cluster cluster, Registry registry, Class type, URL url, URL consumerUrl) { -// ClusterInvoker invoker = getInvoker(cluster, registry, type, url); + protected ClusterInvoker getMigrationInvoker( + RegistryProtocol registryProtocol, + Cluster cluster, + Registry registry, + Class type, + URL url, + URL consumerUrl) { + // ClusterInvoker invoker = getInvoker(cluster, registry, type, url); return new MigrationInvoker(registryProtocol, cluster, registry, type, url, consumerUrl); } - } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/ReferenceCountExporter.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/ReferenceCountExporter.java index bcdce7172f..a86167a507 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/ReferenceCountExporter.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/ReferenceCountExporter.java @@ -51,12 +51,8 @@ public class ReferenceCountExporter implements Exporter { } @Override - public void register() { - - } + public void register() {} @Override - public void unregister() { - - } + public void unregister() {} } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java index c9f0fa7d1b..11c9c80c10 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java @@ -65,8 +65,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.DISABLED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_REGISTER_MODE; import static org.apache.dubbo.common.constants.CommonConstants.EXT_PROTOCOL; +import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_REGISTER_MODE; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_INIT_SERIALIZATION_OPTIMIZER; @@ -94,7 +94,6 @@ import static org.apache.dubbo.rpc.Constants.MOCK_KEY; import static org.apache.dubbo.rpc.cluster.Constants.ROUTER_KEY; import static org.apache.dubbo.rpc.model.ScopeModelUtil.getModuleModel; - /** * RegistryDirectory */ @@ -114,6 +113,7 @@ public class RegistryDirectory extends DynamicDirectory { * The initial value is null and the midway may be assigned to null, please use the local variable reference */ protected volatile Set cachedInvokerUrls; + private final ModuleModel moduleModel; public RegistryDirectory(Class serviceType, URL url) { @@ -130,35 +130,48 @@ public class RegistryDirectory extends DynamicDirectory { if (StringUtils.isNotBlank(queryProtocols)) { String[] acceptProtocols = queryProtocols.split(","); for (String acceptProtocol : acceptProtocols) { - if (!moduleModel.getApplicationModel().getExtensionLoader(Protocol.class).hasExtension(acceptProtocol)) { - throw new IllegalStateException("No such extension org.apache.dubbo.rpc.Protocol by name " + acceptProtocol + ", please check whether related SPI module is missing"); + if (!moduleModel + .getApplicationModel() + .getExtensionLoader(Protocol.class) + .hasExtension(acceptProtocol)) { + throw new IllegalStateException("No such extension org.apache.dubbo.rpc.Protocol by name " + + acceptProtocol + ", please check whether related SPI module is missing"); } } } ApplicationModel applicationModel = url.getApplicationModel(); - String registryClusterName = registry.getUrl().getParameter(RegistryConstants.REGISTRY_CLUSTER_KEY, registry.getUrl().getParameter(PROTOCOL_KEY)); - MetricsEventBus.post(RegistryEvent.toSubscribeEvent(applicationModel,registryClusterName), () -> - { - super.subscribe(url); - return null; - } - ); - if (moduleModel.modelEnvironment().getConfiguration().convert(Boolean.class, org.apache.dubbo.registry.Constants.ENABLE_CONFIGURATION_LISTEN, true)) { + String registryClusterName = registry.getUrl() + .getParameter( + RegistryConstants.REGISTRY_CLUSTER_KEY, + registry.getUrl().getParameter(PROTOCOL_KEY)); + MetricsEventBus.post(RegistryEvent.toSubscribeEvent(applicationModel, registryClusterName), () -> { + super.subscribe(url); + return null; + }); + if (moduleModel + .modelEnvironment() + .getConfiguration() + .convert(Boolean.class, org.apache.dubbo.registry.Constants.ENABLE_CONFIGURATION_LISTEN, true)) { consumerConfigurationListener.addNotifyListener(this); referenceConfigurationListener = new ReferenceConfigurationListener(moduleModel, this, url); } } private ConsumerConfigurationListener getConsumerConfigurationListener(ModuleModel moduleModel) { - return moduleModel.getBeanFactory().getOrRegisterBean(ConsumerConfigurationListener.class, - type -> new ConsumerConfigurationListener(moduleModel)); + return moduleModel + .getBeanFactory() + .getOrRegisterBean( + ConsumerConfigurationListener.class, type -> new ConsumerConfigurationListener(moduleModel)); } @Override public void unSubscribe(URL url) { super.unSubscribe(url); - if (moduleModel.modelEnvironment().getConfiguration().convert(Boolean.class, org.apache.dubbo.registry.Constants.ENABLE_CONFIGURATION_LISTEN, true)) { + if (moduleModel + .modelEnvironment() + .getConfiguration() + .convert(Boolean.class, org.apache.dubbo.registry.Constants.ENABLE_CONFIGURATION_LISTEN, true)) { consumerConfigurationListener.removeNotifyListener(this); if (referenceConfigurationListener != null) { referenceConfigurationListener.stop(); @@ -169,7 +182,10 @@ public class RegistryDirectory extends DynamicDirectory { @Override public void destroy() { super.destroy(); - if (moduleModel.modelEnvironment().getConfiguration().convert(Boolean.class, org.apache.dubbo.registry.Constants.ENABLE_CONFIGURATION_LISTEN, true)) { + if (moduleModel + .modelEnvironment() + .getConfiguration() + .convert(Boolean.class, org.apache.dubbo.registry.Constants.ENABLE_CONFIGURATION_LISTEN, true)) { consumerConfigurationListener.removeNotifyListener(this); if (referenceConfigurationListener != null) { referenceConfigurationListener.stop(); @@ -184,12 +200,15 @@ public class RegistryDirectory extends DynamicDirectory { } Map> categoryUrls = urls.stream() - .filter(Objects::nonNull) - .filter(this::isValidCategory) - .filter(this::isNotCompatibleFor26x) - .collect(Collectors.groupingBy(this::judgeCategory)); + .filter(Objects::nonNull) + .filter(this::isValidCategory) + .filter(this::isNotCompatibleFor26x) + .collect(Collectors.groupingBy(this::judgeCategory)); - if (moduleModel.modelEnvironment().getConfiguration().convert(Boolean.class, ENABLE_26X_CONFIGURATION_LISTEN, true)) { + if (moduleModel + .modelEnvironment() + .getConfiguration() + .convert(Boolean.class, ENABLE_26X_CONFIGURATION_LISTEN, true)) { List configuratorURLs = categoryUrls.getOrDefault(CONFIGURATORS_CATEGORY, Collections.emptyList()); this.configurators = Configurator.toConfigurators(configuratorURLs).orElse(this.configurators); @@ -201,8 +220,10 @@ public class RegistryDirectory extends DynamicDirectory { List providerURLs = categoryUrls.getOrDefault(PROVIDERS_CATEGORY, Collections.emptyList()); // 3.x added for extend URL address - ExtensionLoader addressListenerExtensionLoader = getUrl().getOrDefaultModuleModel().getExtensionLoader(AddressListener.class); - List supportedListeners = addressListenerExtensionLoader.getActivateExtension(getUrl(), (String[]) null); + ExtensionLoader addressListenerExtensionLoader = + getUrl().getOrDefaultModuleModel().getExtensionLoader(AddressListener.class); + List supportedListeners = + addressListenerExtensionLoader.getActivateExtension(getUrl(), (String[]) null); if (supportedListeners != null && !supportedListeners.isEmpty()) { for (AddressListener addressListener : supportedListeners) { providerURLs = addressListener.notify(providerURLs, getConsumerUrl(), this); @@ -251,11 +272,11 @@ public class RegistryDirectory extends DynamicDirectory { Assert.notNull(invokerUrls, "invokerUrls should not be null"); if (invokerUrls.size() == 1 - && invokerUrls.get(0) != null - && EMPTY_PROTOCOL.equals(invokerUrls.get(0).getProtocol())) { - refreshRouter(BitList.emptyList(), () -> - this.forbidden = true // Forbid to access - ); + && invokerUrls.get(0) != null + && EMPTY_PROTOCOL.equals(invokerUrls.get(0).getProtocol())) { + refreshRouter( + BitList.emptyList(), () -> this.forbidden = true // Forbid to access + ); destroyAllInvokers(); // Close all invokers } else { this.forbidden = false; // Allow to access @@ -268,30 +289,38 @@ public class RegistryDirectory extends DynamicDirectory { if (invokerUrls.isEmpty()) { if (CollectionUtils.isNotEmpty(localCachedInvokerUrls)) { // 1-4 Empty address. - logger.warn(REGISTRY_EMPTY_ADDRESS, "configuration ", "", - "Service" + serviceKey + " received empty address list with no EMPTY protocol set, trigger empty protection."); + logger.warn( + REGISTRY_EMPTY_ADDRESS, + "configuration ", + "", + "Service" + serviceKey + + " received empty address list with no EMPTY protocol set, trigger empty protection."); invokerUrls.addAll(localCachedInvokerUrls); } } else { localCachedInvokerUrls = new HashSet<>(); - localCachedInvokerUrls.addAll(invokerUrls);//Cached invoker urls, convenient for comparison + localCachedInvokerUrls.addAll(invokerUrls); // Cached invoker urls, convenient for comparison this.cachedInvokerUrls = localCachedInvokerUrls; } if (invokerUrls.isEmpty()) { return; } - // use local reference to avoid NPE as this.urlInvokerMap will be set null concurrently at destroyAllInvokers(). + // use local reference to avoid NPE as this.urlInvokerMap will be set null concurrently at + // destroyAllInvokers(). Map> localUrlInvokerMap = this.urlInvokerMap; // can't use local reference as oldUrlInvokerMap's mappings might be removed directly at toInvokers(). Map> oldUrlInvokerMap = null; if (localUrlInvokerMap != null) { - // the initial capacity should be set greater than the maximum number of entries divided by the load factor to avoid resizing. - oldUrlInvokerMap = new LinkedHashMap<>(Math.round(1 + localUrlInvokerMap.size() / DEFAULT_HASHMAP_LOAD_FACTOR)); + // the initial capacity should be set greater than the maximum number of entries divided by the load + // factor to avoid resizing. + oldUrlInvokerMap = + new LinkedHashMap<>(Math.round(1 + localUrlInvokerMap.size() / DEFAULT_HASHMAP_LOAD_FACTOR)); localUrlInvokerMap.forEach(oldUrlInvokerMap::put); } - Map> newUrlInvokerMap = toInvokers(oldUrlInvokerMap, invokerUrls);// Translate url list to Invoker map + Map> newUrlInvokerMap = + toInvokers(oldUrlInvokerMap, invokerUrls); // Translate url list to Invoker map /* * If the calculation is wrong, it is not processed. @@ -306,17 +335,19 @@ public class RegistryDirectory extends DynamicDirectory { // 3-1 - Failed to convert the URL address into Invokers. logger.error( - PROXY_FAILED_CONVERT_URL, "inconsistency between the client protocol and the protocol of the server", - "", "urls to invokers error", - new IllegalStateException( - "urls to invokers error. invokerUrls.size :" + - invokerUrls.size() + ", invoker.size :0. urls :" + invokerUrls.toString())); + PROXY_FAILED_CONVERT_URL, + "inconsistency between the client protocol and the protocol of the server", + "", + "urls to invokers error", + new IllegalStateException("urls to invokers error. invokerUrls.size :" + invokerUrls.size() + + ", invoker.size :0. urls :" + invokerUrls.toString())); return; } List> newInvokers = Collections.unmodifiableList(new ArrayList<>(newUrlInvokerMap.values())); - BitList> finalInvokers = multiGroup ? new BitList<>(toMergeInvokerList(newInvokers)) : new BitList<>(newInvokers); + BitList> finalInvokers = + multiGroup ? new BitList<>(toMergeInvokerList(newInvokers)) : new BitList<>(newInvokers); // pre-route and build cache refreshRouter(finalInvokers.clone(), () -> this.setInvokers(finalInvokers)); this.urlInvokerMap = newUrlInvokerMap; @@ -331,13 +362,13 @@ public class RegistryDirectory extends DynamicDirectory { this.invokersChanged(); } - logger.info("Received invokers changed event from registry. " + - "Registry type: interface. " + - "Service Key: " + getConsumerUrl().getServiceKey() + ". " + - "Urls Size : " + invokerUrls.size() + ". " + - "Invokers Size : " + getInvokers().size() + ". " + - "Available Size: " + getValidInvokers().size() + ". " + - "Available Invokers : " + joinValidInvokerAddresses()); + logger.info("Received invokers changed event from registry. " + "Registry type: interface. " + + "Service Key: " + + getConsumerUrl().getServiceKey() + ". " + "Urls Size : " + + invokerUrls.size() + ". " + "Invokers Size : " + + getInvokers().size() + ". " + "Available Size: " + + getValidInvokers().size() + ". " + "Available Invokers : " + + joinValidInvokerAddresses()); } private List> toMergeInvokerList(List> invokers) { @@ -404,7 +435,8 @@ public class RegistryDirectory extends DynamicDirectory { * @return invokers */ private Map> toInvokers(Map> oldUrlInvokerMap, List urls) { - Map> newUrlInvokerMap = new ConcurrentHashMap<>(urls == null ? 1 : (int) (urls.size() / 0.75f + 1)); + Map> newUrlInvokerMap = + new ConcurrentHashMap<>(urls == null ? 1 : (int) (urls.size() / 0.75f + 1)); if (urls == null || urls.isEmpty()) { return newUrlInvokerMap; } @@ -415,7 +447,8 @@ public class RegistryDirectory extends DynamicDirectory { } URL url = mergeUrl(providerUrl); - // get the effective protocol that this consumer should consume based on consumer side protocol configuration and available protocols in address pool. + // get the effective protocol that this consumer should consume based on consumer side protocol + // configuration and available protocols in address pool. String effectiveProtocol = getEffectiveProtocol(queryProtocols, url); if (!effectiveProtocol.equals(url.getProtocol())) { url = url.setProtocol(effectiveProtocol); @@ -441,13 +474,23 @@ public class RegistryDirectory extends DynamicDirectory { // Thrown by AbstractProtocol.optimizeSerialization() if (t instanceof RpcException && t.getMessage().contains("serialization optimizer")) { // 4-2 - serialization optimizer class initialization failed. - logger.error(PROTOCOL_FAILED_INIT_SERIALIZATION_OPTIMIZER, "typo in optimizer class", "", - "Failed to refer invoker for interface:" + serviceType + ",url:(" + url + ")" + t.getMessage(), t); + logger.error( + PROTOCOL_FAILED_INIT_SERIALIZATION_OPTIMIZER, + "typo in optimizer class", + "", + "Failed to refer invoker for interface:" + serviceType + ",url:(" + url + ")" + + t.getMessage(), + t); } else { // 4-3 - Failed to refer invoker by other reason. - logger.error(PROTOCOL_FAILED_REFER_INVOKER, "", "", - "Failed to refer invoker for interface:" + serviceType + ",url:(" + url + ")" + t.getMessage(), t); + logger.error( + PROTOCOL_FAILED_REFER_INVOKER, + "", + "", + "Failed to refer invoker for interface:" + serviceType + ",url:(" + url + ")" + + t.getMessage(), + t); } } if (invoker != null) { // Put new invoker in cache @@ -512,15 +555,23 @@ public class RegistryDirectory extends DynamicDirectory { return false; } - if (!getUrl().getOrDefaultFrameworkModel().getExtensionLoader(Protocol.class).hasExtension(providerUrl.getProtocol())) { + if (!getUrl().getOrDefaultFrameworkModel() + .getExtensionLoader(Protocol.class) + .hasExtension(providerUrl.getProtocol())) { // 4-1 - Unsupported protocol - logger.error(PROTOCOL_UNSUPPORTED, "protocol extension does not installed", "", "Unsupported protocol.", - new IllegalStateException("Unsupported protocol " + providerUrl.getProtocol() + - " in notified url: " + providerUrl + " from registry " + getUrl().getAddress() + - " to consumer " + NetUtils.getLocalHost() + ", supported protocol: " + - getUrl().getOrDefaultFrameworkModel().getExtensionLoader(Protocol.class).getSupportedExtensions())); + logger.error( + PROTOCOL_UNSUPPORTED, + "protocol extension does not installed", + "", + "Unsupported protocol.", + new IllegalStateException("Unsupported protocol " + providerUrl.getProtocol() + " in notified url: " + + providerUrl + " from registry " + getUrl().getAddress() + " to consumer " + + NetUtils.getLocalHost() + ", supported protocol: " + + getUrl().getOrDefaultFrameworkModel() + .getExtensionLoader(Protocol.class) + .getSupportedExtensions())); return false; } @@ -538,9 +589,16 @@ public class RegistryDirectory extends DynamicDirectory { if (providerUrl instanceof ServiceAddressURL) { providerUrl = overrideWithConfigurator(providerUrl); } else { - providerUrl = moduleModel.getApplicationModel().getBeanFactory().getBean(ClusterUtils.class).mergeUrl(providerUrl, queryMap); // Merge the consumer side parameters + providerUrl = moduleModel + .getApplicationModel() + .getBeanFactory() + .getBean(ClusterUtils.class) + .mergeUrl(providerUrl, queryMap); // Merge the consumer side parameters providerUrl = overrideWithConfigurator(providerUrl); - providerUrl = providerUrl.addParameter(Constants.CHECK_KEY, String.valueOf(false)); // Do not check whether the connection is successful or not, always create Invoker! + providerUrl = providerUrl.addParameter( + Constants.CHECK_KEY, + String.valueOf( + false)); // Do not check whether the connection is successful or not, always create Invoker! } // FIXME, kept for mock @@ -548,9 +606,9 @@ public class RegistryDirectory extends DynamicDirectory { providerUrl = providerUrl.removeParameter(MOCK_KEY); } - if ((providerUrl.getPath() == null || providerUrl.getPath() - .length() == 0) && DUBBO_PROTOCOL.equals(providerUrl.getProtocol())) { // Compatible version 1.0 - //fix by tony.chenl DUBBO-44 + if ((providerUrl.getPath() == null || providerUrl.getPath().length() == 0) + && DUBBO_PROTOCOL.equals(providerUrl.getProtocol())) { // Compatible version 1.0 + // fix by tony.chenl DUBBO-44 String path = directoryUrl.getServiceInterface(); if (path != null) { int i = path.indexOf('/'); @@ -591,18 +649,19 @@ public class RegistryDirectory extends DynamicDirectory { String appName = interfaceAddressURL.getApplication(); String side = interfaceAddressURL.getSide(); overriddenURL = URLBuilder.from(interfaceAddressURL) - .clearParameters() - .addParameter(APPLICATION_KEY, appName) - .addParameter(SIDE_KEY, side).build(); + .clearParameters() + .addParameter(APPLICATION_KEY, appName) + .addParameter(SIDE_KEY, side) + .build(); } for (Configurator configurator : configurators) { overriddenURL = configurator.configure(overriddenURL); } url = new DubboServiceAddressURL( - interfaceAddressURL.getUrlAddress(), - interfaceAddressURL.getUrlParam(), - interfaceAddressURL.getConsumerURL(), - (ServiceConfigURL) overriddenURL); + interfaceAddressURL.getUrlAddress(), + interfaceAddressURL.getUrlParam(), + interfaceAddressURL.getConsumerURL(), + (ServiceConfigURL) overriddenURL); } else { for (Configurator configurator : configurators) { url = configurator.configure(url); @@ -624,8 +683,12 @@ public class RegistryDirectory extends DynamicDirectory { invoker.destroy(); } catch (Throwable t) { // 1-15 - Failed to destroy service - logger.warn(REGISTRY_FAILED_DESTROY_SERVICE, "", "", - "Failed to destroy service " + serviceKey + " to provider " + invoker.getUrl(), t); + logger.warn( + REGISTRY_FAILED_DESTROY_SERVICE, + "", + "", + "Failed to destroy service " + serviceKey + " to provider " + invoker.getUrl(), + t); } } localUrlInvokerMap.clear(); @@ -655,12 +718,18 @@ public class RegistryDirectory extends DynamicDirectory { logger.debug("destroy invoker[" + invoker.getUrl() + "] success. "); } } catch (Exception e) { - logger.warn(REGISTRY_FAILED_DESTROY_SERVICE, "", "", "destroy invoker[" + invoker.getUrl() + "] failed. " + e.getMessage(), e); + logger.warn( + REGISTRY_FAILED_DESTROY_SERVICE, + "", + "", + "destroy invoker[" + invoker.getUrl() + "] failed. " + e.getMessage(), + e); } } } - logger.info("New url total size, " + newUrlInvokerMap.size() + ", destroyed total size " + oldUrlInvokerMap.size()); + logger.info( + "New url total size, " + newUrlInvokerMap.size() + ", destroyed total size " + oldUrlInvokerMap.size()); } /** @@ -672,17 +741,21 @@ public class RegistryDirectory extends DynamicDirectory { private boolean isValidCategory(URL url) { String category = url.getCategory(DEFAULT_CATEGORY); - if ((ROUTERS_CATEGORY.equals(category) || ROUTE_PROTOCOL.equals(url.getProtocol())) || - PROVIDERS_CATEGORY.equals(category) || - CONFIGURATORS_CATEGORY.equals(category) || DYNAMIC_CONFIGURATORS_CATEGORY.equals(category) || - APP_DYNAMIC_CONFIGURATORS_CATEGORY.equals(category)) { + if ((ROUTERS_CATEGORY.equals(category) || ROUTE_PROTOCOL.equals(url.getProtocol())) + || PROVIDERS_CATEGORY.equals(category) + || CONFIGURATORS_CATEGORY.equals(category) + || DYNAMIC_CONFIGURATORS_CATEGORY.equals(category) + || APP_DYNAMIC_CONFIGURATORS_CATEGORY.equals(category)) { return true; } // 1-16 - Unsupported category in NotifyListener - logger.warn(REGISTRY_UNSUPPORTED_CATEGORY, "", "", - "Unsupported category " + category + " in notified url: " + url + " from registry " + - getUrl().getAddress() + " to consumer " + NetUtils.getLocalHost()); + logger.warn( + REGISTRY_UNSUPPORTED_CATEGORY, + "", + "", + "Unsupported category " + category + " in notified url: " + url + " from registry " + + getUrl().getAddress() + " to consumer " + NetUtils.getLocalHost()); return false; } @@ -690,9 +763,9 @@ public class RegistryDirectory extends DynamicDirectory { @Override protected Map getDirectoryMeta() { String registryKey = Optional.ofNullable(getRegistry()) - .map(Registry::getUrl) - .map(url -> url.getParameter(RegistryConstants.REGISTRY_CLUSTER_KEY, url.getProtocol())) - .orElse("unknown"); + .map(Registry::getUrl) + .map(url -> url.getParameter(RegistryConstants.REGISTRY_CLUSTER_KEY, url.getProtocol())) + .orElse("unknown"); Map metas = new HashMap<>(); metas.put(REGISTRY_KEY, registryKey); metas.put(REGISTER_MODE_KEY, INTERFACE_REGISTER_MODE); @@ -749,8 +822,6 @@ public class RegistryDirectory extends DynamicDirectory { @Override public String toString() { - return "RegistryDirectory(" + - "registry: " + getUrl().getAddress() + - ")-" + super.toString(); + return "RegistryDirectory(" + "registry: " + getUrl().getAddress() + ")-" + super.toString(); } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java index a15f1ad0cf..5a5fc151b9 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java @@ -155,7 +155,8 @@ import static org.apache.dubbo.rpc.model.ScopeModelUtil.getApplicationModel; */ public class RegistryProtocol implements Protocol, ScopeModelAware { public static final String[] DEFAULT_REGISTER_PROVIDER_KEYS = { - APPLICATION_KEY, CODEC_KEY, EXCHANGER_KEY, SERIALIZATION_KEY, PREFER_SERIALIZATION_KEY, CLUSTER_KEY, CONNECTIONS_KEY, DEPRECATED_KEY, + APPLICATION_KEY, CODEC_KEY, EXCHANGER_KEY, SERIALIZATION_KEY, PREFER_SERIALIZATION_KEY, CLUSTER_KEY, + CONNECTIONS_KEY, DEPRECATED_KEY, GROUP_KEY, LOADBALANCE_KEY, MOCK_KEY, PATH_KEY, TIMEOUT_KEY, TOKEN_KEY, VERSION_KEY, WARMUP_KEY, WEIGHT_KEY, DUBBO_VERSION_KEY, RELEASE_KEY, SIDE_KEY, IPV6_KEY, PACKABLE_METHOD_FACTORY_KEY }; @@ -167,31 +168,35 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RegistryProtocol.class); private final Map serviceConfigurationListeners = new ConcurrentHashMap<>(); - //To solve the problem of RMI repeated exposure port conflicts, the services that have been exposed are no longer exposed. - //provider url <--> registry url <--> exporter + // To solve the problem of RMI repeated exposure port conflicts, the services that have been exposed are no longer + // exposed. + // provider url <--> registry url <--> exporter private final Map>> bounds = new ConcurrentHashMap<>(); protected Protocol protocol; protected ProxyFactory proxyFactory; private ConcurrentMap reExportFailedTasks = new ConcurrentHashMap<>(); - private HashedWheelTimer retryTimer = new HashedWheelTimer(new NamedThreadFactory("DubboReexportTimer", true), DEFAULT_REGISTRY_RETRY_PERIOD, TimeUnit.MILLISECONDS, 128); + private HashedWheelTimer retryTimer = new HashedWheelTimer( + new NamedThreadFactory("DubboReexportTimer", true), + DEFAULT_REGISTRY_RETRY_PERIOD, + TimeUnit.MILLISECONDS, + 128); private FrameworkModel frameworkModel; private ExporterFactory exporterFactory; - //Filter the parameters that do not need to be output in url(Starting with .) + // Filter the parameters that do not need to be output in url(Starting with .) private static String[] getFilteredKeys(URL url) { Map params = url.getParameters(); if (CollectionUtils.isNotEmptyMap(params)) { return params.keySet().stream() - .filter(k -> k.startsWith(HIDE_KEY_PREFIX)) - .toArray(String[]::new); + .filter(k -> k.startsWith(HIDE_KEY_PREFIX)) + .toArray(String[]::new); } else { return new String[0]; } } - public RegistryProtocol() { - } + public RegistryProtocol() {} @Override public void setFrameworkModel(FrameworkModel frameworkModel) { @@ -216,29 +221,43 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { Map> map = new HashMap<>(); List applicationModels = frameworkModel.getApplicationModels(); if (applicationModels.size() == 1) { - return applicationModels.get(0).getBeanFactory().getBean(ProviderConfigurationListener.class).getOverrideListeners(); + return applicationModels + .get(0) + .getBeanFactory() + .getBean(ProviderConfigurationListener.class) + .getOverrideListeners(); } else { for (ApplicationModel applicationModel : applicationModels) { - map.putAll(applicationModel.getBeanFactory().getBean(ProviderConfigurationListener.class).getOverrideListeners()); + map.putAll(applicationModel + .getBeanFactory() + .getBean(ProviderConfigurationListener.class) + .getOverrideListeners()); } } return map; } private static void register(Registry registry, URL registeredProviderUrl) { - ApplicationDeployer deployer = registeredProviderUrl.getOrDefaultApplicationModel().getDeployer(); + ApplicationDeployer deployer = + registeredProviderUrl.getOrDefaultApplicationModel().getDeployer(); try { deployer.increaseServiceRefreshCount(); String registryName = Optional.ofNullable(registry.getUrl()) - .map(u -> u.getParameter(RegistryConstants.REGISTRY_CLUSTER_KEY, - UrlUtils.isServiceDiscoveryURL(u) ? u.getParameter(REGISTRY_KEY) : u.getProtocol())) - .filter(StringUtils::isNotEmpty) - .orElse("unknown"); - MetricsEventBus.post(RegistryEvent.toRsEvent(registeredProviderUrl.getApplicationModel(), registeredProviderUrl.getServiceKey(), 1, Collections.singletonList(registryName)), - () -> { - registry.register(registeredProviderUrl); - return null; - }); + .map(u -> u.getParameter( + RegistryConstants.REGISTRY_CLUSTER_KEY, + UrlUtils.isServiceDiscoveryURL(u) ? u.getParameter(REGISTRY_KEY) : u.getProtocol())) + .filter(StringUtils::isNotEmpty) + .orElse("unknown"); + MetricsEventBus.post( + RegistryEvent.toRsEvent( + registeredProviderUrl.getApplicationModel(), + registeredProviderUrl.getServiceKey(), + 1, + Collections.singletonList(registryName)), + () -> { + registry.register(registeredProviderUrl); + return null; + }); } finally { deployer.decreaseServiceRefreshCount(); } @@ -246,10 +265,7 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { private void registerStatedUrl(URL registryUrl, URL registeredProviderUrl, boolean registered) { ProviderModel model = (ProviderModel) registeredProviderUrl.getServiceModel(); - model.addStatedUrl(new ProviderModel.RegisterStatedURL( - registeredProviderUrl, - registryUrl, - registered)); + model.addStatedUrl(new ProviderModel.RegisterStatedURL(registeredProviderUrl, registryUrl, registered)); } @Override @@ -264,12 +280,14 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { // subscription information to cover. final URL overrideSubscribeUrl = getSubscribedOverrideUrl(providerUrl); final OverrideListener overrideSubscribeListener = new OverrideListener(overrideSubscribeUrl, originInvoker); - Map> overrideListeners = getProviderConfigurationListener(overrideSubscribeUrl).getOverrideListeners(); - overrideListeners.computeIfAbsent(overrideSubscribeUrl, k -> new ConcurrentHashSet<>()) - .add(overrideSubscribeListener); + Map> overrideListeners = + getProviderConfigurationListener(overrideSubscribeUrl).getOverrideListeners(); + overrideListeners + .computeIfAbsent(overrideSubscribeUrl, k -> new ConcurrentHashSet<>()) + .add(overrideSubscribeListener); providerUrl = overrideUrlWithConfig(providerUrl, overrideSubscribeListener); - //export invoker + // export invoker final ExporterChangeableWrapper exporter = doLocalExport(originInvoker, providerUrl); // url to registry @@ -285,14 +303,16 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { // register stated url on provider model registerStatedUrl(registryUrl, registeredProviderUrl, register); - exporter.setRegisterUrl(registeredProviderUrl); exporter.setSubscribeUrl(overrideSubscribeUrl); exporter.setNotifyListener(overrideSubscribeListener); exporter.setRegistered(register); ApplicationModel applicationModel = getApplicationModel(providerUrl.getScopeModel()); - if (applicationModel.modelEnvironment().getConfiguration().convert(Boolean.class, ENABLE_26X_CONFIGURATION_LISTEN, true)) { + if (applicationModel + .modelEnvironment() + .getConfiguration() + .convert(Boolean.class, ENABLE_26X_CONFIGURATION_LISTEN, true)) { if (!registry.isServiceDiscovery()) { // Deprecated! Subscribe to override rules in 2.6.x or before. registry.subscribe(overrideSubscribeUrl, overrideSubscribeListener); @@ -300,14 +320,15 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { } notifyExport(exporter); - //Ensure that a new exporter instance is returned every time export + // Ensure that a new exporter instance is returned every time export return new DestroyableExporter<>(exporter); } private void notifyExport(ExporterChangeableWrapper exporter) { ScopeModel scopeModel = exporter.getRegisterUrl().getScopeModel(); - List listeners = ScopeModelUtil.getExtensionLoader(RegistryProtocolListener.class, scopeModel) - .getActivateExtension(exporter.getOriginInvoker().getUrl(), REGISTRY_PROTOCOL_LISTENER_KEY); + List listeners = ScopeModelUtil.getExtensionLoader( + RegistryProtocolListener.class, scopeModel) + .getActivateExtension(exporter.getOriginInvoker().getUrl(), REGISTRY_PROTOCOL_LISTENER_KEY); if (CollectionUtils.isNotEmpty(listeners)) { for (RegistryProtocolListener listener : listeners) { listener.onExport(this, exporter); @@ -319,7 +340,8 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { ProviderConfigurationListener providerConfigurationListener = getProviderConfigurationListener(providerUrl); providerUrl = providerConfigurationListener.overrideUrl(providerUrl); - ServiceConfigurationListener serviceConfigurationListener = new ServiceConfigurationListener(providerUrl.getOrDefaultModuleModel(), providerUrl, listener); + ServiceConfigurationListener serviceConfigurationListener = + new ServiceConfigurationListener(providerUrl.getOrDefaultModuleModel(), providerUrl, listener); serviceConfigurationListeners.put(providerUrl.getServiceKey(), serviceConfigurationListener); return serviceConfigurationListener.overrideUrl(providerUrl); } @@ -330,12 +352,12 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { String registryUrlKey = getRegistryUrlKey(originInvoker); Invoker invokerDelegate = new InvokerDelegate<>(originInvoker, providerUrl); - ReferenceCountExporter exporter = exporterFactory.createExporter(providerUrlKey, () -> protocol.export(invokerDelegate)); + ReferenceCountExporter exporter = + exporterFactory.createExporter(providerUrlKey, () -> protocol.export(invokerDelegate)); return (ExporterChangeableWrapper) bounds.computeIfAbsent(providerUrlKey, _k -> new ConcurrentHashMap<>()) - .computeIfAbsent(registryUrlKey, s -> { - return new ExporterChangeableWrapper<>( - (ReferenceCountExporter) exporter, originInvoker); - }); + .computeIfAbsent(registryUrlKey, s -> { + return new ExporterChangeableWrapper<>((ReferenceCountExporter) exporter, originInvoker); + }); } public void reExport(Exporter exporter, URL newInvokerUrl) { @@ -359,12 +381,22 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { String registryUrlKey = getRegistryUrlKey(originInvoker); Map> registryMap = bounds.get(providerUrlKey); if (registryMap == null) { - logger.warn(INTERNAL_ERROR, "error state, exporterMap can not be null", "", "error state, exporterMap can not be null", new IllegalStateException("error state, exporterMap can not be null")); + logger.warn( + INTERNAL_ERROR, + "error state, exporterMap can not be null", + "", + "error state, exporterMap can not be null", + new IllegalStateException("error state, exporterMap can not be null")); return; } ExporterChangeableWrapper exporter = (ExporterChangeableWrapper) registryMap.get(registryUrlKey); if (exporter == null) { - logger.warn(INTERNAL_ERROR, "error state, exporterMap can not be null", "", "error state, exporterMap can not be null", new IllegalStateException("error state, exporterMap can not be null")); + logger.warn( + INTERNAL_ERROR, + "error state, exporterMap can not be null", + "", + "error state, exporterMap can not be null", + new IllegalStateException("error state, exporterMap can not be null")); return; } URL registeredUrl = exporter.getRegisterUrl(); @@ -386,21 +418,27 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { return; } ReExportTask task = new ReExportTask( - () -> doReExport(originInvoker, exporter, registryUrl, registeredUrl, newProviderUrl), - registeredUrl, - null - ); + () -> doReExport(originInvoker, exporter, registryUrl, registeredUrl, newProviderUrl), + registeredUrl, + null); oldTask = reExportFailedTasks.putIfAbsent(registeredUrl, task); if (oldTask == null) { // never has a retry task. then start a new task for retry. - retryTimer.newTimeout(task, registryUrl.getParameter(REGISTRY_RETRY_PERIOD_KEY, DEFAULT_REGISTRY_RETRY_PERIOD), TimeUnit.MILLISECONDS); + retryTimer.newTimeout( + task, + registryUrl.getParameter(REGISTRY_RETRY_PERIOD_KEY, DEFAULT_REGISTRY_RETRY_PERIOD), + TimeUnit.MILLISECONDS); } } } } - private void doReExport(final Invoker originInvoker, ExporterChangeableWrapper exporter, - URL registryUrl, URL oldProviderUrl, URL newProviderUrl) { + private void doReExport( + final Invoker originInvoker, + ExporterChangeableWrapper exporter, + URL registryUrl, + URL oldProviderUrl, + URL newProviderUrl) { if (exporter.isRegistered()) { Registry registry; try { @@ -425,14 +463,15 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { } private ProviderModel.RegisterStatedURL getStatedUrl(URL registryUrl, URL providerUrl) { - ProviderModel providerModel = frameworkModel.getServiceRepository() - .lookupExportedService(providerUrl.getServiceKey()); + ProviderModel providerModel = + frameworkModel.getServiceRepository().lookupExportedService(providerUrl.getServiceKey()); List statedUrls = providerModel.getStatedUrl(); return statedUrls.stream() - .filter(u -> u.getRegistryUrl().equals(registryUrl) - && u.getProviderUrl().getProtocol().equals(providerUrl.getProtocol())) - .findFirst().orElseThrow(() -> new IllegalStateException("There should have at least one registered url.")); + .filter(u -> u.getRegistryUrl().equals(registryUrl) + && u.getProviderUrl().getProtocol().equals(providerUrl.getProtocol())) + .findFirst() + .orElseThrow(() -> new IllegalStateException("There should have at least one registered url.")); } /** @@ -442,7 +481,9 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { * @return */ protected Registry getRegistry(final URL registryUrl) { - RegistryFactory registryFactory = ScopeModelUtil.getExtensionLoader(RegistryFactory.class, registryUrl.getScopeModel()).getAdaptiveExtension(); + RegistryFactory registryFactory = ScopeModelUtil.getExtensionLoader( + RegistryFactory.class, registryUrl.getScopeModel()) + .getAdaptiveExtension(); return registryFactory.getRegistry(registryUrl); } @@ -464,11 +505,26 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { * @return url to registry. */ private URL getUrlToRegistry(final URL providerUrl, final URL registryUrl) { - //The address you see at the registry + // The address you see at the registry if (!registryUrl.getParameter(SIMPLIFIED_KEY, false)) { - return providerUrl.removeParameters(getFilteredKeys(providerUrl)).removeParameters( - MONITOR_KEY, BIND_IP_KEY, BIND_PORT_KEY, QOS_ENABLE, QOS_HOST, QOS_PORT, ACCEPT_FOREIGN_IP, VALIDATION_KEY, - INTERFACES, REGISTER_MODE_KEY, PID_KEY, REGISTRY_LOCAL_FILE_CACHE_ENABLED, EXECUTOR_MANAGEMENT_MODE, BACKGROUND_KEY, ANYHOST_KEY); + return providerUrl + .removeParameters(getFilteredKeys(providerUrl)) + .removeParameters( + MONITOR_KEY, + BIND_IP_KEY, + BIND_PORT_KEY, + QOS_ENABLE, + QOS_HOST, + QOS_PORT, + ACCEPT_FOREIGN_IP, + VALIDATION_KEY, + INTERFACES, + REGISTER_MODE_KEY, + PID_KEY, + REGISTRY_LOCAL_FILE_CACHE_ENABLED, + EXECUTOR_MANAGEMENT_MODE, + BACKGROUND_KEY, + ANYHOST_KEY); } else { String extraKeys = registryUrl.getParameter(EXTRA_KEYS_KEY, ""); // if path is not the same as interface name then we should keep INTERFACE_KEY, @@ -480,16 +536,16 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { } extraKeys += INTERFACE_KEY; } - String[] paramsToRegistry = getParamsToRegistry(DEFAULT_REGISTER_PROVIDER_KEYS - , COMMA_SPLIT_PATTERN.split(extraKeys)); + String[] paramsToRegistry = + getParamsToRegistry(DEFAULT_REGISTER_PROVIDER_KEYS, COMMA_SPLIT_PATTERN.split(extraKeys)); return URL.valueOf(providerUrl, paramsToRegistry, providerUrl.getParameter(METHODS_KEY, (String[]) null)); } - } private URL getSubscribedOverrideUrl(URL registeredProviderUrl) { - return registeredProviderUrl.setProtocol(PROVIDER_PROTOCOL) - .addParameters(CATEGORY_KEY, CONFIGURATORS_CATEGORY, CHECK_KEY, String.valueOf(false)); + return registeredProviderUrl + .setProtocol(PROVIDER_PROTOCOL) + .addParameters(CATEGORY_KEY, CONFIGURATORS_CATEGORY, CHECK_KEY, String.valueOf(false)); } /** @@ -501,7 +557,8 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { private URL getProviderUrl(final Invoker originInvoker) { Object providerURL = originInvoker.getUrl().getAttribute(EXPORT_KEY); if (!(providerURL instanceof URL)) { - throw new IllegalArgumentException("The registry export url is null! registry: " + originInvoker.getUrl().getAddress()); + throw new IllegalArgumentException("The registry export url is null! registry: " + + originInvoker.getUrl().getAddress()); } return (URL) providerURL; } @@ -538,7 +595,8 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { String group = qs.get(GROUP_KEY); if (StringUtils.isNotEmpty(group)) { if ((COMMA_SPLIT_PATTERN.split(group)).length > 1 || "*".equals(group)) { - return doRefer(Cluster.getCluster(url.getScopeModel(), MERGEABLE_CLUSTER_NAME), registry, type, url, qs); + return doRefer( + Cluster.getCluster(url.getScopeModel(), MERGEABLE_CLUSTER_NAME), registry, type, url, qs); } } @@ -546,19 +604,20 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { return doRefer(cluster, registry, type, url, qs); } - protected Invoker doRefer(Cluster cluster, Registry registry, Class type, URL url, Map parameters) { + protected Invoker doRefer( + Cluster cluster, Registry registry, Class type, URL url, Map parameters) { Map consumerAttribute = new HashMap<>(url.getAttributes()); consumerAttribute.remove(REFER_KEY); String p = isEmpty(parameters.get(PROTOCOL_KEY)) ? CONSUMER : parameters.get(PROTOCOL_KEY); URL consumerUrl = new ServiceConfigURL( - p, - null, - null, - parameters.get(REGISTER_IP_KEY), - 0, getPath(parameters, type), - parameters, - consumerAttribute - ); + p, + null, + null, + parameters.get(REGISTER_IP_KEY), + 0, + getPath(parameters, type), + parameters, + consumerAttribute); url = url.putAttribute(CONSUMER_URL_KEY, consumerUrl); ClusterInvoker migrationInvoker = getMigrationInvoker(this, cluster, registry, type, url, consumerUrl); return interceptInvoker(migrationInvoker, url, consumerUrl); @@ -568,7 +627,13 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { return !ProtocolUtils.isGeneric(parameters.get(GENERIC_KEY)) ? type.getName() : parameters.get(INTERFACE_KEY); } - protected ClusterInvoker getMigrationInvoker(RegistryProtocol registryProtocol, Cluster cluster, Registry registry, Class type, URL url, URL consumerUrl) { + protected ClusterInvoker getMigrationInvoker( + RegistryProtocol registryProtocol, + Cluster cluster, + Registry registry, + Class type, + URL url, + URL consumerUrl) { return new ServiceDiscoveryMigrationInvoker(registryProtocol, cluster, registry, type, url, consumerUrl); } @@ -596,7 +661,8 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { return invoker; } - public ClusterInvoker getServiceDiscoveryInvoker(Cluster cluster, Registry registry, Class type, URL url) { + public ClusterInvoker getServiceDiscoveryInvoker( + Cluster cluster, Registry registry, Class type, URL url) { DynamicDirectory directory = new ServiceDiscoveryRegistryDirectory<>(type, url); return doCreateInvoker(directory, cluster, registry, type); } @@ -607,18 +673,19 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { return doCreateInvoker(directory, cluster, registry, type); } - protected ClusterInvoker doCreateInvoker(DynamicDirectory directory, Cluster cluster, Registry registry, Class type) { + protected ClusterInvoker doCreateInvoker( + DynamicDirectory directory, Cluster cluster, Registry registry, Class type) { directory.setRegistry(registry); directory.setProtocol(protocol); // all attributes of REFER_KEY - Map parameters = new HashMap<>(directory.getConsumerUrl().getParameters()); + Map parameters = + new HashMap<>(directory.getConsumerUrl().getParameters()); URL urlToRegistry = new ServiceConfigURL( - parameters.get(PROTOCOL_KEY) == null ? CONSUMER : parameters.get(PROTOCOL_KEY), - parameters.remove(REGISTER_IP_KEY), - 0, - getPath(parameters, type), - parameters - ); + parameters.get(PROTOCOL_KEY) == null ? CONSUMER : parameters.get(PROTOCOL_KEY), + parameters.remove(REGISTER_IP_KEY), + 0, + getPath(parameters, type), + parameters); urlToRegistry = urlToRegistry.setScopeModel(directory.getConsumerUrl().getScopeModel()); urlToRegistry = urlToRegistry.setServiceModel(directory.getConsumerUrl().getServiceModel()); if (directory.isShouldRegister()) { @@ -633,7 +700,12 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { public void reRefer(ClusterInvoker invoker, URL newSubscribeUrl) { if (!(invoker instanceof MigrationClusterInvoker)) { - logger.error(REGISTRY_UNSUPPORTED_CATEGORY, "", "", "Only invoker type of MigrationClusterInvoker supports reRefer, current invoker is " + invoker.getClass()); + logger.error( + REGISTRY_UNSUPPORTED_CATEGORY, + "", + "", + "Only invoker type of MigrationClusterInvoker supports reRefer, current invoker is " + + invoker.getClass()); return; } @@ -647,7 +719,7 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { protected List findRegistryProtocolListeners(URL url) { return ScopeModelUtil.getExtensionLoader(RegistryProtocolListener.class, url.getScopeModel()) - .getActivateExtension(url, REGISTRY_PROTOCOL_LISTENER_KEY); + .getActivateExtension(url, REGISTRY_PROTOCOL_LISTENER_KEY); } // available to test @@ -664,8 +736,9 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { // FIXME all application models in framework are removed at this moment for (ApplicationModel applicationModel : frameworkModel.getApplicationModels()) { for (ModuleModel moduleModel : applicationModel.getModuleModels()) { - List listeners = moduleModel.getExtensionLoader(RegistryProtocolListener.class) - .getLoadedExtensionInstances(); + List listeners = moduleModel + .getExtensionLoader(RegistryProtocolListener.class) + .getLoadedExtensionInstances(); if (CollectionUtils.isNotEmpty(listeners)) { for (RegistryProtocolListener listener : listeners) { listener.onDestroy(); @@ -675,7 +748,10 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { } for (ApplicationModel applicationModel : frameworkModel.getApplicationModels()) { - if (applicationModel.modelEnvironment().getConfiguration().convert(Boolean.class, org.apache.dubbo.registry.Constants.ENABLE_CONFIGURATION_LISTEN, true)) { + if (applicationModel + .modelEnvironment() + .getConfiguration() + .convert(Boolean.class, org.apache.dubbo.registry.Constants.ENABLE_CONFIGURATION_LISTEN, true)) { for (ModuleModel moduleModel : applicationModel.getPubModuleModels()) { String applicationName = applicationModel.tryGetApplicationName(); if (applicationName == null) { @@ -683,15 +759,19 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { continue; } if (moduleModel.getServiceRepository().getExportedServices().size() > 0) { - moduleModel.getExtensionLoader(GovernanceRuleRepository.class).getDefaultExtension() - .removeListener(applicationName + CONFIGURATORS_SUFFIX, - getProviderConfigurationListener(moduleModel)); + moduleModel + .getExtensionLoader(GovernanceRuleRepository.class) + .getDefaultExtension() + .removeListener( + applicationName + CONFIGURATORS_SUFFIX, + getProviderConfigurationListener(moduleModel)); } } } } - List> exporters = bounds.values().stream().flatMap(e -> e.values().stream()).collect(Collectors.toList()); + List> exporters = + bounds.values().stream().flatMap(e -> e.values().stream()).collect(Collectors.toList()); for (Exporter exporter : exporters) { exporter.unexport(); } @@ -703,7 +783,7 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { return protocol.getServers(); } - //Merge the urls of configurators + // Merge the urls of configurators private static URL getConfiguredInvokerUrl(List configurators, URL url) { if (CollectionUtils.isNotEmpty(configurators)) { for (Configurator configurator : configurators) { @@ -799,9 +879,10 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { } this.configurators = Configurator.toConfigurators(classifyUrls(matchedUrls, UrlUtils::isConfigurator)) - .orElse(configurators); + .orElse(configurators); - ApplicationDeployer deployer = subscribeUrl.getOrDefaultApplicationModel().getDeployer(); + ApplicationDeployer deployer = + subscribeUrl.getOrDefaultApplicationModel().getDeployer(); try { deployer.increaseServiceRefreshCount(); @@ -818,34 +899,45 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { } else { invoker = originInvoker; } - //The origin invoker + // The origin invoker URL originUrl = RegistryProtocol.this.getProviderUrl(invoker); String providerUrlKey = getProviderUrlKey(originInvoker); String registryUrlKey = getRegistryUrlKey(originInvoker); Map> exporterMap = bounds.get(providerUrlKey); if (exporterMap == null) { - logger.warn(INTERNAL_ERROR, "error state, exporterMap can not be null", "", "error state, exporterMap can not be null", new IllegalStateException("error state, exporterMap can not be null")); + logger.warn( + INTERNAL_ERROR, + "error state, exporterMap can not be null", + "", + "error state, exporterMap can not be null", + new IllegalStateException("error state, exporterMap can not be null")); return; } ExporterChangeableWrapper exporter = exporterMap.get(registryUrlKey); if (exporter == null) { - logger.warn(INTERNAL_ERROR, "unknown error in registry module", "", "error state, exporter should not be null", new IllegalStateException("error state, exporter should not be null")); + logger.warn( + INTERNAL_ERROR, + "unknown error in registry module", + "", + "error state, exporter should not be null", + new IllegalStateException("error state, exporter should not be null")); return; } - //The current, may have been merged many times + // The current, may have been merged many times Invoker exporterInvoker = exporter.getInvoker(); URL currentUrl = exporterInvoker == null ? null : exporterInvoker.getUrl(); - //Merged with this configuration + // Merged with this configuration URL newUrl = getConfiguredInvokerUrl(configurators, originUrl); - newUrl = getConfiguredInvokerUrl(getProviderConfigurationListener(originUrl).getConfigurators(), newUrl); - newUrl = getConfiguredInvokerUrl(serviceConfigurationListeners.get(originUrl.getServiceKey()) - .getConfigurators(), newUrl); + newUrl = getConfiguredInvokerUrl( + getProviderConfigurationListener(originUrl).getConfigurators(), newUrl); + newUrl = getConfiguredInvokerUrl( + serviceConfigurationListeners.get(originUrl.getServiceKey()).getConfigurators(), newUrl); if (!newUrl.equals(currentUrl)) { if (newUrl.getParameter(Constants.NEED_REEXPORT, true)) { RegistryProtocol.this.reExport(originInvoker, newUrl); } - logger.info("exported provider url changed, origin url: " + originUrl + - ", old export url: " + currentUrl + ", new export url: " + newUrl); + logger.info("exported provider url changed, origin url: " + originUrl + ", old export url: " + + currentUrl + ", new export url: " + newUrl); } } @@ -872,8 +964,10 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { } private ProviderConfigurationListener getProviderConfigurationListener(ModuleModel moduleModel) { - return moduleModel.getBeanFactory().getOrRegisterBean(ProviderConfigurationListener.class, - type -> new ProviderConfigurationListener(moduleModel)); + return moduleModel + .getBeanFactory() + .getOrRegisterBean( + ProviderConfigurationListener.class, type -> new ProviderConfigurationListener(moduleModel)); } private class ServiceConfigurationListener extends AbstractConfiguratorListener { @@ -887,7 +981,10 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { this.providerUrl = providerUrl; this.notifyListener = notifyListener; this.moduleModel = moduleModel; - if (moduleModel.modelEnvironment().getConfiguration().convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true)) { + if (moduleModel + .modelEnvironment() + .getConfiguration() + .convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true)) { this.initWith(DynamicConfiguration.getRuleKey(providerUrl) + CONFIGURATORS_SUFFIX); } } @@ -898,7 +995,8 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { @Override protected void notifyOverrides() { - ApplicationDeployer deployer = this.moduleModel.getApplicationModel().getDeployer(); + ApplicationDeployer deployer = + this.moduleModel.getApplicationModel().getDeployer(); try { deployer.increaseServiceRefreshCount(); notifyListener.doOverrideIfNecessary(); @@ -935,7 +1033,8 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { @Override protected void notifyOverrides() { - ApplicationDeployer deployer = this.moduleModel.getApplicationModel().getDeployer(); + ApplicationDeployer deployer = + this.moduleModel.getApplicationModel().getDeployer(); try { deployer.increaseServiceRefreshCount(); overrideListeners.values().forEach(listeners -> { @@ -975,8 +1074,11 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { this.exporter = exporter; exporter.increaseCount(); this.originInvoker = originInvoker; - FrameworkExecutorRepository frameworkExecutorRepository = originInvoker.getUrl().getOrDefaultFrameworkModel().getBeanFactory() - .getBean(FrameworkExecutorRepository.class); + FrameworkExecutorRepository frameworkExecutorRepository = originInvoker + .getUrl() + .getOrDefaultFrameworkModel() + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class); this.executor = frameworkExecutorRepository.getSharedScheduledExecutor(); } @@ -1000,15 +1102,19 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { Registry registry = getRegistry(registryUrl); RegistryProtocol.register(registry, getRegisterUrl()); - ProviderModel providerModel = frameworkModel.getServiceRepository() - .lookupExportedService(getRegisterUrl().getServiceKey()); + ProviderModel providerModel = frameworkModel + .getServiceRepository() + .lookupExportedService(getRegisterUrl().getServiceKey()); List statedUrls = providerModel.getStatedUrl(); statedUrls.stream() - .filter(u -> u.getRegistryUrl().equals(registryUrl) - && u.getProviderUrl().getProtocol().equals(getRegisterUrl().getProtocol())) - .forEach(u -> u.setRegistered(true)); - logger.info("Registered dubbo service " + getRegisterUrl().getServiceKey() + " url " + getRegisterUrl() + " to registry " + registryUrl); + .filter(u -> u.getRegistryUrl().equals(registryUrl) + && u.getProviderUrl() + .getProtocol() + .equals(getRegisterUrl().getProtocol())) + .forEach(u -> u.setRegistered(true)); + logger.info("Registered dubbo service " + getRegisterUrl().getServiceKey() + " url " + getRegisterUrl() + + " to registry " + registryUrl); } } @@ -1018,16 +1124,18 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { URL registryUrl = getRegistryUrl(originInvoker); Registry registry = RegistryProtocol.this.getRegistry(registryUrl); - ProviderModel providerModel = frameworkModel.getServiceRepository() - .lookupExportedService(getRegisterUrl().getServiceKey()); + ProviderModel providerModel = frameworkModel + .getServiceRepository() + .lookupExportedService(getRegisterUrl().getServiceKey()); - List statedURLs = - providerModel.getStatedUrl() - .stream() + List statedURLs = providerModel.getStatedUrl().stream() .filter(u -> u.getRegistryUrl().equals(registryUrl) - && u.getProviderUrl().getProtocol().equals(getRegisterUrl().getProtocol())) + && u.getProviderUrl() + .getProtocol() + .equals(getRegisterUrl().getProtocol())) .collect(Collectors.toList()); - if (statedURLs.isEmpty() || statedURLs.stream().anyMatch(ProviderModel.RegisterStatedURL::isRegistered)) { + if (statedURLs.isEmpty() + || statedURLs.stream().anyMatch(ProviderModel.RegisterStatedURL::isRegistered)) { try { registry.unregister(registerUrl); } catch (Throwable t) { @@ -1037,22 +1145,37 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { try { if (subscribeUrl != null) { - Map> overrideListeners = getProviderConfigurationListener(subscribeUrl).getOverrideListeners(); + Map> overrideListeners = + getProviderConfigurationListener(subscribeUrl).getOverrideListeners(); Set listeners = overrideListeners.get(subscribeUrl); if (listeners != null) { if (listeners.remove(notifyListener)) { ApplicationModel applicationModel = getApplicationModel(registerUrl.getScopeModel()); - if (applicationModel.modelEnvironment().getConfiguration().convert(Boolean.class, ENABLE_26X_CONFIGURATION_LISTEN, true)) { + if (applicationModel + .modelEnvironment() + .getConfiguration() + .convert(Boolean.class, ENABLE_26X_CONFIGURATION_LISTEN, true)) { if (!registry.isServiceDiscovery()) { registry.unsubscribe(subscribeUrl, notifyListener); } } - if (applicationModel.modelEnvironment().getConfiguration().convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true)) { + if (applicationModel + .modelEnvironment() + .getConfiguration() + .convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true)) { for (ModuleModel moduleModel : applicationModel.getPubModuleModels()) { - if (moduleModel.getServiceRepository().getExportedServices().size() > 0) { - moduleModel.getExtensionLoader(GovernanceRuleRepository.class).getDefaultExtension() - .removeListener(subscribeUrl.getServiceKey() + CONFIGURATORS_SUFFIX, - serviceConfigurationListeners.remove(subscribeUrl.getServiceKey())); + if (moduleModel + .getServiceRepository() + .getExportedServices() + .size() + > 0) { + moduleModel + .getExtensionLoader(GovernanceRuleRepository.class) + .getDefaultExtension() + .removeListener( + subscribeUrl.getServiceKey() + CONFIGURATORS_SUFFIX, + serviceConfigurationListeners.remove( + subscribeUrl.getServiceKey())); } } } @@ -1113,5 +1236,4 @@ public class RegistryProtocol implements Protocol, ScopeModelAware { return registerUrl; } } - } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/AbstractRetryTask.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/AbstractRetryTask.java index c6226db132..cdbffdedfe 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/AbstractRetryTask.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/AbstractRetryTask.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.registry.retry; import org.apache.dubbo.common.URL; @@ -117,8 +116,10 @@ public abstract class AbstractRetryTask implements TimerTask { // 1-13 - failed to execute the retrying task. logger.warn( - REGISTRY_EXECUTE_RETRYING_TASK, "registry center offline", "Check the registry server.", - "Final failed to execute task " + taskName + ", url: " + url + ", retry " + retryTimes + " times."); + REGISTRY_EXECUTE_RETRYING_TASK, + "registry center offline", + "Check the registry server.", + "Final failed to execute task " + taskName + ", url: " + url + ", retry " + retryTimes + " times."); return; } @@ -131,8 +132,13 @@ public abstract class AbstractRetryTask implements TimerTask { // 1-13 - failed to execute the retrying task. - logger.warn(REGISTRY_EXECUTE_RETRYING_TASK, "registry center offline", "Check the registry server.", - "Failed to execute task " + taskName + ", url: " + url + ", waiting for again, cause:" + t.getMessage(), t); + logger.warn( + REGISTRY_EXECUTE_RETRYING_TASK, + "registry center offline", + "Check the registry server.", + "Failed to execute task " + taskName + ", url: " + url + ", waiting for again, cause:" + + t.getMessage(), + t); // reput this task when catch exception. reput(timeout, retryPeriod); diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedRegisteredTask.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedRegisteredTask.java index c4d9cc6f08..66b369b163 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedRegisteredTask.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedRegisteredTask.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.registry.retry; import org.apache.dubbo.common.URL; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedSubscribedTask.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedSubscribedTask.java index 06d1ec3151..a845e6e44e 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedSubscribedTask.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedSubscribedTask.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.registry.retry; import org.apache.dubbo.common.URL; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedUnregisteredTask.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedUnregisteredTask.java index 4cf3aa4ebf..bc75aed575 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedUnregisteredTask.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedUnregisteredTask.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.registry.retry; import org.apache.dubbo.common.URL; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedUnsubscribedTask.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedUnsubscribedTask.java index 4b873f71b8..fa17ffe31f 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedUnsubscribedTask.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/retry/FailedUnsubscribedTask.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.registry.retry; import org.apache.dubbo.common.URL; diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/status/RegistryStatusChecker.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/status/RegistryStatusChecker.java index f8e6080d22..b40958a84d 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/status/RegistryStatusChecker.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/status/RegistryStatusChecker.java @@ -61,5 +61,4 @@ public class RegistryStatusChecker implements StatusChecker { } return new Status(level, buf.toString()); } - } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java index 1ba9b330b8..431632a731 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistry.java @@ -96,7 +96,8 @@ public abstract class AbstractRegistry implements Registry { // Log output protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); - // Local disk cache, where the special key value.registries records the list of registry centers, and the others are the list of notified service providers + // Local disk cache, where the special key value.registries records the list of registry centers, and the others are + // the list of notified service providers private final Properties properties = new Properties(); // File cache timing writing private final ScheduledExecutorService registryCacheExecutor; @@ -120,32 +121,40 @@ public abstract class AbstractRegistry implements Registry { setUrl(url); registryManager = url.getOrDefaultApplicationModel().getBeanFactory().getBean(RegistryManager.class); localCacheEnabled = url.getParameter(REGISTRY_LOCAL_FILE_CACHE_ENABLED, true); - registryCacheExecutor = url.getOrDefaultFrameworkModel().getBeanFactory() - .getBean(FrameworkExecutorRepository.class).getSharedScheduledExecutor(); + registryCacheExecutor = url.getOrDefaultFrameworkModel() + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class) + .getSharedScheduledExecutor(); if (localCacheEnabled) { // Start file save timer syncSaveFile = url.getParameter(REGISTRY_FILESAVE_SYNC_KEY, false); - String defaultFilename = System.getProperty(USER_HOME) + DUBBO_REGISTRY + url.getApplication() + - "-" + url.getAddress().replaceAll(":", "-") + CACHE; + String defaultFilename = System.getProperty(USER_HOME) + DUBBO_REGISTRY + url.getApplication() + "-" + + url.getAddress().replaceAll(":", "-") + CACHE; String filename = url.getParameter(FILE_KEY, defaultFilename); File file = null; if (ConfigUtils.isNotEmpty(filename)) { file = new File(filename); - if (!file.exists() && file.getParentFile() != null && !file.getParentFile().exists()) { + if (!file.exists() + && file.getParentFile() != null + && !file.getParentFile().exists()) { if (!file.getParentFile().mkdirs()) { - IllegalArgumentException illegalArgumentException = new IllegalArgumentException( - "Invalid registry cache file " + file + ", cause: Failed to create directory " + file.getParentFile() + "!"); + IllegalArgumentException illegalArgumentException = + new IllegalArgumentException("Invalid registry cache file " + file + + ", cause: Failed to create directory " + file.getParentFile() + "!"); if (logger != null) { // 1-9 failed to read / save registry cache file. - logger.error(REGISTRY_FAILED_READ_WRITE_CACHE_FILE, "cache directory inaccessible", - "Try adjusting permission of the directory.", - "failed to create directory", illegalArgumentException); + logger.error( + REGISTRY_FAILED_READ_WRITE_CACHE_FILE, + "cache directory inaccessible", + "Try adjusting permission of the directory.", + "failed to create directory", + illegalArgumentException); } throw illegalArgumentException; @@ -223,16 +232,21 @@ public abstract class AbstractRegistry implements Registry { } try (RandomAccessFile raf = new RandomAccessFile(lockfile, "rw"); - FileChannel channel = raf.getChannel()) { + FileChannel channel = raf.getChannel()) { FileLock lock = channel.tryLock(); if (lock == null) { - IOException ioException = new IOException("Can not lock the registry cache file " + file.getAbsolutePath() + ", " + - "ignore and retry later, maybe multi java process use the file, please config: dubbo.registry.file=xxx.properties"); + IOException ioException = new IOException( + "Can not lock the registry cache file " + file.getAbsolutePath() + ", " + + "ignore and retry later, maybe multi java process use the file, please config: dubbo.registry.file=xxx.properties"); // 1-9 failed to read / save registry cache file. - logger.warn(REGISTRY_FAILED_READ_WRITE_CACHE_FILE, CAUSE_MULTI_DUBBO_USING_SAME_FILE, "", - "Adjust dubbo.registry.file.", ioException); + logger.warn( + REGISTRY_FAILED_READ_WRITE_CACHE_FILE, + CAUSE_MULTI_DUBBO_USING_SAME_FILE, + "", + "Adjust dubbo.registry.file.", + ioException); throw ioException; } @@ -271,11 +285,17 @@ public abstract class AbstractRegistry implements Registry { if (savePropertiesRetryTimes.get() >= MAX_RETRY_TIMES_SAVE_PROPERTIES) { if (e instanceof OverlappingFileLockException) { // fix #9341, ignore OverlappingFileLockException - logger.info("Failed to save registry cache file for file overlapping lock exception, file name " + file.getName()); + logger.info("Failed to save registry cache file for file overlapping lock exception, file name " + + file.getName()); } else { // 1-9 failed to read / save registry cache file. - logger.warn(REGISTRY_FAILED_READ_WRITE_CACHE_FILE, CAUSE_MULTI_DUBBO_USING_SAME_FILE, "", - "Failed to save registry cache file after retrying " + MAX_RETRY_TIMES_SAVE_PROPERTIES + " times, cause: " + e.getMessage(), e); + logger.warn( + REGISTRY_FAILED_READ_WRITE_CACHE_FILE, + CAUSE_MULTI_DUBBO_USING_SAME_FILE, + "", + "Failed to save registry cache file after retrying " + MAX_RETRY_TIMES_SAVE_PROPERTIES + + " times, cause: " + e.getMessage(), + e); } savePropertiesRetryTimes.set(0); @@ -286,20 +306,29 @@ public abstract class AbstractRegistry implements Registry { savePropertiesRetryTimes.set(0); return; } else { - registryCacheExecutor.schedule(() -> doSaveProperties(lastCacheChanged.incrementAndGet()), DEFAULT_INTERVAL_SAVE_PROPERTIES, TimeUnit.MILLISECONDS); + registryCacheExecutor.schedule( + () -> doSaveProperties(lastCacheChanged.incrementAndGet()), + DEFAULT_INTERVAL_SAVE_PROPERTIES, + TimeUnit.MILLISECONDS); } if (!(e instanceof OverlappingFileLockException)) { - logger.warn(REGISTRY_FAILED_READ_WRITE_CACHE_FILE, CAUSE_MULTI_DUBBO_USING_SAME_FILE, - "However, the retrying count limit is not exceeded. Dubbo will still try.", - "Failed to save registry cache file, will retry, cause: " + e.getMessage(), e); + logger.warn( + REGISTRY_FAILED_READ_WRITE_CACHE_FILE, + CAUSE_MULTI_DUBBO_USING_SAME_FILE, + "However, the retrying count limit is not exceeded. Dubbo will still try.", + "Failed to save registry cache file, will retry, cause: " + e.getMessage(), + e); } } finally { if (lockfile != null) { if (!lockfile.delete()) { // 1-10 Failed to delete lock file. - logger.warn(REGISTRY_FAILED_DELETE_LOCKFILE, "", "", - String.format("Failed to delete lock file [%s]", lockfile.getName())); + logger.warn( + REGISTRY_FAILED_DELETE_LOCKFILE, + "", + "", + String.format("Failed to delete lock file [%s]", lockfile.getName())); } } } @@ -316,28 +345,36 @@ public abstract class AbstractRegistry implements Registry { } } catch (IOException e) { // 1-9 failed to read / save registry cache file. - logger.warn(REGISTRY_FAILED_READ_WRITE_CACHE_FILE, CAUSE_MULTI_DUBBO_USING_SAME_FILE, "", - e.getMessage(), e); + logger.warn( + REGISTRY_FAILED_READ_WRITE_CACHE_FILE, CAUSE_MULTI_DUBBO_USING_SAME_FILE, "", e.getMessage(), e); } catch (Throwable e) { // 1-9 failed to read / save registry cache file. - logger.warn(REGISTRY_FAILED_READ_WRITE_CACHE_FILE, CAUSE_MULTI_DUBBO_USING_SAME_FILE, "", - "Failed to load registry cache file " + file, e); + logger.warn( + REGISTRY_FAILED_READ_WRITE_CACHE_FILE, + CAUSE_MULTI_DUBBO_USING_SAME_FILE, + "", + "Failed to load registry cache file " + file, + e); } } public List getCacheUrls(URL url) { Map> categoryNotified = notified.get(url); if (CollectionUtils.isNotEmptyMap(categoryNotified)) { - List urls = categoryNotified.values().stream().flatMap(Collection::stream).collect(Collectors.toList()); + List urls = categoryNotified.values().stream() + .flatMap(Collection::stream) + .collect(Collectors.toList()); return urls; } for (Map.Entry entry : properties.entrySet()) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); - if (StringUtils.isNotEmpty(key) && key.equals(url.getServiceKey()) && (Character.isLetter(key.charAt(0)) - || key.charAt(0) == '_') && StringUtils.isNotEmpty(value)) { + if (StringUtils.isNotEmpty(key) + && key.equals(url.getServiceKey()) + && (Character.isLetter(key.charAt(0)) || key.charAt(0) == '_') + && StringUtils.isNotEmpty(value)) { String[] arr = value.trim().split(URL_SPLIT); List urls = new ArrayList<>(); for (String u : arr) { @@ -483,8 +520,12 @@ public abstract class AbstractRegistry implements Registry { notify(url, listener, filterEmpty(url, urls)); } catch (Throwable t) { // 1-7: Failed to notify registry event. - logger.error(REGISTRY_FAILED_NOTIFY_EVENT, "consumer is offline", "", - "Failed to notify registry event, urls: " + urls + ", cause: " + t.getMessage(), t); + logger.error( + REGISTRY_FAILED_NOTIFY_EVENT, + "consumer is offline", + "", + "Failed to notify registry event, urls: " + urls + ", cause: " + t.getMessage(), + t); } } } @@ -533,7 +574,8 @@ public abstract class AbstractRegistry implements Registry { listener.notify(categoryList); // We will update our cache file after each notification. - // When our Registry has a subscribed failure due to network jitter, we can return at least the existing cache URL. + // When our Registry has a subscribed failure due to network jitter, we can return at least the existing + // cache URL. if (localCacheEnabled) { saveProperties(url); } @@ -563,7 +605,8 @@ public abstract class AbstractRegistry implements Registry { if (syncSaveFile) { doSaveProperties(version); } else { - registryCacheExecutor.schedule(() -> doSaveProperties(version), DEFAULT_INTERVAL_SAVE_PROPERTIES, TimeUnit.MILLISECONDS); + registryCacheExecutor.schedule( + () -> doSaveProperties(version), DEFAULT_INTERVAL_SAVE_PROPERTIES, TimeUnit.MILLISECONDS); } } catch (Throwable t) { logger.warn(INTERNAL_ERROR, "unknown error in registry module", "", t.getMessage(), t); @@ -586,8 +629,13 @@ public abstract class AbstractRegistry implements Registry { } } catch (Throwable t) { // 1-8: Failed to unregister / unsubscribe url on destroy. - logger.warn(REGISTRY_FAILED_DESTROY_UNREGISTER_URL, "", "", - "Failed to unregister url " + url + " to registry " + getUrl() + " on destroy, cause: " + t.getMessage(), t); + logger.warn( + REGISTRY_FAILED_DESTROY_UNREGISTER_URL, + "", + "", + "Failed to unregister url " + url + " to registry " + getUrl() + " on destroy, cause: " + + t.getMessage(), + t); } } } @@ -604,8 +652,13 @@ public abstract class AbstractRegistry implements Registry { } } catch (Throwable t) { // 1-8: Failed to unregister / unsubscribe url on destroy. - logger.warn(REGISTRY_FAILED_DESTROY_UNREGISTER_URL, "", "", - "Failed to unsubscribe url " + url + " to registry " + getUrl() + " on destroy, cause: " + t.getMessage(), t); + logger.warn( + REGISTRY_FAILED_DESTROY_UNREGISTER_URL, + "", + "", + "Failed to unsubscribe url " + url + " to registry " + getUrl() + " on destroy, cause: " + + t.getMessage(), + t); } } } @@ -621,8 +674,12 @@ public abstract class AbstractRegistry implements Registry { String[] accepts = COMMA_SPLIT_PATTERN.split(pattern); - Set allow = Arrays.stream(accepts).filter(p -> !p.startsWith("-")).collect(Collectors.toSet()); - Set disAllow = Arrays.stream(accepts).filter(p -> p.startsWith("-")).map(p -> p.substring(1)).collect(Collectors.toSet()); + Set allow = + Arrays.stream(accepts).filter(p -> !p.startsWith("-")).collect(Collectors.toSet()); + Set disAllow = Arrays.stream(accepts) + .filter(p -> p.startsWith("-")) + .map(p -> p.substring(1)) + .collect(Collectors.toSet()); if (CollectionUtils.isNotEmpty(allow)) { // allow first diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java index 3400ac1ff1..c24d4c6b3f 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/AbstractRegistryFactory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.registry.support; import org.apache.dubbo.common.URL; @@ -41,7 +40,8 @@ import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; */ public abstract class AbstractRegistryFactory implements RegistryFactory, ScopeModelAware { - private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(AbstractRegistryFactory.class); + private static final ErrorTypeAwareLogger LOGGER = + LoggerFactory.getErrorTypeAwareLogger(AbstractRegistryFactory.class); private RegistryManager registryManager; protected ApplicationModel applicationModel; @@ -55,8 +55,8 @@ public abstract class AbstractRegistryFactory implements RegistryFactory, ScopeM @Override public Registry getRegistry(URL url) { if (registryManager == null) { - throw new IllegalStateException("Unable to fetch RegistryManager from ApplicationModel BeanFactory. " + - "Please check if `setApplicationModel` has been override."); + throw new IllegalStateException("Unable to fetch RegistryManager from ApplicationModel BeanFactory. " + + "Please check if `setApplicationModel` has been override."); } Registry defaultNopRegistry = registryManager.getDefaultNopRegistryIfDestroyed(); @@ -65,12 +65,12 @@ public abstract class AbstractRegistryFactory implements RegistryFactory, ScopeM } url = URLBuilder.from(url) - .setPath(RegistryService.class.getName()) - .addParameter(INTERFACE_KEY, RegistryService.class.getName()) - .removeParameter(TIMESTAMP_KEY) - .removeAttribute(EXPORT_KEY) - .removeAttribute(REFER_KEY) - .build(); + .setPath(RegistryService.class.getName()) + .addParameter(INTERFACE_KEY, RegistryService.class.getName()) + .removeParameter(TIMESTAMP_KEY) + .removeAttribute(EXPORT_KEY) + .removeAttribute(REFER_KEY) + .build(); String key = createRegistryCacheKey(url); Registry registry = null; @@ -105,8 +105,7 @@ public abstract class AbstractRegistryFactory implements RegistryFactory, ScopeM throw new RuntimeException("Can not create registry " + url, e); } else { // 1-11 Failed to obtain or create registry (service) object. - LOGGER.warn(REGISTRY_FAILED_CREATE_INSTANCE, "", "", - "Failed to obtain or create registry ", e); + LOGGER.warn(REGISTRY_FAILED_CREATE_INSTANCE, "", "", "Failed to obtain or create registry ", e); } } finally { // Release the lock @@ -128,6 +127,4 @@ public abstract class AbstractRegistryFactory implements RegistryFactory, ScopeM } protected abstract Registry createRegistry(URL url); - - } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/CacheableFailbackRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/CacheableFailbackRegistry.java index 0fce283a38..94b38c6224 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/CacheableFailbackRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/CacheableFailbackRegistry.java @@ -16,19 +16,6 @@ */ package org.apache.dubbo.registry.support; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.URLStrParser; @@ -48,6 +35,19 @@ import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.ProviderFirstParams; import org.apache.dubbo.rpc.model.ScopeModel; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + import static org.apache.dubbo.common.URLStrParser.ENCODED_AND_MARK; import static org.apache.dubbo.common.URLStrParser.ENCODED_PID_KEY; import static org.apache.dubbo.common.URLStrParser.ENCODED_QUESTION_MARK; @@ -80,9 +80,10 @@ import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATE * @see org.apache.dubbo.registry.support.AbstractRegistry */ public abstract class CacheableFailbackRegistry extends FailbackRegistry { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CacheableFailbackRegistry.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(CacheableFailbackRegistry.class); - private static String[] VARIABLE_KEYS = new String[]{ENCODED_TIMESTAMP_KEY, ENCODED_PID_KEY}; + private static String[] VARIABLE_KEYS = new String[] {ENCODED_TIMESTAMP_KEY, ENCODED_PID_KEY}; protected ConcurrentMap stringAddress = new ConcurrentHashMap<>(); protected ConcurrentMap stringParam = new ConcurrentHashMap<>(); @@ -102,9 +103,13 @@ public abstract class CacheableFailbackRegistry extends FailbackRegistry { extraParameters = new HashMap<>(8); extraParameters.put(CHECK_KEY, String.valueOf(false)); - cacheRemovalScheduler = url.getOrDefaultFrameworkModel().getBeanFactory().getBean(FrameworkExecutorRepository.class).nextScheduledExecutor(); + cacheRemovalScheduler = url.getOrDefaultFrameworkModel() + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class) + .nextScheduledExecutor(); cacheRemovalTaskIntervalInMillis = getIntConfig(url.getScopeModel(), CACHE_CLEAR_TASK_INTERVAL, 2 * 60 * 1000); - cacheClearWaitingThresholdInMillis = getIntConfig(url.getScopeModel(), CACHE_CLEAR_WAITING_THRESHOLD, 5 * 60 * 1000); + cacheClearWaitingThresholdInMillis = + getIntConfig(url.getScopeModel(), CACHE_CLEAR_WAITING_THRESHOLD, 5 * 60 * 1000); } protected static int getIntConfig(ScopeModel scopeModel, String key, int def) { @@ -116,8 +121,11 @@ public abstract class CacheableFailbackRegistry extends FailbackRegistry { } catch (NumberFormatException e) { // 0-2 Property type mismatch. - logger.warn(COMMON_PROPERTY_TYPE_MISMATCH, "typo in property value", "This property requires an integer value.", - "Invalid registry properties configuration key " + key + ", value " + str); + logger.warn( + COMMON_PROPERTY_TYPE_MISMATCH, + "typo in property value", + "This property requires an integer value.", + "Invalid registry properties configuration key " + key + ", value " + str); } } return result; @@ -139,7 +147,8 @@ public abstract class CacheableFailbackRegistry extends FailbackRegistry { } if (CollectionUtils.isNotEmptyMap(waitForRemove)) { if (semaphore.tryAcquire()) { - cacheRemovalScheduler.schedule(new RemovalTask(), cacheRemovalTaskIntervalInMillis, TimeUnit.MILLISECONDS); + cacheRemovalScheduler.schedule( + new RemovalTask(), cacheRemovalTaskIntervalInMillis, TimeUnit.MILLISECONDS); } } } @@ -155,8 +164,12 @@ public abstract class CacheableFailbackRegistry extends FailbackRegistry { // When? FrameworkExecutorRepository gets destroyed. // 1-3: URL evicting failed. - logger.warn(REGISTRY_FAILED_URL_EVICTING, "thread pool getting destroyed", "", - "Failed to evict url for " + url.getServiceKey(), e); + logger.warn( + REGISTRY_FAILED_URL_EVICTING, + "thread pool getting destroyed", + "", + "Failed to evict url for " + url.getServiceKey(), + e); } } @@ -224,15 +237,20 @@ public abstract class CacheableFailbackRegistry extends FailbackRegistry { if (urls.isEmpty()) { int i = path.lastIndexOf(PATH_SEPARATOR); String category = i < 0 ? path : path.substring(i + 1); - if (!PROVIDERS_CATEGORY.equals(category) || !getUrl().getParameter(ENABLE_EMPTY_PROTECTION_KEY, DEFAULT_ENABLE_EMPTY_PROTECTION)) { + if (!PROVIDERS_CATEGORY.equals(category) + || !getUrl().getParameter(ENABLE_EMPTY_PROTECTION_KEY, DEFAULT_ENABLE_EMPTY_PROTECTION)) { if (PROVIDERS_CATEGORY.equals(category)) { - logger.warn(REGISTRY_EMPTY_ADDRESS, "", "", - "Service " + consumer.getServiceKey() + " received empty address list and empty protection is disabled, will clear current available addresses"); + logger.warn( + REGISTRY_EMPTY_ADDRESS, + "", + "", + "Service " + consumer.getServiceKey() + + " received empty address list and empty protection is disabled, will clear current available addresses"); } URL empty = URLBuilder.from(consumer) - .setProtocol(EMPTY_PROTOCOL) - .addParameter(CATEGORY_KEY, category) - .build(); + .setProtocol(EMPTY_PROTOCOL) + .addParameter(CATEGORY_KEY, category) + .build(); urls.add(empty); } } @@ -267,8 +285,7 @@ public abstract class CacheableFailbackRegistry extends FailbackRegistry { if (parts.length <= 1) { // 1-5 Received URL without any parameters. - logger.warn(REGISTRY_NO_PARAMETERS_URL, "", "", - "Received url without any parameters " + rawProvider); + logger.warn(REGISTRY_NO_PARAMETERS_URL, "", "", "Received url without any parameters " + rawProvider); return DubboServiceAddressURL.valueOf(rawProvider, consumerURL); } @@ -280,10 +297,12 @@ public abstract class CacheableFailbackRegistry extends FailbackRegistry { boolean isEncoded = encoded; // PathURLAddress if it's using dubbo protocol. - URLAddress address = ConcurrentHashMapUtils.computeIfAbsent(stringAddress, rawAddress, k -> URLAddress.parse(k, getDefaultURLProtocol(), isEncoded)); + URLAddress address = ConcurrentHashMapUtils.computeIfAbsent( + stringAddress, rawAddress, k -> URLAddress.parse(k, getDefaultURLProtocol(), isEncoded)); address.setTimestamp(System.currentTimeMillis()); - URLParam param = ConcurrentHashMapUtils.computeIfAbsent(stringParam, rawParams, k -> URLParam.parse(k, isEncoded, extraParameters)); + URLParam param = ConcurrentHashMapUtils.computeIfAbsent( + stringParam, rawParams, k -> URLParam.parse(k, isEncoded, extraParameters)); param.setTimestamp(System.currentTimeMillis()); // create service URL using cached address, param, and consumer URL. @@ -296,13 +315,14 @@ public abstract class CacheableFailbackRegistry extends FailbackRegistry { return null; } - protected ServiceAddressURL createServiceURL(URLAddress address, URLParam param, URL consumerURL) { return new DubboServiceAddressURL(address, param, consumerURL, null); } protected URL removeParamsFromConsumer(URL consumer) { - Set providerFirstParams = consumer.getOrDefaultApplicationModel().getExtensionLoader(ProviderFirstParams.class).getSupportedExtensionInstances(); + Set providerFirstParams = consumer.getOrDefaultApplicationModel() + .getExtensionLoader(ProviderFirstParams.class) + .getSupportedExtensionInstances(); if (CollectionUtils.isEmpty(providerFirstParams)) { return consumer; } @@ -391,7 +411,8 @@ public abstract class CacheableFailbackRegistry extends FailbackRegistry { logger.info("Clearing cached URLs, waiting to clear size " + waitForRemove.size()); int clearCount = 0; try { - Iterator> it = waitForRemove.entrySet().iterator(); + Iterator> it = + waitForRemove.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = it.next(); ServiceAddressURL removeURL = entry.getKey(); @@ -413,8 +434,7 @@ public abstract class CacheableFailbackRegistry extends FailbackRegistry { } catch (Throwable t) { // 1-6 Error when clearing cached URLs. - logger.error(REGISTRY_FAILED_CLEAR_CACHED_URLS, "", "", - "Error occurred when clearing cached URLs", t); + logger.error(REGISTRY_FAILED_CLEAR_CACHED_URLS, "", "", "Error occurred when clearing cached URLs", t); } finally { semaphore.release(); @@ -424,7 +444,8 @@ public abstract class CacheableFailbackRegistry extends FailbackRegistry { if (CollectionUtils.isNotEmptyMap(waitForRemove)) { // move to next schedule if (semaphore.tryAcquire()) { - cacheRemovalScheduler.schedule(new RemovalTask(), cacheRemovalTaskIntervalInMillis, TimeUnit.MILLISECONDS); + cacheRemovalScheduler.schedule( + new RemovalTask(), cacheRemovalTaskIntervalInMillis, TimeUnit.MILLISECONDS); } } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/DefaultProviderFirstParams.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/DefaultProviderFirstParams.java index cae73df67f..0a18f2572a 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/DefaultProviderFirstParams.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/DefaultProviderFirstParams.java @@ -30,13 +30,14 @@ import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; public class DefaultProviderFirstParams implements ProviderFirstParams { - private static final Set PARAMS = Collections.unmodifiableSet(new HashSet() {{ - addAll(Arrays.asList(RELEASE_KEY, DUBBO_VERSION_KEY, METHODS_KEY, TIMESTAMP_KEY, TAG_KEY)); - }}); + private static final Set PARAMS = Collections.unmodifiableSet(new HashSet() { + { + addAll(Arrays.asList(RELEASE_KEY, DUBBO_VERSION_KEY, METHODS_KEY, TIMESTAMP_KEY, TAG_KEY)); + } + }); @Override public Set params() { return PARAMS; } - } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java index c216f58b2c..a566a1f71c 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/FailbackRegistry.java @@ -71,7 +71,8 @@ public abstract class FailbackRegistry extends AbstractRegistry { this.retryPeriod = url.getParameter(REGISTRY_RETRY_PERIOD_KEY, DEFAULT_REGISTRY_RETRY_PERIOD); // since the retry task will not be very much. 128 ticks is enough. - retryTimer = new HashedWheelTimer(new NamedThreadFactory("DubboRegistryRetryTimer", true), retryPeriod, TimeUnit.MILLISECONDS, 128); + retryTimer = new HashedWheelTimer( + new NamedThreadFactory("DubboRegistryRetryTimer", true), retryPeriod, TimeUnit.MILLISECONDS, 128); } public void removeFailedRegisteredTask(URL url) { @@ -193,7 +194,6 @@ public abstract class FailbackRegistry extends AbstractRegistry { return failedUnsubscribed; } - @Override public void register(URL url) { if (!shouldRegister(url)) { @@ -210,16 +210,24 @@ public abstract class FailbackRegistry extends AbstractRegistry { // If the startup detection is opened, the Exception is thrown directly. boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) - && url.getParameter(Constants.CHECK_KEY, true) - && (url.getPort() != 0); + && url.getParameter(Constants.CHECK_KEY, true) + && (url.getPort() != 0); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { t = t.getCause(); } - throw new IllegalStateException("Failed to register " + url + " to registry " + getUrl().getAddress() + ", cause: " + t.getMessage(), t); + throw new IllegalStateException( + "Failed to register " + url + " to registry " + getUrl().getAddress() + ", cause: " + + t.getMessage(), + t); } else { - logger.error(INTERNAL_ERROR, "unknown error in registry module", "", "Failed to register " + url + ", waiting for retry, cause: " + t.getMessage(), t); + logger.error( + INTERNAL_ERROR, + "unknown error in registry module", + "", + "Failed to register " + url + ", waiting for retry, cause: " + t.getMessage(), + t); } // Record a failed registration request to a failed list, retry regularly @@ -233,7 +241,8 @@ public abstract class FailbackRegistry extends AbstractRegistry { return false; } if (!acceptable(providerURL)) { - logger.info("URL " + providerURL + " will not be registered to Registry. Registry " + this.getUrl() + " does not accept service of this protocol type."); + logger.info("URL " + providerURL + " will not be registered to Registry. Registry " + this.getUrl() + + " does not accept service of this protocol type."); return false; } return true; @@ -242,7 +251,8 @@ public abstract class FailbackRegistry extends AbstractRegistry { @Override public void reExportRegister(URL url) { if (!acceptable(url)) { - logger.info("URL " + url + " will not be registered to Registry. Registry " + url + " does not accept service of this protocol type."); + logger.info("URL " + url + " will not be registered to Registry. Registry " + url + + " does not accept service of this protocol type."); return; } super.register(url); @@ -253,7 +263,10 @@ public abstract class FailbackRegistry extends AbstractRegistry { doRegister(url); } catch (Exception e) { if (!(e instanceof SkipFailbackWrapperException)) { - throw new IllegalStateException("Failed to register (re-export) " + url + " to registry " + getUrl().getAddress() + ", cause: " + e.getMessage(), e); + throw new IllegalStateException( + "Failed to register (re-export) " + url + " to registry " + getUrl().getAddress() + ", cause: " + + e.getMessage(), + e); } } } @@ -271,16 +284,24 @@ public abstract class FailbackRegistry extends AbstractRegistry { // If the startup detection is opened, the Exception is thrown directly. boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) - && url.getParameter(Constants.CHECK_KEY, true) - && (url.getPort() != 0); + && url.getParameter(Constants.CHECK_KEY, true) + && (url.getPort() != 0); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { t = t.getCause(); } - throw new IllegalStateException("Failed to unregister " + url + " to registry " + getUrl().getAddress() + ", cause: " + t.getMessage(), t); + throw new IllegalStateException( + "Failed to unregister " + url + " to registry " + getUrl().getAddress() + ", cause: " + + t.getMessage(), + t); } else { - logger.error(INTERNAL_ERROR, "unknown error in registry module", "", "Failed to unregister " + url + ", waiting for retry, cause: " + t.getMessage(), t); + logger.error( + INTERNAL_ERROR, + "unknown error in registry module", + "", + "Failed to unregister " + url + ", waiting for retry, cause: " + t.getMessage(), + t); } // Record a failed registration request to a failed list, retry regularly @@ -298,7 +319,10 @@ public abstract class FailbackRegistry extends AbstractRegistry { doUnregister(url); } catch (Exception e) { if (!(e instanceof SkipFailbackWrapperException)) { - throw new IllegalStateException("Failed to unregister(re-export) " + url + " to registry " + getUrl().getAddress() + ", cause: " + e.getMessage(), e); + throw new IllegalStateException( + "Failed to unregister(re-export) " + url + " to registry " + getUrl().getAddress() + ", cause: " + + e.getMessage(), + e); } } } @@ -316,11 +340,17 @@ public abstract class FailbackRegistry extends AbstractRegistry { List urls = getCacheUrls(url); if (CollectionUtils.isNotEmpty(urls)) { notify(url, listener, urls); - logger.error(REGISTRY_FAILED_NOTIFY_EVENT, "", "", "Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: " + getCacheFile().getName() + ", cause: " + t.getMessage(), t); + logger.error( + REGISTRY_FAILED_NOTIFY_EVENT, + "", + "", + "Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: " + + getCacheFile().getName() + ", cause: " + t.getMessage(), + t); } else { // If the startup detection is opened, the Exception is thrown directly. - boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) - && url.getParameter(Constants.CHECK_KEY, true); + boolean check = + getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { @@ -328,7 +358,12 @@ public abstract class FailbackRegistry extends AbstractRegistry { } throw new IllegalStateException("Failed to subscribe " + url + ", cause: " + t.getMessage(), t); } else { - logger.error(REGISTRY_FAILED_NOTIFY_EVENT, "", "", "Failed to subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t); + logger.error( + REGISTRY_FAILED_NOTIFY_EVENT, + "", + "", + "Failed to subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), + t); } } @@ -348,16 +383,24 @@ public abstract class FailbackRegistry extends AbstractRegistry { Throwable t = e; // If the startup detection is opened, the Exception is thrown directly. - boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) - && url.getParameter(Constants.CHECK_KEY, true); + boolean check = + getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { t = t.getCause(); } - throw new IllegalStateException("Failed to unsubscribe " + url + " to registry " + getUrl().getAddress() + ", cause: " + t.getMessage(), t); + throw new IllegalStateException( + "Failed to unsubscribe " + url + " to registry " + getUrl().getAddress() + ", cause: " + + t.getMessage(), + t); } else { - logger.error(REGISTRY_FAILED_NOTIFY_EVENT, "", "", "Failed to unsubscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t); + logger.error( + REGISTRY_FAILED_NOTIFY_EVENT, + "", + "", + "Failed to unsubscribe " + url + ", waiting for retry, cause: " + t.getMessage(), + t); } // Record a failed registration request to a failed list, retry regularly @@ -377,7 +420,12 @@ public abstract class FailbackRegistry extends AbstractRegistry { doNotify(url, listener, urls); } catch (Exception t) { // Record a failed registration request to a failed list - logger.error(REGISTRY_FAILED_NOTIFY_EVENT, "", "", "Failed to notify addresses for subscribe " + url + ", cause: " + t.getMessage(), t); + logger.error( + REGISTRY_FAILED_NOTIFY_EVENT, + "", + "", + "Failed to notify addresses for subscribe " + url + ", cause: " + t.getMessage(), + t); } } diff --git a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/RegistryManager.java b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/RegistryManager.java index e01f3118ff..d6ba90cf7e 100644 --- a/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/RegistryManager.java +++ b/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/support/RegistryManager.java @@ -36,8 +36,8 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; -import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_FETCH_INSTANCE; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_FETCH_INSTANCE; /** * Application Level, used to collect Registries @@ -81,12 +81,11 @@ public class RegistryManager { } public List getServiceDiscoveries() { - return getRegistries() - .stream() - .filter(registry -> registry instanceof ServiceDiscoveryRegistry) - .map(registry -> (ServiceDiscoveryRegistry) registry) - .map(ServiceDiscoveryRegistry::getServiceDiscovery) - .collect(Collectors.toList()); + return getRegistries().stream() + .filter(registry -> registry instanceof ServiceDiscoveryRegistry) + .map(registry -> (ServiceDiscoveryRegistry) registry) + .map(ServiceDiscoveryRegistry::getServiceDiscovery) + .collect(Collectors.toList()); } /** @@ -128,9 +127,12 @@ public class RegistryManager { protected Registry getDefaultNopRegistryIfDestroyed() { if (destroyed.get()) { // 1-12 Failed to fetch (server) instance since the registry instances have been destroyed. - LOGGER.warn(REGISTRY_FAILED_FETCH_INSTANCE, "misuse of the methods", "", - "All registry instances have been destroyed, failed to fetch any instance. " + - "Usually, this means no need to try to do unnecessary redundant resource clearance, all registries has been taken care of."); + LOGGER.warn( + REGISTRY_FAILED_FETCH_INSTANCE, + "misuse of the methods", + "", + "All registry instances have been destroyed, failed to fetch any instance. " + + "Usually, this means no need to try to do unnecessary redundant resource clearance, all registries has been taken care of."); return DEFAULT_NOP_REGISTRY; } @@ -171,29 +173,19 @@ public class RegistryManager { } @Override - public void destroy() { - - } + public void destroy() {} @Override - public void register(URL url) { - - } + public void register(URL url) {} @Override - public void unregister(URL url) { - - } + public void unregister(URL url) {} @Override - public void subscribe(URL url, NotifyListener listener) { - - } + public void subscribe(URL url, NotifyListener listener) {} @Override - public void unsubscribe(URL url, NotifyListener listener) { - - } + public void unsubscribe(URL url, NotifyListener listener) {} @Override public List lookup(URL url) { diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/CacheableFailbackRegistryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/CacheableFailbackRegistryTest.java index d881344a91..b1ff33fddc 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/CacheableFailbackRegistryTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/CacheableFailbackRegistryTest.java @@ -21,15 +21,15 @@ import org.apache.dubbo.common.URLStrParser; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.rpc.model.FrameworkModel; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicReference; - import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; import static org.apache.dubbo.common.constants.RegistryConstants.ENABLE_EMPTY_PROTECTION_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -57,9 +57,12 @@ class CacheableFailbackRegistryTest { service = "org.apache.dubbo.test.DemoService"; serviceUrl = URL.valueOf("dubbo://127.0.0.1/org.apache.dubbo.test.DemoService?category=providers"); registryUrl = URL.valueOf("http://1.2.3.4:9090/registry?check=false&file=N/A"); - urlStr = "dubbo%3A%2F%2F172.19.4.113%3A20880%2Forg.apache.dubbo.demo.DemoService%3Fside%3Dprovider%26timeout%3D3000"; - urlStr2 = "dubbo%3A%2F%2F172.19.4.114%3A20880%2Forg.apache.dubbo.demo.DemoService%3Fside%3Dprovider%26timeout%3D3000"; - urlStr3 = "dubbo%3A%2F%2F172.19.4.115%3A20880%2Forg.apache.dubbo.demo.DemoService%3Fside%3Dprovider%26timeout%3D3000"; + urlStr = + "dubbo%3A%2F%2F172.19.4.113%3A20880%2Forg.apache.dubbo.demo.DemoService%3Fside%3Dprovider%26timeout%3D3000"; + urlStr2 = + "dubbo%3A%2F%2F172.19.4.114%3A20880%2Forg.apache.dubbo.demo.DemoService%3Fside%3Dprovider%26timeout%3D3000"; + urlStr3 = + "dubbo%3A%2F%2F172.19.4.115%3A20880%2Forg.apache.dubbo.demo.DemoService%3Fside%3Dprovider%26timeout%3D3000"; } @AfterEach @@ -237,7 +240,6 @@ class CacheableFailbackRegistryTest { emptyRegistry.clearChildren(); assertEquals(0, currentUrls.get().size()); assertEquals(EMPTY_LIST, currentUrls.get()); - } @Test @@ -284,6 +286,5 @@ class CacheableFailbackRegistryTest { assertEquals(2, resCount.get()); emptyRegistry.clearChildren(); assertEquals(2, currentUrls.get().size()); - } } diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/ListenerRegistryWrapperTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/ListenerRegistryWrapperTest.java index 363adec7fa..ecdcb69434 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/ListenerRegistryWrapperTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/ListenerRegistryWrapperTest.java @@ -16,18 +16,17 @@ */ package org.apache.dubbo.registry; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.registry.integration.DemoService; +import java.util.HashMap; +import java.util.Map; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.HashMap; -import java.util.Map; - import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY; import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; @@ -49,11 +48,8 @@ class ListenerRegistryWrapperTest { parameters.put("registry.listeners", "listener-one"); Map attributes = new HashMap<>(); - ServiceConfigURL serviceConfigURL = new ServiceConfigURL("registry", - "127.0.0.1", - 2181, - "org.apache.dubbo.registry.RegistryService", - parameters); + ServiceConfigURL serviceConfigURL = new ServiceConfigURL( + "registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters); Map refer = new HashMap<>(); attributes.put(REFER_KEY, refer); attributes.put("key1", "value1"); @@ -69,11 +65,7 @@ class ListenerRegistryWrapperTest { Assertions.assertTrue(registryWrapper instanceof ListenerRegistryWrapper); - URL subscribeUrl = new ServiceConfigURL("dubbo", - "127.0.0.1", - 20881, - DemoService.class.getName(), - parameters); + URL subscribeUrl = new ServiceConfigURL("dubbo", "127.0.0.1", 20881, DemoService.class.getName(), parameters); RegistryServiceListener listener = Mockito.mock(RegistryServiceListener.class); RegistryServiceListener1.delegate = listener; @@ -81,5 +73,4 @@ class ListenerRegistryWrapperTest { registryWrapper.subscribe(subscribeUrl, notifyListener); verify(listener, times(1)).onSubscribe(subscribeUrl, registry); } - } diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/MockCacheableRegistryImpl.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/MockCacheableRegistryImpl.java index 50fa724a97..cfcf7aa080 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/MockCacheableRegistryImpl.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/MockCacheableRegistryImpl.java @@ -51,14 +51,10 @@ public class MockCacheableRegistryImpl extends CacheableFailbackRegistry { } @Override - public void doRegister(URL url) { - - } + public void doRegister(URL url) {} @Override - public void doUnregister(URL url) { - - } + public void doUnregister(URL url) {} @Override public void doSubscribe(URL url, NotifyListener listener) { diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/MockLogger.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/MockLogger.java index e2a80dd6cb..2a8c336543 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/MockLogger.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/MockLogger.java @@ -34,79 +34,49 @@ public class MockLogger implements Logger { } @Override - public void trace(String msg) { - - } + public void trace(String msg) {} @Override - public void trace(String msg, Object... arguments) { - - } + public void trace(String msg, Object... arguments) {} @Override - public void trace(Throwable e) { - - } + public void trace(Throwable e) {} @Override - public void trace(String msg, Throwable e) { - - } + public void trace(String msg, Throwable e) {} @Override - public void debug(String msg) { - - } + public void debug(String msg) {} @Override - public void debug(String msg, Object... arguments) { - - } + public void debug(String msg, Object... arguments) {} @Override - public void debug(Throwable e) { - - } + public void debug(Throwable e) {} @Override - public void debug(String msg, Throwable e) { - - } + public void debug(String msg, Throwable e) {} @Override - public void info(String msg) { - - } + public void info(String msg) {} @Override - public void info(String msg, Object... arguments) { - - } + public void info(String msg, Object... arguments) {} @Override - public void info(Throwable e) { - - } + public void info(Throwable e) {} @Override - public void info(String msg, Throwable e) { - - } + public void info(String msg, Throwable e) {} @Override - public void warn(String msg) { - - } + public void warn(String msg) {} @Override - public void warn(String msg, Object... arguments) { - - } + public void warn(String msg, Object... arguments) {} @Override - public void warn(Throwable e) { - - } + public void warn(Throwable e) {} @Override public void warn(String msg, Throwable e) { @@ -114,24 +84,16 @@ public class MockLogger implements Logger { } @Override - public void error(String msg) { - - } + public void error(String msg) {} @Override - public void error(String msg, Object... arguments) { - - } + public void error(String msg, Object... arguments) {} @Override - public void error(Throwable e) { - - } + public void error(Throwable e) {} @Override - public void error(String msg, Throwable e) { - - } + public void error(String msg, Throwable e) {} @Override public boolean isTraceEnabled() { diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/PerformanceRegistryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/PerformanceRegistryTest.java index fdf5d25ccb..1c024d9b5a 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/PerformanceRegistryTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/PerformanceRegistryTest.java @@ -31,7 +31,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNDEF */ class PerformanceRegistryTest { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PerformanceRegistryTest.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(PerformanceRegistryTest.class); @Test void testRegistry() { @@ -44,16 +45,23 @@ class PerformanceRegistryTest { final int concurrent = PerformanceUtils.getIntProperty("concurrent", 100); int r = PerformanceUtils.getIntProperty("runs", 1000); final int runs = r > 0 ? r : Integer.MAX_VALUE; - final Registry registry = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension().getRegistry(URL.valueOf("remote://admin:hello1234@" + PerformanceUtils.getProperty("server", "10.20.153.28:9090"))); + final Registry registry = ExtensionLoader.getExtensionLoader(RegistryFactory.class) + .getAdaptiveExtension() + .getRegistry(URL.valueOf( + "remote://admin:hello1234@" + PerformanceUtils.getProperty("server", "10.20.153.28:9090"))); for (int i = 0; i < concurrent; i++) { final int t = i; new Thread(new Runnable() { - public void run() { - for (int j = 0; j < runs; j++) { - registry.register(URL.valueOf("remote://" + NetUtils.getLocalHost() + ":8080/demoService" + t + "_" + j + "?version=1.0.0&application=demo&dubbo=2.0&interface=" + "org.apache.dubbo.demo.DemoService" + (base + t) + "_" + (base + j))); - } - } - }).start(); + public void run() { + for (int j = 0; j < runs; j++) { + registry.register( + URL.valueOf("remote://" + NetUtils.getLocalHost() + ":8080/demoService" + t + + "_" + j + "?version=1.0.0&application=demo&dubbo=2.0&interface=" + + "org.apache.dubbo.demo.DemoService" + (base + t) + "_" + (base + j))); + } + } + }) + .start(); } synchronized (PerformanceRegistryTest.class) { while (true) { @@ -64,5 +72,4 @@ class PerformanceRegistryTest { } } } - } diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/PerformanceUtils.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/PerformanceUtils.java index a5c43cf793..51238d8a40 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/PerformanceUtils.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/PerformanceUtils.java @@ -57,11 +57,14 @@ public class PerformanceUtils { public static List getEnvironment() { List environment = new ArrayList(); - environment.add("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch", "")); + environment.add("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + + System.getProperty("os.arch", "")); environment.add("CPU: " + Runtime.getRuntime().availableProcessors() + " cores"); - environment.add("JVM: " + System.getProperty("java.vm.name") + " " + System.getProperty("java.runtime.version")); - environment.add("Memory: " + DecimalFormat.getIntegerInstance().format(Runtime.getRuntime().totalMemory()) - + " bytes (Max: " + DecimalFormat.getIntegerInstance().format(Runtime.getRuntime().maxMemory()) + " bytes)"); + environment.add( + "JVM: " + System.getProperty("java.vm.name") + " " + System.getProperty("java.runtime.version")); + environment.add("Memory: " + + DecimalFormat.getIntegerInstance().format(Runtime.getRuntime().totalMemory()) + " bytes (Max: " + + DecimalFormat.getIntegerInstance().format(Runtime.getRuntime().maxMemory()) + " bytes)"); NetworkInterface ni = PerformanceUtils.getNetworkInterface(); if (ni != null) { environment.add("Network: " + ni.getDisplayName()); @@ -123,5 +126,4 @@ public class PerformanceUtils { } return null; } - } diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/RegistryFactoryWrapperTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/RegistryFactoryWrapperTest.java index c87b31c750..4684e32452 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/RegistryFactoryWrapperTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/RegistryFactoryWrapperTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.registry; import org.apache.dubbo.common.URL; @@ -24,7 +23,8 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; class RegistryFactoryWrapperTest { - private RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension(); + private RegistryFactory registryFactory = + ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension(); @Test void test() throws Exception { @@ -33,7 +33,8 @@ class RegistryFactoryWrapperTest { RegistryServiceListener listener2 = Mockito.mock(RegistryServiceListener.class); RegistryServiceListener2.delegate = listener2; - Registry registry = registryFactory.getRegistry(URL.valueOf("simple://localhost:8080/registry-service?registry.listeners=listener-one,listener-two")); + Registry registry = registryFactory.getRegistry( + URL.valueOf("simple://localhost:8080/registry-service?registry.listeners=listener-one,listener-two")); URL url = URL.valueOf("dubbo://localhost:8081/simple.service"); registry.register(url); @@ -52,5 +53,4 @@ class RegistryFactoryWrapperTest { Mockito.verify(listener1, Mockito.times(1)).onUnsubscribe(url, SimpleRegistryFactory.registry); Mockito.verify(listener2, Mockito.times(1)).onUnsubscribe(url, SimpleRegistryFactory.registry); } - } diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/RegistryServiceListener1.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/RegistryServiceListener1.java index 391e0e1384..9ea7ab713b 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/RegistryServiceListener1.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/RegistryServiceListener1.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.registry; import org.apache.dubbo.common.URL; diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/RegistryServiceListener2.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/RegistryServiceListener2.java index 3cf932e0ac..7838333570 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/RegistryServiceListener2.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/RegistryServiceListener2.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.registry; import org.apache.dubbo.common.URL; diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/SimpleRegistryFactory.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/SimpleRegistryFactory.java index 37466c8a40..c81ca90645 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/SimpleRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/SimpleRegistryFactory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.registry; import org.apache.dubbo.common.URL; @@ -23,6 +22,7 @@ import org.mockito.Mockito; public class SimpleRegistryFactory implements RegistryFactory { static Registry registry = Mockito.mock(Registry.class); + @Override public Registry getRegistry(URL url) { return registry; diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/ZKTools.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/ZKTools.java index fcd3dcd76c..aedbed0727 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/ZKTools.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/ZKTools.java @@ -19,6 +19,14 @@ package org.apache.dubbo.registry; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.common.utils.StringUtils; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.CuratorEvent; @@ -30,51 +38,46 @@ import org.apache.curator.framework.recipes.cache.TreeCacheEvent; import org.apache.curator.framework.recipes.cache.TreeCacheListener; import org.apache.curator.retry.ExponentialBackoffRetry; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - /** * */ public class ZKTools { private static CuratorFramework client; - private static ExecutorService executor = Executors.newFixedThreadPool(1, new NamedThreadFactory("ZKTools-test", true)); + private static ExecutorService executor = + Executors.newFixedThreadPool(1, new NamedThreadFactory("ZKTools-test", true)); public static void main(String[] args) throws Exception { - client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", 60 * 1000, 60 * 1000, - new ExponentialBackoffRetry(1000, 3)); + client = CuratorFrameworkFactory.newClient( + "127.0.0.1:2181", 60 * 1000, 60 * 1000, new ExponentialBackoffRetry(1000, 3)); client.start(); - client.getCuratorListenable().addListener(new CuratorListener() { - @Override - public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { - System.out.println("event notification: " + event.getPath()); - System.out.println(event); - } - }, executor); + client.getCuratorListenable() + .addListener( + new CuratorListener() { + @Override + public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { + System.out.println("event notification: " + event.getPath()); + System.out.println(event); + } + }, + executor); -// testMigrationRule(); + // testMigrationRule(); testAppMigrationRule(); -// tesConditionRule(); -// testStartupConfig(); -// testProviderConfig(); -// testPathCache(); -// testTreeCache(); -// testCuratorListener(); -// Thread.sleep(100000); + // tesConditionRule(); + // testStartupConfig(); + // testProviderConfig(); + // testPathCache(); + // testTreeCache(); + // testCuratorListener(); + // Thread.sleep(100000); } public static void testMigrationRule() { - String serviceStr = "key: demo-consumer\n" + - "interfaces:\n" + - " - serviceKey: org.apache.dubbo.demo.DemoService:1.0.0\n" + - " threshold: 1.0\n" + - " step: FORCE_APPLICATION"; + String serviceStr = "key: demo-consumer\n" + "interfaces:\n" + + " - serviceKey: org.apache.dubbo.demo.DemoService:1.0.0\n" + + " threshold: 1.0\n" + + " step: FORCE_APPLICATION"; try { String servicePath = "/dubbo/config/DUBBO_SERVICEDISCOVERY_MIGRATION/demo-consumer.migration"; if (client.checkExists().forPath(servicePath) == null) { @@ -87,15 +90,14 @@ public class ZKTools { } public static void testAppMigrationRule() { - String serviceStr = "key: demo-consumer\n" + - "applications:\n" + - " - name: demo-provider\n" + - " step: FORCE_APPLICATION\n" + - " threshold: 0.8\n" + - "interfaces:\n" + - " - serviceKey: org.apache.dubbo.demo.DemoService\n" + - " threshold: 1.0\n" + - " step: FORCE_APPLICATION"; + String serviceStr = "key: demo-consumer\n" + "applications:\n" + + " - name: demo-provider\n" + + " step: FORCE_APPLICATION\n" + + " threshold: 0.8\n" + + "interfaces:\n" + + " - serviceKey: org.apache.dubbo.demo.DemoService\n" + + " threshold: 1.0\n" + + " step: FORCE_APPLICATION"; try { String servicePath = "/dubbo/config/DUBBO_SERVICEDISCOVERY_MIGRATION/demo-consumer.migration"; if (client.checkExists().forPath(servicePath) == null) { @@ -108,13 +110,13 @@ public class ZKTools { } public static void testStartupConfig() { - String str = "dubbo.registry.address=zookeeper://127.0.0.1:2181\n" + - "dubbo.registry.group=dubboregistrygroup1\n" + - "dubbo.metadata-report.address=zookeeper://127.0.0.1:2181\n" + - "dubbo.protocol.port=20990\n" + - "dubbo.service.org.apache.dubbo.demo.DemoService.timeout=9999\n"; + String str = + "dubbo.registry.address=zookeeper://127.0.0.1:2181\n" + "dubbo.registry.group=dubboregistrygroup1\n" + + "dubbo.metadata-report.address=zookeeper://127.0.0.1:2181\n" + + "dubbo.protocol.port=20990\n" + + "dubbo.service.org.apache.dubbo.demo.DemoService.timeout=9999\n"; -// System.out.println(str); + // System.out.println(str); try { String path = "/dubboregistrygroup1/config/dubbo/dubbo.properties"; @@ -128,19 +130,18 @@ public class ZKTools { } public static void testProviderConfig() { - String str = "---\n" + - "apiVersion: v2.7\n" + - "scope: service\n" + - "key: dd-test/org.apache.dubbo.demo.DemoService:1.0.4\n" + - "enabled: true\n" + - "configs:\n" + - "- addresses: ['0.0.0.0:20880']\n" + - " side: provider\n" + - " parameters:\n" + - " timeout: 6000\n" + - "..."; + String str = "---\n" + "apiVersion: v2.7\n" + + "scope: service\n" + + "key: dd-test/org.apache.dubbo.demo.DemoService:1.0.4\n" + + "enabled: true\n" + + "configs:\n" + + "- addresses: ['0.0.0.0:20880']\n" + + " side: provider\n" + + " parameters:\n" + + " timeout: 6000\n" + + "..."; -// System.out.println(str); + // System.out.println(str); try { String path = "/dubbo/config/dd-test*org.apache.dubbo.demo.DemoService:1.0.4/configurators"; @@ -166,35 +167,33 @@ public class ZKTools { } public static void testConsumerConfig() { - String serviceStr = "---\n" + - "scope: service\n" + - "key: org.apache.dubbo.demo.DemoService\n" + - "configs:\n" + - " - addresses: [30.5.121.156]\n" + - " side: consumer\n" + - " rules:\n" + - " cluster:\n" + - " loadbalance: random\n" + - " cluster: failfast\n" + - " config:\n" + - " timeout: 9999\n" + - " weight: 222\n" + - "..."; - String appStr = "---\n" + - "scope: application\n" + - "key: demo-consumer\n" + - "configs:\n" + - " - addresses: [30.5.121.156]\n" + - " services: [org.apache.dubbo.demo.DemoService]\n" + - " side: consumer\n" + - " rules:\n" + - " cluster:\n" + - " loadbalance: random\n" + - " cluster: failfast\n" + - " config:\n" + - " timeout: 4444\n" + - " weight: 222\n" + - "..."; + String serviceStr = "---\n" + "scope: service\n" + + "key: org.apache.dubbo.demo.DemoService\n" + + "configs:\n" + + " - addresses: [30.5.121.156]\n" + + " side: consumer\n" + + " rules:\n" + + " cluster:\n" + + " loadbalance: random\n" + + " cluster: failfast\n" + + " config:\n" + + " timeout: 9999\n" + + " weight: 222\n" + + "..."; + String appStr = "---\n" + "scope: application\n" + + "key: demo-consumer\n" + + "configs:\n" + + " - addresses: [30.5.121.156]\n" + + " services: [org.apache.dubbo.demo.DemoService]\n" + + " side: consumer\n" + + " rules:\n" + + " cluster:\n" + + " loadbalance: random\n" + + " cluster: failfast\n" + + " config:\n" + + " timeout: 4444\n" + + " weight: 222\n" + + "..."; try { String servicePath = "/dubbo/config/org.apache.dubbo.demo.DemoService/configurators"; if (client.checkExists().forPath(servicePath) == null) { @@ -213,14 +212,13 @@ public class ZKTools { } public static void tesConditionRule() { - String serviceStr = "---\n" + - "scope: application\n" + - "force: true\n" + - "runtime: false\n" + - "conditions:\n" + - " - method!=sayHello =>\n" + - " - method=routeMethod1 => 30.5.121.156:20880\n" + - "..."; + String serviceStr = "---\n" + "scope: application\n" + + "force: true\n" + + "runtime: false\n" + + "conditions:\n" + + " - method!=sayHello =>\n" + + " - method=routeMethod1 => 30.5.121.156:20880\n" + + "..."; try { String servicePath = "/dubbo/config/demo-consumer/routers"; if (client.checkExists().forPath(servicePath) == null) { @@ -237,26 +235,31 @@ public class ZKTools { } public static void testPathCache() throws Exception { - CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", 60 * 1000, 60 * 1000, - new ExponentialBackoffRetry(1000, 3)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + "127.0.0.1:2181", 60 * 1000, 60 * 1000, new ExponentialBackoffRetry(1000, 3)); client.start(); PathChildrenCache pathChildrenCache = new PathChildrenCache(client, "/dubbo/config", true); pathChildrenCache.start(true); - pathChildrenCache.getListenable().addListener((zkClient, event) -> { - System.out.println(event.getData().getPath()); - }, Executors.newFixedThreadPool(1)); + pathChildrenCache + .getListenable() + .addListener( + (zkClient, event) -> { + System.out.println(event.getData().getPath()); + }, + Executors.newFixedThreadPool(1)); List dataList = pathChildrenCache.getCurrentData(); dataList.stream().map(ChildData::getPath).forEach(System.out::println); } public static void testTreeCache() throws Exception { - CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", 60 * 1000, 60 * 1000, - new ExponentialBackoffRetry(1000, 3)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + "127.0.0.1:2181", 60 * 1000, 60 * 1000, new ExponentialBackoffRetry(1000, 3)); client.start(); CountDownLatch latch = new CountDownLatch(1); - TreeCache treeCache = TreeCache.newBuilder(client, "/dubbo/config").setCacheData(true).build(); + TreeCache treeCache = + TreeCache.newBuilder(client, "/dubbo/config").setCacheData(true).build(); treeCache.start(); treeCache.getListenable().addListener(new TreeCacheListener() { @Override @@ -302,7 +305,7 @@ public class ZKTools { latch.await(); - /* Map dataMap = treeCache.getCurrentChildren("/dubbo/config"); + /* Map dataMap = treeCache.getCurrentChildren("/dubbo/config"); dataMap.forEach((k, v) -> { System.out.println(k); treeCache.getCurrentChildren("/dubbo/config/" + k).forEach((ck, cv) -> { @@ -319,21 +322,21 @@ public class ZKTools { } public static void testCuratorListener() throws Exception { - CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", 60 * 1000, 60 * 1000, - new ExponentialBackoffRetry(1000, 3)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + "127.0.0.1:2181", 60 * 1000, 60 * 1000, new ExponentialBackoffRetry(1000, 3)); client.start(); List children = client.getChildren().forPath("/dubbo/config"); children.forEach(System.out::println); -/* + /* - client.getCuratorListenable().addListener(new CuratorListener() { - @Override - public void eventReceived(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception { - curatorEvent.get - } - }); -*/ + client.getCuratorListenable().addListener(new CuratorListener() { + @Override + public void eventReceived(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception { + curatorEvent.get + } + }); + */ /*client.getChildren().usingWatcher(new CuratorWatcher() { @Override diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/AbstractServiceDiscoveryFactoryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/AbstractServiceDiscoveryFactoryTest.java index 65b39fc83a..99f72eeb2c 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/AbstractServiceDiscoveryFactoryTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/AbstractServiceDiscoveryFactoryTest.java @@ -20,11 +20,11 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.List; - /** * {@link AbstractServiceDiscoveryFactory} */ @@ -32,7 +32,9 @@ class AbstractServiceDiscoveryFactoryTest { @Test void testGetServiceDiscoveryWithCache() { - ApplicationModel.defaultModel().getApplicationConfigManager().setApplication(new ApplicationConfig("AbstractServiceDiscoveryFactoryTest")); + ApplicationModel.defaultModel() + .getApplicationConfigManager() + .setApplication(new ApplicationConfig("AbstractServiceDiscoveryFactoryTest")); URL url = URL.valueOf("mock://127.0.0.1:8888"); ServiceDiscoveryFactory factory = ServiceDiscoveryFactory.getExtension(url); ServiceDiscovery serviceDiscovery1 = factory.getServiceDiscovery(url); diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/DefaultServiceInstanceTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/DefaultServiceInstanceTest.java index 11c618d651..742ba2e8a9 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/DefaultServiceInstanceTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/DefaultServiceInstanceTest.java @@ -18,12 +18,12 @@ package org.apache.dubbo.registry.client; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.EXPORTED_SERVICES_REVISION_PROPERTY_NAME; import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.METADATA_STORAGE_TYPE_PROPERTY_NAME; import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getEndpoint; @@ -42,7 +42,8 @@ class DefaultServiceInstanceTest { public DefaultServiceInstance instance; public static DefaultServiceInstance createInstance() { - DefaultServiceInstance instance = new DefaultServiceInstance("A", "127.0.0.1", 20880, ApplicationModel.defaultModel()); + DefaultServiceInstance instance = + new DefaultServiceInstance("A", "127.0.0.1", 20880, ApplicationModel.defaultModel()); Map metadata = instance.getMetadata(); metadata.put(METADATA_STORAGE_TYPE_PROPERTY_NAME, "remote"); metadata.put(EXPORTED_SERVICES_REVISION_PROPERTY_NAME, "111"); @@ -94,7 +95,8 @@ class DefaultServiceInstanceTest { assertEquals("value", allParams2.get("key")); // test equals - DefaultServiceInstance instance2 = new DefaultServiceInstance("A", "127.0.0.1", 20880, ApplicationModel.defaultModel()); + DefaultServiceInstance instance2 = + new DefaultServiceInstance("A", "127.0.0.1", 20880, ApplicationModel.defaultModel()); instance2.setMetadata(new HashMap<>(instance.getMetadata())); instance2.getMetadata().put(EXPORTED_SERVICES_REVISION_PROPERTY_NAME, "222"); // assert instances with different revision and extend params are equal diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/FileSystemServiceDiscoveryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/FileSystemServiceDiscoveryTest.java deleted file mode 100644 index 6e8b8b4026..0000000000 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/FileSystemServiceDiscoveryTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.dubbo.registry.client; -// -//import org.apache.dubbo.common.URLBuilder; -// -//import org.junit.jupiter.api.AfterEach; -//import org.junit.jupiter.api.BeforeEach; -//import org.junit.jupiter.api.Disabled; -//import org.junit.jupiter.api.Test; -// -//import static org.apache.dubbo.registry.client.DefaultServiceInstanceTest.createInstance; -// -//@Disabled("FileSystemServiceDiscovery implementation is not stable enough at present") -//public class FileSystemServiceDiscoveryTest { -// -// private FileSystemServiceDiscovery serviceDiscovery; -// -// private ServiceInstance serviceInstance; -// -// @BeforeEach -// public void init() throws Exception { -// serviceDiscovery = new FileSystemServiceDiscovery(); -// serviceDiscovery.initialize(new URLBuilder().build()); -// serviceInstance = createInstance(); -// } -// -// @AfterEach -// public void destroy() throws Exception { -// serviceDiscovery.destroy(); -// serviceInstance = null; -// } -// -// @Test -// public void testRegisterAndUnregister() { -// -// serviceDiscovery.register(serviceInstance); -// -// serviceDiscovery.unregister(serviceInstance); -// -// serviceDiscovery.register(serviceInstance); -// } -//} diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InstanceAddressURLTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InstanceAddressURLTest.java index 1667dba8e0..28c00b73ef 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InstanceAddressURLTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/InstanceAddressURLTest.java @@ -24,11 +24,6 @@ import org.apache.dubbo.rpc.RpcServiceContext; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - import java.util.Arrays; import java.util.Collections; import java.util.HashMap; @@ -36,6 +31,11 @@ import java.util.HashSet; import java.util.Map; import java.util.Set; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY; @@ -51,25 +51,28 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; class InstanceAddressURLTest { - private static URL url = URL.valueOf("dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService?" + - "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=1000&deprecated=false&dubbo=2.0.2" + - "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService" + - "&metadata-type=remote&methods=sayHello&sayHello.timeout=7000&a.timeout=7777&pid=66666&release=&revision=1.0.0&service-name-mapping=true" + - "&side=provider&timeout=1000×tamp=1629970909999&version=1.0.0&dubbo.tag=provider¶ms-filter=-default"); + private static URL url = URL.valueOf( + "dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService?" + + "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=1000&deprecated=false&dubbo=2.0.2" + + "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService" + + "&metadata-type=remote&methods=sayHello&sayHello.timeout=7000&a.timeout=7777&pid=66666&release=&revision=1.0.0&service-name-mapping=true" + + "&side=provider&timeout=1000×tamp=1629970909999&version=1.0.0&dubbo.tag=provider¶ms-filter=-default"); - private static URL url2 = URL.valueOf("dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService2?" + - "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2" + - "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService2" + - "&metadata-type=remote&methods=sayHello&sayHello.timeout=7000&pid=36621&release=&revision=1.0.0&service-name-mapping=true" + - "&side=provider&timeout=5000×tamp=1629970068002&version=1.0.0&dubbo.tag=provider2&uniqueKey=unique¶ms-filter=-default"); + private static URL url2 = URL.valueOf( + "dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService2?" + + "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2" + + "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService2" + + "&metadata-type=remote&methods=sayHello&sayHello.timeout=7000&pid=36621&release=&revision=1.0.0&service-name-mapping=true" + + "&side=provider&timeout=5000×tamp=1629970068002&version=1.0.0&dubbo.tag=provider2&uniqueKey=unique¶ms-filter=-default"); - private static URL consumerURL = URL.valueOf("dubbo://30.225.21.30/org.apache.dubbo.registry.service.DemoService?" + - "REGISTRY_CLUSTER=registry1&application=demo-consumer&dubbo=2.0.2" + - "&group=greeting&interface=org.apache.dubbo.registry.service.DemoService" + - "&version=1.0.0&timeout=9000&a.timeout=8888&dubbo.tag=consumer&protocol=dubbo"); + private static URL consumerURL = URL.valueOf("dubbo://30.225.21.30/org.apache.dubbo.registry.service.DemoService?" + + "REGISTRY_CLUSTER=registry1&application=demo-consumer&dubbo=2.0.2" + + "&group=greeting&interface=org.apache.dubbo.registry.service.DemoService" + + "&version=1.0.0&timeout=9000&a.timeout=8888&dubbo.tag=consumer&protocol=dubbo"); private DefaultServiceInstance createInstance() { - DefaultServiceInstance instance = new DefaultServiceInstance("demo-provider", "127.0.0.1", 8080, ApplicationModel.defaultModel()); + DefaultServiceInstance instance = + new DefaultServiceInstance("demo-provider", "127.0.0.1", 8080, ApplicationModel.defaultModel()); Map metadata = instance.getMetadata(); metadata.put("key1", "value1"); metadata.put("key2", "value2"); @@ -85,19 +88,22 @@ class InstanceAddressURLTest { } private InstanceAddressURL instanceURL; - private volatile transient Set providerFirstParams; + private transient volatile Set providerFirstParams; @BeforeEach public void setUp() { DefaultServiceInstance instance = createInstance(); MetadataInfo metadataInfo = createMetaDataInfo(); instanceURL = new InstanceAddressURL(instance, metadataInfo); - Set providerFirstParams = ApplicationModel.defaultModel().getExtensionLoader(ProviderFirstParams.class).getSupportedExtensionInstances(); + Set providerFirstParams = ApplicationModel.defaultModel() + .getExtensionLoader(ProviderFirstParams.class) + .getSupportedExtensionInstances(); if (CollectionUtils.isEmpty(providerFirstParams)) { this.providerFirstParams = null; } else { if (providerFirstParams.size() == 1) { - this.providerFirstParams = Collections.unmodifiableSet(providerFirstParams.iterator().next().params()); + this.providerFirstParams = Collections.unmodifiableSet( + providerFirstParams.iterator().next().params()); } else { Set params = new HashSet<>(); for (ProviderFirstParams paramsFilter : providerFirstParams) { @@ -115,20 +121,22 @@ class InstanceAddressURLTest { @Test void test1() { // test reading of keys in instance and metadata work fine - assertEquals("value1", instanceURL.getParameter("key1"));//return instance key - assertNull(instanceURL.getParameter("delay"));// no service key specified + assertEquals("value1", instanceURL.getParameter("key1")); // return instance key + assertNull(instanceURL.getParameter("delay")); // no service key specified RpcServiceContext.getServiceContext().setConsumerUrl(consumerURL); assertEquals("1000", instanceURL.getParameter("delay")); assertEquals("1000", instanceURL.getServiceParameter(consumerURL.getProtocolServiceKey(), "delay")); assertEquals("9000", instanceURL.getMethodParameter("sayHello", "timeout")); - assertEquals("9000", instanceURL.getServiceMethodParameter(consumerURL.getProtocolServiceKey(), "sayHello", "timeout")); + assertEquals( + "9000", + instanceURL.getServiceMethodParameter(consumerURL.getProtocolServiceKey(), "sayHello", "timeout")); assertNull(instanceURL.getParameter("uniqueKey")); assertNull(instanceURL.getServiceParameter(consumerURL.getProtocolServiceKey(), "uniqueKey")); assertEquals("unique", instanceURL.getServiceParameter(url2.getProtocolServiceKey(), "uniqueKey")); - // test some consumer keys have higher priority - assertEquals("8888", instanceURL.getServiceMethodParameter(consumerURL.getProtocolServiceKey(), "a", "timeout")); + assertEquals( + "8888", instanceURL.getServiceMethodParameter(consumerURL.getProtocolServiceKey(), "a", "timeout")); assertEquals("9000", instanceURL.getParameter("timeout")); // test some provider keys have higher priority @@ -141,18 +149,23 @@ class InstanceAddressURLTest { assertEquals(instanceURL.getRemoteApplication(), instanceURL.getParameter(REMOTE_APPLICATION_KEY)); assertEquals("demo-provider", instanceURL.getParameter(REMOTE_APPLICATION_KEY)); assertEquals(instanceURL.getSide(), instanceURL.getParameter(SIDE_KEY)); -// assertThat(Arrays.asList("7000", "8888"), hasItem(instanceURL.getAnyMethodParameter("timeout"))); + // assertThat(Arrays.asList("7000", "8888"), hasItem(instanceURL.getAnyMethodParameter("timeout"))); assertThat(instanceURL.getAnyMethodParameter("timeout"), in(Arrays.asList("7000", "8888"))); Map expectedAllParams = new HashMap<>(); expectedAllParams.putAll(instanceURL.getInstance().getMetadata()); - expectedAllParams.putAll(instanceURL.getMetadataInfo().getServiceInfo(consumerURL.getProtocolServiceKey()).getAllParams()); + expectedAllParams.putAll(instanceURL + .getMetadataInfo() + .getServiceInfo(consumerURL.getProtocolServiceKey()) + .getAllParams()); Map consumerURLParameters = consumerURL.getParameters(); providerFirstParams.forEach(consumerURLParameters::remove); expectedAllParams.putAll(consumerURLParameters); assertEquals(expectedAllParams.size(), instanceURL.getParameters().size()); assertEquals(url.getParameter(TAG_KEY), instanceURL.getParameters().get(TAG_KEY)); - assertEquals(consumerURL.getParameter(TIMEOUT_KEY), instanceURL.getParameters().get(TIMEOUT_KEY)); + assertEquals( + consumerURL.getParameter(TIMEOUT_KEY), + instanceURL.getParameters().get(TIMEOUT_KEY)); assertTrue(instanceURL.hasServiceMethodParameter(url.getProtocolServiceKey(), "a")); assertTrue(instanceURL.hasServiceMethodParameter(url.getProtocolServiceKey(), "sayHello")); assertTrue(instanceURL.hasMethodParameter("a", TIMEOUT_KEY)); @@ -165,7 +178,9 @@ class InstanceAddressURLTest { instanceURL.addParameter("newKey", "newValue"); assertEquals("newValue", instanceURL.getParameter("newKey")); assertEquals("newValue", instanceURL.getParameters().get("newKey")); - assertEquals("newValue", instanceURL.getServiceParameters(url.getProtocolServiceKey()).get("newKey")); + assertEquals( + "newValue", + instanceURL.getServiceParameters(url.getProtocolServiceKey()).get("newKey")); } @Test @@ -177,5 +192,4 @@ class InstanceAddressURLTest { RpcServiceContext.getServiceContext().setConsumerUrl(URL.valueOf("").setScopeModel(moduleModel)); Assertions.assertEquals(moduleModel, instanceURL.getScopeModel()); } - } diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryCacheTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryCacheTest.java index 9b759b8ef4..a12f414cba 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryCacheTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryCacheTest.java @@ -16,16 +16,17 @@ */ package org.apache.dubbo.registry.client; -import java.util.LinkedList; -import java.util.List; -import java.util.Objects; - import org.apache.dubbo.common.URL; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.metadata.MetadataInfo; import org.apache.dubbo.registry.client.support.MockServiceDiscovery; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; + +import java.util.LinkedList; +import java.util.List; +import java.util.Objects; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -41,15 +42,19 @@ class ServiceDiscoveryCacheTest { applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("Test")); URL registryUrl = URL.valueOf("mock://127.0.0.1:12345").addParameter(METADATA_INFO_CACHE_EXPIRE_KEY, 10); - MockServiceDiscovery mockServiceDiscovery = Mockito.spy(new MockServiceDiscovery(applicationModel, registryUrl)); + MockServiceDiscovery mockServiceDiscovery = + Mockito.spy(new MockServiceDiscovery(applicationModel, registryUrl)); mockServiceDiscovery.register(URL.valueOf("mock://127.0.0.1:12345") - .setServiceInterface("org.apache.dubbo.registry.service.DemoService")); + .setServiceInterface("org.apache.dubbo.registry.service.DemoService")); mockServiceDiscovery.register(); ServiceInstance localInstance = mockServiceDiscovery.getLocalInstance(); - Assertions.assertEquals(localInstance.getServiceMetadata(), mockServiceDiscovery.getLocalMetadata(localInstance.getServiceMetadata().getRevision())); + Assertions.assertEquals( + localInstance.getServiceMetadata(), + mockServiceDiscovery.getLocalMetadata( + localInstance.getServiceMetadata().getRevision())); List instances = new LinkedList<>(); instances.add(localInstance.getServiceMetadata().clone()); @@ -57,9 +62,10 @@ class ServiceDiscoveryCacheTest { for (int i = 0; i < 15; i++) { Thread.sleep(1); mockServiceDiscovery.register(URL.valueOf("mock://127.0.0.1:12345") - .setServiceInterface("org.apache.dubbo.registry.service.DemoService" + i)); + .setServiceInterface("org.apache.dubbo.registry.service.DemoService" + i)); mockServiceDiscovery.update(); - instances.add(mockServiceDiscovery.getLocalInstance().getServiceMetadata().clone()); + instances.add( + mockServiceDiscovery.getLocalInstance().getServiceMetadata().clone()); } for (MetadataInfo instance : instances) { @@ -69,15 +75,18 @@ class ServiceDiscoveryCacheTest { for (int i = 0; i < 5; i++) { Thread.sleep(1); mockServiceDiscovery.register(URL.valueOf("mock://127.0.0.1:12345") - .setServiceInterface("org.apache.dubbo.registry.service.DemoService-new" + i)); + .setServiceInterface("org.apache.dubbo.registry.service.DemoService-new" + i)); mockServiceDiscovery.update(); - instances.add(mockServiceDiscovery.getLocalInstance().getServiceMetadata().clone()); + instances.add( + mockServiceDiscovery.getLocalInstance().getServiceMetadata().clone()); } - await().until(() -> Objects.isNull(mockServiceDiscovery.getLocalMetadata(instances.get(4).getRevision()))); + await().until(() -> Objects.isNull( + mockServiceDiscovery.getLocalMetadata(instances.get(4).getRevision()))); for (int i = 0; i < 5; i++) { - Assertions.assertNull(mockServiceDiscovery.getLocalMetadata(instances.get(i).getRevision())); + Assertions.assertNull( + mockServiceDiscovery.getLocalMetadata(instances.get(i).getRevision())); } applicationModel.destroy(); diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryTest.java index 72bb09cbd5..f1711eb3b3 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryTest.java @@ -26,12 +26,6 @@ import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedLi import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; - import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; @@ -42,6 +36,12 @@ import java.util.TreeSet; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO; import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY; @@ -69,8 +69,10 @@ class ServiceDiscoveryRegistryTest { private static AbstractServiceNameMapping mapping = mock(AbstractServiceNameMapping.class); private static Lock lock = new ReentrantLock(); - private static URL registryURL = URL.valueOf("zookeeper://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService"); - private static URL url = URL.valueOf("consumer://127.0.0.1/TestService?interface=TestService1&check=false&protocol=dubbo"); + private static URL registryURL = + URL.valueOf("zookeeper://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService"); + private static URL url = + URL.valueOf("consumer://127.0.0.1/TestService?interface=TestService1&check=false&protocol=dubbo"); private static NotifyListener testServiceListener = mock(NotifyListener.class); private static List instanceList1 = new ArrayList<>(); @@ -89,7 +91,6 @@ class ServiceDiscoveryRegistryTest { instanceList2.add(new DefaultServiceInstance()); instanceList2.add(new DefaultServiceInstance()); - } @AfterEach @@ -136,20 +137,20 @@ class ServiceDiscoveryRegistryTest { registryURL = registryURL.setScopeModel(null); serviceDiscoveryRegistry.unsubscribe(url, testServiceListener); } -// // when check = true + // // when check = true URL checkURL = url.addParameter(CHECK_KEY, true); checkURL.setScopeModel(url.getApplicationModel()); -// Exception exceptionShouldHappen = null; -// try { -// serviceDiscoveryRegistry.doSubscribe(checkURL, testServiceListener); -// } catch (IllegalStateException e) { -// exceptionShouldHappen = e; -// } finally { -// serviceDiscoveryRegistry.unsubscribe(checkURL, testServiceListener); -// } -// if (exceptionShouldHappen == null) { -// fail(); -// } + // Exception exceptionShouldHappen = null; + // try { + // serviceDiscoveryRegistry.doSubscribe(checkURL, testServiceListener); + // } catch (IllegalStateException e) { + // exceptionShouldHappen = e; + // } finally { + // serviceDiscoveryRegistry.unsubscribe(checkURL, testServiceListener); + // } + // if (exceptionShouldHappen == null) { + // fail(); + // } // Normal case Set singleApp = new HashSet<>(); @@ -161,7 +162,7 @@ class ServiceDiscoveryRegistryTest { serviceDiscoveryRegistry.unsubscribe(checkURL, testServiceListener); } - //test provider case + // test provider case checkURL = url.addParameter(PROVIDED_BY, APP_NAME1); try { @@ -196,7 +197,8 @@ class ServiceDiscoveryRegistryTest { Set multiApps = new TreeSet<>(); multiApps.add(APP_NAME1); multiApps.add(APP_NAME2); - MockServiceInstancesChangedListener multiAppsInstanceListener = spy(new MockServiceInstancesChangedListener(multiApps, serviceDiscovery)); + MockServiceInstancesChangedListener multiAppsInstanceListener = + spy(new MockServiceInstancesChangedListener(multiApps, serviceDiscovery)); doNothing().when(multiAppsInstanceListener).onEvent(any()); List urls = new ArrayList<>(); urls.add(URL.valueOf("dubbo://127.0.0.1:20880/TestService")); @@ -207,8 +209,11 @@ class ServiceDiscoveryRegistryTest { serviceDiscoveryRegistry.subscribeURLs(url, testServiceListener, multiApps); assertEquals(2, serviceDiscoveryRegistry.getServiceListeners().size()); - assertEquals(instanceListener, serviceDiscoveryRegistry.getServiceListeners().get(toStringKeys(singleApp))); - assertEquals(multiAppsInstanceListener, serviceDiscoveryRegistry.getServiceListeners().get(toStringKeys(multiApps))); + assertEquals( + instanceListener, serviceDiscoveryRegistry.getServiceListeners().get(toStringKeys(singleApp))); + assertEquals( + multiAppsInstanceListener, + serviceDiscoveryRegistry.getServiceListeners().get(toStringKeys(multiApps))); verify(testServiceListener, times(1)).addServiceListener(multiAppsInstanceListener); verify(multiAppsInstanceListener, times(2)).onEvent(any()); verify(multiAppsInstanceListener, times(1)).addListenerAndNotify(any(), eq(testServiceListener)); @@ -224,17 +229,24 @@ class ServiceDiscoveryRegistryTest { serviceDiscoveryRegistry.subscribeURLs(url2, testServiceListener2, multiApps); // check instance listeners not changed, methods not called assertEquals(2, serviceDiscoveryRegistry.getServiceListeners().size()); - assertEquals(multiAppsInstanceListener, serviceDiscoveryRegistry.getServiceListeners().get(toStringKeys(multiApps))); + assertEquals( + multiAppsInstanceListener, + serviceDiscoveryRegistry.getServiceListeners().get(toStringKeys(multiApps))); verify(multiAppsInstanceListener, times(1)).addListenerAndNotify(any(), eq(testServiceListener)); // still called once, not executed this time verify(serviceDiscovery, times(2)).addServiceInstancesChangedListener(multiAppsInstanceListener); // check different protocol - Map> serviceListeners = multiAppsInstanceListener.getServiceListeners(); + Map> serviceListeners = + multiAppsInstanceListener.getServiceListeners(); assertEquals(2, serviceListeners.size()); assertEquals(1, serviceListeners.get(url.getServiceKey()).size()); assertEquals(1, serviceListeners.get(url2.getServiceKey()).size()); - ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey(url2.getServiceInterface(), url2.getVersion(), url2.getGroup(), url2.getParameter(PROTOCOL_KEY, DUBBO)); - assertTrue(serviceListeners.get(url2.getServiceKey()).contains(new ServiceInstancesChangedListener.NotifyListenerWithKey(protocolServiceKey, testServiceListener2))); + ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey( + url2.getServiceInterface(), url2.getVersion(), url2.getGroup(), url2.getParameter(PROTOCOL_KEY, DUBBO)); + assertTrue(serviceListeners + .get(url2.getServiceKey()) + .contains(new ServiceInstancesChangedListener.NotifyListenerWithKey( + protocolServiceKey, testServiceListener2))); } /** @@ -262,12 +274,16 @@ class ServiceDiscoveryRegistryTest { when(mapping.getMapping(url2)).thenReturn(multiApps); serviceDiscoveryRegistry.doUnsubscribe(url2, testServiceListener2); assertEquals(1, serviceDiscoveryRegistry.getServiceListeners().size()); - ServiceInstancesChangedListener instancesChangedListener = serviceDiscoveryRegistry.getServiceListeners().entrySet().iterator().next().getValue(); + ServiceInstancesChangedListener instancesChangedListener = serviceDiscoveryRegistry + .getServiceListeners() + .entrySet() + .iterator() + .next() + .getValue(); assertTrue(instancesChangedListener.hasListeners()); when(mapping.getMapping(url)).thenReturn(multiApps); serviceDiscoveryRegistry.doUnsubscribe(url, testServiceListener); assertEquals(0, serviceDiscoveryRegistry.getServiceListeners().size()); assertFalse(instancesChangedListener.hasListeners()); } - } diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryTest.java deleted file mode 100644 index e5a9335145..0000000000 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/ServiceDiscoveryTest.java +++ /dev/null @@ -1,247 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.dubbo.registry.client; -// -//import org.apache.dubbo.common.URL; -//import org.apache.dubbo.common.utils.Page; -//import org.apache.dubbo.rpc.model.ApplicationModel; -//import org.apache.dubbo.rpc.model.ScopeModelUtil; -// -//import org.junit.jupiter.api.AfterEach; -//import org.junit.jupiter.api.BeforeEach; -//import org.junit.jupiter.api.Test; -// -//import java.util.HashSet; -//import java.util.LinkedList; -//import java.util.List; -// -//import static java.util.Arrays.asList; -//import static org.junit.jupiter.api.Assertions.assertEquals; -//import static org.junit.jupiter.api.Assertions.assertFalse; -//import static org.junit.jupiter.api.Assertions.assertNotNull; -//import static org.junit.jupiter.api.Assertions.assertTrue; -// -///** -// * {@link ServiceDiscovery} Test case -// * -// * @since 2.7.5 -// */ -//public class ServiceDiscoveryTest { -// -// private ServiceDiscovery serviceDiscovery; -// -// @BeforeEach -// public void init() throws Exception { -// if (serviceDiscovery == null) { -// setServiceDiscovery(new InMemoryServiceDiscovery("sd-test-app")); -// } -// // test start() -// URL registryUrl = URL.valueOf(""); -// registryUrl = registryUrl.setScopeModel(ApplicationModel.defaultModel()); -// serviceDiscovery.initialize(registryUrl); -// } -// -// @AfterEach -// public void destroy() throws Exception { -// // test stop() -// serviceDiscovery.destroy(); -// } -// -// @Test -// public void testToString() { -// assertEquals("InMemoryServiceDiscovery", serviceDiscovery.toString()); -// } -// -// @Test -// public void testRegisterAndUpdateAndUnregister() { -// -// // register -// serviceDiscovery.register(); -// -// ServiceInstance serviceInstance = serviceDiscovery.getLocalInstance(); -// assertNotNull(serviceInstance); -// -// // update -// serviceDiscovery.update(); -// -// // unregister -// serviceDiscovery.unregister(); -// -// } -// -// @Test -// public void testGetInstances() { -// -// List instances = asList( -// new DefaultServiceInstance("A", "127.0.0.1", 8080, ScopeModelUtil.getApplicationModel(serviceDiscovery.getUrl().getScopeModel())), -// new DefaultServiceInstance("A", "127.0.0.1", 8081, ScopeModelUtil.getApplicationModel(serviceDiscovery.getUrl().getScopeModel())), -// new DefaultServiceInstance("A", "127.0.0.1", 8082, ScopeModelUtil.getApplicationModel(serviceDiscovery.getUrl().getScopeModel())) -// ); -// -// instances.forEach(serviceDiscovery::register); -// -// // Duplicated -// serviceDiscovery.register(new DefaultServiceInstance("A", "127.0.0.1", 8080, ScopeModelUtil.getApplicationModel(serviceDiscovery.getUrl().getScopeModel()))); -// // Duplicated -// serviceDiscovery.register(new DefaultServiceInstance("A", "127.0.0.1", 8081, ScopeModelUtil.getApplicationModel(serviceDiscovery.getUrl().getScopeModel()))); -// -// // offset starts 0 -// int offset = 0; -// // pageSize > total elements -// int pageSize = 5; -// -// Page page = serviceDiscovery.getInstances("A", offset, pageSize); -// assertEquals(0, page.getOffset()); -// assertEquals(5, page.getPageSize()); -// assertEquals(3, page.getTotalSize()); -// assertEquals(3, page.getData().size()); -// assertTrue(page.hasData()); -// -// for (ServiceInstance instance : page.getData()) { -// assertTrue(instances.contains(instance)); -// } -// -// // pageSize < total elements -// pageSize = 2; -// -// page = serviceDiscovery.getInstances("A", offset, pageSize); -// assertEquals(0, page.getOffset()); -// assertEquals(2, page.getPageSize()); -// assertEquals(3, page.getTotalSize()); -// assertEquals(2, page.getData().size()); -// assertTrue(page.hasData()); -// -// for (ServiceInstance instance : page.getData()) { -// assertTrue(instances.contains(instance)); -// } -// -// offset = 1; -// page = serviceDiscovery.getInstances("A", offset, pageSize); -// assertEquals(1, page.getOffset()); -// assertEquals(2, page.getPageSize()); -// assertEquals(3, page.getTotalSize()); -// assertEquals(2, page.getData().size()); -// assertTrue(page.hasData()); -// -// for (ServiceInstance instance : page.getData()) { -// assertTrue(instances.contains(instance)); -// } -// -// offset = 2; -// page = serviceDiscovery.getInstances("A", offset, pageSize); -// assertEquals(2, page.getOffset()); -// assertEquals(2, page.getPageSize()); -// assertEquals(3, page.getTotalSize()); -// assertEquals(1, page.getData().size()); -// assertTrue(page.hasData()); -// -// offset = 3; -// page = serviceDiscovery.getInstances("A", offset, pageSize); -// assertEquals(3, page.getOffset()); -// assertEquals(2, page.getPageSize()); -// assertEquals(3, page.getTotalSize()); -// assertEquals(0, page.getData().size()); -// assertFalse(page.hasData()); -// -// offset = 5; -// page = serviceDiscovery.getInstances("A", offset, pageSize); -// assertEquals(5, page.getOffset()); -// assertEquals(2, page.getPageSize()); -// assertEquals(3, page.getTotalSize()); -// assertEquals(0, page.getData().size()); -// assertFalse(page.hasData()); -// } -// -// @Test -// public void testGetInstancesWithHealthy() { -// -// List instances = new LinkedList<>(asList( -// new DefaultServiceInstance("A", "127.0.0.1", 8080, ScopeModelUtil.getApplicationModel(serviceDiscovery.getUrl().getScopeModel())), -// new DefaultServiceInstance("A", "127.0.0.1", 8081, ScopeModelUtil.getApplicationModel(serviceDiscovery.getUrl().getScopeModel())) -// )); -// -// -// DefaultServiceInstance serviceInstance = new DefaultServiceInstance("A", "127.0.0.1", 8082, ScopeModelUtil.getApplicationModel(serviceDiscovery.getUrl().getScopeModel())); -// serviceInstance.setHealthy(false); -// instances.add(serviceInstance); -// -// instances.forEach(serviceDiscovery::register); -// -// // offset starts 0 -// int offset = 0; -// // requestSize > total elements -// int requestSize = 5; -// -// Page page = serviceDiscovery.getInstances("A", offset, requestSize, true); -// assertEquals(0, page.getOffset()); -// assertEquals(5, page.getPageSize()); -// assertEquals(3, page.getTotalSize()); -// assertEquals(2, page.getData().size()); -// assertTrue(page.hasData()); -// -// for (ServiceInstance instance : page.getData()) { -// assertTrue(instances.contains(instance)); -// } -// -// // requestSize < total elements -// requestSize = 2; -// -// offset = 1; -// page = serviceDiscovery.getInstances("A", offset, requestSize, true); -// assertEquals(1, page.getOffset()); -// assertEquals(2, page.getPageSize()); -// assertEquals(3, page.getTotalSize()); -// assertEquals(1, page.getData().size()); -// assertTrue(page.hasData()); -// -// for (ServiceInstance instance : page.getData()) { -// assertTrue(instances.contains(instance)); -// } -// -// offset = 2; -// page = serviceDiscovery.getInstances("A", offset, requestSize, true); -// assertEquals(2, page.getOffset()); -// assertEquals(2, page.getPageSize()); -// assertEquals(3, page.getTotalSize()); -// assertEquals(0, page.getData().size()); -// assertFalse(page.hasData()); -// -// offset = 3; -// page = serviceDiscovery.getInstances("A", offset, requestSize, true); -// assertEquals(3, page.getOffset()); -// assertEquals(2, page.getPageSize()); -// assertEquals(3, page.getTotalSize()); -// assertEquals(0, page.getData().size()); -// assertFalse(page.hasData()); -// -// offset = 5; -// page = serviceDiscovery.getInstances("A", offset, requestSize, true); -// assertEquals(5, page.getOffset()); -// assertEquals(2, page.getPageSize()); -// assertEquals(3, page.getTotalSize()); -// assertEquals(0, page.getData().size()); -// assertFalse(page.hasData()); -// } -// -// public void setServiceDiscovery(ServiceDiscovery serviceDiscovery) { -// this.serviceDiscovery = serviceDiscovery; -// } -// -// public ServiceDiscovery getServiceDiscovery() { -// return serviceDiscovery; -// } -//} diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListenerTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListenerTest.java index 02b01cf5af..66a0376841 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListenerTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListenerTest.java @@ -33,6 +33,15 @@ import org.apache.dubbo.registry.client.metadata.store.MetaCacheManager; import org.apache.dubbo.registry.client.support.MockServiceDiscovery; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + import org.hamcrest.Matchers; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; @@ -48,15 +57,6 @@ import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY; import static org.apache.dubbo.common.utils.CollectionUtils.isEmpty; import static org.apache.dubbo.common.utils.CollectionUtils.isNotEmpty; @@ -83,37 +83,44 @@ class ServiceInstancesChangedListenerTest { static List app1InstancesMultipleProtocols; static String metadata_111 = "{\"app\":\"app1\",\"revision\":\"111\",\"services\":{" - + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app1\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" - + "}}"; + + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app1\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" + + "}}"; static String metadata_222 = "{\"app\":\"app2\",\"revision\":\"222\",\"services\":{" - + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}," - + "\"org.apache.dubbo.demo.DemoService2:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService2\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService2\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService2\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" - + "}}"; + + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}," + + "\"org.apache.dubbo.demo.DemoService2:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService2\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService2\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService2\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" + + "}}"; static String metadata_333 = "{\"app\":\"app2\",\"revision\":\"333\",\"services\":{" - + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}," - + "\"org.apache.dubbo.demo.DemoService2:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService2\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService2\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService2\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}," - + "\"org.apache.dubbo.demo.DemoService3:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService3\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService3\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService3\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" - + "}}"; + + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}," + + "\"org.apache.dubbo.demo.DemoService2:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService2\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService2\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService2\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}," + + "\"org.apache.dubbo.demo.DemoService3:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService3\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService3\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService3\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" + + "}}"; // failed static String metadata_444 = "{\"app\":\"app1\",\"revision\":\"444\",\"services\":{" - + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" - + "}}"; + + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" + + "}}"; // only triple protocol enabled static String metadata_555_triple = "{\"app\":\"app1\",\"revision\":\"555\",\"services\":{" - + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"tri\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" - + "}}"; + + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"tri\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" + + "}}"; static String service1 = "org.apache.dubbo.demo.DemoService"; static String service2 = "org.apache.dubbo.demo.DemoService2"; static String service3 = "org.apache.dubbo.demo.DemoService3"; - static URL consumerURL = URL.valueOf("dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=dubbo®istry_cluster=default"); - static URL consumerURL2 = URL.valueOf("dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService2?interface=org.apache.dubbo.demo.DemoService2&protocol=dubbo®istry_cluster=default"); - static URL consumerURL3 = URL.valueOf("dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService3?interface=org.apache.dubbo.demo.DemoService3&protocol=dubbo®istry_cluster=default"); - static URL multipleProtocolsConsumerURL = URL.valueOf("dubbo,tri://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=dubbo,tri®istry_cluster=default"); - static URL noProtocolConsumerURL = URL.valueOf("consumer://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService®istry_cluster=default"); - static URL singleProtocolsConsumerURL = URL.valueOf("tri://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=tri®istry_cluster=default"); - static URL registryURL = URL.valueOf("dubbo://127.0.0.1:2181/org.apache.dubbo.demo.RegistryService?enable-empty-protection=true"); + static URL consumerURL = URL.valueOf( + "dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=dubbo®istry_cluster=default"); + static URL consumerURL2 = URL.valueOf( + "dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService2?interface=org.apache.dubbo.demo.DemoService2&protocol=dubbo®istry_cluster=default"); + static URL consumerURL3 = URL.valueOf( + "dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService3?interface=org.apache.dubbo.demo.DemoService3&protocol=dubbo®istry_cluster=default"); + static URL multipleProtocolsConsumerURL = URL.valueOf( + "dubbo,tri://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=dubbo,tri®istry_cluster=default"); + static URL noProtocolConsumerURL = URL.valueOf( + "consumer://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService®istry_cluster=default"); + static URL singleProtocolsConsumerURL = URL.valueOf( + "tri://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=tri®istry_cluster=default"); + static URL registryURL = + URL.valueOf("dubbo://127.0.0.1:2181/org.apache.dubbo.demo.RegistryService?enable-empty-protection=true"); static MetadataInfo metadataInfo_111; static MetadataInfo metadataInfo_222; @@ -146,8 +153,8 @@ class ServiceInstancesChangedListenerTest { List urlsFailedRevision = new ArrayList<>(); urlsFailedRevision.add("30.10.0.5:20880?revision=222"); urlsFailedRevision.add("30.10.0.6:20880?revision=222"); - urlsFailedRevision.add("30.10.0.7:20880?revision=444");// revision will fail - urlsFailedRevision.add("30.10.0.8:20880?revision=444");// revision will fail + urlsFailedRevision.add("30.10.0.7:20880?revision=444"); // revision will fail + urlsFailedRevision.add("30.10.0.8:20880?revision=444"); // revision will fail List urlsFailedRevision2 = new ArrayList<>(); urlsFailedRevision2.add("30.10.0.1:20880?revision=222"); @@ -157,8 +164,8 @@ class ServiceInstancesChangedListenerTest { urlsWithoutRevision.add("30.10.0.1:20880"); List urlsMultipleProtocols = new ArrayList<>(); - urlsMultipleProtocols.add("30.10.0.1:20880?revision=555");//triple - urlsMultipleProtocols.addAll(urlsSameRevision);// dubbo + urlsMultipleProtocols.add("30.10.0.1:20880?revision=555"); // triple + urlsMultipleProtocols.addAll(urlsSameRevision); // dubbo app1Instances = buildInstances(urlsSameRevision); app2Instances = buildInstances(urlsDifferentRevision); @@ -183,10 +190,10 @@ class ServiceInstancesChangedListenerTest { when(serviceDiscovery.getRemoteMetadata(eq("555"), anyList())).thenReturn(metadataInfo_555_tri); } - @BeforeEach public void init() { - // Because all tests use the same ServiceDiscovery, the previous metadataCache should be cleared before next unit test + // Because all tests use the same ServiceDiscovery, the previous metadataCache should be cleared before next + // unit test // to avoid contaminating next unit test. clearMetadataCache(); } @@ -304,7 +311,8 @@ class ServiceInstancesChangedListenerTest { listener.onEvent(app2_event); // empty notification - ServiceInstancesChangedEvent app1_event_again = new ServiceInstancesChangedEvent("app1", Collections.EMPTY_LIST); + ServiceInstancesChangedEvent app1_event_again = + new ServiceInstancesChangedEvent("app1", Collections.EMPTY_LIST); listener.onEvent(app1_event_again); // check app1 cleared @@ -328,7 +336,8 @@ class ServiceInstancesChangedListenerTest { assertTrue(serviceUrls3.get(0).getIp().contains("30.10.")); // app2 empty notification - ServiceInstancesChangedEvent app2_event_again = new ServiceInstancesChangedEvent("app2", Collections.EMPTY_LIST); + ServiceInstancesChangedEvent app2_event_again = + new ServiceInstancesChangedEvent("app2", Collections.EMPTY_LIST); listener.onEvent(app2_event_again); // check app2 cleared @@ -468,7 +477,8 @@ class ServiceInstancesChangedListenerTest { listener.addListenerAndNotify(singleProtocolsConsumerURL, demoServiceListener3); // notify app1 instance change - ServiceInstancesChangedEvent app1_event = new ServiceInstancesChangedEvent("app1", app1InstancesMultipleProtocols); + ServiceInstancesChangedEvent app1_event = + new ServiceInstancesChangedEvent("app1", app1InstancesMultipleProtocols); listener.onEvent(app1_event); // check instances expose framework supported default protocols(currently dubbo, triple and rest) are notified @@ -606,10 +616,10 @@ class ServiceInstancesChangedListenerTest { serviceNames.add("app1"); listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery); // notify app1 instance change - ServiceInstancesChangedEvent failed_revision_event = new ServiceInstancesChangedEvent("app1", app1FailedInstances); + ServiceInstancesChangedEvent failed_revision_event = + new ServiceInstancesChangedEvent("app1", app1FailedInstances); listener.onEvent(failed_revision_event); - ProtocolServiceKey protocolServiceKey1 = new ProtocolServiceKey(service1, null, null, "dubbo"); ProtocolServiceKey protocolServiceKey2 = new ProtocolServiceKey(service2, null, null, "dubbo"); @@ -650,7 +660,8 @@ class ServiceInstancesChangedListenerTest { ProtocolServiceKey protocolServiceKey1 = new ProtocolServiceKey(service1, null, null, "dubbo"); ProtocolServiceKey protocolServiceKey2 = new ProtocolServiceKey(service2, null, null, "dubbo"); - Assertions.assertEquals(3, listener.getAddresses(protocolServiceKey1, consumerURL).size()); + Assertions.assertEquals( + 3, listener.getAddresses(protocolServiceKey1, consumerURL).size()); assertTrue(isEmpty(listener.getAddresses(protocolServiceKey2, consumerURL))); // @@ -666,7 +677,6 @@ class ServiceInstancesChangedListenerTest { Assertions.assertEquals(5, serviceUrls_after_retry.size()); List serviceUrls2_after_retry = listener.getAddresses(protocolServiceKey2, consumerURL); Assertions.assertEquals(2, serviceUrls2_after_retry.size()); - } // Abnormal case. Instance does not have revision @@ -718,7 +728,8 @@ class ServiceInstancesChangedListenerTest { private void clearMetadataCache() { try { - MockServiceDiscovery mockServiceDiscovery = (MockServiceDiscovery) ServiceInstancesChangedListenerTest.serviceDiscovery; + MockServiceDiscovery mockServiceDiscovery = + (MockServiceDiscovery) ServiceInstancesChangedListenerTest.serviceDiscovery; MetaCacheManager metaCacheManager = mockServiceDiscovery.getMetaCacheManager(); Field cacheField = metaCacheManager.getClass().getDeclaredField("cache"); cacheField.setAccessible(true); diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListenerWithoutEmptyProtectTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListenerWithoutEmptyProtectTest.java index 37e863121c..942eaca3cc 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListenerWithoutEmptyProtectTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListenerWithoutEmptyProtectTest.java @@ -33,6 +33,15 @@ import org.apache.dubbo.registry.client.metadata.store.MetaCacheManager; import org.apache.dubbo.registry.client.support.MockServiceDiscovery; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + import org.hamcrest.Matchers; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; @@ -48,15 +57,6 @@ import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY; import static org.apache.dubbo.common.utils.CollectionUtils.isEmpty; import static org.apache.dubbo.common.utils.CollectionUtils.isNotEmpty; @@ -83,36 +83,42 @@ public class ServiceInstancesChangedListenerWithoutEmptyProtectTest { static List app1InstancesMultipleProtocols; static String metadata_111 = "{\"app\":\"app1\",\"revision\":\"111\",\"services\":{" - + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app1\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" - + "}}"; + + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app1\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" + + "}}"; static String metadata_222 = "{\"app\":\"app2\",\"revision\":\"222\",\"services\":{" - + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}," - + "\"org.apache.dubbo.demo.DemoService2:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService2\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService2\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService2\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" - + "}}"; + + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}," + + "\"org.apache.dubbo.demo.DemoService2:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService2\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService2\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService2\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" + + "}}"; static String metadata_333 = "{\"app\":\"app2\",\"revision\":\"333\",\"services\":{" - + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}," - + "\"org.apache.dubbo.demo.DemoService2:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService2\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService2\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService2\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}," - + "\"org.apache.dubbo.demo.DemoService3:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService3\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService3\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService3\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" - + "}}"; + + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}," + + "\"org.apache.dubbo.demo.DemoService2:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService2\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService2\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService2\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}," + + "\"org.apache.dubbo.demo.DemoService3:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService3\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService3\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService3\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" + + "}}"; // failed static String metadata_444 = "{\"app\":\"app1\",\"revision\":\"444\",\"services\":{" - + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" - + "}}"; + + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" + + "}}"; // only triple protocol enabled static String metadata_555_triple = "{\"app\":\"app1\",\"revision\":\"555\",\"services\":{" - + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"tri\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" - + "}}"; + + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"tri\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app2\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" + + "}}"; static String service1 = "org.apache.dubbo.demo.DemoService"; static String service2 = "org.apache.dubbo.demo.DemoService2"; static String service3 = "org.apache.dubbo.demo.DemoService3"; - static URL consumerURL = URL.valueOf("dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=dubbo®istry_cluster=default"); - static URL consumerURL2 = URL.valueOf("dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService2?interface=org.apache.dubbo.demo.DemoService2&protocol=dubbo®istry_cluster=default"); - static URL consumerURL3 = URL.valueOf("dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService3?interface=org.apache.dubbo.demo.DemoService3&protocol=dubbo®istry_cluster=default"); - static URL multipleProtocolsConsumerURL = URL.valueOf("dubbo,tri://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=dubbo,tri®istry_cluster=default"); - static URL noProtocolConsumerURL = URL.valueOf("consumer://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService®istry_cluster=default"); - static URL singleProtocolsConsumerURL = URL.valueOf("tri://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=tri®istry_cluster=default"); + static URL consumerURL = URL.valueOf( + "dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=dubbo®istry_cluster=default"); + static URL consumerURL2 = URL.valueOf( + "dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService2?interface=org.apache.dubbo.demo.DemoService2&protocol=dubbo®istry_cluster=default"); + static URL consumerURL3 = URL.valueOf( + "dubbo://127.0.0.1/org.apache.dubbo.demo.DemoService3?interface=org.apache.dubbo.demo.DemoService3&protocol=dubbo®istry_cluster=default"); + static URL multipleProtocolsConsumerURL = URL.valueOf( + "dubbo,tri://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=dubbo,tri®istry_cluster=default"); + static URL noProtocolConsumerURL = URL.valueOf( + "consumer://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService®istry_cluster=default"); + static URL singleProtocolsConsumerURL = URL.valueOf( + "tri://127.0.0.1/org.apache.dubbo.demo.DemoService?interface=org.apache.dubbo.demo.DemoService&protocol=tri®istry_cluster=default"); static URL registryURL = URL.valueOf("dubbo://127.0.0.1:2181/org.apache.dubbo.demo.RegistryService"); static MetadataInfo metadataInfo_111; @@ -146,8 +152,8 @@ public class ServiceInstancesChangedListenerWithoutEmptyProtectTest { List urlsFailedRevision = new ArrayList<>(); urlsFailedRevision.add("30.10.0.5:20880?revision=222"); urlsFailedRevision.add("30.10.0.6:20880?revision=222"); - urlsFailedRevision.add("30.10.0.7:20880?revision=444");// revision will fail - urlsFailedRevision.add("30.10.0.8:20880?revision=444");// revision will fail + urlsFailedRevision.add("30.10.0.7:20880?revision=444"); // revision will fail + urlsFailedRevision.add("30.10.0.8:20880?revision=444"); // revision will fail List urlsFailedRevision2 = new ArrayList<>(); urlsFailedRevision2.add("30.10.0.1:20880?revision=222"); @@ -157,8 +163,8 @@ public class ServiceInstancesChangedListenerWithoutEmptyProtectTest { urlsWithoutRevision.add("30.10.0.1:20880"); List urlsMultipleProtocols = new ArrayList<>(); - urlsMultipleProtocols.add("30.10.0.1:20880?revision=555");//triple - urlsMultipleProtocols.addAll(urlsSameRevision);// dubbo + urlsMultipleProtocols.add("30.10.0.1:20880?revision=555"); // triple + urlsMultipleProtocols.addAll(urlsSameRevision); // dubbo app1Instances = buildInstances(urlsSameRevision); app2Instances = buildInstances(urlsDifferentRevision); @@ -183,10 +189,10 @@ public class ServiceInstancesChangedListenerWithoutEmptyProtectTest { when(serviceDiscovery.getRemoteMetadata(eq("555"), anyList())).thenReturn(metadataInfo_555_tri); } - @BeforeEach public void init() { - // Because all tests use the same ServiceDiscovery, the previous metadataCache should be cleared before next unit test + // Because all tests use the same ServiceDiscovery, the previous metadataCache should be cleared before next + // unit test // to avoid contaminating next unit test. clearMetadataCache(); } @@ -304,7 +310,8 @@ public class ServiceInstancesChangedListenerWithoutEmptyProtectTest { listener.onEvent(app2_event); // empty notification - ServiceInstancesChangedEvent app1_event_again = new ServiceInstancesChangedEvent("app1", Collections.EMPTY_LIST); + ServiceInstancesChangedEvent app1_event_again = + new ServiceInstancesChangedEvent("app1", Collections.EMPTY_LIST); listener.onEvent(app1_event_again); // check app1 cleared @@ -328,7 +335,8 @@ public class ServiceInstancesChangedListenerWithoutEmptyProtectTest { assertTrue(serviceUrls3.get(0).getIp().contains("30.10.")); // app2 empty notification - ServiceInstancesChangedEvent app2_event_again = new ServiceInstancesChangedEvent("app2", Collections.EMPTY_LIST); + ServiceInstancesChangedEvent app2_event_again = + new ServiceInstancesChangedEvent("app2", Collections.EMPTY_LIST); listener.onEvent(app2_event_again); // check app2 cleared @@ -468,7 +476,8 @@ public class ServiceInstancesChangedListenerWithoutEmptyProtectTest { listener.addListenerAndNotify(singleProtocolsConsumerURL, demoServiceListener3); // notify app1 instance change - ServiceInstancesChangedEvent app1_event = new ServiceInstancesChangedEvent("app1", app1InstancesMultipleProtocols); + ServiceInstancesChangedEvent app1_event = + new ServiceInstancesChangedEvent("app1", app1InstancesMultipleProtocols); listener.onEvent(app1_event); // check instances expose framework supported default protocols(currently dubbo, triple and rest) are notified @@ -606,10 +615,10 @@ public class ServiceInstancesChangedListenerWithoutEmptyProtectTest { serviceNames.add("app1"); listener = new ServiceInstancesChangedListener(serviceNames, serviceDiscovery); // notify app1 instance change - ServiceInstancesChangedEvent failed_revision_event = new ServiceInstancesChangedEvent("app1", app1FailedInstances); + ServiceInstancesChangedEvent failed_revision_event = + new ServiceInstancesChangedEvent("app1", app1FailedInstances); listener.onEvent(failed_revision_event); - ProtocolServiceKey protocolServiceKey1 = new ProtocolServiceKey(service1, null, null, "dubbo"); ProtocolServiceKey protocolServiceKey2 = new ProtocolServiceKey(service2, null, null, "dubbo"); @@ -650,7 +659,8 @@ public class ServiceInstancesChangedListenerWithoutEmptyProtectTest { ProtocolServiceKey protocolServiceKey1 = new ProtocolServiceKey(service1, null, null, "dubbo"); ProtocolServiceKey protocolServiceKey2 = new ProtocolServiceKey(service2, null, null, "dubbo"); - Assertions.assertEquals(3, listener.getAddresses(protocolServiceKey1, consumerURL).size()); + Assertions.assertEquals( + 3, listener.getAddresses(protocolServiceKey1, consumerURL).size()); assertTrue(isEmpty(listener.getAddresses(protocolServiceKey2, consumerURL))); // @@ -666,7 +676,6 @@ public class ServiceInstancesChangedListenerWithoutEmptyProtectTest { Assertions.assertEquals(5, serviceUrls_after_retry.size()); List serviceUrls2_after_retry = listener.getAddresses(protocolServiceKey2, consumerURL); Assertions.assertEquals(2, serviceUrls2_after_retry.size()); - } // Abnormal case. Instance does not have revision @@ -718,7 +727,8 @@ public class ServiceInstancesChangedListenerWithoutEmptyProtectTest { private void clearMetadataCache() { try { - MockServiceDiscovery mockServiceDiscovery = (MockServiceDiscovery) ServiceInstancesChangedListenerWithoutEmptyProtectTest.serviceDiscovery; + MockServiceDiscovery mockServiceDiscovery = + (MockServiceDiscovery) ServiceInstancesChangedListenerWithoutEmptyProtectTest.serviceDiscovery; MetaCacheManager metaCacheManager = mockServiceDiscovery.getMetaCacheManager(); Field cacheField = metaCacheManager.getClass().getDeclaredField("cache"); cacheField.setAccessible(true); diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/fastjson/DefaultServiceInstanceDeserializerTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/fastjson/DefaultServiceInstanceDeserializerTest.java deleted file mode 100644 index 57b8086324..0000000000 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/fastjson/DefaultServiceInstanceDeserializerTest.java +++ /dev/null @@ -1,58 +0,0 @@ -///* -// * Licensed to the Apache Software Foundation (ASF) under one or more -// * contributor license agreements. See the NOTICE file distributed with -// * this work for additional information regarding copyright ownership. -// * The ASF licenses this file to You 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 org.apache.dubbo.registry.client.fastjson; -// -//import org.apache.dubbo.registry.client.DefaultServiceInstance; -// -//import com.alibaba.fastjson.JSON; -//import com.alibaba.fastjson.parser.ParserConfig; -//import org.junit.jupiter.api.BeforeAll; -//import org.junit.jupiter.api.Test; -// -///** -// * {@link DefaultServiceInstanceDeserializer} Test -// * -// * @since 2.7.5 -// */ -//public class DefaultServiceInstanceDeserializerTest { -// -// private static final String JSON_CONTENT = "{\n" + -// " \"enabled\": true,\n" + -// " \"healthy\": true,\n" + -// " \"host\": \"fe80:0:0:0:1c49:6eff:fe54:2495%7\",\n" + -// " \"metadata\": {\n" + -// " \"dubbo.metadata-service.url-params\": \"{\\\"dubbo\\\":{\\\"application\\\":\\\"dubbo-provider-demo\\\",\\\"deprecated\\\":\\\"false\\\",\\\"group\\\":\\\"dubbo-provider-demo\\\",\\\"version\\\":\\\"1.0.0\\\",\\\"timestamp\\\":\\\"1566132738256\\\",\\\"dubbo\\\":\\\"2.0.2\\\",\\\"provider.host\\\":\\\"fe80:0:0:0:1c49:6eff:fe54:2495%7\\\",\\\"provider.port\\\":\\\"20880\\\"}}\",\n" + -// " \"dubbo.subscribed-services.revision\": \"1\",\n" + -// " \"dubbo.metadata.storage-type\": \"default\",\n" + -// " \"dubbo.exported-services.revision\": \"640372560\"\n" + -// " },\n" + -// " \"port\": 20880,\n" + -// " \"serviceName\": \"dubbo-provider-demo\"\n" + -// "}"; -// -// @BeforeAll -// public static void init() { -// ParserConfig.getGlobalInstance().putDeserializer(DefaultServiceInstance.class, new DefaultServiceInstanceDeserializer()); -// } -// -// @Test -// public void testDeserialze() { -// -// DefaultServiceInstance serviceInstance = JSON.parseObject(JSON_CONTENT, DefaultServiceInstance.class); -// -// } -//} diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/MetadataServiceNameMappingTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/MetadataServiceNameMappingTest.java index 0f9a347f48..c7ce2cba61 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/MetadataServiceNameMappingTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/MetadataServiceNameMappingTest.java @@ -16,13 +16,6 @@ */ package org.apache.dubbo.registry.client.metadata; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigItem; import org.apache.dubbo.config.ApplicationConfig; @@ -32,6 +25,13 @@ import org.apache.dubbo.metadata.report.MetadataReport; import org.apache.dubbo.metadata.report.MetadataReportInstance; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -99,21 +99,23 @@ class MetadataServiceNameMappingTest { // metadata report using cas and retry, succeeded after retried 10 times when(metadataReport.registerServiceAppMapping(any(), any(), any())).thenReturn(false); when(metadataReport.getConfigItem(any(), any())).thenReturn(new ConfigItem()); - when(metadataReport.registerServiceAppMapping(any(), any(), any(), any())).thenAnswer(new Answer() { - private int counter = 0; + when(metadataReport.registerServiceAppMapping(any(), any(), any(), any())) + .thenAnswer(new Answer() { + private int counter = 0; - @Override - public Boolean answer(InvocationOnMock invocationOnMock) { - if (++counter == 10) { - return true; - } - return false; - } - }); + @Override + public Boolean answer(InvocationOnMock invocationOnMock) { + if (++counter == 10) { + return true; + } + return false; + } + }); assertTrue(mapping.map(url)); // metadata report using cas and retry, failed after 11 times retry - when(metadataReport.registerServiceAppMapping(any(), any(), any(), any())).thenReturn(false); + when(metadataReport.registerServiceAppMapping(any(), any(), any(), any())) + .thenReturn(false); Exception exceptionExpected = null; assertFalse(mapping.map(url)); } diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLBuilderTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLBuilderTest.java index 4a59066288..65d2e7e578 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLBuilderTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLBuilderTest.java @@ -27,11 +27,19 @@ import org.apache.dubbo.rpc.model.ApplicationModel; */ class MetadataServiceURLBuilderTest { - static ServiceInstance serviceInstance = new DefaultServiceInstance("test", "127.0.0.1", 8080, ApplicationModel.defaultModel()); + static ServiceInstance serviceInstance = + new DefaultServiceInstance("test", "127.0.0.1", 8080, ApplicationModel.defaultModel()); static { - serviceInstance.getMetadata().put("dubbo.metadata-service.urls", "[ \"dubbo://192.168.0.102:20881/com.alibaba.cloud.dubbo.service.DubboMetadataService?anyhost=true&application=spring-cloud-alibaba-dubbo-provider&bind.ip=192.168.0.102&bind.port=20881&deprecated=false&dubbo=2.0.2&dynamic=true&generic=false&group=spring-cloud-alibaba-dubbo-provider&interface=com.alibaba.cloud.dubbo.service.DubboMetadataService&methods=getAllServiceKeys,getServiceRestMetadata,getExportedURLs,getAllExportedURLs&pid=17134&qos.enable=false®ister=true&release=2.7.3&revision=1.0.0&side=provider×tamp=1564826098503&version=1.0.0\" ]"); - serviceInstance.getMetadata().put("dubbo.metadata-service.url-params", "{\"application\":\"dubbo-provider-demo\",\"protocol\":\"rest\",\"group\":\"dubbo-provider-demo\",\"version\":\"1.0.0\",\"timestamp\":\"1564845042651\",\"dubbo\":\"2.0.2\",\"host\":\"192.168.0.102\",\"port\":\"20880\"}"); + serviceInstance + .getMetadata() + .put( + "dubbo.metadata-service.urls", + "[ \"dubbo://192.168.0.102:20881/com.alibaba.cloud.dubbo.service.DubboMetadataService?anyhost=true&application=spring-cloud-alibaba-dubbo-provider&bind.ip=192.168.0.102&bind.port=20881&deprecated=false&dubbo=2.0.2&dynamic=true&generic=false&group=spring-cloud-alibaba-dubbo-provider&interface=com.alibaba.cloud.dubbo.service.DubboMetadataService&methods=getAllServiceKeys,getServiceRestMetadata,getExportedURLs,getAllExportedURLs&pid=17134&qos.enable=false®ister=true&release=2.7.3&revision=1.0.0&side=provider×tamp=1564826098503&version=1.0.0\" ]"); + serviceInstance + .getMetadata() + .put( + "dubbo.metadata-service.url-params", + "{\"application\":\"dubbo-provider-demo\",\"protocol\":\"rest\",\"group\":\"dubbo-provider-demo\",\"version\":\"1.0.0\",\"timestamp\":\"1564845042651\",\"dubbo\":\"2.0.2\",\"host\":\"192.168.0.102\",\"port\":\"20880\"}"); } - } diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ProtocolPortsMetadataCustomizerTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ProtocolPortsMetadataCustomizerTest.java index 3c6919d644..b29f42ae77 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ProtocolPortsMetadataCustomizerTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ProtocolPortsMetadataCustomizerTest.java @@ -24,6 +24,9 @@ import org.apache.dubbo.metadata.MetadataService; import org.apache.dubbo.registry.client.DefaultServiceInstance; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.io.IOException; +import java.util.List; + import org.hamcrest.MatcherAssert; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; @@ -31,9 +34,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.io.IOException; -import java.util.List; - import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.ENDPOINTS; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItem; @@ -61,10 +61,12 @@ class ProtocolPortsMetadataCustomizerTest { public void init() { instance = createInstance(); - URL dubboUrl = URL.valueOf("dubbo://30.10.104.63:20880/org.apache.dubbo.demo.GreetingService?" + - "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.demo.GreetingService&metadata-type=remote&methods=hello&pid=55805&release=&revision=1.0.0&service-name-mapping=true&side=provider&timeout=5000×tamp=1630229110058&version=1.0.0"); - URL triURL = URL.valueOf("tri://30.10.104.63:50332/org.apache.dubbo.demo.GreetingService?" + - "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.demo.GreetingService&metadata-type=remote&methods=hello&pid=55805&release=&revision=1.0.0&service-name-mapping=true&side=provider&timeout=5000×tamp=1630229110058&version=1.0.0"); + URL dubboUrl = URL.valueOf( + "dubbo://30.10.104.63:20880/org.apache.dubbo.demo.GreetingService?" + + "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.demo.GreetingService&metadata-type=remote&methods=hello&pid=55805&release=&revision=1.0.0&service-name-mapping=true&side=provider&timeout=5000×tamp=1630229110058&version=1.0.0"); + URL triURL = URL.valueOf( + "tri://30.10.104.63:50332/org.apache.dubbo.demo.GreetingService?" + + "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.demo.GreetingService&metadata-type=remote&methods=hello&pid=55805&release=&revision=1.0.0&service-name-mapping=true&side=provider&timeout=5000×tamp=1630229110058&version=1.0.0"); MetadataInfo metadataInfo = new MetadataInfo(); metadataInfo.addService(dubboUrl); @@ -85,7 +87,8 @@ class ProtocolPortsMetadataCustomizerTest { customizer.customize(instance, ApplicationModel.defaultModel()); String endpoints = instance.getMetadata().get(ENDPOINTS); assertNotNull(endpoints); - List endpointList = JsonUtils.toJavaList(endpoints, DefaultServiceInstance.Endpoint.class); + List endpointList = + JsonUtils.toJavaList(endpoints, DefaultServiceInstance.Endpoint.class); assertEquals(2, endpointList.size()); MatcherAssert.assertThat(endpointList, hasItem(hasProperty("protocol", equalTo("dubbo")))); MatcherAssert.assertThat(endpointList, hasItem(hasProperty("port", equalTo(20880)))); diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceHostPortCustomizerTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceHostPortCustomizerTest.java index 095708537d..93f032e3ff 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceHostPortCustomizerTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceHostPortCustomizerTest.java @@ -24,13 +24,13 @@ import org.apache.dubbo.metadata.MetadataService; import org.apache.dubbo.registry.client.DefaultServiceInstance; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.concurrent.ExecutionException; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import java.util.concurrent.ExecutionException; - import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -41,7 +41,7 @@ import static org.mockito.Mockito.when; */ class ServiceInstanceHostPortCustomizerTest { private static ServiceInstanceHostPortCustomizer serviceInstanceHostPortCustomizer; - + @BeforeAll public static void setUp() { serviceInstanceHostPortCustomizer = new ServiceInstanceHostPortCustomizer(); @@ -51,7 +51,7 @@ class ServiceInstanceHostPortCustomizerTest { public static void clearUp() { ApplicationModel.reset(); } - + @Test void customizePreferredProtocol() throws ExecutionException, InterruptedException { ScopeBeanFactory beanFactory = mock(ScopeBeanFactory.class); @@ -64,7 +64,8 @@ class ServiceInstanceHostPortCustomizerTest { ApplicationConfig applicationConfig = new ApplicationConfig("aa"); // when(applicationModel.getCurrentConfig()).thenReturn(applicationConfig); doReturn(applicationConfig).when(applicationModel).getCurrentConfig(); - DefaultServiceInstance serviceInstance1 = new DefaultServiceInstance("without-preferredProtocol", applicationModel); + DefaultServiceInstance serviceInstance1 = + new DefaultServiceInstance("without-preferredProtocol", applicationModel); MetadataInfo metadataInfo = new MetadataInfo(); metadataInfo.addService(URL.valueOf("tri://127.1.1.1:50052/org.apache.dubbo.demo.GreetingService")); serviceInstance1.setServiceMetadata(metadataInfo); diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataCustomizerTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataCustomizerTest.java index 81362c384f..9a199e7878 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataCustomizerTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataCustomizerTest.java @@ -44,7 +44,6 @@ class ServiceInstanceMetadataCustomizerTest { ApplicationModel.reset(); } - /** * Only 'include' policy spicified in Customized Filter will take effect */ @@ -54,15 +53,18 @@ class ServiceInstanceMetadataCustomizerTest { ApplicationConfig applicationConfig = new ApplicationConfig("aa"); doReturn(applicationConfig).when(applicationModel).getCurrentConfig(); - DefaultServiceInstance serviceInstance1 = new DefaultServiceInstance("ServiceInstanceMetadataCustomizerTest", applicationModel); + DefaultServiceInstance serviceInstance1 = + new DefaultServiceInstance("ServiceInstanceMetadataCustomizerTest", applicationModel); MetadataInfo metadataInfo = new MetadataInfo(); - metadataInfo.addService(URL.valueOf("tri://127.1.1.1:50052/org.apache.dubbo.demo.GreetingService?application=ServiceInstanceMetadataCustomizerTest&env=test&side=provider&group=test")); + metadataInfo.addService( + URL.valueOf( + "tri://127.1.1.1:50052/org.apache.dubbo.demo.GreetingService?application=ServiceInstanceMetadataCustomizerTest&env=test&side=provider&group=test")); serviceInstance1.setServiceMetadata(metadataInfo); serviceInstanceMetadataCustomizer.customize(serviceInstance1, applicationModel); Assertions.assertEquals(1, serviceInstance1.getMetadata().size()); Assertions.assertEquals("provider", serviceInstance1.getMetadata(SIDE_KEY)); - Assertions.assertNull( serviceInstance1.getMetadata("env")); - Assertions.assertNull( serviceInstance1.getMetadata("application")); + Assertions.assertNull(serviceInstance1.getMetadata("env")); + Assertions.assertNull(serviceInstance1.getMetadata("application")); } /** @@ -74,16 +76,19 @@ class ServiceInstanceMetadataCustomizerTest { ApplicationConfig applicationConfig = new ApplicationConfig("aa"); doReturn(applicationConfig).when(applicationModel).getCurrentConfig(); - DefaultServiceInstance serviceInstance1 = new DefaultServiceInstance("ServiceInstanceMetadataCustomizerTest", applicationModel); + DefaultServiceInstance serviceInstance1 = + new DefaultServiceInstance("ServiceInstanceMetadataCustomizerTest", applicationModel); MetadataInfo metadataInfo = new MetadataInfo(); - metadataInfo.addService(URL.valueOf("tri://127.1.1.1:50052/org.apache.dubbo.demo.GreetingService?application=ServiceInstanceMetadataCustomizerTest&env=test&side=provider&group=test¶ms-filter=-customized,-dubbo")); + metadataInfo.addService( + URL.valueOf( + "tri://127.1.1.1:50052/org.apache.dubbo.demo.GreetingService?application=ServiceInstanceMetadataCustomizerTest&env=test&side=provider&group=test¶ms-filter=-customized,-dubbo")); serviceInstance1.setServiceMetadata(metadataInfo); serviceInstanceMetadataCustomizer.customize(serviceInstance1, applicationModel); Assertions.assertEquals(2, serviceInstance1.getMetadata().size()); Assertions.assertEquals("ServiceInstanceMetadataCustomizerTest", serviceInstance1.getMetadata("application")); Assertions.assertEquals("test", serviceInstance1.getMetadata("env")); - Assertions.assertNull( serviceInstance1.getMetadata("side")); - Assertions.assertNull( serviceInstance1.getMetadata("group")); + Assertions.assertNull(serviceInstance1.getMetadata("side")); + Assertions.assertNull(serviceInstance1.getMetadata("group")); } } diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtilsTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtilsTest.java deleted file mode 100644 index b736f31530..0000000000 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtilsTest.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.dubbo.registry.client.metadata; -// -//import org.apache.dubbo.common.URL; -//import org.apache.dubbo.config.ApplicationConfig; -//import org.apache.dubbo.metadata.MetadataService; -//import org.apache.dubbo.metadata.ServiceNameMapping; -//import org.apache.dubbo.registry.Registry; -//import org.apache.dubbo.registry.client.DefaultServiceInstance; -//import org.apache.dubbo.registry.client.InMemoryServiceDiscovery; -//import org.apache.dubbo.registry.client.ServiceDiscovery; -//import org.apache.dubbo.registry.client.ServiceDiscoveryRegistry; -//import org.apache.dubbo.registry.support.RegistryManager; -//import org.apache.dubbo.rpc.model.ApplicationModel; -// -//import com.alibaba.fastjson.JSON; -//import com.alibaba.fastjson.JSONObject; -//import com.google.gson.Gson; -//import org.junit.jupiter.api.AfterAll; -//import org.junit.jupiter.api.Assertions; -//import org.junit.jupiter.api.BeforeAll; -//import org.junit.jupiter.api.BeforeEach; -//import org.junit.jupiter.api.Test; -// -//import java.lang.reflect.Constructor; -//import java.lang.reflect.Field; -//import java.util.Arrays; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -//import java.util.concurrent.ConcurrentHashMap; -// -//import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE; -//import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE; -//import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.METADATA_CLUSTER_PROPERTY_NAME; -//import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.METADATA_SERVICE_URL_PARAMS_PROPERTY_NAME; -//import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.METADATA_STORAGE_TYPE_PROPERTY_NAME; -//import static org.junit.jupiter.api.Assertions.assertEquals; -// -///** -// * {@link ServiceInstanceMetadataUtils} Test -// * -// * @since 2.7.5 -// */ -//public class ServiceInstanceMetadataUtilsTest { -// -// private static URL url = URL.valueOf("dubbo://192.168.0.102:20880/org.apache.dubbo.metadata.MetadataService?&anyhost=true&application=spring-cloud-alibaba-dubbo-provider&bind.ip=192.168.0.102&bind.port=20880&default.deprecated=false&default.dynamic=false&default.register=true&deprecated=false&dubbo=2.0.2&dynamic=false&generic=false&group=spring-cloud-alibaba-dubbo-provider&interface=org.apache.dubbo.metadata.MetadataService&methods=getAllServiceKeys,getServiceRestMetadata,getExportedURLs,getAllExportedURLs&pid=58350®ister=true&release=2.7.1&revision=1.0.0&side=provider×tamp=1557928573174&version=1.0.0"); -// private static URL url2 = URL.valueOf("rest://192.168.0.102:20880/org.apache.dubbo.metadata.MetadataService?&anyhost=true&application=spring-cloud-alibaba-dubbo-provider&bind.ip=192.168.0.102&bind.port=20880&default.deprecated=false&default.dynamic=false&default.register=true&deprecated=false&dubbo=2.0.2&dynamic=false&generic=false&group=spring-cloud-alibaba-dubbo-provider&interface=org.apache.dubbo.metadata.MetadataService&methods=getAllServiceKeys,getServiceRestMetadata,getExportedURLs,getAllExportedURLs&pid=58350®ister=true&release=2.7.1&revision=1.0.0&side=provider×tamp=1557928573174&version=1.0.0"); -// -// private static final String VALUE_URL = "{\"version\":\"1.0.0\",\"dubbo\":\"2.0.2\",\"release\":\"2.7.1\",\"port\":\"20880\",\"protocol\":\"dubbo\"}"; -// private static final String VALUE_URL2 = "{\"version\":\"1.0.0\",\"dubbo\":\"2.0.2\",\"release\":\"2.7.1\",\"port\":\"20880\",\"protocol\":\"rest\"}"; -// -// private DefaultServiceInstance serviceInstance; -// -// @BeforeEach -// public void init() { -// serviceInstance = new DefaultServiceInstance("test", "127.0.0.1", 8080, ApplicationModel.defaultModel()); -// } -// -// @BeforeAll -// public static void setUp() { -// ApplicationConfig applicationConfig = new ApplicationConfig("demo"); -// ApplicationModel.defaultModel().getApplicationConfigManager().setApplication(applicationConfig); -// } -// -// @AfterAll -// public static void clearUp() { -// ApplicationModel.reset(); -// } -// -// -// @Test -// public void testMetadataServiceURLParameters() { -// -// List urls = Arrays.asList(url, url2); -// -// urls.forEach(url -> { -// String parameter = ServiceInstanceMetadataUtils.getMetadataServiceParameter(url); -// -// JSONObject jsonObject = JSON.parseObject(parameter); -// -// for (Map.Entry param : url.getParameters().entrySet()) { -// String value = jsonObject.getString(param.getKey()); -// if (value != null) { -// assertEquals(param.getValue(), value); -// } -// } -// -// }); -// -// assertEquals(ServiceInstanceMetadataUtils.getMetadataServiceParameter(url), VALUE_URL); -// assertEquals(ServiceInstanceMetadataUtils.getMetadataServiceParameter(url2), VALUE_URL2); -// } -// -// @Test -// public void getMetadataServiceURLsParams() { -// Map urlParams = new HashMap<>(); -// urlParams.put("dubbo", "1111"); -// urlParams.put("rest", "2222"); -// serviceInstance.getMetadata().put(METADATA_SERVICE_URL_PARAMS_PROPERTY_NAME, new Gson().toJson(urlParams)); -// Map metadataServiceURLsParams = ServiceInstanceMetadataUtils.getMetadataServiceURLsParams(serviceInstance); -// Assertions.assertEquals(metadataServiceURLsParams.get("dubbo"), "1111"); -// Assertions.assertEquals(metadataServiceURLsParams.get("rest"), "2222"); -// } -// -// @Test -// public void testMetadataStorageType() { -// Assertions.assertEquals(ServiceInstanceMetadataUtils.getMetadataStorageType(serviceInstance), DEFAULT_METADATA_STORAGE_TYPE); -// serviceInstance.getMetadata().put(METADATA_STORAGE_TYPE_PROPERTY_NAME, REMOTE_METADATA_STORAGE_TYPE); -// Assertions.assertEquals(ServiceInstanceMetadataUtils.getMetadataStorageType(serviceInstance), REMOTE_METADATA_STORAGE_TYPE); -// } -// -// @Test -// public void getRemoteCluster() { -// Assertions.assertNull(ServiceInstanceMetadataUtils.getRemoteCluster(serviceInstance)); -// -// serviceInstance.getMetadata().put(METADATA_CLUSTER_PROPERTY_NAME, "REGISTRY_CLUSTER_9103"); -// Assertions.assertEquals(ServiceInstanceMetadataUtils.getRemoteCluster(serviceInstance), "REGISTRY_CLUSTER_9103"); -// } -// -// @Test -// public void testEndpoints() { -// Assertions.assertFalse(ServiceInstanceMetadataUtils.hasEndpoints(serviceInstance)); -// -// Map endpoints = new HashMap<>(); -// endpoints.put("dubbo", 20880); -// endpoints.put("rest", 8080); -// ServiceInstanceMetadataUtils.setEndpoints(serviceInstance, endpoints); -// Assertions.assertTrue(ServiceInstanceMetadataUtils.hasEndpoints(serviceInstance)); -// -// for (Map.Entry entry : endpoints.entrySet()) { -// String protocol = entry.getKey(); -// Integer port = entry.getValue(); -// DefaultServiceInstance.Endpoint endpoint = ServiceInstanceMetadataUtils.getEndpoint(serviceInstance, protocol); -// Assertions.assertEquals(endpoint.getPort(), port); -// } -// } -// -// @Test -// public void testRegisterMetadataAndInstance() throws Exception { -// InMemoryServiceDiscovery inMemoryServiceDiscovery = prepare(); -// ServiceInstanceMetadataUtils.registerMetadataAndInstance(ApplicationModel.defaultModel()); -// -// Assertions.assertTrue(inMemoryServiceDiscovery.getServices().contains(serviceInstance.getServiceName())); -// } -// -// @Test -// public void refreshMetadataAndInstance() throws Exception { -// InMemoryServiceDiscovery inMemoryServiceDiscovery = prepare(); -// -// Assertions.assertNull(inMemoryServiceDiscovery.getLocalInstance()); -// -// ServiceInstanceMetadataUtils.refreshMetadataAndInstance(ApplicationModel.defaultModel()); -// -// Assertions.assertEquals(inMemoryServiceDiscovery.getLocalInstance().getServiceName(), serviceInstance.getServiceName()); -// Assertions.assertEquals(inMemoryServiceDiscovery.getLocalInstance().getHost(), serviceInstance.getHost()); -// Assertions.assertEquals(inMemoryServiceDiscovery.getLocalInstance().getPort(), serviceInstance.getPort()); -// Assertions.assertEquals(inMemoryServiceDiscovery.getLocalInstance().getApplicationModel(), serviceInstance.getApplicationModel()); -// } -// -// private InMemoryServiceDiscovery prepare() throws NoSuchMethodException, InstantiationException, IllegalAccessException, java.lang.reflect.InvocationTargetException, NoSuchFieldException { -// // Construct serviceDiscoveryRegistry -// InMemoryServiceDiscovery inMemoryServiceDiscovery = new InMemoryServiceDiscovery("ServiceInstanceMetadataUtilsTest"); -// URL registryURL = URL.valueOf("registry://localhost:2181?registry=zookeeper"); -// Constructor constructor = ServiceDiscoveryRegistry.class.getDeclaredConstructor(URL.class, ServiceDiscovery.class, ServiceNameMapping.class); -// constructor.setAccessible(true); -// ServiceDiscoveryRegistry serviceDiscoveryRegistry = constructor.newInstance(registryURL, inMemoryServiceDiscovery, metadataService); -// -// // Add serviceDiscoveryRegistry to RegisterManger -// RegistryManager manager = ApplicationModel.defaultModel().getBeanFactory().getBean(RegistryManager.class); -// Field field = manager.getClass().getDeclaredField("registries"); -// field.setAccessible(true); -// Map registries = new ConcurrentHashMap<>(); -// registries.put("127.0.0.1:2181", serviceDiscoveryRegistry); -// field.set(manager, registries); -// return inMemoryServiceDiscovery; -// } -// -//} diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/SpringCloudMetadataServiceURLBuilderTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/SpringCloudMetadataServiceURLBuilderTest.java index 91aba6b4cf..0ce4e31aef 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/SpringCloudMetadataServiceURLBuilderTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/SpringCloudMetadataServiceURLBuilderTest.java @@ -20,10 +20,10 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.client.DefaultServiceInstance; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Test; - import java.util.List; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.registry.client.metadata.MetadataServiceURLBuilderTest.serviceInstance; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -38,7 +38,8 @@ class SpringCloudMetadataServiceURLBuilderTest { @Test void testBuild() { - List urls = builder.build(new DefaultServiceInstance("127.0.0.1", "test", 8080, ApplicationModel.defaultModel())); + List urls = + builder.build(new DefaultServiceInstance("127.0.0.1", "test", 8080, ApplicationModel.defaultModel())); assertEquals(0, urls.size()); urls = builder.build(serviceInstance); @@ -48,5 +49,4 @@ class SpringCloudMetadataServiceURLBuilderTest { assertEquals(20881, url.getPort()); assertEquals("com.alibaba.cloud.dubbo.service.DubboMetadataService", url.getServiceInterface()); } - } diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/StandardMetadataServiceURLBuilderTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/StandardMetadataServiceURLBuilderTest.java index d6bd958d1f..df091959f3 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/StandardMetadataServiceURLBuilderTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/StandardMetadataServiceURLBuilderTest.java @@ -23,12 +23,12 @@ import org.apache.dubbo.metadata.MetadataService; import org.apache.dubbo.registry.client.DefaultServiceInstance; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.List; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import java.util.List; - import static org.apache.dubbo.registry.client.metadata.MetadataServiceURLBuilderTest.serviceInstance; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -51,12 +51,13 @@ class StandardMetadataServiceURLBuilderTest { @Test void testBuild() { - ExtensionLoader loader = ApplicationModel.defaultModel() - .getExtensionLoader(MetadataServiceURLBuilder.class); + ExtensionLoader loader = + ApplicationModel.defaultModel().getExtensionLoader(MetadataServiceURLBuilder.class); MetadataServiceURLBuilder builder = loader.getExtension(StandardMetadataServiceURLBuilder.NAME); // test generateUrlWithoutMetadata - List urls = builder.build(new DefaultServiceInstance("test", "127.0.0.1", 8080, ApplicationModel.defaultModel())); + List urls = + builder.build(new DefaultServiceInstance("test", "127.0.0.1", 8080, ApplicationModel.defaultModel())); assertEquals(1, urls.size()); URL url = urls.get(0); assertEquals("dubbo", url.getProtocol()); @@ -66,7 +67,7 @@ class StandardMetadataServiceURLBuilderTest { assertEquals("test", url.getGroup()); assertEquals("consumer", url.getSide()); assertEquals("1.0.0", url.getVersion()); -// assertEquals(url.getParameters().get("getAndListenInstanceMetadata.1.callback"), "true"); + // assertEquals(url.getParameters().get("getAndListenInstanceMetadata.1.callback"), "true"); assertEquals("false", url.getParameters().get("reconnect")); assertEquals("5000", url.getParameters().get("timeout")); assertEquals(ApplicationModel.defaultModel(), url.getApplicationModel()); @@ -85,5 +86,4 @@ class StandardMetadataServiceURLBuilderTest { assertEquals("dubbo-provider-demo", url.getApplication()); assertEquals("5000", url.getParameters().get("timeout")); } - } diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/CustomizedParamsFilter.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/CustomizedParamsFilter.java index 86743ce816..6af958263d 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/CustomizedParamsFilter.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/CustomizedParamsFilter.java @@ -30,7 +30,7 @@ public class CustomizedParamsFilter implements MetadataParamsFilter { @Override public String[] serviceParamsIncluded() { - return new String[]{APPLICATION_KEY, TIMEOUT_KEY, GROUP_KEY, VERSION_KEY}; + return new String[] {APPLICATION_KEY, TIMEOUT_KEY, GROUP_KEY, VERSION_KEY}; } @Override @@ -43,7 +43,7 @@ public class CustomizedParamsFilter implements MetadataParamsFilter { */ @Override public String[] instanceParamsIncluded() { - return new String[]{SIDE_KEY}; + return new String[] {SIDE_KEY}; } @Override diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/ExcludedParamsFilter.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/ExcludedParamsFilter.java index b686a7dd53..7d13b00b96 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/ExcludedParamsFilter.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/ExcludedParamsFilter.java @@ -44,6 +44,6 @@ public class ExcludedParamsFilter implements MetadataParamsFilter { @Override public String[] instanceParamsExcluded() { - return new String[]{SIDE_KEY}; + return new String[] {SIDE_KEY}; } } diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/ExcludedParamsFilter2.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/ExcludedParamsFilter2.java index ec9c1c0fa6..34b6386c75 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/ExcludedParamsFilter2.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/ExcludedParamsFilter2.java @@ -44,6 +44,6 @@ public class ExcludedParamsFilter2 implements MetadataParamsFilter { @Override public String[] instanceParamsExcluded() { - return new String[]{GROUP_KEY, "params-filter"}; + return new String[] {GROUP_KEY, "params-filter"}; } } diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/InMemoryMetadataServiceTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/InMemoryMetadataServiceTest.java deleted file mode 100644 index 2fb85ccda3..0000000000 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/InMemoryMetadataServiceTest.java +++ /dev/null @@ -1,216 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.dubbo.registry.client.metadata.store; -// -//import org.apache.dubbo.common.URL; -//import org.apache.dubbo.config.ApplicationConfig; -//import org.apache.dubbo.metadata.MetadataInfo; -//import org.apache.dubbo.metadata.MetadataService; -//import org.apache.dubbo.metadata.definition.model.ServiceDefinition; -//import org.apache.dubbo.registry.MockLogger; -//import org.apache.dubbo.rpc.model.ApplicationModel; -//import org.apache.dubbo.rpc.model.FrameworkModel; -// -//import com.google.gson.Gson; -//import org.junit.jupiter.api.AfterAll; -//import org.junit.jupiter.api.BeforeAll; -//import org.junit.jupiter.api.Test; -// -//import java.util.Map; -//import java.util.SortedSet; -// -//import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; -//import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; -//import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; -//import static org.apache.dubbo.common.constants.CommonConstants.PID_KEY; -//import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; -//import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; -//import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -//import static org.junit.jupiter.api.Assertions.assertEquals; -//import static org.junit.jupiter.api.Assertions.assertNotNull; -//import static org.junit.jupiter.api.Assertions.assertNotSame; -//import static org.junit.jupiter.api.Assertions.assertNull; -//import static org.junit.jupiter.api.Assertions.assertTrue; -// -///** -// * Construction of {@link org.apache.dubbo.metadata.MetadataInfo} and {@link org.apache.dubbo.metadata.MetadataInfo.ServiceInfo} included. -// */ -//public class InMemoryMetadataServiceTest { -// private static final MockLogger logger = new MockLogger(); -// -// @BeforeAll -// public static void setUp() { -// FrameworkModel.destroyAll(); -// ApplicationConfig applicationConfig = new ApplicationConfig(); -// applicationConfig.setName("demo-provider2"); -// ApplicationModel.defaultModel().getApplicationConfigManager().setApplication(applicationConfig); -// } -// -// @AfterAll -// public static void clearUp() { -// ApplicationModel.reset(); -// } -// -// /** -// *
      -// * export url -// *
    • normal service
    • -// *
    • generic service
    • -// *
    -// */ -// @Test -// public void testExport() { -// MetadataServiceDelegation metadataService = new MetadataServiceDelegation(); -// metadataService.setApplicationModel(ApplicationModel.defaultModel()); -// // export normal url -// URL url = URL.valueOf("dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService?" + -// "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2" + -// "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService" + -// "&metadata-type=remote&methods=sayHello&pid=36621&release=&revision=1.0.0&service-name-mapping=true" + -// "&side=provider&timeout=5000×tamp=1629970068002&version=1.0.0¶ms-filter=-default"); -// metadataService.exportURL(url); -// -// Map metadataInfoMap = metadataService.getMetadataInfos(); -// MetadataInfo defaultMetadataInfo = metadataInfoMap.get("registry1"); -// assertNotNull(defaultMetadataInfo.getServiceInfo(url.getProtocolServiceKey())); -// assertEquals("demo-provider2", defaultMetadataInfo.getApp()); -// assertEquals(1, defaultMetadataInfo.getServices().size()); -// MetadataInfo.ServiceInfo serviceInfo = defaultMetadataInfo.getServiceInfo(url.getProtocolServiceKey()); -// assertNotNull(serviceInfo); -// assertEquals(url.getServiceKey(), serviceInfo.getServiceKey()); -// assertEquals(url.getProtocolServiceKey(), serviceInfo.getMatchKey()); -// assertNull(serviceInfo.getParams().get(PID_KEY)); -// assertNull(serviceInfo.getParams().get(TIMESTAMP_KEY)); -// assertNotNull(serviceInfo.getParams().get(APPLICATION_KEY)); -// assertNotNull(serviceInfo.getParams().get(INTERFACE_KEY)); -// assertNotNull(serviceInfo.getParams().get("delay")); -// -// // export normal url again -// URL url2 = URL.valueOf("dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService2?" + -// "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2" + -// "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService2" + -// "&metadata-type=remote&methods=sayHello&pid=36621&release=&revision=1.0.0&service-name-mapping=true" + -// "&side=provider&timeout=5000×tamp=1629970068002&version=1.0.0¶ms-filter=customized,-excluded"); -// metadataService.exportURL(url2); -// assertEquals("demo-provider2", defaultMetadataInfo.getApp()); -// assertEquals(2, defaultMetadataInfo.getServices().size()); -// MetadataInfo.ServiceInfo serviceInfo2 = defaultMetadataInfo.getServiceInfo(url2.getProtocolServiceKey()); -// assertNotNull(serviceInfo2); -// assertEquals(4, serviceInfo2.getParams().size()); -// assertNull(serviceInfo2.getParams().get(INTERFACE_KEY)); -// assertNull(serviceInfo2.getParams().get("delay")); -// assertNotNull(serviceInfo2.getParams().get(APPLICATION_KEY)); -// assertNotNull(serviceInfo2.getParams().get(VERSION_KEY)); -// assertNotNull(serviceInfo2.getParams().get(GROUP_KEY)); -// assertNotNull(serviceInfo2.getParams().get(TIMEOUT_KEY)); -// -// // repeat the same url -// metadataService.exportURL(url); -// // serviceInfo is replaced -// assertEquals(2, defaultMetadataInfo.getServices().size()); -// assertNotSame(serviceInfo, defaultMetadataInfo.getServiceInfo(url.getProtocolServiceKey())); -// -// try { -// metadataService.blockUntilUpdated(); -// assertTrue(true); -// metadataService.logger = logger; -// Thread mainThread = Thread.currentThread(); -// new Thread(new Runnable() { -// @Override -// public void run() { -// try { -// Thread.sleep(1000); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// mainThread.interrupt(); -// } -// }).start(); -// metadataService.blockUntilUpdated(); -// logger.checkLogHappened("metadata refresh thread has been "); -// metadataService.exportURL(url.addParameter(GROUP_KEY, "anotherGroup")); -// metadataService.blockUntilUpdated(); -// assertTrue(true); -// } finally { -// metadataService.releaseBlock(); -// } -// } -// -// -// -// /** -// *
      -// * unexport url -// *
    • normal service
    • -// *
    • generic service
    • -// *
    -// */ -// @Test -// public void testUnExport() { -// MetadataServiceDelegation metadataService = new MetadataServiceDelegation(); -// metadataService.setApplicationModel(ApplicationModel.defaultModel()); -// // export normal url -// URL url = URL.valueOf("dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService?" + -// "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2" + -// "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService" + -// "&metadata-type=remote&methods=sayHello&pid=36621&release=&revision=1.0.0&service-name-mapping=true" + -// "&side=provider&timeout=5000×tamp=1629970068002&version=1.0.0¶ms-filter=-default"); -// metadataService.exportURL(url); -// Map metadataInfoMap = metadataService.getMetadataInfos(); -// MetadataInfo defaultMetadataInfo = metadataInfoMap.get("registry1"); -// assertEquals(1, defaultMetadataInfo.getServices().size()); -// MetadataInfo.ServiceInfo serviceInfo = defaultMetadataInfo.getServiceInfo(url.getProtocolServiceKey()); -// assertNotNull(serviceInfo); -// -// metadataService.unexportURL(url); -// assertEquals(0, defaultMetadataInfo.getServices().size()); -// assertNull(defaultMetadataInfo.getServiceInfo(url.getProtocolServiceKey())); -// } -// -// @Test -// public void testServiceDefinition() { -// URL url = URL.valueOf("dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService"); -// MetadataServiceDelegation metadataService = new MetadataServiceDelegation(); -// metadataService.setApplicationModel(ApplicationModel.defaultModel()); -// metadataService.publishServiceDefinition(url); -// -// String serviceDefinition = metadataService.getServiceDefinition(url.getServiceInterface(), url.getVersion(), url.getGroup()); -// Gson gson = new Gson(); -// ServiceDefinition serviceDefinitionBuilder = gson.fromJson(serviceDefinition, ServiceDefinition.class); -// assertEquals(serviceDefinitionBuilder.getCanonicalName(), url.getServiceInterface()); -// } -// -// @Test -// public void testSubscribe() { -// MetadataServiceDelegation metadataService = new MetadataServiceDelegation(); -// metadataService.setApplicationModel(ApplicationModel.defaultModel()); -// -// URL url = URL.valueOf("dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService"); -// metadataService.subscribeURL(url); -// -// URL url2 = URL.valueOf("dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService2"); -// metadataService.subscribeURL(url2); -// -// URL url3 = URL.valueOf("dubbo://30.225.21.30:20880/" + MetadataService.class.getName()); -// metadataService.subscribeURL(url3); -// -// SortedSet subscribedURLs = metadataService.getSubscribedURLs(); -// assertEquals(subscribedURLs.size(), 2); -// assertEquals(subscribedURLs.first(), url.toFullString()); -// assertEquals(subscribedURLs.last(), url2.toFullString()); -// } -//} diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/MetaCacheManagerTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/MetaCacheManagerTest.java index b4e38d5b9a..cd1d5312cf 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/MetaCacheManagerTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/MetaCacheManagerTest.java @@ -19,16 +19,16 @@ package org.apache.dubbo.registry.client.metadata.store; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.metadata.MetadataInfo; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; @@ -51,15 +51,16 @@ class MetaCacheManagerTest { @Test void testCache() { -// ScheduledExecutorService cacheRefreshExecutor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Dubbo-cache-refresh")); -// ExecutorRepository executorRepository = Mockito.mock(ExecutorRepository.class); -// when(executorRepository.getCacheRefreshExecutor()).thenReturn(cacheRefreshExecutor); -// ExtensionAccessor extensionAccessor = Mockito.mock(ExtensionAccessor.class); -// when(extensionAccessor.getDefaultExtension(ExecutorRepository.class)).thenReturn(executorRepository); + // ScheduledExecutorService cacheRefreshExecutor = Executors.newSingleThreadScheduledExecutor(new + // NamedThreadFactory("Dubbo-cache-refresh")); + // ExecutorRepository executorRepository = Mockito.mock(ExecutorRepository.class); + // when(executorRepository.getCacheRefreshExecutor()).thenReturn(cacheRefreshExecutor); + // ExtensionAccessor extensionAccessor = Mockito.mock(ExtensionAccessor.class); + // when(extensionAccessor.getDefaultExtension(ExecutorRepository.class)).thenReturn(executorRepository); MetaCacheManager cacheManager = new MetaCacheManager(); try { -// cacheManager.setExtensionAccessor(extensionAccessor); + // cacheManager.setExtensionAccessor(extensionAccessor); MetadataInfo metadataInfo = cacheManager.get("1"); assertNotNull(metadataInfo); @@ -68,7 +69,9 @@ class MetaCacheManagerTest { assertNull(metadataInfo); Map newMetadatas = new HashMap<>(); - MetadataInfo metadataInfo2 = JsonUtils.toJavaObject("{\"app\":\"demo2\",\"services\":{\"greeting/org.apache.dubbo.registry.service.DemoService2:1.0.0:dubbo\":{\"name\":\"org.apache.dubbo.registry.service.DemoService2\",\"group\":\"greeting\",\"version\":\"1.0.0\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.registry.service.DemoService2\",\"params\":{\"application\":\"demo-provider2\",\"sayHello.timeout\":\"7000\",\"version\":\"1.0.0\",\"timeout\":\"5000\",\"group\":\"greeting\"}},\"greeting/org.apache.dubbo.registry.service.DemoService:1.0.0:dubbo\":{\"name\":\"org.apache.dubbo.registry.service.DemoService\",\"group\":\"greeting\",\"version\":\"1.0.0\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.registry.service.DemoService\",\"params\":{\"application\":\"demo-provider2\",\"version\":\"1.0.0\",\"timeout\":\"5000\",\"group\":\"greeting\"}}}}\n", MetadataInfo.class); + MetadataInfo metadataInfo2 = JsonUtils.toJavaObject( + "{\"app\":\"demo2\",\"services\":{\"greeting/org.apache.dubbo.registry.service.DemoService2:1.0.0:dubbo\":{\"name\":\"org.apache.dubbo.registry.service.DemoService2\",\"group\":\"greeting\",\"version\":\"1.0.0\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.registry.service.DemoService2\",\"params\":{\"application\":\"demo-provider2\",\"sayHello.timeout\":\"7000\",\"version\":\"1.0.0\",\"timeout\":\"5000\",\"group\":\"greeting\"}},\"greeting/org.apache.dubbo.registry.service.DemoService:1.0.0:dubbo\":{\"name\":\"org.apache.dubbo.registry.service.DemoService\",\"group\":\"greeting\",\"version\":\"1.0.0\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.registry.service.DemoService\",\"params\":{\"application\":\"demo-provider2\",\"version\":\"1.0.0\",\"timeout\":\"5000\",\"group\":\"greeting\"}}}}\n", + MetadataInfo.class); newMetadatas.put("2", metadataInfo2); cacheManager.update(newMetadatas); @@ -83,17 +86,19 @@ class MetaCacheManagerTest { } } - @Test void testCacheDump() { System.setProperty("dubbo.meta.cache.fileName", "not-exist.dubbo.cache"); - MetadataInfo metadataInfo3 = JsonUtils.toJavaObject("{\"app\":\"demo3\",\"services\":{\"greeting/org.apache.dubbo.registry.service.DemoService2:1.0.0:dubbo\":{\"name\":\"org.apache.dubbo.registry.service.DemoService2\",\"group\":\"greeting\",\"version\":\"1.0.0\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.registry.service.DemoService2\",\"params\":{\"application\":\"demo-provider2\",\"sayHello.timeout\":\"7000\",\"version\":\"1.0.0\",\"timeout\":\"5000\",\"group\":\"greeting\"}},\"greeting/org.apache.dubbo.registry.service.DemoService:1.0.0:dubbo\":{\"name\":\"org.apache.dubbo.registry.service.DemoService\",\"group\":\"greeting\",\"version\":\"1.0.0\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.registry.service.DemoService\",\"params\":{\"application\":\"demo-provider2\",\"version\":\"1.0.0\",\"timeout\":\"5000\",\"group\":\"greeting\"}}}}\n", MetadataInfo.class); + MetadataInfo metadataInfo3 = JsonUtils.toJavaObject( + "{\"app\":\"demo3\",\"services\":{\"greeting/org.apache.dubbo.registry.service.DemoService2:1.0.0:dubbo\":{\"name\":\"org.apache.dubbo.registry.service.DemoService2\",\"group\":\"greeting\",\"version\":\"1.0.0\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.registry.service.DemoService2\",\"params\":{\"application\":\"demo-provider2\",\"sayHello.timeout\":\"7000\",\"version\":\"1.0.0\",\"timeout\":\"5000\",\"group\":\"greeting\"}},\"greeting/org.apache.dubbo.registry.service.DemoService:1.0.0:dubbo\":{\"name\":\"org.apache.dubbo.registry.service.DemoService\",\"group\":\"greeting\",\"version\":\"1.0.0\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.registry.service.DemoService\",\"params\":{\"application\":\"demo-provider2\",\"version\":\"1.0.0\",\"timeout\":\"5000\",\"group\":\"greeting\"}}}}\n", + MetadataInfo.class); MetaCacheManager cacheManager = new MetaCacheManager(); try { cacheManager.put("3", metadataInfo3); try { - MetaCacheManager.CacheRefreshTask task = new MetaCacheManager.CacheRefreshTask<>(cacheManager.getCacheStore(), cacheManager.getCache(), cacheManager, 0); + MetaCacheManager.CacheRefreshTask task = new MetaCacheManager.CacheRefreshTask<>( + cacheManager.getCacheStore(), cacheManager.getCache(), cacheManager, 0); task.run(); } catch (Exception e) { fail(); @@ -115,7 +120,6 @@ class MetaCacheManagerTest { } } - private String getDirectoryOfClassPath() throws URISyntaxException { URL resource = this.getClass().getResource("/log4j.xml"); String path = Paths.get(resource.toURI()).toFile().getAbsolutePath(); diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/DefaultMigrationAddressComparatorTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/DefaultMigrationAddressComparatorTest.java index f97f0b0c1a..8cf2992a80 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/DefaultMigrationAddressComparatorTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/DefaultMigrationAddressComparatorTest.java @@ -22,14 +22,14 @@ import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.cluster.ClusterInvoker; import org.apache.dubbo.rpc.cluster.Directory; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - import java.util.Collections; import java.util.LinkedList; import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + import static org.apache.dubbo.registry.client.migration.DefaultMigrationAddressComparator.NEW_ADDRESS_SIZE; import static org.apache.dubbo.registry.client.migration.DefaultMigrationAddressComparator.OLD_ADDRESS_SIZE; diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/MigrationInvokerTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/MigrationInvokerTest.java index fd5cf5d115..a1ef5cbb12 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/MigrationInvokerTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/MigrationInvokerTest.java @@ -29,6 +29,9 @@ import org.apache.dubbo.rpc.cluster.ClusterInvoker; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; +import java.util.LinkedList; +import java.util.List; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -36,9 +39,6 @@ import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import java.util.LinkedList; -import java.util.List; - class MigrationInvokerTest { @BeforeEach public void before() { @@ -83,8 +83,11 @@ class MigrationInvokerTest { Mockito.when(directory.getAllInvokers()).thenReturn(invokers); Mockito.when(serviceDiscoveryDirectory.getAllInvokers()).thenReturn(serviceDiscoveryInvokers); - Mockito.when(registryProtocol.getInvoker(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(invoker); - Mockito.when(registryProtocol.getServiceDiscoveryInvoker(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(serviceDiscoveryInvoker); + Mockito.when(registryProtocol.getInvoker(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(invoker); + Mockito.when(registryProtocol.getServiceDiscoveryInvoker( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(serviceDiscoveryInvoker); URL consumerURL = Mockito.mock(URL.class); Mockito.when(consumerURL.getServiceInterface()).thenReturn("Test"); @@ -97,7 +100,8 @@ class MigrationInvokerTest { Mockito.when(invoker.getUrl()).thenReturn(consumerURL); Mockito.when(serviceDiscoveryInvoker.getUrl()).thenReturn(consumerURL); - MigrationInvoker migrationInvoker = new MigrationInvoker<>(registryProtocol, null, null, DemoService.class, null, consumerURL); + MigrationInvoker migrationInvoker = + new MigrationInvoker<>(registryProtocol, null, null, DemoService.class, null, consumerURL); MigrationRule migrationRule = Mockito.mock(MigrationRule.class); Mockito.when(migrationRule.getForce(Mockito.any())).thenReturn(true); @@ -255,8 +259,11 @@ class MigrationInvokerTest { Mockito.when(directory.getAllInvokers()).thenReturn(invokers); Mockito.when(serviceDiscoveryDirectory.getAllInvokers()).thenReturn(serviceDiscoveryInvokers); - Mockito.when(registryProtocol.getInvoker(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(invoker); - Mockito.when(registryProtocol.getServiceDiscoveryInvoker(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(serviceDiscoveryInvoker); + Mockito.when(registryProtocol.getInvoker(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(invoker); + Mockito.when(registryProtocol.getServiceDiscoveryInvoker( + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(serviceDiscoveryInvoker); URL consumerURL = Mockito.mock(URL.class); Mockito.when(consumerURL.getServiceInterface()).thenReturn("Test"); @@ -269,7 +276,8 @@ class MigrationInvokerTest { Mockito.when(invoker.getUrl()).thenReturn(consumerURL); Mockito.when(serviceDiscoveryInvoker.getUrl()).thenReturn(consumerURL); - MigrationInvoker migrationInvoker = new MigrationInvoker<>(registryProtocol, null, null, DemoService.class, null, consumerURL); + MigrationInvoker migrationInvoker = + new MigrationInvoker<>(registryProtocol, null, null, DemoService.class, null, consumerURL); MigrationRule migrationRule = Mockito.mock(MigrationRule.class); Mockito.when(migrationRule.getForce(Mockito.any())).thenReturn(true); diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/MigrationRuleHandlerTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/MigrationRuleHandlerTest.java index 318da69cbe..d203a09ee2 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/MigrationRuleHandlerTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/MigrationRuleHandlerTest.java @@ -31,7 +31,7 @@ class MigrationRuleHandlerTest { MigrationClusterInvoker invoker = Mockito.mock(MigrationClusterInvoker.class); URL url = Mockito.mock(URL.class); Mockito.when(url.getDisplayServiceKey()).thenReturn("test"); - Mockito.when(url.getParameter(Mockito.any(), (String) Mockito.any())).thenAnswer(i->i.getArgument(1)); + Mockito.when(url.getParameter(Mockito.any(), (String) Mockito.any())).thenAnswer(i -> i.getArgument(1)); Mockito.when(url.getOrDefaultApplicationModel()).thenReturn(ApplicationModel.defaultModel()); MigrationRuleHandler handler = new MigrationRuleHandler<>(invoker, url); @@ -61,7 +61,8 @@ class MigrationRuleHandlerTest { testMigrationWithStepUnchanged(rule, url, handler, invoker); } - private void testMigrationFailed(MigrationRule rule, URL url, MigrationRuleHandler handler, MigrationClusterInvoker invoker) { + private void testMigrationFailed( + MigrationRule rule, URL url, MigrationRuleHandler handler, MigrationClusterInvoker invoker) { Assertions.assertEquals(MigrationStep.FORCE_INTERFACE, handler.getMigrationStep()); Mockito.when(invoker.migrateToForceApplicationInvoker(Mockito.any())).thenReturn(false); @@ -72,12 +73,12 @@ class MigrationRuleHandlerTest { Assertions.assertEquals(MigrationStep.FORCE_INTERFACE, handler.getMigrationStep()); } - private void testMigrationWithStepUnchanged(MigrationRule rule, URL url, MigrationRuleHandler handler, MigrationClusterInvoker invoker) { + private void testMigrationWithStepUnchanged( + MigrationRule rule, URL url, MigrationRuleHandler handler, MigrationClusterInvoker invoker) { // set the same as Mockito.when(rule.getStep(url)).thenReturn(handler.getMigrationStep()); handler.doMigrate(rule); // no interaction Mockito.verify(invoker, Mockito.times(1)).migrateToForceInterfaceInvoker(rule); } - } diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/MigrationRuleListenerTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/MigrationRuleListenerTest.java index 6b06bf0f9b..3fc111646e 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/MigrationRuleListenerTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/MigrationRuleListenerTest.java @@ -23,57 +23,54 @@ import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.registry.client.migration.model.MigrationRule; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.concurrent.CountDownLatch; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import java.util.concurrent.CountDownLatch; - import static org.awaitility.Awaitility.await; class MigrationRuleListenerTest { - private String localRule = "key: demo-consumer\n" + - "step: APPLICATION_FIRST\n" + - "threshold: 1.0\n" + - "proportion: 60\n" + - "delay: 60\n" + - "force: false\n" + - "interfaces:\n" + - " - serviceKey: DemoService:1.0.0\n" + - " threshold: 0.5\n" + - " proportion: 30\n" + - " delay: 30\n" + - " force: true\n" + - " step: APPLICATION_FIRST\n" + - " - serviceKey: GreetingService:1.0.0\n" + - " step: FORCE_APPLICATION"; + private String localRule = "key: demo-consumer\n" + "step: APPLICATION_FIRST\n" + + "threshold: 1.0\n" + + "proportion: 60\n" + + "delay: 60\n" + + "force: false\n" + + "interfaces:\n" + + " - serviceKey: DemoService:1.0.0\n" + + " threshold: 0.5\n" + + " proportion: 30\n" + + " delay: 30\n" + + " force: true\n" + + " step: APPLICATION_FIRST\n" + + " - serviceKey: GreetingService:1.0.0\n" + + " step: FORCE_APPLICATION"; - private String remoteRule = "key: demo-consumer\n" + - "step: FORCE_APPLICATION\n" + - "threshold: 1.0\n" + - "proportion: 60\n" + - "delay: 60\n" + - "force: false\n" + - "interfaces:\n" + - " - serviceKey: DemoService:1.0.0\n" + - " threshold: 0.5\n" + - " proportion: 30\n" + - " delay: 30\n" + - " force: true\n" + - " step: FORCE_APPLICATION\n" + - " - serviceKey: GreetingService:1.0.0\n" + - " step: FORCE_INTERFACE"; + private String remoteRule = "key: demo-consumer\n" + "step: FORCE_APPLICATION\n" + + "threshold: 1.0\n" + + "proportion: 60\n" + + "delay: 60\n" + + "force: false\n" + + "interfaces:\n" + + " - serviceKey: DemoService:1.0.0\n" + + " threshold: 0.5\n" + + " proportion: 30\n" + + " delay: 30\n" + + " force: true\n" + + " step: FORCE_APPLICATION\n" + + " - serviceKey: GreetingService:1.0.0\n" + + " step: FORCE_INTERFACE"; - private String dynamicRemoteRule = "key: demo-consumer\n" + - "step: APPLICATION_FIRST\n" + - "threshold: 1.0\n" + - "proportion: 60\n" + - "delay: 60\n" + - "force: false\n" + - "interfaces:\n"; + private String dynamicRemoteRule = "key: demo-consumer\n" + "step: APPLICATION_FIRST\n" + + "threshold: 1.0\n" + + "proportion: 60\n" + + "delay: 60\n" + + "force: false\n" + + "interfaces:\n"; @AfterEach public void tearDown() { @@ -90,7 +87,10 @@ class MigrationRuleListenerTest { DynamicConfiguration dynamicConfiguration = Mockito.mock(DynamicConfiguration.class); ApplicationModel.reset(); - ApplicationModel.defaultModel().getDefaultModule().modelEnvironment().setDynamicConfiguration(dynamicConfiguration); + ApplicationModel.defaultModel() + .getDefaultModule() + .modelEnvironment() + .setDynamicConfiguration(dynamicConfiguration); ApplicationModel.defaultModel().getDefaultModule().modelEnvironment().setLocalMigrationRule(localRule); ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("demo-consumer"); @@ -101,20 +101,22 @@ class MigrationRuleListenerTest { Mockito.when(consumerURL.getParameter("timestamp")).thenReturn("1"); System.setProperty("dubbo.application.migration.delay", "1"); - MigrationRuleHandler handler = Mockito.mock(MigrationRuleHandler.class, Mockito.withSettings().verboseLogging()); + MigrationRuleHandler handler = + Mockito.mock(MigrationRuleHandler.class, Mockito.withSettings().verboseLogging()); CountDownLatch countDownLatch = new CountDownLatch(1); - MigrationRuleListener migrationRuleListener = new MigrationRuleListener(ApplicationModel.defaultModel().getDefaultModule()) { - @Override - public synchronized void process(ConfigChangedEvent event) { - try { - countDownLatch.await(); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - super.process(event); - } - }; + MigrationRuleListener migrationRuleListener = + new MigrationRuleListener(ApplicationModel.defaultModel().getDefaultModule()) { + @Override + public synchronized void process(ConfigChangedEvent event) { + try { + countDownLatch.await(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + super.process(event); + } + }; MigrationInvoker migrationInvoker = Mockito.mock(MigrationInvoker.class); migrationRuleListener.getHandlers().put(migrationInvoker, handler); @@ -123,7 +125,7 @@ class MigrationRuleListenerTest { await().untilAsserted(() -> { Mockito.verify(handler).doMigrate(Mockito.any()); }); -// Mockito.verify(handler, Mockito.timeout(5000)).doMigrate(Mockito.any()); + // Mockito.verify(handler, Mockito.timeout(5000)).doMigrate(Mockito.any()); migrationRuleListener.onRefer(null, migrationInvoker, consumerURL, null); Mockito.verify(handler, Mockito.times(2)).doMigrate(Mockito.any()); @@ -145,9 +147,11 @@ class MigrationRuleListenerTest { Mockito.when(consumerURL.getParameter("timestamp")).thenReturn("1"); System.setProperty("dubbo.application.migration.delay", "1000"); - MigrationRuleHandler handler = Mockito.mock(MigrationRuleHandler.class, Mockito.withSettings().verboseLogging()); + MigrationRuleHandler handler = + Mockito.mock(MigrationRuleHandler.class, Mockito.withSettings().verboseLogging()); - MigrationRuleListener migrationRuleListener = new MigrationRuleListener(ApplicationModel.defaultModel().getDefaultModule()); + MigrationRuleListener migrationRuleListener = + new MigrationRuleListener(ApplicationModel.defaultModel().getDefaultModule()); MigrationInvoker migrationInvoker = Mockito.mock(MigrationInvoker.class); migrationRuleListener.getHandlers().put(migrationInvoker, handler); migrationRuleListener.onRefer(null, migrationInvoker, consumerURL, null); @@ -170,7 +174,10 @@ class MigrationRuleListenerTest { DynamicConfiguration dynamicConfiguration = Mockito.mock(DynamicConfiguration.class); Mockito.doReturn(remoteRule).when(dynamicConfiguration).getConfig(Mockito.anyString(), Mockito.anyString()); - ApplicationModel.defaultModel().getDefaultModule().modelEnvironment().setDynamicConfiguration(dynamicConfiguration); + ApplicationModel.defaultModel() + .getDefaultModule() + .modelEnvironment() + .setDynamicConfiguration(dynamicConfiguration); ApplicationModel.defaultModel().getDefaultModule().modelEnvironment().setLocalMigrationRule(localRule); ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("demo-consumer"); @@ -185,12 +192,15 @@ class MigrationRuleListenerTest { Mockito.when(consumerURL2.getParameter("timestamp")).thenReturn("2"); System.setProperty("dubbo.application.migration.delay", "10"); - MigrationRuleHandler handler = Mockito.mock(MigrationRuleHandler.class, Mockito.withSettings().verboseLogging()); - MigrationRuleHandler handler2 = Mockito.mock(MigrationRuleHandler.class, Mockito.withSettings().verboseLogging()); + MigrationRuleHandler handler = + Mockito.mock(MigrationRuleHandler.class, Mockito.withSettings().verboseLogging()); + MigrationRuleHandler handler2 = + Mockito.mock(MigrationRuleHandler.class, Mockito.withSettings().verboseLogging()); // Both local rule and remote rule are here // Local rule with one delayed task started to apply - MigrationRuleListener migrationRuleListener = new MigrationRuleListener(ApplicationModel.defaultModel().getDefaultModule()); + MigrationRuleListener migrationRuleListener = + new MigrationRuleListener(ApplicationModel.defaultModel().getDefaultModule()); Assertions.assertNotNull(migrationRuleListener.localRuleMigrationFuture); Assertions.assertNull(migrationRuleListener.ruleMigrationFuture); MigrationInvoker migrationInvoker = Mockito.mock(MigrationInvoker.class); @@ -216,7 +226,6 @@ class MigrationRuleListenerTest { Mockito.verify(handler2, Mockito.times(1)).doMigrate(captor2.capture()); Assertions.assertEquals(tmpRemoteRule, captor2.getValue()); - migrationRuleListener.process(new ConfigChangedEvent("key", "group", dynamicRemoteRule)); await().until(migrationRuleListener.ruleQueue::isEmpty); @@ -228,8 +237,10 @@ class MigrationRuleListenerTest { Assertions.assertNotNull(migrationRuleListener.ruleMigrationFuture); ArgumentCaptor captor_event = ArgumentCaptor.forClass(MigrationRule.class); Mockito.verify(handler, Mockito.times(2)).doMigrate(captor_event.capture()); - Assertions.assertEquals("APPLICATION_FIRST", captor_event.getValue().getStep().toString()); + Assertions.assertEquals( + "APPLICATION_FIRST", captor_event.getValue().getStep().toString()); Mockito.verify(handler2, Mockito.times(2)).doMigrate(captor_event.capture()); - Assertions.assertEquals("APPLICATION_FIRST", captor_event.getValue().getStep().toString()); + Assertions.assertEquals( + "APPLICATION_FIRST", captor_event.getValue().getStep().toString()); } } diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/model/MigrationRuleTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/model/MigrationRuleTest.java index e801688f7d..673daf4436 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/model/MigrationRuleTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/migration/model/MigrationRuleTest.java @@ -20,14 +20,14 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.metadata.ServiceNameMapping; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentMatchers; -import org.mockito.Mockito; - import java.util.Collections; import java.util.HashSet; import java.util.Set; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentMatchers; +import org.mockito.Mockito; + import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_TYPE_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -44,28 +44,27 @@ class MigrationRuleTest { void test_parse() { when(mapping.getMapping(any(URL.class))).thenReturn(Collections.emptySet()); - String rule = "key: demo-consumer\n" + - "step: APPLICATION_FIRST\n" + - "threshold: 1.0\n" + - "proportion: 60\n" + - "delay: 60\n" + - "force: false\n" + - "interfaces:\n" + - " - serviceKey: DemoService:1.0.0\n" + - " threshold: 0.5\n" + - " proportion: 30\n" + - " delay: 30\n" + - " force: true\n" + - " step: APPLICATION_FIRST\n" + - " - serviceKey: GreetingService:1.0.0\n" + - " step: FORCE_APPLICATION\n" + - "applications:\n" + - " - serviceKey: TestApplication\n" + - " threshold: 0.3\n" + - " proportion: 20\n" + - " delay: 10\n" + - " force: false\n" + - " step: FORCE_INTERFACE\n"; + String rule = "key: demo-consumer\n" + "step: APPLICATION_FIRST\n" + + "threshold: 1.0\n" + + "proportion: 60\n" + + "delay: 60\n" + + "force: false\n" + + "interfaces:\n" + + " - serviceKey: DemoService:1.0.0\n" + + " threshold: 0.5\n" + + " proportion: 30\n" + + " delay: 30\n" + + " force: true\n" + + " step: APPLICATION_FIRST\n" + + " - serviceKey: GreetingService:1.0.0\n" + + " step: FORCE_APPLICATION\n" + + "applications:\n" + + " - serviceKey: TestApplication\n" + + " threshold: 0.3\n" + + " proportion: 20\n" + + " delay: 10\n" + + " force: false\n" + + " step: FORCE_INTERFACE\n"; MigrationRule migrationRule = MigrationRule.parse(rule); assertEquals("demo-consumer", migrationRule.getKey()); @@ -81,8 +80,10 @@ class MigrationRuleTest { Mockito.when(url.getScopeModel()).thenReturn(defaultModel); Mockito.when(url.getDisplayServiceKey()).thenReturn("DemoService:1.0.0"); - Mockito.when(url.getParameter(ArgumentMatchers.eq(REGISTRY_CLUSTER_TYPE_KEY), anyString())).thenReturn("default"); - Mockito.when(url.getParameter(ArgumentMatchers.eq(REGISTRY_CLUSTER_TYPE_KEY), anyString())).thenReturn("default"); + Mockito.when(url.getParameter(ArgumentMatchers.eq(REGISTRY_CLUSTER_TYPE_KEY), anyString())) + .thenReturn("default"); + Mockito.when(url.getParameter(ArgumentMatchers.eq(REGISTRY_CLUSTER_TYPE_KEY), anyString())) + .thenReturn("default"); assertEquals(2, migrationRule.getInterfaces().size()); diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/support/MockServiceDiscovery.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/support/MockServiceDiscovery.java index 46e7e04264..07dc604581 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/support/MockServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/support/MockServiceDiscovery.java @@ -16,16 +16,16 @@ */ package org.apache.dubbo.registry.client.support; -import java.util.Collections; -import java.util.List; -import java.util.Set; - import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.client.AbstractServiceDiscovery; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.registry.client.metadata.store.MetaCacheManager; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.Collections; +import java.util.List; +import java.util.Set; + public class MockServiceDiscovery extends AbstractServiceDiscovery { public MockServiceDiscovery(ApplicationModel applicationModel, URL registryURL) { super(applicationModel, registryURL); @@ -36,19 +36,13 @@ public class MockServiceDiscovery extends AbstractServiceDiscovery { } @Override - public void doRegister(ServiceInstance serviceInstance) throws RuntimeException { - - } + public void doRegister(ServiceInstance serviceInstance) throws RuntimeException {} @Override - public void doUnregister(ServiceInstance serviceInstance) { - - } + public void doUnregister(ServiceInstance serviceInstance) {} @Override - public void doDestroy() throws Exception { - - } + public void doDestroy() throws Exception {} @Override public Set getServices() { diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/CountRegistryProtocolListener.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/CountRegistryProtocolListener.java index 1de1e3994a..0c2f109147 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/CountRegistryProtocolListener.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/CountRegistryProtocolListener.java @@ -16,22 +16,18 @@ */ package org.apache.dubbo.registry.integration; - import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.cluster.ClusterInvoker; import java.util.concurrent.atomic.AtomicInteger; - public class CountRegistryProtocolListener implements RegistryProtocolListener { private static final AtomicInteger referCounter = new AtomicInteger(0); @Override - public void onExport(RegistryProtocol registryProtocol, Exporter exporter) { - - } + public void onExport(RegistryProtocol registryProtocol, Exporter exporter) {} @Override public void onRefer(RegistryProtocol registryProtocol, ClusterInvoker invoker, URL url, URL registryURL) { @@ -39,9 +35,7 @@ public class CountRegistryProtocolListener implements RegistryProtocolListener { } @Override - public void onDestroy() { - - } + public void onDestroy() {} public static AtomicInteger getReferCounter() { return referCounter; diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/DemoService.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/DemoService.java index a48a5c9c92..36e4cb25ae 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/DemoService.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/DemoService.java @@ -16,6 +16,4 @@ */ package org.apache.dubbo.registry.integration; - -public interface DemoService { -} +public interface DemoService {} diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/DynamicDirectoryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/DynamicDirectoryTest.java index 8253614c6c..310611a4c1 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/DynamicDirectoryTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/DynamicDirectoryTest.java @@ -16,18 +16,17 @@ */ package org.apache.dubbo.registry.integration; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.registry.Registry; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY; @@ -55,62 +54,46 @@ class DynamicDirectoryTest { parameters.put("register", "true"); parameters.put(REGISTER_IP_KEY, "172.23.236.180"); - Map attributes = new HashMap<>(); - ServiceConfigURL serviceConfigURLWithoutSimplified = new ServiceConfigURL("registry", - "127.0.0.1", - 2181, - "org.apache.dubbo.registry.RegistryService", - parameters); + ServiceConfigURL serviceConfigURLWithoutSimplified = new ServiceConfigURL( + "registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters); Map refer = new HashMap<>(); attributes.put(REFER_KEY, refer); attributes.put("key1", "value1"); URL urlWithoutSimplified = serviceConfigURLWithoutSimplified.addAttributes(attributes); DemoDynamicDirectory dynamicDirectoryWithoutSimplified = - new DemoDynamicDirectory<>(DemoService.class, urlWithoutSimplified); + new DemoDynamicDirectory<>(DemoService.class, urlWithoutSimplified); - URL registeredConsumerUrlWithoutSimplified = new ServiceConfigURL("dubbo", - "127.0.0.1", - 2181, - DemoService.class.getName(), - parameters); + URL registeredConsumerUrlWithoutSimplified = + new ServiceConfigURL("dubbo", "127.0.0.1", 2181, DemoService.class.getName(), parameters); dynamicDirectoryWithoutSimplified.setRegisteredConsumerUrl(registeredConsumerUrlWithoutSimplified); - URL urlForNotSimplified = registeredConsumerUrlWithoutSimplified - .addParameters(CATEGORY_KEY, CONSUMERS_CATEGORY, CHECK_KEY, String.valueOf(false)); + URL urlForNotSimplified = registeredConsumerUrlWithoutSimplified.addParameters( + CATEGORY_KEY, CONSUMERS_CATEGORY, CHECK_KEY, String.valueOf(false)); Assertions.assertEquals(urlForNotSimplified, dynamicDirectoryWithoutSimplified.getRegisteredConsumerUrl()); // verify simplified consumer url information that needs to be registered parameters.put(SIMPLIFIED_KEY, "true"); - ServiceConfigURL serviceConfigURLWithSimplified = new ServiceConfigURL("registry", - "127.0.0.1", - 2181, - "org.apache.dubbo.registry.RegistryService", - parameters); + ServiceConfigURL serviceConfigURLWithSimplified = new ServiceConfigURL( + "registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters); URL urlWithSimplified = serviceConfigURLWithSimplified.addAttributes(attributes); - DemoDynamicDirectory dynamicDirectoryWithSimplified = new DemoDynamicDirectory<>(DemoService.class, urlWithSimplified); + DemoDynamicDirectory dynamicDirectoryWithSimplified = + new DemoDynamicDirectory<>(DemoService.class, urlWithSimplified); - URL registeredConsumerUrlWithSimplified = new ServiceConfigURL("dubbo", - "127.0.0.1", - 2181, - DemoService.class.getName(), - parameters); + URL registeredConsumerUrlWithSimplified = + new ServiceConfigURL("dubbo", "127.0.0.1", 2181, DemoService.class.getName(), parameters); dynamicDirectoryWithSimplified.setRegisteredConsumerUrl(registeredConsumerUrlWithSimplified); - URL urlForSimplified = URL.valueOf( - registeredConsumerUrlWithSimplified, - DEFAULT_REGISTER_CONSUMER_KEYS, - null).addParameters(CATEGORY_KEY, CONSUMERS_CATEGORY, CHECK_KEY, String.valueOf(false)); + URL urlForSimplified = URL.valueOf(registeredConsumerUrlWithSimplified, DEFAULT_REGISTER_CONSUMER_KEYS, null) + .addParameters(CATEGORY_KEY, CONSUMERS_CATEGORY, CHECK_KEY, String.valueOf(false)); Assertions.assertEquals(urlForSimplified, dynamicDirectoryWithSimplified.getRegisteredConsumerUrl()); - } - @Test void testSubscribe() { @@ -120,13 +103,9 @@ class DynamicDirectoryTest { parameters.put("register", "true"); parameters.put(REGISTER_IP_KEY, "172.23.236.180"); - Map attributes = new HashMap<>(); - ServiceConfigURL serviceConfigUrl = new ServiceConfigURL("registry", - "127.0.0.1", - 2181, - "org.apache.dubbo.registry.RegistryService", - parameters); + ServiceConfigURL serviceConfigUrl = new ServiceConfigURL( + "registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters); Map refer = new HashMap<>(); attributes.put(REFER_KEY, refer); attributes.put("key1", "value1"); @@ -134,11 +113,7 @@ class DynamicDirectoryTest { DemoDynamicDirectory demoDynamicDirectory = new DemoDynamicDirectory<>(DemoService.class, url); - URL subscribeUrl = new ServiceConfigURL("dubbo", - "127.0.0.1", - 20881, - DemoService.class.getName(), - parameters); + URL subscribeUrl = new ServiceConfigURL("dubbo", "127.0.0.1", 20881, DemoService.class.getName(), parameters); Registry registry = mock(Registry.class); demoDynamicDirectory.setRegistry(registry); @@ -149,7 +124,6 @@ class DynamicDirectoryTest { Assertions.assertEquals(subscribeUrl, demoDynamicDirectory.getSubscribeUrl()); } - static class DemoDynamicDirectory extends DynamicDirectory { public DemoDynamicDirectory(Class serviceType, URL url) { @@ -157,14 +131,10 @@ class DynamicDirectoryTest { } @Override - protected void destroyAllInvokers() { - - } + protected void destroyAllInvokers() {} @Override - protected void refreshOverrideAndInvoker(List urls) { - - } + protected void refreshOverrideAndInvoker(List urls) {} @Override public boolean isAvailable() { @@ -172,8 +142,6 @@ class DynamicDirectoryTest { } @Override - public void notify(List urls) { - - } + public void notify(List urls) {} } } diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/RegistryProtocolTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/RegistryProtocolTest.java index ba81eba1e3..60af22506c 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/RegistryProtocolTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/integration/RegistryProtocolTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.registry.integration; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.CompositeConfiguration; import org.apache.dubbo.common.extension.ExtensionLoader; @@ -30,23 +29,21 @@ import org.apache.dubbo.registry.client.migration.MigrationRuleListener; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.cluster.Cluster; import org.apache.dubbo.rpc.cluster.support.FailoverCluster; -//import org.apache.dubbo.rpc.cluster.support.MergeableCluster; -//import org.apache.dubbo.rpc.cluster.support.wrapper.MockClusterWrapper; import org.apache.dubbo.rpc.cluster.support.wrapper.ScopeClusterWrapper; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; @@ -86,7 +83,7 @@ class RegistryProtocolTest { CompositeConfiguration compositeConfiguration = mock(CompositeConfiguration.class); when(compositeConfiguration.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true)) - .thenReturn(true); + .thenReturn(true); Map parameters = new HashMap<>(); parameters.put(INTERFACE_KEY, DemoService.class.getName()); @@ -95,11 +92,8 @@ class RegistryProtocolTest { parameters.put(REGISTER_IP_KEY, "172.23.236.180"); Map attributes = new HashMap<>(); - ServiceConfigURL serviceConfigURL = new ServiceConfigURL("registry", - "127.0.0.1", - 2181, - "org.apache.dubbo.registry.RegistryService", - parameters); + ServiceConfigURL serviceConfigURL = new ServiceConfigURL( + "registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters); Map refer = new HashMap<>(); attributes.put(REFER_KEY, refer); attributes.put("key1", "value1"); @@ -115,11 +109,15 @@ class RegistryProtocolTest { registryProtocolListeners.add(migrationRuleListener); ModuleModel moduleModel = Mockito.spy(ApplicationModel.defaultModel().getDefaultModule()); - moduleModel.getApplicationModel().getApplicationConfigManager().setApplication(new ApplicationConfig("application1")); + moduleModel + .getApplicationModel() + .getApplicationConfigManager() + .setApplication(new ApplicationConfig("application1")); ExtensionLoader extensionLoaderMock = mock(ExtensionLoader.class); - Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class)).thenReturn(extensionLoaderMock); + Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class)) + .thenReturn(extensionLoaderMock); Mockito.when(extensionLoaderMock.getActivateExtension(url, REGISTRY_PROTOCOL_LISTENER_KEY)) - .thenReturn(registryProtocolListeners); + .thenReturn(registryProtocolListeners); url = url.setScopeModel(moduleModel); when(registryFactory.getRegistry(registryProtocol.getRegistryUrl(url))).thenReturn(registry); @@ -153,7 +151,7 @@ class RegistryProtocolTest { CompositeConfiguration compositeConfiguration = mock(CompositeConfiguration.class); when(compositeConfiguration.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true)) - .thenReturn(true); + .thenReturn(true); Map parameters = new HashMap<>(); parameters.put(INTERFACE_KEY, DemoService.class.getName()); @@ -162,11 +160,8 @@ class RegistryProtocolTest { parameters.put(REGISTER_IP_KEY, "172.23.236.180"); parameters.put(PROTOCOL_KEY, "tri"); Map attributes = new HashMap<>(); - ServiceConfigURL serviceConfigURL = new ServiceConfigURL("registry", - "127.0.0.1", - 2181, - "org.apache.dubbo.registry.RegistryService", - parameters); + ServiceConfigURL serviceConfigURL = new ServiceConfigURL( + "registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters); Map refer = new HashMap<>(); attributes.put(REFER_KEY, refer); attributes.put("key1", "value1"); @@ -182,11 +177,15 @@ class RegistryProtocolTest { registryProtocolListeners.add(migrationRuleListener); ModuleModel moduleModel = Mockito.spy(ApplicationModel.defaultModel().getDefaultModule()); - moduleModel.getApplicationModel().getApplicationConfigManager().setApplication(new ApplicationConfig("application1")); + moduleModel + .getApplicationModel() + .getApplicationConfigManager() + .setApplication(new ApplicationConfig("application1")); ExtensionLoader extensionLoaderMock = mock(ExtensionLoader.class); - Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class)).thenReturn(extensionLoaderMock); + Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class)) + .thenReturn(extensionLoaderMock); Mockito.when(extensionLoaderMock.getActivateExtension(url, REGISTRY_PROTOCOL_LISTENER_KEY)) - .thenReturn(registryProtocolListeners); + .thenReturn(registryProtocolListeners); url = url.setScopeModel(moduleModel); when(registryFactory.getRegistry(registryProtocol.getRegistryUrl(url))).thenReturn(registry); @@ -205,7 +204,6 @@ class RegistryProtocolTest { Assertions.assertEquals(parameters.get(REGISTER_IP_KEY), consumerUrl.getHost()); Assertions.assertFalse(consumerUrl.getAttributes().containsKey(REFER_KEY)); Assertions.assertEquals("value1", consumerUrl.getAttribute("key1")); - } /** @@ -219,13 +217,12 @@ class RegistryProtocolTest { ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("application1"); - ConfigManager configManager = mock(ConfigManager.class); when(configManager.getApplicationOrElseThrow()).thenReturn(applicationConfig); CompositeConfiguration compositeConfiguration = mock(CompositeConfiguration.class); when(compositeConfiguration.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true)) - .thenReturn(true); + .thenReturn(true); Map parameters = new HashMap<>(); parameters.put(INTERFACE_KEY, DemoService.class.getName()); @@ -233,11 +230,8 @@ class RegistryProtocolTest { parameters.put("register", "false"); Map attributes = new HashMap<>(); - ServiceConfigURL serviceConfigURL = new ServiceConfigURL("registry", - "127.0.0.1", - 2181, - "org.apache.dubbo.registry.RegistryService", - parameters); + ServiceConfigURL serviceConfigURL = new ServiceConfigURL( + "registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters); Map refer = new HashMap<>(); attributes.put(REFER_KEY, refer); URL url = serviceConfigURL.addAttributes(attributes); @@ -251,11 +245,15 @@ class RegistryProtocolTest { RegistryProtocol registryProtocol = new RegistryProtocol(); ModuleModel moduleModel = Mockito.spy(ApplicationModel.defaultModel().getDefaultModule()); - moduleModel.getApplicationModel().getApplicationConfigManager().setApplication(new ApplicationConfig("application1")); + moduleModel + .getApplicationModel() + .getApplicationConfigManager() + .setApplication(new ApplicationConfig("application1")); ExtensionLoader extensionLoaderMock = mock(ExtensionLoader.class); - Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class)).thenReturn(extensionLoaderMock); + Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class)) + .thenReturn(extensionLoaderMock); Mockito.when(extensionLoaderMock.getActivateExtension(url, REGISTRY_PROTOCOL_LISTENER_KEY)) - .thenReturn(registryProtocolListeners); + .thenReturn(registryProtocolListeners); Mockito.when(moduleModel.getExtensionLoader(RegistryFactory.class)).thenReturn(extensionLoaderMock); Mockito.when(extensionLoaderMock.getAdaptiveExtension()).thenReturn(registryFactory); url = url.setScopeModel(moduleModel); @@ -266,9 +264,13 @@ class RegistryProtocolTest { Assertions.assertTrue(invoker instanceof MigrationInvoker); Assertions.assertTrue(((MigrationInvoker) invoker).getCluster() instanceof ScopeClusterWrapper); -// Assertions.assertTrue(((ScopeClusterWrapper) ((MigrationInvoker) invoker).getCluster()).getCluster() instanceof MockClusterWrapper); -// Assertions.assertTrue(((MockClusterWrapper) ((ScopeClusterWrapper) ((MigrationInvoker) invoker).getCluster()).getCluster()).getCluster() instanceof FailoverCluster); - Assertions.assertTrue((((ScopeClusterWrapper) ((MigrationInvoker) invoker).getCluster())).getCluster() instanceof FailoverCluster); + // Assertions.assertTrue(((ScopeClusterWrapper) ((MigrationInvoker) + // invoker).getCluster()).getCluster() instanceof MockClusterWrapper); + // Assertions.assertTrue(((MockClusterWrapper) ((ScopeClusterWrapper) ((MigrationInvoker) + // invoker).getCluster()).getCluster()).getCluster() instanceof FailoverCluster); + Assertions.assertTrue( + (((ScopeClusterWrapper) ((MigrationInvoker) invoker).getCluster())).getCluster() + instanceof FailoverCluster); } /** @@ -286,7 +288,7 @@ class RegistryProtocolTest { CompositeConfiguration compositeConfiguration = mock(CompositeConfiguration.class); when(compositeConfiguration.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true)) - .thenReturn(true); + .thenReturn(true); Map parameters = new HashMap<>(); parameters.put(INTERFACE_KEY, DemoService.class.getName()); @@ -295,11 +297,7 @@ class RegistryProtocolTest { Map attributes = new HashMap<>(); ServiceConfigURL serviceConfigURL = new ServiceConfigURL( - "registry", - "127.0.0.1", - 2181, - "org.apache.dubbo.registry.RegistryService", - parameters); + "registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters); Map refer = new HashMap<>(); refer.put(GROUP_KEY, "group1,group2"); attributes.put(REFER_KEY, refer); @@ -314,11 +312,15 @@ class RegistryProtocolTest { RegistryProtocol registryProtocol = new RegistryProtocol(); ModuleModel moduleModel = Mockito.spy(ApplicationModel.defaultModel().getDefaultModule()); - moduleModel.getApplicationModel().getApplicationConfigManager().setApplication(new ApplicationConfig("application1")); + moduleModel + .getApplicationModel() + .getApplicationConfigManager() + .setApplication(new ApplicationConfig("application1")); ExtensionLoader extensionLoaderMock = mock(ExtensionLoader.class); - Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class)).thenReturn(extensionLoaderMock); + Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class)) + .thenReturn(extensionLoaderMock); Mockito.when(extensionLoaderMock.getActivateExtension(url, REGISTRY_PROTOCOL_LISTENER_KEY)) - .thenReturn(registryProtocolListeners); + .thenReturn(registryProtocolListeners); Mockito.when(moduleModel.getExtensionLoader(RegistryFactory.class)).thenReturn(extensionLoaderMock); Mockito.when(extensionLoaderMock.getAdaptiveExtension()).thenReturn(registryFactory); url = url.setScopeModel(moduleModel); @@ -330,9 +332,11 @@ class RegistryProtocolTest { Assertions.assertTrue(invoker instanceof MigrationInvoker); Assertions.assertTrue(((MigrationInvoker) invoker).getCluster() instanceof ScopeClusterWrapper); -// Assertions.assertTrue(((ScopeClusterWrapper) ((MigrationInvoker) invoker).getCluster()).getCluster() instanceof MockClusterWrapper); + // Assertions.assertTrue(((ScopeClusterWrapper) ((MigrationInvoker) + // invoker).getCluster()).getCluster() instanceof MockClusterWrapper); -// Assertions.assertTrue(((MockClusterWrapper) ((ScopeClusterWrapper) ((MigrationInvoker) invoker).getCluster()).getCluster()).getCluster() instanceof MergeableCluster); + // Assertions.assertTrue(((MockClusterWrapper) ((ScopeClusterWrapper) ((MigrationInvoker) + // invoker).getCluster()).getCluster()).getCluster() instanceof MergeableCluster); } @@ -351,7 +355,7 @@ class RegistryProtocolTest { CompositeConfiguration compositeConfiguration = mock(CompositeConfiguration.class); when(compositeConfiguration.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true)) - .thenReturn(true); + .thenReturn(true); Map parameters = new HashMap<>(); parameters.put(INTERFACE_KEY, DemoService.class.getName()); @@ -360,11 +364,7 @@ class RegistryProtocolTest { Map attributes = new HashMap<>(); ServiceConfigURL serviceConfigURL = new ServiceConfigURL( - "registry", - "127.0.0.1", - 2181, - "org.apache.dubbo.registry.RegistryService", - parameters); + "registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters); Map refer = new HashMap<>(); refer.put(GROUP_KEY, "group1,group2"); attributes.put(REFER_KEY, refer); @@ -374,13 +374,15 @@ class RegistryProtocolTest { Map consumerAttribute = new HashMap<>(url.getAttributes()); consumerAttribute.remove(REFER_KEY); - URL consumerUrl = new ServiceConfigURL(parameters.get(PROTOCOL_KEY) == null ? DUBBO : parameters.get(PROTOCOL_KEY), - null, - null, - parameters.get(REGISTER_IP_KEY), - 0, url.getPath(), - parameters, - consumerAttribute); + URL consumerUrl = new ServiceConfigURL( + parameters.get(PROTOCOL_KEY) == null ? DUBBO : parameters.get(PROTOCOL_KEY), + null, + null, + parameters.get(REGISTER_IP_KEY), + 0, + url.getPath(), + parameters, + consumerAttribute); url = url.putAttribute(CONSUMER_URL_KEY, consumerUrl); MigrationRuleListener migrationRuleListener = mock(MigrationRuleListener.class); List registryProtocolListeners = new ArrayList<>(); @@ -388,18 +390,21 @@ class RegistryProtocolTest { RegistryProtocol registryProtocol = new RegistryProtocol(); ModuleModel moduleModel = Mockito.spy(ApplicationModel.defaultModel().getDefaultModule()); - moduleModel.getApplicationModel().getApplicationConfigManager().setApplication(new ApplicationConfig("application1")); + moduleModel + .getApplicationModel() + .getApplicationConfigManager() + .setApplication(new ApplicationConfig("application1")); ExtensionLoader extensionLoaderMock = mock(ExtensionLoader.class); - Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class)).thenReturn(extensionLoaderMock); + Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class)) + .thenReturn(extensionLoaderMock); Mockito.when(extensionLoaderMock.getActivateExtension(url, REGISTRY_PROTOCOL_LISTENER_KEY)) - .thenReturn(registryProtocolListeners); + .thenReturn(registryProtocolListeners); url = url.setScopeModel(moduleModel); registryProtocol.interceptInvoker(clusterInvoker, url, consumerUrl); verify(migrationRuleListener, times(1)).onRefer(registryProtocol, clusterInvoker, consumerUrl, url); } - /** * Verify that if registry.protocol.listener is configured, * whether the corresponding RegistryProtocolListener will be executed normally @@ -416,7 +421,7 @@ class RegistryProtocolTest { CompositeConfiguration compositeConfiguration = mock(CompositeConfiguration.class); when(compositeConfiguration.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true)) - .thenReturn(true); + .thenReturn(true); Map parameters = new HashMap<>(); parameters.put(INTERFACE_KEY, DemoService.class.getName()); @@ -426,11 +431,7 @@ class RegistryProtocolTest { Map attributes = new HashMap<>(); ServiceConfigURL serviceConfigURL = new ServiceConfigURL( - "registry", - "127.0.0.1", - 2181, - "org.apache.dubbo.registry.RegistryService", - parameters); + "registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters); Map refer = new HashMap<>(); refer.put(GROUP_KEY, "group1,group2"); attributes.put(REFER_KEY, refer); @@ -441,29 +442,36 @@ class RegistryProtocolTest { Map consumerAttribute = new HashMap<>(url.getAttributes()); consumerAttribute.remove(REFER_KEY); - URL consumerUrl = new ServiceConfigURL(parameters.get(PROTOCOL_KEY) == null ? DUBBO : parameters.get(PROTOCOL_KEY), - null, - null, - parameters.get(REGISTER_IP_KEY), - 0, url.getPath(), - parameters, - consumerAttribute); + URL consumerUrl = new ServiceConfigURL( + parameters.get(PROTOCOL_KEY) == null ? DUBBO : parameters.get(PROTOCOL_KEY), + null, + null, + parameters.get(REGISTER_IP_KEY), + 0, + url.getPath(), + parameters, + consumerAttribute); url = url.putAttribute(CONSUMER_URL_KEY, consumerUrl); List registryProtocolListeners = new ArrayList<>(); registryProtocolListeners.add(new CountRegistryProtocolListener()); ModuleModel moduleModel = Mockito.spy(ApplicationModel.defaultModel().getDefaultModule()); - moduleModel.getApplicationModel().getApplicationConfigManager().setApplication(new ApplicationConfig("application1")); + moduleModel + .getApplicationModel() + .getApplicationConfigManager() + .setApplication(new ApplicationConfig("application1")); ExtensionLoader extensionLoaderMock = mock(ExtensionLoader.class); - Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class)).thenReturn(extensionLoaderMock); + Mockito.when(moduleModel.getExtensionLoader(RegistryProtocolListener.class)) + .thenReturn(extensionLoaderMock); Mockito.when(extensionLoaderMock.getActivateExtension(url, REGISTRY_PROTOCOL_LISTENER_KEY)) - .thenReturn(registryProtocolListeners); + .thenReturn(registryProtocolListeners); url = url.setScopeModel(moduleModel); registryProtocol.interceptInvoker(clusterInvoker, url, consumerUrl); - Assertions.assertEquals(1, CountRegistryProtocolListener.getReferCounter().get()); + Assertions.assertEquals( + 1, CountRegistryProtocolListener.getReferCounter().get()); } /** @@ -479,7 +487,7 @@ class RegistryProtocolTest { CompositeConfiguration compositeConfiguration = mock(CompositeConfiguration.class); when(compositeConfiguration.convert(Boolean.class, ENABLE_CONFIGURATION_LISTEN, true)) - .thenReturn(true); + .thenReturn(true); Map parameters = new HashMap<>(); parameters.put(INTERFACE_KEY, DemoService.class.getName()); @@ -488,11 +496,8 @@ class RegistryProtocolTest { parameters.put(REGISTER_IP_KEY, "172.23.236.180"); Map attributes = new HashMap<>(); - ServiceConfigURL serviceConfigURL = new ServiceConfigURL("registry", - "127.0.0.1", - 2181, - "org.apache.dubbo.registry.RegistryService", - parameters); + ServiceConfigURL serviceConfigURL = new ServiceConfigURL( + "registry", "127.0.0.1", 2181, "org.apache.dubbo.registry.RegistryService", parameters); Map refer = new HashMap<>(); attributes.put(REFER_KEY, refer); attributes.put("key1", "value1"); @@ -502,7 +507,10 @@ class RegistryProtocolTest { Registry registry = mock(Registry.class); ModuleModel moduleModel = Mockito.spy(ApplicationModel.defaultModel().getDefaultModule()); - moduleModel.getApplicationModel().getApplicationConfigManager().setApplication(new ApplicationConfig("application1")); + moduleModel + .getApplicationModel() + .getApplicationConfigManager() + .setApplication(new ApplicationConfig("application1")); ExtensionLoader extensionLoaderMock = mock(ExtensionLoader.class); Mockito.when(moduleModel.getExtensionLoader(RegistryFactory.class)).thenReturn(extensionLoaderMock); Mockito.when(extensionLoaderMock.getAdaptiveExtension()).thenReturn(registryFactory); @@ -523,13 +531,16 @@ class RegistryProtocolTest { Map urlParameters = consumerUrl.getParameters(); URL urlToRegistry = new ServiceConfigURL( - urlParameters.get(PROTOCOL_KEY) == null ? CONSUMER : urlParameters.get(PROTOCOL_KEY), - urlParameters.remove(REGISTER_IP_KEY), 0, consumerUrl.getPath(), urlParameters); + urlParameters.get(PROTOCOL_KEY) == null ? CONSUMER : urlParameters.get(PROTOCOL_KEY), + urlParameters.remove(REGISTER_IP_KEY), + 0, + consumerUrl.getPath(), + urlParameters); - URL registeredConsumerUrl = urlToRegistry.addParameters(CATEGORY_KEY, CONSUMERS_CATEGORY, CHECK_KEY, - String.valueOf(false)).setScopeModel(moduleModel); + URL registeredConsumerUrl = urlToRegistry + .addParameters(CATEGORY_KEY, CONSUMERS_CATEGORY, CHECK_KEY, String.valueOf(false)) + .setScopeModel(moduleModel); - verify(registry,times(1)).register(registeredConsumerUrl); + verify(registry, times(1)).register(registeredConsumerUrl); } - } diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryFactoryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryFactoryTest.java index 436924531e..9ac6c8892e 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryFactoryTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryFactoryTest.java @@ -22,14 +22,14 @@ import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.Collection; +import java.util.List; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Collection; -import java.util.List; - /** * AbstractRegistryFactoryTest */ @@ -55,30 +55,24 @@ class AbstractRegistryFactoryTest { } @Override - public void destroy() { - } + public void destroy() {} @Override - public void register(URL url) { - } + public void register(URL url) {} @Override - public void unregister(URL url) { - } + public void unregister(URL url) {} @Override - public void subscribe(URL url, NotifyListener listener) { - } + public void subscribe(URL url, NotifyListener listener) {} @Override - public void unsubscribe(URL url, NotifyListener listener) { - } + public void unsubscribe(URL url, NotifyListener listener) {} @Override public List lookup(URL url) { return null; } - }; } }; @@ -103,30 +97,38 @@ class AbstractRegistryFactoryTest { */ // @Test public void testRegistryFactoryIpCache() { - Registry registry1 = registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":2233")); - Registry registry2 = registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostAddress() + ":2233")); + Registry registry1 = registryFactory.getRegistry( + URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":2233")); + Registry registry2 = registryFactory.getRegistry( + URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostAddress() + ":2233")); Assertions.assertEquals(registry1, registry2); } @Test void testRegistryFactoryGroupCache() { - Registry registry1 = registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":2233?group=aaa")); - Registry registry2 = registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":2233?group=bbb")); + Registry registry1 = + registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":2233?group=aaa")); + Registry registry2 = + registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":2233?group=bbb")); Assertions.assertNotSame(registry1, registry2); } @Test void testDestroyAllRegistries() { - Registry registry1 = registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":8888?group=xxx")); - Registry registry2 = registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":9999?group=yyy")); - Registry registry3 = new AbstractRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":2020?group=yyy")) { - @Override - public boolean isAvailable() { - return true; - } - }; + Registry registry1 = + registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":8888?group=xxx")); + Registry registry2 = + registryFactory.getRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":9999?group=yyy")); + Registry registry3 = + new AbstractRegistry(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":2020?group=yyy")) { + @Override + public boolean isAvailable() { + return true; + } + }; - RegistryManager registryManager = ApplicationModel.defaultModel().getBeanFactory().getBean(RegistryManager.class); + RegistryManager registryManager = + ApplicationModel.defaultModel().getBeanFactory().getBean(RegistryManager.class); Collection registries = registryManager.getRegistries(); Assertions.assertTrue(registries.contains(registry1)); diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryTest.java index 637df6ba5b..3eb4eb3dc7 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/AbstractRegistryTest.java @@ -20,13 +20,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.registry.NotifyListener; -import org.hamcrest.MatcherAssert; -import org.hamcrest.Matchers; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; @@ -35,6 +28,13 @@ import java.util.Objects; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; +import org.hamcrest.MatcherAssert; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; /** @@ -52,7 +52,7 @@ class AbstractRegistryTest { @BeforeEach public void init() { URL url = URL.valueOf("dubbo://192.168.0.2:2233"); - //sync update cache file + // sync update cache file url = url.addParameter("save.file", true); testUrl = URL.valueOf("http://192.168.0.3:9090/registry?check=false&file=N/A&interface=com.test"); mockUrl = new ServiceConfigURL("dubbo", "192.168.0.1", 2200); @@ -93,10 +93,10 @@ class AbstractRegistryTest { */ @Test void testRegister() { - //test one url + // test one url abstractRegistry.register(mockUrl); assert abstractRegistry.getRegistered().contains(mockUrl); - //test multiple urls + // test multiple urls for (URL url : abstractRegistry.getRegistered()) { abstractRegistry.unregister(url); } @@ -122,12 +122,13 @@ class AbstractRegistryTest { */ @Test void testUnregister() { - //test one unregister + // test one unregister URL url = new ServiceConfigURL("dubbo", "192.168.0.1", 2200); abstractRegistry.register(url); abstractRegistry.unregister(url); - MatcherAssert.assertThat(false, Matchers.equalTo(abstractRegistry.getRegistered().contains(url))); - //test multiple unregisters + MatcherAssert.assertThat( + false, Matchers.equalTo(abstractRegistry.getRegistered().contains(url))); + // test multiple unregisters for (URL u : abstractRegistry.getRegistered()) { abstractRegistry.unregister(u); } @@ -138,7 +139,8 @@ class AbstractRegistryTest { for (URL urlSub : urlList) { abstractRegistry.unregister(urlSub); } - MatcherAssert.assertThat(0, Matchers.equalTo(abstractRegistry.getRegistered().size())); + MatcherAssert.assertThat( + 0, Matchers.equalTo(abstractRegistry.getRegistered().size())); } @Test @@ -154,16 +156,18 @@ class AbstractRegistryTest { */ @Test void testSubscribeAndUnsubscribe() { - //test subscribe + // test subscribe final AtomicReference notified = new AtomicReference(false); NotifyListener listener = urls -> notified.set(Boolean.TRUE); URL url = new ServiceConfigURL("dubbo", "192.168.0.1", 2200); abstractRegistry.subscribe(url, listener); - Set subscribeListeners = abstractRegistry.getSubscribed().get(url); + Set subscribeListeners = + abstractRegistry.getSubscribed().get(url); MatcherAssert.assertThat(true, Matchers.equalTo(subscribeListeners.contains(listener))); - //test unsubscribe + // test unsubscribe abstractRegistry.unsubscribe(url, listener); - Set unsubscribeListeners = abstractRegistry.getSubscribed().get(url); + Set unsubscribeListeners = + abstractRegistry.getSubscribed().get(url); MatcherAssert.assertThat(false, Matchers.equalTo(unsubscribeListeners.contains(listener))); } @@ -287,7 +291,6 @@ class AbstractRegistryTest { Assertions.assertTrue(abstractRegistry.getRegistered().contains(testUrl)); Assertions.assertNotNull(abstractRegistry.getSubscribed().get(testUrl)); Assertions.assertTrue(abstractRegistry.getSubscribed().get(testUrl).contains(listener)); - } @Test @@ -400,7 +403,6 @@ class AbstractRegistryTest { }); } - /** * Test method for * {@link org.apache.dubbo.registry.support.AbstractRegistry#notify(URL, NotifyListener, List)}. @@ -471,10 +473,8 @@ class AbstractRegistryTest { // check if the output equals the input urls testUrls.add(testUrl); Assertions.assertEquals(AbstractRegistry.filterEmpty(testUrl, testUrls), testUrls); - } - @Test void lookupTest() { // loop up before registry @@ -492,7 +492,6 @@ class AbstractRegistryTest { abstractRegistry.notify(urls); List urlList2 = abstractRegistry.lookup(testUrl); Assertions.assertTrue(urlList2.contains(testUrl)); - } @Test @@ -546,7 +545,7 @@ class AbstractRegistryTest { abstractRegistry.notify(testUrl, listener, urls); Assertions.assertTrue(notifySuccess); List cacheUrl = abstractRegistry.getCacheUrls(testUrl); - Assertions.assertEquals(1,cacheUrl.size()); + Assertions.assertEquals(1, cacheUrl.size()); URL nullUrl = URL.valueOf("http://1.2.3.4:9090/registry?check=false&file=N/A&interface=com.testa"); cacheUrl = abstractRegistry.getCacheUrls(nullUrl); Assertions.assertTrue(Objects.isNull(cacheUrl)); diff --git a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/FailbackRegistryTest.java b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/FailbackRegistryTest.java index b63ae3f1e6..b3141fa9ec 100644 --- a/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/FailbackRegistryTest.java +++ b/dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/support/FailbackRegistryTest.java @@ -22,14 +22,14 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.registry.NotifyListener; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.Arrays; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL; import static org.apache.dubbo.registry.Constants.REGISTRY_RETRY_PERIOD_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -50,8 +50,10 @@ class FailbackRegistryTest { @BeforeEach public void setUp() throws Exception { String failedPeriod = String.valueOf(FAILED_PERIOD); - serviceUrl = URL.valueOf("remote://127.0.0.1/demoservice?method=get").addParameter(REGISTRY_RETRY_PERIOD_KEY, failedPeriod); - registryUrl = URL.valueOf("http://1.2.3.4:9090/registry?check=false&file=N/A").addParameter(REGISTRY_RETRY_PERIOD_KEY, failedPeriod); + serviceUrl = URL.valueOf("remote://127.0.0.1/demoservice?method=get") + .addParameter(REGISTRY_RETRY_PERIOD_KEY, failedPeriod); + registryUrl = URL.valueOf("http://1.2.3.4:9090/registry?check=false&file=N/A") + .addParameter(REGISTRY_RETRY_PERIOD_KEY, failedPeriod); } /** @@ -68,7 +70,8 @@ class FailbackRegistryTest { final CountDownLatch latch = new CountDownLatch(2); NotifyListener listener = urls -> notified.set(Boolean.TRUE); - URL subscribeUrl = serviceUrl.setProtocol(CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")); + URL subscribeUrl = + serviceUrl.setProtocol(CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")); registry = new MockRegistry(registryUrl, serviceUrl, latch); registry.setBad(true); registry.register(serviceUrl); @@ -76,7 +79,7 @@ class FailbackRegistryTest { registry.subscribe(subscribeUrl, listener); registry.unsubscribe(subscribeUrl, listener); - //Failure can not be called to listener. + // Failure can not be called to listener. assertEquals(false, notified.get()); assertEquals(2, latch.getCount()); @@ -84,20 +87,20 @@ class FailbackRegistryTest { for (int i = 0; i < 20; i++) { logger.info("failback registry retry, times:" + i); - //System.out.println(latch.getCount()); - if (latch.getCount() == 0) - break; + // System.out.println(latch.getCount()); + if (latch.getCount() == 0) break; Thread.sleep(sleepTime); } assertEquals(0, latch.getCount()); - //The failed subscribe corresponding key will be cleared when unsubscribing + // The failed subscribe corresponding key will be cleared when unsubscribing assertEquals(false, notified.get()); } @Test void testDoRetryRegister() throws Exception { - final CountDownLatch latch = new CountDownLatch(1);//All of them are called 4 times. A successful attempt to lose 1. subscribe will not be done + final CountDownLatch latch = new CountDownLatch( + 1); // All of them are called 4 times. A successful attempt to lose 1. subscribe will not be done registry = new MockRegistry(registryUrl, serviceUrl, latch); registry.setBad(true); @@ -107,8 +110,7 @@ class FailbackRegistryTest { for (int i = 0; i < tryTimes; i++) { System.out.println("failback registry retry ,times:" + i); - if (latch.getCount() == 0) - break; + if (latch.getCount() == 0) break; Thread.sleep(sleepTime); } assertEquals(0, latch.getCount()); @@ -118,14 +120,17 @@ class FailbackRegistryTest { void testDoRetrySubscribe() throws Exception { final AtomicReference notified = new AtomicReference(false); - final CountDownLatch latch = new CountDownLatch(1);//All of them are called 4 times. A successful attempt to lose 1. subscribe will not be done + final CountDownLatch latch = new CountDownLatch( + 1); // All of them are called 4 times. A successful attempt to lose 1. subscribe will not be done NotifyListener listener = urls -> notified.set(Boolean.TRUE); registry = new MockRegistry(registryUrl, serviceUrl, latch); registry.setBad(true); - registry.subscribe(serviceUrl.setProtocol(CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listener); + registry.subscribe( + serviceUrl.setProtocol(CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), + listener); - //Failure can not be called to listener. + // Failure can not be called to listener. assertEquals(false, notified.get()); assertEquals(1, latch.getCount()); @@ -133,12 +138,11 @@ class FailbackRegistryTest { for (int i = 0; i < tryTimes; i++) { System.out.println("failback registry retry ,times:" + i); - if (latch.getCount() == 0) - break; + if (latch.getCount() == 0) break; Thread.sleep(sleepTime); } assertEquals(0, latch.getCount()); - //The failed subscribe corresponding key will be cleared when unsubscribing + // The failed subscribe corresponding key will be cleared when unsubscribing assertEquals(true, notified.get()); } @@ -189,7 +193,6 @@ class FailbackRegistryTest { throw new RuntimeException("can not invoke!"); } latch.countDown(); - } @Override @@ -198,7 +201,6 @@ class FailbackRegistryTest { throw new RuntimeException("can not invoke!"); } latch.countDown(); - } @Override @@ -206,7 +208,7 @@ class FailbackRegistryTest { if (bad) { throw new RuntimeException("can not invoke!"); } - super.notify(url, listener, Arrays.asList(new URL[]{serviceUrl})); + super.notify(url, listener, Arrays.asList(new URL[] {serviceUrl})); latch.countDown(); } @@ -240,6 +242,5 @@ class FailbackRegistryTest { super.removeFailedSubscribedTask(url, listener); latch.countDown(); } - } } diff --git a/dubbo-registry/dubbo-registry-multicast/pom.xml b/dubbo-registry/dubbo-registry-multicast/pom.xml index 8e03ce51d4..6269d50fc2 100644 --- a/dubbo-registry/dubbo-registry-multicast/pom.xml +++ b/dubbo-registry/dubbo-registry-multicast/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-registry - ${revision} - ../pom.xml - - dubbo-registry-multicast - jar - ${project.artifactId} - The multicast registry module of dubbo project - - false - - - - org.apache.dubbo - dubbo-registry-api - ${project.parent.version} - - - \ No newline at end of file + 4.0.0 + + org.apache.dubbo + dubbo-registry + ${revision} + ../pom.xml + + dubbo-registry-multicast + jar + ${project.artifactId} + The multicast registry module of dubbo project + + false + + + + org.apache.dubbo + dubbo-registry-api + ${project.parent.version} + + + diff --git a/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java b/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java index 0bbdf57679..c5e386bb99 100644 --- a/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java +++ b/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistry.java @@ -84,7 +84,8 @@ public class MulticastRegistry extends FailbackRegistry { private final ConcurrentMap> received = new ConcurrentHashMap>(); - private final ScheduledExecutorService cleanExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("DubboMulticastRegistryCleanTimer", true)); + private final ScheduledExecutorService cleanExecutor = + Executors.newScheduledThreadPool(1, new NamedThreadFactory("DubboMulticastRegistryCleanTimer", true)); private final ScheduledFuture cleanFuture; @@ -108,26 +109,28 @@ public class MulticastRegistry extends FailbackRegistry { multicastPort = url.getPort() <= 0 ? DEFAULT_MULTICAST_PORT : url.getPort(); multicastSocket = new MulticastSocket(multicastPort); NetUtils.joinMulticastGroup(multicastSocket, multicastAddress); - Thread thread = new Thread(() -> { - byte[] buf = new byte[2048]; - DatagramPacket recv = new DatagramPacket(buf, buf.length); - while (!multicastSocket.isClosed()) { - try { - multicastSocket.receive(recv); - String msg = new String(recv.getData()).trim(); - int i = msg.indexOf('\n'); - if (i > 0) { - msg = msg.substring(0, i).trim(); + Thread thread = new Thread( + () -> { + byte[] buf = new byte[2048]; + DatagramPacket recv = new DatagramPacket(buf, buf.length); + while (!multicastSocket.isClosed()) { + try { + multicastSocket.receive(recv); + String msg = new String(recv.getData()).trim(); + int i = msg.indexOf('\n'); + if (i > 0) { + msg = msg.substring(0, i).trim(); + } + MulticastRegistry.this.receive(msg, (InetSocketAddress) recv.getSocketAddress()); + Arrays.fill(buf, (byte) 0); + } catch (Throwable e) { + if (!multicastSocket.isClosed()) { + logger.error(REGISTRY_SOCKET_EXCEPTION, "", "", e.getMessage(), e); + } + } } - MulticastRegistry.this.receive(msg, (InetSocketAddress) recv.getSocketAddress()); - Arrays.fill(buf, (byte) 0); - } catch (Throwable e) { - if (!multicastSocket.isClosed()) { - logger.error(REGISTRY_SOCKET_EXCEPTION, "", "", e.getMessage(), e); - } - } - } - }, "DubboMulticastRegistryReceiver"); + }, + "DubboMulticastRegistryReceiver"); thread.setDaemon(true); thread.start(); } catch (IOException e) { @@ -135,13 +138,22 @@ public class MulticastRegistry extends FailbackRegistry { } this.cleanPeriod = url.getParameter(SESSION_TIMEOUT_KEY, DEFAULT_SESSION_TIMEOUT); if (url.getParameter("clean", true)) { - this.cleanFuture = cleanExecutor.scheduleWithFixedDelay(() -> { - try { - clean(); // Remove the expired - } catch (Throwable t) { // Defensive fault tolerance - logger.error(REGISTRY_SOCKET_EXCEPTION, "", "", "Unexpected exception occur at clean expired provider, cause: " + t.getMessage(), t); - } - }, cleanPeriod, cleanPeriod, TimeUnit.MILLISECONDS); + this.cleanFuture = cleanExecutor.scheduleWithFixedDelay( + () -> { + try { + clean(); // Remove the expired + } catch (Throwable t) { // Defensive fault tolerance + logger.error( + REGISTRY_SOCKET_EXCEPTION, + "", + "", + "Unexpected exception occur at clean expired provider, cause: " + t.getMessage(), + t); + } + }, + cleanPeriod, + cleanPeriod, + TimeUnit.MILLISECONDS); } else { this.cleanFuture = null; } @@ -151,11 +163,11 @@ public class MulticastRegistry extends FailbackRegistry { if (!multicastAddress.isMulticastAddress()) { String message = "Invalid multicast address " + multicastAddress; if (multicastAddress instanceof Inet4Address) { - throw new IllegalArgumentException(message + ", " + - "ipv4 multicast address scope: 224.0.0.0 - 239.255.255.255."); + throw new IllegalArgumentException( + message + ", " + "ipv4 multicast address scope: 224.0.0.0 - 239.255.255.255."); } else { - throw new IllegalArgumentException(message + ", " + "ipv6 multicast address must start with ff, " + - "for example: ff01::1"); + throw new IllegalArgumentException( + message + ", " + "ipv6 multicast address must start with ff, " + "for example: ff01::1"); } } } @@ -179,7 +191,11 @@ public class MulticastRegistry extends FailbackRegistry { } private boolean isExpired(URL url) { - if (!url.getParameter(DYNAMIC_KEY, true) || url.getPort() <= 0 || CONSUMER_PROTOCOL.equals(url.getProtocol()) || ROUTE_PROTOCOL.equals(url.getProtocol()) || OVERRIDE_PROTOCOL.equals(url.getProtocol())) { + if (!url.getParameter(DYNAMIC_KEY, true) + || url.getPort() <= 0 + || CONSUMER_PROTOCOL.equals(url.getProtocol()) + || ROUTE_PROTOCOL.equals(url.getProtocol()) + || OVERRIDE_PROTOCOL.equals(url.getProtocol())) { return false; } try (Socket socket = new Socket(url.getHost(), url.getPort())) { @@ -212,9 +228,14 @@ public class MulticastRegistry extends FailbackRegistry { if (CollectionUtils.isNotEmpty(urls)) { for (URL u : urls) { if (UrlUtils.isMatch(url, u)) { - String host = remoteAddress != null && remoteAddress.getAddress() != null ? remoteAddress.getAddress().getHostAddress() : url.getIp(); + String host = remoteAddress != null && remoteAddress.getAddress() != null + ? remoteAddress.getAddress().getHostAddress() + : url.getIp(); if (url.getParameter("unicast", true) // Whether the consumer's machine has only one process - && !NetUtils.getLocalHost().equals(host)) { // Multiple processes in the same machine cannot be unicast with unicast or there will be only one process receiving information + && !NetUtils.getLocalHost() + .equals(host)) { // Multiple processes in the same machine cannot be unicast + // with unicast or there will be only one process receiving + // information unicast(REGISTER + " " + u.toFullString(), host); } else { multicast(REGISTER + " " + u.toFullString()); @@ -222,8 +243,8 @@ public class MulticastRegistry extends FailbackRegistry { } } } - }/* else if (msg.startsWith(UNSUBSCRIBE)) { - }*/ + } /* else if (msg.startsWith(UNSUBSCRIBE)) { + }*/ } private void multicast(String msg) { @@ -429,5 +450,4 @@ public class MulticastRegistry extends FailbackRegistry { public Map> getReceived() { return received; } - } diff --git a/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistryFactory.java b/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistryFactory.java index de3d64e27c..2ce2920d56 100644 --- a/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastRegistryFactory.java @@ -30,5 +30,4 @@ public class MulticastRegistryFactory extends AbstractRegistryFactory { public Registry createRegistry(URL url) { return new MulticastRegistry(url, applicationModel); } - } diff --git a/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastServiceDiscovery.java b/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastServiceDiscovery.java index 012caf8e8b..40c9376f67 100644 --- a/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-multicast/src/main/java/org/apache/dubbo/registry/multicast/MulticastServiceDiscovery.java @@ -16,15 +16,15 @@ */ package org.apache.dubbo.registry.multicast; -import java.util.Collections; -import java.util.List; -import java.util.Set; - import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.client.AbstractServiceDiscovery; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.Collections; +import java.util.List; +import java.util.Set; + /** * TODO: make multicast protocol support Service Discovery */ @@ -38,17 +38,14 @@ public class MulticastServiceDiscovery extends AbstractServiceDiscovery { } @Override - public void doDestroy() throws Exception { - - } + public void doDestroy() throws Exception {} @Override - public void doRegister(ServiceInstance serviceInstance) throws RuntimeException { - } + public void doRegister(ServiceInstance serviceInstance) throws RuntimeException {} @Override - public void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance) throws RuntimeException { - } + public void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance) + throws RuntimeException {} @Override public void doUnregister(ServiceInstance serviceInstance) throws RuntimeException { @@ -69,5 +66,4 @@ public class MulticastServiceDiscovery extends AbstractServiceDiscovery { public URL getUrl() { return registryURL; } - } diff --git a/dubbo-registry/dubbo-registry-multicast/src/test/java/org/apache/dubbo/registry/multicast/MulticastRegistryTest.java b/dubbo-registry/dubbo-registry-multicast/src/test/java/org/apache/dubbo/registry/multicast/MulticastRegistryTest.java index fde87af605..582a3b2ee9 100644 --- a/dubbo-registry/dubbo-registry-multicast/src/test/java/org/apache/dubbo/registry/multicast/MulticastRegistryTest.java +++ b/dubbo-registry/dubbo-registry-multicast/src/test/java/org/apache/dubbo/registry/multicast/MulticastRegistryTest.java @@ -20,10 +20,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.registry.NotifyListener; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.net.InetAddress; import java.net.MulticastSocket; import java.net.UnknownHostException; @@ -32,6 +28,10 @@ import java.util.Map; import java.util.Random; import java.util.Set; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -43,8 +43,7 @@ class MulticastRegistryTest { private String service = "org.apache.dubbo.test.injvmServie"; private URL registryUrl = URL.valueOf("multicast://239.239.239.239/"); - private URL serviceUrl = URL.valueOf("dubbo://" + NetUtils.getLocalHost() + "/" + service - + "?methods=test1,test2"); + private URL serviceUrl = URL.valueOf("dubbo://" + NetUtils.getLocalHost() + "/" + service + "?methods=test1,test2"); private URL adminUrl = URL.valueOf("dubbo://" + NetUtils.getLocalHost() + "/*"); private URL consumerUrl = URL.valueOf("subscribe://" + NetUtils.getLocalHost() + "/" + service + "?arg1=1&arg2=2"); private MulticastRegistry registry = new MulticastRegistry(registryUrl); @@ -269,7 +268,5 @@ class MulticastRegistryTest { multicastSocket.close(); } } - } - } diff --git a/dubbo-registry/dubbo-registry-multiple/pom.xml b/dubbo-registry/dubbo-registry-multiple/pom.xml index 6719cdf2b8..012288a5a5 100644 --- a/dubbo-registry/dubbo-registry-multiple/pom.xml +++ b/dubbo-registry/dubbo-registry-multiple/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-registry - ${revision} - ../pom.xml - - dubbo-registry-multiple - jar - ${project.artifactId} - The multiple registry module of dubbo project - - false - - - - org.apache.dubbo - dubbo-registry-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.parent.version} - test - - - org.apache.commons - commons-lang3 - test - - - org.apache.dubbo - dubbo-test-common - ${project.parent.version} - test - + 4.0.0 + + org.apache.dubbo + dubbo-registry + ${revision} + ../pom.xml + + dubbo-registry-multiple + jar + ${project.artifactId} + The multiple registry module of dubbo project + + false + + + + org.apache.dubbo + dubbo-registry-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.parent.version} + test + + + org.apache.commons + commons-lang3 + test + + + org.apache.dubbo + dubbo-test-common + ${project.parent.version} + test + - - org.apache.curator - curator-framework - test - - - org.apache.curator - curator-recipes - test - - - org.apache.zookeeper - zookeeper - test - - + + org.apache.curator + curator-framework + test + + + org.apache.curator + curator-recipes + test + + + org.apache.zookeeper + zookeeper + test + + diff --git a/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistry.java b/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistry.java index 7a24a40779..82f9bbef5f 100644 --- a/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistry.java +++ b/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistry.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.registry.multiple; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.Logger; @@ -52,7 +51,8 @@ public class MultipleRegistry extends AbstractRegistry { public static final String REGISTRY_SEPARATOR = "separator"; private final Map serviceRegistries = new ConcurrentHashMap<>(4); private final Map referenceRegistries = new ConcurrentHashMap<>(4); - private final Map multipleNotifyListenerMap = new ConcurrentHashMap<>(32); + private final Map multipleNotifyListenerMap = + new ConcurrentHashMap<>(32); private final URL registryUrl; private final String applicationName; protected RegistryFactory registryFactory; @@ -63,12 +63,14 @@ public class MultipleRegistry extends AbstractRegistry { public MultipleRegistry(URL url) { this(url, true, true); - this.registryFactory = url.getOrDefaultApplicationModel().getExtensionLoader(RegistryFactory.class).getAdaptiveExtension(); + this.registryFactory = url.getOrDefaultApplicationModel() + .getExtensionLoader(RegistryFactory.class) + .getAdaptiveExtension(); boolean defaultRegistry = url.getParameter(CommonConstants.DEFAULT_KEY, true); if (defaultRegistry && effectServiceRegistryURLs.isEmpty() && effectReferenceRegistryURLs.isEmpty()) { - throw new IllegalArgumentException("Illegal registry url. You need to configure parameter " + - REGISTRY_FOR_SERVICE + " or " + REGISTRY_FOR_REFERENCE); + throw new IllegalArgumentException("Illegal registry url. You need to configure parameter " + + REGISTRY_FOR_SERVICE + " or " + REGISTRY_FOR_REFERENCE); } } @@ -76,7 +78,9 @@ public class MultipleRegistry extends AbstractRegistry { super(url); this.registryUrl = url; this.applicationName = url.getApplication(); - this.registryFactory = url.getOrDefaultApplicationModel().getExtensionLoader(RegistryFactory.class).getAdaptiveExtension(); + this.registryFactory = url.getOrDefaultApplicationModel() + .getExtensionLoader(RegistryFactory.class) + .getAdaptiveExtension(); init(); checkApplicationName(this.applicationName); @@ -101,7 +105,9 @@ public class MultipleRegistry extends AbstractRegistry { serviceRegistries.put(tmpUrl, registryMap.get(tmpUrl)); continue; } - final URL registryUrl = URL.valueOf(tmpUrl).addParametersIfAbsent(url.getParameters()).addParameterIfAbsent(CHECK_KEY, url.getParameter(CHECK_KEY, "true")); + final URL registryUrl = URL.valueOf(tmpUrl) + .addParametersIfAbsent(url.getParameters()) + .addParameterIfAbsent(CHECK_KEY, url.getParameter(CHECK_KEY, "true")); Registry registry = registryFactory.getRegistry(registryUrl); registryMap.put(tmpUrl, registry); serviceRegistries.put(tmpUrl, registry); @@ -118,14 +124,14 @@ public class MultipleRegistry extends AbstractRegistry { referenceRegistries.put(tmpUrl, registryMap.get(tmpUrl)); continue; } - final URL registryUrl = URL.valueOf(tmpUrl).addParameterIfAbsent(CHECK_KEY, url.getParameter(CHECK_KEY, "true")); + final URL registryUrl = + URL.valueOf(tmpUrl).addParameterIfAbsent(CHECK_KEY, url.getParameter(CHECK_KEY, "true")); Registry registry = registryFactory.getRegistry(registryUrl); registryMap.put(tmpUrl, registry); referenceRegistries.put(tmpUrl, registry); } } - @Override public URL getUrl() { return registryUrl; @@ -185,7 +191,8 @@ public class MultipleRegistry extends AbstractRegistry { MultipleNotifyListenerWrapper multipleNotifyListenerWrapper = new MultipleNotifyListenerWrapper(listener); multipleNotifyListenerMap.put(listener, multipleNotifyListenerWrapper); for (Registry registry : referenceRegistries.values()) { - SingleNotifyListener singleNotifyListener = new SingleNotifyListener(multipleNotifyListenerWrapper, registry); + SingleNotifyListener singleNotifyListener = + new SingleNotifyListener(multipleNotifyListenerWrapper, registry); multipleNotifyListenerWrapper.putRegistryMap(registry.getUrl(), singleNotifyListener); registry.subscribe(url, singleNotifyListener); } @@ -218,8 +225,7 @@ public class MultipleRegistry extends AbstractRegistry { return urls.stream().distinct().collect(Collectors.toList()); } - protected void init() { - } + protected void init() {} protected List filterServiceRegistry(List serviceRegistryURLs) { return serviceRegistryURLs; @@ -229,9 +235,7 @@ public class MultipleRegistry extends AbstractRegistry { return referenceRegistryURLs; } - - protected void checkApplicationName(String applicationName) { - } + protected void checkApplicationName(String applicationName) {} protected String getApplicationName() { return applicationName; @@ -294,8 +298,8 @@ public class MultipleRegistry extends AbstractRegistry { } // empty protocol if (tmpUrls.size() == 1 - && tmpUrls.get(0) != null - && EMPTY_PROTOCOL.equals(tmpUrls.get(0).getProtocol())) { + && tmpUrls.get(0) != null + && EMPTY_PROTOCOL.equals(tmpUrls.get(0).getProtocol())) { // if only one empty if (emptyURL == null) { emptyURL = tmpUrls.get(0); @@ -328,16 +332,17 @@ public class MultipleRegistry extends AbstractRegistry { public static void aggregateRegistryUrls(List notifyURLs, List singleURLs, URL registryURL) { String registryAttachments = registryURL.getParameter("attachments"); if (StringUtils.isNotBlank(registryAttachments)) { - LOGGER.info("Registry attachments " + registryAttachments + " found, will append to provider urls, urls size " + singleURLs.size()); + LOGGER.info("Registry attachments " + registryAttachments + + " found, will append to provider urls, urls size " + singleURLs.size()); String[] pairs = registryAttachments.split(COMMA_SEPARATOR); Map attachments = new HashMap<>(pairs.length); for (String rawPair : pairs) { - String[] keyValuePair = rawPair.split("="); - if (keyValuePair.length == 2) { - String key = keyValuePair[0]; - String value = keyValuePair[1]; - attachments.put(key, value); - } + String[] keyValuePair = rawPair.split("="); + if (keyValuePair.length == 2) { + String key = keyValuePair[0]; + String value = keyValuePair[1]; + attachments.put(key, value); + } } for (URL tmpUrl : singleURLs) { @@ -393,7 +398,5 @@ public class MultipleRegistry extends AbstractRegistry { public Registry getRegistry() { return registry; } - - } } diff --git a/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistryFactory.java b/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistryFactory.java index 69d695b235..3f92856c34 100644 --- a/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleRegistryFactory.java @@ -29,5 +29,4 @@ public class MultipleRegistryFactory extends AbstractRegistryFactory { protected Registry createRegistry(URL url) { return new MultipleRegistry(url); } - } diff --git a/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleServiceDiscovery.java b/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleServiceDiscovery.java index d675b74cce..1c44f41e3e 100644 --- a/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-multiple/src/main/java/org/apache/dubbo/registry/multiple/MultipleServiceDiscovery.java @@ -53,9 +53,11 @@ public class MultipleServiceDiscovery implements ServiceDiscovery { Map parameters = registryURL.getParameters(); for (String key : parameters.keySet()) { if (key.startsWith(REGISTRY_PREFIX_KEY)) { - URL url = URL.valueOf(registryURL.getParameter(key)).addParameter(CommonConstants.APPLICATION_KEY, applicationName) - .addParameter(REGISTRY_TYPE, SERVICE); - ServiceDiscovery serviceDiscovery = ServiceDiscoveryFactory.getExtension(url).getServiceDiscovery(url); + URL url = URL.valueOf(registryURL.getParameter(key)) + .addParameter(CommonConstants.APPLICATION_KEY, applicationName) + .addParameter(REGISTRY_TYPE, SERVICE); + ServiceDiscovery serviceDiscovery = + ServiceDiscoveryFactory.getExtension(url).getServiceDiscovery(url); serviceDiscoveries.put(key, serviceDiscovery); } } @@ -96,13 +98,15 @@ public class MultipleServiceDiscovery implements ServiceDiscovery { @Override public void addServiceInstancesChangedListener(ServiceInstancesChangedListener listener) - throws NullPointerException, IllegalArgumentException { + throws NullPointerException, IllegalArgumentException { MultiServiceInstancesChangedListener multiListener = (MultiServiceInstancesChangedListener) listener; for (String registryKey : serviceDiscoveries.keySet()) { ServiceDiscovery serviceDiscovery = serviceDiscoveries.get(registryKey); - SingleServiceInstancesChangedListener singleListener = multiListener.getAndComputeIfAbsent(registryKey, k -> - new SingleServiceInstancesChangedListener(listener.getServiceNames(), serviceDiscovery, multiListener)); + SingleServiceInstancesChangedListener singleListener = multiListener.getAndComputeIfAbsent( + registryKey, + k -> new SingleServiceInstancesChangedListener( + listener.getServiceNames(), serviceDiscovery, multiListener)); serviceDiscovery.addServiceInstancesChangedListener(singleListener); } } @@ -137,7 +141,8 @@ public class MultipleServiceDiscovery implements ServiceDiscovery { @Override public MetadataInfo getLocalMetadata() { - throw new UnsupportedOperationException("Multiple registry implementation does not support getMetadata() method."); + throw new UnsupportedOperationException( + "Multiple registry implementation does not support getMetadata() method."); } @Override @@ -155,7 +160,8 @@ public class MultipleServiceDiscovery implements ServiceDiscovery { @Override public MetadataInfo getRemoteMetadata(String revision) { - throw new UnsupportedOperationException("Multiple registry implementation does not support getMetadata() method."); + throw new UnsupportedOperationException( + "Multiple registry implementation does not support getMetadata() method."); } @Override @@ -224,8 +230,8 @@ public class MultipleServiceDiscovery implements ServiceDiscovery { singleListenerMap.put(registryKey, singleListener); } - public SingleServiceInstancesChangedListener getAndComputeIfAbsent(String registryKey, - Function func) { + public SingleServiceInstancesChangedListener getAndComputeIfAbsent( + String registryKey, Function func) { return ConcurrentHashMapUtils.computeIfAbsent(singleListenerMap, registryKey, func); } } @@ -234,8 +240,10 @@ public class MultipleServiceDiscovery implements ServiceDiscovery { private final MultiServiceInstancesChangedListener multiListener; volatile ServiceInstancesChangedEvent event; - public SingleServiceInstancesChangedListener(Set serviceNames, ServiceDiscovery serviceDiscovery, - MultiServiceInstancesChangedListener multiListener) { + public SingleServiceInstancesChangedListener( + Set serviceNames, + ServiceDiscovery serviceDiscovery, + MultiServiceInstancesChangedListener multiListener) { super(serviceNames, serviceDiscovery); this.multiListener = multiListener; } diff --git a/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistry2S2RTest.java b/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistry2S2RTest.java index a91df2ad42..cb83155ff7 100644 --- a/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistry2S2RTest.java +++ b/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistry2S2RTest.java @@ -23,14 +23,14 @@ import org.apache.dubbo.registry.zookeeper.ZookeeperRegistry; import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; import org.apache.dubbo.remoting.zookeeper.curator5.Curator5ZookeeperClient; +import java.util.ArrayList; +import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import java.util.ArrayList; -import java.util.List; - /** * 2019-04-30 */ @@ -47,7 +47,6 @@ class MultipleRegistry2S2RTest { private static ZookeeperRegistry zookeeperRegistry; private static ZookeeperRegistry zookeeperRegistry2; - private static String zookeeperConnectionAddress1, zookeeperConnectionAddress2; @BeforeAll @@ -55,16 +54,20 @@ class MultipleRegistry2S2RTest { zookeeperConnectionAddress1 = System.getProperty("zookeeper.connection.address.1"); zookeeperConnectionAddress2 = System.getProperty("zookeeper.connection.address.2"); - URL url = URL.valueOf("multiple://127.0.0.1?application=vic&enable-empty-protection=false&" + - MultipleRegistry.REGISTRY_FOR_SERVICE + "=" + zookeeperConnectionAddress1 + "," + zookeeperConnectionAddress2 + "&" - + MultipleRegistry.REGISTRY_FOR_REFERENCE + "=" + zookeeperConnectionAddress1 + "," + zookeeperConnectionAddress2); + URL url = URL.valueOf("multiple://127.0.0.1?application=vic&enable-empty-protection=false&" + + MultipleRegistry.REGISTRY_FOR_SERVICE + + "=" + zookeeperConnectionAddress1 + "," + zookeeperConnectionAddress2 + "&" + + MultipleRegistry.REGISTRY_FOR_REFERENCE + "=" + zookeeperConnectionAddress1 + "," + + zookeeperConnectionAddress2); multipleRegistry = (MultipleRegistry) new MultipleRegistryFactory().createRegistry(url); // for test validation zookeeperClient = new Curator5ZookeeperClient(URL.valueOf(zookeeperConnectionAddress1)); - zookeeperRegistry = MultipleRegistryTestUtil.getZookeeperRegistry(multipleRegistry.getServiceRegistries().values()); + zookeeperRegistry = MultipleRegistryTestUtil.getZookeeperRegistry( + multipleRegistry.getServiceRegistries().values()); zookeeperClient2 = new Curator5ZookeeperClient(URL.valueOf(zookeeperConnectionAddress2)); - zookeeperRegistry2 = MultipleRegistryTestUtil.getZookeeperRegistry(multipleRegistry.getServiceRegistries().values()); + zookeeperRegistry2 = MultipleRegistryTestUtil.getZookeeperRegistry( + multipleRegistry.getServiceRegistries().values()); } @Test @@ -88,18 +91,28 @@ class MultipleRegistry2S2RTest { Assertions.assertTrue(multipleRegistry.getServiceRegistries().containsKey(zookeeperConnectionAddress1)); Assertions.assertTrue(multipleRegistry.getServiceRegistries().containsKey(zookeeperConnectionAddress2)); - Assertions.assertEquals(2, multipleRegistry.getServiceRegistries().values().size()); -// java.util.Iterator registryIterable = multipleRegistry.getServiceRegistries().values().iterator(); -// Registry firstRegistry = registryIterable.next(); -// Registry secondRegistry = registryIterable.next(); - Assertions.assertNotNull(MultipleRegistryTestUtil.getZookeeperRegistry(multipleRegistry.getServiceRegistries().values())); - Assertions.assertNotNull(MultipleRegistryTestUtil.getZookeeperRegistry(multipleRegistry.getReferenceRegistries().values())); + Assertions.assertEquals( + 2, multipleRegistry.getServiceRegistries().values().size()); + // java.util.Iterator registryIterable = + // multipleRegistry.getServiceRegistries().values().iterator(); + // Registry firstRegistry = registryIterable.next(); + // Registry secondRegistry = registryIterable.next(); + Assertions.assertNotNull(MultipleRegistryTestUtil.getZookeeperRegistry( + multipleRegistry.getServiceRegistries().values())); + Assertions.assertNotNull(MultipleRegistryTestUtil.getZookeeperRegistry( + multipleRegistry.getReferenceRegistries().values())); - Assertions.assertEquals(MultipleRegistryTestUtil.getZookeeperRegistry(multipleRegistry.getServiceRegistries().values()), - MultipleRegistryTestUtil.getZookeeperRegistry(multipleRegistry.getReferenceRegistries().values())); + Assertions.assertEquals( + MultipleRegistryTestUtil.getZookeeperRegistry( + multipleRegistry.getServiceRegistries().values()), + MultipleRegistryTestUtil.getZookeeperRegistry( + multipleRegistry.getReferenceRegistries().values())); - Assertions.assertEquals(MultipleRegistryTestUtil.getZookeeperRegistry(multipleRegistry.getServiceRegistries().values()), - MultipleRegistryTestUtil.getZookeeperRegistry(multipleRegistry.getReferenceRegistries().values())); + Assertions.assertEquals( + MultipleRegistryTestUtil.getZookeeperRegistry( + multipleRegistry.getServiceRegistries().values()), + MultipleRegistryTestUtil.getZookeeperRegistry( + multipleRegistry.getReferenceRegistries().values())); Assertions.assertEquals(multipleRegistry.getApplicationName(), "vic"); @@ -108,8 +121,10 @@ class MultipleRegistry2S2RTest { @Test void testRegistryAndUnRegistry() throws InterruptedException { - URL serviceUrl = URL.valueOf("http2://multiple/" + SERVICE_NAME + "?notify=false&methods=test1,test2&category=providers"); -// URL serviceUrl2 = URL.valueOf("http2://multiple2/" + SERVICE_NAME + "?notify=false&methods=test1,test2&category=providers"); + URL serviceUrl = URL.valueOf( + "http2://multiple/" + SERVICE_NAME + "?notify=false&methods=test1,test2&category=providers"); + // URL serviceUrl2 = URL.valueOf("http2://multiple2/" + SERVICE_NAME + + // "?notify=false&methods=test1,test2&category=providers"); multipleRegistry.register(serviceUrl); String path = "/dubbo/" + SERVICE_NAME + "/providers"; @@ -139,8 +154,10 @@ class MultipleRegistry2S2RTest { @Test void testSubscription() throws InterruptedException { - URL serviceUrl = URL.valueOf("http2://multiple/" + SERVICE2_NAME + "?notify=false&methods=test1,test2&category=providers"); -// URL serviceUrl2 = URL.valueOf("http2://multiple2/" + SERVICE_NAME + "?notify=false&methods=test1,test2&category=providers"); + URL serviceUrl = URL.valueOf( + "http2://multiple/" + SERVICE2_NAME + "?notify=false&methods=test1,test2&category=providers"); + // URL serviceUrl2 = URL.valueOf("http2://multiple2/" + SERVICE_NAME + + // "?notify=false&methods=test1,test2&category=providers"); multipleRegistry.register(serviceUrl); String path = "/dubbo/" + SERVICE2_NAME + "/providers"; @@ -159,7 +176,8 @@ class MultipleRegistry2S2RTest { Thread.sleep(1500); Assertions.assertEquals(2, list.size()); - List serviceRegistries = new ArrayList(multipleRegistry.getServiceRegistries().values()); + List serviceRegistries = + new ArrayList(multipleRegistry.getServiceRegistries().values()); serviceRegistries.get(0).unregister(serviceUrl); Thread.sleep(1500); Assertions.assertEquals(1, list.size()); @@ -179,12 +197,13 @@ class MultipleRegistry2S2RTest { void testAggregation() { List result = new ArrayList(); List listToAggregate = new ArrayList(); - URL url1= URL.valueOf("dubbo://127.0.0.1:20880/service1"); - URL url2= URL.valueOf("dubbo://127.0.0.1:20880/service1"); + URL url1 = URL.valueOf("dubbo://127.0.0.1:20880/service1"); + URL url2 = URL.valueOf("dubbo://127.0.0.1:20880/service1"); listToAggregate.add(url1); listToAggregate.add(url2); - URL registryURL = URL.valueOf("mock://127.0.0.1/RegistryService?attachments=zone=hangzhou,tag=middleware&enable-empty-protection=false"); + URL registryURL = URL.valueOf( + "mock://127.0.0.1/RegistryService?attachments=zone=hangzhou,tag=middleware&enable-empty-protection=false"); MultipleRegistry.MultipleNotifyListenerWrapper.aggregateRegistryUrls(result, listToAggregate, registryURL); @@ -193,5 +212,4 @@ class MultipleRegistry2S2RTest { Assertions.assertEquals("hangzhou", result.get(0).getParameter("zone")); Assertions.assertEquals("middleware", result.get(1).getParameter("tag")); } - } diff --git a/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistryTestUtil.java b/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistryTestUtil.java index 5f5adfadd6..c69d39b0a5 100644 --- a/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistryTestUtil.java +++ b/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleRegistryTestUtil.java @@ -80,15 +80,15 @@ public class MultipleRegistryTestUtil { // providers List providerURLs = categoryUrls.getOrDefault(PROVIDERS_CATEGORY, Collections.emptyList()); return providerURLs; - } private static boolean isValidCategory(URL url) { String category = url.getCategory(DEFAULT_CATEGORY); - if ((ROUTERS_CATEGORY.equals(category) || ROUTE_PROTOCOL.equals(url.getProtocol())) || - PROVIDERS_CATEGORY.equals(category) || - CONFIGURATORS_CATEGORY.equals(category) || DYNAMIC_CONFIGURATORS_CATEGORY.equals(category) || - APP_DYNAMIC_CONFIGURATORS_CATEGORY.equals(category)) { + if ((ROUTERS_CATEGORY.equals(category) || ROUTE_PROTOCOL.equals(url.getProtocol())) + || PROVIDERS_CATEGORY.equals(category) + || CONFIGURATORS_CATEGORY.equals(category) + || DYNAMIC_CONFIGURATORS_CATEGORY.equals(category) + || APP_DYNAMIC_CONFIGURATORS_CATEGORY.equals(category)) { return true; } return false; diff --git a/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleServiceDiscoveryTest.java b/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleServiceDiscoveryTest.java index 9d0786a77b..359d8a5d0c 100644 --- a/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleServiceDiscoveryTest.java +++ b/dubbo-registry/dubbo-registry-multiple/src/test/java/org/apache/dubbo/registry/multiple/MultipleServiceDiscoveryTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.registry.multiple; -import com.google.common.collect.Sets; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.CollectionUtils; @@ -30,8 +29,6 @@ import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent; import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; import java.lang.reflect.Field; import java.util.ArrayList; @@ -40,6 +37,10 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import com.google.common.collect.Sets; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY; import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.EXPORTED_SERVICES_REVISION_PROPERTY_NAME; @@ -54,12 +55,13 @@ public class MultipleServiceDiscoveryTest { public void testOnEvent() { try { String metadata_111 = "{\"app\":\"app1\",\"revision\":\"111\",\"services\":{" - + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app1\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" - + "}}"; + + "\"org.apache.dubbo.demo.DemoService:dubbo\":{\"name\":\"org.apache.dubbo.demo.DemoService\",\"protocol\":\"dubbo\",\"path\":\"org.apache.dubbo.demo.DemoService\",\"params\":{\"side\":\"provider\",\"release\":\"\",\"methods\":\"sayHello,sayHelloAsync\",\"deprecated\":\"false\",\"dubbo\":\"2.0.2\",\"pid\":\"72723\",\"interface\":\"org.apache.dubbo.demo.DemoService\",\"service-name-mapping\":\"true\",\"timeout\":\"3000\",\"generic\":\"false\",\"metadata-type\":\"remote\",\"delay\":\"5000\",\"application\":\"app1\",\"dynamic\":\"true\",\"REGISTRY_CLUSTER\":\"registry1\",\"anyhost\":\"true\",\"timestamp\":\"1625800233446\"}}" + + "}}"; MetadataInfo metadataInfo = JsonUtils.toJavaObject(metadata_111, MetadataInfo.class); ApplicationModel applicationModel = ApplicationModel.defaultModel(); applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("app2")); - zookeeperConnectionAddress1 = "multiple://127.0.0.1:2181?reference-registry=127.0.0.1:2181?enableEmptyProtection=false&child.a1=zookeeper://127.0.0.1:2181"; + zookeeperConnectionAddress1 = + "multiple://127.0.0.1:2181?reference-registry=127.0.0.1:2181?enableEmptyProtection=false&child.a1=zookeeper://127.0.0.1:2181"; List urlsSameRevision = new ArrayList<>(); urlsSameRevision.add("127.0.0.1:20880?revision=111"); urlsSameRevision.add("127.0.0.2:20880?revision=111"); @@ -71,18 +73,28 @@ public class MultipleServiceDiscoveryTest { Field serviceDiscoveries = multipleServiceDiscoveryClass.getDeclaredField("serviceDiscoveries"); serviceDiscoveries.setAccessible(true); ServiceDiscovery serviceDiscoveryMock = Mockito.mock(ServiceDiscovery.class); - Mockito.when(serviceDiscoveryMock.getRemoteMetadata(Mockito.anyString(), Mockito.anyList())).thenReturn(metadataInfo); - serviceDiscoveries.set(multipleServiceDiscovery, Collections.singletonMap("child.a1", serviceDiscoveryMock)); - MultipleServiceDiscovery.MultiServiceInstancesChangedListener listener = (MultipleServiceDiscovery.MultiServiceInstancesChangedListener) multipleServiceDiscovery.createListener(Sets.newHashSet("app1")); + Mockito.when(serviceDiscoveryMock.getRemoteMetadata(Mockito.anyString(), Mockito.anyList())) + .thenReturn(metadataInfo); + serviceDiscoveries.set( + multipleServiceDiscovery, Collections.singletonMap("child.a1", serviceDiscoveryMock)); + MultipleServiceDiscovery.MultiServiceInstancesChangedListener listener = + (MultipleServiceDiscovery.MultiServiceInstancesChangedListener) + multipleServiceDiscovery.createListener(Sets.newHashSet("app1")); multipleServiceDiscovery.addServiceInstancesChangedListener(listener); - MultipleServiceDiscovery.SingleServiceInstancesChangedListener singleServiceInstancesChangedListener = listener.getAndComputeIfAbsent("child.a1", (a1) -> null); - Assert.notNull(singleServiceInstancesChangedListener, "singleServiceInstancesChangedListener can not be null"); - singleServiceInstancesChangedListener.onEvent(new ServiceInstancesChangedEvent("app1", buildInstances(urlsSameRevision))); - Mockito.verify(serviceDiscoveryMock, Mockito.times(1)).getRemoteMetadata(Mockito.anyString(), Mockito.anyList()); + MultipleServiceDiscovery.SingleServiceInstancesChangedListener singleServiceInstancesChangedListener = + listener.getAndComputeIfAbsent("child.a1", (a1) -> null); + Assert.notNull( + singleServiceInstancesChangedListener, "singleServiceInstancesChangedListener can not be null"); + singleServiceInstancesChangedListener.onEvent( + new ServiceInstancesChangedEvent("app1", buildInstances(urlsSameRevision))); + Mockito.verify(serviceDiscoveryMock, Mockito.times(1)) + .getRemoteMetadata(Mockito.anyString(), Mockito.anyList()); Field serviceUrlsField = ServiceInstancesChangedListener.class.getDeclaredField("serviceUrls"); serviceUrlsField.setAccessible(true); - Map> map= (Map>) serviceUrlsField.get(listener); - Assert.assertTrue(!CollectionUtils.isEmptyMap(map),"url can not be empty"); + Map> map = + (Map>) + serviceUrlsField.get(listener); + Assert.assertTrue(!CollectionUtils.isEmptyMap(map), "url can not be empty"); } catch (NoSuchFieldException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { diff --git a/dubbo-registry/dubbo-registry-nacos/pom.xml b/dubbo-registry/dubbo-registry-nacos/pom.xml index c0918d5dad..6c7e776043 100644 --- a/dubbo-registry/dubbo-registry-nacos/pom.xml +++ b/dubbo-registry/dubbo-registry-nacos/pom.xml @@ -1,3 +1,4 @@ + - - org.apache.dubbo - dubbo-registry - ${revision} - - 4.0.0 + 4.0.0 + + org.apache.dubbo + dubbo-registry + ${revision} + - dubbo-registry-nacos - ${project.artifactId} - The Nacos registry module of Dubbo project + dubbo-registry-nacos + ${project.artifactId} + The Nacos registry module of Dubbo project - + - - org.apache.dubbo - dubbo-registry-api - ${project.version} - + + org.apache.dubbo + dubbo-registry-api + ${project.version} + - - org.apache.dubbo - dubbo-common - ${project.version} - + + org.apache.dubbo + dubbo-common + ${project.version} + - - com.alibaba.nacos - nacos-client - + + com.alibaba.nacos + nacos-client + - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - test - + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.version} + test + - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.parent.version} - test - + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.parent.version} + test + - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - test - + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + test + - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - test - + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + test + - - ch.qos.logback - logback-classic - test - + + ch.qos.logback + logback-classic + test + - - - org.springframework - spring-test - test - + + + org.springframework + spring-test + test + - + diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosAggregateListener.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosAggregateListener.java index b8dcaad92f..e3e3a90c10 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosAggregateListener.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosAggregateListener.java @@ -21,8 +21,6 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.registry.NotifyListener; -import com.alibaba.nacos.api.naming.pojo.Instance; - import java.util.List; import java.util.Map; import java.util.Objects; @@ -32,10 +30,13 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Pattern; import java.util.stream.Collectors; +import com.alibaba.nacos.api.naming.pojo.Instance; + import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_NACOS_SUB_LEGACY; public class NacosAggregateListener { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NacosAggregateListener.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(NacosAggregateListener.class); private final NotifyListener notifyListener; private final Set serviceNames = new ConcurrentHashSet<>(); private final Map> serviceInstances = new ConcurrentHashMap<>(); @@ -53,13 +54,18 @@ public class NacosAggregateListener { } else { serviceInstances.put(serviceName, instances); } - if (isLegacyName(serviceName) && instances != null && - !instances.isEmpty() && warned.compareAndSet(false, true)) { - logger.error(REGISTRY_NACOS_SUB_LEGACY, "", "", - "Received not empty notification for legacy service name: " + serviceName + ", " + - "instances: [" + instances.stream().map(Instance::getIp).collect(Collectors.joining(" ,")) + "]. " + - "Please upgrade these Dubbo client(lower than 2.7.3) to the latest version. " + - "Dubbo will remove the support for legacy service name in the future."); + if (isLegacyName(serviceName) + && instances != null + && !instances.isEmpty() + && warned.compareAndSet(false, true)) { + logger.error( + REGISTRY_NACOS_SUB_LEGACY, + "", + "", + "Received not empty notification for legacy service name: " + serviceName + ", " + "instances: [" + + instances.stream().map(Instance::getIp).collect(Collectors.joining(" ,")) + "]. " + + "Please upgrade these Dubbo client(lower than 2.7.3) to the latest version. " + + "Dubbo will remove the support for legacy service name in the future."); } return serviceInstances.values().stream().flatMap(List::stream).collect(Collectors.toList()); } @@ -85,7 +91,9 @@ public class NacosAggregateListener { return false; } NacosAggregateListener that = (NacosAggregateListener) o; - return Objects.equals(notifyListener, that.notifyListener) && Objects.equals(serviceNames, that.serviceNames) && Objects.equals(serviceInstances, that.serviceInstances); + return Objects.equals(notifyListener, that.notifyListener) + && Objects.equals(serviceNames, that.serviceNames) + && Objects.equals(serviceInstances, that.serviceInstances); } @Override diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosConnectionManager.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosConnectionManager.java index 2992d9677e..326da55bb1 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosConnectionManager.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosConnectionManager.java @@ -23,11 +23,6 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.registry.nacos.util.NacosNamingServiceUtils; -import com.alibaba.nacos.api.NacosFactory; -import com.alibaba.nacos.api.PropertyKeyConst; -import com.alibaba.nacos.api.exception.NacosException; -import com.alibaba.nacos.api.naming.NamingService; - import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -35,6 +30,11 @@ import java.util.Properties; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; +import com.alibaba.nacos.api.NacosFactory; +import com.alibaba.nacos.api.PropertyKeyConst; +import com.alibaba.nacos.api.exception.NacosException; +import com.alibaba.nacos.api.naming.NamingService; + import static com.alibaba.nacos.api.PropertyKeyConst.PASSWORD; import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; import static com.alibaba.nacos.api.PropertyKeyConst.USERNAME; @@ -47,8 +47,8 @@ import static org.apache.dubbo.common.utils.StringConstantFieldValuePredicate.of public class NacosConnectionManager { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NacosNamingServiceUtils.class); - + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(NacosNamingServiceUtils.class); private final URL connectionURL; @@ -126,12 +126,18 @@ public class NacosConnectionManager { if (!check || (UP.equals(serverStatus) && namingServiceAvailable)) { break; } else { - logger.warn(LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION, "", "", - "Failed to connect to nacos naming server. " + - "Server status: " + serverStatus + ". " + - "Naming Service Available: " + namingServiceAvailable + ". " + - (i < retryTimes ? "Dubbo will try to retry in " + sleepMsBetweenRetries + ". " : "Exceed retry max times.") + - "Try times: " + (i + 1)); + logger.warn( + LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION, + "", + "", + "Failed to connect to nacos naming server. " + "Server status: " + + serverStatus + ". " + "Naming Service Available: " + + namingServiceAvailable + ". " + + (i < retryTimes + ? "Dubbo will try to retry in " + sleepMsBetweenRetries + ". " + : "Exceed retry max times.") + + "Try times: " + + (i + 1)); } namingService.shutDown(); namingService = null; @@ -148,8 +154,13 @@ public class NacosConnectionManager { } if (namingService == null) { - logger.error(REGISTRY_NACOS_EXCEPTION, "", "", "Failed to create nacos naming service client. Reason: server status check failed."); - throw new IllegalStateException("Failed to create nacos naming service client. Reason: server status check failed."); + logger.error( + REGISTRY_NACOS_EXCEPTION, + "", + "", + "Failed to create nacos naming service client. Reason: server status check failed."); + throw new IllegalStateException( + "Failed to create nacos naming service client. Reason: server status check failed."); } return namingService; @@ -164,7 +175,6 @@ public class NacosConnectionManager { } } - private Properties buildNacosProperties(URL url) { Properties properties = new Properties(); setServerAddr(url, properties); @@ -173,8 +183,7 @@ public class NacosConnectionManager { } private void setServerAddr(URL url, Properties properties) { - StringBuilder serverAddrBuilder = - new StringBuilder(url.getHost()) // Host + StringBuilder serverAddrBuilder = new StringBuilder(url.getHost()) // Host .append(':') .append(url.getPort()); // Port diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosNamingServiceWrapper.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosNamingServiceWrapper.java index 2b09d8f675..5200f022b5 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosNamingServiceWrapper.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosNamingServiceWrapper.java @@ -16,6 +16,15 @@ */ package org.apache.dubbo.registry.nacos; +import org.apache.dubbo.common.constants.LoggerCodeConstants; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; +import org.apache.dubbo.common.utils.MethodUtils; +import org.apache.dubbo.common.utils.StringUtils; +import org.apache.dubbo.registry.nacos.function.NacosConsumer; +import org.apache.dubbo.registry.nacos.function.NacosFunction; + import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -28,15 +37,6 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; -import org.apache.dubbo.common.constants.LoggerCodeConstants; -import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; -import org.apache.dubbo.common.utils.MethodUtils; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.registry.nacos.function.NacosConsumer; -import org.apache.dubbo.registry.nacos.function.NacosFunction; - import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.listener.EventListener; @@ -44,7 +44,8 @@ import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; public class NacosNamingServiceWrapper { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NacosNamingServiceWrapper.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(NacosNamingServiceWrapper.class); private static final String INNERCLASS_SYMBOL = "$"; @@ -61,9 +62,12 @@ public class NacosNamingServiceWrapper { private final ConcurrentMap registerStatus = new ConcurrentHashMap<>(); private final ConcurrentMap subscribeStatus = new ConcurrentHashMap<>(); - public NacosNamingServiceWrapper(NacosConnectionManager nacosConnectionManager, int retryTimes, int sleepMsBetweenRetries) { + public NacosNamingServiceWrapper( + NacosConnectionManager nacosConnectionManager, int retryTimes, int sleepMsBetweenRetries) { this.nacosConnectionManager = nacosConnectionManager; - this.isSupportBatchRegister = MethodUtils.findMethod(NamingService.class, "batchRegisterInstance", String.class, String.class, List.class) != null; + this.isSupportBatchRegister = MethodUtils.findMethod( + NamingService.class, "batchRegisterInstance", String.class, String.class, List.class) + != null; logger.info("Nacos batch register enable: " + isSupportBatchRegister); this.retryTimes = Math.max(retryTimes, 0); this.sleepMsBetweenRetries = sleepMsBetweenRetries; @@ -73,7 +77,11 @@ public class NacosNamingServiceWrapper { * @deprecated for uts only */ @Deprecated - protected NacosNamingServiceWrapper(NacosConnectionManager nacosConnectionManager, boolean isSupportBatchRegister, int retryTimes, int sleepMsBetweenRetries) { + protected NacosNamingServiceWrapper( + NacosConnectionManager nacosConnectionManager, + boolean isSupportBatchRegister, + int retryTimes, + int sleepMsBetweenRetries) { this.nacosConnectionManager = nacosConnectionManager; this.isSupportBatchRegister = isSupportBatchRegister; this.retryTimes = Math.max(retryTimes, 0); @@ -87,7 +95,8 @@ public class NacosNamingServiceWrapper { public void subscribe(String serviceName, String group, EventListener eventListener) throws NacosException { String nacosServiceName = handleInnerSymbol(serviceName); SubscribeInfo subscribeInfo = new SubscribeInfo(nacosServiceName, group, eventListener); - NamingService namingService = ConcurrentHashMapUtils.computeIfAbsent(subscribeStatus, subscribeInfo, info -> nacosConnectionManager.getNamingService()); + NamingService namingService = ConcurrentHashMapUtils.computeIfAbsent( + subscribeStatus, subscribeInfo, info -> nacosConnectionManager.getNamingService()); accept(() -> namingService.subscribe(nacosServiceName, group, eventListener)); } @@ -102,12 +111,14 @@ public class NacosNamingServiceWrapper { } public List getAllInstances(String serviceName, String group) throws NacosException { - return apply(() -> nacosConnectionManager.getNamingService().getAllInstances(handleInnerSymbol(serviceName), group)); + return apply( + () -> nacosConnectionManager.getNamingService().getAllInstances(handleInnerSymbol(serviceName), group)); } public void registerInstance(String serviceName, String group, Instance instance) throws NacosException { String nacosServiceName = handleInnerSymbol(serviceName); - InstancesInfo instancesInfo = ConcurrentHashMapUtils.computeIfAbsent(registerStatus, new InstanceId(nacosServiceName, group), id -> new InstancesInfo()); + InstancesInfo instancesInfo = ConcurrentHashMapUtils.computeIfAbsent( + registerStatus, new InstanceId(nacosServiceName, group), id -> new InstancesInfo()); try { instancesInfo.lock(); @@ -137,13 +148,15 @@ public class NacosNamingServiceWrapper { instancesInfo.setBatchRegistered(true); return; } catch (NacosException e) { - logger.info("Failed to batch register to nacos. Service Name: " + serviceName + ". Maybe nacos server not support. Will fallback to multi connection register."); + logger.info("Failed to batch register to nacos. Service Name: " + serviceName + + ". Maybe nacos server not support. Will fallback to multi connection register."); // ignore } } if (instancesInfo.isBatchRegistered()) { - NamingService namingService = instancesInfo.getInstances().get(0).getNamingService(); + NamingService namingService = + instancesInfo.getInstances().get(0).getNamingService(); List instanceListToRegister = new ArrayList<>(); for (InstanceInfo instanceInfo : instancesInfo.getInstances()) { instanceListToRegister.add(instanceInfo.getInstance()); @@ -155,10 +168,9 @@ public class NacosNamingServiceWrapper { } // fallback to register one by one - Set selectedNamingServices = instancesInfo.getInstances() - .stream() - .map(InstanceInfo::getNamingService) - .collect(Collectors.toSet()); + Set selectedNamingServices = instancesInfo.getInstances().stream() + .map(InstanceInfo::getNamingService) + .collect(Collectors.toSet()); NamingService namingService = nacosConnectionManager.getNamingService(selectedNamingServices); accept(() -> namingService.registerInstance(nacosServiceName, group, instance)); instancesInfo.getInstances().add(new InstanceInfo(instance, namingService)); @@ -167,9 +179,11 @@ public class NacosNamingServiceWrapper { } } - public void updateInstance(String serviceName, String group, Instance oldInstance, Instance newInstance) throws NacosException { + public void updateInstance(String serviceName, String group, Instance oldInstance, Instance newInstance) + throws NacosException { String nacosServiceName = handleInnerSymbol(serviceName); - InstancesInfo instancesInfo = ConcurrentHashMapUtils.computeIfAbsent(registerStatus, new InstanceId(nacosServiceName, group), id -> new InstancesInfo()); + InstancesInfo instancesInfo = ConcurrentHashMapUtils.computeIfAbsent( + registerStatus, new InstanceId(nacosServiceName, group), id -> new InstancesInfo()); try { instancesInfo.lock(); @@ -177,10 +191,9 @@ public class NacosNamingServiceWrapper { throw new IllegalArgumentException(serviceName + " has not been registered to nacos."); } - Optional optional = instancesInfo.getInstances() - .stream() - .filter(instanceInfo -> instanceInfo.getInstance().equals(oldInstance)) - .findAny(); + Optional optional = instancesInfo.getInstances().stream() + .filter(instanceInfo -> instanceInfo.getInstance().equals(oldInstance)) + .findAny(); if (!optional.isPresent()) { throw new IllegalArgumentException(oldInstance + " has not been registered to nacos."); @@ -193,8 +206,8 @@ public class NacosNamingServiceWrapper { if (isSupportBatchRegister && instancesInfo.isBatchRegistered()) { NamingService namingService = oldInstanceInfo.getNamingService(); List instanceListToRegister = instancesInfo.getInstances().stream() - .map(InstanceInfo::getInstance) - .collect(Collectors.toList()); + .map(InstanceInfo::getInstance) + .collect(Collectors.toList()); accept(() -> namingService.batchRegisterInstance(nacosServiceName, group, instanceListToRegister)); return; @@ -209,16 +222,16 @@ public class NacosNamingServiceWrapper { public void deregisterInstance(String serviceName, String group, String ip, int port) throws NacosException { String nacosServiceName = handleInnerSymbol(serviceName); - InstancesInfo instancesInfo = ConcurrentHashMapUtils.computeIfAbsent(registerStatus, new InstanceId(nacosServiceName, group), id -> new InstancesInfo()); + InstancesInfo instancesInfo = ConcurrentHashMapUtils.computeIfAbsent( + registerStatus, new InstanceId(nacosServiceName, group), id -> new InstancesInfo()); try { instancesInfo.lock(); - List instances = instancesInfo.getInstances() - .stream() - .map(InstanceInfo::getInstance) - .filter(instance -> Objects.equals(instance.getIp(), ip) && instance.getPort() == port) - .collect(Collectors.toList()); + List instances = instancesInfo.getInstances().stream() + .map(InstanceInfo::getInstance) + .filter(instance -> Objects.equals(instance.getIp(), ip) && instance.getPort() == port) + .collect(Collectors.toList()); for (Instance instance : instances) { deregisterInstance(serviceName, group, instance); } @@ -227,17 +240,16 @@ public class NacosNamingServiceWrapper { } } - public void deregisterInstance(String serviceName, String group, Instance instance) throws NacosException { String nacosServiceName = handleInnerSymbol(serviceName); - InstancesInfo instancesInfo = ConcurrentHashMapUtils.computeIfAbsent(registerStatus, new InstanceId(nacosServiceName, group), id -> new InstancesInfo()); + InstancesInfo instancesInfo = ConcurrentHashMapUtils.computeIfAbsent( + registerStatus, new InstanceId(nacosServiceName, group), id -> new InstancesInfo()); try { instancesInfo.lock(); - Optional optional = instancesInfo.getInstances() - .stream() - .filter(instanceInfo -> instanceInfo.getInstance().equals(instance)) - .findAny(); + Optional optional = instancesInfo.getInstances().stream() + .filter(instanceInfo -> instanceInfo.getInstance().equals(instance)) + .findAny(); if (!optional.isPresent()) { return; } @@ -263,7 +275,9 @@ public class NacosNamingServiceWrapper { for (InstanceInfo info : instancesInfo.getInstances()) { instanceListToRegister.add(info.getInstance()); } - accept(() -> instanceInfo.getNamingService().batchRegisterInstance(nacosServiceName, group, instanceListToRegister)); + accept(() -> instanceInfo + .getNamingService() + .batchRegisterInstance(nacosServiceName, group, instanceListToRegister)); } else { // unregister one accept(() -> instanceInfo.getNamingService().deregisterInstance(nacosServiceName, group, instance)); @@ -278,7 +292,9 @@ public class NacosNamingServiceWrapper { } public List selectInstances(String serviceName, String group, boolean healthy) throws NacosException { - return apply(() -> nacosConnectionManager.getNamingService().selectInstances(handleInnerSymbol(serviceName), group, healthy)); + return apply(() -> nacosConnectionManager + .getNamingService() + .selectInstances(handleInnerSymbol(serviceName), group, healthy)); } public void shutdown() throws NacosException { @@ -404,7 +420,9 @@ public class NacosNamingServiceWrapper { return false; } SubscribeInfo that = (SubscribeInfo) o; - return Objects.equals(serviceName, that.serviceName) && Objects.equals(group, that.group) && Objects.equals(eventListener, that.eventListener); + return Objects.equals(serviceName, that.serviceName) + && Objects.equals(group, that.group) + && Objects.equals(eventListener, that.eventListener); } @Override @@ -421,7 +439,6 @@ public class NacosNamingServiceWrapper { return registerStatus; } - private R apply(NacosFunction command) throws NacosException { NacosException le = null; R result = null; @@ -433,15 +450,27 @@ public class NacosNamingServiceWrapper { break; } catch (NacosException e) { le = e; - logger.warn(LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION, "", "", - "Failed to request nacos naming server. " + - (times < retryTimes ? "Dubbo will try to retry in " + sleepMsBetweenRetries + ". " : "Exceed retry max times.") + - "Try times: " + (times + 1), e); + logger.warn( + LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION, + "", + "", + "Failed to request nacos naming server. " + + (times < retryTimes + ? "Dubbo will try to retry in " + sleepMsBetweenRetries + ". " + : "Exceed retry max times.") + + "Try times: " + + (times + 1), + e); if (times < retryTimes) { try { Thread.sleep(sleepMsBetweenRetries); } catch (InterruptedException ex) { - logger.warn(LoggerCodeConstants.INTERNAL_INTERRUPTED, "", "", "Interrupted when waiting to retry.", ex); + logger.warn( + LoggerCodeConstants.INTERNAL_INTERRUPTED, + "", + "", + "Interrupted when waiting to retry.", + ex); Thread.currentThread().interrupt(); } } @@ -451,8 +480,8 @@ public class NacosNamingServiceWrapper { throw le; } if (times > 1) { - logger.info("Failed to request nacos naming server for " + (times - 1) + " times and finally success. " + - "This may caused by high stress of nacos server."); + logger.info("Failed to request nacos naming server for " + (times - 1) + " times and finally success. " + + "This may caused by high stress of nacos server."); } return result; } @@ -467,15 +496,27 @@ public class NacosNamingServiceWrapper { break; } catch (NacosException e) { le = e; - logger.warn(LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION, "", "", - "Failed to request nacos naming server. " + - (times < retryTimes ? "Dubbo will try to retry in " + sleepMsBetweenRetries + ". " : "Exceed retry max times.") + - "Try times: " + (times + 1), e); + logger.warn( + LoggerCodeConstants.REGISTRY_NACOS_EXCEPTION, + "", + "", + "Failed to request nacos naming server. " + + (times < retryTimes + ? "Dubbo will try to retry in " + sleepMsBetweenRetries + ". " + : "Exceed retry max times.") + + "Try times: " + + (times + 1), + e); if (times < retryTimes) { try { Thread.sleep(sleepMsBetweenRetries); } catch (InterruptedException ex) { - logger.warn(LoggerCodeConstants.INTERNAL_INTERRUPTED, "", "", "Interrupted when waiting to retry.", ex); + logger.warn( + LoggerCodeConstants.INTERNAL_INTERRUPTED, + "", + "", + "Interrupted when waiting to retry.", + ex); Thread.currentThread().interrupt(); } } @@ -485,8 +526,8 @@ public class NacosNamingServiceWrapper { throw le; } if (times > 1) { - logger.info("Failed to request nacos naming server for " + (times - 1) + " times and finally success. " + - "This may caused by high stress of nacos server."); + logger.info("Failed to request nacos naming server for " + (times - 1) + " times and finally success. " + + "This may caused by high stress of nacos server."); } } } diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java index 99c0e9bca1..02922034c7 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosRegistry.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.registry.nacos; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -32,14 +31,6 @@ import org.apache.dubbo.registry.support.FailbackRegistry; import org.apache.dubbo.registry.support.SkipFailbackWrapperException; import org.apache.dubbo.rpc.RpcException; -import com.alibaba.nacos.api.common.Constants; -import com.alibaba.nacos.api.exception.NacosException; -import com.alibaba.nacos.api.naming.listener.Event; -import com.alibaba.nacos.api.naming.listener.EventListener; -import com.alibaba.nacos.api.naming.listener.NamingEvent; -import com.alibaba.nacos.api.naming.pojo.Instance; -import com.alibaba.nacos.api.naming.pojo.ListView; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -56,6 +47,14 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import com.alibaba.nacos.api.common.Constants; +import com.alibaba.nacos.api.exception.NacosException; +import com.alibaba.nacos.api.naming.listener.Event; +import com.alibaba.nacos.api.naming.listener.EventListener; +import com.alibaba.nacos.api.naming.listener.NamingEvent; +import com.alibaba.nacos.api.naming.pojo.Instance; +import com.alibaba.nacos.api.naming.pojo.ListView; + import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; @@ -92,12 +91,8 @@ public class NacosRegistry extends FailbackRegistry { /** * All supported categories */ - private static final List ALL_SUPPORTED_CATEGORIES = Arrays.asList( - PROVIDERS_CATEGORY, - CONSUMERS_CATEGORY, - ROUTERS_CATEGORY, - CONFIGURATORS_CATEGORY - ); + private static final List ALL_SUPPORTED_CATEGORIES = + Arrays.asList(PROVIDERS_CATEGORY, CONSUMERS_CATEGORY, ROUTERS_CATEGORY, CONFIGURATORS_CATEGORY); private static final int CATEGORY_INDEX = 0; @@ -127,6 +122,7 @@ public class NacosRegistry extends FailbackRegistry { * The interval in second of lookup Nacos service names(only for Dubbo-OPS) */ private static final long LOOKUP_INTERVAL = Long.getLong("nacos.service.names.lookup.interval", 30); + private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NacosRegistry.class); private final NacosNamingServiceWrapper namingService; /** @@ -134,9 +130,11 @@ public class NacosRegistry extends FailbackRegistry { */ private volatile ScheduledExecutorService scheduledExecutorService; - private final Map> originToAggregateListener = new ConcurrentHashMap<>(); + private final Map> originToAggregateListener = + new ConcurrentHashMap<>(); - private final Map>> nacosListeners = new ConcurrentHashMap<>(); + private final Map>> nacosListeners = + new ConcurrentHashMap<>(); private final boolean supportLegacyServiceName; public NacosRegistry(URL url, NacosNamingServiceWrapper namingService) { @@ -159,15 +157,16 @@ public class NacosRegistry extends FailbackRegistry { List urls = new LinkedList<>(); Set serviceNames = getServiceNames(url, null); for (String serviceName : serviceNames) { - List instances = namingService.getAllInstances(serviceName, - getUrl().getGroup(Constants.DEFAULT_GROUP)); + List instances = + namingService.getAllInstances(serviceName, getUrl().getGroup(Constants.DEFAULT_GROUP)); urls.addAll(buildURLs(url, instances)); } return urls; } catch (SkipFailbackWrapperException exception) { throw exception; - } catch (Exception cause) { - throw new RpcException("Failed to lookup " + url + " from nacos " + getUrl() + ", cause: " + cause.getMessage(), cause); + } catch (Exception cause) { + throw new RpcException( + "Failed to lookup " + url + " from nacos " + getUrl() + ", cause: " + cause.getMessage(), cause); } } @@ -183,15 +182,16 @@ public class NacosRegistry extends FailbackRegistry { * * in https://github.com/apache/dubbo/issues/5978 */ - namingService.registerInstance(serviceName, - getUrl().getGroup(Constants.DEFAULT_GROUP), instance); + namingService.registerInstance(serviceName, getUrl().getGroup(Constants.DEFAULT_GROUP), instance); } else { - logger.info("Please set 'dubbo.registry.parameters.register-consumer-url=true' to turn on consumer url registration."); + logger.info( + "Please set 'dubbo.registry.parameters.register-consumer-url=true' to turn on consumer url registration."); } } catch (SkipFailbackWrapperException exception) { throw exception; } catch (Exception cause) { - throw new RpcException("Failed to register " + url + " to nacos " + getUrl() + ", cause: " + cause.getMessage(), cause); + throw new RpcException( + "Failed to register " + url + " to nacos " + getUrl() + ", cause: " + cause.getMessage(), cause); } } @@ -200,21 +200,22 @@ public class NacosRegistry extends FailbackRegistry { try { String serviceName = getServiceName(url); Instance instance = createInstance(url); - namingService.deregisterInstance(serviceName, - getUrl().getGroup(Constants.DEFAULT_GROUP), - instance.getIp() - , instance.getPort()); + namingService.deregisterInstance( + serviceName, getUrl().getGroup(Constants.DEFAULT_GROUP), instance.getIp(), instance.getPort()); } catch (SkipFailbackWrapperException exception) { throw exception; - } catch (Exception cause) { - throw new RpcException("Failed to unregister " + url + " to nacos " + getUrl() + ", cause: " + cause.getMessage(), cause); + } catch (Exception cause) { + throw new RpcException( + "Failed to unregister " + url + " to nacos " + getUrl() + ", cause: " + cause.getMessage(), cause); } } @Override public void doSubscribe(final URL url, final NotifyListener listener) { NacosAggregateListener nacosAggregateListener = new NacosAggregateListener(listener); - originToAggregateListener.computeIfAbsent(url, k -> new ConcurrentHashMap<>()).put(listener, nacosAggregateListener); + originToAggregateListener + .computeIfAbsent(url, k -> new ConcurrentHashMap<>()) + .put(listener, nacosAggregateListener); Set serviceNames = getServiceNames(url, nacosAggregateListener); @@ -235,8 +236,8 @@ public class NacosRegistry extends FailbackRegistry { * in https://github.com/apache/dubbo/issues/5978 */ for (String serviceName : serviceNames) { - List instances = namingService.getAllInstances(serviceName, - getUrl().getGroup(Constants.DEFAULT_GROUP)); + List instances = + namingService.getAllInstances(serviceName, getUrl().getGroup(Constants.DEFAULT_GROUP)); notifySubscriber(url, serviceName, listener, instances); } for (String serviceName : serviceNames) { @@ -245,23 +246,24 @@ public class NacosRegistry extends FailbackRegistry { } else { for (String serviceName : serviceNames) { List instances = new LinkedList<>(); - instances.addAll(namingService.getAllInstances(serviceName - , getUrl().getGroup(Constants.DEFAULT_GROUP))); + instances.addAll( + namingService.getAllInstances(serviceName, getUrl().getGroup(Constants.DEFAULT_GROUP))); String serviceInterface = serviceName; String[] segments = serviceName.split(SERVICE_NAME_SEPARATOR, -1); if (segments.length == 4) { serviceInterface = segments[SERVICE_INTERFACE_INDEX]; } - URL subscriberURL = url.setPath(serviceInterface).addParameters(INTERFACE_KEY, serviceInterface, - CHECK_KEY, String.valueOf(false)); + URL subscriberURL = url.setPath(serviceInterface) + .addParameters(INTERFACE_KEY, serviceInterface, CHECK_KEY, String.valueOf(false)); notifySubscriber(subscriberURL, serviceName, listener, instances); subscribeEventListener(serviceName, subscriberURL, listener); } } } catch (SkipFailbackWrapperException exception) { throw exception; - } catch (Throwable cause) { - throw new RpcException("Failed to subscribe " + url + " to nacos " + getUrl() + ", cause: " + cause.getMessage(), cause); + } catch (Throwable cause) { + throw new RpcException( + "Failed to subscribe " + url + " to nacos " + getUrl() + ", cause: " + cause.getMessage(), cause); } } @@ -283,7 +285,13 @@ public class NacosRegistry extends FailbackRegistry { } else { Map listenerMap = originToAggregateListener.get(url); if (listenerMap == null) { - logger.warn(REGISTRY_NACOS_EXCEPTION, "", "", String.format("No aggregate listener found for url %s, this service might have already been unsubscribed.", url)); + logger.warn( + REGISTRY_NACOS_EXCEPTION, + "", + "", + String.format( + "No aggregate listener found for url %s, this service might have already been unsubscribed.", + url)); return; } NacosAggregateListener nacosAggregateListener = listenerMap.remove(listener); @@ -292,7 +300,12 @@ public class NacosRegistry extends FailbackRegistry { try { doUnsubscribe(url, nacosAggregateListener, serviceNames); } catch (NacosException e) { - logger.error(REGISTRY_NACOS_EXCEPTION, "", "", "Failed to unsubscribe " + url + " to nacos " + getUrl() + ", cause: " + e.getMessage(), e); + logger.error( + REGISTRY_NACOS_EXCEPTION, + "", + "", + "Failed to unsubscribe " + url + " to nacos " + getUrl() + ", cause: " + e.getMessage(), + e); } } if (listenerMap.isEmpty()) { @@ -301,7 +314,9 @@ public class NacosRegistry extends FailbackRegistry { } } - private void doUnsubscribe(final URL url, final NacosAggregateListener nacosAggregateListener, final Set serviceNames) throws NacosException { + private void doUnsubscribe( + final URL url, final NacosAggregateListener nacosAggregateListener, final Set serviceNames) + throws NacosException { for (String serviceName : serviceNames) { unsubscribeEventListener(serviceName, url, nacosAggregateListener); } @@ -341,7 +356,7 @@ public class NacosRegistry extends FailbackRegistry { // Add the legacy service name since 2.7.6 String legacySubscribedServiceName = getLegacySubscribedServiceName(url); if (!serviceName.toString().equals(legacySubscribedServiceName)) { - //avoid duplicated service names + // avoid duplicated service names serviceNames.add(legacySubscribedServiceName); } } @@ -355,19 +370,24 @@ public class NacosRegistry extends FailbackRegistry { private Set filterServiceNames(NacosServiceName serviceName) { try { Set serviceNames = new LinkedHashSet<>(); - serviceNames.addAll(namingService.getServicesOfServer(1, Integer.MAX_VALUE, - getUrl().getGroup(Constants.DEFAULT_GROUP)).getData() - .stream() - .filter(this::isConformRules) - .map(NacosServiceName::new) - .filter(serviceName::isCompatible) - .map(NacosServiceName::toString) - .collect(Collectors.toList())); + serviceNames.addAll( + namingService + .getServicesOfServer(1, Integer.MAX_VALUE, getUrl().getGroup(Constants.DEFAULT_GROUP)) + .getData() + .stream() + .filter(this::isConformRules) + .map(NacosServiceName::new) + .filter(serviceName::isCompatible) + .map(NacosServiceName::toString) + .collect(Collectors.toList())); return serviceNames; } catch (SkipFailbackWrapperException exception) { throw exception; - } catch (Throwable cause) { - throw new RpcException("Failed to filter serviceName from nacos, url: " + getUrl() + ", serviceName: " + serviceName + ", cause: " + cause.getMessage(), cause); + } catch (Throwable cause) { + throw new RpcException( + "Failed to filter serviceName from nacos, url: " + getUrl() + ", serviceName: " + serviceName + + ", cause: " + cause.getMessage(), + cause); } } @@ -382,7 +402,6 @@ public class NacosRegistry extends FailbackRegistry { return serviceName.split(NAME_SEPARATOR, -1).length == 4; } - /** * Get the legacy subscribed service name for compatible with Dubbo 2.7.3 and below * @@ -405,7 +424,6 @@ public class NacosRegistry extends FailbackRegistry { } } - private boolean isAdminProtocol(URL url) { return ADMIN_PROTOCOL.equals(url.getProtocol()); } @@ -413,21 +431,25 @@ public class NacosRegistry extends FailbackRegistry { private void scheduleServiceNamesLookup(final URL url, final NacosAggregateListener listener) { if (scheduledExecutorService == null) { scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); - scheduledExecutorService.scheduleAtFixedRate(() -> { - Set serviceNames = getAllServiceNames(); - filterData(serviceNames, serviceName -> { - boolean accepted = false; - for (String category : ALL_SUPPORTED_CATEGORIES) { - String prefix = category + SERVICE_NAME_SEPARATOR; - if (serviceName != null && serviceName.startsWith(prefix)) { - accepted = true; - break; - } - } - return accepted; - }); - doSubscribe(url, listener, serviceNames); - }, LOOKUP_INTERVAL, LOOKUP_INTERVAL, TimeUnit.SECONDS); + scheduledExecutorService.scheduleAtFixedRate( + () -> { + Set serviceNames = getAllServiceNames(); + filterData(serviceNames, serviceName -> { + boolean accepted = false; + for (String category : ALL_SUPPORTED_CATEGORIES) { + String prefix = category + SERVICE_NAME_SEPARATOR; + if (serviceName != null && serviceName.startsWith(prefix)) { + accepted = true; + break; + } + } + return accepted; + }); + doSubscribe(url, listener, serviceNames); + }, + LOOKUP_INTERVAL, + LOOKUP_INTERVAL, + TimeUnit.SECONDS); } } @@ -447,8 +469,8 @@ public class NacosRegistry extends FailbackRegistry { try { final Set serviceNames = new LinkedHashSet<>(); int pageIndex = 1; - ListView listView = namingService.getServicesOfServer(pageIndex, PAGINATION_SIZE, - getUrl().getGroup(Constants.DEFAULT_GROUP)); + ListView listView = namingService.getServicesOfServer( + pageIndex, PAGINATION_SIZE, getUrl().getGroup(Constants.DEFAULT_GROUP)); // First page data List firstPageData = listView.getData(); // Append first page into list @@ -464,15 +486,17 @@ public class NacosRegistry extends FailbackRegistry { } // If more than 1 page while (pageIndex < pageNumbers) { - listView = namingService.getServicesOfServer(++pageIndex, PAGINATION_SIZE, - getUrl().getGroup(Constants.DEFAULT_GROUP)); + listView = namingService.getServicesOfServer( + ++pageIndex, PAGINATION_SIZE, getUrl().getGroup(Constants.DEFAULT_GROUP)); serviceNames.addAll(listView.getData()); } return serviceNames; } catch (SkipFailbackWrapperException exception) { throw exception; - } catch (Throwable cause) { - throw new RpcException("Failed to get all serviceName from nacos, url: " + getUrl() + ", cause: " + cause.getMessage(), cause); + } catch (Throwable cause) { + throw new RpcException( + "Failed to get all serviceName from nacos, url: " + getUrl() + ", cause: " + cause.getMessage(), + cause); } } @@ -505,8 +529,8 @@ public class NacosRegistry extends FailbackRegistry { String serviceInterface = segments[SERVICE_INTERFACE_INDEX]; // no match service interface - if (!WILDCARD.equals(targetServiceInterface) && - !StringUtils.isEquals(targetServiceInterface, serviceInterface)) { + if (!WILDCARD.equals(targetServiceInterface) + && !StringUtils.isEquals(targetServiceInterface, serviceInterface)) { return false; } @@ -552,11 +576,15 @@ public class NacosRegistry extends FailbackRegistry { List urls = buildURLs(consumerURL, instances); // Nacos does not support configurators and routers from registry, so all notifications are of providers type. if (urls.size() == 0 && !getUrl().getParameter(ENABLE_EMPTY_PROTECTION_KEY, DEFAULT_ENABLE_EMPTY_PROTECTION)) { - logger.warn(REGISTRY_NACOS_EXCEPTION, "", "", "Received empty url address list and empty protection is disabled, will clear current available addresses"); + logger.warn( + REGISTRY_NACOS_EXCEPTION, + "", + "", + "Received empty url address list and empty protection is disabled, will clear current available addresses"); URL empty = URLBuilder.from(consumerURL) - .setProtocol(EMPTY_PROTOCOL) - .addParameter(CATEGORY_KEY, DEFAULT_CATEGORY) - .build(); + .setProtocol(EMPTY_PROTOCOL) + .addParameter(CATEGORY_KEY, DEFAULT_CATEGORY) + .build(); urls.add(empty); } return urls; @@ -576,22 +604,20 @@ public class NacosRegistry extends FailbackRegistry { } private void subscribeEventListener(String serviceName, final URL url, final NacosAggregateListener listener) - throws NacosException { - Map> listeners = nacosListeners.computeIfAbsent(url, - k -> new ConcurrentHashMap<>()); + throws NacosException { + Map> listeners = + nacosListeners.computeIfAbsent(url, k -> new ConcurrentHashMap<>()); - Map eventListeners = listeners.computeIfAbsent(listener, - k -> new ConcurrentHashMap<>()); + Map eventListeners = listeners.computeIfAbsent(listener, k -> new ConcurrentHashMap<>()); - EventListener eventListener = eventListeners.computeIfAbsent(serviceName, - k -> new RegistryChildListenerImpl(serviceName, url, listener)); + EventListener eventListener = eventListeners.computeIfAbsent( + serviceName, k -> new RegistryChildListenerImpl(serviceName, url, listener)); - namingService.subscribe(serviceName, - getUrl().getGroup(Constants.DEFAULT_GROUP), - eventListener); + namingService.subscribe(serviceName, getUrl().getGroup(Constants.DEFAULT_GROUP), eventListener); } - private void unsubscribeEventListener(String serviceName, final URL url, final NacosAggregateListener listener) throws NacosException { + private void unsubscribeEventListener(String serviceName, final URL url, final NacosAggregateListener listener) + throws NacosException { Map> listenerToServiceEvent = nacosListeners.get(url); if (listenerToServiceEvent == null) { return; @@ -604,9 +630,8 @@ public class NacosRegistry extends FailbackRegistry { if (eventListener == null) { return; } - namingService.unsubscribe(serviceName, - getUrl().getParameter(GROUP_KEY, Constants.DEFAULT_GROUP), - eventListener); + namingService.unsubscribe( + serviceName, getUrl().getParameter(GROUP_KEY, Constants.DEFAULT_GROUP), eventListener); if (serviceToEventMap.isEmpty()) { listenerToServiceEvent.remove(listener); } @@ -622,13 +647,15 @@ public class NacosRegistry extends FailbackRegistry { * @param listener {@link NotifyListener} * @param instances all {@link Instance instances} */ - private void notifySubscriber(URL url, String serviceName, NacosAggregateListener listener, Collection instances) { + private void notifySubscriber( + URL url, String serviceName, NacosAggregateListener listener, Collection instances) { List enabledInstances = new LinkedList<>(instances); if (enabledInstances.size() > 0) { // Instances filterEnabledInstances(enabledInstances); } - List aggregatedUrls = toUrlWithEmpty(url, listener.saveAndAggregateAllInstances(serviceName, enabledInstances)); + List aggregatedUrls = + toUrlWithEmpty(url, listener.saveAndAggregateAllInstances(serviceName, enabledInstances)); NacosRegistry.this.notify(url, listener.getNotifyListener(), aggregatedUrls); } @@ -639,19 +666,14 @@ public class NacosRegistry extends FailbackRegistry { * @return non-null array */ private List getCategories(URL url) { - return ANY_VALUE.equals(url.getServiceInterface()) ? - ALL_SUPPORTED_CATEGORIES : Arrays.asList(DEFAULT_CATEGORY); + return ANY_VALUE.equals(url.getServiceInterface()) ? ALL_SUPPORTED_CATEGORIES : Arrays.asList(DEFAULT_CATEGORY); } private URL buildURL(URL consumerURL, Instance instance) { Map metadata = instance.getMetadata(); String protocol = metadata.get(PROTOCOL_KEY); String path = metadata.get(PATH_KEY); - URL url = new ServiceConfigURL(protocol, - instance.getIp(), - instance.getPort(), - path, - instance.getMetadata()); + URL url = new ServiceConfigURL(protocol, instance.getIp(), instance.getPort(), path, instance.getMetadata()); return new DubboServiceAddressURL(url.getUrlAddress(), url.getUrlParam(), consumerURL, null); } @@ -701,7 +723,6 @@ public class NacosRegistry extends FailbackRegistry { * should be accepted */ boolean accept(T data); - } private class RegistryChildListenerImpl implements EventListener { @@ -743,7 +764,9 @@ public class NacosRegistry extends FailbackRegistry { return false; } RegistryChildListenerImpl that = (RegistryChildListenerImpl) o; - return Objects.equals(serviceName, that.serviceName) && Objects.equals(consumerUrl, that.consumerUrl) && Objects.equals(listener, that.listener); + return Objects.equals(serviceName, that.serviceName) + && Objects.equals(consumerUrl, that.consumerUrl) + && Objects.equals(listener, that.listener); } @Override @@ -751,5 +774,4 @@ public class NacosRegistry extends FailbackRegistry { return Objects.hash(serviceName, consumerUrl, listener); } } - } diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscovery.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscovery.java index 3fbe2853c4..c967fd56ac 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscovery.java @@ -16,13 +16,6 @@ */ package org.apache.dubbo.registry.nacos; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.Collectors; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.function.ThrowableFunction; @@ -38,6 +31,13 @@ import org.apache.dubbo.registry.nacos.util.NacosNamingServiceUtils; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; + import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.listener.Event; import com.alibaba.nacos.api.naming.listener.EventListener; @@ -78,8 +78,10 @@ public class NacosServiceDiscovery extends AbstractServiceDiscovery { super(applicationModel, registryURL); this.namingService = createNamingService(registryURL); // backward compatibility for 3.0.x - this.group = Boolean.parseBoolean(ConfigurationUtils.getProperty(applicationModel, NACOS_SD_USE_DEFAULT_GROUP_KEY, "false")) ? - DEFAULT_GROUP : getGroup(registryURL); + this.group = Boolean.parseBoolean( + ConfigurationUtils.getProperty(applicationModel, NACOS_SD_USE_DEFAULT_GROUP_KEY, "false")) + ? DEFAULT_GROUP + : getGroup(registryURL); } @Override @@ -105,15 +107,17 @@ public class NacosServiceDiscovery extends AbstractServiceDiscovery { } @Override - protected void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance) throws RuntimeException { + protected void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance) + throws RuntimeException { if (EMPTY_REVISION.equals(getExportedServicesRevision(newServiceInstance)) - || EMPTY_REVISION.equals(oldServiceInstance.getMetadata().get(EXPORTED_SERVICES_REVISION_PROPERTY_NAME))) { + || EMPTY_REVISION.equals( + oldServiceInstance.getMetadata().get(EXPORTED_SERVICES_REVISION_PROPERTY_NAME))) { super.doUpdate(oldServiceInstance, newServiceInstance); return; } - if (!Objects.equals(newServiceInstance.getHost(), oldServiceInstance.getHost()) || - !Objects.equals(newServiceInstance.getPort(), oldServiceInstance.getPort())) { + if (!Objects.equals(newServiceInstance.getHost(), oldServiceInstance.getHost()) + || !Objects.equals(newServiceInstance.getPort(), oldServiceInstance.getPort())) { // Ignore if id changed. Should unregister first. super.doUpdate(oldServiceInstance, newServiceInstance); return; @@ -144,11 +148,10 @@ public class NacosServiceDiscovery extends AbstractServiceDiscovery { @Override public List getInstances(String serviceName) throws NullPointerException { - return ThrowableFunction.execute(namingService, service -> - service.selectInstances(serviceName, group, true) - .stream().map((i) -> NacosNamingServiceUtils.toServiceInstance(registryURL, i)) - .collect(Collectors.toList()) - ); + return ThrowableFunction.execute( + namingService, service -> service.selectInstances(serviceName, group, true).stream() + .map((i) -> NacosNamingServiceUtils.toServiceInstance(registryURL, i)) + .collect(Collectors.toList())); } @Override @@ -169,14 +172,16 @@ public class NacosServiceDiscovery extends AbstractServiceDiscovery { namingService.subscribe(serviceName, group, nacosEventListener); eventListeners.put(serviceName, nacosEventListener); } catch (NacosException e) { - logger.error(REGISTRY_NACOS_EXCEPTION, "", "", "add nacos service instances changed listener fail ", e); + logger.error( + REGISTRY_NACOS_EXCEPTION, "", "", "add nacos service instances changed listener fail ", e); } } } } @Override - public void removeServiceInstancesChangedListener(ServiceInstancesChangedListener listener) throws IllegalArgumentException { + public void removeServiceInstancesChangedListener(ServiceInstancesChangedListener listener) + throws IllegalArgumentException { if (!instanceListeners.remove(listener)) { return; } @@ -189,7 +194,12 @@ public class NacosServiceDiscovery extends AbstractServiceDiscovery { try { namingService.unsubscribe(serviceName, group, nacosEventListener); } catch (NacosException e) { - logger.error(REGISTRY_NACOS_EXCEPTION, "", "", "remove nacos service instances changed listener fail ", e); + logger.error( + REGISTRY_NACOS_EXCEPTION, + "", + "", + "remove nacos service instances changed listener fail ", + e); } } } @@ -229,8 +239,7 @@ public class NacosServiceDiscovery extends AbstractServiceDiscovery { private void handleEvent(NamingEvent event, ServiceInstancesChangedListener listener) { String serviceName = event.getServiceName(); - List serviceInstances = event.getInstances() - .stream() + List serviceInstances = event.getInstances().stream() .map((i) -> NacosNamingServiceUtils.toServiceInstance(registryURL, i)) .collect(Collectors.toList()); listener.onEvent(new ServiceInstancesChangedEvent(serviceName, serviceInstances)); diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryFactory.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryFactory.java index c6a350a3c0..4d0bf68cb7 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryFactory.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryFactory.java @@ -40,5 +40,4 @@ public class NacosServiceDiscoveryFactory extends AbstractServiceDiscoveryFactor protected ServiceDiscovery createDiscovery(URL registryURL) { return new NacosServiceDiscovery(applicationModel, registryURL); } - } diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceName.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceName.java index 03a74dfa31..e74c74e3bf 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceName.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceName.java @@ -59,8 +59,7 @@ public class NacosServiceName { private String value; - public NacosServiceName() { - } + public NacosServiceName() {} public NacosServiceName(URL url) { serviceInterface = url.getParameter(INTERFACE_KEY); @@ -129,8 +128,8 @@ public class NacosServiceName { return false; } - if (!StringUtils.isEquals(this.group, concreteServiceName.group) && - !matchRange(this.group, concreteServiceName.group)) { + if (!StringUtils.isEquals(this.group, concreteServiceName.group) + && !matchRange(this.group, concreteServiceName.group)) { return false; } @@ -201,9 +200,12 @@ public class NacosServiceName { private String toValue() { return new StringBuilder(category) - .append(NAME_SEPARATOR).append(serviceInterface) - .append(NAME_SEPARATOR).append(version) - .append(NAME_SEPARATOR).append(group) + .append(NAME_SEPARATOR) + .append(serviceInterface) + .append(NAME_SEPARATOR) + .append(version) + .append(NAME_SEPARATOR) + .append(group) .toString(); } diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/aot/NacosReflectionTypeDescriberRegistrar.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/aot/NacosReflectionTypeDescriberRegistrar.java index 44e52522a6..ea3f762c9d 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/aot/NacosReflectionTypeDescriberRegistrar.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/aot/NacosReflectionTypeDescriberRegistrar.java @@ -19,6 +19,12 @@ package org.apache.dubbo.registry.nacos.aot; import org.apache.dubbo.aot.api.MemberCategory; import org.apache.dubbo.aot.api.ReflectionTypeDescriberRegistrar; import org.apache.dubbo.aot.api.TypeDescriber; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.api.ability.ClientAbilities; import com.alibaba.nacos.api.config.ability.ClientConfigAbility; @@ -75,22 +81,89 @@ import com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.channel.socket.nio import com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.handler.codec.ByteToMessageDecoder; import com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.handler.codec.http2.Http2ConnectionHandler; import com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.ReferenceCountUtil; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - public class NacosReflectionTypeDescriberRegistrar implements ReflectionTypeDescriberRegistrar { @Override public List getTypeDescribers() { List typeDescribers = new ArrayList<>(); - Class[] classesWithDeclared = {ClientAbilities.class, ClientConfigAbility.class, AbstractConfigRequest.class, ConfigBatchListenRequest.class, ConfigListenContext.class, ConfigPublishRequest.class, ConfigQueryRequest.class, ConfigChangeBatchListenResponse.class, ConfigContext.class, ConfigPublishResponse.class, ConfigQueryResponse.class, ClientNamingAbility.class, Instance.class, ServiceInfo.class, AbstractNamingRequest.class, InstanceRequest.class, NotifySubscriberRequest.class, ServiceQueryRequest.class, SubscribeServiceRequest.class, InstanceResponse.class, NotifySubscriberResponse.class, QueryServiceResponse.class, SubscribeServiceResponse.class, ClientRemoteAbility.class, ConnectionSetupRequest.class, HealthCheckRequest.class, InternalRequest.class, Request.class, ServerCheckRequest.class, ServerRequest.class, HealthCheckResponse.class, Response.class, ServerCheckResponse.class, TlsConfig.class, RpcClientTlsConfig.class}; - Class[] classesWithMethods = {Metadata.class, com.alibaba.nacos.api.grpc.auto.Metadata.Builder.class, com.alibaba.nacos.api.grpc.auto.Payload.class, com.alibaba.nacos.api.grpc.auto.Payload.Builder.class, NamingService.class, com.alibaba.nacos.api.remote.Payload.class, NacosClientAuthServiceImpl.class, RamClientAuthServiceImpl.class, NacosConfigService.class, NacosNamingService.class, DefaultPublisher.class, Any.class, com.alibaba.nacos.shaded.com.google.protobuf.Any.Builder.class, ExtensionRegistry.class, AbstractByteBufAllocator.class, ChannelDuplexHandler.class, ChannelInboundHandlerAdapter.class, NioSocketChannel.class, ByteToMessageDecoder.class, Http2ConnectionHandler.class, ReferenceCountUtil.class}; - Class[] classesWithFields = {PropertyKeyConst.class, AbstractFuture.class, AbstractReferenceCountedByteBuf.class}; + Class[] classesWithDeclared = { + ClientAbilities.class, + ClientConfigAbility.class, + AbstractConfigRequest.class, + ConfigBatchListenRequest.class, + ConfigListenContext.class, + ConfigPublishRequest.class, + ConfigQueryRequest.class, + ConfigChangeBatchListenResponse.class, + ConfigContext.class, + ConfigPublishResponse.class, + ConfigQueryResponse.class, + ClientNamingAbility.class, + Instance.class, + ServiceInfo.class, + AbstractNamingRequest.class, + InstanceRequest.class, + NotifySubscriberRequest.class, + ServiceQueryRequest.class, + SubscribeServiceRequest.class, + InstanceResponse.class, + NotifySubscriberResponse.class, + QueryServiceResponse.class, + SubscribeServiceResponse.class, + ClientRemoteAbility.class, + ConnectionSetupRequest.class, + HealthCheckRequest.class, + InternalRequest.class, + Request.class, + ServerCheckRequest.class, + ServerRequest.class, + HealthCheckResponse.class, + Response.class, + ServerCheckResponse.class, + TlsConfig.class, + RpcClientTlsConfig.class + }; + Class[] classesWithMethods = { + Metadata.class, + com.alibaba.nacos.api.grpc.auto.Metadata.Builder.class, + com.alibaba.nacos.api.grpc.auto.Payload.class, + com.alibaba.nacos.api.grpc.auto.Payload.Builder.class, + NamingService.class, + com.alibaba.nacos.api.remote.Payload.class, + NacosClientAuthServiceImpl.class, + RamClientAuthServiceImpl.class, + NacosConfigService.class, + NacosNamingService.class, + DefaultPublisher.class, + Any.class, + com.alibaba.nacos.shaded.com.google.protobuf.Any.Builder.class, + ExtensionRegistry.class, + AbstractByteBufAllocator.class, + ChannelDuplexHandler.class, + ChannelInboundHandlerAdapter.class, + NioSocketChannel.class, + ByteToMessageDecoder.class, + Http2ConnectionHandler.class, + ReferenceCountUtil.class + }; + Class[] classesWithFields = {PropertyKeyConst.class, AbstractFuture.class, AbstractReferenceCountedByteBuf.class + }; Class[] classesWithDefault = {DnsNameResolverProvider.class, PickFirstLoadBalancerProvider.class}; - String[] privateClasses = {"com.alibaba.nacos.shaded.com.google.common.util.concurrent.AbstractFuture.Waiter", "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.grpc.netty.AbstractNettyHandler", "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.grpc.netty.NettyClientHandler", "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.grpc.netty.WriteBufferingAndExceptionHandler", "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.channel.DefaultChannelPipeline.HeadContext", "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.channel.DefaultChannelPipeline.TailContext", "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.BaseMpscLinkedArrayQueueColdProducerFields", "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.BaseMpscLinkedArrayQueueConsumerFields", "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.BaseMpscLinkedArrayQueueProducerFields", "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.MpscArrayQueueConsumerIndexField", "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.MpscArrayQueueProducerIndexField", "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.MpscArrayQueueProducerLimitField"}; + String[] privateClasses = { + "com.alibaba.nacos.shaded.com.google.common.util.concurrent.AbstractFuture.Waiter", + "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.grpc.netty.AbstractNettyHandler", + "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.grpc.netty.NettyClientHandler", + "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.grpc.netty.WriteBufferingAndExceptionHandler", + "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.channel.DefaultChannelPipeline.HeadContext", + "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.channel.DefaultChannelPipeline.TailContext", + "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.BaseMpscLinkedArrayQueueColdProducerFields", + "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.BaseMpscLinkedArrayQueueConsumerFields", + "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.BaseMpscLinkedArrayQueueProducerFields", + "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.MpscArrayQueueConsumerIndexField", + "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.MpscArrayQueueProducerIndexField", + "com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.shaded.org.jctools.queues.MpscArrayQueueProducerLimitField" + }; for (Class className : classesWithDeclared) { typeDescribers.add(buildTypeDescriberWithDeclared(className)); } @@ -114,24 +187,28 @@ public class NacosReflectionTypeDescriberRegistrar implements ReflectionTypeDesc memberCategories.add(MemberCategory.INVOKE_DECLARED_METHODS); memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); memberCategories.add(MemberCategory.DECLARED_FIELDS); - return new TypeDescriber(cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); + return new TypeDescriber( + cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } private TypeDescriber buildTypeDescriberWithFields(Class cl) { Set memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.DECLARED_FIELDS); - return new TypeDescriber(cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); + return new TypeDescriber( + cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } private TypeDescriber buildTypeDescriberWithMethods(Class cl) { Set memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.INVOKE_DECLARED_METHODS); memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); - return new TypeDescriber(cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); + return new TypeDescriber( + cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } private TypeDescriber buildTypeDescriberWithDefault(Class cl) { - return new TypeDescriber(cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), new HashSet<>()); + return new TypeDescriber( + cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), new HashSet<>()); } private TypeDescriber buildTypeDescriberWithDeclared(String className) { @@ -141,7 +218,7 @@ public class NacosReflectionTypeDescriberRegistrar implements ReflectionTypeDesc memberCategories.add(MemberCategory.DECLARED_FIELDS); return new TypeDescriber(className, null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } - + private TypeDescriber buildTypeDescriberWithFields(String className) { Set memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.DECLARED_FIELDS); @@ -158,6 +235,4 @@ public class NacosReflectionTypeDescriberRegistrar implements ReflectionTypeDesc private TypeDescriber buildTypeDescriberWithDefault(String className) { return new TypeDescriber(className, null, new HashSet<>(), new HashSet<>(), new HashSet<>(), new HashSet<>()); } - - } diff --git a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.java b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.java index f594e473d0..8a87e23d25 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.java +++ b/dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtils.java @@ -39,7 +39,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; */ public class NacosNamingServiceUtils { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NacosNamingServiceUtils.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(NacosNamingServiceUtils.class); private static final String NACOS_GROUP_KEY = "nacos.group"; private static final String NACOS_RETRY_KEY = "nacos.retry"; @@ -78,10 +79,10 @@ public class NacosNamingServiceUtils { * @since 2.7.5 */ public static ServiceInstance toServiceInstance(URL registryUrl, Instance instance) { - DefaultServiceInstance serviceInstance = - new DefaultServiceInstance( + DefaultServiceInstance serviceInstance = new DefaultServiceInstance( NamingUtils.getServiceName(instance.getServiceName()), - instance.getIp(), instance.getPort(), + instance.getIp(), + instance.getPort(), ScopeModelUtil.getApplicationModel(registryUrl.getScopeModel())); serviceInstance.setMetadata(instance.getMetadata()); serviceInstance.setEnabled(instance.isEnabled()); @@ -113,7 +114,8 @@ public class NacosNamingServiceUtils { boolean check = connectionURL.getParameter(NACOS_CHECK_KEY, true); int retryTimes = connectionURL.getPositiveParameter(NACOS_RETRY_KEY, 10); int sleepMsBetweenRetries = connectionURL.getPositiveParameter(NACOS_RETRY_WAIT_KEY, 10); - NacosConnectionManager nacosConnectionManager = new NacosConnectionManager(connectionURL, check, retryTimes, sleepMsBetweenRetries); + NacosConnectionManager nacosConnectionManager = + new NacosConnectionManager(connectionURL, check, retryTimes, sleepMsBetweenRetries); return new NacosNamingServiceWrapper(nacosConnectionManager, retryTimes, sleepMsBetweenRetries); } } diff --git a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/MockNamingService.java b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/MockNamingService.java index e611bae357..81bfe0b631 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/MockNamingService.java +++ b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/MockNamingService.java @@ -16,6 +16,8 @@ */ package org.apache.dubbo.registry.nacos; +import java.util.List; + import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.listener.EventListener; @@ -24,78 +26,48 @@ import com.alibaba.nacos.api.naming.pojo.ListView; import com.alibaba.nacos.api.naming.pojo.ServiceInfo; import com.alibaba.nacos.api.selector.AbstractSelector; -import java.util.List; - public class MockNamingService implements NamingService { @Override - public void registerInstance(String serviceName, String ip, int port) { - - } + public void registerInstance(String serviceName, String ip, int port) {} @Override - public void registerInstance(String serviceName, String groupName, String ip, int port) { - - } + public void registerInstance(String serviceName, String groupName, String ip, int port) {} @Override - public void registerInstance(String serviceName, String ip, int port, String clusterName) { - - } + public void registerInstance(String serviceName, String ip, int port, String clusterName) {} @Override - public void registerInstance(String serviceName, String groupName, String ip, int port, String clusterName) { - - } + public void registerInstance(String serviceName, String groupName, String ip, int port, String clusterName) {} @Override - public void registerInstance(String serviceName, Instance instance) { - - } + public void registerInstance(String serviceName, Instance instance) {} @Override - public void registerInstance(String serviceName, String groupName, Instance instance) throws NacosException { - - } + public void registerInstance(String serviceName, String groupName, Instance instance) throws NacosException {} @Override - public void batchRegisterInstance(String serviceName, String groupName, List instances) { - - } + public void batchRegisterInstance(String serviceName, String groupName, List instances) {} @Override - public void deregisterInstance(String serviceName, String ip, int port) { - - } + public void deregisterInstance(String serviceName, String ip, int port) {} @Override - public void deregisterInstance(String serviceName, String groupName, String ip, int port) { - - } + public void deregisterInstance(String serviceName, String groupName, String ip, int port) {} @Override - public void deregisterInstance(String serviceName, String ip, int port, String clusterName) { - - } + public void deregisterInstance(String serviceName, String ip, int port, String clusterName) {} @Override - public void deregisterInstance(String serviceName, String groupName, String ip, int port, String clusterName) { - - } + public void deregisterInstance(String serviceName, String groupName, String ip, int port, String clusterName) {} @Override - public void deregisterInstance(String serviceName, Instance instance) { - - } + public void deregisterInstance(String serviceName, Instance instance) {} @Override - public void deregisterInstance(String serviceName, String groupName, Instance instance) { - - } + public void deregisterInstance(String serviceName, String groupName, Instance instance) {} @Override - public void batchDeregisterInstance(String s, String s1, List list) throws NacosException { - - } + public void batchDeregisterInstance(String s, String s1, List list) throws NacosException {} @Override public List getAllInstances(String serviceName) { @@ -133,7 +105,8 @@ public class MockNamingService implements NamingService { } @Override - public List getAllInstances(String serviceName, String groupName, List clusters, boolean subscribe) { + public List getAllInstances( + String serviceName, String groupName, List clusters, boolean subscribe) { return null; } @@ -163,17 +136,20 @@ public class MockNamingService implements NamingService { } @Override - public List selectInstances(String serviceName, String groupName, List clusters, boolean healthy) { + public List selectInstances( + String serviceName, String groupName, List clusters, boolean healthy) { return null; } @Override - public List selectInstances(String serviceName, List clusters, boolean healthy, boolean subscribe) { + public List selectInstances( + String serviceName, List clusters, boolean healthy, boolean subscribe) { return null; } @Override - public List selectInstances(String serviceName, String groupName, List clusters, boolean healthy, boolean subscribe) { + public List selectInstances( + String serviceName, String groupName, List clusters, boolean healthy, boolean subscribe) { return null; } @@ -213,49 +189,35 @@ public class MockNamingService implements NamingService { } @Override - public Instance selectOneHealthyInstance(String serviceName, String groupName, List clusters, boolean subscribe) { + public Instance selectOneHealthyInstance( + String serviceName, String groupName, List clusters, boolean subscribe) { return null; } @Override - public void subscribe(String serviceName, EventListener listener) throws NacosException { - - } + public void subscribe(String serviceName, EventListener listener) throws NacosException {} @Override - public void subscribe(String serviceName, String groupName, EventListener listener) throws NacosException { - - } + public void subscribe(String serviceName, String groupName, EventListener listener) throws NacosException {} @Override - public void subscribe(String serviceName, List clusters, EventListener listener) throws NacosException { - - } + public void subscribe(String serviceName, List clusters, EventListener listener) throws NacosException {} @Override - public void subscribe(String serviceName, String groupName, List clusters, EventListener listener) throws NacosException { - - } + public void subscribe(String serviceName, String groupName, List clusters, EventListener listener) + throws NacosException {} @Override - public void unsubscribe(String serviceName, EventListener listener) { - - } + public void unsubscribe(String serviceName, EventListener listener) {} @Override - public void unsubscribe(String serviceName, String groupName, EventListener listener) { - - } + public void unsubscribe(String serviceName, String groupName, EventListener listener) {} @Override - public void unsubscribe(String serviceName, List clusters, EventListener listener) { - - } + public void unsubscribe(String serviceName, List clusters, EventListener listener) {} @Override - public void unsubscribe(String serviceName, String groupName, List clusters, EventListener listener) { - - } + public void unsubscribe(String serviceName, String groupName, List clusters, EventListener listener) {} @Override public ListView getServicesOfServer(int pageNo, int pageSize) { @@ -288,7 +250,5 @@ public class MockNamingService implements NamingService { } @Override - public void shutDown() { - - } + public void shutDown() {} } diff --git a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosConnectionsManagerTest.java b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosConnectionsManagerTest.java index bc2dea58d0..ca17d3c2db 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosConnectionsManagerTest.java +++ b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosConnectionsManagerTest.java @@ -18,6 +18,13 @@ package org.apache.dubbo.registry.nacos; import org.apache.dubbo.common.URL; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.atomic.AtomicInteger; + import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; @@ -27,13 +34,6 @@ import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.atomic.AtomicInteger; - import static com.alibaba.nacos.client.constant.Constants.HealthCheck.DOWN; import static com.alibaba.nacos.client.constant.Constants.HealthCheck.UP; import static org.mockito.ArgumentMatchers.any; @@ -102,7 +102,9 @@ public class NacosConnectionsManagerTest { return atomicInteger.incrementAndGet() > 10 ? UP : DOWN; } }; - nacosFactoryMockedStatic.when(() -> NacosFactory.createNamingService((Properties) any())).thenReturn(mock); + nacosFactoryMockedStatic + .when(() -> NacosFactory.createNamingService((Properties) any())) + .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848"); Assertions.assertThrows(IllegalStateException.class, () -> new NacosConnectionManager(url, true, 5, 10)); @@ -114,6 +116,7 @@ public class NacosConnectionsManagerTest { } } } + @Test void testNoCheck() { try (MockedStatic nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { @@ -123,7 +126,9 @@ public class NacosConnectionsManagerTest { return DOWN; } }; - nacosFactoryMockedStatic.when(() -> NacosFactory.createNamingService((Properties) any())).thenReturn(mock); + nacosFactoryMockedStatic + .when(() -> NacosFactory.createNamingService((Properties) any())) + .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848"); @@ -144,13 +149,14 @@ public class NacosConnectionsManagerTest { return DOWN; } }; - nacosFactoryMockedStatic.when(() -> NacosFactory.createNamingService((Properties) any())).thenReturn(mock); - + nacosFactoryMockedStatic + .when(() -> NacosFactory.createNamingService((Properties) any())) + .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848") - .addParameter("nacos.retry", 5) - .addParameter("nacos.retry-wait", 10) - .addParameter("nacos.check", "false"); + .addParameter("nacos.retry", 5) + .addParameter("nacos.retry-wait", 10) + .addParameter("nacos.check", "false"); try { new NacosConnectionManager(url, false, 5, 10); } catch (Throwable t) { @@ -178,12 +184,13 @@ public class NacosConnectionsManagerTest { return UP; } }; - nacosFactoryMockedStatic.when(() -> NacosFactory.createNamingService((Properties) any())).thenReturn(mock); - + nacosFactoryMockedStatic + .when(() -> NacosFactory.createNamingService((Properties) any())) + .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848") - .addParameter("nacos.retry", 5) - .addParameter("nacos.retry-wait", 10); + .addParameter("nacos.retry", 5) + .addParameter("nacos.retry-wait", 10); Assertions.assertThrows(IllegalStateException.class, () -> new NacosConnectionManager(url, true, 5, 10)); try { diff --git a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosNamingServiceWrapperTest.java b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosNamingServiceWrapperTest.java index 6e3c730d83..f55f9f1385 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosNamingServiceWrapperTest.java +++ b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosNamingServiceWrapperTest.java @@ -18,14 +18,6 @@ package org.apache.dubbo.registry.nacos; import org.apache.dubbo.common.URL; -import com.alibaba.nacos.api.exception.NacosException; -import com.alibaba.nacos.api.naming.NamingService; -import com.alibaba.nacos.api.naming.listener.EventListener; -import com.alibaba.nacos.api.naming.pojo.Instance; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -34,6 +26,14 @@ import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; +import com.alibaba.nacos.api.exception.NacosException; +import com.alibaba.nacos.api.naming.NamingService; +import com.alibaba.nacos.api.naming.listener.EventListener; +import com.alibaba.nacos.api.naming.pojo.Instance; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + class NacosNamingServiceWrapperTest { @Test void testSubscribe() throws NacosException { @@ -102,7 +102,8 @@ class NacosNamingServiceWrapperTest { Assertions.assertEquals(1, namingServiceList.size()); - NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(nacosConnectionManager, false, 0, 0); + NacosNamingServiceWrapper nacosNamingServiceWrapper = + new NacosNamingServiceWrapper(nacosConnectionManager, false, 0, 0); Instance instance1 = new Instance(); instance1.setIp("ip1"); @@ -128,13 +129,16 @@ class NacosNamingServiceWrapperTest { Mockito.verify(namingServiceList.get(2), Mockito.times(1)).registerInstance("service_name", "test", instance3); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); - Mockito.verify(namingServiceList.get(0), Mockito.times(1)).deregisterInstance("service_name", "test", instance1); + Mockito.verify(namingServiceList.get(0), Mockito.times(1)) + .deregisterInstance("service_name", "test", instance1); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); - Mockito.verify(namingServiceList.get(1), Mockito.times(1)).deregisterInstance("service_name", "test", instance2); + Mockito.verify(namingServiceList.get(1), Mockito.times(1)) + .deregisterInstance("service_name", "test", instance2); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance3); - Mockito.verify(namingServiceList.get(2), Mockito.times(1)).deregisterInstance("service_name", "test", instance3); + Mockito.verify(namingServiceList.get(2), Mockito.times(1)) + .deregisterInstance("service_name", "test", instance3); } @Test @@ -145,7 +149,9 @@ class NacosNamingServiceWrapperTest { protected NamingService createNamingService() { NamingService namingService = Mockito.mock(NamingService.class); try { - Mockito.doThrow(new NacosException()).when(namingService).batchRegisterInstance(Mockito.anyString(), Mockito.anyString(), Mockito.any(List.class)); + Mockito.doThrow(new NacosException()) + .when(namingService) + .batchRegisterInstance(Mockito.anyString(), Mockito.anyString(), Mockito.any(List.class)); } catch (NacosException e) { throw new RuntimeException(e); } @@ -156,7 +162,8 @@ class NacosNamingServiceWrapperTest { Assertions.assertEquals(1, namingServiceList.size()); - NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(nacosConnectionManager, true, 0, 0); + NacosNamingServiceWrapper nacosNamingServiceWrapper = + new NacosNamingServiceWrapper(nacosConnectionManager, true, 0, 0); Instance instance1 = new Instance(); instance1.setIp("ip1"); @@ -182,23 +189,30 @@ class NacosNamingServiceWrapperTest { Mockito.verify(namingServiceList.get(2), Mockito.times(1)).registerInstance("service_name", "test", instance3); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); - Mockito.verify(namingServiceList.get(0), Mockito.times(1)).deregisterInstance("service_name", "test", instance1); + Mockito.verify(namingServiceList.get(0), Mockito.times(1)) + .deregisterInstance("service_name", "test", instance1); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); - Mockito.verify(namingServiceList.get(1), Mockito.times(1)).deregisterInstance("service_name", "test", instance2); + Mockito.verify(namingServiceList.get(1), Mockito.times(1)) + .deregisterInstance("service_name", "test", instance2); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); - Mockito.verify(namingServiceList.get(0), Mockito.times(2)).registerInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.any()); - Mockito.verify(namingServiceList.get(1), Mockito.times(2)).registerInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.any()); + Mockito.verify(namingServiceList.get(0), Mockito.times(2)) + .registerInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.any()); + Mockito.verify(namingServiceList.get(1), Mockito.times(2)) + .registerInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.any()); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); - Mockito.verify(namingServiceList.get(0), Mockito.times(2)).deregisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.any()); - Mockito.verify(namingServiceList.get(1), Mockito.times(2)).deregisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.any()); + Mockito.verify(namingServiceList.get(0), Mockito.times(2)) + .deregisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.any()); + Mockito.verify(namingServiceList.get(1), Mockito.times(2)) + .deregisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.any()); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance3); - Mockito.verify(namingServiceList.get(2), Mockito.times(1)).deregisterInstance("service_name", "test", instance3); + Mockito.verify(namingServiceList.get(2), Mockito.times(1)) + .deregisterInstance("service_name", "test", instance3); } @Test @@ -215,7 +229,8 @@ class NacosNamingServiceWrapperTest { Assertions.assertEquals(1, namingServiceList.size()); - NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(nacosConnectionManager, true, 0, 0); + NacosNamingServiceWrapper nacosNamingServiceWrapper = + new NacosNamingServiceWrapper(nacosConnectionManager, true, 0, 0); Instance instance1 = new Instance(); instance1.setIp("ip1"); @@ -228,41 +243,74 @@ class NacosNamingServiceWrapperTest { instance2.setPort(2); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); - Mockito.verify(namingServiceList.get(0), Mockito.times(1)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(1)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2)))); Instance instance3 = new Instance(); instance3.setIp("ip3"); instance3.setPort(3); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance3); Assertions.assertEquals(1, namingServiceList.size()); - Mockito.verify(namingServiceList.get(0), Mockito.times(1)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2, instance3)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(1)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); - Mockito.verify(namingServiceList.get(0), Mockito.times(1)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance2, instance3)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(1)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); - Mockito.verify(namingServiceList.get(0), Mockito.times(1)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); + Mockito.verify(namingServiceList.get(0), Mockito.times(1)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Assertions.assertEquals(1, namingServiceList.size()); - Mockito.verify(namingServiceList.get(0), Mockito.times(1)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(1)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1)))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); - Mockito.verify(namingServiceList.get(0), Mockito.times(1)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1, instance2)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(1)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); - Mockito.verify(namingServiceList.get(0), Mockito.times(1)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance2)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(1)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); - Mockito.verify(namingServiceList.get(0), Mockito.times(2)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); + Mockito.verify(namingServiceList.get(0), Mockito.times(2)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance3); - Mockito.verify(namingServiceList.get(0), Mockito.times(1)).deregisterInstance("service_name", "test", instance3); + Mockito.verify(namingServiceList.get(0), Mockito.times(1)) + .deregisterInstance("service_name", "test", instance3); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance3); - Mockito.verify(namingServiceList.get(0), Mockito.times(1)).deregisterInstance("service_name", "test", instance3); - + Mockito.verify(namingServiceList.get(0), Mockito.times(1)) + .deregisterInstance("service_name", "test", instance3); // rerun nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); @@ -270,40 +318,73 @@ class NacosNamingServiceWrapperTest { nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); - Mockito.verify(namingServiceList.get(0), Mockito.times(2)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(2)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2)))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance3); Assertions.assertEquals(1, namingServiceList.size()); - Mockito.verify(namingServiceList.get(0), Mockito.times(2)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2, instance3)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(2)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); - Mockito.verify(namingServiceList.get(0), Mockito.times(2)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance2, instance3)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(2)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); - Mockito.verify(namingServiceList.get(0), Mockito.times(3)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); + Mockito.verify(namingServiceList.get(0), Mockito.times(3)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Assertions.assertEquals(1, namingServiceList.size()); - Mockito.verify(namingServiceList.get(0), Mockito.times(2)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(2)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1)))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); - Mockito.verify(namingServiceList.get(0), Mockito.times(2)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1, instance2)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(2)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); - Mockito.verify(namingServiceList.get(0), Mockito.times(2)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance2)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(2)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); - Mockito.verify(namingServiceList.get(0), Mockito.times(4)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); + Mockito.verify(namingServiceList.get(0), Mockito.times(4)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance3); - Mockito.verify(namingServiceList.get(0), Mockito.times(2)).deregisterInstance("service_name", "test", instance3); + Mockito.verify(namingServiceList.get(0), Mockito.times(2)) + .deregisterInstance("service_name", "test", instance3); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance3); - Mockito.verify(namingServiceList.get(0), Mockito.times(2)).deregisterInstance("service_name", "test", instance3); + Mockito.verify(namingServiceList.get(0), Mockito.times(2)) + .deregisterInstance("service_name", "test", instance3); } - @Test void testUnregister() throws NacosException { List namingServiceList = new LinkedList<>(); @@ -318,7 +399,8 @@ class NacosNamingServiceWrapperTest { Assertions.assertEquals(1, namingServiceList.size()); - NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(nacosConnectionManager, true, 0, 0); + NacosNamingServiceWrapper nacosNamingServiceWrapper = + new NacosNamingServiceWrapper(nacosConnectionManager, true, 0, 0); Instance instance1 = new Instance(); instance1.setIp("ip1"); @@ -331,43 +413,76 @@ class NacosNamingServiceWrapperTest { instance2.setPort(2); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); - Mockito.verify(namingServiceList.get(0), Mockito.times(1)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(1)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2)))); Instance instance3 = new Instance(); instance3.setIp("ip3"); instance3.setPort(3); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance3); Assertions.assertEquals(1, namingServiceList.size()); - Mockito.verify(namingServiceList.get(0), Mockito.times(1)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2, instance3)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(1)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance1); - Mockito.verify(namingServiceList.get(0), Mockito.times(1)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance2, instance3)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(1)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance2); - Mockito.verify(namingServiceList.get(0), Mockito.times(1)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); + Mockito.verify(namingServiceList.get(0), Mockito.times(1)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Assertions.assertEquals(1, namingServiceList.size()); - Mockito.verify(namingServiceList.get(0), Mockito.times(1)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(1)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1)))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); - Mockito.verify(namingServiceList.get(0), Mockito.times(1)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1, instance2)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(1)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip2", 1); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip1", 2); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip1", 1); - Mockito.verify(namingServiceList.get(0), Mockito.times(1)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance2)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(1)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip2", 2); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip2", 2); - Mockito.verify(namingServiceList.get(0), Mockito.times(2)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); + Mockito.verify(namingServiceList.get(0), Mockito.times(2)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip3", 3); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip3", 3); - Mockito.verify(namingServiceList.get(0), Mockito.times(1)).deregisterInstance("service_name", "test", instance3); + Mockito.verify(namingServiceList.get(0), Mockito.times(1)) + .deregisterInstance("service_name", "test", instance3); // rerun nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); @@ -375,135 +490,175 @@ class NacosNamingServiceWrapperTest { nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); - Mockito.verify(namingServiceList.get(0), Mockito.times(2)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(2)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2)))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance3); Assertions.assertEquals(1, namingServiceList.size()); - Mockito.verify(namingServiceList.get(0), Mockito.times(2)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2, instance3)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(2)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance1, instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip1", 1); - Mockito.verify(namingServiceList.get(0), Mockito.times(2)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance2, instance3)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(2)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance2, instance3)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip2", 2); - Mockito.verify(namingServiceList.get(0), Mockito.times(3)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); + Mockito.verify(namingServiceList.get(0), Mockito.times(3)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance1); Assertions.assertEquals(1, namingServiceList.size()); - Mockito.verify(namingServiceList.get(0), Mockito.times(2)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(2)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1)))); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance2); Assertions.assertEquals(1, namingServiceList.size()); - Mockito.verify(namingServiceList.get(0), Mockito.times(2)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1, instance2)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(2)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance1, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip1", 1); - Mockito.verify(namingServiceList.get(0), Mockito.times(2)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance2)))); + Mockito.verify(namingServiceList.get(0), Mockito.times(2)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(new ArrayList<>(Arrays.asList(instance3, instance2)))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip2", 2); - Mockito.verify(namingServiceList.get(0), Mockito.times(4)).batchRegisterInstance(Mockito.eq("service_name"), Mockito.eq("test"), Mockito.eq(Collections.singletonList(instance3))); + Mockito.verify(namingServiceList.get(0), Mockito.times(4)) + .batchRegisterInstance( + Mockito.eq("service_name"), + Mockito.eq("test"), + Mockito.eq(Collections.singletonList(instance3))); nacosNamingServiceWrapper.deregisterInstance("service_name", "test", "ip3", 3); - Mockito.verify(namingServiceList.get(0), Mockito.times(2)).deregisterInstance("service_name", "test", instance3); + Mockito.verify(namingServiceList.get(0), Mockito.times(2)) + .deregisterInstance("service_name", "test", instance3); } @Test void testConcurrency() throws NacosException, InterruptedException { NacosConnectionManager connectionManager = Mockito.mock(NacosConnectionManager.class); - CountDownLatch startLatch = new CountDownLatch(1); CountDownLatch stopLatch = new CountDownLatch(1); NamingService namingService = Mockito.mock(NamingService.class); Mockito.when(connectionManager.getNamingService()).thenReturn(namingService); - NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(connectionManager, false, 0, 0); + NacosNamingServiceWrapper nacosNamingServiceWrapper = + new NacosNamingServiceWrapper(connectionManager, false, 0, 0); Instance instance = new Instance(); nacosNamingServiceWrapper.registerInstance("service_name", "test", instance); - NacosNamingServiceWrapper.InstancesInfo instancesInfo = nacosNamingServiceWrapper.getRegisterStatus().get(new NacosNamingServiceWrapper.InstanceId("service_name", "test")); + NacosNamingServiceWrapper.InstancesInfo instancesInfo = nacosNamingServiceWrapper + .getRegisterStatus() + .get(new NacosNamingServiceWrapper.InstanceId("service_name", "test")); Assertions.assertEquals(1, instancesInfo.getInstances().size()); - nacosNamingServiceWrapper.getRegisterStatus().put(new NacosNamingServiceWrapper.InstanceId("service_name", "test"), new NacosNamingServiceWrapper.InstancesInfo(){ - private final NacosNamingServiceWrapper.InstancesInfo delegate = instancesInfo; + nacosNamingServiceWrapper + .getRegisterStatus() + .put( + new NacosNamingServiceWrapper.InstanceId("service_name", "test"), + new NacosNamingServiceWrapper.InstancesInfo() { + private final NacosNamingServiceWrapper.InstancesInfo delegate = instancesInfo; - @Override - public void lock() { - delegate.lock(); - } + @Override + public void lock() { + delegate.lock(); + } - @Override - public void unlock() { - delegate.unlock(); - } + @Override + public void unlock() { + delegate.unlock(); + } - @Override - public List getInstances() { - try { - if (startLatch.getCount() > 0) { - Thread.sleep(1000); - startLatch.countDown(); - Thread.sleep(1000); + @Override + public List getInstances() { + try { + if (startLatch.getCount() > 0) { + Thread.sleep(1000); + startLatch.countDown(); + Thread.sleep(1000); + } + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + return delegate.getInstances(); + } + + @Override + public boolean isBatchRegistered() { + return delegate.isBatchRegistered(); + } + + @Override + public void setBatchRegistered(boolean batchRegistered) { + delegate.setBatchRegistered(batchRegistered); + } + + @Override + public boolean isValid() { + return delegate.isValid(); + } + + @Override + public void setValid(boolean valid) { + delegate.setValid(valid); + } + }); + + new Thread(() -> { + try { + startLatch.await(); + nacosNamingServiceWrapper.registerInstance("service_name", "test", instance); + stopLatch.countDown(); + } catch (Exception e) { + throw new RuntimeException(e); } - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - return delegate.getInstances(); - } + }) + .start(); - @Override - public boolean isBatchRegistered() { - return delegate.isBatchRegistered(); - } - - @Override - public void setBatchRegistered(boolean batchRegistered) { - delegate.setBatchRegistered(batchRegistered); - } - - @Override - public boolean isValid() { - return delegate.isValid(); - } - - @Override - public void setValid(boolean valid) { - delegate.setValid(valid); - } - }); - - new Thread(()->{ - try { - startLatch.await(); - nacosNamingServiceWrapper.registerInstance("service_name", "test", instance); - stopLatch.countDown(); - } catch (Exception e) { - throw new RuntimeException(e); - } - }).start(); - - new Thread(()->{ - try { - nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance); - } catch (NacosException e) { - throw new RuntimeException(e); - } - }).start(); + new Thread(() -> { + try { + nacosNamingServiceWrapper.deregisterInstance("service_name", "test", instance); + } catch (NacosException e) { + throw new RuntimeException(e); + } + }) + .start(); stopLatch.await(); - NacosNamingServiceWrapper.InstancesInfo instancesInfoNew = nacosNamingServiceWrapper.getRegisterStatus().get(new NacosNamingServiceWrapper.InstanceId("service_name", "test")); + NacosNamingServiceWrapper.InstancesInfo instancesInfoNew = nacosNamingServiceWrapper + .getRegisterStatus() + .get(new NacosNamingServiceWrapper.InstanceId("service_name", "test")); Assertions.assertEquals(1, instancesInfoNew.getInstances().size()); Assertions.assertNotEquals(instancesInfo, instancesInfoNew); } - @Test void testSuccess() { NamingService namingService = new MockNamingService() { @Override - public void registerInstance(String serviceName, String groupName, Instance instance) { - - } + public void registerInstance(String serviceName, String groupName, Instance instance) {} @Override public List getAllInstances(String serviceName, String groupName) { @@ -511,7 +666,8 @@ class NacosNamingServiceWrapperTest { } }; - NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); + NacosNamingServiceWrapper nacosNamingServiceWrapper = + new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); try { nacosNamingServiceWrapper.registerInstance("Test", "Test", null); } catch (NacosException e) { @@ -528,7 +684,8 @@ class NacosNamingServiceWrapperTest { void testFailNoRetry() { NamingService namingService = new MockNamingService() { @Override - public void registerInstance(String serviceName, String groupName, Instance instance) throws NacosException { + public void registerInstance(String serviceName, String groupName, Instance instance) + throws NacosException { throw new NacosException(); } @@ -538,12 +695,13 @@ class NacosNamingServiceWrapperTest { } }; - NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); - Assertions.assertThrows(NacosException.class, () -> nacosNamingServiceWrapper.registerInstance("Test", "Test", null)); + NacosNamingServiceWrapper nacosNamingServiceWrapper = + new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); + Assertions.assertThrows( + NacosException.class, () -> nacosNamingServiceWrapper.registerInstance("Test", "Test", null)); Assertions.assertThrows(NacosException.class, () -> nacosNamingServiceWrapper.getAllInstances("Test", "Test")); } - @Test void testFailRetry() { NamingService namingService = new MockNamingService() { @@ -551,7 +709,8 @@ class NacosNamingServiceWrapperTest { private final AtomicInteger count2 = new AtomicInteger(0); @Override - public void registerInstance(String serviceName, String groupName, Instance instance) throws NacosException { + public void registerInstance(String serviceName, String groupName, Instance instance) + throws NacosException { if (count1.incrementAndGet() < 10) { throw new NacosException(); } @@ -566,8 +725,10 @@ class NacosNamingServiceWrapperTest { } }; - NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 5, 10); - Assertions.assertThrows(NacosException.class, () -> nacosNamingServiceWrapper.registerInstance("Test", "Test", null)); + NacosNamingServiceWrapper nacosNamingServiceWrapper = + new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 5, 10); + Assertions.assertThrows( + NacosException.class, () -> nacosNamingServiceWrapper.registerInstance("Test", "Test", null)); try { nacosNamingServiceWrapper.registerInstance("Test", "Test", null); } catch (NacosException e) { @@ -580,6 +741,5 @@ class NacosNamingServiceWrapperTest { } catch (NacosException e) { Assertions.fail(e); } - } } diff --git a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosRegistryFactoryTest.java b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosRegistryFactoryTest.java index 2af57626a4..a8665b03f2 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosRegistryFactoryTest.java +++ b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosRegistryFactoryTest.java @@ -18,6 +18,7 @@ package org.apache.dubbo.registry.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -36,8 +37,7 @@ class NacosRegistryFactoryTest { } @AfterEach - public void teardown() { - } + public void teardown() {} @Test void testCreateRegistryCacheKey() { @@ -49,10 +49,10 @@ class NacosRegistryFactoryTest { @Test void testCreateRegistryCacheKeyWithNamespace() { - URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostAddress() + ":8080?namespace=test&nacos.check=false"); + URL url = URL.valueOf( + "dubbo://" + NetUtils.getLocalAddress().getHostAddress() + ":8080?namespace=test&nacos.check=false"); String registryCacheKey1 = nacosRegistryFactory.createRegistryCacheKey(url); String registryCacheKey2 = nacosRegistryFactory.createRegistryCacheKey(url); Assertions.assertEquals(registryCacheKey1, registryCacheKey2); } - } diff --git a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosRegistryTest.java b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosRegistryTest.java index c5355d6e36..110cff95e1 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosRegistryTest.java +++ b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosRegistryTest.java @@ -16,26 +16,26 @@ */ package org.apache.dubbo.registry.nacos; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.utils.NetUtils; +import org.apache.dubbo.registry.NotifyListener; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.registry.NotifyListener; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; import com.alibaba.nacos.client.naming.NacosNamingService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; @@ -55,8 +55,9 @@ class NacosRegistryTest { private static final String serviceInterface = "org.apache.dubbo.registry.nacos.NacosService"; - private final URL serviceUrl = URL.valueOf("nacos://127.0.0.1:3333/" + serviceInterface + "?interface=" + - serviceInterface + "¬ify=false&methods=test1,test2&category=providers&version=1.0.0&group=default&side=provider"); + private final URL serviceUrl = + URL.valueOf("nacos://127.0.0.1:3333/" + serviceInterface + "?interface=" + serviceInterface + + "¬ify=false&methods=test1,test2&category=providers&version=1.0.0&group=default&side=provider"); private NacosRegistryFactory nacosRegistryFactory; @@ -76,11 +77,8 @@ class NacosRegistryTest { this.nacosRegistry = (NacosRegistry) nacosRegistryFactory.createRegistry(registryUrl); } - @AfterEach - public void tearDown() throws Exception { - - } + public void tearDown() throws Exception {} @Test void testRegister() { @@ -103,7 +101,8 @@ class NacosRegistryTest { // ignore } - NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); + NacosNamingServiceWrapper nacosNamingServiceWrapper = + new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); nacosRegistry = new NacosRegistry(this.registryUrl, nacosNamingServiceWrapper); Set registered; @@ -134,16 +133,15 @@ class NacosRegistryTest { instance.setIp(ip); instance.setPort(port); instance.setMetadata(new HashMap<>(newUrl.getParameters())); - doNothing().when(namingService).registerInstance(serviceName, - Constants.DEFAULT_GROUP, instance); + doNothing().when(namingService).registerInstance(serviceName, Constants.DEFAULT_GROUP, instance); - doNothing().when(namingService).deregisterInstance(serviceName, - Constants.DEFAULT_GROUP, ip, port); + doNothing().when(namingService).deregisterInstance(serviceName, Constants.DEFAULT_GROUP, ip, port); } catch (NacosException e) { // ignore } - NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); + NacosNamingServiceWrapper nacosNamingServiceWrapper = + new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); nacosRegistry = new NacosRegistry(this.registryUrl, nacosNamingServiceWrapper); nacosRegistry.register(serviceUrl); @@ -177,13 +175,15 @@ class NacosRegistryTest { List instances = new ArrayList<>(); instances.add(instance); - when(namingService.getAllInstances(serviceName, - this.registryUrl.getParameter(GROUP_KEY, Constants.DEFAULT_GROUP))).thenReturn(instances); + when(namingService.getAllInstances( + serviceName, this.registryUrl.getParameter(GROUP_KEY, Constants.DEFAULT_GROUP))) + .thenReturn(instances); } catch (NacosException e) { // ignore } - NacosNamingServiceWrapper nacosNamingServiceWrapper = new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); + NacosNamingServiceWrapper nacosNamingServiceWrapper = + new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); nacosRegistry = new NacosRegistry(this.registryUrl, nacosNamingServiceWrapper); NotifyListener listener = mock(NotifyListener.class); @@ -214,15 +214,16 @@ class NacosRegistryTest { List instances = new ArrayList<>(); instances.add(instance); - when(namingService.getAllInstances(serviceName, - this.registryUrl.getParameter(GROUP_KEY, Constants.DEFAULT_GROUP))).thenReturn(instances); + when(namingService.getAllInstances( + serviceName, this.registryUrl.getParameter(GROUP_KEY, Constants.DEFAULT_GROUP))) + .thenReturn(instances); } catch (NacosException e) { // ignore } - NacosNamingServiceWrapper nacosNamingServiceWrapper = new - NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); + NacosNamingServiceWrapper nacosNamingServiceWrapper = + new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); nacosRegistry = new NacosRegistry(this.registryUrl, nacosNamingServiceWrapper); NotifyListener listener = mock(NotifyListener.class); @@ -238,12 +239,11 @@ class NacosRegistryTest { Assertions.assertEquals(0, subscribed.get(serviceUrl).size()); } - @Test void testIsConformRules() { NamingService namingService = mock(NacosNamingService.class); - URL serviceUrlWithoutCategory = URL.valueOf("nacos://127.0.0.1:3333/" + serviceInterface + "?interface=" + - serviceInterface + "¬ify=false&methods=test1,test2&version=1.0.0&group=default"); + URL serviceUrlWithoutCategory = URL.valueOf("nacos://127.0.0.1:3333/" + serviceInterface + "?interface=" + + serviceInterface + "¬ify=false&methods=test1,test2&version=1.0.0&group=default"); try { String serviceName = "providers:org.apache.dubbo.registry.nacos.NacosService:1.0.0:default"; String category = this.serviceUrl.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY); @@ -259,8 +259,9 @@ class NacosRegistryTest { List instances = new ArrayList<>(); instances.add(instance); - when(namingService.getAllInstances(serviceName, - this.registryUrl.getParameter(GROUP_KEY, Constants.DEFAULT_GROUP))).thenReturn(instances); + when(namingService.getAllInstances( + serviceName, this.registryUrl.getParameter(GROUP_KEY, Constants.DEFAULT_GROUP))) + .thenReturn(instances); String serviceNameWithoutVersion = "providers:org.apache.dubbo.registry.nacos.NacosService:default"; String serviceName1 = "providers:org.apache.dubbo.registry.nacos.NacosService:1.0.0:default"; @@ -269,14 +270,15 @@ class NacosRegistryTest { serviceNames.add(serviceName1); ListView result = new ListView<>(); result.setData(serviceNames); - when(namingService.getServicesOfServer(1, Integer.MAX_VALUE, - registryUrl.getParameter(GROUP_KEY, Constants.DEFAULT_GROUP))).thenReturn(result); + when(namingService.getServicesOfServer( + 1, Integer.MAX_VALUE, registryUrl.getParameter(GROUP_KEY, Constants.DEFAULT_GROUP))) + .thenReturn(result); } catch (NacosException e) { // ignore } - NacosNamingServiceWrapper nacosNamingServiceWrapper = new - NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); + NacosNamingServiceWrapper nacosNamingServiceWrapper = + new NacosNamingServiceWrapper(new NacosConnectionManager(namingService), 0, 0); nacosRegistry = new NacosRegistry(this.registryUrl, nacosNamingServiceWrapper); Set registered; @@ -287,15 +289,13 @@ class NacosRegistryTest { Assertions.assertTrue(registered.contains(serviceUrlWithoutCategory)); Assertions.assertEquals(2, registered.size()); - URL serviceUrlWithWildcard = URL.valueOf("nacos://127.0.0.1:3333/" + - serviceInterface + - "?interface=org.apache.dubbo.registry.nacos.NacosService" + - "¬ify=false&methods=test1,test2&category=providers&version=*&group=default"); + URL serviceUrlWithWildcard = URL.valueOf("nacos://127.0.0.1:3333/" + serviceInterface + + "?interface=org.apache.dubbo.registry.nacos.NacosService" + + "¬ify=false&methods=test1,test2&category=providers&version=*&group=default"); - URL serviceUrlWithOutWildcard = URL.valueOf("nacos://127.0.0.1:3333/" + - serviceInterface + - "?interface=org.apache.dubbo.registry.nacos.NacosService" + - "¬ify=false&methods=test1,test2&category=providers&version=1.0.0&group=default"); + URL serviceUrlWithOutWildcard = URL.valueOf("nacos://127.0.0.1:3333/" + serviceInterface + + "?interface=org.apache.dubbo.registry.nacos.NacosService" + + "¬ify=false&methods=test1,test2&category=providers&version=1.0.0&group=default"); NotifyListener listener = mock(NotifyListener.class); nacosRegistry.subscribe(serviceUrlWithWildcard, listener); diff --git a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryFactoryTest.java b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryFactoryTest.java index 6f9003490c..271d829113 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryFactoryTest.java +++ b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryFactoryTest.java @@ -20,6 +20,7 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.registry.client.ServiceDiscovery; import org.apache.dubbo.rpc.model.ApplicationModel; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -35,7 +36,9 @@ class NacosServiceDiscoveryFactoryTest { public void setup() { nacosServiceDiscoveryFactory = new NacosServiceDiscoveryFactory(); ApplicationModel applicationModel = ApplicationModel.defaultModel(); - applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("NacosServiceDiscoveryFactoryTest")); + applicationModel + .getApplicationConfigManager() + .setApplication(new ApplicationConfig("NacosServiceDiscoveryFactoryTest")); nacosServiceDiscoveryFactory.setApplicationModel(applicationModel); } diff --git a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryTest.java b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryTest.java index d994a08f59..97b8a3e540 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryTest.java +++ b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/NacosServiceDiscoveryTest.java @@ -16,12 +16,6 @@ */ package org.apache.dubbo.registry.nacos; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.config.ApplicationConfig; @@ -31,6 +25,16 @@ import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent; import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ScopeModelUtil; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import com.alibaba.nacos.api.exception.NacosException; +import com.alibaba.nacos.api.naming.pojo.Instance; +import com.alibaba.nacos.api.naming.pojo.ListView; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; @@ -39,10 +43,6 @@ import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.internal.util.collections.Sets; -import com.alibaba.nacos.api.exception.NacosException; -import com.alibaba.nacos.api.naming.pojo.Instance; -import com.alibaba.nacos.api.naming.pojo.ListView; - import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -72,14 +72,16 @@ class NacosServiceDiscoveryTest { protected String group = DEFAULT_GROUP; private DefaultServiceInstance createServiceInstance(String serviceName, String host, int port) { - return new DefaultServiceInstance(serviceName, host, port, ScopeModelUtil.getApplicationModel(registryUrl.getScopeModel())); + return new DefaultServiceInstance( + serviceName, host, port, ScopeModelUtil.getApplicationModel(registryUrl.getScopeModel())); } public static class NacosServiceDiscoveryGroupTest1 extends NacosServiceDiscoveryTest { public NacosServiceDiscoveryGroupTest1() { super(); group = "test-group1"; - registryUrl = URL.valueOf("nacos://127.0.0.1:" + NetUtils.getAvailablePort() + "?nacos.check=false").addParameter("group", group); + registryUrl = URL.valueOf("nacos://127.0.0.1:" + NetUtils.getAvailablePort() + "?nacos.check=false") + .addParameter("group", group); } } @@ -87,17 +89,17 @@ class NacosServiceDiscoveryTest { public NacosServiceDiscoveryGroupTest2() { super(); group = "test-group2"; - registryUrl = URL.valueOf("nacos://127.0.0.1:" + NetUtils.getAvailablePort() + "?nacos.check=false").addParameter("group", group); + registryUrl = URL.valueOf("nacos://127.0.0.1:" + NetUtils.getAvailablePort() + "?nacos.check=false") + .addParameter("group", group); } } - - public static class NacosServiceDiscoveryGroupTest3 extends NacosServiceDiscoveryTest { public NacosServiceDiscoveryGroupTest3() { super(); group = DEFAULT_GROUP; - registryUrl = URL.valueOf("nacos://127.0.0.1:" + NetUtils.getAvailablePort() + "?nacos.check=false").addParameter("group", "test-group3"); + registryUrl = URL.valueOf("nacos://127.0.0.1:" + NetUtils.getAvailablePort() + "?nacos.check=false") + .addParameter("group", "test-group3"); } @BeforeAll @@ -118,7 +120,7 @@ class NacosServiceDiscoveryTest { registryUrl.setScopeModel(applicationModel); -// this.nacosServiceDiscovery = new NacosServiceDiscovery(SERVICE_NAME, registryUrl); + // this.nacosServiceDiscovery = new NacosServiceDiscovery(SERVICE_NAME, registryUrl); this.nacosServiceDiscovery = new NacosServiceDiscovery(applicationModel, registryUrl); Field namingService = nacosServiceDiscovery.getClass().getDeclaredField("namingService"); namingService.setAccessible(true); @@ -133,7 +135,8 @@ class NacosServiceDiscoveryTest { @Test void testDoRegister() throws NacosException { - DefaultServiceInstance serviceInstance = createServiceInstance(SERVICE_NAME, LOCALHOST, NetUtils.getAvailablePort()); + DefaultServiceInstance serviceInstance = + createServiceInstance(SERVICE_NAME, LOCALHOST, NetUtils.getAvailablePort()); // register nacosServiceDiscovery.doRegister(serviceInstance); @@ -149,7 +152,8 @@ class NacosServiceDiscoveryTest { @Test void testDoUnRegister() throws NacosException { // register - DefaultServiceInstance serviceInstance = createServiceInstance(SERVICE_NAME, LOCALHOST, NetUtils.getAvailablePort()); + DefaultServiceInstance serviceInstance = + createServiceInstance(SERVICE_NAME, LOCALHOST, NetUtils.getAvailablePort()); // register nacosServiceDiscovery.doRegister(serviceInstance); @@ -167,7 +171,8 @@ class NacosServiceDiscoveryTest { @Test void testGetServices() throws NacosException { - DefaultServiceInstance serviceInstance = createServiceInstance(SERVICE_NAME, LOCALHOST, NetUtils.getAvailablePort()); + DefaultServiceInstance serviceInstance = + createServiceInstance(SERVICE_NAME, LOCALHOST, NetUtils.getAvailablePort()); // register nacosServiceDiscovery.doRegister(serviceInstance); @@ -181,7 +186,8 @@ class NacosServiceDiscoveryTest { serviceNames.add(serviceName); ListView result = new ListView<>(); result.setData(serviceNames); - when(namingServiceWrapper.getServicesOfServer(anyInt(), anyInt(), eq(group))).thenReturn(result); + when(namingServiceWrapper.getServicesOfServer(anyInt(), anyInt(), eq(group))) + .thenReturn(result); Set services = nacosServiceDiscovery.getServices(); assertEquals(2, services.size()); } @@ -191,12 +197,12 @@ class NacosServiceDiscoveryTest { List serviceInstances = new LinkedList<>(); // Add Listener nacosServiceDiscovery.addServiceInstancesChangedListener( - new ServiceInstancesChangedListener(Sets.newSet(SERVICE_NAME), nacosServiceDiscovery) { - @Override - public void onEvent(ServiceInstancesChangedEvent event) { - serviceInstances.addAll(event.getServiceInstances()); - } - }); + new ServiceInstancesChangedListener(Sets.newSet(SERVICE_NAME), nacosServiceDiscovery) { + @Override + public void onEvent(ServiceInstancesChangedEvent event) { + serviceInstances.addAll(event.getServiceInstances()); + } + }); nacosServiceDiscovery.register(); nacosServiceDiscovery.update(); diff --git a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtilsTest.java b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtilsTest.java index b2e0b4e515..5f0a0fbbcb 100644 --- a/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtilsTest.java +++ b/dubbo-registry/dubbo-registry-nacos/src/test/java/org/apache/dubbo/registry/nacos/util/NacosNamingServiceUtilsTest.java @@ -16,26 +16,26 @@ */ package org.apache.dubbo.registry.nacos.util; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.metadata.report.MetadataReport; +import org.apache.dubbo.registry.client.ServiceInstance; +import org.apache.dubbo.registry.nacos.MockNamingService; +import org.apache.dubbo.registry.nacos.NacosNamingServiceWrapper; + import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.atomic.AtomicInteger; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.metadata.report.MetadataReport; -import org.apache.dubbo.registry.client.ServiceInstance; -import org.apache.dubbo.registry.nacos.MockNamingService; -import org.apache.dubbo.registry.nacos.NacosNamingServiceWrapper; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.mockito.MockedStatic; -import org.mockito.Mockito; - import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; import static com.alibaba.nacos.client.constant.Constants.HealthCheck.DOWN; import static com.alibaba.nacos.client.constant.Constants.HealthCheck.UP; @@ -83,7 +83,6 @@ class NacosNamingServiceUtilsTest { Assertions.assertNotNull(namingService); } - @Test void testRetryCreate() throws NacosException { try (MockedStatic nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { @@ -94,13 +93,15 @@ class NacosNamingServiceUtilsTest { return atomicInteger.incrementAndGet() > 10 ? UP : DOWN; } }; - nacosFactoryMockedStatic.when(() -> NacosFactory.createNamingService((Properties) any())).thenReturn(mock); - + nacosFactoryMockedStatic + .when(() -> NacosFactory.createNamingService((Properties) any())) + .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848") - .addParameter("nacos.retry", 5) - .addParameter("nacos.retry-wait", 10); - Assertions.assertThrows(IllegalStateException.class, () -> NacosNamingServiceUtils.createNamingService(url)); + .addParameter("nacos.retry", 5) + .addParameter("nacos.retry-wait", 10); + Assertions.assertThrows( + IllegalStateException.class, () -> NacosNamingServiceUtils.createNamingService(url)); try { NacosNamingServiceUtils.createNamingService(url); @@ -119,13 +120,14 @@ class NacosNamingServiceUtilsTest { return DOWN; } }; - nacosFactoryMockedStatic.when(() -> NacosFactory.createNamingService((Properties) any())).thenReturn(mock); - + nacosFactoryMockedStatic + .when(() -> NacosFactory.createNamingService((Properties) any())) + .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848") - .addParameter("nacos.retry", 5) - .addParameter("nacos.retry-wait", 10) - .addParameter("nacos.check", "false"); + .addParameter("nacos.retry", 5) + .addParameter("nacos.retry-wait", 10) + .addParameter("nacos.check", "false"); try { NacosNamingServiceUtils.createNamingService(url); } catch (Throwable t) { @@ -153,13 +155,15 @@ class NacosNamingServiceUtilsTest { return UP; } }; - nacosFactoryMockedStatic.when(() -> NacosFactory.createNamingService((Properties) any())).thenReturn(mock); - + nacosFactoryMockedStatic + .when(() -> NacosFactory.createNamingService((Properties) any())) + .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848") - .addParameter("nacos.retry", 5) - .addParameter("nacos.retry-wait", 10); - Assertions.assertThrows(IllegalStateException.class, () -> NacosNamingServiceUtils.createNamingService(url)); + .addParameter("nacos.retry", 5) + .addParameter("nacos.retry-wait", 10); + Assertions.assertThrows( + IllegalStateException.class, () -> NacosNamingServiceUtils.createNamingService(url)); try { NacosNamingServiceUtils.createNamingService(url); diff --git a/dubbo-registry/dubbo-registry-zookeeper/pom.xml b/dubbo-registry/dubbo-registry-zookeeper/pom.xml index 9571e7e3d3..f1e9cfa3d2 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/pom.xml +++ b/dubbo-registry/dubbo-registry-zookeeper/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-registry - ${revision} - ../pom.xml - - dubbo-registry-zookeeper - jar - ${project.artifactId} - The zookeeper registry module of dubbo project - - false - - - - org.apache.dubbo - dubbo-registry-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-zookeeper-curator5 - ${project.parent.version} - - - org.apache.curator - curator-x-discovery - - + 4.0.0 + + org.apache.dubbo + dubbo-registry + ${revision} + ../pom.xml + + dubbo-registry-zookeeper + jar + ${project.artifactId} + The zookeeper registry module of dubbo project + + false + + + + org.apache.dubbo + dubbo-registry-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-remoting-zookeeper-curator5 + ${project.parent.version} + + + org.apache.curator + curator-x-discovery + + diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperInstance.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperInstance.java index 5bf38d0284..f021e32aac 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperInstance.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperInstance.java @@ -35,8 +35,7 @@ public class ZookeeperInstance { private Map metadata = new HashMap<>(); @SuppressWarnings("unused") - private ZookeeperInstance() { - } + private ZookeeperInstance() {} public ZookeeperInstance(String id, String name, Map metadata) { this.id = id; @@ -70,8 +69,7 @@ public class ZookeeperInstance { @Override public String toString() { - return "ZookeeperInstance{" + "id='" + this.id + '\'' + ", name='" + this.name - + '\'' + ", metadata=" + this.metadata + '}'; + return "ZookeeperInstance{" + "id='" + this.id + '\'' + ", name='" + this.name + '\'' + ", metadata=" + + this.metadata + '}'; } - } diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java index b35ca17797..4052df8d26 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistry.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.registry.zookeeper; import org.apache.dubbo.common.URL; @@ -68,7 +67,8 @@ public class ZookeeperRegistry extends CacheableFailbackRegistry { private final Set anyServices = new ConcurrentHashSet<>(); - private final ConcurrentMap> zkListeners = new ConcurrentHashMap<>(); + private final ConcurrentMap> zkListeners = + new ConcurrentHashMap<>(); private ZookeeperClient zkClient; @@ -89,12 +89,20 @@ public class ZookeeperRegistry extends CacheableFailbackRegistry { this.zkClient.addStateListener((state) -> { if (state == StateListener.RECONNECTED) { - logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Trying to fetch the latest urls, in case there are provider changes during connection loss.\n" + - " Since ephemeral ZNode will not get deleted for a connection lose, " + - "there's no need to re-register url of this instance."); + logger.warn( + REGISTRY_ZOOKEEPER_EXCEPTION, + "", + "", + "Trying to fetch the latest urls, in case there are provider changes during connection loss.\n" + + " Since ephemeral ZNode will not get deleted for a connection lose, " + + "there's no need to re-register url of this instance."); ZookeeperRegistry.this.fetchLatestAddresses(); } else if (state == StateListener.NEW_SESSION_CREATED) { - logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Trying to re-register urls and re-subscribe listeners of this instance to registry..."); + logger.warn( + REGISTRY_ZOOKEEPER_EXCEPTION, + "", + "", + "Trying to re-register urls and re-subscribe listeners of this instance to registry..."); try { ZookeeperRegistry.this.recover(); @@ -102,8 +110,12 @@ public class ZookeeperRegistry extends CacheableFailbackRegistry { logger.error(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", e.getMessage(), e); } } else if (state == StateListener.SESSION_LOST) { - logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Url of this instance will be deleted from registry soon. " + - "Dubbo client will try to re-register once a new session is created."); + logger.warn( + REGISTRY_ZOOKEEPER_EXCEPTION, + "", + "", + "Url of this instance will be deleted from registry soon. " + + "Dubbo client will try to re-register once a new session is created."); } else if (state == StateListener.SUSPENDED) { } else if (state == StateListener.CONNECTED) { @@ -160,7 +172,8 @@ public class ZookeeperRegistry extends CacheableFailbackRegistry { checkDestroyed(); zkClient.create(toUrlPath(url), url.getParameter(DYNAMIC_KEY, true), true); } catch (Throwable e) { - throw new RpcException("Failed to register " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e); + throw new RpcException( + "Failed to register " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e); } } @@ -170,7 +183,8 @@ public class ZookeeperRegistry extends CacheableFailbackRegistry { checkDestroyed(); zkClient.delete(toUrlPath(url)); } catch (Throwable e) { - throw new RpcException("Failed to unregister " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e); + throw new RpcException( + "Failed to unregister " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e); } } @@ -181,18 +195,26 @@ public class ZookeeperRegistry extends CacheableFailbackRegistry { if (ANY_VALUE.equals(url.getServiceInterface())) { String root = toRootPath(); boolean check = url.getParameter(CHECK_KEY, false); - ConcurrentMap listeners = ConcurrentHashMapUtils.computeIfAbsent(zkListeners, url, k -> new ConcurrentHashMap<>()); + ConcurrentMap listeners = + ConcurrentHashMapUtils.computeIfAbsent(zkListeners, url, k -> new ConcurrentHashMap<>()); - ChildListener zkListener = ConcurrentHashMapUtils.computeIfAbsent(listeners, listener, k -> (parentPath, currentChildren) -> { - for (String child : currentChildren) { - child = URL.decode(child); - if (!anyServices.contains(child)) { - anyServices.add(child); - subscribe(url.setPath(child).addParameters(INTERFACE_KEY, child, - Constants.CHECK_KEY, String.valueOf(check)), k); - } - } - }); + ChildListener zkListener = ConcurrentHashMapUtils.computeIfAbsent( + listeners, listener, k -> (parentPath, currentChildren) -> { + for (String child : currentChildren) { + child = URL.decode(child); + if (!anyServices.contains(child)) { + anyServices.add(child); + subscribe( + url.setPath(child) + .addParameters( + INTERFACE_KEY, + child, + Constants.CHECK_KEY, + String.valueOf(check)), + k); + } + } + }); zkClient.create(root, false, true); @@ -201,8 +223,11 @@ public class ZookeeperRegistry extends CacheableFailbackRegistry { for (String service : services) { service = URL.decode(service); anyServices.add(service); - subscribe(url.setPath(service).addParameters(INTERFACE_KEY, service, - Constants.CHECK_KEY, String.valueOf(check)), listener); + subscribe( + url.setPath(service) + .addParameters( + INTERFACE_KEY, service, Constants.CHECK_KEY, String.valueOf(check)), + listener); } } } else { @@ -220,8 +245,10 @@ public class ZookeeperRegistry extends CacheableFailbackRegistry { /dubbo/[service name]/routers */ for (String path : toCategoriesPath(url)) { - ConcurrentMap listeners = ConcurrentHashMapUtils.computeIfAbsent(zkListeners, url, k -> new ConcurrentHashMap<>()); - ChildListener zkListener = ConcurrentHashMapUtils.computeIfAbsent(listeners, listener, k -> new RegistryChildListenerImpl(url, k, latch)); + ConcurrentMap listeners = ConcurrentHashMapUtils.computeIfAbsent( + zkListeners, url, k -> new ConcurrentHashMap<>()); + ChildListener zkListener = ConcurrentHashMapUtils.computeIfAbsent( + listeners, listener, k -> new RegistryChildListenerImpl(url, k, latch)); if (zkListener instanceof RegistryChildListenerImpl) { ((RegistryChildListenerImpl) zkListener).setLatch(latch); @@ -245,7 +272,8 @@ public class ZookeeperRegistry extends CacheableFailbackRegistry { } } } catch (Throwable e) { - throw new RpcException("Failed to subscribe " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e); + throw new RpcException( + "Failed to subscribe " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e); } } @@ -289,7 +317,8 @@ public class ZookeeperRegistry extends CacheableFailbackRegistry { } return toUrlsWithoutEmpty(url, providers); } catch (Throwable e) { - throw new RpcException("Failed to lookup " + url + " from zookeeper " + getUrl() + ", cause: " + e.getMessage(), e); + throw new RpcException( + "Failed to lookup " + url + " from zookeeper " + getUrl() + ", cause: " + e.getMessage(), e); } } @@ -315,9 +344,10 @@ public class ZookeeperRegistry extends CacheableFailbackRegistry { private String[] toCategoriesPath(URL url) { String[] categories; if (ANY_VALUE.equals(url.getCategory())) { - categories = new String[]{PROVIDERS_CATEGORY, CONSUMERS_CATEGORY, ROUTERS_CATEGORY, CONFIGURATORS_CATEGORY}; + categories = + new String[] {PROVIDERS_CATEGORY, CONSUMERS_CATEGORY, ROUTERS_CATEGORY, CONFIGURATORS_CATEGORY}; } else { - categories = url.getCategory(new String[]{DEFAULT_CATEGORY}); + categories = url.getCategory(new String[] {DEFAULT_CATEGORY}); } String[] paths = new String[categories.length]; for (int i = 0; i < categories.length; i++) { @@ -384,7 +414,11 @@ public class ZookeeperRegistry extends CacheableFailbackRegistry { try { latch.await(); } catch (InterruptedException e) { - logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Zookeeper children listener thread was interrupted unexpectedly, may cause race condition with the main thread."); + logger.warn( + REGISTRY_ZOOKEEPER_EXCEPTION, + "", + "", + "Zookeeper children listener thread was interrupted unexpectedly, may cause race condition with the main thread."); } notifier.notify(path, children); @@ -430,7 +464,9 @@ public class ZookeeperRegistry extends CacheableFailbackRegistry { } protected void doNotify(String path, Object rawAddresses) { - ZookeeperRegistry.this.notify(consumerUrl, listener, ZookeeperRegistry.this.toUrlsWithEmpty(consumerUrl, path, (List) rawAddresses)); + ZookeeperRegistry.this.notify( + consumerUrl, listener, ZookeeperRegistry.this.toUrlsWithEmpty(consumerUrl, path, (List) + rawAddresses)); } } } diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistryFactory.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistryFactory.java index b4f20df09d..ec4ce4ac34 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistryFactory.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistryFactory.java @@ -49,5 +49,4 @@ public class ZookeeperRegistryFactory extends AbstractRegistryFactory { public Registry createRegistry(URL url) { return new ZookeeperRegistry(url, zookeeperTransporter); } - } diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscovery.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscovery.java index 34ee84363a..06c2305055 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscovery.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscovery.java @@ -16,19 +16,6 @@ */ package org.apache.dubbo.registry.zookeeper; -import java.io.IOException; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CountDownLatch; - -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.api.CuratorWatcher; -import org.apache.curator.x.discovery.ServiceCache; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.function.ThrowableConsumer; import org.apache.dubbo.common.function.ThrowableFunction; @@ -43,6 +30,19 @@ import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedLi import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.io.IOException; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; + +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.api.CuratorWatcher; +import org.apache.curator.x.discovery.ServiceCache; + import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION; import static org.apache.dubbo.common.function.ThrowableFunction.execute; import static org.apache.dubbo.metadata.RevisionResolver.EMPTY_REVISION; @@ -113,17 +113,19 @@ public class ZookeeperServiceDiscovery extends AbstractServiceDiscovery { } @Override - protected void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance) throws RuntimeException { + protected void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance) + throws RuntimeException { if (EMPTY_REVISION.equals(getExportedServicesRevision(newServiceInstance)) - || EMPTY_REVISION.equals(oldServiceInstance.getMetadata().get(EXPORTED_SERVICES_REVISION_PROPERTY_NAME))) { + || EMPTY_REVISION.equals( + oldServiceInstance.getMetadata().get(EXPORTED_SERVICES_REVISION_PROPERTY_NAME))) { super.doUpdate(oldServiceInstance, newServiceInstance); return; } org.apache.curator.x.discovery.ServiceInstance oldInstance = build(oldServiceInstance); org.apache.curator.x.discovery.ServiceInstance newInstance = build(newServiceInstance); - if (!Objects.equals(newInstance.getName(), oldInstance.getName()) || - !Objects.equals(newInstance.getId(), oldInstance.getId())) { + if (!Objects.equals(newInstance.getName(), oldInstance.getName()) + || !Objects.equals(newInstance.getId(), oldInstance.getId())) { // Ignore if id changed. Should unregister first. super.doUpdate(oldServiceInstance, newServiceInstance); return; @@ -159,7 +161,8 @@ public class ZookeeperServiceDiscovery extends AbstractServiceDiscovery { } @Override - public void removeServiceInstancesChangedListener(ServiceInstancesChangedListener listener) throws IllegalArgumentException { + public void removeServiceInstancesChangedListener(ServiceInstancesChangedListener listener) + throws IllegalArgumentException { if (!instanceListeners.remove(listener)) { return; } @@ -172,7 +175,10 @@ public class ZookeeperServiceDiscovery extends AbstractServiceDiscovery { try { watcher.getCacheInstance().close(); } catch (IOException e) { - logger.error(REGISTRY_ZOOKEEPER_EXCEPTION, "curator stop watch failed", "", + logger.error( + REGISTRY_ZOOKEEPER_EXCEPTION, + "curator stop watch failed", + "", "Curator Stop service discovery watch failed. Service Name: " + serviceName); } } @@ -182,7 +188,7 @@ public class ZookeeperServiceDiscovery extends AbstractServiceDiscovery { @Override public boolean isAvailable() { - //Fix the issue of timeout for all calls to the isAvailable method after the zookeeper is disconnected + // Fix the issue of timeout for all calls to the isAvailable method after the zookeeper is disconnected return !isDestroy() && isConnected() && CollectionUtils.isNotEmpty(getServices()); } @@ -205,10 +211,10 @@ public class ZookeeperServiceDiscovery extends AbstractServiceDiscovery { CountDownLatch latch = new CountDownLatch(1); ZookeeperServiceDiscoveryChangeWatcher watcher = watcherCaches.computeIfAbsent(serviceName, name -> { - ServiceCache serviceCache = serviceDiscovery.serviceCacheBuilder() - .name(name) - .build(); - ZookeeperServiceDiscoveryChangeWatcher newer = new ZookeeperServiceDiscoveryChangeWatcher(this, serviceCache, name, latch); + ServiceCache serviceCache = + serviceDiscovery.serviceCacheBuilder().name(name).build(); + ZookeeperServiceDiscoveryChangeWatcher newer = + new ZookeeperServiceDiscoveryChangeWatcher(this, serviceCache, name, latch); serviceCache.addListener(newer); try { diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryChangeWatcher.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryChangeWatcher.java index f4e5168431..73830b4445 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryChangeWatcher.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryChangeWatcher.java @@ -25,6 +25,10 @@ import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent; import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import org.apache.dubbo.rpc.model.ScopeModelUtil; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CountDownLatch; + import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.curator.framework.state.ConnectionState; @@ -32,10 +36,6 @@ import org.apache.curator.x.discovery.ServiceCache; import org.apache.curator.x.discovery.details.ServiceCacheListener; import org.apache.zookeeper.Watcher; -import java.util.List; -import java.util.Set; -import java.util.concurrent.CountDownLatch; - /** * Zookeeper {@link ServiceDiscovery} Change {@link CuratorWatcher watcher} only interests in * {@link Watcher.Event.EventType#NodeChildrenChanged} and {@link Watcher.Event.EventType#NodeDataChanged} event types, @@ -56,21 +56,28 @@ public class ZookeeperServiceDiscoveryChangeWatcher implements ServiceCacheListe private final CountDownLatch latch; - public ZookeeperServiceDiscoveryChangeWatcher(ZookeeperServiceDiscovery zookeeperServiceDiscovery, - ServiceCache cacheInstance, - String serviceName, - CountDownLatch latch) { + public ZookeeperServiceDiscoveryChangeWatcher( + ZookeeperServiceDiscovery zookeeperServiceDiscovery, + ServiceCache cacheInstance, + String serviceName, + CountDownLatch latch) { this.zookeeperServiceDiscovery = zookeeperServiceDiscovery; this.cacheInstance = cacheInstance; this.serviceName = serviceName; - this.notifier = new RegistryNotifier(zookeeperServiceDiscovery.getUrl(), zookeeperServiceDiscovery.getDelay(), - ScopeModelUtil.getFrameworkModel(zookeeperServiceDiscovery.getUrl().getScopeModel()).getBeanFactory() - .getBean(FrameworkExecutorRepository.class).getServiceDiscoveryAddressNotificationExecutor()) { - @Override - protected void doNotify(Object rawAddresses) { - listeners.forEach(listener -> listener.onEvent((ServiceInstancesChangedEvent) rawAddresses)); - } - }; + this.notifier = + new RegistryNotifier( + zookeeperServiceDiscovery.getUrl(), + zookeeperServiceDiscovery.getDelay(), + ScopeModelUtil.getFrameworkModel( + zookeeperServiceDiscovery.getUrl().getScopeModel()) + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class) + .getServiceDiscoveryAddressNotificationExecutor()) { + @Override + protected void doNotify(Object rawAddresses) { + listeners.forEach(listener -> listener.onEvent((ServiceInstancesChangedEvent) rawAddresses)); + } + }; this.latch = latch; } diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/aot/ZookeeperReflectionTypeDescriberRegistrar.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/aot/ZookeeperReflectionTypeDescriberRegistrar.java index 2e0b5520ca..81901eec0b 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/aot/ZookeeperReflectionTypeDescriberRegistrar.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/aot/ZookeeperReflectionTypeDescriberRegistrar.java @@ -26,7 +26,6 @@ import java.util.HashSet; import java.util.List; import java.util.Set; - public class ZookeeperReflectionTypeDescriberRegistrar implements ReflectionTypeDescriberRegistrar { @Override @@ -42,6 +41,7 @@ public class ZookeeperReflectionTypeDescriberRegistrar implements ReflectionType memberCategories.add(MemberCategory.INVOKE_DECLARED_METHODS); memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); memberCategories.add(MemberCategory.DECLARED_FIELDS); - return new TypeDescriber(cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); + return new TypeDescriber( + cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } } diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkParams.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkParams.java index fd095a2ff6..d3dce60aaa 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkParams.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkParams.java @@ -19,11 +19,11 @@ package org.apache.dubbo.registry.zookeeper.util; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.client.ServiceInstance; -import org.apache.curator.framework.CuratorFramework; - import java.util.concurrent.TimeUnit; import java.util.function.Function; +import org.apache.curator.framework.CuratorFramework; + import static org.apache.dubbo.registry.zookeeper.ZookeeperServiceDiscovery.DEFAULT_GROUP; /** @@ -74,7 +74,6 @@ public enum CuratorFrameworkParams { * The unit of time related to blocking on connection to Zookeeper. */ BLOCK_UNTIL_CONNECTED_UNIT("blockUntilConnectedUnit", TimeUnit.SECONDS, TimeUnit::valueOf), - ; private final String name; @@ -102,4 +101,3 @@ public enum CuratorFrameworkParams { return (T) value; } } - diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtils.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtils.java index 178757b5b9..83b47fc1c1 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtils.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtils.java @@ -24,6 +24,11 @@ import org.apache.dubbo.registry.zookeeper.ZookeeperInstance; import org.apache.dubbo.registry.zookeeper.ZookeeperServiceDiscovery; import org.apache.dubbo.rpc.model.ScopeModelUtil; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; @@ -36,11 +41,6 @@ import org.apache.curator.x.discovery.ServiceInstanceBuilder; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.ACL; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - import static org.apache.curator.x.discovery.ServiceInstance.builder; import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; import static org.apache.dubbo.registry.zookeeper.ZookeeperServiceDiscovery.DEFAULT_GROUP; @@ -59,18 +59,19 @@ import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.RO */ public abstract class CuratorFrameworkUtils { - public static ServiceDiscovery buildServiceDiscovery(CuratorFramework curatorFramework, - String basePath) { + public static ServiceDiscovery buildServiceDiscovery( + CuratorFramework curatorFramework, String basePath) { return ServiceDiscoveryBuilder.builder(ZookeeperInstance.class) - .client(curatorFramework) - .basePath(basePath) - .build(); + .client(curatorFramework) + .basePath(basePath) + .build(); } - public static CuratorFramework buildCuratorFramework(URL connectionURL, ZookeeperServiceDiscovery serviceDiscovery) throws Exception { + public static CuratorFramework buildCuratorFramework(URL connectionURL, ZookeeperServiceDiscovery serviceDiscovery) + throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder() - .connectString(connectionURL.getBackupAddress()) - .retryPolicy(buildRetryPolicy(connectionURL)); + .connectString(connectionURL.getBackupAddress()) + .retryPolicy(buildRetryPolicy(connectionURL)); String userInformation = connectionURL.getUserInformation(); if (StringUtils.isNotEmpty(userInformation)) { builder = builder.authorization("digest", userInformation.getBytes()); @@ -89,8 +90,9 @@ public abstract class CuratorFrameworkUtils { CuratorFramework curatorFramework = builder.build(); curatorFramework.start(); - curatorFramework.blockUntilConnected(BLOCK_UNTIL_CONNECTED_WAIT.getParameterValue(connectionURL), - BLOCK_UNTIL_CONNECTED_UNIT.getParameterValue(connectionURL)); + curatorFramework.blockUntilConnected( + BLOCK_UNTIL_CONNECTED_WAIT.getParameterValue(connectionURL), + BLOCK_UNTIL_CONNECTED_UNIT.getParameterValue(connectionURL)); if (!curatorFramework.getState().equals(CuratorFrameworkState.STARTED)) { throw new IllegalStateException("zookeeper client initialization failed"); @@ -110,22 +112,25 @@ public abstract class CuratorFrameworkUtils { return new ExponentialBackoffRetry(baseSleepTimeMs, maxRetries, getMaxSleepMs); } - - public static List build(URL registryUrl, Collection> instances) { + public static List build( + URL registryUrl, Collection> instances) { return instances.stream().map((i) -> build(registryUrl, i)).collect(Collectors.toList()); } - public static ServiceInstance build(URL registryUrl, org.apache.curator.x.discovery.ServiceInstance instance) { + public static ServiceInstance build( + URL registryUrl, org.apache.curator.x.discovery.ServiceInstance instance) { String name = instance.getName(); String host = instance.getAddress(); int port = instance.getPort(); ZookeeperInstance zookeeperInstance = instance.getPayload(); - DefaultServiceInstance serviceInstance = new DefaultServiceInstance(name, host, port, ScopeModelUtil.getApplicationModel(registryUrl.getScopeModel())); + DefaultServiceInstance serviceInstance = new DefaultServiceInstance( + name, host, port, ScopeModelUtil.getApplicationModel(registryUrl.getScopeModel())); serviceInstance.setMetadata(zookeeperInstance.getMetadata()); return serviceInstance; } - public static org.apache.curator.x.discovery.ServiceInstance build(ServiceInstance serviceInstance) { + public static org.apache.curator.x.discovery.ServiceInstance build( + ServiceInstance serviceInstance) { ServiceInstanceBuilder builder; String serviceName = serviceInstance.getServiceName(); String host = serviceInstance.getHost(); @@ -134,12 +139,8 @@ public abstract class CuratorFrameworkUtils { String id = generateId(host, port); ZookeeperInstance zookeeperInstance = new ZookeeperInstance(id, serviceName, metadata); try { - builder = builder() - .id(id) - .name(serviceName) - .address(host) - .port(port) - .payload(zookeeperInstance); + builder = + builder().id(id).name(serviceName).address(host).port(port).payload(zookeeperInstance); } catch (Exception e) { throw new RuntimeException(e); } diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistryTest.java b/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistryTest.java index 3f36ad395b..6ca5962185 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistryTest.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperRegistryTest.java @@ -24,17 +24,17 @@ import org.apache.dubbo.registry.status.RegistryStatusChecker; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CountDownLatch; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.CountDownLatch; - import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; @@ -127,8 +127,7 @@ class ZookeeperRegistryTest { zookeeperRegistry.lookup(null); fail(); } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage(), - containsString("lookup url == null")); + assertThat(expected.getMessage(), containsString("lookup url == null")); } } @@ -141,9 +140,9 @@ class ZookeeperRegistryTest { @Disabled @Test /* - This UT is unstable, consider remove it later. - @see https://github.com/apache/dubbo/issues/1787 - */ + This UT is unstable, consider remove it later. + @see https://github.com/apache/dubbo/issues/1787 + */ public void testStatusChecker() { RegistryStatusChecker registryStatusChecker = new RegistryStatusChecker(ApplicationModel.defaultModel()); Status status = registryStatusChecker.check(); @@ -175,7 +174,6 @@ class ZookeeperRegistryTest { assertThat(zookeeperRegistry.isAvailable(), is(false)); } - @Test void testDoRegisterWithException() { Assertions.assertThrows(RpcException.class, () -> { @@ -194,7 +192,6 @@ class ZookeeperRegistryTest { @Test void testDoSubscribeWithException() { - Assertions.assertThrows(RpcException.class, - () -> zookeeperRegistry.doSubscribe(anyUrl, listener)); + Assertions.assertThrows(RpcException.class, () -> zookeeperRegistry.doSubscribe(anyUrl, listener)); } } diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryTest.java b/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryTest.java index f3420bb596..a9405e9392 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryTest.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/ZookeeperServiceDiscoveryTest.java @@ -24,6 +24,11 @@ import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent; import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; @@ -32,11 +37,6 @@ import org.junit.jupiter.api.condition.DisabledForJreRange; import org.junit.jupiter.api.condition.JRE; import org.mockito.internal.util.collections.Sets; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CountDownLatch; - import static java.util.Arrays.asList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -85,11 +85,11 @@ class ZookeeperServiceDiscoveryTest { // Add Listener discovery.addServiceInstancesChangedListener( new ServiceInstancesChangedListener(Sets.newSet(SERVICE_NAME), discovery) { - @Override - public void onEvent(ServiceInstancesChangedEvent event) { - latch.countDown(); - } - }); + @Override + public void onEvent(ServiceInstancesChangedEvent event) { + latch.countDown(); + } + }); discovery.register(); latch.await(); @@ -100,7 +100,7 @@ class ZookeeperServiceDiscoveryTest { discovery.register(); serviceInstances = discovery.getInstances(SERVICE_NAME); - DefaultServiceInstance serviceInstance = (DefaultServiceInstance)discovery.getLocalInstance(); + DefaultServiceInstance serviceInstance = (DefaultServiceInstance) discovery.getLocalInstance(); assertTrue(serviceInstances.contains(serviceInstance)); assertEquals(asList(serviceInstance), serviceInstances); @@ -121,5 +121,4 @@ class ZookeeperServiceDiscoveryTest { assertTrue(serviceInstances.isEmpty()); } - } diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtilsTest.java b/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtilsTest.java index 01ed19db28..40b233c9be 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtilsTest.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/test/java/org/apache/dubbo/registry/zookeeper/util/CuratorFrameworkUtilsTest.java @@ -23,6 +23,10 @@ import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.registry.zookeeper.ZookeeperInstance; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + import org.apache.curator.framework.CuratorFramework; import org.apache.curator.x.discovery.ServiceDiscovery; import org.junit.jupiter.api.Assertions; @@ -30,10 +34,6 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.EXPORTED_SERVICES_REVISION_PROPERTY_NAME; import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.METADATA_STORAGE_TYPE_PROPERTY_NAME; import static org.apache.dubbo.registry.zookeeper.util.CuratorFrameworkParams.ROOT_PATH; @@ -67,7 +67,8 @@ class CuratorFrameworkUtilsTest { @Test void testBuildServiceDiscovery() throws Exception { CuratorFramework curatorFramework = CuratorFrameworkUtils.buildCuratorFramework(registryUrl, null); - ServiceDiscovery discovery = CuratorFrameworkUtils.buildServiceDiscovery(curatorFramework, ROOT_PATH.getParameterValue(registryUrl)); + ServiceDiscovery discovery = + CuratorFrameworkUtils.buildServiceDiscovery(curatorFramework, ROOT_PATH.getParameterValue(registryUrl)); Assertions.assertNotNull(discovery); discovery.close(); curatorFramework.getZookeeperClient().close(); @@ -75,14 +76,17 @@ class CuratorFrameworkUtilsTest { @Test void testBuild() { - ServiceInstance dubboServiceInstance = new DefaultServiceInstance("A", "127.0.0.1", 8888, ApplicationModel.defaultModel()); + ServiceInstance dubboServiceInstance = + new DefaultServiceInstance("A", "127.0.0.1", 8888, ApplicationModel.defaultModel()); Map metadata = dubboServiceInstance.getMetadata(); metadata.put(METADATA_STORAGE_TYPE_PROPERTY_NAME, "remote"); metadata.put(EXPORTED_SERVICES_REVISION_PROPERTY_NAME, "111"); metadata.put("site", "dubbo"); - // convert {org.apache.dubbo.registry.client.ServiceInstance} to {org.apache.curator.x.discovery.ServiceInstance} - org.apache.curator.x.discovery.ServiceInstance curatorServiceInstance = CuratorFrameworkUtils.build(dubboServiceInstance); + // convert {org.apache.dubbo.registry.client.ServiceInstance} to + // {org.apache.curator.x.discovery.ServiceInstance} + org.apache.curator.x.discovery.ServiceInstance curatorServiceInstance = + CuratorFrameworkUtils.build(dubboServiceInstance); Assertions.assertEquals(curatorServiceInstance.getId(), dubboServiceInstance.getAddress()); Assertions.assertEquals(curatorServiceInstance.getName(), dubboServiceInstance.getServiceName()); Assertions.assertEquals(curatorServiceInstance.getAddress(), dubboServiceInstance.getHost()); @@ -93,14 +97,16 @@ class CuratorFrameworkUtilsTest { Assertions.assertEquals(payload.getMetadata(), metadata); Assertions.assertEquals(payload.getName(), dubboServiceInstance.getServiceName()); - // convert {org.apache.curator.x.discovery.ServiceInstance} to {org.apache.dubbo.registry.client.ServiceInstance} + // convert {org.apache.curator.x.discovery.ServiceInstance} to + // {org.apache.dubbo.registry.client.ServiceInstance} ServiceInstance serviceInstance = CuratorFrameworkUtils.build(registryUrl, curatorServiceInstance); Assertions.assertEquals(serviceInstance, dubboServiceInstance); - // convert {Collection>} to {List} - List serviceInstances = CuratorFrameworkUtils.build(registryUrl, Arrays.asList(curatorServiceInstance)); + // convert {Collection>} to + // {List} + List serviceInstances = + CuratorFrameworkUtils.build(registryUrl, Arrays.asList(curatorServiceInstance)); Assertions.assertNotNull(serviceInstances); Assertions.assertEquals(serviceInstances.get(0), dubboServiceInstance); } - } diff --git a/dubbo-registry/pom.xml b/dubbo-registry/pom.xml index b72880197a..28008cdf8e 100644 --- a/dubbo-registry/pom.xml +++ b/dubbo-registry/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-parent - ${revision} - ../pom.xml - - dubbo-registry - pom - ${project.artifactId} - The registry module of dubbo project - - false - - - dubbo-registry-api - dubbo-registry-multicast - dubbo-registry-zookeeper - dubbo-registry-nacos - dubbo-registry-multiple - + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + + dubbo-registry + pom + ${project.artifactId} + The registry module of dubbo project + + dubbo-registry-api + dubbo-registry-multicast + dubbo-registry-zookeeper + dubbo-registry-nacos + dubbo-registry-multiple + + + false + - - - org.apache.dubbo - dubbo-test-check - ${project.parent.version} - test - - + + + org.apache.dubbo + dubbo-test-check + ${project.parent.version} + test + + diff --git a/dubbo-remoting/dubbo-remoting-api/pom.xml b/dubbo-remoting/dubbo-remoting-api/pom.xml index 2c96dfddc1..a7c838e900 100644 --- a/dubbo-remoting/dubbo-remoting-api/pom.xml +++ b/dubbo-remoting/dubbo-remoting-api/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-remoting - ${revision} - ../pom.xml - - dubbo-remoting-api - jar - ${project.artifactId} - The remoting module of dubbo project - - false - - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - org.apache.dubbo - dubbo-serialization-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.parent.version} - test - - - org.slf4j - slf4j-log4j12 - test - - + 4.0.0 + + org.apache.dubbo + dubbo-remoting + ${revision} + ../pom.xml + + dubbo-remoting-api + jar + ${project.artifactId} + The remoting module of dubbo project + + false + + + + org.apache.dubbo + dubbo-common + ${project.parent.version} + + + org.apache.dubbo + dubbo-serialization-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.parent.version} + test + + + org.slf4j + slf4j-log4j12 + test + + diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/ChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/ChannelHandler.java index 14fa5d043e..d09da2fe6d 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/ChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/ChannelHandler.java @@ -19,7 +19,6 @@ package org.apache.dubbo.remoting; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; - /** * ChannelHandler. (API, Prototype, ThreadSafe) * @@ -66,5 +65,4 @@ public interface ChannelHandler { * @param exception exception. */ void caught(Channel channel, Throwable exception) throws RemotingException; - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Client.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Client.java index 1e3f87a91f..a3a02c144a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Client.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Client.java @@ -34,5 +34,4 @@ public interface Client extends Endpoint, Channel, Resetable, IdleSensible { @Deprecated void reset(org.apache.dubbo.common.Parameters parameters); - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec.java index ee0dcad885..89bdd69557 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec.java @@ -58,5 +58,4 @@ public interface Codec { */ @Adaptive({Constants.CODEC_KEY}) Object decode(Channel channel, InputStream input) throws IOException; - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec2.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec2.java index a862cae615..bcae4766f2 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec2.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Codec2.java @@ -32,10 +32,8 @@ public interface Codec2 { @Adaptive({Constants.CODEC_KEY}) Object decode(Channel channel, ChannelBuffer buffer) throws IOException; - enum DecodeResult { - NEED_MORE_INPUT, SKIP_SOME_INPUT + NEED_MORE_INPUT, + SKIP_SOME_INPUT } - } - diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java index d6969e7731..25469e00e2 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Constants.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting; - import java.util.Arrays; import java.util.List; @@ -77,6 +75,7 @@ public interface Constants { * ticks per wheel. */ int TICKS_PER_WHEEL = 128; + String PAYLOAD_KEY = "payload"; /** * 8M @@ -184,5 +183,4 @@ public interface Constants { String USE_SECURE_RANDOM_ID = "dubbo.application.use-secure-random-request-id"; String CONNECTION_HANDLER_NAME = "connectionHandler"; - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Decodeable.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Decodeable.java index a913ef8740..e46ba5ef14 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Decodeable.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Decodeable.java @@ -14,11 +14,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting; public interface Decodeable { void decode() throws Exception; - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Dispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Dispatcher.java index 6f6f88f2e5..99ff0238c2 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Dispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Dispatcher.java @@ -38,5 +38,4 @@ public interface Dispatcher { @Adaptive({Constants.DISPATCHER_KEY, "dispather", "channel.handler"}) // The last two parameters are reserved for compatibility with the old configuration ChannelHandler dispatch(ChannelHandler handler, URL url); - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Endpoint.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Endpoint.java index 2a20f7c379..c8e8aaf47c 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Endpoint.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Endpoint.java @@ -85,5 +85,4 @@ public interface Endpoint { * @return closed */ boolean isClosed(); - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/ExecutionException.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/ExecutionException.java index 97783c158b..d36767b17c 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/ExecutionException.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/ExecutionException.java @@ -44,25 +44,29 @@ public class ExecutionException extends RemotingException { this.request = request; } - public ExecutionException(Object request, InetSocketAddress localAddress, InetSocketAddress remoteAddress, String message, - Throwable cause) { + public ExecutionException( + Object request, + InetSocketAddress localAddress, + InetSocketAddress remoteAddress, + String message, + Throwable cause) { super(localAddress, remoteAddress, message, cause); this.request = request; } - public ExecutionException(Object request, InetSocketAddress localAddress, InetSocketAddress remoteAddress, String message) { + public ExecutionException( + Object request, InetSocketAddress localAddress, InetSocketAddress remoteAddress, String message) { super(localAddress, remoteAddress, message); this.request = request; } - public ExecutionException(Object request, InetSocketAddress localAddress, InetSocketAddress remoteAddress, Throwable cause) { + public ExecutionException( + Object request, InetSocketAddress localAddress, InetSocketAddress remoteAddress, Throwable cause) { super(localAddress, remoteAddress, cause); this.request = request; } - public Object getRequest() { return request; } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingException.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingException.java index 32abe4eaf1..146ce3888c 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingException.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingException.java @@ -38,7 +38,9 @@ public class RemotingException extends Exception { private InetSocketAddress remoteAddress; public RemotingException(Channel channel, String msg) { - this(channel == null ? null : channel.getLocalAddress(), channel == null ? null : channel.getRemoteAddress(), + this( + channel == null ? null : channel.getLocalAddress(), + channel == null ? null : channel.getRemoteAddress(), msg); } @@ -50,7 +52,9 @@ public class RemotingException extends Exception { } public RemotingException(Channel channel, Throwable cause) { - this(channel == null ? null : channel.getLocalAddress(), channel == null ? null : channel.getRemoteAddress(), + this( + channel == null ? null : channel.getLocalAddress(), + channel == null ? null : channel.getRemoteAddress(), cause); } @@ -62,12 +66,15 @@ public class RemotingException extends Exception { } public RemotingException(Channel channel, String message, Throwable cause) { - this(channel == null ? null : channel.getLocalAddress(), channel == null ? null : channel.getRemoteAddress(), - message, cause); + this( + channel == null ? null : channel.getLocalAddress(), + channel == null ? null : channel.getRemoteAddress(), + message, + cause); } - public RemotingException(InetSocketAddress localAddress, InetSocketAddress remoteAddress, String message, - Throwable cause) { + public RemotingException( + InetSocketAddress localAddress, InetSocketAddress remoteAddress, String message, Throwable cause) { super(message, cause); this.localAddress = localAddress; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingServer.java index 2c60d396d0..29fe60ace2 100755 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/RemotingServer.java @@ -54,5 +54,4 @@ public interface RemotingServer extends Endpoint, Resetable, IdleSensible { @Deprecated void reset(org.apache.dubbo.common.Parameters parameters); - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/TimeoutException.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/TimeoutException.java index 9ecb8e4e4e..861073e664 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/TimeoutException.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/TimeoutException.java @@ -36,8 +36,8 @@ public class TimeoutException extends RemotingException { this.phase = serverSide ? SERVER_SIDE : CLIENT_SIDE; } - public TimeoutException(boolean serverSide, InetSocketAddress localAddress, - InetSocketAddress remoteAddress, String message) { + public TimeoutException( + boolean serverSide, InetSocketAddress localAddress, InetSocketAddress remoteAddress, String message) { super(localAddress, remoteAddress, message); this.phase = serverSide ? SERVER_SIDE : CLIENT_SIDE; } @@ -53,5 +53,4 @@ public class TimeoutException extends RemotingException { public boolean isClientSide() { return phase == 0; } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Transporter.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Transporter.java index 3b4ba462a8..eee680fd12 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Transporter.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Transporter.java @@ -55,5 +55,4 @@ public interface Transporter { */ @Adaptive({Constants.CLIENT_KEY, Constants.TRANSPORTER_KEY}) Client connect(URL url, ChannelHandler handler) throws RemotingException; - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Transporters.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Transporters.java index d8dbb4ee45..05783637cc 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Transporters.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Transporters.java @@ -25,8 +25,7 @@ import org.apache.dubbo.remoting.transport.ChannelHandlerDispatcher; */ public class Transporters { - private Transporters() { - } + private Transporters() {} public static RemotingServer bind(String url, ChannelHandler... handler) throws RemotingException { return bind(URL.valueOf(url), handler); @@ -68,7 +67,8 @@ public class Transporters { } public static Transporter getTransporter(URL url) { - return url.getOrDefaultFrameworkModel().getExtensionLoader(Transporter.class).getAdaptiveExtension(); + return url.getOrDefaultFrameworkModel() + .getExtensionLoader(Transporter.class) + .getAdaptiveExtension(); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/AbstractHttpProtocolDetector.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/AbstractHttpProtocolDetector.java index de3b9a40c9..6cd013f81d 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/AbstractHttpProtocolDetector.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/AbstractHttpProtocolDetector.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.api; - import org.apache.dubbo.remoting.buffer.ChannelBuffer; import java.util.ArrayList; @@ -32,7 +31,6 @@ import static org.apache.dubbo.remoting.api.AbstractHttpProtocolDetector.HttpMet import static org.apache.dubbo.remoting.api.AbstractHttpProtocolDetector.HttpMethod.PUT; import static org.apache.dubbo.remoting.api.AbstractHttpProtocolDetector.HttpMethod.TRACE; - /** * http protocol detector */ @@ -41,8 +39,6 @@ public abstract class AbstractHttpProtocolDetector implements ProtocolDetector { protected int empty = ' '; protected static String SIMPLE_HTTP = "XXX HTTP/1"; - - protected static final List QOS_HTTP_METHOD = Arrays.asList(GET, POST); /** @@ -50,7 +46,8 @@ public abstract class AbstractHttpProtocolDetector implements ProtocolDetector { * first GET ,POST,DELETE,PUT * second HEAD,PATCH,OPTIONS,TRACE */ - protected static final List HTTP_METHODS = Arrays.asList(GET, POST, DELETE, PUT, HEAD, PATCH, OPTIONS, TRACE); + protected static final List HTTP_METHODS = + Arrays.asList(GET, POST, DELETE, PUT, HEAD, PATCH, OPTIONS, TRACE); protected static char[][] getHttpMethodsPrefix(int length, List httpMethods) { if (0 >= length || length > 3) { @@ -63,10 +60,8 @@ public abstract class AbstractHttpProtocolDetector implements ProtocolDetector { } return prefix.toArray(new char[0][]); - } - protected static char[][] getHttpMethodsPrefix() { return getHttpMethodsPrefix(3, HTTP_METHODS); } @@ -115,7 +110,6 @@ public abstract class AbstractHttpProtocolDetector implements ProtocolDetector { return split[index]; } - /** * between first and second empty char * @@ -148,7 +142,6 @@ public abstract class AbstractHttpProtocolDetector implements ProtocolDetector { } return stringBuilder.toString(); - } public enum HttpMethod { @@ -162,7 +155,6 @@ public abstract class AbstractHttpProtocolDetector implements ProtocolDetector { OPTIONS("OPTIONS"), TRACE("TRACE"); - HttpMethod(String value) { this.value = value; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/AbstractWireProtocol.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/AbstractWireProtocol.java index 4bc8702cbb..d91d5e01ed 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/AbstractWireProtocol.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/AbstractWireProtocol.java @@ -34,11 +34,8 @@ public abstract class AbstractWireProtocol implements WireProtocol { } @Override - public void configClientPipeline(URL url, ChannelOperator operator, ContextOperator contextOperator) { - - } + public void configClientPipeline(URL url, ChannelOperator operator, ContextOperator contextOperator) {} @Override - public void close() { - } + public void close() {} } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/ProtocolDetector.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/ProtocolDetector.java index 6a35952821..b400a4f41f 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/ProtocolDetector.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/ProtocolDetector.java @@ -16,13 +16,11 @@ */ package org.apache.dubbo.remoting.api; - import org.apache.dubbo.remoting.buffer.ChannelBuffer; import java.util.HashMap; import java.util.Map; - /** * Determine incoming bytes belong to the specific protocol. */ @@ -56,23 +54,23 @@ public interface ProtocolDetector { return flag; } - public static Result recognized(){ + public static Result recognized() { return new Result(Flag.RECOGNIZED); } - - public static Result unrecognized(){ + public static Result unrecognized() { return new Result(Flag.UNRECOGNIZED); } - - public static Result needMoreData(){ + public static Result needMoreData() { return new Result(Flag.NEED_MORE_DATA); } } enum Flag { - RECOGNIZED, UNRECOGNIZED, NEED_MORE_DATA + RECOGNIZED, + UNRECOGNIZED, + NEED_MORE_DATA } default int getByteByIndex(ChannelBuffer buffer, int index) { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/AbstractConnectionClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/AbstractConnectionClient.java index 66e9b3a410..052b50d0ec 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/AbstractConnectionClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/AbstractConnectionClient.java @@ -32,7 +32,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERR public abstract class AbstractConnectionClient extends AbstractClient { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractConnectionClient.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(AbstractConnectionClient.class); protected WireProtocol protocol; @@ -44,8 +45,8 @@ public abstract class AbstractConnectionClient extends AbstractClient { private volatile long counter; - private static final AtomicLongFieldUpdater COUNTER_UPDATER - = AtomicLongFieldUpdater.newUpdater(AbstractConnectionClient.class, "counter"); + private static final AtomicLongFieldUpdater COUNTER_UPDATER = + AtomicLongFieldUpdater.newUpdater(AbstractConnectionClient.class, "counter"); protected AbstractConnectionClient(URL url, ChannelHandler handler) throws RemotingException { super(url, handler); @@ -142,5 +143,4 @@ public abstract class AbstractConnectionClient extends AbstractClient { public long getCounter() { return COUNTER_UPDATER.get(this); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/ConnectionHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/ConnectionHandler.java index 4ed563a5c3..4bafd19266 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/ConnectionHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/ConnectionHandler.java @@ -31,5 +31,4 @@ public interface ConnectionHandler { * @param channel Channel */ void reconnect(Object channel); - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/ConnectionManager.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/ConnectionManager.java index 61a984b757..129d2399ab 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/ConnectionManager.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/ConnectionManager.java @@ -29,5 +29,4 @@ public interface ConnectionManager { AbstractConnectionClient connect(URL url, ChannelHandler handler); void forEachConnection(Consumer connectionConsumer); - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/MultiplexProtocolConnectionManager.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/MultiplexProtocolConnectionManager.java index 25ef6fa009..28cfbebc77 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/MultiplexProtocolConnectionManager.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/MultiplexProtocolConnectionManager.java @@ -38,7 +38,8 @@ public class MultiplexProtocolConnectionManager implements ConnectionManager { @Override public AbstractConnectionClient connect(URL url, ChannelHandler handler) { - final ConnectionManager manager = ConcurrentHashMapUtils.computeIfAbsent(protocols, url.getProtocol(), this::createSingleProtocolConnectionManager); + final ConnectionManager manager = ConcurrentHashMapUtils.computeIfAbsent( + protocols, url.getProtocol(), this::createSingleProtocolConnectionManager); return manager.connect(url, handler); } @@ -48,6 +49,8 @@ public class MultiplexProtocolConnectionManager implements ConnectionManager { } private ConnectionManager createSingleProtocolConnectionManager(String protocol) { - return frameworkModel.getExtensionLoader(ConnectionManager.class).getExtension(SingleProtocolConnectionManager.NAME); + return frameworkModel + .getExtensionLoader(ConnectionManager.class) + .getExtension(SingleProtocolConnectionManager.NAME); } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/SingleProtocolConnectionManager.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/SingleProtocolConnectionManager.java index d8333efbbc..3f84069671 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/SingleProtocolConnectionManager.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/connection/SingleProtocolConnectionManager.java @@ -44,7 +44,9 @@ public class SingleProtocolConnectionManager implements ConnectionManager { return connections.compute(url.getAddress(), (address, conn) -> { if (conn == null) { String transport = url.getParameter(Constants.TRANSPORTER_KEY, "netty4"); - ConnectionManager manager = frameworkModel.getExtensionLoader(ConnectionManager.class).getExtension(transport); + ConnectionManager manager = frameworkModel + .getExtensionLoader(ConnectionManager.class) + .getExtension(transport); final AbstractConnectionClient connectionClient = manager.connect(url, handler); connectionClient.addCloseListener(() -> connections.remove(address, connectionClient)); return connectionClient; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/ChannelHandlerPretender.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/ChannelHandlerPretender.java index b17dd7c7be..583095472d 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/ChannelHandlerPretender.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/ChannelHandlerPretender.java @@ -28,5 +28,4 @@ public class ChannelHandlerPretender extends ChannelHandlerAdapter { public Object getRealHandler() { return realHandler; } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/DefaultCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/DefaultCodec.java index 4756dd38ef..c4f18ab953 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/DefaultCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/DefaultCodec.java @@ -24,9 +24,7 @@ import java.io.IOException; public class DefaultCodec implements Codec2 { @Override - public void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException { - - } + public void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException {} @Override public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/DefaultPuHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/DefaultPuHandler.java index 0e021f934d..8ca7dc6c85 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/DefaultPuHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/DefaultPuHandler.java @@ -22,27 +22,17 @@ import org.apache.dubbo.remoting.RemotingException; public class DefaultPuHandler implements ChannelHandler { @Override - public void connected(Channel channel) throws RemotingException { - - } + public void connected(Channel channel) throws RemotingException {} @Override - public void disconnected(Channel channel) throws RemotingException { - - } + public void disconnected(Channel channel) throws RemotingException {} @Override - public void sent(Channel channel, Object message) throws RemotingException { - - } + public void sent(Channel channel, Object message) throws RemotingException {} @Override - public void received(Channel channel, Object message) throws RemotingException { - - } + public void received(Channel channel, Object message) throws RemotingException {} @Override - public void caught(Channel channel, Throwable exception) throws RemotingException { - - } + public void caught(Channel channel, Throwable exception) throws RemotingException {} } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/PortUnificationTransporter.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/PortUnificationTransporter.java index 0562085c32..e9f3c789a9 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/PortUnificationTransporter.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/api/pu/PortUnificationTransporter.java @@ -33,5 +33,4 @@ public interface PortUnificationTransporter { @Adaptive({Constants.CLIENT_KEY, Constants.TRANSPORTER_KEY}) AbstractConnectionClient connect(URL url, ChannelHandler handler) throws RemotingException; - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/AbstractChannelBuffer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/AbstractChannelBuffer.java index 37f10b44a9..0697264077 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/AbstractChannelBuffer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/AbstractChannelBuffer.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.buffer; import java.io.IOException; @@ -310,8 +309,7 @@ public abstract class AbstractChannelBuffer implements ChannelBuffer { @Override public boolean equals(Object o) { - return o instanceof ChannelBuffer - && ChannelBuffers.equals(this, (ChannelBuffer) o); + return o instanceof ChannelBuffer && ChannelBuffers.equals(this, (ChannelBuffer) o); } @Override @@ -326,11 +324,10 @@ public abstract class AbstractChannelBuffer implements ChannelBuffer { @Override public String toString() { - return getClass().getSimpleName() + '(' + - "ridx=" + readerIndex + ", " + - "widx=" + writerIndex + ", " + - "cap=" + capacity() + - ')'; + return getClass().getSimpleName() + '(' + "ridx=" + + readerIndex + ", " + "widx=" + + writerIndex + ", " + "cap=" + + capacity() + ')'; } protected void checkReadableBytes(int minimumReadableBytes) { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ByteBufferBackedChannelBuffer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ByteBufferBackedChannelBuffer.java index 6bcfa16acf..2a1880e3d3 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ByteBufferBackedChannelBuffer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ByteBufferBackedChannelBuffer.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.buffer; import java.io.IOException; @@ -53,13 +52,11 @@ public class ByteBufferBackedChannelBuffer extends AbstractChannelBuffer { } } - @Override public int capacity() { return capacity; } - @Override public ChannelBuffer copy(int index, int length) { ByteBuffer src; @@ -69,21 +66,17 @@ public class ByteBufferBackedChannelBuffer extends AbstractChannelBuffer { throw new IndexOutOfBoundsException(); } - ByteBuffer dst = buffer.isDirect() - ? ByteBuffer.allocateDirect(length) - : ByteBuffer.allocate(length); + ByteBuffer dst = buffer.isDirect() ? ByteBuffer.allocateDirect(length) : ByteBuffer.allocate(length); dst.put(src); dst.clear(); return new ByteBufferBackedChannelBuffer(dst); } - @Override public byte getByte(int index) { return buffer.get(index); } - @Override public void getBytes(int index, byte[] dst, int dstIndex, int length) { ByteBuffer data = buffer.duplicate(); @@ -95,7 +88,6 @@ public class ByteBufferBackedChannelBuffer extends AbstractChannelBuffer { data.get(dst, dstIndex, length); } - @Override public void getBytes(int index, ByteBuffer dst) { ByteBuffer data = buffer.duplicate(); @@ -108,7 +100,6 @@ public class ByteBufferBackedChannelBuffer extends AbstractChannelBuffer { dst.put(data); } - @Override public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { if (dst instanceof ByteBufferBackedChannelBuffer) { @@ -124,7 +115,6 @@ public class ByteBufferBackedChannelBuffer extends AbstractChannelBuffer { } } - @Override public void getBytes(int index, OutputStream out, int length) throws IOException { if (length == 0) { @@ -140,19 +130,16 @@ public class ByteBufferBackedChannelBuffer extends AbstractChannelBuffer { } } - @Override public boolean isDirect() { return buffer.isDirect(); } - @Override public void setByte(int index, int value) { buffer.put(index, (byte) value); } - @Override public void setBytes(int index, byte[] src, int srcIndex, int length) { ByteBuffer data = buffer.duplicate(); @@ -160,7 +147,6 @@ public class ByteBufferBackedChannelBuffer extends AbstractChannelBuffer { data.put(src, srcIndex, length); } - @Override public void setBytes(int index, ByteBuffer src) { ByteBuffer data = buffer.duplicate(); @@ -168,7 +154,6 @@ public class ByteBufferBackedChannelBuffer extends AbstractChannelBuffer { data.put(src); } - @Override public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { if (src instanceof ByteBufferBackedChannelBuffer) { @@ -184,7 +169,6 @@ public class ByteBufferBackedChannelBuffer extends AbstractChannelBuffer { } } - @Override public ByteBuffer toByteBuffer(int index, int length) { if (index == 0 && length == capacity()) { @@ -194,7 +178,6 @@ public class ByteBufferBackedChannelBuffer extends AbstractChannelBuffer { } } - @Override public int setBytes(int index, InputStream in, int length) throws IOException { int readBytes = 0; @@ -235,19 +218,16 @@ public class ByteBufferBackedChannelBuffer extends AbstractChannelBuffer { return readBytes; } - @Override public byte[] array() { return buffer.array(); } - @Override public boolean hasArray() { return buffer.hasArray(); } - @Override public int arrayOffset() { return buffer.arrayOffset(); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBuffer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBuffer.java index e77cf46ab2..fd384f0f16 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBuffer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBuffer.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.buffer; import java.io.IOException; @@ -953,7 +952,5 @@ public interface ChannelBuffer extends Comparable { * If this buffer is backed by an NIO direct buffer, * in some scenarios it may be necessary to manually release. */ - default void release() { - - } + default void release() {} } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBufferFactory.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBufferFactory.java index 5042260c24..30290d9679 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBufferFactory.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBufferFactory.java @@ -25,5 +25,4 @@ public interface ChannelBufferFactory { ChannelBuffer getBuffer(byte[] array, int offset, int length); ChannelBuffer getBuffer(ByteBuffer nioBuffer); - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBufferInputStream.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBufferInputStream.java index 8e64eaa01d..6b461ad781 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBufferInputStream.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBufferInputStream.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.buffer; import java.io.IOException; @@ -105,5 +104,4 @@ public class ChannelBufferInputStream extends InputStream { buffer.skipBytes(nBytes); return nBytes; } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBufferOutputStream.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBufferOutputStream.java index afc7187413..95e1664dcb 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBufferOutputStream.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBufferOutputStream.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.buffer; import java.io.IOException; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBuffers.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBuffers.java index cc62925da1..08dde5e42a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBuffers.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBuffers.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.buffer; import java.nio.ByteBuffer; @@ -25,8 +24,7 @@ public final class ChannelBuffers { public static final int DEFAULT_CAPACITY = 256; - private ChannelBuffers() { - } + private ChannelBuffers() {} public static ChannelBuffer dynamicBuffer() { return dynamicBuffer(DEFAULT_CAPACITY); @@ -36,8 +34,7 @@ public final class ChannelBuffers { return new DynamicChannelBuffer(capacity); } - public static ChannelBuffer dynamicBuffer(int capacity, - ChannelBufferFactory factory) { + public static ChannelBuffer dynamicBuffer(int capacity, ChannelBufferFactory factory) { return new DynamicChannelBuffer(capacity, factory); } @@ -86,8 +83,7 @@ public final class ChannelBuffers { return EMPTY_BUFFER; } - ChannelBuffer buffer = new ByteBufferBackedChannelBuffer( - ByteBuffer.allocateDirect(capacity)); + ChannelBuffer buffer = new ByteBufferBackedChannelBuffer(ByteBuffer.allocateDirect(capacity)); buffer.clear(); return buffer; } @@ -176,5 +172,4 @@ public final class ChannelBuffers { return aLen - bLen; } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/DirectChannelBufferFactory.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/DirectChannelBufferFactory.java index 0b99a6cb31..4fd2922435 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/DirectChannelBufferFactory.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/DirectChannelBufferFactory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.buffer; import java.nio.ByteBuffer; @@ -74,5 +73,4 @@ public class DirectChannelBufferFactory implements ChannelBufferFactory { nioBuffer.position(pos); return buf; } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/DynamicChannelBuffer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/DynamicChannelBuffer.java index cfd7965ffe..6733d83a50 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/DynamicChannelBuffer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/DynamicChannelBuffer.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.buffer; import java.io.IOException; @@ -60,13 +59,11 @@ public class DynamicChannelBuffer extends AbstractChannelBuffer { buffer = newBuffer; } - @Override public int capacity() { return buffer.capacity(); } - @Override public ChannelBuffer copy(int index, int length) { DynamicChannelBuffer copiedBuffer = new DynamicChannelBuffer(Math.max(length, 64), factory()); @@ -75,79 +72,66 @@ public class DynamicChannelBuffer extends AbstractChannelBuffer { return copiedBuffer; } - @Override public ChannelBufferFactory factory() { return factory; } - @Override public byte getByte(int index) { return buffer.getByte(index); } - @Override public void getBytes(int index, byte[] dst, int dstIndex, int length) { buffer.getBytes(index, dst, dstIndex, length); } - @Override public void getBytes(int index, ByteBuffer dst) { buffer.getBytes(index, dst); } - @Override public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { buffer.getBytes(index, dst, dstIndex, length); } - @Override public void getBytes(int index, OutputStream dst, int length) throws IOException { buffer.getBytes(index, dst, length); } - @Override public boolean isDirect() { return buffer.isDirect(); } - @Override public void setByte(int index, int value) { buffer.setByte(index, value); } - @Override public void setBytes(int index, byte[] src, int srcIndex, int length) { buffer.setBytes(index, src, srcIndex, length); } - @Override public void setBytes(int index, ByteBuffer src) { buffer.setBytes(index, src); } - @Override public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { buffer.setBytes(index, src, srcIndex, length); } - @Override public int setBytes(int index, InputStream src, int length) throws IOException { return buffer.setBytes(index, src, length); } - @Override public ByteBuffer toByteBuffer(int index, int length) { return buffer.toByteBuffer(index, length); @@ -183,19 +167,16 @@ public class DynamicChannelBuffer extends AbstractChannelBuffer { return super.writeBytes(in, length); } - @Override public byte[] array() { return buffer.array(); } - @Override public boolean hasArray() { return buffer.hasArray(); } - @Override public int arrayOffset() { return buffer.arrayOffset(); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/HeapChannelBuffer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/HeapChannelBuffer.java index 2d1e32ec02..623c9faed6 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/HeapChannelBuffer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/HeapChannelBuffer.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.buffer; import java.io.IOException; @@ -115,13 +114,11 @@ public class HeapChannelBuffer extends AbstractChannelBuffer { } @Override - public void getBytes(int index, OutputStream out, int length) - throws IOException { + public void getBytes(int index, OutputStream out, int length) throws IOException { out.write(array, index, length); } - public int getBytes(int index, GatheringByteChannel out, int length) - throws IOException { + public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { return out.write(ByteBuffer.wrap(array, index, length)); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/HeapChannelBufferFactory.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/HeapChannelBufferFactory.java index 11e1b0afe7..5b2b5374c7 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/HeapChannelBufferFactory.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/HeapChannelBufferFactory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.buffer; import java.nio.ByteBuffer; @@ -53,5 +52,4 @@ public class HeapChannelBufferFactory implements ChannelBufferFactory { nioBuffer.position(pos); return buf; } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeClient.java index 8ce3fac479..67988f9736 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeClient.java @@ -23,6 +23,4 @@ import org.apache.dubbo.remoting.Client; * * */ -public interface ExchangeClient extends Client, ExchangeChannel { - -} +public interface ExchangeClient extends Client, ExchangeChannel {} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeHandler.java index 118c932805..57d61a8208 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeHandler.java @@ -36,5 +36,4 @@ public interface ExchangeHandler extends ChannelHandler, TelnetHandler { * @throws RemotingException */ CompletableFuture reply(ExchangeChannel channel, Object request) throws RemotingException; - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeServer.java index f8565c4125..3e519c2ac1 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/ExchangeServer.java @@ -40,5 +40,4 @@ public interface ExchangeServer extends RemotingServer { * @return channel */ ExchangeChannel getExchangeChannel(InetSocketAddress remoteAddress); - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchanger.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchanger.java index 9b94db8bd7..fd3d19819f 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchanger.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchanger.java @@ -52,5 +52,4 @@ public interface Exchanger { */ @Adaptive({Constants.EXCHANGER_KEY}) ExchangeClient connect(URL url, ExchangeHandler handler) throws RemotingException; - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchangers.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchangers.java index c8f9b9da14..080ca5e352 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchangers.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchangers.java @@ -28,8 +28,7 @@ import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter; * Exchanger facade. (API, Static, ThreadSafe) */ public class Exchangers { - private Exchangers() { - } + private Exchangers() {} public static ExchangeServer bind(String url, Replier replier) throws RemotingException { return bind(URL.valueOf(url), replier); @@ -78,7 +77,8 @@ public class Exchangers { return connect(url, new ChannelHandlerAdapter(), replier); } - public static ExchangeClient connect(String url, ChannelHandler handler, Replier replier) throws RemotingException { + public static ExchangeClient connect(String url, ChannelHandler handler, Replier replier) + throws RemotingException { return connect(URL.valueOf(url), handler, replier); } @@ -102,7 +102,8 @@ public class Exchangers { public static Exchanger getExchanger(URL url) { String type = url.getParameter(Constants.EXCHANGER_KEY, Constants.DEFAULT_EXCHANGER); - return url.getOrDefaultFrameworkModel().getExtensionLoader(Exchanger.class).getExtension(type); + return url.getOrDefaultFrameworkModel() + .getExtensionLoader(Exchanger.class) + .getExtension(type); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/HeartBeatResponse.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/HeartBeatResponse.java index 35d4477c49..e85a2e8a7b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/HeartBeatResponse.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/HeartBeatResponse.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.remoting.exchange; -public class HeartBeatResponse extends Response{ +public class HeartBeatResponse extends Response { private byte proto; public HeartBeatResponse(long id, String version) { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/PortUnificationExchanger.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/PortUnificationExchanger.java index 26252adc98..58da07715f 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/PortUnificationExchanger.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/PortUnificationExchanger.java @@ -35,7 +35,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERR public class PortUnificationExchanger { - private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(PortUnificationExchanger.class); + private static final ErrorTypeAwareLogger log = + LoggerFactory.getErrorTypeAwareLogger(PortUnificationExchanger.class); private static final ConcurrentMap servers = new ConcurrentHashMap<>(); public static RemotingServer bind(URL url, ChannelHandler handler) { @@ -85,8 +86,8 @@ public class PortUnificationExchanger { } public static PortUnificationTransporter getTransporter(URL url) { - return url.getOrDefaultFrameworkModel().getExtensionLoader(PortUnificationTransporter.class) - .getAdaptiveExtension(); + return url.getOrDefaultFrameworkModel() + .getExtensionLoader(PortUnificationTransporter.class) + .getAdaptiveExtension(); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Request.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Request.java index 20d80453d6..bab83e2023 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Request.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Request.java @@ -174,6 +174,7 @@ public class Request { @Override public String toString() { return "Request [id=" + mId + ", version=" + mVersion + ", twoWay=" + mTwoWay + ", event=" + mEvent - + ", broken=" + mBroken + ", mPayload=" + mPayload + ", data=" + (mData == this ? "this" : safeToString(mData)) + "]"; + + ", broken=" + mBroken + ", mPayload=" + mPayload + ", data=" + + (mData == this ? "this" : safeToString(mData)) + "]"; } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Response.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Response.java index 1a4c15eb13..32dbb38275 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Response.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Response.java @@ -95,8 +95,7 @@ public class Response { private Object mResult; - public Response() { - } + public Response() {} public Response(long id) { mId = id; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/codec/ExchangeCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/codec/ExchangeCodec.java index 717f894cc7..4eeccebca7 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/codec/ExchangeCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/codec/ExchangeCodec.java @@ -95,8 +95,7 @@ public class ExchangeCodec extends TelnetCodec { @Override protected Object decode(Channel channel, ChannelBuffer buffer, int readable, byte[] header) throws IOException { // check magic number. - if (readable > 0 && header[0] != MAGIC_HIGH - || readable > 1 && header[1] != MAGIC_LOW) { + if (readable > 0 && header[0] != MAGIC_HIGH || readable > 1 && header[1] != MAGIC_LOW) { int length = header.length; if (header.length < readable) { header = Bytes.copyOf(header, readable); @@ -172,14 +171,22 @@ public class ExchangeCodec extends TelnetCodec { // heart beat response data is always null; data = null; } else { - data = decodeEventData(channel, CodecSupport.deserialize(channel.getUrl(), new ByteArrayInputStream(eventPayload), proto), eventPayload); + data = decodeEventData( + channel, + CodecSupport.deserialize( + channel.getUrl(), new ByteArrayInputStream(eventPayload), proto), + eventPayload); } } else { - data = decodeResponseData(channel, CodecSupport.deserialize(channel.getUrl(), is, proto), getRequestData(channel, res, id)); + data = decodeResponseData( + channel, + CodecSupport.deserialize(channel.getUrl(), is, proto), + getRequestData(channel, res, id)); } res.setResult(data); } else { - res.setErrorMessage(CodecSupport.deserialize(channel.getUrl(), is, proto).readUTF()); + res.setErrorMessage(CodecSupport.deserialize(channel.getUrl(), is, proto) + .readUTF()); } } catch (Throwable t) { res.setStatus(Response.CLIENT_ERROR); @@ -200,7 +207,11 @@ public class ExchangeCodec extends TelnetCodec { data = null; } else { req = new Request(id); - data = decodeEventData(channel, CodecSupport.deserialize(channel.getUrl(), new ByteArrayInputStream(eventPayload), proto), eventPayload); + data = decodeEventData( + channel, + CodecSupport.deserialize( + channel.getUrl(), new ByteArrayInputStream(eventPayload), proto), + eventPayload); } req.setEvent(true); } else { @@ -229,11 +240,17 @@ public class ExchangeCodec extends TelnetCodec { } } - logger.warn(PROTOCOL_TIMEOUT_SERVER, "", "", "The timeout response finally returned at " - + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())) - + ", response status is " + response.getStatus() + ", response id is " + response.getId() - + (channel == null ? "" : ", channel: " + channel.getLocalAddress() - + " -> " + channel.getRemoteAddress()) + ", please check provider side for detailed result."); + logger.warn( + PROTOCOL_TIMEOUT_SERVER, + "", + "", + "The timeout response finally returned at " + + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())) + + ", response status is " + response.getStatus() + ", response id is " + response.getId() + + (channel == null + ? "" + : ", channel: " + channel.getLocalAddress() + " -> " + channel.getRemoteAddress()) + + ", please check provider side for detailed result."); throw new IllegalArgumentException("Failed to find any request match the response, response id: " + id); } @@ -364,17 +381,34 @@ public class ExchangeCodec extends TelnetCodec { channel.send(r); return; } catch (RemotingException e) { - logger.warn(TRANSPORT_FAILED_RESPONSE, "", "", "Failed to send bad_response info back: " + t.getMessage() + ", cause: " + e.getMessage(), e); + logger.warn( + TRANSPORT_FAILED_RESPONSE, + "", + "", + "Failed to send bad_response info back: " + t.getMessage() + ", cause: " + + e.getMessage(), + e); } } else { // FIXME log error message in Codec and handle in caught() of IoHanndler? - logger.warn(TRANSPORT_FAILED_RESPONSE, "", "", "Fail to encode response: " + res + ", send bad_response info instead, cause: " + t.getMessage(), t); + logger.warn( + TRANSPORT_FAILED_RESPONSE, + "", + "", + "Fail to encode response: " + res + ", send bad_response info instead, cause: " + + t.getMessage(), + t); try { r.setErrorMessage("Failed to send response: " + res + ", cause: " + StringUtils.toString(t)); channel.send(r); return; } catch (RemotingException e) { - logger.warn(TRANSPORT_FAILED_RESPONSE, "", "", "Failed to send bad_response info back: " + res + ", cause: " + e.getMessage(), e); + logger.warn( + TRANSPORT_FAILED_RESPONSE, + "", + "", + "Failed to send bad_response info back: " + res + ", cause: " + e.getMessage(), + e); } } } @@ -444,9 +478,12 @@ public class ExchangeCodec extends TelnetCodec { try { if (eventBytes != null) { int dataLen = eventBytes.length; - int threshold = ConfigurationUtils.getSystemConfiguration(channel.getUrl().getScopeModel()).getInt("deserialization.event.size", 15); + int threshold = ConfigurationUtils.getSystemConfiguration( + channel.getUrl().getScopeModel()) + .getInt("deserialization.event.size", 15); if (dataLen > threshold) { - throw new IllegalArgumentException("Event data too long, actual size " + threshold + ", threshold " + threshold + " rejected for security consideration."); + throw new IllegalArgumentException("Event data too long, actual size " + threshold + ", threshold " + + threshold + " rejected for security consideration."); } } return in.readEvent(); @@ -489,11 +526,13 @@ public class ExchangeCodec extends TelnetCodec { encodeResponseData(out, data); } - protected void encodeRequestData(Channel channel, ObjectOutput out, Object data, String version) throws IOException { + protected void encodeRequestData(Channel channel, ObjectOutput out, Object data, String version) + throws IOException { encodeRequestData(out, data); } - protected void encodeResponseData(Channel channel, ObjectOutput out, Object data, String version) throws IOException { + protected void encodeResponseData(Channel channel, ObjectOutput out, Object data, String version) + throws IOException { encodeResponseData(out, data); } @@ -509,7 +548,8 @@ public class ExchangeCodec extends TelnetCodec { res.setEvent(true); } res.setStatus(Response.CLIENT_ERROR); - String errorMsg = "Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel; + String errorMsg = + "Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel; logger.error(TRANSPORT_EXCEED_PAYLOAD_LIMIT, "", "", errorMsg); res.setErrorMessage(errorMsg); return res; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java index 75544e9927..9f2e9c2d21 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/DefaultFuture.java @@ -61,7 +61,9 @@ public class DefaultFuture extends CompletableFuture { */ private static final Map FUTURES = new ConcurrentHashMap<>(); - private static final GlobalResourceInitializer TIME_OUT_TIMER = new GlobalResourceInitializer<>(() -> new HashedWheelTimer(new NamedThreadFactory("dubbo-future-timeout", true), 30, TimeUnit.MILLISECONDS), DefaultFuture::destroy); + private static final GlobalResourceInitializer TIME_OUT_TIMER = new GlobalResourceInitializer<>( + () -> new HashedWheelTimer(new NamedThreadFactory("dubbo-future-timeout", true), 30, TimeUnit.MILLISECONDS), + DefaultFuture::destroy); // invoke id. private final Long id; @@ -162,10 +164,14 @@ public class DefaultFuture extends CompletableFuture { try { future.get(restTime, TimeUnit.MILLISECONDS); } catch (java.util.concurrent.TimeoutException ignore) { - logger.warn(PROTOCOL_TIMEOUT_SERVER, "", "", - "Trying to close channel " + channel + ", but response is not received in " - + timeout + "ms, and the request id is " + future.id); - } catch (Throwable ignore) {} + logger.warn( + PROTOCOL_TIMEOUT_SERVER, + "", + "", + "Trying to close channel " + channel + ", but response is not received in " + + timeout + "ms, and the request id is " + future.id); + } catch (Throwable ignore) { + } } if (!future.isDone()) { respInactive(channel, future); @@ -178,9 +184,11 @@ public class DefaultFuture extends CompletableFuture { private static void respInactive(Channel channel, DefaultFuture future) { Response disconnectResponse = new Response(future.getId()); disconnectResponse.setStatus(Response.CHANNEL_INACTIVE); - disconnectResponse.setErrorMessage("Channel " + - channel + " is inactive. Directly return the unFinished request : " + - (logger.isDebugEnabled() ? future.getRequest() : future.getRequest().copyWithoutData())); + disconnectResponse.setErrorMessage("Channel " + channel + + " is inactive. Directly return the unFinished request : " + + (logger.isDebugEnabled() + ? future.getRequest() + : future.getRequest().copyWithoutData())); DefaultFuture.received(channel, disconnectResponse); } @@ -200,11 +208,18 @@ public class DefaultFuture extends CompletableFuture { future.doReceived(response); shutdownExecutorIfNeeded(future); } else { - logger.warn(PROTOCOL_TIMEOUT_SERVER, "", "", "The timeout response finally returned at " - + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())) - + ", response status is " + response.getStatus() - + (channel == null ? "" : ", channel: " + channel.getLocalAddress() - + " -> " + channel.getRemoteAddress()) + ", please check provider side for detailed result."); + logger.warn( + PROTOCOL_TIMEOUT_SERVER, + "", + "", + "The timeout response finally returned at " + + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())) + + ", response status is " + response.getStatus() + + (channel == null + ? "" + : ", channel: " + channel.getLocalAddress() + " -> " + + channel.getRemoteAddress()) + + ", please check provider side for detailed result."); } } finally { CHANNELS.remove(response.getId()); @@ -242,10 +257,11 @@ public class DefaultFuture extends CompletableFuture { if (res.getStatus() == Response.OK) { this.complete(res.getResult()); } else if (res.getStatus() == Response.CLIENT_TIMEOUT || res.getStatus() == Response.SERVER_TIMEOUT) { - this.completeExceptionally(new TimeoutException(res.getStatus() == Response.SERVER_TIMEOUT, channel, res.getErrorMessage())); - } else if(res.getStatus() == Response.SERIALIZATION_ERROR){ + this.completeExceptionally( + new TimeoutException(res.getStatus() == Response.SERVER_TIMEOUT, channel, res.getErrorMessage())); + } else if (res.getStatus() == Response.SERIALIZATION_ERROR) { this.completeExceptionally(new SerializationException(res.getErrorMessage())); - }else { + } else { this.completeExceptionally(new RemotingException(channel, res.getErrorMessage())); } } @@ -276,18 +292,21 @@ public class DefaultFuture extends CompletableFuture { private String getTimeoutMessage(boolean scan) { long nowTimestamp = System.currentTimeMillis(); - return (sent > 0 && sent - start < timeout ? "Waiting server-side response timeout" : "Sending request timeout in client-side") - + (scan ? " by scan timer" : "") + ". start time: " - + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(start))) + ", end time: " - + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(nowTimestamp))) + "," - + (sent > 0 ? " client elapsed: " + (sent - start) - + " ms, server elapsed: " + (nowTimestamp - sent) - : " elapsed: " + (nowTimestamp - start)) + " ms, timeout: " - + timeout + " ms, request: " + (logger.isDebugEnabled() ? request : request.copyWithoutData()) + ", channel: " + channel.getLocalAddress() - + " -> " + channel.getRemoteAddress(); + return (sent > 0 && sent - start < timeout + ? "Waiting server-side response timeout" + : "Sending request timeout in client-side") + + (scan ? " by scan timer" : "") + ". start time: " + + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(start))) + ", end time: " + + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(nowTimestamp))) + "," + + (sent > 0 + ? " client elapsed: " + (sent - start) + " ms, server elapsed: " + (nowTimestamp - sent) + : " elapsed: " + (nowTimestamp - start)) + + " ms, timeout: " + + timeout + " ms, request: " + (logger.isDebugEnabled() ? request : request.copyWithoutData()) + + ", channel: " + channel.getLocalAddress() + + " -> " + channel.getRemoteAddress(); } - private static class TimeoutCheckTask implements TimerTask { private final Long requestID; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ExchangeHandlerAdapter.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ExchangeHandlerAdapter.java index 6b923cfb5e..cabb3683a2 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ExchangeHandlerAdapter.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ExchangeHandlerAdapter.java @@ -36,5 +36,4 @@ public abstract class ExchangeHandlerAdapter extends TelnetHandlerAdapter implem public CompletableFuture reply(ExchangeChannel channel, Object msg) throws RemotingException { return null; } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ExchangeHandlerDispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ExchangeHandlerDispatcher.java index 066c700187..44680de02f 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ExchangeHandlerDispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ExchangeHandlerDispatcher.java @@ -112,5 +112,4 @@ public class ExchangeHandlerDispatcher implements ExchangeHandler { public String telnet(Channel channel, String message) throws RemotingException { return telnetHandler.telnet(channel, message); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ExchangeServerDelegate.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ExchangeServerDelegate.java index 8fdc4289b5..e6dff6291b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ExchangeServerDelegate.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ExchangeServerDelegate.java @@ -33,8 +33,7 @@ public class ExchangeServerDelegate implements ExchangeServer { private transient ExchangeServer server; - public ExchangeServerDelegate() { - } + public ExchangeServerDelegate() {} public ExchangeServerDelegate(ExchangeServer server) { setServer(server); @@ -128,5 +127,4 @@ public class ExchangeServerDelegate implements ExchangeServer { public void startClose() { server.startClose(); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/MultiMessage.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/MultiMessage.java index dbe3bff714..2821a0b823 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/MultiMessage.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/MultiMessage.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.exchange.support; import java.util.ArrayList; @@ -31,8 +30,7 @@ public final class MultiMessage implements Iterable { private final List messages = new ArrayList(); - private MultiMessage() { - } + private MultiMessage() {} public static MultiMessage createFromCollection(Collection collection) { MultiMessage result = new MultiMessage(); @@ -82,5 +80,4 @@ public final class MultiMessage implements Iterable { public Iterator iterator() { return messages.iterator(); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/Replier.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/Replier.java index 1be0c1cb1c..194067637c 100755 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/Replier.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/Replier.java @@ -33,5 +33,4 @@ public interface Replier { * @throws RemotingException */ Object reply(ExchangeChannel channel, T request) throws RemotingException; - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ReplierDispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ReplierDispatcher.java index afb6052a31..549593a888 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ReplierDispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/ReplierDispatcher.java @@ -74,5 +74,4 @@ public class ReplierDispatcher implements Replier { public Object reply(ExchangeChannel channel, Object request) throws RemotingException { return ((Replier) getReplier(request.getClass())).reply(channel, request); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/AbstractTimerTask.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/AbstractTimerTask.java index ce5c5e6014..e9c1dfeada 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/AbstractTimerTask.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/AbstractTimerTask.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.exchange.support.header; import org.apache.dubbo.common.timer.HashedWheelTimer; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/CloseTimerTask.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/CloseTimerTask.java index aa4df8d053..ac75bb6432 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/CloseTimerTask.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/CloseTimerTask.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.exchange.support.header; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -34,7 +33,8 @@ public class CloseTimerTask extends AbstractTimerTask { private final int closeTimeout; - public CloseTimerTask(ChannelProvider channelProvider, HashedWheelTimer hashedWheelTimer, Long tick, int closeTimeout) { + public CloseTimerTask( + ChannelProvider channelProvider, HashedWheelTimer hashedWheelTimer, Long tick, int closeTimeout) { super(channelProvider, hashedWheelTimer, tick); this.closeTimeout = closeTimeout; } @@ -47,12 +47,21 @@ public class CloseTimerTask extends AbstractTimerTask { Long now = now(); // check ping & pong at server if ((lastRead != null && now - lastRead > closeTimeout) - || (lastWrite != null && now - lastWrite > closeTimeout)) { - logger.warn(PROTOCOL_FAILED_RESPONSE, "", "", "Close channel " + channel + ", because idleCheck timeout: " + closeTimeout + "ms"); + || (lastWrite != null && now - lastWrite > closeTimeout)) { + logger.warn( + PROTOCOL_FAILED_RESPONSE, + "", + "", + "Close channel " + channel + ", because idleCheck timeout: " + closeTimeout + "ms"); channel.close(); } } catch (Throwable t) { - logger.warn(TRANSPORT_FAILED_CLOSE, "", "", "Exception when close remote channel " + channel.getRemoteAddress(), t); + logger.warn( + TRANSPORT_FAILED_CLOSE, + "", + "", + "Exception when close remote channel " + channel.getRemoteAddress(), + t); } } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java index b4c7bb65a3..6145e985f9 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannel.java @@ -44,7 +44,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FA */ final class HeaderExchangeChannel implements ExchangeChannel { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(HeaderExchangeChannel.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(HeaderExchangeChannel.class); private static final String CHANNEL_KEY = HeaderExchangeChannel.class.getName() + ".CHANNEL"; @@ -60,9 +61,9 @@ final class HeaderExchangeChannel implements ExchangeChannel { } this.channel = channel; this.shutdownTimeout = Optional.ofNullable(channel.getUrl()) - .map(URL::getOrDefaultApplicationModel) - .map(ConfigurationUtils::getServerShutdownTimeout) - .orElse(DEFAULT_TIMEOUT); + .map(URL::getOrDefaultApplicationModel) + .map(ConfigurationUtils::getServerShutdownTimeout) + .orElse(DEFAULT_TIMEOUT); } static HeaderExchangeChannel getOrAddChannel(Channel ch) { @@ -99,11 +100,12 @@ final class HeaderExchangeChannel implements ExchangeChannel { @Override public void send(Object message, boolean sent) throws RemotingException { if (closed) { - throw new RemotingException(this.getLocalAddress(), null, "Failed to send message " + message + ", cause: The channel " + this + " is closed!"); + throw new RemotingException( + this.getLocalAddress(), + null, + "Failed to send message " + message + ", cause: The channel " + this + " is closed!"); } - if (message instanceof Request - || message instanceof Response - || message instanceof String) { + if (message instanceof Request || message instanceof Response || message instanceof String) { channel.send(message, sent); } else { Request request = new Request(); @@ -130,9 +132,13 @@ final class HeaderExchangeChannel implements ExchangeChannel { } @Override - public CompletableFuture request(Object request, int timeout, ExecutorService executor) throws RemotingException { + public CompletableFuture request(Object request, int timeout, ExecutorService executor) + throws RemotingException { if (closed) { - throw new RemotingException(this.getLocalAddress(), null, "Failed to send request " + request + ", cause: The channel " + this + " is closed!"); + throw new RemotingException( + this.getLocalAddress(), + null, + "Failed to send request " + request + ", cause: The channel " + this + " is closed!"); } Request req; if (request instanceof Request) { @@ -187,8 +193,7 @@ final class HeaderExchangeChannel implements ExchangeChannel { } if (timeout > 0) { long start = System.currentTimeMillis(); - while (DefaultFuture.hasFuture(channel) - && System.currentTimeMillis() - start < timeout) { + while (DefaultFuture.hasFuture(channel) && System.currentTimeMillis() - start < timeout) { try { Thread.sleep(10); } catch (InterruptedException e) { @@ -281,5 +286,4 @@ final class HeaderExchangeChannel implements ExchangeChannel { public String toString() { return channel.toString(); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java index 6b9dd53e95..e654b327c0 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeClient.java @@ -51,10 +51,13 @@ public class HeaderExchangeClient implements ExchangeClient { private final Client client; private final ExchangeChannel channel; - public static GlobalResourceInitializer IDLE_CHECK_TIMER = new GlobalResourceInitializer<>(() -> - new HashedWheelTimer(new NamedThreadFactory("dubbo-client-heartbeat-reconnect", true), 1, - TimeUnit.SECONDS, TICKS_PER_WHEEL), - HashedWheelTimer::stop); + public static GlobalResourceInitializer IDLE_CHECK_TIMER = new GlobalResourceInitializer<>( + () -> new HashedWheelTimer( + new NamedThreadFactory("dubbo-client-heartbeat-reconnect", true), + 1, + TimeUnit.SECONDS, + TICKS_PER_WHEEL), + HashedWheelTimer::stop); private ReconnectTimerTask reconnectTimerTask; private HeartbeatTimerTask heartBeatTimerTask; @@ -101,7 +104,8 @@ public class HeaderExchangeClient implements ExchangeClient { } @Override - public CompletableFuture request(Object request, int timeout, ExecutorService executor) throws RemotingException { + public CompletableFuture request(Object request, int timeout, ExecutorService executor) + throws RemotingException { return channel.request(request, timeout, executor); } @@ -209,15 +213,19 @@ public class HeaderExchangeClient implements ExchangeClient { if (!client.canHandleIdle()) { int heartbeat = getHeartbeat(url); long heartbeatTick = calculateLeastDuration(heartbeat); - heartBeatTimerTask = new HeartbeatTimerTask(() -> Collections.singleton(this), IDLE_CHECK_TIMER.get(), heartbeatTick, heartbeat); + heartBeatTimerTask = new HeartbeatTimerTask( + () -> Collections.singleton(this), IDLE_CHECK_TIMER.get(), heartbeatTick, heartbeat); } } private void startReconnectTask(URL url) { if (shouldReconnect(url)) { long heartbeatTimeoutTick = calculateLeastDuration(idleTimeout); - reconnectTimerTask = new ReconnectTimerTask(() -> Collections.singleton(this), IDLE_CHECK_TIMER.get(), - calculateReconnectDuration(url, heartbeatTimeoutTick), idleTimeout); + reconnectTimerTask = new ReconnectTimerTask( + () -> Collections.singleton(this), + IDLE_CHECK_TIMER.get(), + calculateReconnectDuration(url, heartbeatTimeoutTick), + idleTimeout); } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java index d1fc4cdd1a..cefa8bb20e 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeHandler.java @@ -43,13 +43,13 @@ import static org.apache.dubbo.common.constants.CommonConstants.WRITEABLE_EVENT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_RESPONSE; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNSUPPORTED_MESSAGE; - /** * ExchangeReceiver */ public class HeaderExchangeHandler implements ChannelHandlerDelegate { - protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(HeaderExchangeHandler.class); + protected static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(HeaderExchangeHandler.class); private final ExchangeHandler handler; @@ -69,9 +69,9 @@ public class HeaderExchangeHandler implements ChannelHandlerDelegate { private static boolean isClientSide(Channel channel) { InetSocketAddress address = channel.getRemoteAddress(); URL url = channel.getUrl(); - return url.getPort() == address.getPort() && - NetUtils.filterLocalHost(url.getIp()) - .equals(NetUtils.filterLocalHost(address.getAddress().getHostAddress())); + return url.getPort() == address.getPort() + && NetUtils.filterLocalHost(url.getIp()) + .equals(NetUtils.filterLocalHost(address.getAddress().getHostAddress())); } void handlerEvent(Channel channel, Request req) throws RemotingException { @@ -119,7 +119,11 @@ public class HeaderExchangeHandler implements ChannelHandlerDelegate { } channel.send(res); } catch (RemotingException e) { - logger.warn(TRANSPORT_FAILED_RESPONSE, "", "", "Send result to consumer failed, channel is " + channel + ", msg is " + e); + logger.warn( + TRANSPORT_FAILED_RESPONSE, + "", + "", + "Send result to consumer failed, channel is " + channel + ", msg is " + e); } }); } catch (Throwable e) { @@ -133,8 +137,9 @@ public class HeaderExchangeHandler implements ChannelHandlerDelegate { public void connected(Channel channel) throws RemotingException { ExchangeChannel exchangeChannel = HeaderExchangeChannel.getOrAddChannel(channel); handler.connected(exchangeChannel); - channel.setAttribute(Constants.CHANNEL_SHUTDOWN_TIMEOUT_KEY, - ConfigurationUtils.getServerShutdownTimeout(channel.getUrl().getOrDefaultApplicationModel())); + channel.setAttribute( + Constants.CHANNEL_SHUTDOWN_TIMEOUT_KEY, + ConfigurationUtils.getServerShutdownTimeout(channel.getUrl().getOrDefaultApplicationModel())); } @Override @@ -181,8 +186,8 @@ public class HeaderExchangeHandler implements ChannelHandlerDelegate { } else if (exception instanceof RemotingException) { throw (RemotingException) exception; } else { - throw new RemotingException(channel.getLocalAddress(), channel.getRemoteAddress(), - exception.getMessage(), exception); + throw new RemotingException( + channel.getLocalAddress(), channel.getRemoteAddress(), exception.getMessage(), exception); } } } @@ -206,7 +211,8 @@ public class HeaderExchangeHandler implements ChannelHandlerDelegate { handleResponse(channel, (Response) message); } else if (message instanceof String) { if (isClientSide(channel)) { - Exception e = new Exception("Dubbo client can not supported string message: " + message + " in channel: " + channel + ", url: " + channel.getUrl()); + Exception e = new Exception("Dubbo client can not supported string message: " + message + + " in channel: " + channel + ", url: " + channel.getUrl()); logger.error(TRANSPORT_UNSUPPORTED_MESSAGE, "", "", e.getMessage(), e); } else { String echo = handler.telnet(channel, (String) message); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java index 3dca5a9746..340c50c724 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServer.java @@ -62,7 +62,10 @@ public class HeaderExchangeServer implements ExchangeServer { private final AtomicBoolean closed = new AtomicBoolean(false); - public static GlobalResourceInitializer IDLE_CHECK_TIMER = new GlobalResourceInitializer<>(() -> new HashedWheelTimer(new NamedThreadFactory("dubbo-server-idleCheck", true), 1, TimeUnit.SECONDS, TICKS_PER_WHEEL), HashedWheelTimer::stop); + public static GlobalResourceInitializer IDLE_CHECK_TIMER = new GlobalResourceInitializer<>( + () -> new HashedWheelTimer( + new NamedThreadFactory("dubbo-server-idleCheck", true), 1, TimeUnit.SECONDS, TICKS_PER_WHEEL), + HashedWheelTimer::stop); private CloseTimerTask closeTimer; @@ -107,8 +110,7 @@ public class HeaderExchangeServer implements ExchangeServer { if (getUrl().getParameter(Constants.CHANNEL_SEND_READONLYEVENT_KEY, true)) { sendChannelReadOnlyEvent(); } - while (HeaderExchangeServer.this.isRunning() - && System.currentTimeMillis() - start < (long) timeout) { + while (HeaderExchangeServer.this.isRunning() && System.currentTimeMillis() - start < (long) timeout) { try { Thread.sleep(10); } catch (InterruptedException e) { @@ -230,8 +232,10 @@ public class HeaderExchangeServer implements ExchangeServer { @Override public void send(Object message) throws RemotingException { if (closed.get()) { - throw new RemotingException(this.getLocalAddress(), null, "Failed to send message " + message - + ", cause: The server " + getLocalAddress() + " is closed!"); + throw new RemotingException( + this.getLocalAddress(), + null, + "Failed to send message " + message + ", cause: The server " + getLocalAddress() + " is closed!"); } server.send(message); } @@ -239,8 +243,10 @@ public class HeaderExchangeServer implements ExchangeServer { @Override public void send(Object message, boolean sent) throws RemotingException { if (closed.get()) { - throw new RemotingException(this.getLocalAddress(), null, "Failed to send message " + message - + ", cause: The server " + getLocalAddress() + " is closed!"); + throw new RemotingException( + this.getLocalAddress(), + null, + "Failed to send message " + message + ", cause: The server " + getLocalAddress() + " is closed!"); } server.send(message, sent); } @@ -258,7 +264,8 @@ public class HeaderExchangeServer implements ExchangeServer { private void startIdleCheckTask(URL url) { if (!server.canHandleIdle()) { - AbstractTimerTask.ChannelProvider cp = () -> unmodifiableCollection(HeaderExchangeServer.this.getChannels()); + AbstractTimerTask.ChannelProvider cp = + () -> unmodifiableCollection(HeaderExchangeServer.this.getChannels()); int closeTimeout = getCloseTimeout(url); long closeTimeoutTick = calculateLeastDuration(closeTimeout); this.closeTimer = new CloseTimerTask(cp, IDLE_CHECK_TIMER.get(), closeTimeoutTick, closeTimeout); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchanger.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchanger.java index 67f2440d83..7c6b4d51be 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchanger.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchanger.java @@ -39,19 +39,21 @@ public class HeaderExchanger implements Exchanger { @Override public ExchangeClient connect(URL url, ExchangeHandler handler) throws RemotingException { - return new HeaderExchangeClient(Transporters.connect(url, new DecodeHandler(new HeaderExchangeHandler(handler))), true); + return new HeaderExchangeClient( + Transporters.connect(url, new DecodeHandler(new HeaderExchangeHandler(handler))), true); } @Override public ExchangeServer bind(URL url, ExchangeHandler handler) throws RemotingException { ExchangeServer server; boolean isPuServerKey = url.getParameter(IS_PU_SERVER_KEY, false); - if(isPuServerKey) { - server = new HeaderExchangeServer(PortUnificationExchanger.bind(url, new DecodeHandler(new HeaderExchangeHandler(handler)))); - }else { - server = new HeaderExchangeServer(Transporters.bind(url, new DecodeHandler(new HeaderExchangeHandler(handler)))); + if (isPuServerKey) { + server = new HeaderExchangeServer( + PortUnificationExchanger.bind(url, new DecodeHandler(new HeaderExchangeHandler(handler)))); + } else { + server = new HeaderExchangeServer( + Transporters.bind(url, new DecodeHandler(new HeaderExchangeHandler(handler)))); } return server; } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandler.java index f1bb03cbef..56470f0203 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandler.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.exchange.support.header; import org.apache.dubbo.common.logger.Logger; @@ -77,15 +76,16 @@ public class HeartbeatHandler extends AbstractChannelHandlerDelegate { if (logger.isDebugEnabled()) { int heartbeat = channel.getUrl().getParameter(Constants.HEARTBEAT_KEY, 0); logger.debug("Received heartbeat from remote channel " + channel.getRemoteAddress() - + ", cause: The channel has no data-transmission exceeds a heartbeat period" - + (heartbeat > 0 ? ": " + heartbeat + "ms" : "")); + + ", cause: The channel has no data-transmission exceeds a heartbeat period" + + (heartbeat > 0 ? ": " + heartbeat + "ms" : "")); } } return; } if (isHeartbeatResponse(message)) { if (logger.isDebugEnabled()) { - logger.debug("Receive heartbeat response in thread " + Thread.currentThread().getName()); + logger.debug("Receive heartbeat response in thread " + + Thread.currentThread().getName()); } return; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatTimerTask.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatTimerTask.java index e418a1de99..6c3c3eaad1 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatTimerTask.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatTimerTask.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.exchange.support.header; import org.apache.dubbo.common.Version; @@ -36,7 +35,8 @@ public class HeartbeatTimerTask extends AbstractTimerTask { private final int heartbeat; - HeartbeatTimerTask(ChannelProvider channelProvider, HashedWheelTimer hashedWheelTimer, Long heartbeatTick, int heartbeat) { + HeartbeatTimerTask( + ChannelProvider channelProvider, HashedWheelTimer hashedWheelTimer, Long heartbeatTick, int heartbeat) { super(channelProvider, hashedWheelTimer, heartbeatTick); this.heartbeat = heartbeat; } @@ -48,7 +48,7 @@ public class HeartbeatTimerTask extends AbstractTimerTask { Long lastWrite = lastWrite(channel); Long now = now(); if ((lastRead != null && now - lastRead > heartbeat) - || (lastWrite != null && now - lastWrite > heartbeat)) { + || (lastWrite != null && now - lastWrite > heartbeat)) { Request req = new Request(); req.setVersion(Version.getProtocolVersion()); req.setTwoWay(true); @@ -56,12 +56,17 @@ public class HeartbeatTimerTask extends AbstractTimerTask { channel.send(req); if (logger.isDebugEnabled()) { logger.debug("Send heartbeat to remote channel " + channel.getRemoteAddress() - + ", cause: The channel has no data-transmission exceeds a heartbeat period: " - + heartbeat + "ms"); + + ", cause: The channel has no data-transmission exceeds a heartbeat period: " + + heartbeat + "ms"); } } } catch (Throwable t) { - logger.warn(TRANSPORT_FAILED_RESPONSE, "", "", "Exception when heartbeat to remote channel " + channel.getRemoteAddress(), t); + logger.warn( + TRANSPORT_FAILED_RESPONSE, + "", + "", + "Exception when heartbeat to remote channel " + channel.getRemoteAddress(), + t); } } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/ReconnectTimerTask.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/ReconnectTimerTask.java index 506ec003c1..354df1b689 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/ReconnectTimerTask.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/ReconnectTimerTask.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.exchange.support.header; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -35,7 +34,11 @@ public class ReconnectTimerTask extends AbstractTimerTask { private final int idleTimeout; - public ReconnectTimerTask(ChannelProvider channelProvider, HashedWheelTimer hashedWheelTimer, Long heartbeatTimeoutTick, int idleTimeout) { + public ReconnectTimerTask( + ChannelProvider channelProvider, + HashedWheelTimer hashedWheelTimer, + Long heartbeatTimeoutTick, + int idleTimeout) { super(channelProvider, hashedWheelTimer, heartbeatTimeoutTick); this.idleTimeout = idleTimeout; } @@ -56,8 +59,12 @@ public class ReconnectTimerTask extends AbstractTimerTask { } // check pong at client } else if (lastRead != null && now - lastRead > idleTimeout) { - logger.warn(TRANSPORT_FAILED_RECONNECT, "", "", "Reconnect to channel " + channel + ", because heartbeat read idle time out: " - + idleTimeout + "ms"); + logger.warn( + TRANSPORT_FAILED_RECONNECT, + "", + "", + "Reconnect to channel " + channel + ", because heartbeat read idle time out: " + idleTimeout + + "ms"); try { ((Client) channel).reconnect(); } catch (Exception e) { @@ -65,7 +72,12 @@ public class ReconnectTimerTask extends AbstractTimerTask { } } } catch (Throwable t) { - logger.warn(INTERNAL_ERROR, "unknown error in remoting module", "", "Exception when reconnect to remote channel " + channel.getRemoteAddress(), t); + logger.warn( + INTERNAL_ERROR, + "unknown error in remoting module", + "", + "Exception when reconnect to remote channel " + channel.getRemoteAddress(), + t); } } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/TelnetHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/TelnetHandler.java index fe3acb776c..3d8ea36d54 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/TelnetHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/TelnetHandler.java @@ -34,5 +34,4 @@ public interface TelnetHandler { * @param message */ String telnet(Channel channel, String message) throws RemotingException; - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/codec/TelnetCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/codec/TelnetCodec.java index 9cfd979e17..c106572e3f 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/codec/TelnetCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/codec/TelnetCodec.java @@ -48,18 +48,17 @@ public class TelnetCodec extends TransportCodec { private static final String HISTORY_INDEX_KEY = "telnet.history.index"; - private static final byte[] UP = new byte[]{27, 91, 65}; + private static final byte[] UP = new byte[] {27, 91, 65}; - private static final byte[] DOWN = new byte[]{27, 91, 66}; + private static final byte[] DOWN = new byte[] {27, 91, 66}; - private static final List ENTER = Arrays.asList( - new byte[]{'\r', '\n'} /* Windows Enter */, - new byte[]{'\n'} /* Linux Enter */); + private static final List ENTER = + Arrays.asList(new byte[] {'\r', '\n'} /* Windows Enter */, new byte[] {'\n'} /* Linux Enter */); private static final List EXIT = Arrays.asList( - new byte[]{3} /* Windows Ctrl+C */, - new byte[]{-1, -12, -1, -3, 6} /* Linux Ctrl+C */, - new byte[]{-1, -19, -1, -3, 6} /* Linux Pause */); + new byte[] {3} /* Windows Ctrl+C */, + new byte[] {-1, -12, -1, -3, 6} /* Linux Ctrl+C */, + new byte[] {-1, -19, -1, -3, 6} /* Linux Pause */); private static Charset getCharset(Channel channel) { if (channel != null) { @@ -115,8 +114,9 @@ public class TelnetCodec extends TransportCodec { } else if (i < message.length - 2) { i = i + 2; } - } else if (b == -1 && i < message.length - 2 - && (message[i + 1] == -3 || message[i + 1] == -5)) { // handshake + } else if (b == -1 + && i < message.length - 2 + && (message[i + 1] == -3 || message[i + 1] == -5)) { // handshake i = i + 2; } else { copy[index++] = message[i]; @@ -179,7 +179,9 @@ public class TelnetCodec extends TransportCodec { if (message[message.length - 1] == '\b') { // Windows backspace echo try { boolean isDoubleChar = message.length >= 3 && message[message.length - 3] < 0; // double byte char - channel.send(new String(isDoubleChar ? new byte[]{32, 32, 8, 8} : new byte[]{32, 8}, getCharset(channel).name())); + channel.send(new String( + isDoubleChar ? new byte[] {32, 32, 8, 8} : new byte[] {32, 8}, + getCharset(channel).name())); } catch (RemotingException e) { throw new IOException(StringUtils.toString(e)); } @@ -189,7 +191,8 @@ public class TelnetCodec extends TransportCodec { for (Object command : EXIT) { if (isEquals(message, (byte[]) command)) { if (logger.isInfoEnabled()) { - logger.info(new Exception("Close channel " + channel + " on exit command: " + Arrays.toString((byte[]) command))); + logger.info(new Exception( + "Close channel " + channel + " on exit command: " + Arrays.toString((byte[]) command))); } channel.close(); return null; @@ -295,5 +298,4 @@ public class TelnetCodec extends TransportCodec { } return result; } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/Help.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/Help.java index cc8f2ba98a..23df4bf891 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/Help.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/Help.java @@ -35,5 +35,4 @@ public @interface Help { String summary(); String detail() default ""; - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java index cb18ed7cb1..2e3d0308c1 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java @@ -72,7 +72,8 @@ public class TelnetHandlerAdapter extends ChannelHandlerAdapter implements Telne } else { buf.append("Command: "); buf.append(command); - buf.append(" disabled for security reasons, please enable support by listing the commands through 'telnet'"); + buf.append( + " disabled for security reasons, please enable support by listing the commands through 'telnet'"); } } else { buf.append("Unsupported command: "); @@ -101,5 +102,4 @@ public class TelnetHandlerAdapter extends ChannelHandlerAdapter implements Telne } return false; } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetUtils.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetUtils.java index 009f6ba4c3..8a78d599ff 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetUtils.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/TelnetUtils.java @@ -80,7 +80,7 @@ public class TelnetUtils { } widths[widths.length - 1] = Math.min(widths[widths.length - 1], maxwidth - maxcountbefore); StringBuilder buf = new StringBuilder(); - //line + // line buf.append('+'); for (int j = 0; j < widths.length; j++) { for (int k = 0; k < widths[j] + 2; k++) { @@ -89,7 +89,7 @@ public class TelnetUtils { buf.append('+'); } buf.append("\r\n"); - //header + // header buf.append('|'); for (int j = 0; j < widths.length; j++) { String cell = header.get(j); @@ -104,7 +104,7 @@ public class TelnetUtils { buf.append(" |"); } buf.append("\r\n"); - //line + // line buf.append('+'); for (int j = 0; j < widths.length; j++) { for (int k = 0; k < widths[j] + 2; k++) { @@ -113,7 +113,7 @@ public class TelnetUtils { buf.append('+'); } buf.append("\r\n"); - //content + // content for (List row : table) { StringBuilder rowbuf = new StringBuilder(); rowbuf.append('|'); @@ -126,9 +126,10 @@ public class TelnetUtils { if (rowbuf.length() >= totalWidth) { buf.append(rowbuf.toString()); rowbuf = new StringBuilder(); -// for(int m = 0;m < maxcountbefore && maxcountbefore < totalWidth ; m++){ -// rowbuf.append(" "); -// } + // for(int m = 0;m < maxcountbefore && maxcountbefore < totalWidth ; + // m++){ + // rowbuf.append(" "); + // } } rowbuf.append(cell, cell.length() - remaing, cell.length() - remaing + 1); @@ -144,7 +145,7 @@ public class TelnetUtils { } buf.append(rowbuf).append("\r\n"); } - //line + // line buf.append('+'); for (int j = 0; j < widths.length; j++) { for (int k = 0; k < widths[j] + 2; k++) { @@ -155,5 +156,4 @@ public class TelnetUtils { buf.append("\r\n"); return buf.toString(); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/ClearTelnetHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/ClearTelnetHandler.java index f7de70eaeb..5af5551de0 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/ClearTelnetHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/ClearTelnetHandler.java @@ -37,7 +37,7 @@ public class ClearTelnetHandler implements TelnetHandler { if (!StringUtils.isNumber(message)) { return "Illegal lines " + message + ", must be integer."; } - lines = Math.min(MAX_LINES,Integer.parseInt(message)); + lines = Math.min(MAX_LINES, Integer.parseInt(message)); } StringBuilder buf = new StringBuilder(); for (int i = 0; i < lines; i++) { @@ -45,5 +45,4 @@ public class ClearTelnetHandler implements TelnetHandler { } return buf.toString(); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/ExitTelnetHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/ExitTelnetHandler.java index becf205bb6..829abfda64 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/ExitTelnetHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/ExitTelnetHandler.java @@ -33,5 +33,4 @@ public class ExitTelnetHandler implements TelnetHandler { channel.close(); return null; } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/HelpTelnetHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/HelpTelnetHandler.java index 04c8142766..da5b727398 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/HelpTelnetHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/HelpTelnetHandler.java @@ -50,9 +50,9 @@ public class HelpTelnetHandler implements TelnetHandler { @Override public String telnet(Channel channel, String message) { if (message.length() > 0) { - return processedTable.computeIfAbsent(message, commandName -> generateForOneCommand(commandName)); + return processedTable.computeIfAbsent(message, commandName -> generateForOneCommand(commandName)); } else { - return processedTable.computeIfAbsent(MAIN_HELP, commandName -> generateForAllCommand(channel)); + return processedTable.computeIfAbsent(MAIN_HELP, commandName -> generateForAllCommand(channel)); } } @@ -79,14 +79,15 @@ public class HelpTelnetHandler implements TelnetHandler { for (TelnetHandler handler : handlers) { Help help = handler.getClass().getAnnotation(Help.class); List row = new ArrayList(); - String parameter = " " + extensionLoader.getExtensionName(handler) + " " + (help != null ? help.parameter().replace("\r\n", " ").replace("\n", " ") : ""); + String parameter = " " + extensionLoader.getExtensionName(handler) + " " + + (help != null ? help.parameter().replace("\r\n", " ").replace("\n", " ") : ""); row.add(parameter.length() > 55 ? parameter.substring(0, 55) + "..." : parameter); - String summary = help != null ? help.summary().replace("\r\n", " ").replace("\n", " ") : ""; + String summary = + help != null ? help.summary().replace("\r\n", " ").replace("\n", " ") : ""; row.add(summary.length() > 55 ? summary.substring(0, 55) + "..." : summary); table.add(row); } } return "Please input \"help [command]\" show detail.\r\n" + TelnetUtils.toList(table); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/LogTelnetHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/LogTelnetHandler.java index 144fabb8a8..4cd8010cfa 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/LogTelnetHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/LogTelnetHandler.java @@ -69,12 +69,15 @@ public class LogTelnetHandler implements TelnetHandler { filechannel.read(bb, pos); } bb.flip(); - String content = new String(bb.array()).replace("<", "<") - .replace(">", ">").replace("\n", "

    "); + String content = new String(bb.array()) + .replace("<", "<") + .replace(">", ">") + .replace("\n", "

    "); buf.append("\r\ncontent:" + content); - buf.append("\r\nmodified:" + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") - .format(new Date(file.lastModified())))); + buf.append("\r\nmodified:" + + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") + .format(new Date(file.lastModified())))); buf.append("\r\nsize:" + size + "\r\n"); } } @@ -91,5 +94,4 @@ public class LogTelnetHandler implements TelnetHandler { .append("\r\nCURRENT LOG APPENDER:" + (file == null ? "console" : file.getAbsolutePath())); return buf.toString(); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/StatusTelnetHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/StatusTelnetHandler.java index 946362e85e..f65966321c 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/StatusTelnetHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/telnet/support/command/StatusTelnetHandler.java @@ -47,11 +47,12 @@ public class StatusTelnetHandler implements TelnetHandler { @Override public String telnet(Channel channel, String message) { - ApplicationModel applicationModel = ScopeModelUtil.getApplicationModel(channel.getUrl().getScopeModel()); + ApplicationModel applicationModel = + ScopeModelUtil.getApplicationModel(channel.getUrl().getScopeModel()); ExtensionLoader extensionLoader = applicationModel.getExtensionLoader(StatusChecker.class); if ("-l".equals(message)) { List checkers = extensionLoader.getActivateExtension(channel.getUrl(), STATUS_KEY); - String[] header = new String[]{"resource", "status", "message"}; + String[] header = new String[] {"resource", "status", "message"}; List> table = new ArrayList>(); Map statuses = new HashMap(); if (CollectionUtils.isNotEmpty(checkers)) { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractChannel.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractChannel.java index 28353269fc..d96513965a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractChannel.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractChannel.java @@ -34,9 +34,12 @@ public abstract class AbstractChannel extends AbstractPeer implements Channel { @Override public void send(Object message, boolean sent) throws RemotingException { if (isClosed()) { - throw new RemotingException(this, "Failed to send message " - + (message == null ? "" : message.getClass().getName()) + ":" + PayloadDropper.getRequestWithoutData(message) - + ", cause: Channel closed. channel: " + getLocalAddress() + " -> " + getRemoteAddress()); + throw new RemotingException( + this, + "Failed to send message " + + (message == null ? "" : message.getClass().getName()) + ":" + + PayloadDropper.getRequestWithoutData(message) + + ", cause: Channel closed. channel: " + getLocalAddress() + " -> " + getRemoteAddress()); } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java index 71392adf82..7b465c6649 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractClient.java @@ -35,9 +35,9 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_CLIENT_THREADPOOL; +import static org.apache.dubbo.common.constants.CommonConstants.LAZY_CONNECT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.LAZY_CONNECT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CONNECT_PROVIDER; import static org.apache.dubbo.config.Constants.CLIENT_THREAD_POOL_NAME; @@ -66,25 +66,35 @@ public abstract class AbstractClient extends AbstractEndpoint implements Client doOpen(); } catch (Throwable t) { close(); - throw new RemotingException(url.toInetSocketAddress(), null, - "Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() - + " connect to the server " + getRemoteAddress() + ", cause: " + t.getMessage(), t); + throw new RemotingException( + url.toInetSocketAddress(), + null, + "Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + + " connect to the server " + getRemoteAddress() + ", cause: " + t.getMessage(), + t); } try { // connect. connect(); if (logger.isInfoEnabled()) { - logger.info("Start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + " connect to the server " + getRemoteAddress()); + logger.info("Start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + + " connect to the server " + getRemoteAddress()); } } catch (RemotingException t) { // If lazy connect client fails to establish a connection, the client instance will still be created, // and the reconnection will be initiated by ReconnectTask, so there is no need to throw an exception if (url.getParameter(LAZY_CONNECT_KEY, false)) { - logger.warn(TRANSPORT_FAILED_CONNECT_PROVIDER, "", "", "Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + - " connect to the server " + getRemoteAddress() + - " (the connection request is initiated by lazy connect client, ignore and retry later!), cause: " + - t.getMessage(), t); + logger.warn( + TRANSPORT_FAILED_CONNECT_PROVIDER, + "", + "", + "Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + + " connect to the server " + + getRemoteAddress() + + " (the connection request is initiated by lazy connect client, ignore and retry later!), cause: " + + t.getMessage(), + t); return; } @@ -92,14 +102,23 @@ public abstract class AbstractClient extends AbstractEndpoint implements Client close(); throw t; } else { - logger.warn(TRANSPORT_FAILED_CONNECT_PROVIDER, "", "", "Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() - + " connect to the server " + getRemoteAddress() + " (check == false, ignore and retry later!), cause: " + t.getMessage(), t); + logger.warn( + TRANSPORT_FAILED_CONNECT_PROVIDER, + "", + "", + "Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + + " connect to the server " + getRemoteAddress() + + " (check == false, ignore and retry later!), cause: " + t.getMessage(), + t); } } catch (Throwable t) { close(); - throw new RemotingException(url.toInetSocketAddress(), null, - "Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() - + " connect to the server " + getRemoteAddress() + ", cause: " + t.getMessage(), t); + throw new RemotingException( + url.toInetSocketAddress(), + null, + "Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + + " connect to the server " + getRemoteAddress() + ", cause: " + t.getMessage(), + t); } } @@ -113,7 +132,7 @@ public abstract class AbstractClient extends AbstractEndpoint implements Client * which means params are shared among different services. Since client is shared among services this is currently not a problem. */ url = url.addParameter(THREAD_NAME_KEY, CLIENT_THREAD_POOL_NAME) - .addParameterIfAbsent(THREADPOOL_KEY, DEFAULT_CLIENT_THREADPOOL); + .addParameterIfAbsent(THREADPOOL_KEY, DEFAULT_CLIENT_THREADPOOL); executor = executorRepository.createExecutorIfAbsent(url); } @@ -194,7 +213,7 @@ public abstract class AbstractClient extends AbstractEndpoint implements Client connect(); } Channel channel = getChannel(); - //TODO Can the value returned by getChannel() be null? need improvement. + // TODO Can the value returned by getChannel() be null? need improvement. if (channel == null || !channel.isConnected()) { throw new RemotingException(this, "message can not send, because channel is closed . url:" + getUrl()); } @@ -210,23 +229,32 @@ public abstract class AbstractClient extends AbstractEndpoint implements Client } if (isClosed() || isClosing()) { - logger.warn(TRANSPORT_FAILED_CONNECT_PROVIDER, "", "", "No need to connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " - + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() + ", cause: client status is closed or closing."); + logger.warn( + TRANSPORT_FAILED_CONNECT_PROVIDER, + "", + "", + "No need to connect to server " + getRemoteAddress() + " from " + + getClass().getSimpleName() + " " + NetUtils.getLocalHost() + " using dubbo version " + + Version.getVersion() + ", cause: client status is closed or closing."); return; } doConnect(); if (!isConnected()) { - throw new RemotingException(this, "Failed to connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " - + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() - + ", cause: Connect wait timeout: " + getConnectTimeout() + "ms."); + throw new RemotingException( + this, + "Failed to connect to server " + getRemoteAddress() + " from " + + getClass().getSimpleName() + " " + + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() + + ", cause: Connect wait timeout: " + getConnectTimeout() + "ms."); } else { if (logger.isInfoEnabled()) { - logger.info("Successfully connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " - + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() - + ", channel is " + this.getChannel()); + logger.info("Successfully connect to server " + getRemoteAddress() + " from " + + getClass().getSimpleName() + " " + + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() + + ", channel is " + this.getChannel()); } } @@ -234,9 +262,13 @@ public abstract class AbstractClient extends AbstractEndpoint implements Client throw e; } catch (Throwable e) { - throw new RemotingException(this, "Failed to connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " - + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() - + ", cause: " + e.getMessage(), e); + throw new RemotingException( + this, + "Failed to connect to server " + getRemoteAddress() + " from " + + getClass().getSimpleName() + " " + + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() + + ", cause: " + e.getMessage(), + e); } finally { connectLock.unlock(); @@ -278,14 +310,26 @@ public abstract class AbstractClient extends AbstractEndpoint implements Client @Override public void close() { if (isClosed()) { - logger.warn(TRANSPORT_FAILED_CONNECT_PROVIDER, "", "", "No need to close connection to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() + ", cause: the client status is closed."); + logger.warn( + TRANSPORT_FAILED_CONNECT_PROVIDER, + "", + "", + "No need to close connection to server " + getRemoteAddress() + " from " + + getClass().getSimpleName() + " " + NetUtils.getLocalHost() + " using dubbo version " + + Version.getVersion() + ", cause: the client status is closed."); return; } connectLock.lock(); try { if (isClosed()) { - logger.warn(TRANSPORT_FAILED_CONNECT_PROVIDER, "", "", "No need to close connection to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " " + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion() + ", cause: the client status is closed."); + logger.warn( + TRANSPORT_FAILED_CONNECT_PROVIDER, + "", + "", + "No need to close connection to server " + getRemoteAddress() + " from " + + getClass().getSimpleName() + " " + NetUtils.getLocalHost() + " using dubbo version " + + Version.getVersion() + ", cause: the client status is closed."); return; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java index 144e352bb2..d5320053f6 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractCodec.java @@ -57,7 +57,7 @@ public abstract class AbstractCodec implements Codec2, ScopeModelAware { boolean overPayload = isOverPayload(payload, size); if (overPayload) { ExceedPayloadLimitException e = new ExceedPayloadLimitException( - "Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel); + "Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel); logger.error(TRANSPORT_EXCEED_PAYLOAD_LIMIT, "", "", e.getMessage(), e); throw e; } @@ -70,7 +70,7 @@ public abstract class AbstractCodec implements Codec2, ScopeModelAware { boolean overPayload = isOverPayload(payload, size); if (overPayload) { ExceedPayloadLimitException e = new ExceedPayloadLimitException( - "Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel); + "Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel); logger.error(TRANSPORT_EXCEED_PAYLOAD_LIMIT, "", "", e.getMessage(), e); throw e; } @@ -109,11 +109,10 @@ public abstract class AbstractCodec implements Codec2, ScopeModelAware { InetSocketAddress address = channel.getRemoteAddress(); URL url = channel.getUrl(); boolean isClient = url.getPort() == address.getPort() - && NetUtils.filterLocalHost(url.getIp()).equals( - NetUtils.filterLocalHost(address.getAddress() - .getHostAddress())); - channel.setAttribute(SIDE_KEY, isClient ? CLIENT_SIDE - : SERVER_SIDE); + && NetUtils.filterLocalHost(url.getIp()) + .equals(NetUtils.filterLocalHost( + address.getAddress().getHostAddress())); + channel.setAttribute(SIDE_KEY, isClient ? CLIENT_SIDE : SERVER_SIDE); return isClient; } } @@ -121,5 +120,4 @@ public abstract class AbstractCodec implements Codec2, ScopeModelAware { protected boolean isServerSide(Channel channel) { return !isClientSide(channel); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractEndpoint.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractEndpoint.java index 16b57f1204..f8ab69fdcd 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractEndpoint.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractEndpoint.java @@ -45,7 +45,8 @@ public abstract class AbstractEndpoint extends AbstractPeer implements Resetable public AbstractEndpoint(URL url, ChannelHandler handler) { super(url, handler); this.codec = getChannelCodec(url); - this.connectTimeout = url.getPositiveParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT); + this.connectTimeout = + url.getPositiveParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT); } protected static Codec2 getChannelCodec(URL url) { @@ -58,8 +59,8 @@ public abstract class AbstractEndpoint extends AbstractPeer implements Resetable if (frameworkModel.getExtensionLoader(Codec2.class).hasExtension(codecName)) { return frameworkModel.getExtensionLoader(Codec2.class).getExtension(codecName); } else if (frameworkModel.getExtensionLoader(Codec.class).hasExtension(codecName)) { - return new CodecAdapter(frameworkModel.getExtensionLoader(Codec.class) - .getExtension(codecName)); + return new CodecAdapter( + frameworkModel.getExtensionLoader(Codec.class).getExtension(codecName)); } else { return frameworkModel.getExtensionLoader(Codec2.class).getExtension("default"); } @@ -68,8 +69,8 @@ public abstract class AbstractEndpoint extends AbstractPeer implements Resetable @Override public void reset(URL url) { if (isClosed()) { - throw new IllegalStateException("Failed to reset parameters " - + url + ", cause: Channel closed. channel: " + getLocalAddress()); + throw new IllegalStateException( + "Failed to reset parameters " + url + ", cause: Channel closed. channel: " + getLocalAddress()); } try { @@ -104,5 +105,4 @@ public abstract class AbstractEndpoint extends AbstractPeer implements Resetable protected int getConnectTimeout() { return connectTimeout; } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java index 65978841fb..bb50ddc304 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/AbstractServer.java @@ -68,13 +68,19 @@ public abstract class AbstractServer extends AbstractEndpoint implements Remotin try { doOpen(); if (logger.isInfoEnabled()) { - logger.info("Start " + getClass().getSimpleName() + " bind " + getBindAddress() + ", export " + getLocalAddress()); + logger.info("Start " + getClass().getSimpleName() + " bind " + getBindAddress() + ", export " + + getLocalAddress()); } } catch (Throwable t) { - throw new RemotingException(url.toInetSocketAddress(), null, "Failed to bind " + getClass().getSimpleName() - + " on " + bindAddress + ", cause: " + t.getMessage(), t); + throw new RemotingException( + url.toInetSocketAddress(), + null, + "Failed to bind " + getClass().getSimpleName() + " on " + bindAddress + ", cause: " + + t.getMessage(), + t); } - executors.add(executorRepository.createExecutorIfAbsent(ExecutorUtil.setThreadName(url, SERVER_THREAD_POOL_NAME))); + executors.add( + executorRepository.createExecutorIfAbsent(ExecutorUtil.setThreadName(url, SERVER_THREAD_POOL_NAME))); } protected abstract void doOpen() throws Throwable; @@ -100,7 +106,8 @@ public abstract class AbstractServer extends AbstractEndpoint implements Remotin logger.error(INTERNAL_ERROR, "unknown error in remoting module", "", t.getMessage(), t); } - ExecutorService executor = executorRepository.createExecutorIfAbsent(ExecutorUtil.setThreadName(url, SERVER_THREAD_POOL_NAME)); + ExecutorService executor = + executorRepository.createExecutorIfAbsent(ExecutorUtil.setThreadName(url, SERVER_THREAD_POOL_NAME)); executors.add(executor); executorRepository.updateThreadpool(url, executor); super.setUrl(getUrl().addParameters(url.getParameters())); @@ -119,7 +126,8 @@ public abstract class AbstractServer extends AbstractEndpoint implements Remotin @Override public void close() { if (logger.isInfoEnabled()) { - logger.info("Close " + getClass().getSimpleName() + " bind " + getBindAddress() + ", export " + getLocalAddress()); + logger.info("Close " + getClass().getSimpleName() + " bind " + getBindAddress() + ", export " + + getLocalAddress()); } for (ExecutorService executor : executors) { @@ -164,13 +172,23 @@ public abstract class AbstractServer extends AbstractEndpoint implements Remotin public void connected(Channel ch) throws RemotingException { // If the server has entered the shutdown process, reject any new connection if (this.isClosing() || this.isClosed()) { - logger.warn(INTERNAL_ERROR, "unknown error in remoting module", "", "Close new channel " + ch + ", cause: server is closing or has been closed. For example, receive a new connect request while in shutdown process."); + logger.warn( + INTERNAL_ERROR, + "unknown error in remoting module", + "", + "Close new channel " + ch + + ", cause: server is closing or has been closed. For example, receive a new connect request while in shutdown process."); ch.close(); return; } - if (accepts > 0 && getChannelsSize()> accepts) { - logger.error(INTERNAL_ERROR, "unknown error in remoting module", "", "Close channel " + ch + ", cause: The server " + ch.getLocalAddress() + " connections greater than max config " + accepts); + if (accepts > 0 && getChannelsSize() > accepts) { + logger.error( + INTERNAL_ERROR, + "unknown error in remoting module", + "", + "Close channel " + ch + ", cause: The server " + ch.getLocalAddress() + + " connections greater than max config " + accepts); ch.close(); return; } @@ -179,10 +197,13 @@ public abstract class AbstractServer extends AbstractEndpoint implements Remotin @Override public void disconnected(Channel ch) throws RemotingException { - if (getChannelsSize()==0) { - logger.warn(INTERNAL_ERROR, "unknown error in remoting module", "", "All clients has disconnected from " + ch.getLocalAddress() + ". You can graceful shutdown now."); + if (getChannelsSize() == 0) { + logger.warn( + INTERNAL_ERROR, + "unknown error in remoting module", + "", + "All clients has disconnected from " + ch.getLocalAddress() + ". You can graceful shutdown now."); } super.disconnected(ch); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelDelegate.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelDelegate.java index eb4ce77a03..1a89b9fc78 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelDelegate.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelDelegate.java @@ -30,8 +30,7 @@ public class ChannelDelegate implements Channel { private transient Channel channel; - public ChannelDelegate() { - } + public ChannelDelegate() {} public ChannelDelegate(Channel channel) { setChannel(channel); @@ -122,5 +121,4 @@ public class ChannelDelegate implements Channel { public boolean isClosed() { return channel.isClosed(); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelHandlerAdapter.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelHandlerAdapter.java index 188b7de4ba..8e09d2b920 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelHandlerAdapter.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelHandlerAdapter.java @@ -26,23 +26,17 @@ import org.apache.dubbo.remoting.RemotingException; public class ChannelHandlerAdapter implements ChannelHandler { @Override - public void connected(Channel channel) throws RemotingException { - } + public void connected(Channel channel) throws RemotingException {} @Override - public void disconnected(Channel channel) throws RemotingException { - } + public void disconnected(Channel channel) throws RemotingException {} @Override - public void sent(Channel channel, Object message) throws RemotingException { - } + public void sent(Channel channel, Object message) throws RemotingException {} @Override - public void received(Channel channel, Object message) throws RemotingException { - } + public void received(Channel channel, Object message) throws RemotingException {} @Override - public void caught(Channel channel, Throwable exception) throws RemotingException { - } - + public void caught(Channel channel, Throwable exception) throws RemotingException {} } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelHandlerDispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelHandlerDispatcher.java index 13174c5c75..f8c47276c0 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelHandlerDispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ChannelHandlerDispatcher.java @@ -35,12 +35,12 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERR */ public class ChannelHandlerDispatcher implements ChannelHandler { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ChannelHandlerDispatcher.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ChannelHandlerDispatcher.class); private final Collection channelHandlers = new CopyOnWriteArraySet<>(); - public ChannelHandlerDispatcher() { - } + public ChannelHandlerDispatcher() {} public ChannelHandlerDispatcher(ChannelHandler... handlers) { // if varargs is used, the type of handlers is ChannelHandler[] and it is not null @@ -51,7 +51,8 @@ public class ChannelHandlerDispatcher implements ChannelHandler { public ChannelHandlerDispatcher(Collection handlers) { if (CollectionUtils.isNotEmpty(handlers)) { // filter null object - this.channelHandlers.addAll(handlers.stream().filter(Objects::nonNull).collect(Collectors.toSet())); + this.channelHandlers.addAll( + handlers.stream().filter(Objects::nonNull).collect(Collectors.toSet())); } } @@ -123,5 +124,4 @@ public class ChannelHandlerDispatcher implements ChannelHandler { } } } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ClientDelegate.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ClientDelegate.java index d2a7673d0e..9b1204bb3c 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ClientDelegate.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ClientDelegate.java @@ -30,8 +30,7 @@ public class ClientDelegate implements Client { private transient Client client; - public ClientDelegate() { - } + public ClientDelegate() {} public ClientDelegate(Client client) { setClient(client); @@ -138,5 +137,4 @@ public class ClientDelegate implements Client { public boolean isClosed() { return client.isClosed(); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java index d109e97cb1..8023274ac4 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.transport; import org.apache.dubbo.common.URL; @@ -52,16 +51,21 @@ public class CodecSupport { private static final ThreadLocal TL_BUFFER = ThreadLocal.withInitial(() -> new byte[1024]); static { - ExtensionLoader extensionLoader = FrameworkModel.defaultModel().getExtensionLoader(Serialization.class); + ExtensionLoader extensionLoader = + FrameworkModel.defaultModel().getExtensionLoader(Serialization.class); Set supportedExtensions = extensionLoader.getSupportedExtensions(); for (String name : supportedExtensions) { Serialization serialization = extensionLoader.getExtension(name); byte idByte = serialization.getContentTypeId(); if (ID_SERIALIZATION_MAP.containsKey(idByte)) { - logger.error(TRANSPORT_FAILED_SERIALIZATION, "", "", "Serialization extension " + serialization.getClass().getName() - + " has duplicate id to Serialization extension " - + ID_SERIALIZATION_MAP.get(idByte).getClass().getName() - + ", ignore this Serialization extension"); + logger.error( + TRANSPORT_FAILED_SERIALIZATION, + "", + "", + "Serialization extension " + serialization.getClass().getName() + + " has duplicate id to Serialization extension " + + ID_SERIALIZATION_MAP.get(idByte).getClass().getName() + + ", ignore this Serialization extension"); continue; } ID_SERIALIZATION_MAP.put(idByte, serialization); @@ -70,8 +74,7 @@ public class CodecSupport { } } - private CodecSupport() { - } + private CodecSupport() {} public static Serialization getSerializationById(Byte id) { return ID_SERIALIZATION_MAP.get(id); @@ -82,7 +85,9 @@ public class CodecSupport { } public static Serialization getSerialization(URL url) { - return url.getOrDefaultFrameworkModel().getExtensionLoader(Serialization.class).getExtension(UrlUtils.serializationOrDefault(url)); + return url.getOrDefaultFrameworkModel() + .getExtensionLoader(Serialization.class) + .getExtension(UrlUtils.serializationOrDefault(url)); } public static Serialization getSerialization(Byte id) throws IOException { @@ -107,7 +112,7 @@ public class CodecSupport { */ public static byte[] getNullBytesOf(Serialization s) { return ConcurrentHashMapUtils.computeIfAbsent(ID_NULLBYTES_MAP, s.getContentTypeId(), k -> { - //Pre-generated Null object bytes + // Pre-generated Null object bytes ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] nullBytes = new byte[0]; try { @@ -117,7 +122,12 @@ public class CodecSupport { nullBytes = baos.toByteArray(); baos.close(); } catch (Exception e) { - logger.warn(TRANSPORT_FAILED_SERIALIZATION, "", "", "Serialization extension " + s.getClass().getName() + " not support serializing null object, return an empty bytes instead."); + logger.warn( + TRANSPORT_FAILED_SERIALIZATION, + "", + "", + "Serialization extension " + s.getClass().getName() + + " not support serializing null object, return an empty bytes instead."); } return nullBytes; }); @@ -165,14 +175,14 @@ public class CodecSupport { checkSerialization(requestSerializeName, all); } - public static void checkSerialization(String requestSerializeName, Collection allSerializeName) throws IOException { + public static void checkSerialization(String requestSerializeName, Collection allSerializeName) + throws IOException { for (String serialization : allSerializeName) { if (serialization.equals(requestSerializeName)) { return; } } - throw new IOException("Unexpected serialization type:" + requestSerializeName + " received from network, please check if the peer send the right id."); + throw new IOException("Unexpected serialization type:" + requestSerializeName + + " received from network, please check if the peer send the right id."); } - - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/DecodeHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/DecodeHandler.java index 11b93b8494..71d4e535b2 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/DecodeHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/DecodeHandler.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.transport; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/MultiMessageHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/MultiMessageHandler.java index 0e78bb06b0..9cb55fb514 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/MultiMessageHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/MultiMessageHandler.java @@ -30,7 +30,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERR */ public class MultiMessageHandler extends AbstractChannelHandlerDelegate { - protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MultiMessageHandler.class); + protected static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(MultiMessageHandler.class); public MultiMessageHandler(ChannelHandler handler) { super(handler); @@ -45,11 +46,21 @@ public class MultiMessageHandler extends AbstractChannelHandlerDelegate { try { handler.received(channel, obj); } catch (Throwable t) { - logger.error(INTERNAL_ERROR, "unknown error in remoting module", "", "MultiMessageHandler received fail.", t); + logger.error( + INTERNAL_ERROR, + "unknown error in remoting module", + "", + "MultiMessageHandler received fail.", + t); try { handler.caught(channel, t); } catch (Throwable t1) { - logger.error(INTERNAL_ERROR, "unknown error in remoting module", "", "MultiMessageHandler caught fail.", t1); + logger.error( + INTERNAL_ERROR, + "unknown error in remoting module", + "", + "MultiMessageHandler caught fail.", + t1); } } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ServerDelegate.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ServerDelegate.java index 0aa39495ce..76477df145 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ServerDelegate.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/ServerDelegate.java @@ -34,8 +34,7 @@ public class ServerDelegate implements RemotingServer { private transient RemotingServer server; - public ServerDelegate() { - } + public ServerDelegate() {} public ServerDelegate(RemotingServer server) { setServer(server); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/codec/CodecAdapter.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/codec/CodecAdapter.java index d49313ffe3..dad824eca8 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/codec/CodecAdapter.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/codec/CodecAdapter.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.transport.codec; import org.apache.dubbo.common.io.UnsafeByteArrayInputStream; @@ -37,8 +36,7 @@ public class CodecAdapter implements Codec2 { } @Override - public void encode(Channel channel, ChannelBuffer buffer, Object message) - throws IOException { + public void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException { UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(1024); codec.encode(channel, os, message); buffer.writeBytes(os.toByteArray()); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelEventRunnable.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelEventRunnable.java index 4bb558c4cd..0cc0d0a9eb 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelEventRunnable.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelEventRunnable.java @@ -25,7 +25,8 @@ import org.apache.dubbo.remoting.ChannelHandler; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; public class ChannelEventRunnable implements Runnable { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ChannelEventRunnable.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ChannelEventRunnable.class); private final ChannelHandler handler; private final Channel channel; @@ -45,7 +46,8 @@ public class ChannelEventRunnable implements Runnable { this(channel, handler, state, null, t); } - public ChannelEventRunnable(Channel channel, ChannelHandler handler, ChannelState state, Object message, Throwable exception) { + public ChannelEventRunnable( + Channel channel, ChannelHandler handler, ChannelState state, Object message, Throwable exception) { this.channel = channel; this.handler = handler; this.state = state; @@ -61,8 +63,13 @@ public class ChannelEventRunnable implements Runnable { try { handler.received(channel, message); } catch (Exception e) { - logger.warn(INTERNAL_ERROR, "unknown error in remoting module", "", "ChannelEventRunnable handle " + state + " operation error, channel is " + channel - + ", message is " + message, e); + logger.warn( + INTERNAL_ERROR, + "unknown error in remoting module", + "", + "ChannelEventRunnable handle " + state + " operation error, channel is " + channel + + ", message is " + message, + e); } } else { switch (state) { @@ -70,34 +77,58 @@ public class ChannelEventRunnable implements Runnable { try { handler.connected(channel); } catch (Exception e) { - logger.warn(INTERNAL_ERROR, "unknown error in remoting module", "", "ChannelEventRunnable handle " + state + " operation error, channel is " + channel, e); + logger.warn( + INTERNAL_ERROR, + "unknown error in remoting module", + "", + "ChannelEventRunnable handle " + state + " operation error, channel is " + channel, + e); } break; case DISCONNECTED: try { handler.disconnected(channel); } catch (Exception e) { - logger.warn(INTERNAL_ERROR, "unknown error in remoting module", "", "ChannelEventRunnable handle " + state + " operation error, channel is " + channel, e); + logger.warn( + INTERNAL_ERROR, + "unknown error in remoting module", + "", + "ChannelEventRunnable handle " + state + " operation error, channel is " + channel, + e); } break; case SENT: try { handler.sent(channel, message); } catch (Exception e) { - logger.warn(INTERNAL_ERROR, "unknown error in remoting module", "", "ChannelEventRunnable handle " + state + " operation error, channel is " + channel - + ", message is " + message, e); + logger.warn( + INTERNAL_ERROR, + "unknown error in remoting module", + "", + "ChannelEventRunnable handle " + state + " operation error, channel is " + channel + + ", message is " + message, + e); } break; case CAUGHT: try { handler.caught(channel, exception); } catch (Exception e) { - logger.warn(INTERNAL_ERROR, "unknown error in remoting module", "", "ChannelEventRunnable handle " + state + " operation error, channel is " + channel - + ", message is: " + message + ", exception is " + exception, e); + logger.warn( + INTERNAL_ERROR, + "unknown error in remoting module", + "", + "ChannelEventRunnable handle " + state + " operation error, channel is " + channel + + ", message is: " + message + ", exception is " + exception, + e); } break; default: - logger.warn(INTERNAL_ERROR, "unknown error in remoting module", "", "unknown state: " + state + ", message is " + message); + logger.warn( + INTERNAL_ERROR, + "unknown error in remoting module", + "", + "unknown state: " + state + ", message is " + message); } } } finally { @@ -135,5 +166,4 @@ public class ChannelEventRunnable implements Runnable { */ CAUGHT } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelHandlers.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelHandlers.java index f11163515a..9ffe65d08a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelHandlers.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelHandlers.java @@ -26,8 +26,7 @@ public class ChannelHandlers { private static ChannelHandlers INSTANCE = new ChannelHandlers(); - protected ChannelHandlers() { - } + protected ChannelHandlers() {} public static ChannelHandler wrap(ChannelHandler handler, URL url) { return ChannelHandlers.getInstance().wrapInternal(handler, url); @@ -42,7 +41,9 @@ public class ChannelHandlers { } protected ChannelHandler wrapInternal(ChannelHandler handler, URL url) { - return new MultiMessageHandler(new HeartbeatHandler(url.getOrDefaultFrameworkModel().getExtensionLoader(Dispatcher.class) - .getAdaptiveExtension().dispatch(handler, url))); + return new MultiMessageHandler(new HeartbeatHandler(url.getOrDefaultFrameworkModel() + .getExtensionLoader(Dispatcher.class) + .getAdaptiveExtension() + .dispatch(handler, url))); } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java index 325f53625b..36c3b4499f 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java @@ -28,15 +28,16 @@ import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.exchange.support.DefaultFuture; import org.apache.dubbo.remoting.transport.ChannelHandlerDelegate; -import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.executor.ExecutorSupport; +import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; public class WrappedChannelHandler implements ChannelHandlerDelegate { - protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(WrappedChannelHandler.class); + protected static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(WrappedChannelHandler.class); protected final ChannelHandler handler; @@ -47,12 +48,11 @@ public class WrappedChannelHandler implements ChannelHandlerDelegate { public WrappedChannelHandler(ChannelHandler handler, URL url) { this.handler = handler; this.url = url; - this.executorSupport = ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()).getExecutorSupport(url); + this.executorSupport = ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()) + .getExecutorSupport(url); } - public void close() { - - } + public void close() {} @Override public void connected(Channel channel) throws RemotingException { @@ -85,8 +85,8 @@ public class WrappedChannelHandler implements ChannelHandlerDelegate { return; } - String msg = "Server side(" + url.getIp() + "," + url.getPort() - + ") thread pool is exhausted, detail msg:" + t.getMessage(); + String msg = "Server side(" + url.getIp() + "," + url.getPort() + ") thread pool is exhausted, detail msg:" + + t.getMessage(); Response response = new Response(request.getId(), request.getVersion()); response.setStatus(Response.SERVER_THREADPOOL_EXHAUSTED_ERROR); @@ -120,7 +120,8 @@ public class WrappedChannelHandler implements ChannelHandlerDelegate { if (msg instanceof Response) { Response response = (Response) msg; DefaultFuture responseFuture = DefaultFuture.getFuture(response.getId()); - // a typical scenario is the response returned after timeout, the timeout response may have completed the future + // a typical scenario is the response returned after timeout, the timeout response may have completed the + // future if (responseFuture == null) { return getSharedExecutorService(); } else { @@ -174,5 +175,4 @@ public class WrappedChannelHandler implements ChannelHandlerDelegate { public ExecutorService getExecutorService() { return getSharedExecutorService(); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/all/AllChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/all/AllChannelHandler.java index d5fa975cf6..6305514fb8 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/all/AllChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/all/AllChannelHandler.java @@ -41,7 +41,8 @@ public class AllChannelHandler extends WrappedChannelHandler { try { executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.CONNECTED)); } catch (Throwable t) { - throw new ExecutionException("connect event", channel, getClass() + " error when process connected event .", t); + throw new ExecutionException( + "connect event", channel, getClass() + " error when process connected event .", t); } } @@ -51,7 +52,8 @@ public class AllChannelHandler extends WrappedChannelHandler { try { executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.DISCONNECTED)); } catch (Throwable t) { - throw new ExecutionException("disconnect event", channel, getClass() + " error when process disconnected event .", t); + throw new ExecutionException( + "disconnect event", channel, getClass() + " error when process disconnected event .", t); } } @@ -61,7 +63,7 @@ public class AllChannelHandler extends WrappedChannelHandler { try { executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.RECEIVED, message)); } catch (Throwable t) { - if(message instanceof Request && t instanceof RejectedExecutionException){ + if (message instanceof Request && t instanceof RejectedExecutionException) { sendFeedback(channel, (Request) message, t); return; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/all/AllDispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/all/AllDispatcher.java index 31ee4c8b45..836568d1b9 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/all/AllDispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/all/AllDispatcher.java @@ -31,5 +31,4 @@ public class AllDispatcher implements Dispatcher { public ChannelHandler dispatch(ChannelHandler handler, URL url) { return new AllChannelHandler(handler, url); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java index 77fb6bb9ba..4652bc1dd4 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java @@ -49,12 +49,14 @@ public class ConnectionOrderedChannelHandler extends WrappedChannelHandler { public ConnectionOrderedChannelHandler(ChannelHandler handler, URL url) { super(handler, url); String threadName = url.getParameter(THREAD_NAME_KEY, DEFAULT_THREAD_NAME); - connectionExecutor = new ThreadPoolExecutor(1, 1, - 0L, TimeUnit.MILLISECONDS, - new LinkedBlockingQueue<>(url.getPositiveParameter(CONNECT_QUEUE_CAPACITY, Integer.MAX_VALUE)), - new NamedThreadFactory(threadName, true), - new AbortPolicyWithReport(threadName, url) - ); // FIXME There's no place to release connectionExecutor! + connectionExecutor = new ThreadPoolExecutor( + 1, + 1, + 0L, + TimeUnit.MILLISECONDS, + new LinkedBlockingQueue<>(url.getPositiveParameter(CONNECT_QUEUE_CAPACITY, Integer.MAX_VALUE)), + new NamedThreadFactory(threadName, true), + new AbortPolicyWithReport(threadName, url)); // FIXME There's no place to release connectionExecutor! queueWarningLimit = url.getParameter(CONNECT_QUEUE_WARNING_SIZE, DEFAULT_CONNECT_QUEUE_WARNING_SIZE); } @@ -64,7 +66,8 @@ public class ConnectionOrderedChannelHandler extends WrappedChannelHandler { checkQueueLength(); connectionExecutor.execute(new ChannelEventRunnable(channel, handler, ChannelState.CONNECTED)); } catch (Throwable t) { - throw new ExecutionException("connect event", channel, getClass() + " error when process connected event .", t); + throw new ExecutionException( + "connect event", channel, getClass() + " error when process connected event .", t); } } @@ -74,7 +77,8 @@ public class ConnectionOrderedChannelHandler extends WrappedChannelHandler { checkQueueLength(); connectionExecutor.execute(new ChannelEventRunnable(channel, handler, ChannelState.DISCONNECTED)); } catch (Throwable t) { - throw new ExecutionException("disconnected event", channel, getClass() + " error when process disconnected event .", t); + throw new ExecutionException( + "disconnected event", channel, getClass() + " error when process disconnected event .", t); } } @@ -104,7 +108,13 @@ public class ConnectionOrderedChannelHandler extends WrappedChannelHandler { private void checkQueueLength() { if (connectionExecutor.getQueue().size() > queueWarningLimit) { - logger.warn(TRANSPORT_CONNECTION_LIMIT_EXCEED, "", "", "connectionordered channel handler queue size: " + connectionExecutor.getQueue().size() + " exceed the warning limit number :" + queueWarningLimit); + logger.warn( + TRANSPORT_CONNECTION_LIMIT_EXCEED, + "", + "", + "connectionordered channel handler queue size: " + + connectionExecutor.getQueue().size() + " exceed the warning limit number :" + + queueWarningLimit); } } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedDispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedDispatcher.java index fed92b1768..a6b5b0d367 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedDispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedDispatcher.java @@ -31,5 +31,4 @@ public class ConnectionOrderedDispatcher implements Dispatcher { public ChannelHandler dispatch(ChannelHandler handler, URL url) { return new ConnectionOrderedChannelHandler(handler, url); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/direct/DirectChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/direct/DirectChannelHandler.java index 9bb8d1f40f..60e01d4b9b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/direct/DirectChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/direct/DirectChannelHandler.java @@ -47,5 +47,4 @@ public class DirectChannelHandler extends WrappedChannelHandler { handler.received(channel, message); } } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/direct/DirectDispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/direct/DirectDispatcher.java index aaed4e7922..4cd138ff17 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/direct/DirectDispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/direct/DirectDispatcher.java @@ -31,5 +31,4 @@ public class DirectDispatcher implements Dispatcher { public ChannelHandler dispatch(ChannelHandler handler, URL url) { return new DirectChannelHandler(handler, url); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/execution/ExecutionDispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/execution/ExecutionDispatcher.java index d5bc91d90f..a2e61f5151 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/execution/ExecutionDispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/execution/ExecutionDispatcher.java @@ -31,5 +31,4 @@ public class ExecutionDispatcher implements Dispatcher { public ChannelHandler dispatch(ChannelHandler handler, URL url) { return new ExecutionChannelHandler(handler, url); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/message/MessageOnlyChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/message/MessageOnlyChannelHandler.java index c3c25852be..77eb620d62 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/message/MessageOnlyChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/message/MessageOnlyChannelHandler.java @@ -41,12 +41,11 @@ public class MessageOnlyChannelHandler extends WrappedChannelHandler { try { executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.RECEIVED, message)); } catch (Throwable t) { - if(message instanceof Request && t instanceof RejectedExecutionException){ + if (message instanceof Request && t instanceof RejectedExecutionException) { sendFeedback(channel, (Request) message, t); return; } throw new ExecutionException(message, channel, getClass() + " error when process received event .", t); } } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/message/MessageOnlyDispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/message/MessageOnlyDispatcher.java index fa427d16d4..3fbad4bd44 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/message/MessageOnlyDispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/message/MessageOnlyDispatcher.java @@ -31,5 +31,4 @@ public class MessageOnlyDispatcher implements Dispatcher { public ChannelHandler dispatch(ChannelHandler handler, URL url) { return new MessageOnlyChannelHandler(handler, url); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/utils/UrlUtils.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/utils/UrlUtils.java index e3f510c7cc..2ba32fc4eb 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/utils/UrlUtils.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/utils/UrlUtils.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.utils; import org.apache.dubbo.common.URL; @@ -127,7 +126,9 @@ public class UrlUtils { public static Collection allSerializations(URL url) { // preferSerialization -> serialization -> default serialization Set serializations = new LinkedHashSet<>(preferSerialization(url)); - Optional.ofNullable(url.getParameter(SERIALIZATION_KEY)).filter(StringUtils::isNotBlank).ifPresent(serializations::add); + Optional.ofNullable(url.getParameter(SERIALIZATION_KEY)) + .filter(StringUtils::isNotBlank) + .ifPresent(serializations::add); serializations.add(DefaultSerializationSelector.getDefaultRemotingSerialization()); return Collections.unmodifiableSet(serializations); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/ChanelHandlerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/ChanelHandlerTest.java index f17bced5ca..8c3bde9838 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/ChanelHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/ChanelHandlerTest.java @@ -49,8 +49,11 @@ class ChanelHandlerTest { exchangeClient = Exchangers.connect(url, handler); } catch (Throwable t) { - if (t != null && t.getCause() != null && t.getCause().getClass() != null && (t.getCause().getClass() == java.net.ConnectException.class - || t.getCause().getClass() == java.net.ConnectException.class)) { + if (t != null + && t.getCause() != null + && t.getCause().getClass() != null + && (t.getCause().getClass() == java.net.ConnectException.class + || t.getCause().getClass() == java.net.ConnectException.class)) { } else { t.printStackTrace(); @@ -83,12 +86,15 @@ class ChanelHandlerTest { return; } final String server = System.getProperty("server", "127.0.0.1:9911"); - final String transporter = PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER); - final String serialization = PerformanceUtils.getProperty(Constants.SERIALIZATION_KEY, DefaultSerializationSelector.getDefaultRemotingSerialization()); + final String transporter = + PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER); + final String serialization = PerformanceUtils.getProperty( + Constants.SERIALIZATION_KEY, DefaultSerializationSelector.getDefaultRemotingSerialization()); final int timeout = PerformanceUtils.getIntProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT); int sleep = PerformanceUtils.getIntProperty("sleep", 60 * 1000 * 60); - final String url = "exchange://" + server + "?transporter=" + transporter + "&serialization=" + serialization + "&timeout=" + timeout; + final String url = "exchange://" + server + "?transporter=" + transporter + "&serialization=" + serialization + + "&timeout=" + timeout; ExchangeClient exchangeClient = initClient(url); Thread.sleep(sleep); closeClient(exchangeClient); @@ -121,9 +127,7 @@ class ChanelHandlerTest { */ @Override public void caught(Channel channel, Throwable exception) throws RemotingException { -// System.out.println("caught event:"+exception); + // System.out.println("caught event:"+exception); } - - } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientCloseTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientCloseTest.java index 6b8006ac85..2ec49a987d 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientCloseTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientCloseTest.java @@ -22,10 +22,10 @@ import org.apache.dubbo.common.serialize.support.DefaultSerializationSelector; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.remoting.exchange.Exchangers; -import org.junit.jupiter.api.Test; - import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNDEFINED_ARGUMENT; @@ -36,7 +36,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNDEF */ class PerformanceClientCloseTest { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PerformanceClientCloseTest.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(PerformanceClientCloseTest.class); @Test void testClient() throws Throwable { @@ -46,53 +47,56 @@ class PerformanceClientCloseTest { return; } final String server = System.getProperty("server", "127.0.0.1:9911"); - final String transporter = PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER); - final String serialization = PerformanceUtils.getProperty(Constants.SERIALIZATION_KEY, DefaultSerializationSelector.getDefaultRemotingSerialization()); + final String transporter = + PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER); + final String serialization = PerformanceUtils.getProperty( + Constants.SERIALIZATION_KEY, DefaultSerializationSelector.getDefaultRemotingSerialization()); final int timeout = PerformanceUtils.getIntProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT); final int concurrent = PerformanceUtils.getIntProperty("concurrent", 1); final int runs = PerformanceUtils.getIntProperty("runs", Integer.MAX_VALUE); final String onerror = PerformanceUtils.getProperty("onerror", "continue"); final String url = "exchange://" + server + "?transporter=" + transporter - + "&serialization=" + serialization -// + "&"+Constants.CHANNEL_HANDLER_KEY+"=connection" - + "&timeout=" + timeout; + + "&serialization=" + serialization + // + "&"+Constants.CHANNEL_HANDLER_KEY+"=connection" + + "&timeout=" + timeout; final AtomicInteger count = new AtomicInteger(); final AtomicInteger error = new AtomicInteger(); for (int n = 0; n < concurrent; n++) { new Thread(new Runnable() { - public void run() { - for (int i = 0; i < runs; i++) { - ExchangeClient client = null; - try { - client = Exchangers.connect(url); - int c = count.incrementAndGet(); - if (c % 100 == 0) { - System.out.println("count: " + count.get() + ", error: " + error.get()); - } - } catch (Exception e) { - error.incrementAndGet(); - e.printStackTrace(); - System.out.println("count: " + count.get() + ", error: " + error.get()); - if ("exit".equals(onerror)) { - System.exit(-1); - } else if ("break".equals(onerror)) { - break; - } else if ("sleep".equals(onerror)) { + public void run() { + for (int i = 0; i < runs; i++) { + ExchangeClient client = null; try { - Thread.sleep(30000); - } catch (InterruptedException e1) { + client = Exchangers.connect(url); + int c = count.incrementAndGet(); + if (c % 100 == 0) { + System.out.println("count: " + count.get() + ", error: " + error.get()); + } + } catch (Exception e) { + error.incrementAndGet(); + e.printStackTrace(); + System.out.println("count: " + count.get() + ", error: " + error.get()); + if ("exit".equals(onerror)) { + System.exit(-1); + } else if ("break".equals(onerror)) { + break; + } else if ("sleep".equals(onerror)) { + try { + Thread.sleep(30000); + } catch (InterruptedException e1) { + } + } + } finally { + if (client != null) { + client.close(); + } } } - } finally { - if (client != null) { - client.close(); - } } - } - } - }).start(); + }) + .start(); } synchronized (PerformanceServerTest.class) { while (true) { @@ -103,5 +107,4 @@ class PerformanceClientCloseTest { } } } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java index a684d9c2d7..2248f0c0c4 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java @@ -22,11 +22,11 @@ import org.apache.dubbo.common.serialize.support.DefaultSerializationSelector; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.remoting.exchange.Exchangers; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.Random; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNDEFINED_ARGUMENT; @@ -34,7 +34,8 @@ import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY; class PerformanceClientFixedTest { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PerformanceClientTest.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(PerformanceClientTest.class); @Test void testClient() throws Exception { @@ -44,18 +45,21 @@ class PerformanceClientFixedTest { return; } final String server = System.getProperty("server", "127.0.0.1:9911"); - final String transporter = PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER); - final String serialization = PerformanceUtils.getProperty(Constants.SERIALIZATION_KEY, DefaultSerializationSelector.getDefaultRemotingSerialization()); + final String transporter = + PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER); + final String serialization = PerformanceUtils.getProperty( + Constants.SERIALIZATION_KEY, DefaultSerializationSelector.getDefaultRemotingSerialization()); final int timeout = PerformanceUtils.getIntProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT); - //final int length = PerformanceUtils.getIntProperty("length", 1024); + // final int length = PerformanceUtils.getIntProperty("length", 1024); final int connectionCount = PerformanceUtils.getIntProperty(CONNECTIONS_KEY, 1); - //final int concurrent = PerformanceUtils.getIntProperty("concurrent", 100); - //int r = PerformanceUtils.getIntProperty("runs", 10000); - //final int runs = r > 0 ? r : Integer.MAX_VALUE; - //final String onerror = PerformanceUtils.getProperty("onerror", "continue"); - final String url = "exchange://" + server + "?transporter=" + transporter + "&serialization=" + serialization + "&timeout=" + timeout; + // final int concurrent = PerformanceUtils.getIntProperty("concurrent", 100); + // int r = PerformanceUtils.getIntProperty("runs", 10000); + // final int runs = r > 0 ? r : Integer.MAX_VALUE; + // final String onerror = PerformanceUtils.getProperty("onerror", "continue"); + final String url = "exchange://" + server + "?transporter=" + transporter + "&serialization=" + serialization + + "&timeout=" + timeout; - //int idx = server.indexOf(':'); + // int idx = server.indexOf(':'); Random rd = new Random(connectionCount); ArrayList arrays = new ArrayList(); String oneKBlock = null; @@ -92,7 +96,8 @@ class PerformanceClientFixedTest { StringBuilder sb1 = new StringBuilder(); Random rd2 = new Random(); - char[] numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz" + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray(); + char[] numbersAndLetters = + ("0123456789abcdefghijklmnopqrstuvwxyz" + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray(); int size1 = numbersAndLetters.length; for (int j = 0; j < 1024; j++) { sb1.append(numbersAndLetters[rd2.nextInt(size1)]); @@ -128,13 +133,11 @@ class PerformanceClientFixedTest { System.out.println("send messageBlock;get " + output); throw new Throwable("return results invalid"); } else { - if (j % 100 == 0) - System.out.println("OK: " + j); + if (j % 100 == 0) System.out.println("OK: " + j); } } catch (Throwable t) { t.printStackTrace(); } } } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientMain.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientMain.java index 0628f7fb24..9ae015061e 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientMain.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientMain.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting; - /** * PerformanceClientMain */ @@ -25,5 +24,4 @@ public class PerformanceClientMain { public static void main(String[] args) throws Throwable { new PerformanceClientTest().testClient(); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java index a81b835ec8..49b6bb763d 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java @@ -24,8 +24,6 @@ import org.apache.dubbo.remoting.exchange.Exchangers; import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.junit.jupiter.api.Test; - import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; @@ -34,6 +32,8 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNDEFINED_ARGUMENT; @@ -46,7 +46,8 @@ import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY; */ class PerformanceClientTest { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PerformanceClientTest.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(PerformanceClientTest.class); @Test @SuppressWarnings("unchecked") @@ -57,8 +58,10 @@ class PerformanceClientTest { return; } final String server = System.getProperty("server", "127.0.0.1:9911"); - final String transporter = PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER); - final String serialization = PerformanceUtils.getProperty(Constants.SERIALIZATION_KEY, DefaultSerializationSelector.getDefaultRemotingSerialization()); + final String transporter = + PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER); + final String serialization = PerformanceUtils.getProperty( + Constants.SERIALIZATION_KEY, DefaultSerializationSelector.getDefaultRemotingSerialization()); final int timeout = PerformanceUtils.getIntProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT); final int length = PerformanceUtils.getIntProperty("length", 1024); final int connections = PerformanceUtils.getIntProperty(CONNECTIONS_KEY, 1); @@ -67,16 +70,19 @@ class PerformanceClientTest { final int runs = r > 0 ? r : Integer.MAX_VALUE; final String onerror = PerformanceUtils.getProperty("onerror", "continue"); - final String url = "exchange://" + server + "?transporter=" + transporter + "&serialization=" + serialization + "&timeout=" + timeout; + final String url = "exchange://" + server + "?transporter=" + transporter + "&serialization=" + serialization + + "&timeout=" + timeout; // Create clients and build connections final ExchangeClient[] exchangeClients = new ExchangeClient[connections]; for (int i = 0; i < connections; i++) { - //exchangeClients[i] = Exchangers.connect(url,handler); + // exchangeClients[i] = Exchangers.connect(url,handler); exchangeClients[i] = Exchangers.connect(url); } - List serverEnvironment = (List) exchangeClients[0].request("environment").get(); - List serverScene = (List) exchangeClients[0].request("scene").get(); + List serverEnvironment = + (List) exchangeClients[0].request("environment").get(); + List serverScene = + (List) exchangeClients[0].request("scene").get(); // Create some data for test StringBuilder buf = new StringBuilder(length); @@ -95,67 +101,71 @@ class PerformanceClientTest { final CountDownLatch latch = new CountDownLatch(concurrent); for (int i = 0; i < concurrent; i++) { new Thread(new Runnable() { - public void run() { - try { - AtomicInteger index = new AtomicInteger(); - long init = System.currentTimeMillis(); - for (int i = 0; i < runs; i++) { + public void run() { try { - count.incrementAndGet(); - ExchangeClient client = exchangeClients[index.getAndIncrement() % connections]; - long start = System.currentTimeMillis(); - String result = (String) client.request(data).get(); - long end = System.currentTimeMillis(); - if (!data.equals(result)) { - throw new IllegalStateException("Invalid result " + result); - } - time.addAndGet(end - start); - } catch (Exception e) { - error.incrementAndGet(); - e.printStackTrace(); - if ("exit".equals(onerror)) { - System.exit(-1); - } else if ("break".equals(onerror)) { - break; - } else if ("sleep".equals(onerror)) { + AtomicInteger index = new AtomicInteger(); + long init = System.currentTimeMillis(); + for (int i = 0; i < runs; i++) { try { - Thread.sleep(30000); - } catch (InterruptedException e1) { + count.incrementAndGet(); + ExchangeClient client = exchangeClients[index.getAndIncrement() % connections]; + long start = System.currentTimeMillis(); + String result = + (String) client.request(data).get(); + long end = System.currentTimeMillis(); + if (!data.equals(result)) { + throw new IllegalStateException("Invalid result " + result); + } + time.addAndGet(end - start); + } catch (Exception e) { + error.incrementAndGet(); + e.printStackTrace(); + if ("exit".equals(onerror)) { + System.exit(-1); + } else if ("break".equals(onerror)) { + break; + } else if ("sleep".equals(onerror)) { + try { + Thread.sleep(30000); + } catch (InterruptedException e1) { + } + } } } + all.addAndGet(System.currentTimeMillis() - init); + } finally { + latch.countDown(); } } - all.addAndGet(System.currentTimeMillis() - init); - } finally { - latch.countDown(); - } - } - }).start(); + }) + .start(); } // Output, tps is not for accuracy, but it reflects the situation to a certain extent. new Thread(new Runnable() { - public void run() { - try { - SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); - long lastCount = count.get(); - long sleepTime = 2000; - long elapsd = sleepTime / 1000; - boolean bfirst = true; - while (latch.getCount() > 0) { - long c = count.get() - lastCount; - if (!bfirst)// The first time is inaccurate. - System.out.println("[" + dateFormat.format(new Date()) + "] count: " + count.get() + ", error: " + error.get() + ",tps:" + (c / elapsd)); + public void run() { + try { + SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); + long lastCount = count.get(); + long sleepTime = 2000; + long elapsd = sleepTime / 1000; + boolean bfirst = true; + while (latch.getCount() > 0) { + long c = count.get() - lastCount; + if (!bfirst) // The first time is inaccurate. + System.out.println("[" + dateFormat.format(new Date()) + "] count: " + count.get() + + ", error: " + error.get() + ",tps:" + (c / elapsd)); - bfirst = false; - lastCount = count.get(); - Thread.sleep(sleepTime); + bfirst = false; + lastCount = count.get(); + Thread.sleep(sleepTime); + } + } catch (Exception e) { + e.printStackTrace(); + } } - } catch (Exception e) { - e.printStackTrace(); - } - } - }).start(); + }) + .start(); latch.await(); @@ -209,12 +219,14 @@ class PerformanceClientTest { PerformanceUtils.printSeparator(); PerformanceUtils.printHeader("Test Result"); PerformanceUtils.printSeparator(); - PerformanceUtils.printBody("Succeeded Requests: " + DecimalFormat.getIntegerInstance().format(succeeded)); + PerformanceUtils.printBody( + "Succeeded Requests: " + DecimalFormat.getIntegerInstance().format(succeeded)); PerformanceUtils.printBody("Failed Requests: " + failed); PerformanceUtils.printBody("Client Elapsed Time: " + clientElapsed + " ms"); PerformanceUtils.printBody("Average Response Time: " + art + " ms"); PerformanceUtils.printBody("Requests Per Second: " + qps + "/s"); - PerformanceUtils.printBody("Throughput Per Second: " + DecimalFormat.getIntegerInstance().format(throughput) + " bytes/s"); + PerformanceUtils.printBody( + "Throughput Per Second: " + DecimalFormat.getIntegerInstance().format(throughput) + " bytes/s"); PerformanceUtils.printBorder(); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerMain.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerMain.java index 878221b75d..03b6420636 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerMain.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerMain.java @@ -24,5 +24,4 @@ public class PerformanceServerMain { public static void main(String[] args) throws Exception { new PerformanceServerTest().testServer(); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java index 90af441c7a..a5ccc5c7ec 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java @@ -26,12 +26,12 @@ import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; import org.apache.dubbo.remoting.transport.dispatcher.execution.ExecutionDispatcher; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADPOOL; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; @@ -48,7 +48,8 @@ import static org.apache.dubbo.remoting.Constants.DEFAULT_BUFFER_SIZE; */ class PerformanceServerTest { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PerformanceServerTest.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(PerformanceServerTest.class); private static ExchangeServer server = null; private static void restartServer(int times, int alive, int sleep) throws Exception { @@ -70,81 +71,88 @@ class PerformanceServerTest { private static ExchangeServer statServer() throws Exception { final int port = PerformanceUtils.getIntProperty("port", 9911); - final String transporter = PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER); - final String serialization = PerformanceUtils.getProperty(Constants.SERIALIZATION_KEY, DefaultSerializationSelector.getDefaultRemotingSerialization()); + final String transporter = + PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER); + final String serialization = PerformanceUtils.getProperty( + Constants.SERIALIZATION_KEY, DefaultSerializationSelector.getDefaultRemotingSerialization()); final String threadpool = PerformanceUtils.getProperty(THREADPOOL_KEY, DEFAULT_THREADPOOL); final int threads = PerformanceUtils.getIntProperty(THREADS_KEY, DEFAULT_THREADS); final int iothreads = PerformanceUtils.getIntProperty(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS); final int buffer = PerformanceUtils.getIntProperty(BUFFER_KEY, DEFAULT_BUFFER_SIZE); final String channelHandler = PerformanceUtils.getProperty(Constants.DISPATCHER_KEY, ExecutionDispatcher.NAME); - // Start server - ExchangeServer server = Exchangers.bind("exchange://0.0.0.0:" + port + "?transporter=" - + transporter + "&serialization=" - + serialization + "&threadpool=" + threadpool - + "&threads=" + threads + "&iothreads=" + iothreads + "&buffer=" + buffer + "&channel.handler=" + channelHandler, new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { - public String telnet(Channel channel, String message) throws RemotingException { - return "echo: " + message + "\r\ntelnet> "; - } + ExchangeServer server = Exchangers.bind( + "exchange://0.0.0.0:" + port + "?transporter=" + + transporter + "&serialization=" + + serialization + "&threadpool=" + threadpool + + "&threads=" + threads + "&iothreads=" + iothreads + "&buffer=" + buffer + "&channel.handler=" + + channelHandler, + new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { + public String telnet(Channel channel, String message) throws RemotingException { + return "echo: " + message + "\r\ntelnet> "; + } - public CompletableFuture reply(ExchangeChannel channel, Object request) throws RemotingException { - if ("environment".equals(request)) { - return CompletableFuture.completedFuture(PerformanceUtils.getEnvironment()); - } - if ("scene".equals(request)) { - List scene = new ArrayList(); - scene.add("Transporter: " + transporter); - scene.add("Service Threads: " + threads); - return CompletableFuture.completedFuture(scene); - } - return CompletableFuture.completedFuture(request); - } - }); + public CompletableFuture reply(ExchangeChannel channel, Object request) + throws RemotingException { + if ("environment".equals(request)) { + return CompletableFuture.completedFuture(PerformanceUtils.getEnvironment()); + } + if ("scene".equals(request)) { + List scene = new ArrayList(); + scene.add("Transporter: " + transporter); + scene.add("Service Threads: " + threads); + return CompletableFuture.completedFuture(scene); + } + return CompletableFuture.completedFuture(request); + } + }); return server; } private static ExchangeServer statTelnetServer(int port) throws Exception { // Start server - ExchangeServer telnetserver = Exchangers.bind("exchange://0.0.0.0:" + port, new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { - public String telnet(Channel channel, String message) throws RemotingException { - if (message.equals("help")) { - return "support cmd: \r\n\tstart \r\n\tstop \r\n\tshutdown \r\n\trestart times [alive] [sleep] \r\ntelnet>"; - } else if (message.equals("stop")) { - logger.info("server closed:" + server); - server.close(); - return "stop server\r\ntelnet>"; - } else if (message.startsWith("start")) { - try { - restartServer(0, 0, 0); - } catch (Exception e) { - e.printStackTrace(); - } - return "start server\r\ntelnet>"; - } else if (message.startsWith("shutdown")) { - System.exit(0); - return "start server\r\ntelnet>"; - } else if (message.startsWith("channels")) { - return "server.getExchangeChannels():" + server.getExchangeChannels().size() + "\r\ntelnet>"; - } else if (message.startsWith("restart ")) { //r times [sleep] r 10 or r 10 100 - String[] args = message.split(" "); - int times = Integer.parseInt(args[1]); - int alive = args.length > 2 ? Integer.parseInt(args[2]) : 0; - int sleep = args.length > 3 ? Integer.parseInt(args[3]) : 100; - try { - restartServer(times, alive, sleep); - } catch (Exception e) { - e.printStackTrace(); - } + ExchangeServer telnetserver = Exchangers.bind( + "exchange://0.0.0.0:" + port, new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { + public String telnet(Channel channel, String message) throws RemotingException { + if (message.equals("help")) { + return "support cmd: \r\n\tstart \r\n\tstop \r\n\tshutdown \r\n\trestart times [alive] [sleep] \r\ntelnet>"; + } else if (message.equals("stop")) { + logger.info("server closed:" + server); + server.close(); + return "stop server\r\ntelnet>"; + } else if (message.startsWith("start")) { + try { + restartServer(0, 0, 0); + } catch (Exception e) { + e.printStackTrace(); + } + return "start server\r\ntelnet>"; + } else if (message.startsWith("shutdown")) { + System.exit(0); + return "start server\r\ntelnet>"; + } else if (message.startsWith("channels")) { + return "server.getExchangeChannels():" + + server.getExchangeChannels().size() + "\r\ntelnet>"; + } else if (message.startsWith("restart ")) { // r times [sleep] r 10 or r 10 100 + String[] args = message.split(" "); + int times = Integer.parseInt(args[1]); + int alive = args.length > 2 ? Integer.parseInt(args[2]) : 0; + int sleep = args.length > 3 ? Integer.parseInt(args[3]) : 100; + try { + restartServer(times, alive, sleep); + } catch (Exception e) { + e.printStackTrace(); + } - return "restart server,times:" + times + " stop alive time: " + alive + ",sleep time: " + sleep + " usage:r times [alive] [sleep] \r\ntelnet>"; - } else { - return "echo: " + message + "\r\ntelnet> "; - } - - } - }); + return "restart server,times:" + times + " stop alive time: " + alive + ",sleep time: " + + sleep + " usage:r times [alive] [sleep] \r\ntelnet>"; + } else { + return "echo: " + message + "\r\ntelnet> "; + } + } + }); return telnetserver; } @@ -170,5 +178,4 @@ class PerformanceServerTest { } } } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceUtils.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceUtils.java index 6ae0073a71..56e9bd9906 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceUtils.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceUtils.java @@ -56,11 +56,14 @@ public class PerformanceUtils { public static List getEnvironment() { List environment = new ArrayList(); - environment.add("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch", "")); + environment.add("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + + System.getProperty("os.arch", "")); environment.add("CPU: " + Runtime.getRuntime().availableProcessors() + " cores"); - environment.add("JVM: " + System.getProperty("java.vm.name") + " " + System.getProperty("java.runtime.version")); - environment.add("Memory: " + DecimalFormat.getIntegerInstance().format(Runtime.getRuntime().totalMemory()) - + " bytes (Max: " + DecimalFormat.getIntegerInstance().format(Runtime.getRuntime().maxMemory()) + " bytes)"); + environment.add( + "JVM: " + System.getProperty("java.vm.name") + " " + System.getProperty("java.runtime.version")); + environment.add("Memory: " + + DecimalFormat.getIntegerInstance().format(Runtime.getRuntime().totalMemory()) + " bytes (Max: " + + DecimalFormat.getIntegerInstance().format(Runtime.getRuntime().maxMemory()) + " bytes)"); NetworkInterface ni = PerformanceUtils.getNetworkInterface(); if (ni != null) { environment.add("Network: " + ni.getDisplayName()); @@ -122,5 +125,4 @@ public class PerformanceUtils { } return null; } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/TelnetServer.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/TelnetServer.java index 8a6aef4a33..892fe35105 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/TelnetServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/TelnetServer.java @@ -46,5 +46,4 @@ public class TelnetServer { } } } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/api/EmptyProtocol.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/api/EmptyProtocol.java index 774638491e..cd71980992 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/api/EmptyProtocol.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/api/EmptyProtocol.java @@ -18,7 +18,6 @@ package org.apache.dubbo.remoting.api; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.api.pu.ChannelOperator; - import org.apache.dubbo.remoting.api.ssl.ContextOperator; public class EmptyProtocol implements WireProtocol { @@ -28,17 +27,11 @@ public class EmptyProtocol implements WireProtocol { } @Override - public void configServerProtocolHandler(URL url, ChannelOperator operator) { - - } + public void configServerProtocolHandler(URL url, ChannelOperator operator) {} @Override - public void configClientPipeline(URL url, ChannelOperator operator, ContextOperator contextOperator) { - - } + public void configClientPipeline(URL url, ChannelOperator operator, ContextOperator contextOperator) {} @Override - public void close() { - - } + public void close() {} } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/AbstractChannelBufferTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/AbstractChannelBufferTest.java index e3232bd7c9..99d7fb1300 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/AbstractChannelBufferTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/AbstractChannelBufferTest.java @@ -16,17 +16,17 @@ */ package org.apache.dubbo.remoting.buffer; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Random; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.remoting.buffer.ChannelBuffers.directBuffer; import static org.apache.dubbo.remoting.buffer.ChannelBuffers.wrappedBuffer; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -34,7 +34,6 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; - public abstract class AbstractChannelBufferTest { private static final int CAPACITY = 4096; // Must be even @@ -52,7 +51,6 @@ public abstract class AbstractChannelBufferTest { return true; } - @BeforeEach public void init() { buffer = newBuffer(CAPACITY); @@ -240,7 +238,8 @@ public abstract class AbstractChannelBufferTest { @Test void getDirectByteBufferBoundaryCheck() { - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.getBytes(-1, ByteBuffer.allocateDirect(0))); + Assertions.assertThrows( + IndexOutOfBoundsException.class, () -> buffer.getBytes(-1, ByteBuffer.allocateDirect(0))); } @Test @@ -886,5 +885,4 @@ public abstract class AbstractChannelBufferTest { // Should remain unchanged. assertEquals(CAPACITY / 4 * 2, buffer.readerIndex()); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ByteBufferBackedChannelBufferTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ByteBufferBackedChannelBufferTest.java index 2d3b1f8a1b..f846ff8dcf 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ByteBufferBackedChannelBufferTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ByteBufferBackedChannelBufferTest.java @@ -30,6 +30,6 @@ class ByteBufferBackedChannelBufferTest extends AbstractChannelBufferTest { @Override protected ChannelBuffer[] components() { - return new ChannelBuffer[]{buffer}; + return new ChannelBuffer[] {buffer}; } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ChannelBufferFactoryTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ChannelBufferFactoryTest.java index e8c21fca8a..e88052f377 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ChannelBufferFactoryTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ChannelBufferFactoryTest.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.remoting.buffer; +import java.nio.ByteBuffer; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.nio.ByteBuffer; /** * {@link DirectChannelBufferFactory} * {@link HeapChannelBufferFactory} @@ -34,17 +34,16 @@ class ChannelBufferFactoryTest { ChannelBuffer directBuffer1 = directChannelBufferFactory.getBuffer(16); ChannelBuffer directBuffer2 = directChannelBufferFactory.getBuffer(ByteBuffer.allocate(16)); - ChannelBuffer directBuffer3 = directChannelBufferFactory.getBuffer(new byte[]{1}, 0, 1); + ChannelBuffer directBuffer3 = directChannelBufferFactory.getBuffer(new byte[] {1}, 0, 1); Assertions.assertTrue(directBuffer1.isDirect()); Assertions.assertTrue(directBuffer2.isDirect()); Assertions.assertTrue(directBuffer3.isDirect()); ChannelBuffer heapBuffer1 = heapChannelBufferFactory.getBuffer(16); ChannelBuffer heapBuffer2 = heapChannelBufferFactory.getBuffer(ByteBuffer.allocate(16)); - ChannelBuffer heapBuffer3 = heapChannelBufferFactory.getBuffer(new byte[]{1}, 0, 1); + ChannelBuffer heapBuffer3 = heapChannelBufferFactory.getBuffer(new byte[] {1}, 0, 1); Assertions.assertTrue(heapBuffer1.hasArray()); Assertions.assertTrue(heapBuffer2.hasArray()); Assertions.assertTrue(heapBuffer3.hasArray()); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ChannelBufferStreamTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ChannelBufferStreamTest.java index 8e549b1155..c168958562 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ChannelBufferStreamTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ChannelBufferStreamTest.java @@ -16,10 +16,10 @@ */ package org.apache.dubbo.remoting.buffer; -import org.junit.jupiter.api.Test; - import java.io.IOException; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertSame; @@ -28,27 +28,27 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; class ChannelBufferStreamTest { - + @Test void testChannelBufferOutputStreamWithNull() { assertThrows(NullPointerException.class, () -> new ChannelBufferOutputStream(null)); } - + @Test void testChannelBufferInputStreamWithNull() { assertThrows(NullPointerException.class, () -> new ChannelBufferInputStream(null)); } - + @Test void testChannelBufferInputStreamWithNullAndLength() { assertThrows(NullPointerException.class, () -> new ChannelBufferInputStream(null, 0)); } - + @Test void testChannelBufferInputStreamWithBadLength() { assertThrows(IllegalArgumentException.class, () -> new ChannelBufferInputStream(mock(ChannelBuffer.class), -1)); } - + @Test void testChannelBufferInputStreamWithOutOfBounds() { assertThrows(IndexOutOfBoundsException.class, () -> { @@ -56,14 +56,14 @@ class ChannelBufferStreamTest { new ChannelBufferInputStream(buf, buf.capacity() + 1); }); } - + @Test void testChannelBufferWriteOutAndReadIn() { ChannelBuffer buf = ChannelBuffers.dynamicBuffer(); testChannelBufferOutputStream(buf); testChannelBufferInputStream(buf); } - + public void testChannelBufferOutputStream(final ChannelBuffer buf) { try (ChannelBufferOutputStream out = new ChannelBufferOutputStream(buf)) { assertSame(buf, out.buffer()); @@ -72,44 +72,44 @@ class ChannelBufferStreamTest { // ignored } } - + private void write(final ChannelBufferOutputStream out) throws IOException { out.write(new byte[0]); - out.write(new byte[]{1, 2, 3, 4}); - out.write(new byte[]{1, 3, 3, 4}, 0, 0); + out.write(new byte[] {1, 2, 3, 4}); + out.write(new byte[] {1, 3, 3, 4}, 0, 0); } - + public void testChannelBufferInputStream(final ChannelBuffer buf) { try (ChannelBufferInputStream in = new ChannelBufferInputStream(buf)) { assertTrue(in.markSupported()); in.mark(Integer.MAX_VALUE); - + assertEquals(buf.writerIndex(), in.skip(Long.MAX_VALUE)); assertFalse(buf.readable()); - + in.reset(); assertEquals(0, buf.readerIndex()); assertEquals(4, in.skip(4)); assertEquals(4, buf.readerIndex()); in.reset(); - + readBytes(in); - + assertEquals(buf.readerIndex(), in.readBytes()); } catch (IOException ioe) { // ignored } } - + private void readBytes(ChannelBufferInputStream in) throws IOException { byte[] tmp = new byte[13]; in.read(tmp); - + assertEquals(1, tmp[0]); assertEquals(2, tmp[1]); assertEquals(3, tmp[2]); assertEquals(4, tmp[3]); - + assertEquals(-1, in.read()); assertEquals(-1, in.read(tmp)); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ChannelBuffersTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ChannelBuffersTest.java index 50e656c23c..17effade2a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ChannelBuffersTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/ChannelBuffersTest.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.remoting.buffer; +import java.nio.ByteBuffer; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.nio.ByteBuffer; - import static org.apache.dubbo.remoting.buffer.ChannelBuffers.DEFAULT_CAPACITY; import static org.apache.dubbo.remoting.buffer.ChannelBuffers.EMPTY_BUFFER; @@ -41,7 +41,7 @@ class ChannelBuffersTest { } @Test - void testPrefixEquals(){ + void testPrefixEquals() { ChannelBuffer bufA = ChannelBuffers.wrappedBuffer("abcedfaf".getBytes()); ChannelBuffer bufB = ChannelBuffers.wrappedBuffer("abcedfaa".getBytes()); Assertions.assertTrue(ChannelBuffers.equals(bufA, bufB)); @@ -64,7 +64,7 @@ class ChannelBuffersTest { Assertions.assertTrue(channelBuffer instanceof HeapChannelBuffer); Assertions.assertEquals(channelBuffer.capacity(), 15); - channelBuffer = ChannelBuffers.wrappedBuffer(new byte[]{}); + channelBuffer = ChannelBuffers.wrappedBuffer(new byte[] {}); Assertions.assertEquals(channelBuffer, EMPTY_BUFFER); ByteBuffer byteBuffer = ByteBuffer.allocate(16); @@ -92,19 +92,19 @@ class ChannelBuffersTest { @Test void testEqualsHashCodeCompareMethod() { ChannelBuffer buffer1 = ChannelBuffers.buffer(4); - byte[] bytes1 = new byte[]{1, 2, 3, 4}; + byte[] bytes1 = new byte[] {1, 2, 3, 4}; buffer1.writeBytes(bytes1); ChannelBuffer buffer2 = ChannelBuffers.buffer(4); - byte[] bytes2 = new byte[]{1, 2, 3, 4}; + byte[] bytes2 = new byte[] {1, 2, 3, 4}; buffer2.writeBytes(bytes2); ChannelBuffer buffer3 = ChannelBuffers.buffer(3); - byte[] bytes3 = new byte[]{1, 2, 3}; + byte[] bytes3 = new byte[] {1, 2, 3}; buffer3.writeBytes(bytes3); ChannelBuffer buffer4 = ChannelBuffers.buffer(4); - byte[] bytes4 = new byte[]{1, 2, 3, 5}; + byte[] bytes4 = new byte[] {1, 2, 3, 5}; buffer4.writeBytes(bytes4); Assertions.assertTrue(ChannelBuffers.equals(buffer1, buffer2)); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/DirectChannelBufferTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/DirectChannelBufferTest.java index f3d2636c74..879f1b7c5e 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/DirectChannelBufferTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/DirectChannelBufferTest.java @@ -31,6 +31,6 @@ class DirectChannelBufferTest extends AbstractChannelBufferTest { @Override protected ChannelBuffer[] components() { - return new ChannelBuffer[]{buffer}; + return new ChannelBuffer[] {buffer}; } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/DynamicChannelBufferTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/DynamicChannelBufferTest.java index 9e1e8f4ee5..6c968568d0 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/DynamicChannelBufferTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/DynamicChannelBufferTest.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.remoting.buffer; +import java.util.Random; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.Random; - import static org.junit.jupiter.api.Assertions.assertEquals; class DynamicChannelBufferTest extends AbstractChannelBufferTest { @@ -40,7 +40,7 @@ class DynamicChannelBufferTest extends AbstractChannelBufferTest { @Override protected ChannelBuffer[] components() { - return new ChannelBuffer[]{buffer}; + return new ChannelBuffer[] {buffer}; } @Test @@ -71,7 +71,5 @@ class DynamicChannelBufferTest extends AbstractChannelBufferTest { random.nextBytes(bytes); buf.writeBytes(bytes); Assertions.assertEquals(buf.capacity(), 128); - } } - diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/HeapChannelBufferTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/HeapChannelBufferTest.java index ed62db0a96..c1b51b3ee9 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/HeapChannelBufferTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/buffer/HeapChannelBufferTest.java @@ -36,7 +36,7 @@ class HeapChannelBufferTest extends AbstractChannelBufferTest { @Override protected ChannelBuffer[] components() { - return new ChannelBuffer[]{buffer}; + return new ChannelBuffer[] {buffer}; } @Test diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/AbstractMockChannel.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/AbstractMockChannel.java index b2d8bc9624..994bd9acfd 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/AbstractMockChannel.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/AbstractMockChannel.java @@ -39,9 +39,7 @@ public class AbstractMockChannel implements Channel { private Map attributes = new HashMap(1); private volatile Object receivedMessage = null; - public AbstractMockChannel() { - - } + public AbstractMockChannel() {} public AbstractMockChannel(URL remoteUrl) { this.remoteUrl = remoteUrl; diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/CodecAdapterTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/CodecAdapterTest.java index 60214b2c6f..d762186366 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/CodecAdapterTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/CodecAdapterTest.java @@ -26,5 +26,4 @@ class CodecAdapterTest extends ExchangeCodecTest { public void setUp() throws Exception { codec = new CodecAdapter(new DeprecatedExchangeCodec()); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/DeprecatedExchangeCodec.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/DeprecatedExchangeCodec.java index c747ea6eff..f14f355282 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/DeprecatedExchangeCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/DeprecatedExchangeCodec.java @@ -55,7 +55,8 @@ final class DeprecatedExchangeCodec extends DeprecatedTelnetCodec implements Cod protected static final byte FLAG_TWOWAY = (byte) 0x40; protected static final byte FLAG_EVENT = (byte) 0x20; protected static final int SERIALIZATION_MASK = 0x1f; - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DeprecatedExchangeCodec.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(DeprecatedExchangeCodec.class); public Short getMagicCode() { return MAGIC; @@ -80,8 +81,7 @@ final class DeprecatedExchangeCodec extends DeprecatedTelnetCodec implements Cod protected Object decode(Channel channel, InputStream is, int readable, byte[] header) throws IOException { // check magic number. - if (readable > 0 && header[0] != MAGIC_HIGH - || readable > 1 && header[1] != MAGIC_LOW) { + if (readable > 0 && header[0] != MAGIC_HIGH || readable > 1 && header[1] != MAGIC_LOW) { int length = header.length; if (header.length < readable) { header = Bytes.copyOf(header, readable); @@ -112,8 +112,7 @@ final class DeprecatedExchangeCodec extends DeprecatedTelnetCodec implements Cod } // limit input stream. - if (readable != tt) - is = StreamUtils.limitedInputStream(is, len); + if (readable != tt) is = StreamUtils.limitedInputStream(is, len); try { return decodeBody(channel, is, header); @@ -194,11 +193,9 @@ final class DeprecatedExchangeCodec extends DeprecatedTelnetCodec implements Cod protected Object getRequestData(long id) { DefaultFuture future = DefaultFuture.getFuture(id); - if (future == null) - return null; + if (future == null) return null; Request req = future.getRequest(); - if (req == null) - return null; + if (req == null) return null; return req.getData(); } @@ -279,7 +276,13 @@ final class DeprecatedExchangeCodec extends DeprecatedTelnetCodec implements Cod if (!res.isEvent() && res.getStatus() != Response.BAD_RESPONSE) { try { // FIXME log error info in Codec and put all error handle logic in IoHanndler? - logger.warn(TRANSPORT_FAILED_RESPONSE, "", "", "Fail to encode response: " + res + ", send bad_response info instead, cause: " + t.getMessage(), t); + logger.warn( + TRANSPORT_FAILED_RESPONSE, + "", + "", + "Fail to encode response: " + res + ", send bad_response info instead, cause: " + + t.getMessage(), + t); Response r = new Response(res.getId(), res.getVersion()); if (t instanceof IOException) { @@ -292,7 +295,12 @@ final class DeprecatedExchangeCodec extends DeprecatedTelnetCodec implements Cod return; } catch (RemotingException e) { - logger.warn(TRANSPORT_FAILED_RESPONSE, "", "", "Failed to send bad_response info back: " + res + ", cause: " + e.getMessage(), e); + logger.warn( + TRANSPORT_FAILED_RESPONSE, + "", + "", + "Failed to send bad_response info back: " + res + ", cause: " + e.getMessage(), + e); } } @@ -412,5 +420,4 @@ final class DeprecatedExchangeCodec extends DeprecatedTelnetCodec implements Cod protected void encodeResponseData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeResponseData(out, data); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/DeprecatedTelnetCodec.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/DeprecatedTelnetCodec.java index 3f7ded3931..2f9180277c 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/DeprecatedTelnetCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/DeprecatedTelnetCodec.java @@ -44,19 +44,25 @@ import static org.apache.dubbo.remoting.Constants.CHARSET_KEY; public class DeprecatedTelnetCodec implements Codec { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DeprecatedTelnetCodec.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(DeprecatedTelnetCodec.class); private static final String HISTORY_LIST_KEY = "telnet.history.list"; private static final String HISTORY_INDEX_KEY = "telnet.history.index"; - private static final byte[] UP = new byte[]{27, 91, 65}; + private static final byte[] UP = new byte[] {27, 91, 65}; - private static final byte[] DOWN = new byte[]{27, 91, 66}; + private static final byte[] DOWN = new byte[] {27, 91, 66}; - private static final List ENTER = Arrays.asList(new Object[]{new byte[]{'\r', '\n'} /* Windows Enter */, new byte[]{'\n'} /* Linux Enter */}); + private static final List ENTER = Arrays.asList( + new Object[] {new byte[] {'\r', '\n'} /* Windows Enter */, new byte[] {'\n'} /* Linux Enter */}); - private static final List EXIT = Arrays.asList(new Object[]{new byte[]{3} /* Windows Ctrl+C */, new byte[]{-1, -12, -1, -3, 6} /* Linux Ctrl+C */, new byte[]{-1, -19, -1, -3, 6} /* Linux Pause */}); + private static final List EXIT = Arrays.asList(new Object[] { + new byte[] {3} /* Windows Ctrl+C */, + new byte[] {-1, -12, -1, -3, 6} /* Linux Ctrl+C */, + new byte[] {-1, -19, -1, -3, 6} /* Linux Pause */ + }); static void checkPayload(Channel channel, long size) throws IOException { int payload = Constants.DEFAULT_PAYLOAD; @@ -64,7 +70,8 @@ public class DeprecatedTelnetCodec implements Codec { payload = channel.getUrl().getPositiveParameter(Constants.PAYLOAD_KEY, Constants.DEFAULT_PAYLOAD); } if (size > payload) { - IOException e = new IOException("Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel); + IOException e = new IOException( + "Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel); logger.error(TRANSPORT_EXCEED_PAYLOAD_LIMIT, "", "", e.getMessage(), e); throw e; } @@ -124,8 +131,9 @@ public class DeprecatedTelnetCodec implements Codec { } else if (i < message.length - 2) { i = i + 2; } - } else if (b == -1 && i < message.length - 2 - && (message[i + 1] == -3 || message[i + 1] == -5)) { // handshake + } else if (b == -1 + && i < message.length - 2 + && (message[i + 1] == -3 || message[i + 1] == -5)) { // handshake i = i + 2; } else { copy[index++] = message[i]; @@ -164,11 +172,10 @@ public class DeprecatedTelnetCodec implements Codec { InetSocketAddress address = channel.getRemoteAddress(); URL url = channel.getUrl(); boolean client = url.getPort() == address.getPort() - && NetUtils.filterLocalHost(url.getIp()).equals( - NetUtils.filterLocalHost(address.getAddress() - .getHostAddress())); - channel.setAttribute(SIDE_KEY, client ? "client" - : "server"); + && NetUtils.filterLocalHost(url.getIp()) + .equals(NetUtils.filterLocalHost( + address.getAddress().getHostAddress())); + channel.setAttribute(SIDE_KEY, client ? "client" : "server"); return client; } } @@ -182,7 +189,8 @@ public class DeprecatedTelnetCodec implements Codec { output.write(msgData); output.flush(); } else { - ObjectOutput objectOutput = CodecSupport.getSerialization(channel.getUrl()).serialize(channel.getUrl(), output); + ObjectOutput objectOutput = + CodecSupport.getSerialization(channel.getUrl()).serialize(channel.getUrl(), output); objectOutput.writeObject(message); objectOutput.flushBuffer(); } @@ -208,7 +216,9 @@ public class DeprecatedTelnetCodec implements Codec { if (message[message.length - 1] == '\b') { // Windows backspace echo try { boolean doublechar = message.length >= 3 && message[message.length - 3] < 0; // double byte char - channel.send(new String(doublechar ? new byte[]{32, 32, 8, 8} : new byte[]{32, 8}, getCharset(channel).name())); + channel.send(new String( + doublechar ? new byte[] {32, 32, 8, 8} : new byte[] {32, 8}, + getCharset(channel).name())); } catch (RemotingException e) { throw new IOException(StringUtils.toString(e)); } @@ -218,7 +228,8 @@ public class DeprecatedTelnetCodec implements Codec { for (Object command : EXIT) { if (isEquals(message, (byte[]) command)) { if (logger.isInfoEnabled()) { - logger.info(new Exception("Close channel " + channel + " on exit command: " + Arrays.toString((byte[]) command))); + logger.info(new Exception( + "Close channel " + channel + " on exit command: " + Arrays.toString((byte[]) command))); } channel.close(); return null; diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/ExchangeCodecTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/ExchangeCodecTest.java index ee5ea1134e..14a6fbf733 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/ExchangeCodecTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/ExchangeCodecTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.codec; - import org.apache.dubbo.common.Version; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.io.Bytes; @@ -35,18 +34,18 @@ import org.apache.dubbo.remoting.exchange.support.DefaultFuture; import org.apache.dubbo.remoting.telnet.codec.TelnetCodec; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + import static org.apache.dubbo.common.constants.CommonConstants.READONLY_EVENT; /** @@ -70,17 +69,20 @@ class ExchangeCodecTest extends TelnetCodecTest { private static final byte MAGIC_HIGH = (byte) Bytes.short2bytes(MAGIC)[0]; private static final byte MAGIC_LOW = (byte) Bytes.short2bytes(MAGIC)[1]; Serialization serialization = getSerialization(DefaultSerializationSelector.getDefaultRemotingSerialization()); - private static final byte SERIALIZATION_BYTE = FrameworkModel.defaultModel().getExtension(Serialization.class, DefaultSerializationSelector.getDefaultRemotingSerialization()).getContentTypeId(); + private static final byte SERIALIZATION_BYTE = FrameworkModel.defaultModel() + .getExtension(Serialization.class, DefaultSerializationSelector.getDefaultRemotingSerialization()) + .getContentTypeId(); private static Serialization getSerialization(String name) { - Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(name); + Serialization serialization = + ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(name); return serialization; } private Object decode(byte[] request) throws IOException { ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(request); AbstractMockChannel channel = getServerSideChannel(url); - //decode + // decode Object obj = codec.decode(channel, buffer); return obj; } @@ -111,7 +113,7 @@ class ExchangeCodecTest extends TelnetCodecTest { bos.flush(); bos.close(); byte[] data = bos.toByteArray(); -// byte[] len = Bytes.int2bytes(data.length); + // byte[] len = Bytes.int2bytes(data.length); System.arraycopy(data, 0, header, 12, data.length); byte[] request = join(header, data); return request; @@ -122,7 +124,7 @@ class ExchangeCodecTest extends TelnetCodecTest { byte[] newbuf = join(header, objectToByte(request)); return newbuf; } - //=================================================================================== + // =================================================================================== @BeforeEach public void setUp() throws Exception { @@ -132,11 +134,11 @@ class ExchangeCodecTest extends TelnetCodecTest { @Test void test_Decode_Error_MagicNum() throws IOException { HashMap inputBytes = new HashMap(); - inputBytes.put(new byte[]{0}, TelnetCodec.DecodeResult.NEED_MORE_INPUT); - inputBytes.put(new byte[]{MAGIC_HIGH, 0}, TelnetCodec.DecodeResult.NEED_MORE_INPUT); - inputBytes.put(new byte[]{0, MAGIC_LOW}, TelnetCodec.DecodeResult.NEED_MORE_INPUT); + inputBytes.put(new byte[] {0}, TelnetCodec.DecodeResult.NEED_MORE_INPUT); + inputBytes.put(new byte[] {MAGIC_HIGH, 0}, TelnetCodec.DecodeResult.NEED_MORE_INPUT); + inputBytes.put(new byte[] {0, MAGIC_LOW}, TelnetCodec.DecodeResult.NEED_MORE_INPUT); - for (Map.Entry entry: inputBytes.entrySet()) { + for (Map.Entry entry : inputBytes.entrySet()) { testDecode_assertEquals(assemblyDataProtocol(entry.getKey()), entry.getValue()); } } @@ -145,16 +147,16 @@ class ExchangeCodecTest extends TelnetCodecTest { void test_Decode_Error_Length() throws IOException { DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(0), 100000, null); - byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); Channel channel = getServerSideChannel(url); - byte[] baddata = new byte[]{1, 2}; + byte[] baddata = new byte[] {1, 2}; ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(join(request, baddata)); Response obj = (Response) codec.decode(channel, buffer); Assertions.assertEquals(person, obj.getResult()); - //only decode necessary bytes + // only decode necessary bytes Assertions.assertEquals(request.length, buffer.readerIndex()); future.cancel(); @@ -162,12 +164,12 @@ class ExchangeCodecTest extends TelnetCodecTest { @Test void test_Decode_Error_Response_Object() throws IOException { - //00000010-response/oneway/hearbeat=true |20-stats=ok|id=0|length=0 - byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + // 00000010-response/oneway/hearbeat=true |20-stats=ok|id=0|length=0 + byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); - //bad object - byte[] badbytes = new byte[]{-1, -2, -3, -4, -3, -4, -3, -4, -3, -4, -3, -4}; + // bad object + byte[] badbytes = new byte[] {-1, -2, -3, -4, -3, -4, -3, -4, -3, -4, -3, -4}; System.arraycopy(badbytes, 0, request, 21, badbytes.length); Response obj = (Response) decode(request); @@ -176,13 +178,13 @@ class ExchangeCodecTest extends TelnetCodecTest { @Test void testInvalidSerializaitonId() throws Exception { - byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, (byte)0x8F, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - Object obj = decode(header); + byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, (byte) 0x8F, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + Object obj = decode(header); Assertions.assertTrue(obj instanceof Request); Request request = (Request) obj; Assertions.assertTrue(request.isBroken()); Assertions.assertTrue(request.getData() instanceof IOException); - header = new byte[]{MAGIC_HIGH, MAGIC_LOW, (byte)0x1F, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + header = new byte[] {MAGIC_HIGH, MAGIC_LOW, (byte) 0x1F, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; obj = decode(header); Assertions.assertTrue(obj instanceof Response); @@ -193,7 +195,7 @@ class ExchangeCodecTest extends TelnetCodecTest { @Test void test_Decode_Check_Payload() throws IOException { - byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; + byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; byte[] request = assemblyDataProtocol(header); try { @@ -202,35 +204,37 @@ class ExchangeCodecTest extends TelnetCodecTest { Object obj = codec.decode(channel, buffer); Assertions.assertTrue(obj instanceof Response); - Assertions.assertTrue(((Response) obj).getErrorMessage().startsWith( - "Data length too large: " + Bytes.bytes2int(new byte[]{1, 1, 1, 1}))); + Assertions.assertTrue(((Response) obj) + .getErrorMessage() + .startsWith("Data length too large: " + Bytes.bytes2int(new byte[] {1, 1, 1, 1}))); } catch (IOException expected) { - Assertions.assertTrue(expected.getMessage().startsWith("Data length too large: " + Bytes.bytes2int(new byte[]{1, 1, 1, 1}))); + Assertions.assertTrue(expected.getMessage() + .startsWith("Data length too large: " + Bytes.bytes2int(new byte[] {1, 1, 1, 1}))); } - } @Test void test_Decode_Header_Need_Readmore() throws IOException { - byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, 0, 0, 0, 0, 0, 0, 0, 0, 0}; testDecode_assertEquals(header, TelnetCodec.DecodeResult.NEED_MORE_INPUT); } @Test void test_Decode_Body_Need_Readmore() throws IOException { - byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 'a', 'a'}; + byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 'a', 'a'}; testDecode_assertEquals(header, TelnetCodec.DecodeResult.NEED_MORE_INPUT); } @Test void test_Decode_MigicCodec_Contain_ExchangeHeader() throws IOException { - byte[] header = new byte[]{0, 0, MAGIC_HIGH, MAGIC_LOW, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + byte[] header = new byte[] {0, 0, MAGIC_HIGH, MAGIC_LOW, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Channel channel = getServerSideChannel(url); ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(header); Object obj = codec.decode(channel, buffer); Assertions.assertEquals(TelnetCodec.DecodeResult.NEED_MORE_INPUT, obj); - //If the telnet data and request data are in the same data packet, we should guarantee that the receipt of request data won't be affected by the factor that telnet does not have an end characters. + // If the telnet data and request data are in the same data packet, we should guarantee that the receipt of + // request data won't be affected by the factor that telnet does not have an end characters. Assertions.assertEquals(2, buffer.readerIndex()); } @@ -238,8 +242,8 @@ class ExchangeCodecTest extends TelnetCodecTest { void test_Decode_Return_Response_Person() throws IOException { DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(0), 100000, null); - //00000010-response/oneway/hearbeat=false/hessian |20-stats=ok|id=0|length=0 - byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + // 00000010-response/oneway/hearbeat=false/hessian |20-stats=ok|id=0|length=0 + byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); @@ -251,9 +255,9 @@ class ExchangeCodecTest extends TelnetCodecTest { future.cancel(); } - @Test //The status input has a problem, and the read information is wrong when the serialization is serialized. + @Test // The status input has a problem, and the read information is wrong when the serialization is serialized. public void test_Decode_Return_Response_Error() throws IOException { - byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; String errorString = "encode request data error "; byte[] request = getRequestBytes(errorString, header); Response obj = (Response) decode(request); @@ -264,8 +268,10 @@ class ExchangeCodecTest extends TelnetCodecTest { @Test @Disabled("Event should not be object.") void test_Decode_Return_Request_Event_Object() throws IOException { - //|10011111|20-stats=ok|id=0|length=0 - byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + // |10011111|20-stats=ok|id=0|length=0 + byte[] header = new byte[] { + MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; Person person = new Person(); byte[] request = getRequestBytes(person, header); @@ -281,8 +287,10 @@ class ExchangeCodecTest extends TelnetCodecTest { @Test void test_Decode_Return_Request_Event_String() throws IOException { - //|10011111|20-stats=ok|id=0|length=0 - byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + // |10011111|20-stats=ok|id=0|length=0 + byte[] header = new byte[] { + MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; String event = READONLY_EVENT; byte[] request = getRequestBytes(event, header); @@ -296,8 +304,10 @@ class ExchangeCodecTest extends TelnetCodecTest { @Test void test_Decode_Return_Request_Heartbeat_Object() throws IOException { - //|10011111|20-stats=ok|id=0|length=0 - byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + // |10011111|20-stats=ok|id=0|length=0 + byte[] header = new byte[] { + MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; byte[] request = getRequestBytes(null, header); Request obj = (Request) decode(request); Assertions.assertNull(obj.getData()); @@ -310,8 +320,10 @@ class ExchangeCodecTest extends TelnetCodecTest { @Test @Disabled("Event should not be object.") void test_Decode_Return_Request_Object() throws IOException { - //|10011111|20-stats=ok|id=0|length=0 - byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + // |10011111|20-stats=ok|id=0|length=0 + byte[] header = new byte[] { + MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; Person person = new Person(); byte[] request = getRequestBytes(person, header); @@ -327,12 +339,14 @@ class ExchangeCodecTest extends TelnetCodecTest { @Test void test_Decode_Error_Request_Object() throws IOException { - //00000010-response/oneway/hearbeat=true |20-stats=ok|id=0|length=0 - byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + // 00000010-response/oneway/hearbeat=true |20-stats=ok|id=0|length=0 + byte[] header = new byte[] { + MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; Person person = new Person(); byte[] request = getRequestBytes(person, header); - //bad object - byte[] badbytes = new byte[]{-1, -2, -3, -4, -3, -4, -3, -4, -3, -4, -3, -4}; + // bad object + byte[] badbytes = new byte[] {-1, -2, -3, -4, -3, -4, -3, -4, -3, -4, -3, -4}; System.arraycopy(badbytes, 0, request, 21, badbytes.length); Request obj = (Request) decode(request); @@ -344,8 +358,8 @@ class ExchangeCodecTest extends TelnetCodecTest { void test_Header_Response_NoSerializationFlag() throws IOException { DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(0), 100000, null); - //00000010-response/oneway/hearbeat=false/noset |20-stats=ok|id=0|length=0 - byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + // 00000010-response/oneway/hearbeat=false/noset |20-stats=ok|id=0|length=0 + byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); @@ -361,8 +375,8 @@ class ExchangeCodecTest extends TelnetCodecTest { void test_Header_Response_Heartbeat() throws IOException { DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(0), 100000, null); - //00000010-response/oneway/hearbeat=true |20-stats=ok|id=0|length=0 - byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + // 00000010-response/oneway/hearbeat=true |20-stats=ok|id=0|length=0 + byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; Person person = new Person(); byte[] request = getRequestBytes(person, header); @@ -384,7 +398,7 @@ class ExchangeCodecTest extends TelnetCodecTest { codec.encode(channel, encodeBuffer, request); - //encode resault check need decode + // encode resault check need decode byte[] data = new byte[encodeBuffer.writerIndex()]; encodeBuffer.readBytes(data); ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(data); @@ -414,7 +428,7 @@ class ExchangeCodecTest extends TelnetCodecTest { byte[] data = new byte[encodeBuffer.writerIndex()]; encodeBuffer.readBytes(data); - //encode resault check need decode + // encode resault check need decode ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(data); Response obj = (Response) codec.decode(channel, decodeBuffer); @@ -423,7 +437,7 @@ class ExchangeCodecTest extends TelnetCodecTest { Assertions.assertEquals(response.isHeartbeat(), obj.isHeartbeat()); Assertions.assertEquals(person, obj.getResult()); // encode response verson ?? -// Assertions.assertEquals(response.getProtocolVersion(), obj.getVersion()); + // Assertions.assertEquals(response.getProtocolVersion(), obj.getVersion()); future.cancel(); } @@ -446,7 +460,7 @@ class ExchangeCodecTest extends TelnetCodecTest { byte[] data = new byte[encodeBuffer.writerIndex()]; encodeBuffer.readBytes(data); - //encode resault check need decode + // encode resault check need decode ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(data); Response obj = (Response) codec.decode(channel, decodeBuffer); Assertions.assertEquals(response.getId(), obj.getId()); @@ -454,7 +468,7 @@ class ExchangeCodecTest extends TelnetCodecTest { Assertions.assertEquals(response.isHeartbeat(), obj.isHeartbeat()); Assertions.assertEquals(badString, obj.getErrorMessage()); Assertions.assertNull(obj.getResult()); -// Assertions.assertEquals(response.getProtocolVersion(), obj.getVersion()); + // Assertions.assertEquals(response.getProtocolVersion(), obj.getVersion()); } @Test @@ -502,7 +516,8 @@ class ExchangeCodecTest extends TelnetCodecTest { Assertions.fail(); } catch (IOException e) { Assertions.assertTrue(e.getMessage().startsWith("Data length too large: ")); - Assertions.assertTrue(e.getMessage().contains("max payload: 4, channel: org.apache.dubbo.remoting.codec.AbstractMockChannel")); + Assertions.assertTrue(e.getMessage() + .contains("max payload: 4, channel: org.apache.dubbo.remoting.codec.AbstractMockChannel")); } Response response = new Response(1L); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/TelnetCodecTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/TelnetCodecTest.java index cd0a9c5d48..bdcbc4a9c9 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/TelnetCodecTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/TelnetCodecTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.codec; - import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Codec2; @@ -24,10 +23,6 @@ import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBuffers; import org.apache.dubbo.remoting.telnet.codec.TelnetCodec; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -37,11 +32,15 @@ import java.io.Serializable; import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + class TelnetCodecTest { protected Codec2 codec; - byte[] UP = new byte[]{27, 91, 65}; - byte[] DOWN = new byte[]{27, 91, 66}; - //====================================================== + byte[] UP = new byte[] {27, 91, 65}; + byte[] DOWN = new byte[] {27, 91, 66}; + // ====================================================== URL url = URL.valueOf("dubbo://10.20.30.40:20880"); /** @@ -81,7 +80,7 @@ class TelnetCodecTest { bytes = (byte[]) obj; } else { try { - //object to bytearray + // object to bytearray ByteArrayOutputStream bo = new ByteArrayOutputStream(); ObjectOutputStream oo = new ObjectOutputStream(bo); oo.writeObject(obj); @@ -109,19 +108,18 @@ class TelnetCodecTest { } protected void testDecode_assertEquals(byte[] request, Object ret, boolean isServerside) throws IOException { - //init channel + // init channel Channel channel = isServerside ? getServerSideChannel(url) : getClientSideChannel(url); - //init request string + // init request string ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(request); - //decode + // decode Object obj = codec.decode(channel, buffer); Assertions.assertEquals(ret, obj); } - protected void testEecode_assertEquals(Object request, byte[] ret, boolean isServerside) throws IOException { - //init channel + // init channel Channel channel = isServerside ? getServerSideChannel(url) : getClientSideChannel(url); ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(1024); @@ -146,8 +144,9 @@ class TelnetCodecTest { testDecode_assertEquals(null, request, ret, channelReceive); } - private void testDecode_assertEquals(AbstractMockChannel channel, Object request, Object expectRet, Object channelReceive) throws IOException { - //init channel + private void testDecode_assertEquals( + AbstractMockChannel channel, Object request, Object expectRet, Object channelReceive) throws IOException { + // init channel if (channel == null) { channel = getServerSideChannel(url); } @@ -155,21 +154,21 @@ class TelnetCodecTest { byte[] buf = objectToByte(request); ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(buf); - //decode + // decode Object obj = codec.decode(channel, buffer); Assertions.assertEquals(expectRet, obj); Assertions.assertEquals(channelReceive, channel.getReceivedMessage()); } private void testDecode_PersonWithEnterByte(byte[] enterBytes, boolean isNeedMore) throws IOException { - //init channel + // init channel Channel channel = getServerSideChannel(url); - //init request string + // init request string Person request = new Person(); byte[] newBuf = join(objectToByte(request), enterBytes); ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(newBuf); - //decode + // decode Object obj = codec.decode(channel, buffer); if (isNeedMore) { Assertions.assertEquals(Codec2.DecodeResult.NEED_MORE_INPUT, obj); @@ -179,11 +178,11 @@ class TelnetCodecTest { } private void testDecode_WithExitByte(byte[] exitbytes, boolean isChannelClose) throws IOException { - //init channel + // init channel Channel channel = getServerSideChannel(url); ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(exitbytes); - //decode + // decode codec.decode(channel, buffer); Assertions.assertEquals(isChannelClose, channel.isClosed()); } @@ -195,7 +194,7 @@ class TelnetCodecTest { @Test void testDecode_BlankMessage() throws IOException { - testDecode_assertEquals(new byte[]{}, Codec2.DecodeResult.NEED_MORE_INPUT); + testDecode_assertEquals(new byte[] {}, Codec2.DecodeResult.NEED_MORE_INPUT); } @Test @@ -220,21 +219,21 @@ class TelnetCodecTest { @Test void testDecode_Person_WithEnter() throws IOException { - testDecode_PersonWithEnterByte(new byte[]{'\r', '\n'}, false);//windows end - testDecode_PersonWithEnterByte(new byte[]{'\n', '\r'}, true); - testDecode_PersonWithEnterByte(new byte[]{'\n'}, false); //linux end - testDecode_PersonWithEnterByte(new byte[]{'\r'}, true); - testDecode_PersonWithEnterByte(new byte[]{'\r', 100}, true); + testDecode_PersonWithEnterByte(new byte[] {'\r', '\n'}, false); // windows end + testDecode_PersonWithEnterByte(new byte[] {'\n', '\r'}, true); + testDecode_PersonWithEnterByte(new byte[] {'\n'}, false); // linux end + testDecode_PersonWithEnterByte(new byte[] {'\r'}, true); + testDecode_PersonWithEnterByte(new byte[] {'\r', 100}, true); } @Test void testDecode_WithExitByte() throws IOException { HashMap exitBytes = new HashMap(); - exitBytes.put(new byte[]{3}, true); /* Windows Ctrl+C */ - exitBytes.put(new byte[]{1, 3}, false); //must equal the bytes - exitBytes.put(new byte[]{-1, -12, -1, -3, 6}, true); /* Linux Ctrl+C */ - exitBytes.put(new byte[]{1, -1, -12, -1, -3, 6}, false); //must equal the bytes - exitBytes.put(new byte[]{-1, -19, -1, -3, 6}, true); /* Linux Pause */ + exitBytes.put(new byte[] {3}, true); /* Windows Ctrl+C */ + exitBytes.put(new byte[] {1, 3}, false); // must equal the bytes + exitBytes.put(new byte[] {-1, -12, -1, -3, 6}, true); /* Linux Ctrl+C */ + exitBytes.put(new byte[] {1, -1, -12, -1, -3, 6}, false); // must equal the bytes + exitBytes.put(new byte[] {-1, -19, -1, -3, 6}, true); /* Linux Pause */ for (Map.Entry entry : exitBytes.entrySet()) { testDecode_WithExitByte(entry.getKey(), entry.getValue()); @@ -243,15 +242,19 @@ class TelnetCodecTest { @Test void testDecode_Backspace() throws IOException { - //32 8 first add space and then add backspace. - testDecode_assertEquals(new byte[]{'\b'}, Codec2.DecodeResult.NEED_MORE_INPUT, new String(new byte[]{32, 8})); + // 32 8 first add space and then add backspace. + testDecode_assertEquals(new byte[] {'\b'}, Codec2.DecodeResult.NEED_MORE_INPUT, new String(new byte[] {32, 8})); // test chinese byte[] chineseBytes = "中".getBytes(); - byte[] request = join(chineseBytes, new byte[]{'\b'}); - testDecode_assertEquals(request, Codec2.DecodeResult.NEED_MORE_INPUT, new String(new byte[]{32, 32, 8, 8})); - //There may be some problem handling chinese (negative number recognition). Ignoring this problem, the backspace key is only meaningfully input in a real telnet program. - testDecode_assertEquals(new byte[]{'a', 'x', -1, 'x', '\b'}, Codec2.DecodeResult.NEED_MORE_INPUT, new String(new byte[]{32, 32, 8, 8})); + byte[] request = join(chineseBytes, new byte[] {'\b'}); + testDecode_assertEquals(request, Codec2.DecodeResult.NEED_MORE_INPUT, new String(new byte[] {32, 32, 8, 8})); + // There may be some problem handling chinese (negative number recognition). Ignoring this problem, the + // backspace key is only meaningfully input in a real telnet program. + testDecode_assertEquals( + new byte[] {'a', 'x', -1, 'x', '\b'}, + Codec2.DecodeResult.NEED_MORE_INPUT, + new String(new byte[] {32, 32, 8, 8})); } @Test @@ -265,14 +268,14 @@ class TelnetCodecTest { @Test void testDecode_History_UP() throws IOException { - //init channel + // init channel AbstractMockChannel channel = getServerSideChannel(url); testDecode_assertEquals(channel, UP, Codec2.DecodeResult.NEED_MORE_INPUT, null); String request1 = "aaa\n"; Object expected1 = "aaa"; - //init history + // init history testDecode_assertEquals(channel, request1, expected1, null); testDecode_assertEquals(channel, UP, Codec2.DecodeResult.NEED_MORE_INPUT, expected1); @@ -283,14 +286,14 @@ class TelnetCodecTest { Assertions.assertThrows(IOException.class, () -> { url = url.addParameter(AbstractMockChannel.ERROR_WHEN_SEND, Boolean.TRUE.toString()); - //init channel + // init channel AbstractMockChannel channel = getServerSideChannel(url); testDecode_assertEquals(channel, UP, Codec2.DecodeResult.NEED_MORE_INPUT, null); String request1 = "aaa\n"; Object expected1 = "aaa"; - //init history + // init history testDecode_assertEquals(channel, request1, expected1, null); testDecode_assertEquals(channel, UP, Codec2.DecodeResult.NEED_MORE_INPUT, expected1); @@ -299,31 +302,31 @@ class TelnetCodecTest { }); } - //============================================================================================================================= + // ============================================================================================================================= @Test void testEncode_String_ClientSide() throws IOException { testEecode_assertEquals("aaa", "aaa\r\n".getBytes(), false); } - + /*@Test public void testDecode_History_UP_DOWN_MULTI() throws IOException{ AbstractMockChannel channel = getServerSideChannel(url); - - String request1 = "aaa\n"; + + String request1 = "aaa\n"; Object expected1 = request1.replace("\n", ""); - //init history + //init history testDecode_assertEquals(channel, request1, expected1, null); - - String request2 = "bbb\n"; + + String request2 = "bbb\n"; Object expected2 = request2.replace("\n", ""); - //init history + //init history testDecode_assertEquals(channel, request2, expected2, null); - - String request3 = "ccc\n"; + + String request3 = "ccc\n"; Object expected3= request3.replace("\n", ""); - //init history + //init history testDecode_assertEquals(channel, request3, expected3, null); - + byte[] UP = new byte[] {27, 91, 65}; byte[] DOWN = new byte[] {27, 91, 66}; //history[aaa,bbb,ccc] @@ -340,7 +343,7 @@ class TelnetCodecTest { testDecode_assertEquals(channel, UP, Codec.NEED_MORE_INPUT, expected2); }*/ - //====================================================== + // ====================================================== public static class Person implements Serializable { private static final long serialVersionUID = 3362088148941547337L; public String name; @@ -357,26 +360,17 @@ class TelnetCodecTest { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; + if (other.name != null) return false; + } else if (!name.equals(other.name)) return false; if (sex == null) { - if (other.sex != null) - return false; - } else if (!sex.equals(other.sex)) - return false; + if (other.sex != null) return false; + } else if (!sex.equals(other.sex)) return false; return true; } - } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/ExchangersTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/ExchangersTest.java index f6a991d164..134aaa90e3 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/ExchangersTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/ExchangersTest.java @@ -35,10 +35,9 @@ class ExchangersTest { Exchangers.bind(url, new ChannelHandlerAdapter(), Mockito.mock(Replier.class)); Exchangers.bind(url, new ExchangeHandlerDispatcher()); - Assertions.assertThrows(RuntimeException.class, - () -> Exchangers.bind((URL) null, new ExchangeHandlerDispatcher())); - Assertions.assertThrows(RuntimeException.class, - () -> Exchangers.bind(url, (ExchangeHandlerDispatcher) null)); + Assertions.assertThrows( + RuntimeException.class, () -> Exchangers.bind((URL) null, new ExchangeHandlerDispatcher())); + Assertions.assertThrows(RuntimeException.class, () -> Exchangers.bind(url, (ExchangeHandlerDispatcher) null)); } @Test @@ -50,9 +49,9 @@ class ExchangersTest { Exchangers.connect(url, new ChannelHandlerAdapter(), Mockito.mock(Replier.class)); Exchangers.connect(url, new ExchangeHandlerDispatcher()); - Assertions.assertThrows(RuntimeException.class, - () -> Exchangers.connect((URL) null, new ExchangeHandlerDispatcher())); - Assertions.assertThrows(RuntimeException.class, - () -> Exchangers.connect(url, (ExchangeHandlerDispatcher) null)); + Assertions.assertThrows( + RuntimeException.class, () -> Exchangers.connect((URL) null, new ExchangeHandlerDispatcher())); + Assertions.assertThrows( + RuntimeException.class, () -> Exchangers.connect(url, (ExchangeHandlerDispatcher) null)); } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/MockExchanger.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/MockExchanger.java index 9c820c08cf..1a6b662c7d 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/MockExchanger.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/MockExchanger.java @@ -21,7 +21,7 @@ import org.apache.dubbo.remoting.RemotingException; import org.mockito.Mockito; -public class MockExchanger implements Exchanger{ +public class MockExchanger implements Exchanger { private ExchangeServer exchangeServer = Mockito.mock(ExchangeServer.class); private ExchangeClient exchangeClient = Mockito.mock(ExchangeClient.class); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/RequestTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/RequestTest.java index ae1323e865..9bfa7def77 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/RequestTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/RequestTest.java @@ -50,5 +50,4 @@ class RequestTest { Request copyWithoutData = request.copyWithoutData(); Assertions.assertNull(copyWithoutData.getData()); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/ResponseTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/ResponseTest.java index 54d135bd9b..95a8da81ce 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/ResponseTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/ResponseTest.java @@ -39,5 +39,4 @@ class ResponseTest { Assertions.assertEquals(response.getResult(), HEARTBEAT_EVENT); Assertions.assertEquals(response.getErrorMessage(), "errorMsg"); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/DefaultFutureTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/DefaultFutureTest.java index 171d040cd9..c2d5f4ac8f 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/DefaultFutureTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/DefaultFutureTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.exchange.support; import org.apache.dubbo.common.URL; @@ -26,15 +25,15 @@ import org.apache.dubbo.remoting.TimeoutException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.handler.MockedChannel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + class DefaultFutureTest { private static final AtomicInteger index = new AtomicInteger(); @@ -50,7 +49,7 @@ class DefaultFutureTest { DefaultFuture future = defaultFuture(3000); Assertions.assertTrue(!future.isDone(), "init future is finished!"); - //cancel a future + // cancel a future future.cancel(); Assertions.assertTrue(future.isDone(), "cancel a future failed!"); } @@ -68,20 +67,23 @@ class DefaultFutureTest { @Disabled public void timeoutNotSend() throws Exception { final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - System.out.println("before a future is create , time is : " + LocalDateTime.now().format(formatter)); + System.out.println( + "before a future is create , time is : " + LocalDateTime.now().format(formatter)); // timeout after 5 seconds. DefaultFuture f = defaultFuture(5000); while (!f.isDone()) { - //spin + // spin Thread.sleep(100); } - System.out.println("after a future is timeout , time is : " + LocalDateTime.now().format(formatter)); + System.out.println( + "after a future is timeout , time is : " + LocalDateTime.now().format(formatter)); // get operate will throw a timeout exception, because the future is timeout. try { f.get(); } catch (Exception e) { - Assertions.assertTrue(e.getCause() instanceof TimeoutException, "catch exception is not timeout exception!"); + Assertions.assertTrue( + e.getCause() instanceof TimeoutException, "catch exception is not timeout exception!"); System.out.println(e.getMessage()); } } @@ -98,7 +100,8 @@ class DefaultFutureTest { @Test public void clientTimeoutSend() throws Exception { final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); - System.out.println("before a future is create , time is : " + LocalDateTime.now().format(formatter)); + System.out.println( + "before a future is create , time is : " + LocalDateTime.now().format(formatter)); // timeout after 5 milliseconds. Channel channel = new MockedChannel(); Request request = new Request(10); @@ -111,15 +114,19 @@ class DefaultFutureTest { // spin Thread.sleep(100); } - System.out.println("after a future is timeout , time is : " + LocalDateTime.now().format(formatter)); + System.out.println( + "after a future is timeout , time is : " + LocalDateTime.now().format(formatter)); // get operate will throw a timeout exception, because the future is timeout. try { f.get(); } catch (Exception e) { - Assertions.assertTrue(e.getCause() instanceof TimeoutException, "catch exception is not timeout exception!"); + Assertions.assertTrue( + e.getCause() instanceof TimeoutException, "catch exception is not timeout exception!"); System.out.println(e.getMessage()); - Assertions.assertTrue(e.getMessage().startsWith(e.getCause().getClass().getCanonicalName() + ": Sending request timeout in client-side")); + Assertions.assertTrue(e.getMessage() + .startsWith( + e.getCause().getClass().getCanonicalName() + ": Sending request timeout in client-side")); } } @@ -136,24 +143,27 @@ class DefaultFutureTest { @Disabled public void timeoutSend() throws Exception { final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - System.out.println("before a future is create , time is : " + LocalDateTime.now().format(formatter)); + System.out.println( + "before a future is create , time is : " + LocalDateTime.now().format(formatter)); // timeout after 5 seconds. Channel channel = new MockedChannel(); Request request = new Request(10); DefaultFuture f = DefaultFuture.newFuture(channel, request, 5000, null); - //mark the future is sent + // mark the future is sent DefaultFuture.sent(channel, request); while (!f.isDone()) { - //spin + // spin Thread.sleep(100); } - System.out.println("after a future is timeout , time is : " + LocalDateTime.now().format(formatter)); + System.out.println( + "after a future is timeout , time is : " + LocalDateTime.now().format(formatter)); // get operate will throw a timeout exception, because the future is timeout. try { f.get(); } catch (Exception e) { - Assertions.assertTrue(e.getCause() instanceof TimeoutException, "catch exception is not timeout exception!"); + Assertions.assertTrue( + e.getCause() instanceof TimeoutException, "catch exception is not timeout exception!"); System.out.println(e.getMessage()); } } @@ -166,19 +176,20 @@ class DefaultFutureTest { @Test void interruptSend() throws Exception { final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - System.out.println("before a future is create , time is : " + LocalDateTime.now().format(formatter)); + System.out.println( + "before a future is create , time is : " + LocalDateTime.now().format(formatter)); // timeout after 1 seconds. Channel channel = new MockedChannel(); int channelId = 10; Request request = new Request(channelId); ThreadlessExecutor executor = new ThreadlessExecutor(); DefaultFuture f = DefaultFuture.newFuture(channel, request, 1000, executor); - //mark the future is sent + // mark the future is sent DefaultFuture.sent(channel, request); // get operate will throw a interrupted exception, because the thread is interrupted. try { new InterruptThread(Thread.currentThread()).start(); - while (!f. isDone()){ + while (!f.isDone()) { executor.waitAndDrain(Long.MAX_VALUE); } f.get(); @@ -188,12 +199,13 @@ class DefaultFutureTest { } finally { executor.shutdown(); } - //waiting timeout check task finished + // waiting timeout check task finished Thread.sleep(1500); - System.out.println("after a future is timeout , time is : " + LocalDateTime.now().format(formatter)); + System.out.println( + "after a future is timeout , time is : " + LocalDateTime.now().format(formatter)); DefaultFuture future = DefaultFuture.getFuture(channelId); - //waiting future should be removed by time out check task + // waiting future should be removed by time out check task Assertions.assertNull(future); } @@ -202,7 +214,8 @@ class DefaultFutureTest { Channel channel = new MockedChannel(); Request request = new Request(123); ExecutorService executor = ExtensionLoader.getExtensionLoader(ExecutorRepository.class) - .getDefaultExtension().createExecutorIfAbsent(URL.valueOf("dubbo://127.0.0.1:23456")); + .getDefaultExtension() + .createExecutorIfAbsent(URL.valueOf("dubbo://127.0.0.1:23456")); DefaultFuture.newFuture(channel, request, 1000, executor); DefaultFuture.closeChannel(channel, 0); Assertions.assertFalse(executor.isTerminated()); @@ -241,15 +254,12 @@ class DefaultFutureTest { public void run() { super.run(); try { - //interrupt waiting thread before timeout + // interrupt waiting thread before timeout Thread.sleep(500); parent.interrupt(); } catch (InterruptedException e) { System.out.println(e.getMessage()); } } - } - - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/ExchangeHandlerDispatcherTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/ExchangeHandlerDispatcherTest.java index f06ae441e5..8a35165855 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/ExchangeHandlerDispatcherTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/ExchangeHandlerDispatcherTest.java @@ -21,11 +21,11 @@ import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.telnet.support.TelnetHandlerAdapter; +import java.lang.reflect.Field; + import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.lang.reflect.Field; - class ExchangeHandlerDispatcherTest { @Test diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/MultiMessageTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/MultiMessageTest.java index 5cfb6fdacf..f24a927092 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/MultiMessageTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/MultiMessageTest.java @@ -16,13 +16,13 @@ */ package org.apache.dubbo.remoting.exchange.support; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.Arrays; import java.util.Collection; import java.util.Iterator; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + /** * {@link MultiMessage} */ @@ -59,8 +59,8 @@ class MultiMessageTest { MultiMessage multiMessage1 = MultiMessage.createFromCollection(Arrays.asList("test1", "test2")); MultiMessage multiMessage2 = MultiMessage.createFromArray("test1", "test2"); - Assertions.assertArrayEquals(multiMessage1.getMessages().toArray(), multiMessage2.getMessages().toArray()); - + Assertions.assertArrayEquals( + multiMessage1.getMessages().toArray(), + multiMessage2.getMessages().toArray()); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/CloseTimerTaskTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/CloseTimerTaskTest.java index 882a481c24..0e385a6f4c 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/CloseTimerTaskTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/CloseTimerTaskTest.java @@ -20,14 +20,14 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.timer.HashedWheelTimer; import org.apache.dubbo.remoting.Channel; +import java.util.Collections; +import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Collections; -import java.util.concurrent.TimeUnit; - import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.remoting.Constants.HEARTBEAT_CHECK_TICK; @@ -76,5 +76,4 @@ class CloseTimerTaskTest { Thread.sleep(2000L); Assertions.assertTrue(channel.isClosed()); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannelTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannelTest.java index 150752639c..5def632fd7 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannelTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeChannelTest.java @@ -22,14 +22,14 @@ import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.support.DefaultFuture; +import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import java.util.List; - import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -72,7 +72,6 @@ class HeaderExchangeChannelTest { public boolean isConnected() { return true; } - }; Assertions.assertNull(channel.getAttribute(CHANNEL_KEY)); HeaderExchangeChannel ret = HeaderExchangeChannel.getOrAddChannel(channel); @@ -88,7 +87,6 @@ class HeaderExchangeChannelTest { Assertions.assertNull(ret); } - @Test void removeChannelIfDisconnectedTest() { Assertions.assertNull(channel.getAttribute(CHANNEL_KEY)); @@ -186,18 +184,16 @@ class HeaderExchangeChannelTest { Assertions.assertTrue(channel.isClosed()); } - @Test void closeWithTimeoutTest02() { Assertions.assertFalse(channel.isClosed()); Request request = new Request(); DefaultFuture.newFuture(channel, request, 100, null); header.close(100); - //return directly + // return directly header.close(1000); } - @Test void startCloseTest() { try { @@ -231,7 +227,6 @@ class HeaderExchangeChannelTest { Assertions.assertFalse(header.isConnected()); } - @Test void getChannelHandlerTest() { Assertions.assertNull(header.getChannelHandler()); @@ -242,7 +237,6 @@ class HeaderExchangeChannelTest { Assertions.assertNull(header.getExchangeHandler()); } - @Test void getAttributeAndSetAttributeTest() { header.setAttribute("test", "test"); @@ -258,7 +252,6 @@ class HeaderExchangeChannelTest { Assertions.assertFalse(header.hasAttribute("test")); } - @Test void hasAttributeTest() { Assertions.assertFalse(header.hasAttribute("test")); @@ -284,10 +277,8 @@ class HeaderExchangeChannelTest { }); } - @Test void toStringTest() { Assertions.assertEquals(header.toString(), channel.toString()); } } - diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServerTest.java index 5fedc828df..37b1dc9b69 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeaderExchangeServerTest.java @@ -23,14 +23,14 @@ import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.RemotingServer; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - import java.net.InetSocketAddress; import java.util.Arrays; import java.util.Collection; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + /** * {@link HeaderExchangeServer} */ @@ -51,8 +51,10 @@ class HeaderExchangeServerTest { Channel channel2 = Mockito.mock(Channel.class); Channel exchangeChannel1 = new HeaderExchangeChannel(channel1); Channel exchangeChannel2 = new HeaderExchangeChannel(channel2); - Mockito.when(channel1.getAttribute(HeaderExchangeChannel.class.getName() + ".CHANNEL")).thenReturn(exchangeChannel1); - Mockito.when(channel2.getAttribute(HeaderExchangeChannel.class.getName() + ".CHANNEL")).thenReturn(exchangeChannel2); + Mockito.when(channel1.getAttribute(HeaderExchangeChannel.class.getName() + ".CHANNEL")) + .thenReturn(exchangeChannel1); + Mockito.when(channel2.getAttribute(HeaderExchangeChannel.class.getName() + ".CHANNEL")) + .thenReturn(exchangeChannel2); Collection exChannels = Arrays.asList(exchangeChannel1, exchangeChannel2); Mockito.when(server.getChannels()).thenReturn(Arrays.asList(channel1, channel2)); Assertions.assertEquals(headerExchangeServer.getChannels(), exChannels); @@ -87,5 +89,4 @@ class HeaderExchangeServerTest { Assertions.assertThrows(RemotingException.class, () -> headerExchangeServer.send("test")); Assertions.assertThrows(RemotingException.class, () -> headerExchangeServer.send("test", true)); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java index 07a0f63a0a..f5ccd39793 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartBeatTaskTest.java @@ -14,22 +14,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.exchange.support.header; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.timer.HashedWheelTimer; import org.apache.dubbo.remoting.exchange.Request; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; - import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.remoting.Constants.HEARTBEAT_CHECK_TICK; @@ -55,7 +54,9 @@ class HeartBeatTaskTest { } }; - heartbeatTimerTask = new HeartbeatTimerTask(() -> Collections.singleton(channel), heartbeatTimer, tickDuration / HEARTBEAT_CHECK_TICK, (int) tickDuration); + heartbeatTimerTask = new HeartbeatTimerTask( + () -> Collections.singleton(channel), heartbeatTimer, tickDuration / HEARTBEAT_CHECK_TICK, (int) + tickDuration); } @AfterEach @@ -79,5 +80,4 @@ class HeartBeatTaskTest { Request request = (Request) obj; Assertions.assertTrue(request.isHeartbeat()); } - } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/MockChannel.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/MockChannel.java index 0512dffe04..335247f48d 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/MockChannel.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/MockChannel.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.exchange.support.header; import org.apache.dubbo.common.Parameters; @@ -124,9 +123,7 @@ public class MockChannel implements Channel, Client { } @Override - public void reset(URL url) { - - } + public void reset(URL url) {} @Override public void reconnect() throws RemotingException { @@ -134,9 +131,7 @@ public class MockChannel implements Channel, Client { } @Override - public void reset(Parameters parameters) { - - } + public void reset(Parameters parameters) {} public int getReconnectCount() { return reconnectCount; diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/ReconnectTimerTaskTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/ReconnectTimerTaskTest.java index e68b26355e..6c758b372a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/ReconnectTimerTaskTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/support/header/ReconnectTimerTaskTest.java @@ -19,14 +19,14 @@ package org.apache.dubbo.remoting.exchange.support.header; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.timer.HashedWheelTimer; +import java.util.Collections; +import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Collections; -import java.util.concurrent.TimeUnit; - import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.remoting.Constants.HEARTBEAT_CHECK_TICK; @@ -56,7 +56,9 @@ class ReconnectTimerTaskTest { } }; - reconnectTimerTask = new ReconnectTimerTask(() -> Collections.singleton(channel), reconnectTimer, tickDuration / HEARTBEAT_CHECK_TICK, (int) tickDuration); + reconnectTimerTask = new ReconnectTimerTask( + () -> Collections.singleton(channel), reconnectTimer, tickDuration / HEARTBEAT_CHECK_TICK, (int) + tickDuration); } @AfterEach diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/HeaderExchangeHandlerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/HeaderExchangeHandlerTest.java index 7cd1437d59..ed0bde4f9a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/HeaderExchangeHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/HeaderExchangeHandlerTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.handler; - import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; @@ -27,16 +26,16 @@ import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.exchange.support.DefaultFuture; import org.apache.dubbo.remoting.exchange.support.header.HeaderExchangeHandler; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.HEARTBEAT_EVENT; import static org.apache.dubbo.common.constants.CommonConstants.READONLY_EVENT; -//TODO response test +// TODO response test class HeaderExchangeHandlerTest { @Test @@ -221,7 +220,7 @@ class HeaderExchangeHandlerTest { headerExchangeHandler.received(mockChannel, response); Object result = future.get(); - Assertions.assertEquals(result.toString(),"MOCK_DATA"); + Assertions.assertEquals(result.toString(), "MOCK_DATA"); } private class BizException extends RuntimeException { diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/MockedChannel.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/MockedChannel.java index 902445e3c7..7224aab981 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/MockedChannel.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/MockedChannel.java @@ -36,7 +36,6 @@ public class MockedChannel implements Channel { super(); } - @Override public URL getUrl() { return url; @@ -55,8 +54,7 @@ public class MockedChannel implements Channel { } @Override - public void send(Object message) throws RemotingException { - } + public void send(Object message) throws RemotingException {} @Override public void send(Object message, boolean sent) throws RemotingException { diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/MockedChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/MockedChannelHandler.java index d9ffe9bebc..a38fe8d6a5 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/MockedChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/MockedChannelHandler.java @@ -45,14 +45,13 @@ public class MockedChannelHandler implements ChannelHandler { @Override public void received(Channel channel, Object message) throws RemotingException { - //echo + // echo channel.send(message); } @Override public void caught(Channel channel, Throwable exception) throws RemotingException { throw new RemotingException(channel, exception); - } public Set getChannels() { diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/TelnetUtilsTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/TelnetUtilsTest.java index 452a3df5c0..23dd1faa8f 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/TelnetUtilsTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/TelnetUtilsTest.java @@ -18,13 +18,13 @@ package org.apache.dubbo.remoting.telnet; import org.apache.dubbo.remoting.telnet.support.TelnetUtils; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.Arrays; import java.util.LinkedList; import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class TelnetUtilsTest { /** @@ -35,9 +35,9 @@ class TelnetUtilsTest { @Test void testToList() { List> table = new LinkedList<>(); - table.add(Arrays.asList("abc","abc","abc")); - table.add(Arrays.asList("1","2","3")); - table.add(Arrays.asList("x","y","z")); + table.add(Arrays.asList("abc", "abc", "abc")); + table.add(Arrays.asList("1", "2", "3")); + table.add(Arrays.asList("x", "y", "z")); String toList = TelnetUtils.toList(table); @@ -58,11 +58,11 @@ class TelnetUtilsTest { @Test void testToTable() { List> table = new LinkedList<>(); - table.add(Arrays.asList("abc","abc","abc")); - table.add(Arrays.asList("1","2","3")); - table.add(Arrays.asList("x","y","z")); + table.add(Arrays.asList("abc", "abc", "abc")); + table.add(Arrays.asList("1", "2", "3")); + table.add(Arrays.asList("x", "y", "z")); - String toTable = TelnetUtils.toTable(new String[]{"A","B","C"},table); + String toTable = TelnetUtils.toTable(new String[] {"A", "B", "C"}, table); Assertions.assertTrue(toTable.contains("| A | B | C |")); Assertions.assertTrue(toTable.contains("| abc | abc | abc |")); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/ClearTelnetHandlerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/ClearTelnetHandlerTest.java index c9163fb98e..8cf9f990b0 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/ClearTelnetHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/ClearTelnetHandlerTest.java @@ -36,7 +36,8 @@ class ClearTelnetHandlerTest { Assertions.assertEquals(buf.toString(), telnetHandler.telnet(Mockito.mock(Channel.class), "50")); // Illegal Input - Assertions.assertTrue(telnetHandler.telnet(Mockito.mock(Channel.class), "Illegal").contains("Illegal")); + Assertions.assertTrue( + telnetHandler.telnet(Mockito.mock(Channel.class), "Illegal").contains("Illegal")); for (int i = 0; i < 50; i++) { buf.append("\r\n"); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/HelpTelnetHandlerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/HelpTelnetHandlerTest.java index a5b77dd8ef..34e55e6d6a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/HelpTelnetHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/HelpTelnetHandlerTest.java @@ -37,13 +37,11 @@ class HelpTelnetHandlerTest { Assertions.assertTrue(helpTelnetHandler.telnet(channel, "").contains(prompt)); // "help" command output - String demoOutput = - "Command:\r\n" + - " help [command]\r\n" + - "Summary:\r\n" + - " Show help.\r\n" + - "Detail:\r\n" + - " Show help."; - Assertions.assertEquals(helpTelnetHandler.telnet(channel, "help"),demoOutput); + String demoOutput = "Command:\r\n" + " help [command]\r\n" + + "Summary:\r\n" + + " Show help.\r\n" + + "Detail:\r\n" + + " Show help."; + Assertions.assertEquals(helpTelnetHandler.telnet(channel, "help"), demoOutput); } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/StatusTelnetHandlerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/StatusTelnetHandlerTest.java index 9fc9da5824..471a6355d5 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/StatusTelnetHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/StatusTelnetHandlerTest.java @@ -31,14 +31,14 @@ class StatusTelnetHandlerTest { Mockito.when(channel.getUrl()).thenReturn(URL.valueOf("dubbo://127.0.0.1:12345")); StatusTelnetHandler statusTelnetHandler = new StatusTelnetHandler(); - Assertions.assertNotNull(statusTelnetHandler.telnet(channel,"")); - Assertions.assertNotNull(statusTelnetHandler.telnet(channel,"-l")); + Assertions.assertNotNull(statusTelnetHandler.telnet(channel, "")); + Assertions.assertNotNull(statusTelnetHandler.telnet(channel, "-l")); String errorPrompt = "Unsupported parameter "; - Assertions.assertTrue(statusTelnetHandler.telnet(channel,"other").contains(errorPrompt)); + Assertions.assertTrue(statusTelnetHandler.telnet(channel, "other").contains(errorPrompt)); Mockito.when(channel.getUrl()).thenReturn(URL.valueOf("dubbo://127.0.0.1:12345?status=load,memory")); - Assertions.assertNotNull(statusTelnetHandler.telnet(channel,"")); - Assertions.assertNotNull(statusTelnetHandler.telnet(channel,"-l")); + Assertions.assertNotNull(statusTelnetHandler.telnet(channel, "")); + Assertions.assertNotNull(statusTelnetHandler.telnet(channel, "-l")); } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapterTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapterTest.java index 40afb734be..65b8d6fda1 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapterTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/telnet/support/TelnetHandlerAdapterTest.java @@ -22,13 +22,13 @@ import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.rpc.model.FrameworkModel; +import java.util.HashMap; +import java.util.Map; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.HashMap; -import java.util.Map; - class TelnetHandlerAdapterTest { @Test @@ -54,7 +54,8 @@ class TelnetHandlerAdapterTest { Assertions.assertEquals(expectedResult, telnetHandlerAdapter.telnet(channel, message)); message = "--no-prompt help"; - expectedResult = "Command: help disabled for security reasons, please enable support by listing the commands through 'telnet'\r\n"; + expectedResult = + "Command: help disabled for security reasons, please enable support by listing the commands through 'telnet'\r\n"; Assertions.assertEquals(expectedResult, telnetHandlerAdapter.telnet(channel, message)); message = "--no-prompt"; @@ -62,7 +63,8 @@ class TelnetHandlerAdapterTest { Assertions.assertEquals(expectedResult, telnetHandlerAdapter.telnet(channel, message)); message = "help"; - expectedResult = "Command: help disabled for security reasons, please enable support by listing the commands through 'telnet'\r\ndubbo>"; + expectedResult = + "Command: help disabled for security reasons, please enable support by listing the commands through 'telnet'\r\ndubbo>"; Assertions.assertEquals(expectedResult, telnetHandlerAdapter.telnet(channel, message)); } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/AbstractCodecTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/AbstractCodecTest.java index 973af20a58..7b559f2262 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/AbstractCodecTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/AbstractCodecTest.java @@ -20,12 +20,12 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.buffer.ChannelBuffer; -import org.junit.jupiter.api.Test; -import org.mockito.internal.verification.VerificationModeFactory; - import java.io.IOException; import java.net.InetSocketAddress; +import org.junit.jupiter.api.Test; +import org.mockito.internal.verification.VerificationModeFactory; + import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; @@ -46,10 +46,11 @@ class AbstractCodecTest { try { AbstractCodec.checkPayload(channel, 15 * 1024 * 1024); } catch (IOException expected) { - assertThat(expected.getMessage(), allOf( - containsString("Data length too large: "), - containsString("max payload: " + 8 * 1024 * 1024) - )); + assertThat( + expected.getMessage(), + allOf( + containsString("Data length too large: "), + containsString("max payload: " + 8 * 1024 * 1024))); } verify(channel, VerificationModeFactory.atLeastOnce()).getUrl(); @@ -65,19 +66,19 @@ class AbstractCodecTest { try { AbstractCodec.checkPayload(channel, 1024 * 1024, 1024 * 1024); } catch (IOException expected) { - assertThat(expected.getMessage(), allOf( - containsString("Data length too large: "), - containsString("max payload: " + 1024 * 1024) - )); + assertThat( + expected.getMessage(), + allOf(containsString("Data length too large: "), containsString("max payload: " + 1024 * 1024))); } try { AbstractCodec.checkPayload(channel, 0, 15 * 1024 * 1024); } catch (IOException expected) { - assertThat(expected.getMessage(), allOf( - containsString("Data length too large: "), - containsString("max payload: " + 8 * 1024 * 1024) - )); + assertThat( + expected.getMessage(), + allOf( + containsString("Data length too large: "), + containsString("max payload: " + 8 * 1024 * 1024))); } verify(channel, VerificationModeFactory.atLeastOnce()).getUrl(); @@ -107,15 +108,12 @@ class AbstractCodecTest { given(channel.getUrl()).willReturn(URL.valueOf("dubbo://172.24.157.13:9103")); assertThat(codec.isClientSide(channel), is(false)); assertThat(codec.isServerSide(channel), is(true)); - } private AbstractCodec getAbstractCodec() { AbstractCodec codec = new AbstractCodec() { @Override - public void encode(Channel channel, ChannelBuffer buffer, Object message) { - - } + public void encode(Channel channel, ChannelBuffer buffer, Object message) {} @Override public Object decode(Channel channel, ChannelBuffer buffer) { diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/ChannelHandlerDispatcherTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/ChannelHandlerDispatcherTest.java index 960551f2a6..2e7fdf2838 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/ChannelHandlerDispatcherTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/ChannelHandlerDispatcherTest.java @@ -19,14 +19,15 @@ package org.apache.dubbo.remoting.transport; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; import java.util.Collection; import java.util.Collections; import java.util.HashSet; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + class ChannelHandlerDispatcherTest { @Test @@ -55,7 +56,6 @@ class ChannelHandlerDispatcherTest { channelHandlerDispatcher = channelHandlerDispatcher.removeChannelHandler(channelHandler1); Assertions.assertFalse(channelHandlerDispatcher.getChannelHandlers().contains(channelHandler1)); - } @Test @@ -63,18 +63,23 @@ class ChannelHandlerDispatcherTest { ChannelHandlerDispatcher channelHandlerDispatcher = new ChannelHandlerDispatcher(null, null); Assertions.assertEquals(0, channelHandlerDispatcher.getChannelHandlers().size()); ChannelHandlerDispatcher channelHandlerDispatcher1 = new ChannelHandlerDispatcher((MockChannelHandler) null); - Assertions.assertEquals(0, channelHandlerDispatcher1.getChannelHandlers().size()); - ChannelHandlerDispatcher channelHandlerDispatcher2 = new ChannelHandlerDispatcher(null, new MockChannelHandler()); - Assertions.assertEquals(1, channelHandlerDispatcher2.getChannelHandlers().size()); - ChannelHandlerDispatcher channelHandlerDispatcher3 = new ChannelHandlerDispatcher(Collections.singleton(new MockChannelHandler())); - Assertions.assertEquals(1, channelHandlerDispatcher3.getChannelHandlers().size()); + Assertions.assertEquals( + 0, channelHandlerDispatcher1.getChannelHandlers().size()); + ChannelHandlerDispatcher channelHandlerDispatcher2 = + new ChannelHandlerDispatcher(null, new MockChannelHandler()); + Assertions.assertEquals( + 1, channelHandlerDispatcher2.getChannelHandlers().size()); + ChannelHandlerDispatcher channelHandlerDispatcher3 = + new ChannelHandlerDispatcher(Collections.singleton(new MockChannelHandler())); + Assertions.assertEquals( + 1, channelHandlerDispatcher3.getChannelHandlers().size()); Collection mockChannelHandlers = new HashSet<>(); mockChannelHandlers.add(new MockChannelHandler()); mockChannelHandlers.add(null); ChannelHandlerDispatcher channelHandlerDispatcher4 = new ChannelHandlerDispatcher(mockChannelHandlers); - Assertions.assertEquals(1, channelHandlerDispatcher4.getChannelHandlers().size()); + Assertions.assertEquals( + 1, channelHandlerDispatcher4.getChannelHandlers().size()); } - } class MockChannelHandler extends ChannelHandlerAdapter { diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/CodecSupportTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/CodecSupportTest.java index 5411a608a6..d05c7c6f2a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/CodecSupportTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/CodecSupportTest.java @@ -20,13 +20,12 @@ import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.serialize.support.DefaultSerializationSelector; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; class CodecSupportTest { diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/MultiMessageHandlerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/MultiMessageHandlerTest.java index 5c0e3849f6..f598b40853 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/MultiMessageHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/MultiMessageHandlerTest.java @@ -41,7 +41,8 @@ class MultiMessageHandlerTest { // verify ArgumentCaptor channelArgumentCaptor = ArgumentCaptor.forClass(Channel.class); ArgumentCaptor objectArgumentCaptor = ArgumentCaptor.forClass(Object.class); - Mockito.verify(handler, Mockito.times(2)).received(channelArgumentCaptor.capture(), objectArgumentCaptor.capture()); + Mockito.verify(handler, Mockito.times(2)) + .received(channelArgumentCaptor.capture(), objectArgumentCaptor.capture()); Assertions.assertEquals(objectArgumentCaptor.getAllValues().get(0), "test1"); Assertions.assertEquals(objectArgumentCaptor.getAllValues().get(1), "test2"); Assertions.assertEquals(channelArgumentCaptor.getValue(), channel); @@ -49,7 +50,8 @@ class MultiMessageHandlerTest { Object obj = new Object(); multiMessageHandler.received(channel, obj); // verify - Mockito.verify(handler, Mockito.times(3)).received(channelArgumentCaptor.capture(), objectArgumentCaptor.capture()); + Mockito.verify(handler, Mockito.times(3)) + .received(channelArgumentCaptor.capture(), objectArgumentCaptor.capture()); Assertions.assertEquals(objectArgumentCaptor.getValue(), obj); Assertions.assertEquals(channelArgumentCaptor.getValue(), channel); @@ -58,10 +60,10 @@ class MultiMessageHandlerTest { multiMessageHandler.received(channel, multiMessage); // verify ArgumentCaptor throwableArgumentCaptor = ArgumentCaptor.forClass(Throwable.class); - Mockito.verify(handler, Mockito.times(2)).caught(channelArgumentCaptor.capture(), throwableArgumentCaptor.capture()); + Mockito.verify(handler, Mockito.times(2)) + .caught(channelArgumentCaptor.capture(), throwableArgumentCaptor.capture()); Assertions.assertEquals(throwableArgumentCaptor.getAllValues().get(0), runtimeException); Assertions.assertEquals(throwableArgumentCaptor.getAllValues().get(1), runtimeException); Assertions.assertEquals(channelArgumentCaptor.getValue(), channel); - } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelEventRunnableTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelEventRunnableTest.java index 59641bf20e..3bea230978 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelEventRunnableTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/transport/dispatcher/ChannelEventRunnableTest.java @@ -19,13 +19,13 @@ package org.apache.dubbo.remoting.transport.dispatcher; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; +import java.util.Arrays; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import java.util.Arrays; - /** * {@link ChannelEventRunnable} */ @@ -38,11 +38,16 @@ class ChannelEventRunnableTest { Channel channel = Mockito.mock(Channel.class); ChannelHandler handler = Mockito.mock(ChannelHandler.class); - ChannelEventRunnable connectRunnable = new ChannelEventRunnable(channel, handler, ChannelEventRunnable.ChannelState.CONNECTED); - ChannelEventRunnable disconnectRunnable = new ChannelEventRunnable(channel, handler, ChannelEventRunnable.ChannelState.DISCONNECTED); - ChannelEventRunnable sentRunnable = new ChannelEventRunnable(channel, handler, ChannelEventRunnable.ChannelState.SENT); - ChannelEventRunnable receivedRunnable = new ChannelEventRunnable(channel, handler, ChannelEventRunnable.ChannelState.RECEIVED, ""); - ChannelEventRunnable caughtRunnable = new ChannelEventRunnable(channel, handler, ChannelEventRunnable.ChannelState.CAUGHT, new RuntimeException()); + ChannelEventRunnable connectRunnable = + new ChannelEventRunnable(channel, handler, ChannelEventRunnable.ChannelState.CONNECTED); + ChannelEventRunnable disconnectRunnable = + new ChannelEventRunnable(channel, handler, ChannelEventRunnable.ChannelState.DISCONNECTED); + ChannelEventRunnable sentRunnable = + new ChannelEventRunnable(channel, handler, ChannelEventRunnable.ChannelState.SENT); + ChannelEventRunnable receivedRunnable = + new ChannelEventRunnable(channel, handler, ChannelEventRunnable.ChannelState.RECEIVED, ""); + ChannelEventRunnable caughtRunnable = new ChannelEventRunnable( + channel, handler, ChannelEventRunnable.ChannelState.CAUGHT, new RuntimeException()); connectRunnable.run(); disconnectRunnable.run(); @@ -56,7 +61,9 @@ class ChannelEventRunnableTest { Mockito.verify(handler, Mockito.times(1)).connected(channelArgumentCaptor.capture()); Mockito.verify(handler, Mockito.times(1)).disconnected(channelArgumentCaptor.capture()); Mockito.verify(handler, Mockito.times(1)).sent(channelArgumentCaptor.capture(), Mockito.any()); - Mockito.verify(handler, Mockito.times(1)).received(channelArgumentCaptor.capture(), objectArgumentCaptor.capture()); - Mockito.verify(handler, Mockito.times(1)).caught(channelArgumentCaptor.capture(), throwableArgumentCaptor.capture()); + Mockito.verify(handler, Mockito.times(1)) + .received(channelArgumentCaptor.capture(), objectArgumentCaptor.capture()); + Mockito.verify(handler, Mockito.times(1)) + .caught(channelArgumentCaptor.capture(), throwableArgumentCaptor.capture()); } } diff --git a/dubbo-remoting/dubbo-remoting-http/pom.xml b/dubbo-remoting/dubbo-remoting-http/pom.xml index 5875b1b0d7..e4af576a47 100644 --- a/dubbo-remoting/dubbo-remoting-http/pom.xml +++ b/dubbo-remoting/dubbo-remoting-http/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - org.apache.dubbo - dubbo-remoting - ${revision} - ../pom.xml - - dubbo-remoting-http - jar - ${project.artifactId} - The http remoting module of dubbo project - - false - - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-api - ${project.parent.version} - - - org.eclipse.jetty - jetty-server - - - org.eclipse.jetty - jetty-servlet - - - org.apache.tomcat.embed - tomcat-embed-core - - - org.apache.httpcomponents - fluent-hc - 4.5.14 - test - - - org.slf4j - slf4j-log4j12 - test - + + 4.0.0 + + org.apache.dubbo + dubbo-remoting + ${revision} + ../pom.xml + + dubbo-remoting-http + jar + ${project.artifactId} + The http remoting module of dubbo project + + false + + + + org.apache.dubbo + dubbo-common + ${project.parent.version} + + + org.apache.dubbo + dubbo-remoting-api + ${project.parent.version} + + + org.eclipse.jetty + jetty-server + + + org.eclipse.jetty + jetty-servlet + + + org.apache.tomcat.embed + tomcat-embed-core + + + org.apache.httpcomponents + fluent-hc + 4.5.14 + test + + + org.slf4j + slf4j-log4j12 + test + - - com.squareup.okhttp3 - okhttp - + + com.squareup.okhttp3 + okhttp + - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - + + org.apache.dubbo + dubbo-rpc-api + ${project.parent.version} + - - org.apache.httpcomponents - httpclient - + + org.apache.httpcomponents + httpclient + - + diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/BaseRestClient.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/BaseRestClient.java index d644daf7dd..23c78419ad 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/BaseRestClient.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/BaseRestClient.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.http; - import org.apache.dubbo.remoting.http.config.HttpClientConfig; public abstract class BaseRestClient implements RestClient { @@ -32,7 +31,6 @@ public abstract class BaseRestClient implements RestClient { protected abstract CLIENT createHttpClient(HttpClientConfig clientConfig); - public HttpClientConfig getClientConfig() { return clientConfig; } diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpBinder.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpBinder.java index 338283b482..26db36d92c 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpBinder.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpBinder.java @@ -36,5 +36,4 @@ public interface HttpBinder { */ @Adaptive({Constants.SERVER_KEY}) HttpServer bind(URL url, HttpHandler handler); - } diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpHandler.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpHandler.java index e6e9203c89..27085f67bc 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpHandler.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpHandler.java @@ -31,5 +31,4 @@ public interface HttpHandler { * @throws IOException */ void handle(REQUEST request, RESPONSE response) throws IOException; - } diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpServer.java index 57d5399e10..d85582eb76 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpServer.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpServer.java @@ -68,5 +68,4 @@ public interface HttpServer extends Resetable, RemotingServer { * @return closed */ boolean isClosed(); - } diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/RequestTemplate.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/RequestTemplate.java index 6d19f1636b..d02d63be29 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/RequestTemplate.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/RequestTemplate.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.http; - import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Invocation; @@ -28,7 +27,6 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; - public class RequestTemplate implements Serializable { private static final long serialVersionUID = 1L; public static final String CONTENT_ENCODING = "Content-Encoding"; @@ -49,7 +47,6 @@ public class RequestTemplate implements Serializable { private String contextPath = ""; private Class bodyType; - public RequestTemplate(Invocation invocation, String httpMethod, String address) { this(invocation, httpMethod, address, ""); } @@ -101,10 +98,8 @@ public class RequestTemplate implements Serializable { } return queryBuilder.toString().replace("?&", "?"); - } - public RequestTemplate path(String path) { this.path = path; return this; @@ -132,7 +127,7 @@ public class RequestTemplate implements Serializable { return getUnSerializedBody() == null; } - public RequestTemplate body(Object body,Class bodyType) { + public RequestTemplate body(Object body, Class bodyType) { this.body = body; setBodyType(bodyType); return this; @@ -204,7 +199,6 @@ public class RequestTemplate implements Serializable { header.addAll(values); } - public void addParam(String key, String value) { addValueByKey(key, value, this.queries); } @@ -231,7 +225,6 @@ public class RequestTemplate implements Serializable { params.addAll(values); } - public void addValueByKey(String key, String value, Map> maps) { if (value == null) { @@ -245,12 +238,9 @@ public class RequestTemplate implements Serializable { } values = maps.get(key); - values.add(value); - } - public Integer getContentLength() { if (!getAllHeaders().containsKey(CONTENT_LENGTH)) { @@ -260,16 +250,14 @@ public class RequestTemplate implements Serializable { HashSet strings = (HashSet) getAllHeaders().get(CONTENT_LENGTH); return Integer.parseInt(new ArrayList<>(strings).get(0)); - } - public String getAddress() { return address; } public void setAddress(String address) { - addHeader("Host", address);// must header + addHeader("Host", address); // must header this.address = address; } @@ -281,7 +269,6 @@ public class RequestTemplate implements Serializable { this.protocol = protocol; } - public Invocation getInvocation() { return invocation; } @@ -296,7 +283,6 @@ public class RequestTemplate implements Serializable { } else { return "/" + contextPath; } - } public void setContextPath(String contextPath) { diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/RestClient.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/RestClient.java index f8827dd2d4..e5b8cecf7d 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/RestClient.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/RestClient.java @@ -20,7 +20,6 @@ import org.apache.dubbo.remoting.RemotingException; import java.util.concurrent.CompletableFuture; - public interface RestClient { /** * send message. @@ -46,5 +45,4 @@ public interface RestClient { * @return closed */ boolean isClosed(); - } diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/config/HttpClientConfig.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/config/HttpClientConfig.java index 6e7e49e660..09e0ab92a1 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/config/HttpClientConfig.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/config/HttpClientConfig.java @@ -28,9 +28,7 @@ public class HttpClientConfig { private int HTTP_CLIENT_CONNECTION_MANAGER_CLOSE_WAIT_TIME_MS = 1000; private int HTTP_CLIENT_CONNECTION_MANAGER_CLOSE_IDLE_TIME_S = 30; - - public HttpClientConfig() { - } + public HttpClientConfig() {} public int getReadTimeout() { return readTimeout; diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/AbstractHttpClientFactory.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/AbstractHttpClientFactory.java index 44936b0d37..ad9e7f7821 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/AbstractHttpClientFactory.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/AbstractHttpClientFactory.java @@ -1,19 +1,3 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -46,7 +30,6 @@ public abstract class AbstractHttpClientFactory implements RestClientFactory { protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); - // TODO load config protected HttpClientConfig httpClientConfig = new HttpClientConfig(); @@ -67,21 +50,14 @@ public abstract class AbstractHttpClientFactory implements RestClientFactory { //////////////////////////////////////// implements end /////////////////////////////////////////////// - //////////////////////////////////////// inner methods /////////////////////////////////////////////// - protected void beforeCreated(URL url) { - } + protected void beforeCreated(URL url) {} protected abstract RestClient doCreateRestClient(URL url) throws RpcException; - protected void afterCreated(RestClient client) { - } + protected void afterCreated(RestClient client) {} //////////////////////////////////////// inner methods /////////////////////////////////////////////// - - - - } diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/RestClientFactory.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/RestClientFactory.java index ca82b052e5..c64453dbda 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/RestClientFactory.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/RestClientFactory.java @@ -30,9 +30,6 @@ import org.apache.dubbo.rpc.RpcException; @SPI(value = Constants.OK_HTTP, scope = ExtensionScope.FRAMEWORK) public interface RestClientFactory { - @Adaptive({Constants.CLIENT_KEY}) RestClient createRestClient(URL url) throws RpcException; - - } diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/ApacheHttpClientFactory.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/ApacheHttpClientFactory.java index 08fef6f4ea..89d9c36f6f 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/ApacheHttpClientFactory.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/ApacheHttpClientFactory.java @@ -27,11 +27,9 @@ import org.apache.dubbo.rpc.RpcException; @Activate(Constants.APACHE_HTTP_CLIENT) public class ApacheHttpClientFactory extends AbstractHttpClientFactory { - @Override protected RestClient doCreateRestClient(URL url) throws RpcException { - return new HttpClientRestClient(httpClientConfig); } } diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/OkHttpClientFactory.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/OkHttpClientFactory.java index 87e154c76a..523df3caf8 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/OkHttpClientFactory.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/OkHttpClientFactory.java @@ -27,7 +27,6 @@ import org.apache.dubbo.rpc.RpcException; @Activate(Constants.OK_HTTP) public class OkHttpClientFactory extends AbstractHttpClientFactory { - @Override protected RestClient doCreateRestClient(URL url) throws RpcException { diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/URLConnectionClientFactory.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/URLConnectionClientFactory.java index 94676a091d..40c2a82a66 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/URLConnectionClientFactory.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/URLConnectionClientFactory.java @@ -27,7 +27,6 @@ import org.apache.dubbo.rpc.RpcException; @Activate(Constants.URL_CONNECTION) public class URLConnectionClientFactory extends AbstractHttpClientFactory { - @Override protected RestClient doCreateRestClient(URL url) throws RpcException { diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinder.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinder.java index 9a41285684..05e5dc5a35 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinder.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinder.java @@ -30,5 +30,4 @@ public class JettyHttpBinder implements HttpBinder { public HttpServer bind(URL url, HttpHandler handler) { return new JettyHttpServer(url, handler); } - } diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java index cba4f9fa00..0139a5d79f 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java @@ -81,13 +81,17 @@ public class JettyHttpServer extends AbstractHttpServer { // TODO Context.SESSIONS is the best option here? (In jetty 9.x, it becomes ServletContextHandler.SESSIONS) ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS); context.setServletHandler(servletHandler); - ServletManager.getInstance().addServletContext(url.getParameter(Constants.BIND_PORT_KEY, url.getPort()), context.getServletContext()); + ServletManager.getInstance() + .addServletContext( + url.getParameter(Constants.BIND_PORT_KEY, url.getPort()), context.getServletContext()); try { server.start(); } catch (Exception e) { - throw new IllegalStateException("Failed to start jetty server on " + url.getParameter(Constants.BIND_IP_KEY) + ":" + url.getParameter(Constants.BIND_PORT_KEY) + ", cause: " - + e.getMessage(), e); + throw new IllegalStateException( + "Failed to start jetty server on " + url.getParameter(Constants.BIND_IP_KEY) + ":" + + url.getParameter(Constants.BIND_PORT_KEY) + ", cause: " + e.getMessage(), + e); } } @@ -106,5 +110,4 @@ public class JettyHttpServer extends AbstractHttpServer { } } } - } diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/HttpClientRestClient.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/HttpClientRestClient.java index f8f85411af..f09b288c5f 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/HttpClientRestClient.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/HttpClientRestClient.java @@ -21,6 +21,15 @@ import org.apache.dubbo.remoting.http.RestClient; import org.apache.dubbo.remoting.http.RestResult; import org.apache.dubbo.remoting.http.config.HttpClientConfig; +import java.io.IOException; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Collectors; + import org.apache.commons.io.IOUtils; import org.apache.http.Header; import org.apache.http.HttpEntityEnclosingRequest; @@ -41,16 +50,6 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.stream.Collectors; - - public class HttpClientRestClient implements RestClient { private final CloseableHttpClient closeableHttpClient; private final HttpClientConfig httpClientConfig; @@ -69,10 +68,10 @@ public class HttpClientRestClient implements RestClient { httpRequest = createHttpUriRequest(httpMethod, requestTemplate); if (httpRequest instanceof HttpEntityEnclosingRequest) { - ((HttpEntityEnclosingRequestBase) httpRequest).setEntity(new ByteArrayEntity(requestTemplate.getSerializedBody())); + ((HttpEntityEnclosingRequestBase) httpRequest) + .setEntity(new ByteArrayEntity(requestTemplate.getSerializedBody())); } - Map> allHeaders = requestTemplate.getAllHeaders(); allHeaders.remove("Content-Length"); @@ -107,7 +106,8 @@ public class HttpClientRestClient implements RestClient { @Override public Map> headers() { - return Arrays.stream(response.getAllHeaders()).collect(Collectors.toMap(Header::getName, h -> Collections.singletonList(h.getValue()))); + return Arrays.stream(response.getAllHeaders()) + .collect(Collectors.toMap(Header::getName, h -> Collections.singletonList(h.getValue()))); } @Override @@ -122,8 +122,8 @@ public class HttpClientRestClient implements RestClient { @Override public String getMessage() throws IOException { - return appendErrorMessage(response.getStatusLine().getReasonPhrase(), - new String(getErrorResponse())); + return appendErrorMessage( + response.getStatusLine().getReasonPhrase(), new String(getErrorResponse())); } }); } catch (IOException e) { @@ -148,9 +148,7 @@ public class HttpClientRestClient implements RestClient { } @Override - public void close(int timeout) { - - } + public void close(int timeout) {} @Override public boolean isClosed() { @@ -186,7 +184,5 @@ public class HttpClientRestClient implements RestClient { throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod); } return httpUriRequest; - } - } diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/OKHttpRestClient.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/OKHttpRestClient.java index 461d2bcd62..36ba2e6d18 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/OKHttpRestClient.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/OKHttpRestClient.java @@ -21,6 +21,13 @@ import org.apache.dubbo.remoting.http.RestClient; import org.apache.dubbo.remoting.http.RestResult; import org.apache.dubbo.remoting.http.config.HttpClientConfig; +import java.io.IOException; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; @@ -30,13 +37,6 @@ import okhttp3.Response; import okhttp3.ResponseBody; import okhttp3.internal.http.HttpMethod; -import java.io.IOException; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.TimeUnit; - // TODO add version 4.0 implements ,and default version is < 4.0,for dependency conflict public class OKHttpRestClient implements RestClient { private final OkHttpClient okHttpClient; @@ -132,9 +132,7 @@ public class OKHttpRestClient implements RestClient { } @Override - public void close(int timeout) { - - } + public void close(int timeout) {} @Override public boolean isClosed() { @@ -142,11 +140,11 @@ public class OKHttpRestClient implements RestClient { } public OkHttpClient createHttpClient(HttpClientConfig httpClientConfig) { - OkHttpClient client = new OkHttpClient.Builder(). - readTimeout(httpClientConfig.getReadTimeout(), TimeUnit.SECONDS). - writeTimeout(httpClientConfig.getWriteTimeout(), TimeUnit.SECONDS). - connectTimeout(httpClientConfig.getConnectTimeout(), TimeUnit.SECONDS). - build(); + OkHttpClient client = new OkHttpClient.Builder() + .readTimeout(httpClientConfig.getReadTimeout(), TimeUnit.SECONDS) + .writeTimeout(httpClientConfig.getWriteTimeout(), TimeUnit.SECONDS) + .connectTimeout(httpClientConfig.getConnectTimeout(), TimeUnit.SECONDS) + .build(); return client; } } diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/URLConnectionRestClient.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/URLConnectionRestClient.java index 960912c0ea..65f20a19f2 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/URLConnectionRestClient.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/URLConnectionRestClient.java @@ -21,8 +21,6 @@ import org.apache.dubbo.remoting.http.RestClient; import org.apache.dubbo.remoting.http.RestResult; import org.apache.dubbo.remoting.http.config.HttpClientConfig; -import org.apache.commons.io.IOUtils; - import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; @@ -33,6 +31,7 @@ import java.util.concurrent.CompletableFuture; import java.util.zip.DeflaterOutputStream; import java.util.zip.GZIPOutputStream; +import org.apache.commons.io.IOUtils; public class URLConnectionRestClient implements RestClient { private final HttpClientConfig clientConfig; @@ -62,7 +61,6 @@ public class URLConnectionRestClient implements RestClient { } } - // writeBody boolean gzipEncodedRequest = requestTemplate.isGzipEncodedRequest(); @@ -103,21 +101,16 @@ public class URLConnectionRestClient implements RestClient { } @Override - public void close() { - - } + public void close() {} @Override - public void close(int timeout) { - - } + public void close(int timeout) {} @Override public boolean isClosed() { return true; } - private RestResult getRestResultFromConnection(HttpURLConnection connection) { return new RestResult() { @@ -149,14 +142,12 @@ public class URLConnectionRestClient implements RestClient { @Override public String getMessage() throws IOException { return appendErrorMessage(connection.getResponseMessage(), new String(getErrorResponse())); - } }; } private void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { - connection.setDoInput(true); if ("GET".equals(httpMethod)) { @@ -165,9 +156,10 @@ public class URLConnectionRestClient implements RestClient { connection.setInstanceFollowRedirects(false); } - - if ("POST".equals(httpMethod) || "PUT".equals(httpMethod) || - "PATCH".equals(httpMethod) || "DELETE".equals(httpMethod)) { + if ("POST".equals(httpMethod) + || "PUT".equals(httpMethod) + || "PATCH".equals(httpMethod) + || "DELETE".equals(httpMethod)) { connection.setDoOutput(true); } else { connection.setDoOutput(false); @@ -175,5 +167,4 @@ public class URLConnectionRestClient implements RestClient { connection.setRequestMethod(httpMethod); } - } diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/BootstrapListener.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/BootstrapListener.java index 94554ba56f..0a902f292f 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/BootstrapListener.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/BootstrapListener.java @@ -26,7 +26,8 @@ public class BootstrapListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { - ServletManager.getInstance().addServletContext(ServletManager.EXTERNAL_SERVER_PORT, servletContextEvent.getServletContext()); + ServletManager.getInstance() + .addServletContext(ServletManager.EXTERNAL_SERVER_PORT, servletContextEvent.getServletContext()); } @Override diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/DispatcherServlet.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/DispatcherServlet.java index 3500f05e0f..ced2170b3b 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/DispatcherServlet.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/DispatcherServlet.java @@ -22,6 +22,7 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -55,11 +56,10 @@ public class DispatcherServlet extends HttpServlet { protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpHandler handler = HANDLERS.get(request.getLocalPort()); - if (handler == null) {// service not found. + if (handler == null) { // service not found. response.sendError(HttpServletResponse.SC_NOT_FOUND, "Service not found."); } else { handler.handle(request, response); } } - } diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpBinder.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpBinder.java index 447ea4e6ed..33aecc5aff 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpBinder.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpBinder.java @@ -30,5 +30,4 @@ public class ServletHttpBinder implements HttpBinder { public HttpServer bind(URL url, HttpHandler handler) { return new ServletHttpServer(url, handler); } - } diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpServer.java index 29e02d2208..bf0b01457e 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpServer.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpServer.java @@ -27,5 +27,4 @@ public class ServletHttpServer extends AbstractHttpServer { super(url, handler); DispatcherServlet.addHttpHandler(url.getParameter(Constants.BIND_PORT_KEY, 8080), handler); } - } diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletManager.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletManager.java index e81fae23c6..a261b6e54c 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletManager.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletManager.java @@ -17,6 +17,7 @@ package org.apache.dubbo.remoting.http.servlet; import javax.servlet.ServletContext; + import java.util.Map; import java.util.concurrent.ConcurrentHashMap; diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/support/AbstractHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/support/AbstractHttpServer.java index 437ac0d36d..cc01b1e064 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/support/AbstractHttpServer.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/support/AbstractHttpServer.java @@ -60,8 +60,7 @@ public abstract class AbstractHttpServer implements HttpServer { } @Override - public void reset(URL url) { - } + public void reset(URL url) {} @Override public boolean isBound() { @@ -91,7 +90,6 @@ public abstract class AbstractHttpServer implements HttpServer { /** * Following methods are extended from RemotingServer, useless for http servers */ - @Override public boolean canHandleIdle() { return false; @@ -108,9 +106,7 @@ public abstract class AbstractHttpServer implements HttpServer { } @Override - public void reset(Parameters parameters) { - - } + public void reset(Parameters parameters) {} @Override public ChannelHandler getChannelHandler() { @@ -118,17 +114,11 @@ public abstract class AbstractHttpServer implements HttpServer { } @Override - public void send(Object message) throws RemotingException { - - } + public void send(Object message) throws RemotingException {} @Override - public void send(Object message, boolean sent) throws RemotingException { - - } + public void send(Object message, boolean sent) throws RemotingException {} @Override - public void startClose() { - - } + public void startClose() {} } diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinder.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinder.java index 4e4a74bb7e..92b4bf1c70 100755 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinder.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinder.java @@ -27,5 +27,4 @@ public class TomcatHttpBinder implements HttpBinder { public HttpServer bind(URL url, HttpHandler handler) { return new TomcatHttpServer(url, handler); } - } diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java index dfbba2948e..3d73fcadb1 100755 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java @@ -24,13 +24,13 @@ import org.apache.dubbo.remoting.http.servlet.DispatcherServlet; import org.apache.dubbo.remoting.http.servlet.ServletManager; import org.apache.dubbo.remoting.http.support.AbstractHttpServer; +import java.io.File; + import org.apache.catalina.Context; import org.apache.catalina.LifecycleException; import org.apache.catalina.connector.Connector; import org.apache.catalina.startup.Tomcat; -import java.io.File; - import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_STOP_HTTP_SERVER; diff --git a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinderTest.java b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinderTest.java index a00fbcd9c2..04fc431863 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinderTest.java +++ b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinderTest.java @@ -23,13 +23,14 @@ import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.HttpServer; -import org.apache.http.client.fluent.Request; -import org.junit.jupiter.api.Test; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import java.io.IOException; +import org.apache.http.client.fluent.Request; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; @@ -37,16 +38,17 @@ class JettyHttpBinderTest { @Test void shouldAbleHandleRequestForJettyBinder() throws Exception { int port = NetUtils.getAvailablePort(); - URL url = new ServiceConfigURL("http", "localhost", port, - new String[]{Constants.BIND_PORT_KEY, String.valueOf(port)}); - HttpServer httpServer = new JettyHttpServer(url, new HttpHandler() { + URL url = new ServiceConfigURL( + "http", "localhost", port, new String[] {Constants.BIND_PORT_KEY, String.valueOf(port)}); + HttpServer httpServer = new JettyHttpServer(url, new HttpHandler() { @Override public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { response.getWriter().write("Jetty"); } }); - String response = Request.Get(url.toJavaURL().toURI()).execute().returnContent().asString(); + String response = + Request.Get(url.toJavaURL().toURI()).execute().returnContent().asString(); assertThat(response, is("Jetty")); diff --git a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyLoggerAdapterTest.java b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyLoggerAdapterTest.java index f2de8ccdef..e4cbbfd539 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyLoggerAdapterTest.java +++ b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyLoggerAdapterTest.java @@ -25,16 +25,17 @@ import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.HttpServer; -import org.apache.http.client.fluent.Request; -import org.eclipse.jetty.util.log.Log; -import org.junit.jupiter.api.Test; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; +import org.apache.http.client.fluent.Request; +import org.eclipse.jetty.util.log.Log; +import org.junit.jupiter.api.Test; + import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.anyString; @@ -45,11 +46,11 @@ import static org.mockito.Mockito.when; class JettyLoggerAdapterTest { @Test - void testJettyUseDubboLogger() throws Exception{ + void testJettyUseDubboLogger() throws Exception { int port = NetUtils.getAvailablePort(); - URL url = new ServiceConfigURL("http", "localhost", port, - new String[]{Constants.BIND_PORT_KEY, String.valueOf(port)}); - HttpServer httpServer = new JettyHttpServer(url, new HttpHandler() { + URL url = new ServiceConfigURL( + "http", "localhost", port, new String[] {Constants.BIND_PORT_KEY, String.valueOf(port)}); + HttpServer httpServer = new JettyHttpServer(url, new HttpHandler() { @Override public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { response.getWriter().write("Jetty is using Dubbo's logger"); @@ -62,12 +63,12 @@ class JettyLoggerAdapterTest { httpServer.close(); } - @Test - void testSuccessLogger() throws Exception{ + void testSuccessLogger() throws Exception { Logger successLogger = mock(Logger.class); Class clazz = Class.forName("org.apache.dubbo.remoting.http.jetty.JettyLoggerAdapter"); - JettyLoggerAdapter jettyLoggerAdapter = (JettyLoggerAdapter) clazz.getDeclaredConstructor().newInstance(); + JettyLoggerAdapter jettyLoggerAdapter = + (JettyLoggerAdapter) clazz.getDeclaredConstructor().newInstance(); Field loggerField = clazz.getDeclaredField("logger"); loggerField.setAccessible(true); @@ -96,32 +97,30 @@ class JettyLoggerAdapterTest { jettyLoggerAdapter.debug("debug", new Exception("debug")); } - @Test - void testNewLogger(){ + void testNewLogger() { JettyLoggerAdapter loggerAdapter = new JettyLoggerAdapter(); - org.eclipse.jetty.util.log.Logger logger = loggerAdapter.newLogger(this.getClass().getName()); + org.eclipse.jetty.util.log.Logger logger = + loggerAdapter.newLogger(this.getClass().getName()); assertThat(logger.getClass().isAssignableFrom(JettyLoggerAdapter.class), is(true)); } - @Test - void testDebugEnabled(){ + void testDebugEnabled() { JettyLoggerAdapter loggerAdapter = new JettyLoggerAdapter(); loggerAdapter.setDebugEnabled(true); assertThat(loggerAdapter.isDebugEnabled(), is(true)); } - @Test - void testLoggerFormat() throws Exception{ + void testLoggerFormat() throws Exception { Class clazz = Class.forName("org.apache.dubbo.remoting.http.jetty.JettyLoggerAdapter"); Object newInstance = clazz.getDeclaredConstructor().newInstance(); Method method = clazz.getDeclaredMethod("format", String.class, Object[].class); method.setAccessible(true); - String print = (String) method.invoke(newInstance, "Hello,{}! I'am {}", new String[]{"World","Jetty"}); + String print = (String) method.invoke(newInstance, "Hello,{}! I'am {}", new String[] {"World", "Jetty"}); assertThat(print, is("Hello,World! I'am Jetty")); } diff --git a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/rest/RestClientTest.java b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/rest/RestClientTest.java index 04b4489b5b..3f1491e94b 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/rest/RestClientTest.java +++ b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/rest/RestClientTest.java @@ -26,11 +26,10 @@ import org.apache.dubbo.remoting.http.jetty.JettyHttpServer; import org.apache.dubbo.remoting.http.restclient.HttpClientRestClient; import org.apache.dubbo.remoting.http.restclient.OKHttpRestClient; import org.apache.dubbo.remoting.http.restclient.URLConnectionRestClient; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Arrays; @@ -38,6 +37,9 @@ import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; @@ -46,8 +48,8 @@ public class RestClientTest { @Test public void testRestClient() throws Exception { int port = NetUtils.getAvailablePort(); - URL url = new ServiceConfigURL("http", "localhost", port, - new String[]{Constants.BIND_PORT_KEY, String.valueOf(port)}); + URL url = new ServiceConfigURL( + "http", "localhost", port, new String[] {Constants.BIND_PORT_KEY, String.valueOf(port)}); HttpServer httpServer = new JettyHttpServer(url, new HttpHandler() { @Override public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { @@ -75,10 +77,8 @@ public class RestClientTest { RestResult restResult = send.get(); - assertThat(new String(restResult.getBody()), is("Jetty")); - restClient = new HttpClientRestClient(new HttpClientConfig()); send = restClient.send(requestTemplate); @@ -98,12 +98,11 @@ public class RestClientTest { httpServer.close(); } - @Test public void testError() throws Exception { int port = NetUtils.getAvailablePort(); - URL url = new ServiceConfigURL("http", "localhost", port, - new String[]{Constants.BIND_PORT_KEY, String.valueOf(port)}); + URL url = new ServiceConfigURL( + "http", "localhost", port, new String[] {Constants.BIND_PORT_KEY, String.valueOf(port)}); HttpServer httpServer = new JettyHttpServer(url, new HttpHandler() { @Override public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { @@ -126,8 +125,7 @@ public class RestClientTest { CompletableFuture send = restClient.send(requestTemplate); - String error = "Server Error\n" + - " error info is: server error"; + String error = "Server Error\n" + " error info is: server error"; RestResult restResult = send.get(); String contentType = "text/html;charset=iso-8859-1"; @@ -143,14 +141,12 @@ public class RestClientTest { send = restClient.send(requestTemplate); restResult = send.get(); - Assertions.assertEquals(500, restResult.getResponseCode()); Assertions.assertEquals(error, restResult.getMessage()); Assertions.assertEquals(contentType, restResult.getContentType()); restClient.close(); - restClient = new URLConnectionRestClient(new HttpClientConfig()); send = restClient.send(requestTemplate); restResult = send.get(); @@ -160,7 +156,6 @@ public class RestClientTest { Assertions.assertEquals(contentType, restResult.getContentType()); restClient.close(); - httpServer.close(); } @@ -171,29 +166,28 @@ public class RestClientTest { requestTemplate.body(new Object(), Object.class); - Assertions.assertEquals(requestTemplate.getBodyType(),Object.class); + Assertions.assertEquals(requestTemplate.getBodyType(), Object.class); - - requestTemplate.addHeader("Content-Length",1); + requestTemplate.addHeader("Content-Length", 1); Integer contentLength = requestTemplate.getContentLength(); - Assertions.assertEquals(1,contentLength); + Assertions.assertEquals(1, contentLength); List strings = Arrays.asList("h1", "h2"); - requestTemplate.addHeaders("header",strings); + requestTemplate.addHeaders("header", strings); + Assertions.assertArrayEquals( + strings.toArray(new String[0]), + requestTemplate.getHeaders("header").toArray(new String[0])); - Assertions.assertArrayEquals(strings.toArray(new String[0]),requestTemplate.getHeaders("header").toArray(new String[0])); - - strings = Arrays.asList("p1", "p2"); - - requestTemplate.addParams("param",strings); - - Assertions.assertArrayEquals(strings.toArray(new String[0]),requestTemplate.getParam("param").toArray(new String[0])); - + strings = Arrays.asList("p1", "p2"); + requestTemplate.addParams("param", strings); + Assertions.assertArrayEquals( + strings.toArray(new String[0]), + requestTemplate.getParam("param").toArray(new String[0])); } } diff --git a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinderTest.java b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinderTest.java index ac100eef3f..75efc28b41 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinderTest.java +++ b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinderTest.java @@ -23,13 +23,14 @@ import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.HttpServer; -import org.apache.http.client.fluent.Request; -import org.junit.jupiter.api.Test; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import java.io.IOException; +import org.apache.http.client.fluent.Request; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; @@ -37,17 +38,19 @@ class TomcatHttpBinderTest { @Test void shouldAbleHandleRequestForTomcatBinder() throws Exception { int port = NetUtils.getAvailablePort(); - URL url = new ServiceConfigURL("http", "localhost", port, - new String[]{Constants.BIND_PORT_KEY, String.valueOf(port)}); + URL url = new ServiceConfigURL( + "http", "localhost", port, new String[] {Constants.BIND_PORT_KEY, String.valueOf(port)}); - HttpServer httpServer = new TomcatHttpBinder().bind(url, new HttpHandler() { - @Override - public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { - response.getWriter().write("Tomcat"); - } - }); + HttpServer httpServer = new TomcatHttpBinder() + .bind(url, new HttpHandler() { + @Override + public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { + response.getWriter().write("Tomcat"); + } + }); - String response = Request.Get(url.toJavaURL().toURI()).execute().returnContent().asString(); + String response = + Request.Get(url.toJavaURL().toURI()).execute().returnContent().asString(); assertThat(response, is("Tomcat")); diff --git a/dubbo-remoting/dubbo-remoting-http12/pom.xml b/dubbo-remoting/dubbo-remoting-http12/pom.xml index ad702991e9..a59990aaae 100644 --- a/dubbo-remoting/dubbo-remoting-http12/pom.xml +++ b/dubbo-remoting/dubbo-remoting-http12/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - org.apache.dubbo - dubbo-remoting - ${revision} - ../pom.xml - - dubbo-remoting-http12 - jar - ${project.artifactId} - The http1/2 remoting module of dubbo project - - false - - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-api - ${project.parent.version} - - - com.google.protobuf - protobuf-java-util - + + 4.0.0 + + org.apache.dubbo + dubbo-remoting + ${revision} + ../pom.xml + + dubbo-remoting-http12 + jar + ${project.artifactId} + The http1/2 remoting module of dubbo project + + false + + + + org.apache.dubbo + dubbo-rpc-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-common + ${project.parent.version} + + + org.apache.dubbo + dubbo-remoting-api + ${project.parent.version} + + + com.google.protobuf + protobuf-java-util + - - io.netty - netty-transport - - - io.netty - netty-codec-http2 - + + io.netty + netty-transport + + + io.netty + netty-codec-http2 + - - + diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/AbstractServerHttpChannelObserver.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/AbstractServerHttpChannelObserver.java index adc23ec718..65aaa6cd38 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/AbstractServerHttpChannelObserver.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/AbstractServerHttpChannelObserver.java @@ -85,13 +85,9 @@ public abstract class AbstractServerHttpChannelObserver implements CustomizableH } } - protected void preOutputMessage(HttpOutputMessage outputMessage) throws Throwable { + protected void preOutputMessage(HttpOutputMessage outputMessage) throws Throwable {} - } - - protected void postOutputMessage(HttpOutputMessage outputMessage) throws Throwable { - - } + protected void postOutputMessage(HttpOutputMessage outputMessage) throws Throwable {} protected abstract HttpMetadata encodeHttpMetadata(); @@ -140,7 +136,11 @@ public abstract class AbstractServerHttpChannelObserver implements CustomizableH private void doSendHeaders(String statusCode) { HttpMetadata httpMetadata = encodeHttpMetadata(); httpMetadata.headers().set(HttpHeaderNames.STATUS.getName(), statusCode); - httpMetadata.headers().set(HttpHeaderNames.CONTENT_TYPE.getName(), httpMessageCodec.contentType().getName()); + httpMetadata + .headers() + .set( + HttpHeaderNames.CONTENT_TYPE.getName(), + httpMessageCodec.contentType().getName()); this.headersCustomizer.accept(httpMetadata.headers()); getHttpChannel().writeHeader(httpMetadata); this.headerSent = true; @@ -154,5 +154,4 @@ public abstract class AbstractServerHttpChannelObserver implements CustomizableH this.trailersCustomizer.accept(httpMetadata.headers(), throwable); getHttpChannel().writeHeader(httpMetadata); } - } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/CustomizableHttpChannelObserver.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/CustomizableHttpChannelObserver.java index e43e8d9b49..ceda7cdbce 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/CustomizableHttpChannelObserver.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/CustomizableHttpChannelObserver.java @@ -23,5 +23,4 @@ public interface CustomizableHttpChannelObserver extends HttpChannelObserver< void setTrailersCustomizer(TrailersCustomizer trailersCustomizer); void setErrorResponseCustomizer(ErrorResponseCustomizer errorResponseCustomizer); - } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/ErrorCodeHolder.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/ErrorCodeHolder.java index fa7361aa9c..19226b936c 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/ErrorCodeHolder.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/ErrorCodeHolder.java @@ -19,5 +19,4 @@ package org.apache.dubbo.remoting.http12; public interface ErrorCodeHolder { long getErrorCode(); - } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/ErrorResponseCustomizer.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/ErrorResponseCustomizer.java index 1d9a21c9fc..0c61f3be37 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/ErrorResponseCustomizer.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/ErrorResponseCustomizer.java @@ -21,6 +21,5 @@ import java.util.function.BiConsumer; @FunctionalInterface public interface ErrorResponseCustomizer extends BiConsumer { - ErrorResponseCustomizer NO_OP = (errorResponse, throwable) -> { - }; + ErrorResponseCustomizer NO_OP = (errorResponse, throwable) -> {}; } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/FlowControlStreamObserver.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/FlowControlStreamObserver.java index 92bfd38e1e..0c166045ef 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/FlowControlStreamObserver.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/FlowControlStreamObserver.java @@ -39,5 +39,4 @@ public interface FlowControlStreamObserver extends StreamObserver { * specified. */ void disableAutoFlowControl(); - } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HeadersCustomizer.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HeadersCustomizer.java index a94823dd5d..5ccd9e6d9c 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HeadersCustomizer.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HeadersCustomizer.java @@ -21,6 +21,5 @@ import java.util.function.Consumer; @FunctionalInterface public interface HeadersCustomizer extends Consumer { - HeadersCustomizer NO_OP = headers -> { - }; + HeadersCustomizer NO_OP = headers -> {}; } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpChannel.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpChannel.java index 8b9a9f2a2f..795bf8ee37 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpChannel.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpChannel.java @@ -30,5 +30,4 @@ public interface HttpChannel { SocketAddress remoteAddress(); void flush(); - } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpChannelObserver.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpChannelObserver.java index 12b51b44e5..4cb0342642 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpChannelObserver.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpChannelObserver.java @@ -21,5 +21,4 @@ import org.apache.dubbo.common.stream.StreamObserver; public interface HttpChannelObserver extends StreamObserver { HttpChannel getHttpChannel(); - } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpHeaderNames.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpHeaderNames.java index cdbf64fa58..632dc0cdd0 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpHeaderNames.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpHeaderNames.java @@ -17,7 +17,6 @@ package org.apache.dubbo.remoting.http12; public enum HttpHeaderNames { - STATUS(":status"), CONTENT_TYPE("content-type"), diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpHeaders.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpHeaders.java index 9f6ddf8848..24407ad9f2 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpHeaders.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpHeaders.java @@ -52,7 +52,6 @@ public class HttpHeaders implements Map>, Serializable, Clo this.locale = Locale.US; } - // Implementation of java.util.Map @Override @@ -101,7 +100,6 @@ public class HttpHeaders implements Map>, Serializable, Clo } @Override - public List getOrDefault(Object key, List defaultValue) { if (key instanceof String) { String caseInsensitiveKey = this.caseInsensitiveKeys.get(convertKey((String) key)); @@ -132,7 +130,6 @@ public class HttpHeaders implements Map>, Serializable, Clo } @Override - public List putIfAbsent(String key, List value) { String oldKey = this.caseInsensitiveKeys.putIfAbsent(convertKey(key), key); if (oldKey != null) { @@ -147,7 +144,6 @@ public class HttpHeaders implements Map>, Serializable, Clo } @Override - public List computeIfAbsent(String key, Function> mappingFunction) { String oldKey = this.caseInsensitiveKeys.putIfAbsent(convertKey(key), key); if (oldKey != null) { @@ -162,7 +158,6 @@ public class HttpHeaders implements Map>, Serializable, Clo } @Override - public List remove(Object key) { if (key instanceof String) { String caseInsensitiveKey = removeCaseInsensitiveKey((String) key); @@ -232,7 +227,6 @@ public class HttpHeaders implements Map>, Serializable, Clo return this.targetMap.toString(); } - public Locale getLocale() { return this.locale; } @@ -245,12 +239,10 @@ public class HttpHeaders implements Map>, Serializable, Clo return false; } - private String removeCaseInsensitiveKey(String key) { return this.caseInsensitiveKeys.remove(convertKey(key)); } - private class KeySet extends AbstractSet { private final Set delegate; @@ -295,7 +287,6 @@ public class HttpHeaders implements Map>, Serializable, Clo } } - private class Values extends AbstractCollection> { private final Collection> delegate; @@ -335,7 +326,6 @@ public class HttpHeaders implements Map>, Serializable, Clo } } - private class EntrySet extends AbstractSet>> { private final Set>> delegate; @@ -386,12 +376,10 @@ public class HttpHeaders implements Map>, Serializable, Clo } } - private abstract class EntryIterator implements Iterator { private final Iterator>> delegate; - private Entry> last; public EntryIterator() { @@ -419,7 +407,6 @@ public class HttpHeaders implements Map>, Serializable, Clo } } - private class KeySetIterator extends EntryIterator { @Override @@ -428,7 +415,6 @@ public class HttpHeaders implements Map>, Serializable, Clo } } - private class ValuesIterator extends EntryIterator> { @Override @@ -437,7 +423,6 @@ public class HttpHeaders implements Map>, Serializable, Clo } } - private class EntrySetIterator extends EntryIterator>> { @Override @@ -445,5 +430,4 @@ public class HttpHeaders implements Map>, Serializable, Clo return nextEntry(); } } - } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpInputMessage.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpInputMessage.java index b80833764a..60d6a4dec7 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpInputMessage.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpInputMessage.java @@ -21,5 +21,4 @@ import java.io.InputStream; public interface HttpInputMessage { InputStream getBody(); - } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpMetadata.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpMetadata.java index c1fce4a759..dabecb607f 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpMetadata.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpMetadata.java @@ -19,5 +19,4 @@ package org.apache.dubbo.remoting.http12; public interface HttpMetadata { HttpHeaders headers(); - } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpOutputMessage.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpOutputMessage.java index ff8210ab4c..e56630430c 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpOutputMessage.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpOutputMessage.java @@ -32,5 +32,4 @@ public interface HttpOutputMessage { }; OutputStream getBody(); - } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpStatus.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpStatus.java index 675737f2df..a5c2e2c933 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpStatus.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpStatus.java @@ -17,7 +17,6 @@ package org.apache.dubbo.remoting.http12; public enum HttpStatus { - OK(200), REQUEST_TIMEOUT(408), UNSUPPORTED_MEDIA_TYPE(415), diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpTransportListener.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpTransportListener.java index e478a45f21..9265a3ba93 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpTransportListener.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpTransportListener.java @@ -21,5 +21,4 @@ public interface HttpTransportListener
    , HeadersCustomizer { - TrailersCustomizer NO_OP = (headers, throwable) -> { - }; + TrailersCustomizer NO_OP = (headers, throwable) -> {}; @Override default void accept(HttpHeaders headers) { diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/command/DataQueueCommand.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/command/DataQueueCommand.java index 8594dcb011..d01e585623 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/command/DataQueueCommand.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/command/DataQueueCommand.java @@ -28,13 +28,12 @@ public class DataQueueCommand extends HttpChannelQueueCommand { @Override public void run() { - getHttpChannel().writeMessage(httpOutputMessage) - .whenComplete((unused, throwable) -> { - if (throwable != null) { - completeExceptionally(throwable); - } else { - complete(unused); - } - }); + getHttpChannel().writeMessage(httpOutputMessage).whenComplete((unused, throwable) -> { + if (throwable != null) { + completeExceptionally(throwable); + } else { + complete(unused); + } + }); } } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/command/HeaderQueueCommand.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/command/HeaderQueueCommand.java index 8464260cf9..cf286bc6c2 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/command/HeaderQueueCommand.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/command/HeaderQueueCommand.java @@ -28,8 +28,7 @@ public class HeaderQueueCommand extends HttpChannelQueueCommand { @Override public void run() { - getHttpChannel().writeHeader(httpMetadata) - .whenComplete((unused, throwable) -> { + getHttpChannel().writeHeader(httpMetadata).whenComplete((unused, throwable) -> { if (throwable != null) { completeExceptionally(throwable); } else { diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/command/HttpChannelQueueCommand.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/command/HttpChannelQueueCommand.java index 0d327d1282..6474dd8143 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/command/HttpChannelQueueCommand.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/command/HttpChannelQueueCommand.java @@ -21,7 +21,8 @@ import org.apache.dubbo.remoting.http12.HttpChannelHolder; import java.util.concurrent.CompletableFuture; -public abstract class HttpChannelQueueCommand extends CompletableFuture implements QueueCommand, HttpChannelHolder { +public abstract class HttpChannelQueueCommand extends CompletableFuture + implements QueueCommand, HttpChannelHolder { private HttpChannelHolder httpChannelHolder; @@ -32,5 +33,4 @@ public abstract class HttpChannelQueueCommand extends CompletableFuture im public HttpChannel getHttpChannel() { return httpChannelHolder.getHttpChannel(); } - } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/command/QueueCommand.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/command/QueueCommand.java index dceeaacd9c..98326c43e7 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/command/QueueCommand.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/command/QueueCommand.java @@ -16,6 +16,4 @@ */ package org.apache.dubbo.remoting.http12.command; -public interface QueueCommand extends Runnable { - -} +public interface QueueCommand extends Runnable {} diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/exception/HttpRequestTimeout.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/exception/HttpRequestTimeout.java index 973369b6c8..8db35f9491 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/exception/HttpRequestTimeout.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/exception/HttpRequestTimeout.java @@ -31,12 +31,11 @@ public class HttpRequestTimeout extends HttpStatusException { return side; } - public static HttpRequestTimeout serverSide(){ + public static HttpRequestTimeout serverSide() { return new HttpRequestTimeout("server"); } - public static HttpRequestTimeout clientSide(){ + public static HttpRequestTimeout clientSide() { return new HttpRequestTimeout("client"); } - } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/exception/IllegalPathException.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/exception/IllegalPathException.java index 96e36082af..1a8e2a265e 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/exception/IllegalPathException.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/exception/IllegalPathException.java @@ -16,10 +16,9 @@ */ package org.apache.dubbo.remoting.http12.exception; -public class IllegalPathException extends RuntimeException{ +public class IllegalPathException extends RuntimeException { - public IllegalPathException() { - } + public IllegalPathException() {} public IllegalPathException(String message) { super(message); diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1OutputMessage.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1OutputMessage.java index 42cf7a1ee5..2406b8249c 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1OutputMessage.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1OutputMessage.java @@ -32,5 +32,4 @@ public class Http1OutputMessage implements HttpOutputMessage { public OutputStream getBody() { return outputStream; } - } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1Request.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1Request.java index 2b3c3cbabf..afe5ebf082 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1Request.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1Request.java @@ -19,6 +19,4 @@ package org.apache.dubbo.remoting.http12.h1; import org.apache.dubbo.remoting.http12.HttpInputMessage; import org.apache.dubbo.remoting.http12.RequestMetadata; -public interface Http1Request extends RequestMetadata, HttpInputMessage { - -} +public interface Http1Request extends RequestMetadata, HttpInputMessage {} diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerChannelObserver.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerChannelObserver.java index d2fceb8d9a..6d92b86554 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerChannelObserver.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerChannelObserver.java @@ -24,7 +24,8 @@ import org.apache.dubbo.remoting.http12.HttpHeaders; import org.apache.dubbo.remoting.http12.HttpMetadata; import org.apache.dubbo.remoting.http12.HttpOutputMessage; -public class Http1ServerChannelObserver extends AbstractServerHttpChannelObserver implements HttpChannelObserver { +public class Http1ServerChannelObserver extends AbstractServerHttpChannelObserver + implements HttpChannelObserver { public Http1ServerChannelObserver(HttpChannel httpChannel) { super(httpChannel); diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerStreamChannelObserver.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerStreamChannelObserver.java index 063b971df3..e5ee7aff44 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerStreamChannelObserver.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerStreamChannelObserver.java @@ -36,7 +36,9 @@ public class Http1ServerStreamChannelObserver extends Http1ServerChannelObserver @Override protected void preOutputMessage(HttpOutputMessage httpMessage) throws IOException { HttpOutputMessage httpOutputMessage = this.getHttpChannel().newOutputMessage(); - httpOutputMessage.getBody().write(SERVER_SENT_EVENT_DATA_PREFIX_BYTES, 0, SERVER_SENT_EVENT_DATA_PREFIX_BYTES.length); + httpOutputMessage + .getBody() + .write(SERVER_SENT_EVENT_DATA_PREFIX_BYTES, 0, SERVER_SENT_EVENT_DATA_PREFIX_BYTES.length); this.getHttpChannel().writeMessage(httpOutputMessage); } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerTransportListener.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerTransportListener.java index 9e41598f42..62b0d396a1 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerTransportListener.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerTransportListener.java @@ -20,6 +20,4 @@ import org.apache.dubbo.remoting.http12.HttpInputMessage; import org.apache.dubbo.remoting.http12.HttpTransportListener; import org.apache.dubbo.remoting.http12.RequestMetadata; -public interface Http1ServerTransportListener extends HttpTransportListener { - -} +public interface Http1ServerTransportListener extends HttpTransportListener {} diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerTransportListenerFactory.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerTransportListenerFactory.java index 1e8f7de276..595ed1d475 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerTransportListenerFactory.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h1/Http1ServerTransportListenerFactory.java @@ -26,5 +26,4 @@ import org.apache.dubbo.rpc.model.FrameworkModel; public interface Http1ServerTransportListenerFactory { Http1ServerTransportListener newInstance(HttpChannel httpChannel, URL url, FrameworkModel frameworkModel); - } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/CancelableTransportListener.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/CancelableTransportListener.java index 3f842e0818..71290b46e4 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/CancelableTransportListener.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/CancelableTransportListener.java @@ -20,8 +20,8 @@ import org.apache.dubbo.remoting.http12.HttpInputMessage; import org.apache.dubbo.remoting.http12.HttpMetadata; import org.apache.dubbo.remoting.http12.HttpTransportListener; -public interface CancelableTransportListener
    extends HttpTransportListener { +public interface CancelableTransportListener
    + extends HttpTransportListener { void cancelByRemote(long errorCode); - } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2Headers.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2Headers.java index 4a2c885e18..faea5b272f 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2Headers.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2Headers.java @@ -17,7 +17,6 @@ package org.apache.dubbo.remoting.http12.h2; public enum Http2Headers { - PATH(":path"), METHOD(":method"), @@ -33,4 +32,4 @@ public enum Http2Headers { public String getName() { return name; } - } +} diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2InputMessage.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2InputMessage.java index 640b13c049..81ab23e321 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2InputMessage.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2InputMessage.java @@ -18,6 +18,4 @@ package org.apache.dubbo.remoting.http12.h2; import org.apache.dubbo.remoting.http12.HttpInputMessage; -public interface Http2InputMessage extends HttpInputMessage, Http2StreamFrame { - -} +public interface Http2InputMessage extends HttpInputMessage, Http2StreamFrame {} diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2ServerChannelObserver.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2ServerChannelObserver.java index ce9187c265..c9fa6af4bb 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2ServerChannelObserver.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2ServerChannelObserver.java @@ -26,7 +26,10 @@ import org.apache.dubbo.remoting.http12.HttpMetadata; import org.apache.dubbo.remoting.http12.message.StreamingDecoder; import org.apache.dubbo.rpc.CancellationContext; -public class Http2ServerChannelObserver extends AbstractServerHttpChannelObserver implements HttpChannelObserver, FlowControlStreamObserver, Http2CancelableStreamObserver { +public class Http2ServerChannelObserver extends AbstractServerHttpChannelObserver + implements HttpChannelObserver, + FlowControlStreamObserver, + Http2CancelableStreamObserver { private CancellationContext cancellationContext; diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2ServerTransportListenerFactory.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2ServerTransportListenerFactory.java index 5b7308d932..3c955bac9d 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2ServerTransportListenerFactory.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2ServerTransportListenerFactory.java @@ -27,5 +27,4 @@ public interface Http2ServerTransportListenerFactory { Http2TransportListener newInstance(H2StreamChannel streamChannel, URL url, FrameworkModel frameworkModel); boolean supportContentType(String contentType); - } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2TransportListener.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2TransportListener.java index 19faa32e4d..16531e7a93 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2TransportListener.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/Http2TransportListener.java @@ -16,6 +16,4 @@ */ package org.apache.dubbo.remoting.http12.h2; -public interface Http2TransportListener extends CancelableTransportListener { - -} +public interface Http2TransportListener extends CancelableTransportListener {} diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/command/ResetQueueCommand.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/command/ResetQueueCommand.java index 7fabddb7cf..79908ccc3f 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/command/ResetQueueCommand.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/h2/command/ResetQueueCommand.java @@ -29,14 +29,12 @@ public class ResetQueueCommand extends HttpChannelQueueCommand { @Override public void run() { - ((H2StreamChannel) getHttpChannel()) - .writeResetFrame(errorCode) - .whenComplete((unused, throwable) -> { - if (throwable != null) { - completeExceptionally(throwable); - } else { - complete(unused); - } - }); + ((H2StreamChannel) getHttpChannel()).writeResetFrame(errorCode).whenComplete((unused, throwable) -> { + if (throwable != null) { + completeExceptionally(throwable); + } else { + complete(unused); + } + }); } } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/HttpMessageCodec.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/HttpMessageCodec.java index 65c3ad65e9..35a23532c3 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/HttpMessageCodec.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/HttpMessageCodec.java @@ -33,15 +33,17 @@ public interface HttpMessageCodec { void encode(OutputStream outputStream, Object data) throws EncodeException; default void encode(OutputStream outputStream, Object[] data) throws EncodeException { - //default encode first data + // default encode first data this.encode(outputStream, data == null || data.length == 0 ? null : data[0]); } Object decode(InputStream inputStream, Class targetType) throws DecodeException; default Object[] decode(InputStream inputStream, Class[] targetTypes) throws DecodeException { - //default decode first target type - return new Object[]{this.decode(inputStream, targetTypes == null || targetTypes.length == 0 ? null : targetTypes[0])}; + // default decode first target type + return new Object[] { + this.decode(inputStream, targetTypes == null || targetTypes.length == 0 ? null : targetTypes[0]) + }; } MediaType contentType(); @@ -50,5 +52,4 @@ public interface HttpMessageCodec { MediaType mediaType = this.contentType(); return mediaType.getName().startsWith(contentType); } - } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/HttpMessageCodecFactory.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/HttpMessageCodecFactory.java index 80978b6a98..9f8d3ac497 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/HttpMessageCodecFactory.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/HttpMessageCodecFactory.java @@ -35,5 +35,4 @@ public interface HttpMessageCodecFactory { MediaType mediaType = this.contentType(); return mediaType.getName().startsWith(contentType); } - } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/JsonCodec.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/JsonCodec.java index 852e1d0ceb..329707a5d5 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/JsonCodec.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/JsonCodec.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.http12.message; -import com.alibaba.fastjson2.JSONObject; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.remoting.http12.exception.DecodeException; @@ -28,6 +27,8 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; +import com.alibaba.fastjson2.JSONObject; + /** * body is json */ diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/JsonPbCodec.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/JsonPbCodec.java index 6d7a760b7e..6b4a6ff5b8 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/JsonPbCodec.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/JsonPbCodec.java @@ -16,8 +16,6 @@ */ package org.apache.dubbo.remoting.http12.message; -import com.google.protobuf.Message; -import com.google.protobuf.util.JsonFormat; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.MethodUtils; @@ -29,6 +27,9 @@ import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; +import com.google.protobuf.Message; +import com.google.protobuf.util.JsonFormat; + @Activate public class JsonPbCodec implements HttpMessageCodec { @@ -45,7 +46,9 @@ public class JsonPbCodec implements HttpMessageCodec { @Override public boolean support(String contentType) { - return HttpMessageCodec.super.support(contentType) && ClassUtils.isPresent("com.google.protobuf.Message", getClass().getClassLoader()); + return HttpMessageCodec.super.support(contentType) + && ClassUtils.isPresent( + "com.google.protobuf.Message", getClass().getClassLoader()); } @Override @@ -77,7 +80,8 @@ public class JsonPbCodec implements HttpMessageCodec { while ((len = body.read(data)) != -1) { builder.append(new String(data, 0, len)); } - Message.Builder newBuilder = (Message.Builder) MethodUtils.findMethod(targetType, "newBuilder").invoke(null); + Message.Builder newBuilder = (Message.Builder) + MethodUtils.findMethod(targetType, "newBuilder").invoke(null); JsonFormat.parser().ignoringUnknownFields().merge(builder.toString(), newBuilder); return newBuilder.build(); } @@ -91,8 +95,8 @@ public class JsonPbCodec implements HttpMessageCodec { public Object[] decode(InputStream dataInputStream, Class[] targetTypes) throws DecodeException { try { if (hasProtobuf(targetTypes)) { - //protobuf only support one parameter - return new Object[]{decode(dataInputStream, targetTypes[0])}; + // protobuf only support one parameter + return new Object[] {decode(dataInputStream, targetTypes[0])}; } } catch (Throwable e) { throw new DecodeException(e); @@ -107,7 +111,7 @@ public class JsonPbCodec implements HttpMessageCodec { return Message.class.isAssignableFrom(targetType); } - private static boolean hasProtobuf(Class[] classes){ + private static boolean hasProtobuf(Class[] classes) { for (Class clazz : classes) { if (isProtobuf(clazz)) { return true; diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/JsonPbCodecFactory.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/JsonPbCodecFactory.java index 3b7cf19d0a..bc82ce9ca0 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/JsonPbCodecFactory.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/JsonPbCodecFactory.java @@ -26,7 +26,10 @@ public class JsonPbCodecFactory implements HttpMessageCodecFactory { @Override public HttpMessageCodec createCodec(URL url, FrameworkModel frameworkModel) { - HttpMessageCodec codec = frameworkModel.getExtensionLoader(HttpMessageCodecFactory.class).getExtension(JsonCodecFactory.NAME).createCodec(url, frameworkModel); + HttpMessageCodec codec = frameworkModel + .getExtensionLoader(HttpMessageCodecFactory.class) + .getExtension(JsonCodecFactory.NAME) + .createCodec(url, frameworkModel); JsonPbCodec jsonPbCodec = new JsonPbCodec(); jsonPbCodec.setJsonCodec(codec); return jsonPbCodec; @@ -39,6 +42,8 @@ public class JsonPbCodecFactory implements HttpMessageCodecFactory { @Override public boolean support(String contentType) { - return HttpMessageCodecFactory.super.support(contentType) && ClassUtils.isPresent("com.google.protobuf.Message", getClass().getClassLoader()); + return HttpMessageCodecFactory.super.support(contentType) + && ClassUtils.isPresent( + "com.google.protobuf.Message", getClass().getClassLoader()); } } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/LengthFieldStreamingDecoder.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/LengthFieldStreamingDecoder.java index 67da0dea90..8256419ad3 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/LengthFieldStreamingDecoder.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/LengthFieldStreamingDecoder.java @@ -146,7 +146,7 @@ public class LengthFieldStreamingDecoder implements StreamingDecoder { } protected void processOffset(InputStream inputStream, int lengthFieldOffset) throws IOException { - //default skip offset + // default skip offset skipOffset(inputStream, lengthFieldOffset); } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/ListeningDecoder.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/ListeningDecoder.java index 2765827a33..af29e6b750 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/ListeningDecoder.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/ListeningDecoder.java @@ -36,8 +36,6 @@ public interface ListeningDecoder { */ void onMessage(Object message); - default void onClose() { - - } + default void onClose() {} } } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/MediaType.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/MediaType.java index b04c024804..7703eeb50c 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/MediaType.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/MediaType.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.http12.message; - import java.nio.charset.Charset; import java.util.Collections; import java.util.Map; diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/MethodMetadata.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/MethodMetadata.java index 09f572ed74..241d0c42bd 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/MethodMetadata.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/MethodMetadata.java @@ -63,16 +63,19 @@ public class MethodMetadata { switch (method.getRpcType()) { case CLIENT_STREAM: case BI_STREAM: - actualRequestTypes = new Class[]{ - (Class) ((ParameterizedType) method.getMethod() - .getGenericReturnType()).getActualTypeArguments()[0]}; - actualResponseType = (Class) ((ParameterizedType) method.getMethod() - .getGenericParameterTypes()[0]).getActualTypeArguments()[0]; + actualRequestTypes = new Class[] { + (Class) + ((ParameterizedType) method.getMethod().getGenericReturnType()).getActualTypeArguments()[0] + }; + actualResponseType = + (Class) ((ParameterizedType) method.getMethod().getGenericParameterTypes()[0]) + .getActualTypeArguments()[0]; return new MethodMetadata(actualRequestTypes, actualResponseType); case SERVER_STREAM: - actualRequestTypes = new Class[]{method.getMethod().getParameterTypes()[0]}; - actualResponseType = (Class) ((ParameterizedType) method.getMethod() - .getGenericParameterTypes()[1]).getActualTypeArguments()[0]; + actualRequestTypes = new Class[] {method.getMethod().getParameterTypes()[0]}; + actualResponseType = + (Class) ((ParameterizedType) method.getMethod().getGenericParameterTypes()[1]) + .getActualTypeArguments()[0]; return new MethodMetadata(actualRequestTypes, actualResponseType); case UNARY: actualRequestTypes = method.getParameterClasses(); diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/StreamingDecoder.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/StreamingDecoder.java index f1b1b2e046..65d54f221e 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/StreamingDecoder.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/StreamingDecoder.java @@ -40,13 +40,11 @@ public interface StreamingDecoder { /** * @param rawMessage raw message */ - default void onFragmentMessage(InputStream dataHeader, InputStream rawMessage){ + default void onFragmentMessage(InputStream dataHeader, InputStream rawMessage) { onFragmentMessage(rawMessage); } - default void onClose() { - - } + default void onClose() {} } class DefaultFragmentListener implements FragmentListener { diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/HttpWriteQueueHandler.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/HttpWriteQueueHandler.java index e292aada05..a81a983af9 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/HttpWriteQueueHandler.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/HttpWriteQueueHandler.java @@ -16,10 +16,11 @@ */ package org.apache.dubbo.remoting.http12.netty4; +import org.apache.dubbo.remoting.http12.command.HttpWriteQueue; + import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.EventLoop; -import org.apache.dubbo.remoting.http12.command.HttpWriteQueue; public class HttpWriteQueueHandler extends ChannelInboundHandlerAdapter { diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/NettyHttpChannelFutureListener.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/NettyHttpChannelFutureListener.java index 279f851260..65d12df0e3 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/NettyHttpChannelFutureListener.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/NettyHttpChannelFutureListener.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.remoting.http12.netty4; +import java.util.concurrent.CompletableFuture; + import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; -import java.util.concurrent.CompletableFuture; - public class NettyHttpChannelFutureListener extends CompletableFuture implements ChannelFutureListener { @Override diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h1/NettyHttp1Channel.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h1/NettyHttp1Channel.java index 030a7da084..c71cd1cee9 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h1/NettyHttp1Channel.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h1/NettyHttp1Channel.java @@ -16,8 +16,6 @@ */ package org.apache.dubbo.remoting.http12.netty4.h1; -import io.netty.buffer.ByteBufOutputStream; -import io.netty.channel.Channel; import org.apache.dubbo.remoting.http12.HttpChannel; import org.apache.dubbo.remoting.http12.HttpMetadata; import org.apache.dubbo.remoting.http12.HttpOutputMessage; @@ -27,6 +25,9 @@ import org.apache.dubbo.remoting.http12.netty4.NettyHttpChannelFutureListener; import java.net.SocketAddress; import java.util.concurrent.CompletableFuture; +import io.netty.buffer.ByteBufOutputStream; +import io.netty.channel.Channel; + public class NettyHttp1Channel implements HttpChannel { private final Channel channel; @@ -60,7 +61,5 @@ public class NettyHttp1Channel implements HttpChannel { } @Override - public void flush() { - - } + public void flush() {} } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h1/NettyHttp1Codec.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h1/NettyHttp1Codec.java index b8425cd623..dfb7e3e39d 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h1/NettyHttp1Codec.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h1/NettyHttp1Codec.java @@ -16,18 +16,6 @@ */ package org.apache.dubbo.remoting.http12.netty4.h1; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.ByteBufInputStream; -import io.netty.buffer.ByteBufOutputStream; -import io.netty.channel.ChannelDuplexHandler; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelPromise; -import io.netty.handler.codec.http.DefaultHttpResponse; -import io.netty.handler.codec.http.FullHttpRequest; -import io.netty.handler.codec.http.HttpHeaders; -import io.netty.handler.codec.http.HttpResponseStatus; -import io.netty.handler.codec.http.HttpVersion; -import io.netty.handler.codec.http.LastHttpContent; import org.apache.dubbo.remoting.http12.HttpHeaderNames; import org.apache.dubbo.remoting.http12.HttpMetadata; import org.apache.dubbo.remoting.http12.HttpOutputMessage; @@ -40,24 +28,40 @@ import java.io.OutputStream; import java.util.List; import java.util.Map; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufInputStream; +import io.netty.buffer.ByteBufOutputStream; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import io.netty.handler.codec.http.DefaultHttpResponse; +import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.handler.codec.http.HttpHeaders; +import io.netty.handler.codec.http.HttpResponseStatus; +import io.netty.handler.codec.http.HttpVersion; +import io.netty.handler.codec.http.LastHttpContent; + public class NettyHttp1Codec extends ChannelDuplexHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { - //decode FullHttpRequest + // decode FullHttpRequest if (msg instanceof FullHttpRequest) { FullHttpRequest fullHttpRequest = (FullHttpRequest) msg; HttpHeaders headers = fullHttpRequest.headers(); Http1RequestMetadata http1RequestMetadata = new Http1RequestMetadata(); http1RequestMetadata.setPath(fullHttpRequest.uri()); http1RequestMetadata.setMethod(fullHttpRequest.method().name()); - org.apache.dubbo.remoting.http12.HttpHeaders httpHeaders = new org.apache.dubbo.remoting.http12.HttpHeaders(); + org.apache.dubbo.remoting.http12.HttpHeaders httpHeaders = + new org.apache.dubbo.remoting.http12.HttpHeaders(); for (Map.Entry header : headers) { String key = header.getKey(); httpHeaders.set(key, header.getValue()); } http1RequestMetadata.setHeaders(httpHeaders); - Http1Request http1Request = new DefaultHttp1Request(http1RequestMetadata, new Http1InputMessage(new ByteBufInputStream(fullHttpRequest.content(), true))); + Http1Request http1Request = new DefaultHttp1Request( + http1RequestMetadata, + new Http1InputMessage(new ByteBufInputStream(fullHttpRequest.content(), true))); super.channelRead(ctx, http1Request); return; } @@ -78,13 +82,13 @@ public class NettyHttp1Codec extends ChannelDuplexHandler { } private void doWriteHeader(ChannelHandlerContext ctx, HttpMetadata msg, ChannelPromise promise) { - //process status + // process status List statusHeaders = msg.headers().remove(HttpHeaderNames.STATUS.getName()); HttpResponseStatus status = HttpResponseStatus.OK; if (!(statusHeaders == null || statusHeaders.isEmpty())) { status = HttpResponseStatus.valueOf(Integer.parseInt(statusHeaders.get(0))); } - //process normal headers + // process normal headers DefaultHttpResponse defaultHttpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status); HttpHeaders headers = defaultHttpResponse.headers(); for (Map.Entry> entry : msg.headers().entrySet()) { @@ -106,5 +110,4 @@ public class NettyHttp1Codec extends ChannelDuplexHandler { } throw new IllegalArgumentException("HttpOutputMessage body must be 'io.netty.buffer.ByteBufOutputStream'"); } - } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h1/NettyHttp1ConnectionHandler.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h1/NettyHttp1ConnectionHandler.java index 9385a30564..77d7724853 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h1/NettyHttp1ConnectionHandler.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h1/NettyHttp1ConnectionHandler.java @@ -16,8 +16,6 @@ */ package org.apache.dubbo.remoting.http12.netty4.h1; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadpool.ThreadPool; import org.apache.dubbo.common.utils.Assert; @@ -35,6 +33,9 @@ import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.List; import java.util.concurrent.Executor; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; + public class NettyHttp1ConnectionHandler extends SimpleChannelInboundHandler { private Http1ServerTransportListenerFactory http1ServerTransportListenerFactory; @@ -50,24 +51,32 @@ public class NettyHttp1ConnectionHandler extends SimpleChannelInboundHandler { try { @@ -79,18 +88,23 @@ public class NettyHttp1ConnectionHandler extends SimpleChannelInboundHandler candidates) { + private static HttpMessageCodecFactory findSuitableCodec( + String contentType, List candidates) { for (HttpMessageCodecFactory factory : candidates) { if (factory.support(contentType)) { return factory; diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyH2StreamChannel.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyH2StreamChannel.java index f315b13100..05941658cf 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyH2StreamChannel.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyH2StreamChannel.java @@ -16,10 +16,6 @@ */ package org.apache.dubbo.remoting.http12.netty4.h2; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.ByteBufOutputStream; -import io.netty.handler.codec.http2.DefaultHttp2ResetFrame; -import io.netty.handler.codec.http2.Http2StreamChannel; import org.apache.dubbo.remoting.http12.HttpMetadata; import org.apache.dubbo.remoting.http12.HttpOutputMessage; import org.apache.dubbo.remoting.http12.h2.H2StreamChannel; @@ -30,6 +26,11 @@ import org.apache.dubbo.remoting.http12.netty4.NettyHttpChannelFutureListener; import java.net.SocketAddress; import java.util.concurrent.CompletableFuture; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufOutputStream; +import io.netty.handler.codec.http2.DefaultHttp2ResetFrame; +import io.netty.handler.codec.http2.Http2StreamChannel; + public class NettyH2StreamChannel implements H2StreamChannel { private final Http2StreamChannel http2StreamChannel; @@ -40,7 +41,7 @@ public class NettyH2StreamChannel implements H2StreamChannel { @Override public CompletableFuture writeHeader(HttpMetadata httpMetadata) { - //WriteQueue.enqueue header frame + // WriteQueue.enqueue header frame NettyHttpChannelFutureListener nettyHttpChannelFutureListener = new NettyHttpChannelFutureListener(); http2StreamChannel.write(httpMetadata).addListener(nettyHttpChannelFutureListener); return nettyHttpChannelFutureListener; diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyHttp2FrameCodec.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyHttp2FrameCodec.java index 3cf80e1b51..9496c94a00 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyHttp2FrameCodec.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyHttp2FrameCodec.java @@ -16,6 +16,18 @@ */ package org.apache.dubbo.remoting.http12.netty4.h2; +import org.apache.dubbo.remoting.http12.HttpHeaders; +import org.apache.dubbo.remoting.http12.h2.Http2Header; +import org.apache.dubbo.remoting.http12.h2.Http2InputMessage; +import org.apache.dubbo.remoting.http12.h2.Http2InputMessageFrame; +import org.apache.dubbo.remoting.http12.h2.Http2MetadataFrame; +import org.apache.dubbo.remoting.http12.h2.Http2OutputMessage; + +import java.io.IOException; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; + import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufInputStream; import io.netty.buffer.ByteBufOutputStream; @@ -28,17 +40,6 @@ import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame; import io.netty.handler.codec.http2.Http2DataFrame; import io.netty.handler.codec.http2.Http2Headers; import io.netty.handler.codec.http2.Http2HeadersFrame; -import org.apache.dubbo.remoting.http12.HttpHeaders; -import org.apache.dubbo.remoting.http12.h2.Http2Header; -import org.apache.dubbo.remoting.http12.h2.Http2InputMessage; -import org.apache.dubbo.remoting.http12.h2.Http2InputMessageFrame; -import org.apache.dubbo.remoting.http12.h2.Http2MetadataFrame; -import org.apache.dubbo.remoting.http12.h2.Http2OutputMessage; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.List; -import java.util.Map; public class NettyHttp2FrameCodec extends ChannelDuplexHandler { @@ -82,7 +83,8 @@ public class NettyHttp2FrameCodec extends ChannelDuplexHandler { private Http2InputMessage onHttp2DataFrame(Http2DataFrame dataFrame) { ByteBuf content = dataFrame.content(); - Http2InputMessageFrame message = new Http2InputMessageFrame(new ByteBufInputStream(content, true), dataFrame.isEndStream()); + Http2InputMessageFrame message = + new Http2InputMessageFrame(new ByteBufInputStream(content, true), dataFrame.isEndStream()); message.setId(dataFrame.stream().id()); return message; } @@ -98,7 +100,8 @@ public class NettyHttp2FrameCodec extends ChannelDuplexHandler { return new DefaultHttp2HeadersFrame(http2Headers, http2Header.isEndStream()); } - private Http2DataFrame encodeHttp2DataFrame(ChannelHandlerContext ctx, Http2OutputMessage outputMessage) throws IOException { + private Http2DataFrame encodeHttp2DataFrame(ChannelHandlerContext ctx, Http2OutputMessage outputMessage) + throws IOException { OutputStream body = outputMessage.getBody(); if (body == null) { return new DefaultHttp2DataFrame(outputMessage.isEndStream()); @@ -109,5 +112,4 @@ public class NettyHttp2FrameCodec extends ChannelDuplexHandler { } throw new IllegalArgumentException("Http2OutputMessage body must be ByteBufOutputStream"); } - } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyHttp2FrameHandler.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyHttp2FrameHandler.java index 05e0cbed97..22514f1474 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyHttp2FrameHandler.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyHttp2FrameHandler.java @@ -16,9 +16,6 @@ */ package org.apache.dubbo.remoting.http12.netty4.h2; -import io.netty.channel.ChannelDuplexHandler; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.http2.Http2ResetFrame; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.http12.HttpStatus; @@ -28,12 +25,16 @@ import org.apache.dubbo.remoting.http12.h2.Http2Header; import org.apache.dubbo.remoting.http12.h2.Http2InputMessage; import org.apache.dubbo.remoting.http12.h2.Http2TransportListener; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.http2.Http2ResetFrame; + import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_RESPONSE; public class NettyHttp2FrameHandler extends ChannelDuplexHandler { - private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger( - NettyHttp2FrameHandler.class); + private static final ErrorTypeAwareLogger LOGGER = + LoggerFactory.getErrorTypeAwareLogger(NettyHttp2FrameHandler.class); private final H2StreamChannel h2StreamChannel; @@ -57,7 +58,7 @@ public class NettyHttp2FrameHandler extends ChannelDuplexHandler { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { - //reset frame + // reset frame if (evt instanceof Http2ResetFrame) { long errorCode = ((Http2ResetFrame) evt).errorCode(); transportListener.cancelByRemote(errorCode); @@ -77,5 +78,4 @@ public class NettyHttp2FrameHandler extends ChannelDuplexHandler { } h2StreamChannel.writeResetFrame(statusCode); } - } diff --git a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyHttp2ProtocolSelectorHandler.java b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyHttp2ProtocolSelectorHandler.java index 09dbf9f2fc..f102a87324 100644 --- a/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyHttp2ProtocolSelectorHandler.java +++ b/dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyHttp2ProtocolSelectorHandler.java @@ -16,10 +16,6 @@ */ package org.apache.dubbo.remoting.http12.netty4.h2; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.SimpleChannelInboundHandler; -import io.netty.handler.codec.http2.Http2StreamChannel; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.http12.HttpHeaderNames; @@ -35,6 +31,11 @@ import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.Set; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPipeline; +import io.netty.channel.SimpleChannelInboundHandler; +import io.netty.handler.codec.http2.Http2StreamChannel; + public class NettyHttp2ProtocolSelectorHandler extends SimpleChannelInboundHandler { private Http2ServerTransportListenerFactory defaultHttp2ServerTransportListenerFactory; @@ -48,7 +49,10 @@ public class NettyHttp2ProtocolSelectorHandler extends SimpleChannelInboundHandl this.frameworkModel = frameworkModel; } - public NettyHttp2ProtocolSelectorHandler(URL url, FrameworkModel frameworkModel, Http2ServerTransportListenerFactory defaultHttp2ServerTransportListenerFactory) { + public NettyHttp2ProtocolSelectorHandler( + URL url, + FrameworkModel frameworkModel, + Http2ServerTransportListenerFactory defaultHttp2ServerTransportListenerFactory) { this.url = url; this.frameworkModel = frameworkModel; this.defaultHttp2ServerTransportListenerFactory = defaultHttp2ServerTransportListenerFactory; @@ -58,7 +62,7 @@ public class NettyHttp2ProtocolSelectorHandler extends SimpleChannelInboundHandl protected void channelRead0(ChannelHandlerContext ctx, HttpMetadata metadata) { HttpHeaders headers = metadata.headers(); String contentType = headers.getFirst(HttpHeaderNames.CONTENT_TYPE.getName()); - //415 + // 415 if (!StringUtils.hasText(contentType)) { throw new UnsupportedMediaTypeException(contentType); } @@ -67,19 +71,23 @@ public class NettyHttp2ProtocolSelectorHandler extends SimpleChannelInboundHandl throw new UnsupportedMediaTypeException(contentType); } H2StreamChannel h2StreamChannel = new NettyH2StreamChannel((Http2StreamChannel) ctx.channel()); - HttpWriteQueueHandler writeQueueHandler = ctx.channel().parent().pipeline().get(HttpWriteQueueHandler.class); + HttpWriteQueueHandler writeQueueHandler = + ctx.channel().parent().pipeline().get(HttpWriteQueueHandler.class); if (writeQueueHandler != null) { HttpWriteQueue writeQueue = writeQueueHandler.getWriteQueue(); h2StreamChannel = new Http2WriteQueueChannel(h2StreamChannel, writeQueue); } ChannelPipeline pipeline = ctx.pipeline(); - pipeline.addLast(new NettyHttp2FrameHandler(h2StreamChannel, factory.newInstance(h2StreamChannel, url, frameworkModel))); + pipeline.addLast( + new NettyHttp2FrameHandler(h2StreamChannel, factory.newInstance(h2StreamChannel, url, frameworkModel))); pipeline.remove(this); ctx.fireChannelRead(metadata); } private Http2ServerTransportListenerFactory adaptHttp2ServerTransportListenerFactory(String contentType) { - Set http2ServerTransportListenerFactories = frameworkModel.getExtensionLoader(Http2ServerTransportListenerFactory.class).getSupportedExtensionInstances(); + Set http2ServerTransportListenerFactories = frameworkModel + .getExtensionLoader(Http2ServerTransportListenerFactory.class) + .getSupportedExtensionInstances(); for (Http2ServerTransportListenerFactory factory : http2ServerTransportListenerFactories) { if (factory.supportContentType(contentType)) { return factory; diff --git a/dubbo-remoting/dubbo-remoting-netty/pom.xml b/dubbo-remoting/dubbo-remoting-netty/pom.xml index 4c65fd2dd2..300e15c07f 100644 --- a/dubbo-remoting/dubbo-remoting-netty/pom.xml +++ b/dubbo-remoting/dubbo-remoting-netty/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-remoting - ${revision} - ../pom.xml - - dubbo-remoting-netty - jar - ${project.artifactId} - The netty remoting module of dubbo project - - false - - - - org.apache.dubbo - dubbo-remoting-api - ${project.parent.version} - - - org.jboss.netty - netty - - - org.slf4j - slf4j-log4j12 - test - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.parent.version} - test - - + 4.0.0 + + org.apache.dubbo + dubbo-remoting + ${revision} + ../pom.xml + + dubbo-remoting-netty + jar + ${project.artifactId} + The netty remoting module of dubbo project + + false + + + + org.apache.dubbo + dubbo-remoting-api + ${project.parent.version} + + + org.jboss.netty + netty + + + org.slf4j + slf4j-log4j12 + test + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.parent.version} + test + + diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyBackedChannelBuffer.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyBackedChannelBuffer.java index 54b8f28af9..ab193b31f7 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyBackedChannelBuffer.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyBackedChannelBuffer.java @@ -44,37 +44,31 @@ public class NettyBackedChannelBuffer implements ChannelBuffer { return buffer.capacity(); } - @Override public ChannelBuffer copy(int index, int length) { return new NettyBackedChannelBuffer(buffer.copy(index, length)); } - @Override public ChannelBufferFactory factory() { return NettyBackedChannelBufferFactory.getInstance(); } - @Override public byte getByte(int index) { return buffer.getByte(index); } - @Override public void getBytes(int index, byte[] dst, int dstIndex, int length) { buffer.getBytes(index, dst, dstIndex, length); } - @Override public void getBytes(int index, ByteBuffer dst) { buffer.getBytes(index, dst); } - @Override public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { // careful @@ -83,37 +77,31 @@ public class NettyBackedChannelBuffer implements ChannelBuffer { dst.setBytes(dstIndex, data, 0, length); } - @Override public void getBytes(int index, OutputStream dst, int length) throws IOException { buffer.getBytes(index, dst, length); } - @Override public boolean isDirect() { return buffer.isDirect(); } - @Override public void setByte(int index, int value) { buffer.setByte(index, value); } - @Override public void setBytes(int index, byte[] src, int srcIndex, int length) { buffer.setBytes(index, src, srcIndex, length); } - @Override public void setBytes(int index, ByteBuffer src) { buffer.setBytes(index, src); } - @Override public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { if (length > src.readableBytes()) { @@ -125,77 +113,64 @@ public class NettyBackedChannelBuffer implements ChannelBuffer { setBytes(index, data, 0, length); } - @Override public int setBytes(int index, InputStream src, int length) throws IOException { return buffer.setBytes(index, src, length); } - @Override public ByteBuffer toByteBuffer(int index, int length) { return buffer.toByteBuffer(index, length); } - @Override public byte[] array() { return buffer.array(); } - @Override public boolean hasArray() { return buffer.hasArray(); } - @Override public int arrayOffset() { return buffer.arrayOffset(); } - // AbstractChannelBuffer - @Override public void clear() { buffer.clear(); } - @Override public ChannelBuffer copy() { return new NettyBackedChannelBuffer(buffer.copy()); } - @Override public void discardReadBytes() { buffer.discardReadBytes(); } - @Override public void ensureWritableBytes(int writableBytes) { buffer.ensureWritableBytes(writableBytes); } - @Override public void getBytes(int index, byte[] dst) { buffer.getBytes(index, dst); } - @Override public void getBytes(int index, ChannelBuffer dst) { // careful getBytes(index, dst, dst.writableBytes()); } - @Override public void getBytes(int index, ChannelBuffer dst, int length) { // careful @@ -206,62 +181,52 @@ public class NettyBackedChannelBuffer implements ChannelBuffer { dst.writerIndex(dst.writerIndex() + length); } - @Override public void markReaderIndex() { buffer.markReaderIndex(); } - @Override public void markWriterIndex() { buffer.markWriterIndex(); } - @Override public boolean readable() { return buffer.readable(); } - @Override public int readableBytes() { return buffer.readableBytes(); } - @Override public byte readByte() { return buffer.readByte(); } - @Override public void readBytes(byte[] dst) { buffer.readBytes(dst); } - @Override public void readBytes(byte[] dst, int dstIndex, int length) { buffer.readBytes(dst, dstIndex, length); } - @Override public void readBytes(ByteBuffer dst) { buffer.readBytes(dst); } - @Override public void readBytes(ChannelBuffer dst) { // careful readBytes(dst, dst.writableBytes()); } - @Override public void readBytes(ChannelBuffer dst, int length) { // careful @@ -272,7 +237,6 @@ public class NettyBackedChannelBuffer implements ChannelBuffer { dst.writerIndex(dst.writerIndex() + length); } - @Override public void readBytes(ChannelBuffer dst, int dstIndex, int length) { // careful @@ -284,56 +248,47 @@ public class NettyBackedChannelBuffer implements ChannelBuffer { dst.setBytes(dstIndex, data, 0, length); } - @Override public ChannelBuffer readBytes(int length) { return new NettyBackedChannelBuffer(buffer.readBytes(length)); } - @Override public void resetReaderIndex() { buffer.resetReaderIndex(); } - @Override public void resetWriterIndex() { buffer.resetWriterIndex(); } - @Override public int readerIndex() { return buffer.readerIndex(); } - @Override public void readerIndex(int readerIndex) { buffer.readerIndex(readerIndex); } - @Override public void readBytes(OutputStream dst, int length) throws IOException { buffer.readBytes(dst, length); } - @Override public void setBytes(int index, byte[] src) { buffer.setBytes(index, src); } - @Override public void setBytes(int index, ChannelBuffer src) { // careful setBytes(index, src, src.readableBytes()); } - @Override public void setBytes(int index, ChannelBuffer src, int length) { // careful @@ -344,68 +299,57 @@ public class NettyBackedChannelBuffer implements ChannelBuffer { src.readerIndex(src.readerIndex() + length); } - @Override public void setIndex(int readerIndex, int writerIndex) { buffer.setIndex(readerIndex, writerIndex); } - @Override public void skipBytes(int length) { buffer.skipBytes(length); } - @Override public ByteBuffer toByteBuffer() { return buffer.toByteBuffer(); } - @Override public boolean writable() { return buffer.writable(); } - @Override public int writableBytes() { return buffer.writableBytes(); } - @Override public void writeByte(int value) { buffer.writeByte(value); } - @Override public void writeBytes(byte[] src) { buffer.writeBytes(src); } - @Override public void writeBytes(byte[] src, int index, int length) { buffer.writeBytes(src, index, length); } - @Override public void writeBytes(ByteBuffer src) { buffer.writeBytes(src); } - @Override public void writeBytes(ChannelBuffer src) { // careful writeBytes(src, src.readableBytes()); } - @Override public void writeBytes(ChannelBuffer src, int length) { // careful @@ -416,7 +360,6 @@ public class NettyBackedChannelBuffer implements ChannelBuffer { src.readerIndex(src.readerIndex() + length); } - @Override public void writeBytes(ChannelBuffer src, int srcIndex, int length) { // careful @@ -425,25 +368,21 @@ public class NettyBackedChannelBuffer implements ChannelBuffer { writeBytes(data, 0, length); } - @Override public int writeBytes(InputStream src, int length) throws IOException { return buffer.writeBytes(src, length); } - @Override public int writerIndex() { return buffer.writerIndex(); } - @Override public void writerIndex(int writerIndex) { buffer.writerIndex(writerIndex); } - @Override public int compareTo(ChannelBuffer o) { return ChannelBuffers.compare(this, o); diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyBackedChannelBufferFactory.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyBackedChannelBufferFactory.java index de3e8091c4..218b6e2680 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyBackedChannelBufferFactory.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyBackedChannelBufferFactory.java @@ -19,10 +19,10 @@ package org.apache.dubbo.remoting.transport.netty; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBufferFactory; -import org.jboss.netty.buffer.ChannelBuffers; - import java.nio.ByteBuffer; +import org.jboss.netty.buffer.ChannelBuffers; + /** * Wrap netty dynamic channel buffer. */ @@ -34,13 +34,11 @@ public class NettyBackedChannelBufferFactory implements ChannelBufferFactory { return INSTANCE; } - @Override public ChannelBuffer getBuffer(int capacity) { return new NettyBackedChannelBuffer(ChannelBuffers.dynamicBuffer(capacity)); } - @Override public ChannelBuffer getBuffer(byte[] array, int offset, int length) { org.jboss.netty.buffer.ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(length); @@ -48,7 +46,6 @@ public class NettyBackedChannelBufferFactory implements ChannelBufferFactory { return new NettyBackedChannelBuffer(buffer); } - @Override public ChannelBuffer getBuffer(ByteBuffer nioBuffer) { return new NettyBackedChannelBuffer(ChannelBuffers.wrappedBuffer(nioBuffer)); diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyChannel.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyChannel.java index ee51ee6050..695983a22f 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyChannel.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyChannel.java @@ -24,13 +24,13 @@ import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.transport.AbstractChannel; import org.apache.dubbo.remoting.utils.PayloadDropper; -import org.jboss.netty.channel.ChannelFuture; - import java.net.InetSocketAddress; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import org.jboss.netty.channel.ChannelFuture; + import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE; @@ -42,7 +42,8 @@ final class NettyChannel extends AbstractChannel { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NettyChannel.class); - private static final ConcurrentMap CHANNEL_MAP = new ConcurrentHashMap(); + private static final ConcurrentMap CHANNEL_MAP = + new ConcurrentHashMap(); private final org.jboss.netty.channel.Channel channel; @@ -111,12 +112,18 @@ final class NettyChannel extends AbstractChannel { throw cause; } } catch (Throwable e) { - throw new RemotingException(this, "Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to " + getRemoteAddress() + ", cause: " + e.getMessage(), e); + throw new RemotingException( + this, + "Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to " + + getRemoteAddress() + ", cause: " + e.getMessage(), + e); } if (!success) { - throw new RemotingException(this, "Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to " + getRemoteAddress() - + "in timeout(" + timeout + "ms) limit"); + throw new RemotingException( + this, + "Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to " + + getRemoteAddress() + "in timeout(" + timeout + "ms) limit"); } } @@ -212,5 +219,4 @@ final class NettyChannel extends AbstractChannel { public String toString() { return "NettyChannel [channel=" + channel + "]"; } - } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyClient.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyClient.java index 3f907959be..6ed419f3a3 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyClient.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyClient.java @@ -27,6 +27,9 @@ import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.transport.AbstractClient; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; @@ -36,9 +39,6 @@ import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_CLIENT_CONNECT_TIMEOUT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CONNECT_PROVIDER; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_DISCONNECT_PROVIDER; @@ -52,9 +52,10 @@ public class NettyClient extends AbstractClient { // ChannelFactory's closure has a DirectMemory leak, using static to avoid // https://issues.jboss.org/browse/NETTY-424 - private static final ChannelFactory CHANNEL_FACTORY = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(new NamedThreadFactory("NettyClientBoss", true)), - Executors.newCachedThreadPool(new NamedThreadFactory("NettyClientWorker", true)), - Constants.DEFAULT_IO_THREADS); + private static final ChannelFactory CHANNEL_FACTORY = new NioClientSocketChannelFactory( + Executors.newCachedThreadPool(new NamedThreadFactory("NettyClientBoss", true)), + Executors.newCachedThreadPool(new NamedThreadFactory("NettyClientWorker", true)), + Constants.DEFAULT_IO_THREADS); private ClientBootstrap bootstrap; private volatile Channel channel; // volatile, please copy reference to use @@ -102,7 +103,8 @@ public class NettyClient extends AbstractClient { if (oldChannel != null) { try { if (logger.isInfoEnabled()) { - logger.info("Close old netty channel " + oldChannel + " on create new netty channel " + newChannel); + logger.info("Close old netty channel " + oldChannel + " on create new netty channel " + + newChannel); } oldChannel.close(); } finally { @@ -127,22 +129,38 @@ public class NettyClient extends AbstractClient { } else if (future.getCause() != null) { Throwable cause = future.getCause(); - RemotingException remotingException = new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server " - + getRemoteAddress() + ", error message is:" + cause.getMessage(), cause); + RemotingException remotingException = new RemotingException( + this, + "client(url: " + getUrl() + ") failed to connect to server " + getRemoteAddress() + + ", error message is:" + cause.getMessage(), + cause); // 6-1 - Failed to connect to provider server by other reason. - logger.error(TRANSPORT_FAILED_CONNECT_PROVIDER, "network disconnected", "", "Failed to connect to provider server by other reason.", cause); + logger.error( + TRANSPORT_FAILED_CONNECT_PROVIDER, + "network disconnected", + "", + "Failed to connect to provider server by other reason.", + cause); throw remotingException; } else { - RemotingException remotingException = new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server " - + getRemoteAddress() + " client-side timeout " - + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client " - + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()); + RemotingException remotingException = new RemotingException( + this, + "client(url: " + getUrl() + ") failed to connect to server " + + getRemoteAddress() + " client-side timeout " + + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + + "ms) from netty client " + + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()); // 6-2 - Client-side timeout. - logger.error(TRANSPORT_CLIENT_CONNECT_TIMEOUT, "provider crash", "", "Client-side timeout.", remotingException); + logger.error( + TRANSPORT_CLIENT_CONNECT_TIMEOUT, + "provider crash", + "", + "Client-side timeout.", + remotingException); throw remotingException; } @@ -183,5 +201,4 @@ public class NettyClient extends AbstractClient { Channel getNettyChannel() { return channel; } - } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyCodecAdapter.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyCodecAdapter.java index 984ec89a40..4034392695 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyCodecAdapter.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyCodecAdapter.java @@ -20,6 +20,8 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.buffer.DynamicChannelBuffer; +import java.io.IOException; + import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; @@ -32,8 +34,6 @@ import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; -import java.io.IOException; - import static org.apache.dubbo.remoting.Constants.BUFFER_KEY; import static org.apache.dubbo.remoting.Constants.DEFAULT_BUFFER_SIZE; import static org.apache.dubbo.remoting.Constants.MAX_BUFFER_SIZE; @@ -121,8 +121,7 @@ final class NettyCodecAdapter { message.writeBytes(input.toByteBuffer()); } } else { - message = org.apache.dubbo.remoting.buffer.ChannelBuffers.wrappedBuffer( - input.toByteBuffer()); + message = org.apache.dubbo.remoting.buffer.ChannelBuffers.wrappedBuffer(input.toByteBuffer()); } NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler); diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyHandler.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyHandler.java index db6e2dded6..f1d4bfd23c 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyHandler.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyHandler.java @@ -23,6 +23,10 @@ import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; +import java.net.InetSocketAddress; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + import org.jboss.netty.channel.ChannelHandler.Sharable; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelStateEvent; @@ -30,10 +34,6 @@ import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelHandler; -import java.net.InetSocketAddress; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - /** * NettyHandler */ @@ -68,7 +68,10 @@ public class NettyHandler extends SimpleChannelHandler { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler); try { if (channel != null) { - channels.put(NetUtils.toAddressString((InetSocketAddress) ctx.getChannel().getRemoteAddress()), channel); + channels.put( + NetUtils.toAddressString( + (InetSocketAddress) ctx.getChannel().getRemoteAddress()), + channel); } handler.connected(channel); } finally { @@ -76,7 +79,8 @@ public class NettyHandler extends SimpleChannelHandler { } if (logger.isInfoEnabled()) { - logger.info("The connection between " + channel.getRemoteAddress() + " and " + channel.getLocalAddress() + " is established"); + logger.info("The connection between " + channel.getRemoteAddress() + " and " + channel.getLocalAddress() + + " is established"); } } @@ -84,14 +88,16 @@ public class NettyHandler extends SimpleChannelHandler { public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler); try { - channels.remove(NetUtils.toAddressString((InetSocketAddress) ctx.getChannel().getRemoteAddress())); + channels.remove(NetUtils.toAddressString( + (InetSocketAddress) ctx.getChannel().getRemoteAddress())); handler.disconnected(channel); } finally { NettyChannel.removeChannelIfDisconnected(ctx.getChannel()); } if (logger.isInfoEnabled()) { - logger.info("The connection between " + channel.getRemoteAddress() + " and " + channel.getLocalAddress() + " is disconnected"); + logger.info("The connection between " + channel.getRemoteAddress() + " and " + channel.getLocalAddress() + + " is disconnected"); } } @@ -125,5 +131,4 @@ public class NettyHandler extends SimpleChannelHandler { NettyChannel.removeChannelIfDisconnected(ctx.getChannel()); } } - } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyHelper.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyHelper.java index f7f70bfecd..b25d5be140 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyHelper.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyHelper.java @@ -116,5 +116,4 @@ final class NettyHelper { return logger.toString(); } } - } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyPortUnificationServer.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyPortUnificationServer.java index a4d63b608d..204009b9c1 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyPortUnificationServer.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyPortUnificationServer.java @@ -30,13 +30,6 @@ import org.apache.dubbo.remoting.api.WireProtocol; import org.apache.dubbo.remoting.api.pu.AbstractPortUnificationServer; import org.apache.dubbo.remoting.transport.dispatcher.ChannelHandlers; -import org.jboss.netty.bootstrap.ServerBootstrap; -import org.jboss.netty.channel.ChannelFactory; -import org.jboss.netty.channel.ChannelPipeline; -import org.jboss.netty.channel.ChannelPipelineFactory; -import org.jboss.netty.channel.Channels; -import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; - import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; @@ -45,6 +38,13 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import org.jboss.netty.bootstrap.ServerBootstrap; +import org.jboss.netty.channel.ChannelFactory; +import org.jboss.netty.channel.ChannelPipeline; +import org.jboss.netty.channel.ChannelPipelineFactory; +import org.jboss.netty.channel.Channels; +import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; + import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.BACKLOG_KEY; @@ -58,15 +58,15 @@ import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_WORKER_POOL_NAME; */ public class NettyPortUnificationServer extends AbstractPortUnificationServer { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NettyPortUnificationServer.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(NettyPortUnificationServer.class); - private Map dubboChannels = new ConcurrentHashMap<>();// + private Map dubboChannels = new ConcurrentHashMap<>(); // private ServerBootstrap bootstrap; private org.jboss.netty.channel.Channel channel; - public NettyPortUnificationServer(URL url, ChannelHandler handler) throws RemotingException { super(url, ChannelHandlers.wrap(handler, url)); } @@ -83,8 +83,8 @@ public class NettyPortUnificationServer extends AbstractPortUnificationServer { } } - public void bind(){ - if(channel == null) { + public void bind() { + if (channel == null) { doOpen(); } } @@ -93,8 +93,10 @@ public class NettyPortUnificationServer extends AbstractPortUnificationServer { protected void doOpen() { NettyHelper.setNettyLoggerFactory(); ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory(EVENT_LOOP_BOSS_POOL_NAME, true)); - ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory(EVENT_LOOP_WORKER_POOL_NAME, true)); - ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS)); + ExecutorService worker = + Executors.newCachedThreadPool(new NamedThreadFactory(EVENT_LOOP_WORKER_POOL_NAME, true)); + ChannelFactory channelFactory = new NioServerSocketChannelFactory( + boss, worker, getUrl().getPositiveParameter(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS)); bootstrap = new ServerBootstrap(channelFactory); final NettyHandler nettyHandler = new NettyHandler(getUrl(), this); @@ -107,7 +109,8 @@ public class NettyPortUnificationServer extends AbstractPortUnificationServer { bootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() { - NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyPortUnificationServer.this); + NettyCodecAdapter adapter = + new NettyCodecAdapter(getCodec(), getUrl(), NettyPortUnificationServer.this); ChannelPipeline pipeline = Channels.pipeline(); /*int idleTimeout = getIdleTimeout(); if (idleTimeout > 10000) { @@ -127,8 +130,6 @@ public class NettyPortUnificationServer extends AbstractPortUnificationServer { } InetSocketAddress bindAddress = new InetSocketAddress(bindIp, bindPort); channel = bootstrap.bind(bindAddress); - - } @Override @@ -201,5 +202,4 @@ public class NettyPortUnificationServer extends AbstractPortUnificationServer { public boolean isBound() { return channel.isBound(); } - } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyServer.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyServer.java index d5aec38b92..42a2346481 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyServer.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyServer.java @@ -30,13 +30,6 @@ import org.apache.dubbo.remoting.RemotingServer; import org.apache.dubbo.remoting.transport.AbstractServer; import org.apache.dubbo.remoting.transport.dispatcher.ChannelHandlers; -import org.jboss.netty.bootstrap.ServerBootstrap; -import org.jboss.netty.channel.ChannelFactory; -import org.jboss.netty.channel.ChannelPipeline; -import org.jboss.netty.channel.ChannelPipelineFactory; -import org.jboss.netty.channel.Channels; -import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; - import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; @@ -44,6 +37,13 @@ import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import org.jboss.netty.bootstrap.ServerBootstrap; +import org.jboss.netty.channel.ChannelFactory; +import org.jboss.netty.channel.ChannelPipeline; +import org.jboss.netty.channel.ChannelPipelineFactory; +import org.jboss.netty.channel.Channels; +import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; + import static org.apache.dubbo.common.constants.CommonConstants.BACKLOG_KEY; import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE; @@ -71,8 +71,10 @@ public class NettyServer extends AbstractServer implements RemotingServer { protected void doOpen() throws Throwable { NettyHelper.setNettyLoggerFactory(); ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory(EVENT_LOOP_BOSS_POOL_NAME, true)); - ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory(EVENT_LOOP_WORKER_POOL_NAME, true)); - ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS)); + ExecutorService worker = + Executors.newCachedThreadPool(new NamedThreadFactory(EVENT_LOOP_WORKER_POOL_NAME, true)); + ChannelFactory channelFactory = new NioServerSocketChannelFactory( + boss, worker, getUrl().getPositiveParameter(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS)); bootstrap = new ServerBootstrap(channelFactory); final NettyHandler nettyHandler = new NettyHandler(getUrl(), this); @@ -164,5 +166,4 @@ public class NettyServer extends AbstractServer implements RemotingServer { public boolean isBound() { return channel.isBound(); } - } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyTransporter.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyTransporter.java index 4dde31eb26..c9dd8f53d2 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyTransporter.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyTransporter.java @@ -36,5 +36,4 @@ public class NettyTransporter implements Transporter { public Client connect(URL url, ChannelHandler handler) throws RemotingException { return new NettyClient(url, handler); } - } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java index 608a530731..ca34345c95 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.exchange.support.header; import org.apache.dubbo.common.URL; @@ -32,13 +31,14 @@ import org.apache.dubbo.remoting.exchange.ExchangeServer; import org.apache.dubbo.remoting.exchange.Exchangers; import org.apache.dubbo.remoting.transport.dispatcher.FakeChannelHandlers; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT; class HeartbeatHandlerTest { @@ -70,9 +70,9 @@ class HeartbeatHandlerTest { void testServerHeartbeat() throws Exception { FakeChannelHandlers.resetChannelHandlers(); URL serverURL = URL.valueOf("telnet://localhost:" + NetUtils.getAvailablePort(56780)) - .addParameter(Constants.EXCHANGER_KEY, HeaderExchanger.NAME) - .addParameter(Constants.TRANSPORTER_KEY, "netty3") - .addParameter(Constants.HEARTBEAT_KEY, 1000); + .addParameter(Constants.EXCHANGER_KEY, HeaderExchanger.NAME) + .addParameter(Constants.TRANSPORTER_KEY, "netty3") + .addParameter(Constants.HEARTBEAT_KEY, 1000); CountDownLatch connect = new CountDownLatch(1); CountDownLatch disconnect = new CountDownLatch(1); ApplicationModel applicationModel = ApplicationModel.defaultModel(); @@ -101,10 +101,10 @@ class HeartbeatHandlerTest { @Test void testHeartbeat() throws Exception { URL serverURL = URL.valueOf("telnet://localhost:" + NetUtils.getAvailablePort(56785)) - .addParameter(Constants.EXCHANGER_KEY, HeaderExchanger.NAME) - .addParameter(Constants.TRANSPORTER_KEY, "netty3") - .addParameter(Constants.HEARTBEAT_KEY, 1000) - .addParameter(Constants.CODEC_KEY, "telnet"); + .addParameter(Constants.EXCHANGER_KEY, HeaderExchanger.NAME) + .addParameter(Constants.TRANSPORTER_KEY, "netty3") + .addParameter(Constants.HEARTBEAT_KEY, 1000) + .addParameter(Constants.CODEC_KEY, "telnet"); ApplicationModel applicationModel = ApplicationModel.defaultModel(); ApplicationConfig applicationConfig = new ApplicationConfig("provider-app"); applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT); @@ -128,9 +128,9 @@ class HeartbeatHandlerTest { void testClientHeartbeat() throws Exception { FakeChannelHandlers.setTestingChannelHandlers(); URL serverURL = URL.valueOf("telnet://localhost:" + NetUtils.getAvailablePort(56790)) - .addParameter(Constants.EXCHANGER_KEY, HeaderExchanger.NAME) - .addParameter(Constants.TRANSPORTER_KEY, "netty3") - .addParameter(Constants.CODEC_KEY, "telnet"); + .addParameter(Constants.EXCHANGER_KEY, HeaderExchanger.NAME) + .addParameter(Constants.TRANSPORTER_KEY, "netty3") + .addParameter(Constants.CODEC_KEY, "telnet"); ApplicationModel applicationModel = ApplicationModel.defaultModel(); ApplicationConfig applicationConfig = new ApplicationConfig("provider-app"); applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT); @@ -179,9 +179,7 @@ class HeartbeatHandlerTest { } @Override - public void sent(Channel channel, Object message) throws RemotingException { - - } + public void sent(Channel channel, Object message) throws RemotingException {} @Override public void received(Channel channel, Object message) throws RemotingException { @@ -197,5 +195,4 @@ class HeartbeatHandlerTest { return message; } } - } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/dispatcher/FakeChannelHandlers.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/dispatcher/FakeChannelHandlers.java index 0e17dab774..8c3c96411f 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/dispatcher/FakeChannelHandlers.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/dispatcher/FakeChannelHandlers.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.transport.dispatcher; import org.apache.dubbo.common.URL; @@ -39,6 +38,7 @@ public class FakeChannelHandlers extends ChannelHandlers { @Override protected ChannelHandler wrapInternal(ChannelHandler handler, URL url) { return ExtensionLoader.getExtensionLoader(Dispatcher.class) - .getAdaptiveExtension().dispatch(handler, url); + .getAdaptiveExtension() + .dispatch(handler, url); } } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientReconnectTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientReconnectTest.java index 37183b94cb..a5a82dca66 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientReconnectTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientReconnectTest.java @@ -75,10 +75,10 @@ class ClientReconnectTest { } } - public Client startClient(int port, int heartbeat) throws RemotingException { - URL url = URL.valueOf("exchange://127.0.0.1:" + port + "/client.reconnect.test?check=false&codec=exchange&client=netty3&" + - Constants.HEARTBEAT_KEY + "=" + heartbeat + "&" + LEAST_RECONNECT_DURATION_KEY + "=0"); + URL url = URL.valueOf( + "exchange://127.0.0.1:" + port + "/client.reconnect.test?check=false&codec=exchange&client=netty3&" + + Constants.HEARTBEAT_KEY + "=" + heartbeat + "&" + LEAST_RECONNECT_DURATION_KEY + "=0"); ApplicationModel applicationModel = ApplicationModel.defaultModel(); ApplicationConfig applicationConfig = new ApplicationConfig("provider-app"); applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT); @@ -98,15 +98,12 @@ class ClientReconnectTest { } @Override - public void connected(Channel channel) throws RemotingException { - } + public void connected(Channel channel) throws RemotingException {} @Override - public void disconnected(Channel channel) throws RemotingException { - } + public void disconnected(Channel channel) throws RemotingException {} @Override - public void caught(Channel channel, Throwable exception) throws RemotingException { - } + public void caught(Channel channel, Throwable exception) throws RemotingException {} } } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientToServerTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientToServerTest.java index a21ed9e114..3a8ff64488 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientToServerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientToServerTest.java @@ -22,16 +22,16 @@ import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeServer; import org.apache.dubbo.remoting.exchange.support.Replier; +import java.util.concurrent.CompletableFuture; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.concurrent.CompletableFuture; - /** * ClientToServer */ -public abstract class ClientToServerTest { +public abstract class ClientToServerTest { protected static final String LOCALHOST = "127.0.0.1"; @@ -55,11 +55,9 @@ public abstract class ClientToServerTest { @BeforeEach protected void tearDown() { try { - if (server != null) - server.close(); + if (server != null) server.close(); } finally { - if (client != null) - client.close(); + if (client != null) client.close(); } } @@ -70,22 +68,22 @@ public abstract class ClientToServerTest { Assertions.assertEquals("hello,world", result.getName()); } -// @Test -// public void testCallback() throws Exception { -// final Object waitter = new Object(); -// client.invoke(new World("world"), new InvokeCallback() { -// public void callback(Hello result) { -// Assertions.assertEquals("hello,world", result.getName()); -// synchronized (waitter) { -// waitter.notifyAll(); -// } -// } -// public void onException(Throwable exception) { -// } -// }); -// synchronized (waitter) { -// waitter.wait(); -// } -// } + // @Test + // public void testCallback() throws Exception { + // final Object waitter = new Object(); + // client.invoke(new World("world"), new InvokeCallback() { + // public void callback(Hello result) { + // Assertions.assertEquals("hello,world", result.getName()); + // synchronized (waitter) { + // waitter.notifyAll(); + // } + // } + // public void onException(Throwable exception) { + // } + // }); + // synchronized (waitter) { + // waitter.wait(); + // } + // } } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientsTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientsTest.java index dfcd94a447..eb0112e588 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientsTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientsTest.java @@ -51,14 +51,20 @@ class ClientsTest { @Test void testGetTransport3() { String name = "netty3"; - assertEquals(NettyTransporter.class, ExtensionLoader.getExtensionLoader(Transporter.class).getExtension(name).getClass()); + assertEquals( + NettyTransporter.class, + ExtensionLoader.getExtensionLoader(Transporter.class) + .getExtension(name) + .getClass()); } @Test void testGetTransportWrong() { Assertions.assertThrows(IllegalStateException.class, () -> { String name = "nety"; - assertNull(ExtensionLoader.getExtensionLoader(Transporter.class).getExtension(name).getClass()); + assertNull(ExtensionLoader.getExtensionLoader(Transporter.class) + .getExtension(name) + .getClass()); }); } } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/Hello.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/Hello.java index 52ce36b2a8..3b669f8c4a 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/Hello.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/Hello.java @@ -27,8 +27,7 @@ public class Hello implements Serializable { private String name; - public Hello() { - } + public Hello() {} public Hello(String name) { this.name = name; @@ -41,5 +40,4 @@ public class Hello implements Serializable { public void setName(String name) { this.name = name; } - } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyBackedChannelBufferTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyBackedChannelBufferTest.java index 99005d9140..aacca98823 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyBackedChannelBufferTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyBackedChannelBufferTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.transport.netty; - import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientTest.java index 4b14d0f4b1..46337903d6 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientTest.java @@ -23,13 +23,14 @@ import org.apache.dubbo.remoting.RemotingServer; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.Exchangers; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT; /** @@ -54,16 +55,16 @@ class NettyClientTest { @AfterAll public static void tearDown() { try { - if (server != null) - server.close(); + if (server != null) server.close(); } finally { } } -// public static void main(String[] args) throws RemotingException, InterruptedException { -// ExchangeChannel client = Exchangers.connect(URL.valueOf("exchange://10.20.153.10:20880?client=netty3&heartbeat=1000&codec=exchange")); -// Thread.sleep(60 * 1000 * 50); -// } + // public static void main(String[] args) throws RemotingException, InterruptedException { + // ExchangeChannel client = + // Exchangers.connect(URL.valueOf("exchange://10.20.153.10:20880?client=netty3&heartbeat=1000&codec=exchange")); + // Thread.sleep(60 * 1000 * 50); + // } @Test void testClientClose() throws Exception { @@ -88,7 +89,8 @@ class NettyClientTest { @Test void testServerClose() throws Exception { for (int i = 0; i < 100; i++) { - URL url = URL.valueOf("exchange://localhost:" + NetUtils.getAvailablePort(6000) + "?server=netty3&codec=exchange"); + URL url = URL.valueOf( + "exchange://localhost:" + NetUtils.getAvailablePort(6000) + "?server=netty3&codec=exchange"); ApplicationModel applicationModel = ApplicationModel.defaultModel(); ApplicationConfig applicationConfig = new ApplicationConfig("provider-app"); applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT); diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientToServerTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientToServerTest.java index 57131fcbc6..c7c1a86478 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientToServerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientToServerTest.java @@ -56,5 +56,4 @@ class NettyClientToServerTest extends ClientToServerTest { url = url.setScopeModel(applicationModel); return Exchangers.connect(url); } - } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyStringTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyStringTest.java index 8b1fde4034..64a2bb85e8 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyStringTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyStringTest.java @@ -23,6 +23,7 @@ import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeServer; import org.apache.dubbo.remoting.exchange.Exchangers; import org.apache.dubbo.rpc.model.ApplicationModel; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -39,8 +40,8 @@ class NettyStringTest { @BeforeAll public static void setUp() throws Exception { - //int port = (int) (1000 * Math.random() + 10000); - //int port = 10001; + // int port = (int) (1000 * Math.random() + 10000); + // int port = 10001; int port = NetUtils.getAvailablePort(); System.out.println(port); URL serverURL = URL.valueOf("telnet://0.0.0.0:" + port + "?server=netty3&codec=telnet"); @@ -59,17 +60,15 @@ class NettyStringTest { @AfterAll public static void tearDown() { try { - if (server != null) - server.close(); + if (server != null) server.close(); } finally { - if (client != null) - client.close(); + if (client != null) client.close(); } } @Test void testHandler() { - //Thread.sleep(20000); + // Thread.sleep(20000); /*client.request("world\r\n"); Future future = client.request("world", 10000); String result = (String)future.get(); diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/TelnetServerHandler.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/TelnetServerHandler.java index 54b951b5de..c83db19c84 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/TelnetServerHandler.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/TelnetServerHandler.java @@ -39,8 +39,7 @@ public class TelnetServerHandler implements Replier { } else { response = "Did you say '" + msg + "'?\r\n"; } - //System.out.println(response); + // System.out.println(response); return response; } - } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ThreadNameTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ThreadNameTest.java index 203cc35353..ffc7100b93 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ThreadNameTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ThreadNameTest.java @@ -23,15 +23,16 @@ import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT; class ThreadNameTest { @@ -54,15 +55,13 @@ class ThreadNameTest { @BeforeEach public void before() throws Exception { int port = NetUtils.getAvailablePort(20880 + new Random().nextInt(10000)); - serverURL = URL.valueOf("telnet://localhost?side=provider&codec=telnet") - .setPort(port); + serverURL = URL.valueOf("telnet://localhost?side=provider&codec=telnet").setPort(port); ApplicationModel applicationModel = ApplicationModel.defaultModel(); ApplicationConfig applicationConfig = new ApplicationConfig("provider-app"); applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT); applicationModel.getApplicationConfigManager().setApplication(applicationConfig); serverURL = serverURL.setScopeModel(applicationModel); - clientURL = URL.valueOf("telnet://localhost?side=consumer&codec=telnet") - .setPort(port); + clientURL = URL.valueOf("telnet://localhost?side=consumer&codec=telnet").setPort(port); clientURL = clientURL.setScopeModel(applicationModel); serverHandler = new ThreadNameVerifyHandler(serverRegex, false, serverLatch); clientHandler = new ThreadNameVerifyHandler(clientRegex, true, clientLatch); @@ -114,14 +113,14 @@ class ThreadNameTest { if (!success) { success = Thread.currentThread().getName().matches(message); } - if(success) { + if (success) { latch.countDown(); } } private void output(String method) { - System.out.println(Thread.currentThread().getName() - + " " + (client ? "client " + method : "server " + method)); + System.out.println( + Thread.currentThread().getName() + " " + (client ? "client " + method : "server " + method)); } @Override @@ -144,7 +143,7 @@ class ThreadNameTest { @Override public void received(Channel channel, Object message) throws RemotingException { - // server: DubboServerHandler or DubboSharedHandler thread. + // server: DubboServerHandler or DubboSharedHandler thread. output("received"); } @@ -154,5 +153,4 @@ class ThreadNameTest { output("caught"); } } - } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/World.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/World.java index 7185da312a..372857aee0 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/World.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/World.java @@ -27,8 +27,7 @@ public class World implements Serializable { private String name; - public World() { - } + public World() {} public World(String name) { this.name = name; @@ -41,5 +40,4 @@ public class World implements Serializable { public void setName(String name) { this.name = name; } - } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/WorldHandler.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/WorldHandler.java index 689f978ccf..80ac7118db 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/WorldHandler.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/WorldHandler.java @@ -32,5 +32,4 @@ public class WorldHandler implements Replier { public Object reply(ExchangeChannel channel, World msg) throws RemotingException { return new Hello("hello," + msg.getName()); } - } diff --git a/dubbo-remoting/dubbo-remoting-netty4/pom.xml b/dubbo-remoting/dubbo-remoting-netty4/pom.xml index 3fbc0698c8..02d3e9747e 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/pom.xml +++ b/dubbo-remoting/dubbo-remoting-netty4/pom.xml @@ -1,3 +1,4 @@ + - - dubbo-remoting - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 + 4.0.0 + + org.apache.dubbo + dubbo-remoting + ${revision} + ../pom.xml + - dubbo-remoting-netty4 - jar + dubbo-remoting-netty4 + jar - ${project.artifactId} - The netty4 remoting module of dubbo project + ${project.artifactId} + The netty4 remoting module of dubbo project - - false - UTF-8 - + + false + UTF-8 + - - - org.apache.dubbo - dubbo-remoting-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-metrics-netty - ${project.parent.version} - - - io.netty - netty-handler-proxy - compile - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.parent.version} - test - - - org.slf4j - slf4j-log4j12 - test - - - io.netty - netty-transport-classes-epoll - compile - - - io.netty - netty-transport-native-epoll - linux-aarch_64 - runtime - + + + org.apache.dubbo + dubbo-remoting-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-metrics-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-metrics-netty + ${project.parent.version} + + + io.netty + netty-handler-proxy + compile + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.parent.version} + test + + + org.slf4j + slf4j-log4j12 + test + + + io.netty + netty-transport-classes-epoll + compile + + + io.netty + netty-transport-native-epoll + linux-aarch_64 + runtime + - - org.apache.dubbo - dubbo-native - ${project.parent.version} - - + + org.apache.dubbo + dubbo-native + ${project.parent.version} + + diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/Netty4BatchWriteQueue.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/Netty4BatchWriteQueue.java index b07eae7d3f..75089d31c2 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/Netty4BatchWriteQueue.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/Netty4BatchWriteQueue.java @@ -16,17 +16,18 @@ */ package org.apache.dubbo.remoting.transport.netty4; -import io.netty.channel.Channel; -import io.netty.channel.ChannelFuture; -import io.netty.channel.ChannelFutureListener; -import io.netty.channel.ChannelPromise; -import io.netty.channel.EventLoop; import org.apache.dubbo.common.BatchExecutorQueue; import org.apache.dubbo.remoting.exchange.support.MultiMessage; import java.util.LinkedList; import java.util.Queue; +import io.netty.channel.Channel; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelPromise; +import io.netty.channel.EventLoop; + /** * netty4 batch write queue */ @@ -73,7 +74,7 @@ public class Netty4BatchWriteQueue extends BatchExecutorQueue src.readableBytes()) { @@ -125,77 +113,64 @@ public class NettyBackedChannelBuffer implements ChannelBuffer { setBytes(index, data, 0, length); } - @Override public int setBytes(int index, InputStream src, int length) throws IOException { return buffer.setBytes(index, src, length); } - @Override public ByteBuffer toByteBuffer(int index, int length) { return buffer.nioBuffer(index, length); } - @Override public byte[] array() { return buffer.array(); } - @Override public boolean hasArray() { return buffer.hasArray(); } - @Override public int arrayOffset() { return buffer.arrayOffset(); } - // AbstractChannelBuffer - @Override public void clear() { buffer.clear(); } - @Override public ChannelBuffer copy() { return new NettyBackedChannelBuffer(buffer.copy()); } - @Override public void discardReadBytes() { buffer.discardReadBytes(); } - @Override public void ensureWritableBytes(int writableBytes) { buffer.ensureWritable(writableBytes); } - @Override public void getBytes(int index, byte[] dst) { buffer.getBytes(index, dst); } - @Override public void getBytes(int index, ChannelBuffer dst) { // careful getBytes(index, dst, dst.writableBytes()); } - @Override public void getBytes(int index, ChannelBuffer dst, int length) { // careful @@ -206,62 +181,52 @@ public class NettyBackedChannelBuffer implements ChannelBuffer { dst.writerIndex(dst.writerIndex() + length); } - @Override public void markReaderIndex() { buffer.markReaderIndex(); } - @Override public void markWriterIndex() { buffer.markWriterIndex(); } - @Override public boolean readable() { return buffer.isReadable(); } - @Override public int readableBytes() { return buffer.readableBytes(); } - @Override public byte readByte() { return buffer.readByte(); } - @Override public void readBytes(byte[] dst) { buffer.readBytes(dst); } - @Override public void readBytes(byte[] dst, int dstIndex, int length) { buffer.readBytes(dst, dstIndex, length); } - @Override public void readBytes(ByteBuffer dst) { buffer.readBytes(dst); } - @Override public void readBytes(ChannelBuffer dst) { // careful readBytes(dst, dst.writableBytes()); } - @Override public void readBytes(ChannelBuffer dst, int length) { // careful @@ -272,7 +237,6 @@ public class NettyBackedChannelBuffer implements ChannelBuffer { dst.writerIndex(dst.writerIndex() + length); } - @Override public void readBytes(ChannelBuffer dst, int dstIndex, int length) { // careful @@ -284,56 +248,47 @@ public class NettyBackedChannelBuffer implements ChannelBuffer { dst.setBytes(dstIndex, data, 0, length); } - @Override public ChannelBuffer readBytes(int length) { return new NettyBackedChannelBuffer(buffer.readBytes(length)); } - @Override public void resetReaderIndex() { buffer.resetReaderIndex(); } - @Override public void resetWriterIndex() { buffer.resetWriterIndex(); } - @Override public int readerIndex() { return buffer.readerIndex(); } - @Override public void readerIndex(int readerIndex) { buffer.readerIndex(readerIndex); } - @Override public void readBytes(OutputStream dst, int length) throws IOException { buffer.readBytes(dst, length); } - @Override public void setBytes(int index, byte[] src) { buffer.setBytes(index, src); } - @Override public void setBytes(int index, ChannelBuffer src) { // careful setBytes(index, src, src.readableBytes()); } - @Override public void setBytes(int index, ChannelBuffer src, int length) { // careful @@ -344,68 +299,57 @@ public class NettyBackedChannelBuffer implements ChannelBuffer { src.readerIndex(src.readerIndex() + length); } - @Override public void setIndex(int readerIndex, int writerIndex) { buffer.setIndex(readerIndex, writerIndex); } - @Override public void skipBytes(int length) { buffer.skipBytes(length); } - @Override public ByteBuffer toByteBuffer() { return buffer.nioBuffer(); } - @Override public boolean writable() { return buffer.isWritable(); } - @Override public int writableBytes() { return buffer.writableBytes(); } - @Override public void writeByte(int value) { buffer.writeByte(value); } - @Override public void writeBytes(byte[] src) { buffer.writeBytes(src); } - @Override public void writeBytes(byte[] src, int index, int length) { buffer.writeBytes(src, index, length); } - @Override public void writeBytes(ByteBuffer src) { buffer.writeBytes(src); } - @Override public void writeBytes(ChannelBuffer src) { // careful writeBytes(src, src.readableBytes()); } - @Override public void writeBytes(ChannelBuffer src, int length) { // careful @@ -416,7 +360,6 @@ public class NettyBackedChannelBuffer implements ChannelBuffer { src.readerIndex(src.readerIndex() + length); } - @Override public void writeBytes(ChannelBuffer src, int srcIndex, int length) { // careful @@ -425,26 +368,22 @@ public class NettyBackedChannelBuffer implements ChannelBuffer { writeBytes(data, 0, length); } - @Override public int writeBytes(InputStream src, int length) throws IOException { return buffer.writeBytes(src, length); } - @Override public int writerIndex() { return buffer.writerIndex(); } - @Override public void writerIndex(int writerIndex) { buffer.ensureWritable(writerIndex); buffer.writerIndex(writerIndex); } - @Override public int compareTo(ChannelBuffer o) { return ChannelBuffers.compare(this, o); diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java index 2ca031cdf4..41b7bb5f4c 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java @@ -16,11 +16,6 @@ */ package org.apache.dubbo.remoting.transport.netty4; -import io.netty.buffer.ByteBuf; -import io.netty.channel.Channel; -import io.netty.channel.ChannelFuture; -import io.netty.channel.ChannelFutureListener; -import io.netty.handler.codec.EncoderException; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -44,6 +39,12 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicBoolean; +import io.netty.buffer.ByteBuf; +import io.netty.channel.Channel; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelFutureListener; +import io.netty.handler.codec.EncoderException; + import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_ENCODE_IN_IO_THREAD; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.ENCODE_IN_IO_THREAD_KEY; @@ -60,7 +61,8 @@ final class NettyChannel extends AbstractChannel { /** * the cache for netty channel and dubbo channel */ - private static final ConcurrentMap CHANNEL_MAP = new ConcurrentHashMap(); + private static final ConcurrentMap CHANNEL_MAP = + new ConcurrentHashMap(); /** * netty channel */ @@ -223,11 +225,17 @@ final class NettyChannel extends AbstractChannel { } } catch (Throwable e) { removeChannelIfDisconnected(channel); - throw new RemotingException(this, "Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to " + getRemoteAddress() + ", cause: " + e.getMessage(), e); + throw new RemotingException( + this, + "Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to " + + getRemoteAddress() + ", cause: " + e.getMessage(), + e); } if (!success) { - throw new RemotingException(this, "Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to " + getRemoteAddress() - + "in timeout(" + timeout + "ms) limit"); + throw new RemotingException( + this, + "Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to " + + getRemoteAddress() + "in timeout(" + timeout + "ms) limit"); } } @@ -283,7 +291,6 @@ final class NettyChannel extends AbstractChannel { attributes.remove(key); } - @Override public int hashCode() { final int prime = 31; @@ -344,9 +351,9 @@ final class NettyChannel extends AbstractChannel { */ private static Response buildErrorResponse(Request request, Throwable t) { Response response = new Response(request.getId(), request.getVersion()); - if(t instanceof EncoderException){ + if (t instanceof EncoderException) { response.setStatus(Response.SERIALIZATION_ERROR); - }else{ + } else { response.setStatus(Response.BAD_REQUEST); } response.setErrorMessage(StringUtils.toString(t)); @@ -362,10 +369,10 @@ final class NettyChannel extends AbstractChannel { FrameworkModel frameworkModel = getFrameworkModel(url.getScopeModel()); if (frameworkModel.getExtensionLoader(Codec2.class).hasExtension(codecName)) { return frameworkModel.getExtensionLoader(Codec2.class).getExtension(codecName); - } else if(frameworkModel.getExtensionLoader(Codec.class).hasExtension(codecName)){ - return new CodecAdapter(frameworkModel.getExtensionLoader(Codec.class) - .getExtension(codecName)); - }else { + } else if (frameworkModel.getExtensionLoader(Codec.class).hasExtension(codecName)) { + return new CodecAdapter( + frameworkModel.getExtensionLoader(Codec.class).getExtension(codecName)); + } else { return frameworkModel.getExtensionLoader(Codec2.class).getExtension("default"); } } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannelHandler.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannelHandler.java index cfedb14371..6082db24a0 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannelHandler.java @@ -23,12 +23,12 @@ import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelInboundHandlerAdapter; - import java.net.InetSocketAddress; import java.util.Map; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; + public class NettyChannelHandler extends ChannelInboundHandlerAdapter { private static final Logger logger = LoggerFactory.getLogger(NettyChannelHandler.class); @@ -48,11 +48,13 @@ public class NettyChannelHandler extends ChannelInboundHandlerAdapter { super.channelActive(ctx); NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); if (channel != null) { - dubboChannels.put(NetUtils.toAddressString((InetSocketAddress) ctx.channel().remoteAddress()), channel); + dubboChannels.put( + NetUtils.toAddressString((InetSocketAddress) ctx.channel().remoteAddress()), channel); handler.connected(channel); if (logger.isInfoEnabled()) { - logger.info("The connection of " + channel.getRemoteAddress() + " -> " + channel.getLocalAddress() + " is established."); + logger.info("The connection of " + channel.getRemoteAddress() + " -> " + channel.getLocalAddress() + + " is established."); } } } @@ -62,16 +64,17 @@ public class NettyChannelHandler extends ChannelInboundHandlerAdapter { super.channelInactive(ctx); NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); try { - dubboChannels.remove(NetUtils.toAddressString((InetSocketAddress) ctx.channel().remoteAddress())); + dubboChannels.remove( + NetUtils.toAddressString((InetSocketAddress) ctx.channel().remoteAddress())); if (channel != null) { handler.disconnected(channel); if (logger.isInfoEnabled()) { - logger.info("The connection of " + channel.getRemoteAddress() + " -> " + channel.getLocalAddress() + " is disconnected."); + logger.info("The connection of " + channel.getRemoteAddress() + " -> " + channel.getLocalAddress() + + " is disconnected."); } } } finally { NettyChannel.removeChannel(ctx.channel()); } } - } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java index d175a84c0a..d01a481049 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClient.java @@ -33,6 +33,8 @@ import org.apache.dubbo.remoting.transport.netty4.ssl.SslClientTlsHandler; import org.apache.dubbo.remoting.transport.netty4.ssl.SslContexts; import org.apache.dubbo.remoting.utils.UrlUtils; +import java.net.InetSocketAddress; + import io.netty.bootstrap.Bootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.Channel; @@ -46,8 +48,6 @@ import io.netty.handler.ssl.SslContext; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.concurrent.EventExecutorGroup; -import java.net.InetSocketAddress; - import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_CLIENT_CONNECT_TIMEOUT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CONNECT_PROVIDER; @@ -72,9 +72,9 @@ public class NettyClient extends AbstractClient { /** * netty client bootstrap */ - private static final GlobalResourceInitializer EVENT_LOOP_GROUP = new GlobalResourceInitializer<>(() -> - eventLoopGroup(Constants.DEFAULT_IO_THREADS, "NettyClientWorker"), - EventExecutorGroup::shutdownGracefully); + private static final GlobalResourceInitializer EVENT_LOOP_GROUP = new GlobalResourceInitializer<>( + () -> eventLoopGroup(Constants.DEFAULT_IO_THREADS, "NettyClientWorker"), + EventExecutorGroup::shutdownGracefully); private Bootstrap bootstrap; @@ -90,7 +90,8 @@ public class NettyClient extends AbstractClient { * It wil init and start netty. */ public NettyClient(final URL url, final ChannelHandler handler) throws RemotingException { - // you can customize name and type of client thread pool by THREAD_NAME_KEY and THREADPOOL_KEY in CommonConstants. + // you can customize name and type of client thread pool by THREAD_NAME_KEY and THREADPOOL_KEY in + // CommonConstants. // the handler will be wrapped: MultiMessageHandler->HeartbeatHandler->handler super(url, wrapChannelHandler(url, handler)); } @@ -112,12 +113,13 @@ public class NettyClient extends AbstractClient { } protected void initBootstrap(NettyClientHandler nettyClientHandler) { - bootstrap.group(EVENT_LOOP_GROUP.get()) - .option(ChannelOption.SO_KEEPALIVE, true) - .option(ChannelOption.TCP_NODELAY, true) - .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) - //.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout()) - .channel(socketChannelClass()); + bootstrap + .group(EVENT_LOOP_GROUP.get()) + .option(ChannelOption.SO_KEEPALIVE, true) + .option(ChannelOption.TCP_NODELAY, true) + .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) + // .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout()) + .channel(socketChannelClass()); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Math.max(DEFAULT_CONNECT_TIMEOUT, getConnectTimeout())); SslContext sslContext = SslContexts.buildClientSslContext(getUrl()); @@ -132,16 +134,19 @@ public class NettyClient extends AbstractClient { } NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this); - ch.pipeline()//.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug - .addLast("decoder", adapter.getDecoder()) - .addLast("encoder", adapter.getEncoder()) - .addLast("client-idle-handler", new IdleStateHandler(heartbeatInterval, 0, 0, MILLISECONDS)) - .addLast("handler", nettyClientHandler); + ch.pipeline() // .addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug + .addLast("decoder", adapter.getDecoder()) + .addLast("encoder", adapter.getEncoder()) + .addLast("client-idle-handler", new IdleStateHandler(heartbeatInterval, 0, 0, MILLISECONDS)) + .addLast("handler", nettyClientHandler); - String socksProxyHost = ConfigurationUtils.getProperty(getUrl().getOrDefaultApplicationModel(), SOCKS_PROXY_HOST); + String socksProxyHost = + ConfigurationUtils.getProperty(getUrl().getOrDefaultApplicationModel(), SOCKS_PROXY_HOST); if (socksProxyHost != null && !isFilteredAddress(getUrl().getHost())) { - int socksProxyPort = Integer.parseInt(ConfigurationUtils.getProperty(getUrl().getOrDefaultApplicationModel(), SOCKS_PROXY_PORT, DEFAULT_SOCKS_PROXY_PORT)); - Socks5ProxyHandler socks5ProxyHandler = new Socks5ProxyHandler(new InetSocketAddress(socksProxyHost, socksProxyPort)); + int socksProxyPort = Integer.parseInt(ConfigurationUtils.getProperty( + getUrl().getOrDefaultApplicationModel(), SOCKS_PROXY_PORT, DEFAULT_SOCKS_PROXY_PORT)); + Socks5ProxyHandler socks5ProxyHandler = + new Socks5ProxyHandler(new InetSocketAddress(socksProxyHost, socksProxyPort)); ch.pipeline().addFirst(socks5ProxyHandler); } } @@ -158,14 +163,15 @@ public class NettyClient extends AbstractClient { try { String ipv6Address = NetUtils.getLocalHostV6(); InetSocketAddress connectAddress; - //first try ipv6 address + // first try ipv6 address if (ipv6Address != null && getUrl().getParameter(CommonConstants.IPV6_KEY) != null) { - connectAddress = new InetSocketAddress(getUrl().getParameter(CommonConstants.IPV6_KEY), getUrl().getPort()); + connectAddress = + new InetSocketAddress(getUrl().getParameter(CommonConstants.IPV6_KEY), getUrl().getPort()); try { doConnect(connectAddress); return; } catch (Throwable throwable) { - //ignore + // ignore } } @@ -174,7 +180,7 @@ public class NettyClient extends AbstractClient { } finally { // just add new valid channel to NettyChannel's cache if (!isConnected()) { - //future.cancel(true); + // future.cancel(true); } } } @@ -194,7 +200,8 @@ public class NettyClient extends AbstractClient { if (oldChannel != null) { try { if (logger.isInfoEnabled()) { - logger.info("Close old netty channel " + oldChannel + " on create new netty channel " + newChannel); + logger.info("Close old netty channel " + oldChannel + " on create new netty channel " + + newChannel); } oldChannel.close(); } finally { @@ -222,11 +229,18 @@ public class NettyClient extends AbstractClient { // 6-1 Failed to connect to provider server by other reason. - RemotingException remotingException = new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server " - + serverAddress + ", error message is:" + cause.getMessage(), cause); + RemotingException remotingException = new RemotingException( + this, + "client(url: " + getUrl() + ") failed to connect to server " + serverAddress + + ", error message is:" + cause.getMessage(), + cause); - logger.error(TRANSPORT_FAILED_CONNECT_PROVIDER, "network disconnected", "", - "Failed to connect to provider server by other reason.", cause); + logger.error( + TRANSPORT_FAILED_CONNECT_PROVIDER, + "network disconnected", + "", + "Failed to connect to provider server by other reason.", + cause); throw remotingException; @@ -234,20 +248,27 @@ public class NettyClient extends AbstractClient { // 6-2 Client-side timeout - RemotingException remotingException = new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server " - + serverAddress + " client-side timeout " - + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client " - + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()); + RemotingException remotingException = new RemotingException( + this, + "client(url: " + getUrl() + ") failed to connect to server " + + serverAddress + " client-side timeout " + + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + + "ms) from netty client " + + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()); - logger.error(TRANSPORT_CLIENT_CONNECT_TIMEOUT, "provider crash", "", - "Client-side timeout.", remotingException); + logger.error( + TRANSPORT_CLIENT_CONNECT_TIMEOUT, + "provider crash", + "", + "Client-side timeout.", + remotingException); throw remotingException; } } finally { // just add new valid channel to NettyChannel's cache if (!isConnected()) { - //future.cancel(true); + // future.cancel(true); } } } @@ -263,7 +284,8 @@ public class NettyClient extends AbstractClient { @Override protected void doClose() throws Throwable { - // can't shut down nioEventLoopGroup because the method will be invoked when closing one channel but not a client, + // can't shut down nioEventLoopGroup because the method will be invoked when closing one channel but not a + // client, // but when and how to close the nioEventLoopGroup ? // nioEventLoopGroup.shutdownGracefully(); } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClientHandler.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClientHandler.java index 0ab1c129fd..71c9f5ec0b 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClientHandler.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyClientHandler.java @@ -57,7 +57,8 @@ public class NettyClientHandler extends ChannelDuplexHandler { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); handler.connected(channel); if (logger.isInfoEnabled()) { - logger.info("The connection of " + channel.getLocalAddress() + " -> " + channel.getRemoteAddress() + " is established."); + logger.info("The connection of " + channel.getLocalAddress() + " -> " + channel.getRemoteAddress() + + " is established."); } } @@ -71,7 +72,8 @@ public class NettyClientHandler extends ChannelDuplexHandler { } if (logger.isInfoEnabled()) { - logger.info("The connection of " + channel.getLocalAddress() + " -> " + channel.getRemoteAddress() + " is disconnected."); + logger.info("The connection of " + channel.getLocalAddress() + " -> " + channel.getRemoteAddress() + + " is disconnected."); } } @@ -109,8 +111,7 @@ public class NettyClientHandler extends ChannelDuplexHandler { } @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) - throws Exception { + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); try { handler.caught(channel, cause); @@ -118,5 +119,4 @@ public class NettyClientHandler extends ChannelDuplexHandler { NettyChannel.removeChannelIfDisconnected(ctx.channel()); } } - } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyCodecAdapter.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyCodecAdapter.java index bf029272ab..6001213c78 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyCodecAdapter.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyCodecAdapter.java @@ -19,6 +19,10 @@ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.buffer.ChannelBuffer; +import org.apache.dubbo.remoting.exchange.support.MultiMessage; + +import java.io.IOException; +import java.util.List; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; @@ -26,15 +30,11 @@ import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.MessageToByteEncoder; -import org.apache.dubbo.remoting.exchange.support.MultiMessage; - -import java.io.IOException; -import java.util.List; /** * NettyCodecAdapter. */ -final public class NettyCodecAdapter { +public final class NettyCodecAdapter { private final ChannelHandler encoder = new InternalEncoder(); @@ -105,7 +105,7 @@ final public class NettyCodecAdapter { message.readerIndex(saveReaderIndex); break; } else { - //is it possible to go here ? + // is it possible to go here ? if (saveReaderIndex == message.readerIndex()) { throw new IOException("Decode without read data."); } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConfigOperator.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConfigOperator.java index 17df15cc4b..142e62de18 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConfigOperator.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConfigOperator.java @@ -55,22 +55,29 @@ public class NettyConfigOperator implements ChannelOperator { codecName = url.getProtocol(); } if (url.getOrDefaultFrameworkModel().getExtensionLoader(Codec2.class).hasExtension(codecName)) { - codec2 = url.getOrDefaultFrameworkModel().getExtensionLoader(Codec2.class).getExtension(codecName); - } else if (url.getOrDefaultFrameworkModel().getExtensionLoader(Codec.class).hasExtension(codecName)) { - codec2 = new CodecAdapter(url.getOrDefaultFrameworkModel().getExtensionLoader(Codec.class) - .getExtension(codecName)); + codec2 = url.getOrDefaultFrameworkModel() + .getExtensionLoader(Codec2.class) + .getExtension(codecName); + } else if (url.getOrDefaultFrameworkModel() + .getExtensionLoader(Codec.class) + .hasExtension(codecName)) { + codec2 = new CodecAdapter(url.getOrDefaultFrameworkModel() + .getExtensionLoader(Codec.class) + .getExtension(codecName)); } else { - codec2 = url.getOrDefaultFrameworkModel().getExtensionLoader(Codec2.class).getExtension("default"); + codec2 = url.getOrDefaultFrameworkModel() + .getExtensionLoader(Codec2.class) + .getExtension("default"); } if (!(codec2 instanceof DefaultCodec)) { ((NettyChannel) channel).setCodec(codec2); NettyCodecAdapter codec = new NettyCodecAdapter(codec2, channel.getUrl(), handler); - ((NettyChannel) channel).getNioChannel().pipeline().addLast( - codec.getDecoder() - ).addLast( - codec.getEncoder() - ); + ((NettyChannel) channel) + .getNioChannel() + .pipeline() + .addLast(codec.getDecoder()) + .addLast(codec.getEncoder()); } for (ChannelHandler handler : handlerList) { @@ -82,12 +89,10 @@ public class NettyConfigOperator implements ChannelOperator { // todo distinguish between client and server channel if (isClientSide(channel)) { - //todo config client channel handler + // todo config client channel handler } else { NettyServerHandler sh = new NettyServerHandler(channel.getUrl(), handler); - ((NettyChannel) channel).getNioChannel().pipeline().addLast( - sh - ); + ((NettyChannel) channel).getNioChannel().pipeline().addLast(sh); } } @@ -101,11 +106,8 @@ public class NettyConfigOperator implements ChannelOperator { } else { addChannelHandler(realHandler); } - - } - private void addChannelHandler(Object channelHandler) { if (!(channelHandler instanceof io.netty.channel.ChannelHandler)) { return; @@ -125,5 +127,4 @@ public class NettyConfigOperator implements ChannelOperator { private boolean isClientSide(Channel channel) { return channel.getUrl().getSide("").equalsIgnoreCase(CommonConstants.CONSUMER); } - } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConnectionClient.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConnectionClient.java index a86e9634c5..66e8c08416 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConnectionClient.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConnectionClient.java @@ -31,6 +31,10 @@ import org.apache.dubbo.remoting.transport.netty4.ssl.SslClientTlsHandler; import org.apache.dubbo.remoting.transport.netty4.ssl.SslContexts; import org.apache.dubbo.remoting.utils.UrlUtils; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; + import io.netty.bootstrap.Bootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.ChannelFuture; @@ -47,10 +51,6 @@ import io.netty.util.concurrent.DefaultPromise; import io.netty.util.concurrent.GlobalEventExecutor; import io.netty.util.concurrent.Promise; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_CLIENT_CONNECT_TIMEOUT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CONNECT_PROVIDER; @@ -59,7 +59,8 @@ import static org.apache.dubbo.remoting.transport.netty4.NettyEventLoopFactory.s public class NettyConnectionClient extends AbstractConnectionClient { - private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(NettyConnectionClient.class); + private static final ErrorTypeAwareLogger LOGGER = + LoggerFactory.getErrorTypeAwareLogger(NettyConnectionClient.class); private AtomicReference> connectingPromise; @@ -73,14 +74,15 @@ public class NettyConnectionClient extends AbstractConnectionClient { public static final AttributeKey CONNECTION = AttributeKey.valueOf("connection"); - public NettyConnectionClient(URL url, ChannelHandler handler) throws RemotingException { super(url, handler); } @Override protected void initConnectionClient() { - this.protocol = getUrl().getOrDefaultFrameworkModel().getExtensionLoader(WireProtocol.class).getExtension(getUrl().getProtocol()); + this.protocol = getUrl().getOrDefaultFrameworkModel() + .getExtensionLoader(WireProtocol.class) + .getExtension(getUrl().getProtocol()); this.remote = getConnectAddress(); this.connectingPromise = new AtomicReference<>(); this.connectionListener = new ConnectionListener(); @@ -98,7 +100,8 @@ public class NettyConnectionClient extends AbstractConnectionClient { private void initBootstrap() { final Bootstrap nettyBootstrap = new Bootstrap(); - nettyBootstrap.group(NettyEventLoopFactory.NIO_EVENT_LOOP_GROUP.get()) + nettyBootstrap + .group(NettyEventLoopFactory.NIO_EVENT_LOOP_GROUP.get()) .option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) @@ -119,7 +122,7 @@ public class NettyConnectionClient extends AbstractConnectionClient { pipeline.addLast("negotiation", new SslClientTlsHandler(sslContext)); } -// pipeline.addLast("logging", new LoggingHandler(LogLevel.INFO)); //for debug + // pipeline.addLast("logging", new LoggingHandler(LogLevel.INFO)); //for debug int heartbeat = UrlUtils.getHeartbeat(getUrl()); pipeline.addLast("client-idle-handler", new IdleStateHandler(heartbeat, 0, 0, MILLISECONDS)); @@ -155,8 +158,8 @@ public class NettyConnectionClient extends AbstractConnectionClient { protected void doConnect() throws RemotingException { if (isClosed()) { if (LOGGER.isDebugEnabled()) { - LOGGER.debug(String.format("%s aborted to reconnect cause connection closed. ", - NettyConnectionClient.this)); + LOGGER.debug( + String.format("%s aborted to reconnect cause connection closed. ", NettyConnectionClient.this)); } } init.compareAndSet(false, true); @@ -176,22 +179,32 @@ public class NettyConnectionClient extends AbstractConnectionClient { Throwable cause = promise.cause(); // 6-1 Failed to connect to provider server by other reason. - RemotingException remotingException = new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server " - + getConnectAddress() + ", error message is:" + cause.getMessage(), cause); + RemotingException remotingException = new RemotingException( + this, + "client(url: " + getUrl() + ") failed to connect to server " + getConnectAddress() + + ", error message is:" + cause.getMessage(), + cause); - LOGGER.error(TRANSPORT_FAILED_CONNECT_PROVIDER, "network disconnected", "", - "Failed to connect to provider server by other reason.", cause); + LOGGER.error( + TRANSPORT_FAILED_CONNECT_PROVIDER, + "network disconnected", + "", + "Failed to connect to provider server by other reason.", + cause); throw remotingException; } else if (!ret || !promise.isSuccess()) { // 6-2 Client-side timeout - RemotingException remotingException = new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server " - + getConnectAddress() + " client-side timeout " - + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client " - + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()); + RemotingException remotingException = new RemotingException( + this, + "client(url: " + getUrl() + ") failed to connect to server " + + getConnectAddress() + " client-side timeout " + + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + + "ms) from netty client " + + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()); - LOGGER.error(TRANSPORT_CLIENT_CONNECT_TIMEOUT, "provider crash", "", - "Client-side timeout.", remotingException); + LOGGER.error( + TRANSPORT_CLIENT_CONNECT_TIMEOUT, "provider crash", "", "Client-side timeout.", remotingException); throw remotingException; } @@ -285,7 +298,6 @@ public class NettyConnectionClient extends AbstractConnectionClient { nettyChannel = getNettyChannel(); return nettyChannel != null && nettyChannel.isActive(); - } @Override @@ -303,9 +315,10 @@ public class NettyConnectionClient extends AbstractConnectionClient { public ChannelFuture write(Object request) throws RemotingException { if (!isAvailable()) { - throw new RemotingException(null, null, - "Failed to send request " + request + ", cause: The channel to " + remote - + " is closed!"); + throw new RemotingException( + null, + null, + "Failed to send request " + request + ", cause: The channel to " + remote + " is closed!"); } return ((io.netty.channel.Channel) getChannel()).writeAndFlush(request); } @@ -322,8 +335,8 @@ public class NettyConnectionClient extends AbstractConnectionClient { @Override public String toString() { - return super.toString() + " (Ref=" + this.getCounter() + ",local=" + - (getChannel() == null ? null : getChannel().getLocalAddress()) + ",remote=" + getRemoteAddress(); + return super.toString() + " (Ref=" + this.getCounter() + ",local=" + + (getChannel() == null ? null : getChannel().getLocalAddress()) + ",remote=" + getRemoteAddress(); } class ConnectionListener implements ChannelFutureListener { @@ -336,23 +349,32 @@ public class NettyConnectionClient extends AbstractConnectionClient { final NettyConnectionClient connectionClient = NettyConnectionClient.this; if (connectionClient.isClosed() || connectionClient.getCounter() == 0) { if (LOGGER.isDebugEnabled()) { - LOGGER.debug(String.format("%s aborted to reconnect. %s", connectionClient, - future.cause().getMessage())); + LOGGER.debug(String.format( + "%s aborted to reconnect. %s", + connectionClient, future.cause().getMessage())); } return; } if (LOGGER.isDebugEnabled()) { - LOGGER.debug(String.format("%s is reconnecting, attempt=%d cause=%s", connectionClient, 0, - future.cause().getMessage())); + LOGGER.debug(String.format( + "%s is reconnecting, attempt=%d cause=%s", + connectionClient, 0, future.cause().getMessage())); } final EventLoop loop = future.channel().eventLoop(); - loop.schedule(() -> { - try { - connectionClient.doConnect(); - } catch (RemotingException e) { - LOGGER.error(TRANSPORT_FAILED_RECONNECT, "", "", "Failed to connect to server: " + getConnectAddress()); - } - }, 1L, TimeUnit.SECONDS); + loop.schedule( + () -> { + try { + connectionClient.doConnect(); + } catch (RemotingException e) { + LOGGER.error( + TRANSPORT_FAILED_RECONNECT, + "", + "", + "Failed to connect to server: " + getConnectAddress()); + } + }, + 1L, + TimeUnit.SECONDS); } } } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConnectionHandler.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConnectionHandler.java index 3ab6fbc8fc..c583cd3c89 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConnectionHandler.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConnectionHandler.java @@ -16,11 +16,12 @@ */ package org.apache.dubbo.remoting.transport.netty4; - import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.api.connection.ConnectionHandler; +import java.util.concurrent.TimeUnit; + import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; @@ -29,15 +30,14 @@ import io.netty.channel.EventLoop; import io.netty.util.Attribute; import io.netty.util.AttributeKey; -import java.util.concurrent.TimeUnit; - import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_RECONNECT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNEXPECTED_EXCEPTION; @ChannelHandler.Sharable public class NettyConnectionHandler extends ChannelInboundHandlerAdapter implements ConnectionHandler { - private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(NettyConnectionHandler.class); + private static final ErrorTypeAwareLogger LOGGER = + LoggerFactory.getErrorTypeAwareLogger(NettyConnectionHandler.class); private static final AttributeKey GO_AWAY_KEY = AttributeKey.valueOf("dubbo_channel_goaway"); private final NettyConnectionClient connectionClient; @@ -81,13 +81,21 @@ public class NettyConnectionHandler extends ChannelInboundHandlerAdapter impleme LOGGER.info("The client has been closed and will not reconnect. "); return; } - eventLoop.schedule(() -> { - try { - connectionClient.doConnect(); - } catch (Throwable e) { - LOGGER.error(TRANSPORT_FAILED_RECONNECT, "", "", "Fail to connect to " + connectionClient.getChannel(), e); - } - }, 1, TimeUnit.SECONDS); + eventLoop.schedule( + () -> { + try { + connectionClient.doConnect(); + } catch (Throwable e) { + LOGGER.error( + TRANSPORT_FAILED_RECONNECT, + "", + "", + "Fail to connect to " + connectionClient.getChannel(), + e); + } + }, + 1, + TimeUnit.SECONDS); } @Override @@ -97,14 +105,14 @@ public class NettyConnectionHandler extends ChannelInboundHandlerAdapter impleme if (!connectionClient.isClosed()) { connectionClient.onConnected(ctx.channel()); if (LOGGER.isInfoEnabled()) { - LOGGER.info("The connection of " + channel.getLocalAddress() + " -> " + channel.getRemoteAddress() + " is established."); + LOGGER.info("The connection of " + channel.getLocalAddress() + " -> " + channel.getRemoteAddress() + + " is established."); } } else { ctx.close(); } } - @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { LOGGER.warn(TRANSPORT_UNEXPECTED_EXCEPTION, "", "", String.format("Channel error:%s", ctx.channel()), cause); @@ -119,5 +127,4 @@ public class NettyConnectionHandler extends ChannelInboundHandlerAdapter impleme reconnect(ctx.channel()); } } - } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyEventLoopFactory.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyEventLoopFactory.java index 2db6f9697e..ad3c807cf6 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyEventLoopFactory.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyEventLoopFactory.java @@ -19,6 +19,8 @@ package org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.resource.GlobalResourceInitializer; import org.apache.dubbo.remoting.Constants; +import java.util.concurrent.ThreadFactory; + import io.netty.channel.EventLoopGroup; import io.netty.channel.epoll.Epoll; import io.netty.channel.epoll.EpollEventLoopGroup; @@ -31,8 +33,6 @@ import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.util.concurrent.DefaultThreadFactory; -import java.util.concurrent.ThreadFactory; - import static org.apache.dubbo.common.constants.CommonConstants.OS_LINUX_PREFIX; import static org.apache.dubbo.common.constants.CommonConstants.OS_NAME_KEY; import static org.apache.dubbo.remoting.Constants.NETTY_EPOLL_ENABLE_KEY; @@ -41,15 +41,16 @@ public class NettyEventLoopFactory { /** * netty client bootstrap */ - public static final GlobalResourceInitializer NIO_EVENT_LOOP_GROUP = new GlobalResourceInitializer<>(() -> - eventLoopGroup(Constants.DEFAULT_IO_THREADS, "NettyClientWorker"), - eventLoopGroup -> eventLoopGroup.shutdownGracefully() - ); + public static final GlobalResourceInitializer NIO_EVENT_LOOP_GROUP = + new GlobalResourceInitializer<>( + () -> eventLoopGroup(Constants.DEFAULT_IO_THREADS, "NettyClientWorker"), + eventLoopGroup -> eventLoopGroup.shutdownGracefully()); public static EventLoopGroup eventLoopGroup(int threads, String threadFactoryName) { ThreadFactory threadFactory = new DefaultThreadFactory(threadFactoryName, true); - return shouldEpoll() ? new EpollEventLoopGroup(threads, threadFactory) : - new NioEventLoopGroup(threads, threadFactory); + return shouldEpoll() + ? new EpollEventLoopGroup(threads, threadFactory) + : new NioEventLoopGroup(threads, threadFactory); } public static Class socketChannelClass() { diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServer.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServer.java index a7cab7b985..eaaab27f71 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServer.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServer.java @@ -30,6 +30,12 @@ import org.apache.dubbo.remoting.api.WireProtocol; import org.apache.dubbo.remoting.api.pu.AbstractPortUnificationServer; import org.apache.dubbo.remoting.transport.dispatcher.ChannelHandlers; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.ChannelFuture; @@ -40,12 +46,6 @@ import io.netty.channel.EventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.util.concurrent.Future; -import java.net.InetSocketAddress; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; @@ -59,7 +59,8 @@ import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_WORKER_POOL_NAME; */ public class NettyPortUnificationServer extends AbstractPortUnificationServer { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NettyPortUnificationServer.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(NettyPortUnificationServer.class); private final int serverShutdownTimeoutMills; /** @@ -70,19 +71,19 @@ public class NettyPortUnificationServer extends AbstractPortUnificationServer { * the boss channel that receive connections and dispatch these to worker channel. */ private io.netty.channel.Channel channel; + private EventLoopGroup bossGroup; private EventLoopGroup workerGroup; private final Map dubboChannels = new ConcurrentHashMap<>(); - public NettyPortUnificationServer(URL url, ChannelHandler handler) throws RemotingException { super(url, ChannelHandlers.wrap(handler, url)); - // you can customize name and type of client thread pool by THREAD_NAME_KEY and THREADPOOL_KEY in CommonConstants. + // you can customize name and type of client thread pool by THREAD_NAME_KEY and THREADPOOL_KEY in + // CommonConstants. // the handler will be wrapped: MultiMessageHandler->HeartbeatHandler->handler // read config before destroy - serverShutdownTimeoutMills = ConfigurationUtils.getServerShutdownTimeout( - getUrl().getOrDefaultModuleModel()); + serverShutdownTimeoutMills = ConfigurationUtils.getServerShutdownTimeout(getUrl().getOrDefaultModuleModel()); } @Override @@ -109,27 +110,33 @@ public class NettyPortUnificationServer extends AbstractPortUnificationServer { bossGroup = NettyEventLoopFactory.eventLoopGroup(1, EVENT_LOOP_BOSS_POOL_NAME); workerGroup = NettyEventLoopFactory.eventLoopGroup( - getUrl().getPositiveParameter(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS), - EVENT_LOOP_WORKER_POOL_NAME); + getUrl().getPositiveParameter(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS), + EVENT_LOOP_WORKER_POOL_NAME); - bootstrap.group(bossGroup, workerGroup) - .channel(NettyEventLoopFactory.serverSocketChannelClass()) - .option(ChannelOption.SO_REUSEADDR, Boolean.TRUE) - .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE) - .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) - .childHandler(new ChannelInitializer() { - @Override - protected void initChannel(SocketChannel ch) throws Exception { - // Do not add idle state handler here, because it should be added in the protocol handler. - final ChannelPipeline p = ch.pipeline(); - NettyChannelHandler nettyChannelHandler = new NettyChannelHandler(dubboChannels, getUrl(), NettyPortUnificationServer.this); - NettyPortUnificationServerHandler puHandler = new NettyPortUnificationServerHandler(getUrl(), true, getProtocols(), - NettyPortUnificationServer.this, - getSupportedUrls(), getSupportedHandlers()); - p.addLast("channel-handler", nettyChannelHandler); - p.addLast("negotiation-protocol", puHandler); - } - }); + bootstrap + .group(bossGroup, workerGroup) + .channel(NettyEventLoopFactory.serverSocketChannelClass()) + .option(ChannelOption.SO_REUSEADDR, Boolean.TRUE) + .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE) + .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel ch) throws Exception { + // Do not add idle state handler here, because it should be added in the protocol handler. + final ChannelPipeline p = ch.pipeline(); + NettyChannelHandler nettyChannelHandler = + new NettyChannelHandler(dubboChannels, getUrl(), NettyPortUnificationServer.this); + NettyPortUnificationServerHandler puHandler = new NettyPortUnificationServerHandler( + getUrl(), + true, + getProtocols(), + NettyPortUnificationServer.this, + getSupportedUrls(), + getSupportedHandlers()); + p.addLast("channel-handler", nettyChannelHandler); + p.addLast("negotiation-protocol", puHandler); + } + }); // bind String bindIp = getUrl().getParameter(Constants.BIND_IP_KEY, getUrl().getHost()); @@ -153,10 +160,9 @@ public class NettyPortUnificationServer extends AbstractPortUnificationServer { if (bootstrap != null) { long timeout = ConfigurationUtils.reCalShutdownTime(serverShutdownTimeoutMills); long quietPeriod = Math.min(2000L, timeout); - Future bossGroupShutdownFuture = bossGroup.shutdownGracefully(quietPeriod, - timeout, MILLISECONDS); - Future workerGroupShutdownFuture = workerGroup.shutdownGracefully(quietPeriod, - timeout, MILLISECONDS); + Future bossGroupShutdownFuture = bossGroup.shutdownGracefully(quietPeriod, timeout, MILLISECONDS); + Future workerGroupShutdownFuture = + workerGroup.shutdownGracefully(quietPeriod, timeout, MILLISECONDS); bossGroupShutdownFuture.awaitUninterruptibly(timeout, MILLISECONDS); workerGroupShutdownFuture.awaitUninterruptibly(timeout, MILLISECONDS); } @@ -230,5 +236,4 @@ public class NettyPortUnificationServer extends AbstractPortUnificationServer { public boolean canHandleIdle() { return true; } - } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServerHandler.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServerHandler.java index 1741e298c2..4969cf1d2d 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServerHandler.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationServerHandler.java @@ -28,6 +28,12 @@ import org.apache.dubbo.remoting.api.WireProtocol; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.transport.netty4.ssl.SslContexts; +import javax.net.ssl.SSLSession; + +import java.util.List; +import java.util.Map; +import java.util.Set; + import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; @@ -36,17 +42,12 @@ import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.SslHandshakeCompletionEvent; -import javax.net.ssl.SSLSession; -import java.util.List; -import java.util.Map; -import java.util.Set; - import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; public class NettyPortUnificationServerHandler extends ByteToMessageDecoder { - private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger( - NettyPortUnificationServerHandler.class); + private static final ErrorTypeAwareLogger LOGGER = + LoggerFactory.getErrorTypeAwareLogger(NettyPortUnificationServerHandler.class); private final URL url; private final ChannelHandler handler; private final boolean detectSsl; @@ -54,10 +55,13 @@ public class NettyPortUnificationServerHandler extends ByteToMessageDecoder { private final Map urlMapper; private final Map handlerMapper; - - public NettyPortUnificationServerHandler(URL url, boolean detectSsl, - List protocols, ChannelHandler handler, - Map urlMapper, Map handlerMapper) { + public NettyPortUnificationServerHandler( + URL url, + boolean detectSsl, + List protocols, + ChannelHandler handler, + Map urlMapper, + Map handlerMapper) { this.url = url; this.protocols = protocols; this.detectSsl = detectSsl; @@ -68,7 +72,12 @@ public class NettyPortUnificationServerHandler extends ByteToMessageDecoder { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - LOGGER.error(INTERNAL_ERROR, "unknown error in remoting module", "", "Unexpected exception from downstream before protocol detected.", cause); + LOGGER.error( + INTERNAL_ERROR, + "unknown error in remoting module", + "", + "Unexpected exception from downstream before protocol detected.", + cause); } @Override @@ -76,10 +85,16 @@ public class NettyPortUnificationServerHandler extends ByteToMessageDecoder { if (evt instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt; if (handshakeEvent.isSuccess()) { - SSLSession session = ctx.pipeline().get(SslHandler.class).engine().getSession(); + SSLSession session = + ctx.pipeline().get(SslHandler.class).engine().getSession(); LOGGER.info("TLS negotiation succeed with session: " + session); } else { - LOGGER.error(INTERNAL_ERROR, "", "", "TLS negotiation failed when trying to accept new connection.", handshakeEvent.cause()); + LOGGER.error( + INTERNAL_ERROR, + "", + "", + "TLS negotiation failed when trying to accept new connection.", + handshakeEvent.cause()); ctx.close(); } } @@ -87,8 +102,7 @@ public class NettyPortUnificationServerHandler extends ByteToMessageDecoder { } @Override - protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) - throws Exception { + protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); // Will use the first five bytes to detect a protocol. // size of telnet command ls is 2 bytes @@ -96,8 +110,10 @@ public class NettyPortUnificationServerHandler extends ByteToMessageDecoder { return; } - CertManager certManager = url.getOrDefaultFrameworkModel().getBeanFactory().getBean(CertManager.class); - ProviderCert providerConnectionConfig = certManager.getProviderConnectionConfig(url, ctx.channel().remoteAddress()); + CertManager certManager = + url.getOrDefaultFrameworkModel().getBeanFactory().getBean(CertManager.class); + ProviderCert providerConnectionConfig = + certManager.getProviderConnectionConfig(url, ctx.channel().remoteAddress()); if (providerConnectionConfig != null && isSsl(in)) { enableSsl(ctx, providerConnectionConfig); @@ -112,8 +128,9 @@ public class NettyPortUnificationServerHandler extends ByteToMessageDecoder { case UNRECOGNIZED: continue; case RECOGNIZED: - String protocolName = url.getOrDefaultFrameworkModel().getExtensionLoader(WireProtocol.class) - .getExtensionName(protocol); + String protocolName = url.getOrDefaultFrameworkModel() + .getExtensionLoader(WireProtocol.class) + .getExtensionName(protocol); ChannelHandler localHandler = this.handlerMapper.getOrDefault(protocolName, handler); URL localURL = this.urlMapper.getOrDefault(protocolName, url); channel.setUrl(localURL); @@ -130,12 +147,15 @@ public class NettyPortUnificationServerHandler extends ByteToMessageDecoder { byte[] preface = new byte[in.readableBytes()]; in.readBytes(preface); Set supported = url.getApplicationModel() - .getExtensionLoader(WireProtocol.class) - .getSupportedExtensions(); - LOGGER.error(INTERNAL_ERROR, "unknown error in remoting module", "", String.format("Can not recognize protocol from downstream=%s . " - + "preface=%s protocols=%s", ctx.channel().remoteAddress(), - Bytes.bytes2hex(preface), - supported)); + .getExtensionLoader(WireProtocol.class) + .getSupportedExtensions(); + LOGGER.error( + INTERNAL_ERROR, + "unknown error in remoting module", + "", + String.format( + "Can not recognize protocol from downstream=%s . " + "preface=%s protocols=%s", + ctx.channel().remoteAddress(), Bytes.bytes2hex(preface), supported)); // Unknown protocol; discard everything and close the connection. in.clear(); @@ -147,9 +167,9 @@ public class NettyPortUnificationServerHandler extends ByteToMessageDecoder { ChannelPipeline p = ctx.pipeline(); SslContext sslContext = SslContexts.buildServerSslContext(providerConnectionConfig); p.addLast("ssl", sslContext.newHandler(ctx.alloc())); - p.addLast("unificationA", - new NettyPortUnificationServerHandler(url, false, protocols, - handler, urlMapper, handlerMapper)); + p.addLast( + "unificationA", + new NettyPortUnificationServerHandler(url, false, protocols, handler, urlMapper, handlerMapper)); p.remove(this); } @@ -160,6 +180,4 @@ public class NettyPortUnificationServerHandler extends ByteToMessageDecoder { } return false; } - - } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationTransporter.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationTransporter.java index f75375b533..03ff97fc29 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationTransporter.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyPortUnificationTransporter.java @@ -36,7 +36,9 @@ public class NettyPortUnificationTransporter implements PortUnificationTransport @Override public AbstractConnectionClient connect(URL url, ChannelHandler handler) throws RemotingException { - ConnectionManager manager = url.getOrDefaultFrameworkModel().getExtensionLoader(ConnectionManager.class).getExtension(MultiplexProtocolConnectionManager.NAME); + ConnectionManager manager = url.getOrDefaultFrameworkModel() + .getExtensionLoader(ConnectionManager.class) + .getExtension(MultiplexProtocolConnectionManager.NAME); return manager.connect(url, handler); } } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java index d165651858..9f5bd0a075 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java @@ -36,6 +36,12 @@ import org.apache.dubbo.remoting.transport.netty4.ssl.SslServerTlsHandler; import org.apache.dubbo.remoting.utils.UrlUtils; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.ChannelFuture; @@ -46,12 +52,6 @@ import io.netty.channel.socket.SocketChannel; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.concurrent.Future; -import java.net.InetSocketAddress; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.KEEP_ALIVE_KEY; @@ -59,7 +59,6 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FA import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_BOSS_POOL_NAME; import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_WORKER_POOL_NAME; - /** * NettyServer. */ @@ -85,7 +84,8 @@ public class NettyServer extends AbstractServer { private final int serverShutdownTimeoutMills; public NettyServer(URL url, ChannelHandler handler) throws RemotingException { - // you can customize name and type of client thread pool by THREAD_NAME_KEY and THREAD_POOL_KEY in CommonConstants. + // you can customize name and type of client thread pool by THREAD_NAME_KEY and THREAD_POOL_KEY in + // CommonConstants. // the handler will be wrapped: MultiMessageHandler->HeartbeatHandler->handler super(url, ChannelHandlers.wrap(handler, url)); @@ -125,14 +125,24 @@ public class NettyServer extends AbstractServer { ApplicationModel applicationModel = ApplicationModel.defaultModel(); MetricsEventBus.post(NettyEvent.toNettyEvent(applicationModel), () -> { Map dataMap = new HashMap<>(); - dataMap.put(MetricsKey.NETTY_ALLOCATOR_HEAP_MEMORY_USED.getName(), PooledByteBufAllocator.DEFAULT.metric().usedHeapMemory()); - dataMap.put(MetricsKey.NETTY_ALLOCATOR_DIRECT_MEMORY_USED.getName(), PooledByteBufAllocator.DEFAULT.metric().usedDirectMemory()); - dataMap.put(MetricsKey.NETTY_ALLOCATOR_HEAP_ARENAS_NUM.getName(), (long) PooledByteBufAllocator.DEFAULT.numHeapArenas()); - dataMap.put(MetricsKey.NETTY_ALLOCATOR_DIRECT_ARENAS_NUM.getName(), (long) PooledByteBufAllocator.DEFAULT.numDirectArenas()); - dataMap.put(MetricsKey.NETTY_ALLOCATOR_NORMAL_CACHE_SIZE.getName(), (long) PooledByteBufAllocator.DEFAULT.normalCacheSize()); - dataMap.put(MetricsKey.NETTY_ALLOCATOR_SMALL_CACHE_SIZE.getName(), (long) PooledByteBufAllocator.DEFAULT.smallCacheSize()); - dataMap.put(MetricsKey.NETTY_ALLOCATOR_THREAD_LOCAL_CACHES_NUM.getName(), (long) PooledByteBufAllocator.DEFAULT.numThreadLocalCaches()); - dataMap.put(MetricsKey.NETTY_ALLOCATOR_CHUNK_SIZE.getName(), (long) PooledByteBufAllocator.DEFAULT.chunkSize()); + dataMap.put( + MetricsKey.NETTY_ALLOCATOR_HEAP_MEMORY_USED.getName(), + PooledByteBufAllocator.DEFAULT.metric().usedHeapMemory()); + dataMap.put( + MetricsKey.NETTY_ALLOCATOR_DIRECT_MEMORY_USED.getName(), + PooledByteBufAllocator.DEFAULT.metric().usedDirectMemory()); + dataMap.put(MetricsKey.NETTY_ALLOCATOR_HEAP_ARENAS_NUM.getName(), (long) + PooledByteBufAllocator.DEFAULT.numHeapArenas()); + dataMap.put(MetricsKey.NETTY_ALLOCATOR_DIRECT_ARENAS_NUM.getName(), (long) + PooledByteBufAllocator.DEFAULT.numDirectArenas()); + dataMap.put(MetricsKey.NETTY_ALLOCATOR_NORMAL_CACHE_SIZE.getName(), (long) + PooledByteBufAllocator.DEFAULT.normalCacheSize()); + dataMap.put(MetricsKey.NETTY_ALLOCATOR_SMALL_CACHE_SIZE.getName(), (long) + PooledByteBufAllocator.DEFAULT.smallCacheSize()); + dataMap.put(MetricsKey.NETTY_ALLOCATOR_THREAD_LOCAL_CACHES_NUM.getName(), (long) + PooledByteBufAllocator.DEFAULT.numThreadLocalCaches()); + dataMap.put(MetricsKey.NETTY_ALLOCATOR_CHUNK_SIZE.getName(), (long) + PooledByteBufAllocator.DEFAULT.chunkSize()); return dataMap; }); } @@ -148,8 +158,8 @@ public class NettyServer extends AbstractServer { protected EventLoopGroup createWorkerGroup() { return NettyEventLoopFactory.eventLoopGroup( - getUrl().getPositiveParameter(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS), - EVENT_LOOP_WORKER_POOL_NAME); + getUrl().getPositiveParameter(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS), + EVENT_LOOP_WORKER_POOL_NAME); } protected NettyServerHandler createNettyServerHandler() { @@ -158,25 +168,26 @@ public class NettyServer extends AbstractServer { protected void initServerBootstrap(NettyServerHandler nettyServerHandler) { boolean keepalive = getUrl().getParameter(KEEP_ALIVE_KEY, Boolean.FALSE); - bootstrap.group(bossGroup, workerGroup) - .channel(NettyEventLoopFactory.serverSocketChannelClass()) - .option(ChannelOption.SO_REUSEADDR, Boolean.TRUE) - .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE) - .childOption(ChannelOption.SO_KEEPALIVE, keepalive) - .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) - .childHandler(new ChannelInitializer() { - @Override - protected void initChannel(SocketChannel ch) throws Exception { - int closeTimeout = UrlUtils.getCloseTimeout(getUrl()); - NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this); - ch.pipeline().addLast("negotiation", new SslServerTlsHandler(getUrl())); - ch.pipeline() - .addLast("decoder", adapter.getDecoder()) - .addLast("encoder", adapter.getEncoder()) - .addLast("server-idle-handler", new IdleStateHandler(0, 0, closeTimeout, MILLISECONDS)) - .addLast("handler", nettyServerHandler); - } - }); + bootstrap + .group(bossGroup, workerGroup) + .channel(NettyEventLoopFactory.serverSocketChannelClass()) + .option(ChannelOption.SO_REUSEADDR, Boolean.TRUE) + .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE) + .childOption(ChannelOption.SO_KEEPALIVE, keepalive) + .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel ch) throws Exception { + int closeTimeout = UrlUtils.getCloseTimeout(getUrl()); + NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this); + ch.pipeline().addLast("negotiation", new SslServerTlsHandler(getUrl())); + ch.pipeline() + .addLast("decoder", adapter.getDecoder()) + .addLast("encoder", adapter.getEncoder()) + .addLast("server-idle-handler", new IdleStateHandler(0, 0, closeTimeout, MILLISECONDS)) + .addLast("handler", nettyServerHandler); + } + }); } @Override @@ -219,7 +230,8 @@ public class NettyServer extends AbstractServer { long timeout = ConfigurationUtils.reCalShutdownTime(serverShutdownTimeoutMills); long quietPeriod = Math.min(2000L, timeout); Future bossGroupShutdownFuture = bossGroup.shutdownGracefully(quietPeriod, timeout, MILLISECONDS); - Future workerGroupShutdownFuture = workerGroup.shutdownGracefully(quietPeriod, timeout, MILLISECONDS); + Future workerGroupShutdownFuture = + workerGroup.shutdownGracefully(quietPeriod, timeout, MILLISECONDS); bossGroupShutdownFuture.syncUninterruptibly(); workerGroupShutdownFuture.syncUninterruptibly(); } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServerHandler.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServerHandler.java index 7ea3733120..1eff7fc84b 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServerHandler.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServerHandler.java @@ -23,15 +23,15 @@ import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; +import java.net.InetSocketAddress; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.handler.timeout.IdleStateEvent; -import java.net.InetSocketAddress; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - /** * NettyServerHandler. */ @@ -67,12 +67,14 @@ public class NettyServerHandler extends ChannelDuplexHandler { public void channelActive(ChannelHandlerContext ctx) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); if (channel != null) { - channels.put(NetUtils.toAddressString((InetSocketAddress) ctx.channel().remoteAddress()), channel); + channels.put( + NetUtils.toAddressString((InetSocketAddress) ctx.channel().remoteAddress()), channel); } handler.connected(channel); if (logger.isInfoEnabled()) { - logger.info("The connection of " + channel.getRemoteAddress() + " -> " + channel.getLocalAddress() + " is established."); + logger.info("The connection of " + channel.getRemoteAddress() + " -> " + channel.getLocalAddress() + + " is established."); } } @@ -80,14 +82,16 @@ public class NettyServerHandler extends ChannelDuplexHandler { public void channelInactive(ChannelHandlerContext ctx) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); try { - channels.remove(NetUtils.toAddressString((InetSocketAddress) ctx.channel().remoteAddress())); + channels.remove( + NetUtils.toAddressString((InetSocketAddress) ctx.channel().remoteAddress())); handler.disconnected(channel); } finally { NettyChannel.removeChannel(ctx.channel()); } if (logger.isInfoEnabled()) { - logger.info("The connection of " + channel.getRemoteAddress() + " -> " + channel.getLocalAddress() + " is disconnected."); + logger.info("The connection of " + channel.getRemoteAddress() + " -> " + channel.getLocalAddress() + + " is disconnected."); } } @@ -99,7 +103,6 @@ public class NettyServerHandler extends ChannelDuplexHandler { ctx.fireChannelRead(msg); } - @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { super.write(ctx, msg, promise); @@ -123,8 +126,7 @@ public class NettyServerHandler extends ChannelDuplexHandler { } @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) - throws Exception { + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); try { handler.caught(channel, cause); @@ -132,5 +134,4 @@ public class NettyServerHandler extends ChannelDuplexHandler { NettyChannel.removeChannelIfDisconnected(ctx.channel()); } } - } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettySslContextOperator.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettySslContextOperator.java index e1f7f52396..38873bb406 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettySslContextOperator.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettySslContextOperator.java @@ -16,9 +16,10 @@ */ package org.apache.dubbo.remoting.transport.netty4; -import io.netty.handler.ssl.SslContext; import org.apache.dubbo.remoting.api.ssl.ContextOperator; +import io.netty.handler.ssl.SslContext; + public class NettySslContextOperator implements ContextOperator { @Override diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporter.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporter.java index 78e334b761..0743e4d374 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporter.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporter.java @@ -39,5 +39,4 @@ public class NettyTransporter implements Transporter { public Client connect(URL url, ChannelHandler handler) throws RemotingException { return new NettyClient(url, handler); } - } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/aot/Netty4ReflectionTypeDescriberRegistrar.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/aot/Netty4ReflectionTypeDescriberRegistrar.java index 829a23a8e0..47d9972bc8 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/aot/Netty4ReflectionTypeDescriberRegistrar.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/aot/Netty4ReflectionTypeDescriberRegistrar.java @@ -33,7 +33,6 @@ import java.util.HashSet; import java.util.List; import java.util.Set; - public class Netty4ReflectionTypeDescriberRegistrar implements ReflectionTypeDescriberRegistrar { @Override @@ -53,6 +52,7 @@ public class Netty4ReflectionTypeDescriberRegistrar implements ReflectionTypeDes private TypeDescriber buildTypeDescriberWithPublicMethod(Class cl) { Set memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.INVOKE_PUBLIC_METHODS); - return new TypeDescriber(cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); + return new TypeDescriber( + cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/FormattingTuple.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/FormattingTuple.java index eac0a47494..a66efb40e0 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/FormattingTuple.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/FormattingTuple.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.transport.netty4.logging; - import org.apache.dubbo.common.utils.ArrayUtils; /** diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/MessageFormatter.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/MessageFormatter.java index 5c98405ddf..a8f3c302c5 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/MessageFormatter.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/MessageFormatter.java @@ -116,7 +116,7 @@ final class MessageFormatter { * @return The formatted message */ static FormattingTuple format(String messagePattern, Object arg) { - return arrayFormat(messagePattern, new Object[]{arg}); + return arrayFormat(messagePattern, new Object[] {arg}); } /** @@ -138,9 +138,8 @@ final class MessageFormatter { * anchor * @return The formatted message */ - static FormattingTuple format(final String messagePattern, - Object argA, Object argB) { - return arrayFormat(messagePattern, new Object[]{argA, argB}); + static FormattingTuple format(final String messagePattern, Object argA, Object argB) { + return arrayFormat(messagePattern, new Object[] {argA, argB}); } static Throwable getThrowableCandidate(Object[] argArray) { @@ -165,8 +164,7 @@ final class MessageFormatter { * anchors * @return The formatted message */ - static FormattingTuple arrayFormat(final String messagePattern, - final Object[] argArray) { + static FormattingTuple arrayFormat(final String messagePattern, final Object[] argArray) { Throwable throwableCandidate = getThrowableCandidate(argArray); @@ -190,13 +188,11 @@ final class MessageFormatter { if (j == -1) { // no more variables if (i == 0) { // this is a simple string - return new FormattingTuple(messagePattern, argArray, - throwableCandidate); + return new FormattingTuple(messagePattern, argArray, throwableCandidate); } else { // add the tail string which contains no variables and return // the result. sbuf.append(messagePattern.substring(i)); - return new FormattingTuple(sbuf.toString(), argArray, - throwableCandidate); + return new FormattingTuple(sbuf.toString(), argArray, throwableCandidate); } } else { if (isEscapedDelimeter(messagePattern, j)) { @@ -230,8 +226,7 @@ final class MessageFormatter { } } - static boolean isEscapedDelimeter(String messagePattern, - int delimeterStartIndex) { + static boolean isEscapedDelimeter(String messagePattern, int delimeterStartIndex) { if (delimeterStartIndex == 0) { return false; @@ -239,14 +234,12 @@ final class MessageFormatter { return messagePattern.charAt(delimeterStartIndex - 1) == ESCAPE_CHAR; } - static boolean isDoubleEscaped(String messagePattern, - int delimeterStartIndex) { + static boolean isDoubleEscaped(String messagePattern, int delimeterStartIndex) { return delimeterStartIndex >= 2 && messagePattern.charAt(delimeterStartIndex - 2) == ESCAPE_CHAR; } // special treatment of array values was suggested by 'lizongbo' - private static void deeplyAppendParameter(StringBuffer sbuf, Object o, - Map seenMap) { + private static void deeplyAppendParameter(StringBuffer sbuf, Object o, Map seenMap) { if (o == null) { sbuf.append("null"); return; @@ -283,16 +276,14 @@ final class MessageFormatter { String oAsString = o.toString(); sbuf.append(oAsString); } catch (Throwable t) { - System.err - .println("SLF4J: Failed toString() invocation on an object of type [" + System.err.println("SLF4J: Failed toString() invocation on an object of type [" + o.getClass().getName() + ']'); logger.error(TRANSPORT_UNSUPPORTED_MESSAGE, "", "", t.getMessage(), t); sbuf.append("[FAILED toString()]"); } } - private static void objectArrayAppend(StringBuffer sbuf, Object[] a, - Map seenMap) { + private static void objectArrayAppend(StringBuffer sbuf, Object[] a, Map seenMap) { sbuf.append('['); if (!seenMap.containsKey(a)) { seenMap.put(a, null); @@ -407,6 +398,5 @@ final class MessageFormatter { sbuf.append(']'); } - private MessageFormatter() { - } + private MessageFormatter() {} } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslClientTlsHandler.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslClientTlsHandler.java index 4c0ea5dd63..9918d171ee 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslClientTlsHandler.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslClientTlsHandler.java @@ -20,18 +20,17 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLSession; + import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.SslHandshakeCompletionEvent; -import javax.net.ssl.SSLEngine; -import javax.net.ssl.SSLSession; - import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; - public class SslClientTlsHandler extends ChannelInboundHandlerAdapter { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SslClientTlsHandler.class); @@ -57,11 +56,17 @@ public class SslClientTlsHandler extends ChannelInboundHandlerAdapter { if (evt instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt; if (handshakeEvent.isSuccess()) { - SSLSession session = ctx.pipeline().get(SslHandler.class).engine().getSession(); + SSLSession session = + ctx.pipeline().get(SslHandler.class).engine().getSession(); logger.info("TLS negotiation succeed with: " + session.getPeerHost()); ctx.pipeline().remove(this); } else { - logger.error(INTERNAL_ERROR, "unknown error in remoting module", "", "TLS negotiation failed when trying to accept new connection.", handshakeEvent.cause()); + logger.error( + INTERNAL_ERROR, + "unknown error in remoting module", + "", + "TLS negotiation failed when trying to accept new connection.", + handshakeEvent.cause()); ctx.fireExceptionCaught(handshakeEvent.cause()); } } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslContexts.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslContexts.java index ec07ad4e03..beb7e61142 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslContexts.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslContexts.java @@ -24,18 +24,19 @@ import org.apache.dubbo.common.ssl.Cert; import org.apache.dubbo.common.ssl.CertManager; import org.apache.dubbo.common.ssl.ProviderCert; +import javax.net.ssl.SSLException; + +import java.io.IOException; +import java.io.InputStream; +import java.security.Provider; +import java.security.Security; + import io.netty.handler.ssl.ClientAuth; import io.netty.handler.ssl.OpenSsl; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslProvider; -import javax.net.ssl.SSLException; -import java.io.IOException; -import java.io.InputStream; -import java.security.Provider; -import java.security.Security; - import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE_STREAM; public class SslContexts { @@ -53,11 +54,11 @@ public class SslContexts { serverTrustCertStream = providerConnectionConfig.getTrustCertInputStream(); String password = providerConnectionConfig.getPassword(); if (password != null) { - sslClientContextBuilder = SslContextBuilder.forServer(serverKeyCertChainPathStream, - serverPrivateKeyPathStream, password); + sslClientContextBuilder = + SslContextBuilder.forServer(serverKeyCertChainPathStream, serverPrivateKeyPathStream, password); } else { - sslClientContextBuilder = SslContextBuilder.forServer(serverKeyCertChainPathStream, - serverPrivateKeyPathStream); + sslClientContextBuilder = + SslContextBuilder.forServer(serverKeyCertChainPathStream, serverPrivateKeyPathStream); } if (serverTrustCertStream != null) { @@ -83,7 +84,8 @@ public class SslContexts { } public static SslContext buildClientSslContext(URL url) { - CertManager certManager = url.getOrDefaultFrameworkModel().getBeanFactory().getBean(CertManager.class); + CertManager certManager = + url.getOrDefaultFrameworkModel().getBeanFactory().getBean(CertManager.class); Cert consumerConnectionConfig = certManager.getConsumerConnectionConfig(url); if (consumerConnectionConfig == null) { return null; @@ -136,8 +138,8 @@ public class SslContexts { return SslProvider.JDK; } throw new IllegalStateException( - "Could not find any valid TLS provider, please check your dependency or deployment environment, " + - "usually netty-tcnative, Conscrypt, or Jetty NPN/ALPN is needed."); + "Could not find any valid TLS provider, please check your dependency or deployment environment, " + + "usually netty-tcnative, Conscrypt, or Jetty NPN/ALPN is needed."); } private static boolean checkJdkProvider() { @@ -155,5 +157,4 @@ public class SslContexts { logger.warn(TRANSPORT_FAILED_CLOSE_STREAM, "", "", "Failed to close a stream.", e); } } - } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslServerTlsHandler.java b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslServerTlsHandler.java index 5aaca5e00a..408b8915a6 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslServerTlsHandler.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslServerTlsHandler.java @@ -23,6 +23,10 @@ import org.apache.dubbo.common.ssl.AuthPolicy; import org.apache.dubbo.common.ssl.CertManager; import org.apache.dubbo.common.ssl.ProviderCert; +import javax.net.ssl.SSLSession; + +import java.util.List; + import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; @@ -31,9 +35,6 @@ import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.SslHandshakeCompletionEvent; -import javax.net.ssl.SSLSession; -import java.util.List; - import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; public class SslServerTlsHandler extends ByteToMessageDecoder { @@ -55,7 +56,12 @@ public class SslServerTlsHandler extends ByteToMessageDecoder { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - logger.error(INTERNAL_ERROR, "unknown error in remoting module", "", "TLS negotiation failed when trying to accept new connection.", cause); + logger.error( + INTERNAL_ERROR, + "unknown error in remoting module", + "", + "TLS negotiation failed when trying to accept new connection.", + cause); } @Override @@ -63,12 +69,18 @@ public class SslServerTlsHandler extends ByteToMessageDecoder { if (evt instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt; if (handshakeEvent.isSuccess()) { - SSLSession session = ctx.pipeline().get(SslHandler.class).engine().getSession(); + SSLSession session = + ctx.pipeline().get(SslHandler.class).engine().getSession(); logger.info("TLS negotiation succeed with: " + session.getPeerHost()); // Remove after handshake success. ctx.pipeline().remove(this); } else { - logger.error(INTERNAL_ERROR, "", "", "TLS negotiation failed when trying to accept new connection.", handshakeEvent.cause()); + logger.error( + INTERNAL_ERROR, + "", + "", + "TLS negotiation failed when trying to accept new connection.", + handshakeEvent.cause()); ctx.close(); } } @@ -76,7 +88,8 @@ public class SslServerTlsHandler extends ByteToMessageDecoder { } @Override - protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List list) throws Exception { + protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List list) + throws Exception { // Will use the first five bytes to detect a protocol. if (byteBuf.readableBytes() < 5) { return; @@ -86,8 +99,10 @@ public class SslServerTlsHandler extends ByteToMessageDecoder { return; } - CertManager certManager = url.getOrDefaultFrameworkModel().getBeanFactory().getBean(CertManager.class); - ProviderCert providerConnectionConfig = certManager.getProviderConnectionConfig(url, channelHandlerContext.channel().remoteAddress()); + CertManager certManager = + url.getOrDefaultFrameworkModel().getBeanFactory().getBean(CertManager.class); + ProviderCert providerConnectionConfig = certManager.getProviderConnectionConfig( + url, channelHandlerContext.channel().remoteAddress()); if (providerConnectionConfig == null) { ChannelPipeline p = channelHandlerContext.pipeline(); @@ -120,5 +135,4 @@ public class SslServerTlsHandler extends ByteToMessageDecoder { p.addLast("unificationA", new SslServerTlsHandler(url, true)); p.remove(this); } - } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientReconnectTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientReconnectTest.java index ff15bda516..47fce295e7 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientReconnectTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientReconnectTest.java @@ -81,10 +81,9 @@ class ClientReconnectTest { } } - public Client startClient(int port, int heartbeat) throws RemotingException { - URL url = URL.valueOf("exchange://127.0.0.1:" + port + "/client.reconnect.test?client=netty4&check=false&" + - Constants.HEARTBEAT_KEY + "=" + heartbeat + "&" + LEAST_RECONNECT_DURATION_KEY + "=0"); + URL url = URL.valueOf("exchange://127.0.0.1:" + port + "/client.reconnect.test?client=netty4&check=false&" + + Constants.HEARTBEAT_KEY + "=" + heartbeat + "&" + LEAST_RECONNECT_DURATION_KEY + "=0"); FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); ApplicationConfig applicationConfig = new ApplicationConfig("provider-app"); @@ -118,15 +117,12 @@ class ClientReconnectTest { } @Override - public void connected(Channel channel) throws RemotingException { - } + public void connected(Channel channel) throws RemotingException {} @Override - public void disconnected(Channel channel) throws RemotingException { - } + public void disconnected(Channel channel) throws RemotingException {} @Override - public void caught(Channel channel, Throwable exception) throws RemotingException { - } + public void caught(Channel channel, Throwable exception) throws RemotingException {} } } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientToServerTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientToServerTest.java index f97f31f1aa..2fdbe07035 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientToServerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientToServerTest.java @@ -22,13 +22,13 @@ import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeServer; import org.apache.dubbo.remoting.exchange.support.Replier; +import java.util.concurrent.CompletableFuture; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.concurrent.CompletableFuture; - /** * ClientToServer */ @@ -54,11 +54,9 @@ public abstract class ClientToServerTest { @AfterEach protected void tearDown() { try { - if (server != null) - server.close(); + if (server != null) server.close(); } finally { - if (client != null) - client.close(); + if (client != null) client.close(); } } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientsTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientsTest.java index 4eb68351b7..cec40e77d0 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientsTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ClientsTest.java @@ -51,14 +51,20 @@ class ClientsTest { @Test void testGetTransport3() { String name = "netty4"; - assertEquals(NettyTransporter.class, ExtensionLoader.getExtensionLoader(Transporter.class).getExtension(name).getClass()); + assertEquals( + NettyTransporter.class, + ExtensionLoader.getExtensionLoader(Transporter.class) + .getExtension(name) + .getClass()); } @Test void testGetTransportWrong() { Assertions.assertThrows(IllegalStateException.class, () -> { String name = "nety"; - assertNull(ExtensionLoader.getExtensionLoader(Transporter.class).getExtension(name).getClass()); + assertNull(ExtensionLoader.getExtensionLoader(Transporter.class) + .getExtension(name) + .getClass()); }); } } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ConnectionTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ConnectionTest.java index ba9fd3eb0d..37b4439bba 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ConnectionTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ConnectionTest.java @@ -28,18 +28,17 @@ import org.apache.dubbo.remoting.api.pu.DefaultPuHandler; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; -import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT; public class ConnectionTest { @@ -66,7 +65,9 @@ public class ConnectionTest { url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel); server = new NettyPortUnificationServer(url, new DefaultPuHandler()); server.bind(); - connectionManager = url.getOrDefaultFrameworkModel().getExtensionLoader(ConnectionManager.class).getExtension(MultiplexProtocolConnectionManager.NAME); + connectionManager = url.getOrDefaultFrameworkModel() + .getExtensionLoader(ConnectionManager.class) + .getExtension(MultiplexProtocolConnectionManager.NAME); } @AfterAll @@ -126,7 +127,8 @@ public class ConnectionTest { void connectSyncTest() throws Throwable { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("empty://127.0.0.1:" + port + "?foo=bar"); - NettyPortUnificationServer nettyPortUnificationServer = new NettyPortUnificationServer(url, new DefaultPuHandler()); + NettyPortUnificationServer nettyPortUnificationServer = + new NettyPortUnificationServer(url, new DefaultPuHandler()); nettyPortUnificationServer.bind(); final AbstractConnectionClient connectionClient = connectionManager.connect(url, new DefaultPuHandler()); Assertions.assertTrue(connectionClient.isAvailable()); @@ -141,7 +143,6 @@ public class ConnectionTest { connectionClient.close(); Assertions.assertFalse(connectionClient.isAvailable()); nettyPortUnificationServer.close(); - } @Test diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/DefaultCodec.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/DefaultCodec.java index 9f33bfaa00..d74e8e5398 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/DefaultCodec.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/DefaultCodec.java @@ -24,9 +24,7 @@ import java.io.IOException; public class DefaultCodec implements Codec2 { @Override - public void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException { - - } + public void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException {} @Override public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/DemoService.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/DemoService.java index cd622b9f07..30603e752b 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/DemoService.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/DemoService.java @@ -19,7 +19,6 @@ package org.apache.dubbo.remoting.transport.netty4; /** * TestService */ - public interface DemoService { void sayHello(String name); diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/DemoServiceImpl.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/DemoServiceImpl.java index 22cb86cf4d..a428b03b7d 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/DemoServiceImpl.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/DemoServiceImpl.java @@ -19,7 +19,6 @@ package org.apache.dubbo.remoting.transport.netty4; /** * TestServiceImpl */ - public class DemoServiceImpl implements DemoService { public void sayHello(String name) { System.out.println("hello " + name); diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/Hello.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/Hello.java index f99bb4ab95..e7eb7f39dc 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/Hello.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/Hello.java @@ -27,8 +27,7 @@ public class Hello implements Serializable { private String name; - public Hello() { - } + public Hello() {} public Hello(String name) { this.name = name; @@ -41,5 +40,4 @@ public class Hello implements Serializable { public void setName(String name) { this.name = name; } - } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/MockResult.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/MockResult.java index fbd05f796a..182626a592 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/MockResult.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/MockResult.java @@ -21,7 +21,6 @@ import java.io.Serializable; /** * AppResponse. */ - public class MockResult implements Serializable { private static final long serialVersionUID = -3630485157441794463L; diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyBackedChannelBufferTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyBackedChannelBufferTest.java index f50bf21460..c2224e1994 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyBackedChannelBufferTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyBackedChannelBufferTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.transport.netty4; - import org.apache.dubbo.remoting.buffer.ChannelBuffer; import io.netty.buffer.Unpooled; @@ -61,5 +60,4 @@ class NettyBackedChannelBufferTest { assertEquals(1, actual[0]); assertEquals(2, actual[1]); } - } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyChannelTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyChannelTest.java index 2d6c99deb7..3d51c148b8 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyChannelTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyChannelTest.java @@ -16,23 +16,23 @@ */ package org.apache.dubbo.remoting.transport.netty4; -import io.netty.buffer.PooledByteBufAllocator; -import io.netty.channel.ChannelPromise; -import io.netty.channel.EventLoop; -import io.netty.util.concurrent.GenericFutureListener; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; +import java.net.InetSocketAddress; + +import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.Channel; +import io.netty.channel.ChannelPromise; +import io.netty.channel.EventLoop; +import io.netty.util.concurrent.GenericFutureListener; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import java.net.InetSocketAddress; - class NettyChannelTest { private Channel channel = Mockito.mock(Channel.class); private URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 8080); @@ -63,7 +63,6 @@ class NettyChannelTest { nettyChannel = NettyChannel.getOrAddChannel(channel, url, channelHandler); nettyChannel.markActive(true); Assertions.assertTrue(nettyChannel.isActive()); - } @Test @@ -94,15 +93,21 @@ class NettyChannelTest { Exception exception = Mockito.mock(Exception.class); Mockito.when(exception.getMessage()).thenReturn("future cause"); Mockito.when(future.cause()).thenReturn(exception); - Assertions.assertThrows(RemotingException.class, () -> { - finalNettyChannel.send("msg", true); - }, "future cause"); + Assertions.assertThrows( + RemotingException.class, + () -> { + finalNettyChannel.send("msg", true); + }, + "future cause"); Mockito.when(future.await(1000)).thenReturn(false); Mockito.when(future.cause()).thenReturn(null); - Assertions.assertThrows(RemotingException.class, () -> { - finalNettyChannel.send("msg", true); - }, "in timeout(1000ms) limit"); + Assertions.assertThrows( + RemotingException.class, + () -> { + finalNettyChannel.send("msg", true); + }, + "in timeout(1000ms) limit"); ChannelPromise channelPromise = Mockito.mock(ChannelPromise.class); Mockito.when(channel.newPromise()).thenReturn(channelPromise); @@ -110,7 +115,8 @@ class NettyChannelTest { Mockito.when(channelPromise.cause()).thenReturn(null); Mockito.when(channelPromise.addListener(Mockito.any())).thenReturn(channelPromise); finalNettyChannel.send("msg", true); - ArgumentCaptor listenerArgumentCaptor = ArgumentCaptor.forClass(GenericFutureListener.class); + ArgumentCaptor listenerArgumentCaptor = + ArgumentCaptor.forClass(GenericFutureListener.class); Mockito.verify(channelPromise, Mockito.times(1)).addListener(listenerArgumentCaptor.capture()); } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientHandlerTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientHandlerTest.java index 508153fd83..8db75f0be5 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientHandlerTest.java @@ -16,16 +16,17 @@ */ package org.apache.dubbo.remoting.transport.netty4; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.url.component.ServiceConfigURL; +import org.apache.dubbo.remoting.ChannelHandler; +import org.apache.dubbo.remoting.exchange.Request; + import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.handler.timeout.IdleStateEvent; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.url.component.ServiceConfigURL; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.exchange.Request; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; @@ -78,7 +79,5 @@ class NettyClientHandlerTest { ArgumentCaptor requestArgumentCaptor = ArgumentCaptor.forClass(Request.class); Thread.sleep(500); Mockito.verify(channel, Mockito.times(1)).writeAndFlush(requestArgumentCaptor.capture()); - - } } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientToServerTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientToServerTest.java index 4b66d3faea..2fb11c51a6 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientToServerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyClientToServerTest.java @@ -47,9 +47,10 @@ class NettyClientToServerTest extends ClientToServerTest { configManager.setApplication(applicationConfig); configManager.getApplication(); applicationModel.setConfigManager(configManager); - url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000).putAttribute(CommonConstants.SCOPE_MODEL, applicationModel); + url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000) + .putAttribute(CommonConstants.SCOPE_MODEL, applicationModel); url = url.setScopeModel(applicationModel); -// ModuleModel moduleModel = applicationModel.getDefaultModule(); + // ModuleModel moduleModel = applicationModel.getDefaultModule(); ModuleModel moduleModel = applicationModel.getDefaultModule(); url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel); @@ -73,5 +74,4 @@ class NettyClientToServerTest extends ClientToServerTest { url = url.putAttribute(CommonConstants.SCOPE_MODEL, moduleModel); return Exchangers.connect(url); } - } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyEventLoopFactoryTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyEventLoopFactoryTest.java index 98f647a846..43fbdbe5a6 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyEventLoopFactoryTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyEventLoopFactoryTest.java @@ -59,7 +59,8 @@ class NettyEventLoopFactoryTest { Class socketChannelClass = NettyEventLoopFactory.socketChannelClass(); Assertions.assertEquals(socketChannelClass, EpollSocketChannel.class); - Class serverSocketChannelClass = NettyEventLoopFactory.serverSocketChannelClass(); + Class serverSocketChannelClass = + NettyEventLoopFactory.serverSocketChannelClass(); Assertions.assertEquals(serverSocketChannelClass, EpollServerSocketChannel.class); } else { @@ -69,7 +70,8 @@ class NettyEventLoopFactoryTest { Class socketChannelClass = NettyEventLoopFactory.socketChannelClass(); Assertions.assertEquals(socketChannelClass, NioSocketChannel.class); - Class serverSocketChannelClass = NettyEventLoopFactory.serverSocketChannelClass(); + Class serverSocketChannelClass = + NettyEventLoopFactory.serverSocketChannelClass(); Assertions.assertEquals(serverSocketChannelClass, NioServerSocketChannel.class); } } @@ -78,5 +80,4 @@ class NettyEventLoopFactoryTest { String osName = System.getProperty(OS_NAME_KEY); return osName.toLowerCase().contains(OS_LINUX_PREFIX) && Epoll.isAvailable(); } - } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporterTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporterTest.java index 772f3d604a..3267f90834 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporterTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/NettyTransporterTest.java @@ -27,13 +27,13 @@ import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.RemotingServer; import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter; - import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; -import org.junit.jupiter.api.Test; import java.util.concurrent.CountDownLatch; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -42,8 +42,8 @@ class NettyTransporterTest { @Test void shouldAbleToBindNetty4() throws Exception { int port = NetUtils.getAvailablePort(); - URL url = new ServiceConfigURL("telnet", "localhost", port, - new String[]{Constants.BIND_PORT_KEY, String.valueOf(port)}); + URL url = new ServiceConfigURL( + "telnet", "localhost", port, new String[] {Constants.BIND_PORT_KEY, String.valueOf(port)}); ApplicationModel applicationModel = ApplicationModel.defaultModel(); ApplicationConfig applicationConfig = new ApplicationConfig("provider-app"); @@ -66,8 +66,8 @@ class NettyTransporterTest { final CountDownLatch lock = new CountDownLatch(1); int port = NetUtils.getAvailablePort(); - URL url = new ServiceConfigURL("telnet", "localhost", port, - new String[]{Constants.BIND_PORT_KEY, String.valueOf(port)}); + URL url = new ServiceConfigURL( + "telnet", "localhost", port, new String[] {Constants.BIND_PORT_KEY, String.valueOf(port)}); ApplicationModel applicationModel = ApplicationModel.defaultModel(); ApplicationConfig applicationConfig = new ApplicationConfig("provider-app"); applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT); diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/PortUnificationExchangerTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/PortUnificationExchangerTest.java index faa9de8869..87c1fa9bc5 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/PortUnificationExchangerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/PortUnificationExchangerTest.java @@ -27,6 +27,7 @@ import org.apache.dubbo.remoting.api.pu.DefaultPuHandler; import org.apache.dubbo.remoting.exchange.PortUnificationExchanger; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -78,5 +79,4 @@ class PortUnificationExchangerTest { PortUnificationExchanger.close(); Assertions.assertEquals(0, PortUnificationExchanger.getServers().size()); } - } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/PortUnificationServerTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/PortUnificationServerTest.java index 21b0c8efa9..afebf205fa 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/PortUnificationServerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/PortUnificationServerTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.remoting.transport.netty4; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.NetUtils; diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ReplierDispatcherTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ReplierDispatcherTest.java index 3ba8098f2d..0fa2d0a9e3 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ReplierDispatcherTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/ReplierDispatcherTest.java @@ -29,11 +29,6 @@ import org.apache.dubbo.remoting.exchange.support.ReplierDispatcher; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.io.Serializable; import java.util.LinkedList; import java.util.List; @@ -45,14 +40,17 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT; import static org.junit.jupiter.api.Assertions.fail; - /** * ReplierDispatcherTest */ - class ReplierDispatcherTest { private ExchangeServer exchangeServer; @@ -67,7 +65,8 @@ class ReplierDispatcherTest { ReplierDispatcher dispatcher = new ReplierDispatcher(); dispatcher.addReplier(RpcMessage.class, new RpcMessageHandler()); dispatcher.addReplier(Data.class, (channel, msg) -> new StringMessage("hello world")); - URL url = URL.valueOf("exchange://localhost:" + port + "?" + CommonConstants.TIMEOUT_KEY + "=60000&threadpool=cached"); + URL url = URL.valueOf( + "exchange://localhost:" + port + "?" + CommonConstants.TIMEOUT_KEY + "=60000&threadpool=cached"); ApplicationModel applicationModel = ApplicationModel.defaultModel(); ApplicationConfig applicationConfig = new ApplicationConfig("provider-app"); applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT); @@ -82,10 +81,10 @@ class ReplierDispatcherTest { exchangeServer = Exchangers.bind(url, dispatcher); } - @Test void testDataPackage() throws Exception { - ExchangeChannel client = Exchangers.connect(URL.valueOf("exchange://localhost:" + port + "?" + CommonConstants.TIMEOUT_KEY + "=60000")); + ExchangeChannel client = Exchangers.connect( + URL.valueOf("exchange://localhost:" + port + "?" + CommonConstants.TIMEOUT_KEY + "=60000")); Random random = new Random(); for (int i = 5; i < 100; i++) { StringBuilder sb = new StringBuilder(); @@ -98,7 +97,6 @@ class ReplierDispatcherTest { clients.put(Thread.currentThread().getName(), client); } - @Test void testMultiThread() throws Exception { int tc = 10; @@ -120,12 +118,18 @@ class ReplierDispatcherTest { } void clientExchangeInfo(int port) throws Exception { - ExchangeChannel client = Exchangers.connect(URL.valueOf("exchange://localhost:" + port + "?" + CommonConstants.TIMEOUT_KEY + "=60000")); + ExchangeChannel client = Exchangers.connect( + URL.valueOf("exchange://localhost:" + port + "?" + CommonConstants.TIMEOUT_KEY + "=60000")); clients.put(Thread.currentThread().getName(), client); - MockResult result = (MockResult) client.request(new RpcMessage(DemoService.class.getName(), "plus", new Class[]{int.class, int.class}, new Object[]{55, 25})).get(); + MockResult result = (MockResult) client.request(new RpcMessage( + DemoService.class.getName(), "plus", new Class[] {int.class, int.class}, new Object[] {55, 25 + })) + .get(); Assertions.assertEquals(result.getResult(), 80); for (int i = 0; i < 100; i++) { - client.request(new RpcMessage(DemoService.class.getName(), "sayHello", new Class[]{String.class}, new Object[]{"qianlei" + i})); + client.request(new RpcMessage( + DemoService.class.getName(), "sayHello", new Class[] {String.class}, new Object[] {"qianlei" + i + })); } for (int i = 0; i < 100; i++) { CompletableFuture future = client.request(new Data()); @@ -133,12 +137,10 @@ class ReplierDispatcherTest { } } - @AfterEach public void tearDown() { try { - if (exchangeServer != null) - exchangeServer.close(); + if (exchangeServer != null) exchangeServer.close(); } finally { if (clients.size() != 0) clients.forEach((key, value) -> { @@ -148,14 +150,12 @@ class ReplierDispatcherTest { } } - static class Data implements Serializable { private static final long serialVersionUID = -4666580993978548778L; private String mData = ""; - public Data() { - } + public Data() {} public String getData() { return mData; diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/RpcMessage.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/RpcMessage.java index 44630924a6..0773242d6d 100755 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/RpcMessage.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/RpcMessage.java @@ -21,7 +21,6 @@ import java.io.Serializable; /** * RpcMessage. */ - public class RpcMessage implements Serializable { private static final long serialVersionUID = -5148079121106659095L; @@ -55,5 +54,4 @@ public class RpcMessage implements Serializable { public Object[] getArguments() { return mArguments; } - } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/RpcMessageHandler.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/RpcMessageHandler.java index 6912a5b7a6..89099f8d6b 100755 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/RpcMessageHandler.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/RpcMessageHandler.java @@ -27,9 +27,8 @@ import java.lang.reflect.InvocationTargetException; /** * RpcMessageHandler. */ - public class RpcMessageHandler implements Replier { - private final static ServiceProvider DEFAULT_PROVIDER = new ServiceProvider() { + private static final ServiceProvider DEFAULT_PROVIDER = new ServiceProvider() { public Object getImplementation(String service) { String impl = service + "Impl"; try { @@ -67,11 +66,9 @@ public class RpcMessageHandler implements Replier { } catch (InvocationTargetException e) { return new MockResult(e.getTargetException()); } - } public interface ServiceProvider { Object getImplementation(String service); } - } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/World.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/World.java index 9ee2814cd3..9775bbe617 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/World.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/World.java @@ -27,8 +27,7 @@ public class World implements Serializable { private String name; - public World() { - } + public World() {} public World(String name) { this.name = name; @@ -41,5 +40,4 @@ public class World implements Serializable { public void setName(String name) { this.name = name; } - } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/WorldHandler.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/WorldHandler.java index 7b83598154..511a207123 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/WorldHandler.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/WorldHandler.java @@ -32,5 +32,4 @@ public class WorldHandler implements Replier { public Object reply(ExchangeChannel channel, World msg) throws RemotingException { return new Hello("hello," + msg.getName()); } - } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/EmptyWireProtocol.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/EmptyWireProtocol.java index 5f90d7975b..2943b64a9f 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/EmptyWireProtocol.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/EmptyWireProtocol.java @@ -20,7 +20,6 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.api.ProtocolDetector; import org.apache.dubbo.remoting.api.WireProtocol; import org.apache.dubbo.remoting.api.pu.ChannelOperator; - import org.apache.dubbo.remoting.api.ssl.ContextOperator; public class EmptyWireProtocol implements WireProtocol { @@ -30,17 +29,11 @@ public class EmptyWireProtocol implements WireProtocol { } @Override - public void configServerProtocolHandler(URL url, ChannelOperator operator) { - - } + public void configServerProtocolHandler(URL url, ChannelOperator operator) {} @Override - public void configClientPipeline(URL url, ChannelOperator operator, ContextOperator contextOperator) { - - } + public void configClientPipeline(URL url, ChannelOperator operator, ContextOperator contextOperator) {} @Override - public void close() { - - } + public void close() {} } diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/MultiplexProtocolConnectionManagerTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/MultiplexProtocolConnectionManagerTest.java index 76a45adadd..9ed0cafe7f 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/MultiplexProtocolConnectionManagerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/MultiplexProtocolConnectionManagerTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.transport.netty4.api; import org.apache.dubbo.common.URL; @@ -29,15 +28,15 @@ import org.apache.dubbo.remoting.transport.netty4.NettyPortUnificationServer; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; +import java.lang.reflect.Field; +import java.util.Map; +import java.util.function.Consumer; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import java.lang.reflect.Field; -import java.util.Map; -import java.util.function.Consumer; - import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT; public class MultiplexProtocolConnectionManagerTest { @@ -47,7 +46,6 @@ public class MultiplexProtocolConnectionManagerTest { private static NettyPortUnificationServer server; - private static ConnectionManager connectionManager; @BeforeAll @@ -70,7 +68,8 @@ public class MultiplexProtocolConnectionManagerTest { server = new NettyPortUnificationServer(url1, new DefaultPuHandler()); server.bind(); connectionManager = url1.getOrDefaultFrameworkModel() - .getExtensionLoader(ConnectionManager.class).getExtension(MultiplexProtocolConnectionManager.NAME); + .getExtensionLoader(ConnectionManager.class) + .getExtension(MultiplexProtocolConnectionManager.NAME); } @AfterAll @@ -120,6 +119,4 @@ public class MultiplexProtocolConnectionManagerTest { // ignored } } - } - diff --git a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/SingleProtocolConnectionManagerTest.java b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/SingleProtocolConnectionManagerTest.java index 5369ea0f22..61dd658e4b 100644 --- a/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/SingleProtocolConnectionManagerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/api/SingleProtocolConnectionManagerTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.remoting.transport.netty4.api; import org.apache.dubbo.common.URL; @@ -32,15 +31,15 @@ import org.apache.dubbo.remoting.transport.netty4.NettyPortUnificationServer; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; +import java.lang.reflect.Field; +import java.util.Map; +import java.util.function.Consumer; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import java.lang.reflect.Field; -import java.util.Map; -import java.util.function.Consumer; - import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT; public class SingleProtocolConnectionManagerTest { @@ -69,7 +68,8 @@ public class SingleProtocolConnectionManagerTest { server = new NettyPortUnificationServer(url, new DefaultPuHandler()); server.bind(); connectionManager = url.getOrDefaultFrameworkModel() - .getExtensionLoader(ConnectionManager.class).getExtension(SingleProtocolConnectionManager.NAME); + .getExtensionLoader(ConnectionManager.class) + .getExtension(SingleProtocolConnectionManager.NAME); } @AfterAll @@ -83,7 +83,8 @@ public class SingleProtocolConnectionManagerTest { @Test public void testConnect() throws Exception { - final NettyConnectionClient connectionClient = (NettyConnectionClient) connectionManager.connect(url, new DefaultPuHandler()); + final NettyConnectionClient connectionClient = + (NettyConnectionClient) connectionManager.connect(url, new DefaultPuHandler()); Assertions.assertNotNull(connectionClient); Field protocolsField = connectionManager.getClass().getDeclaredField("connections"); protocolsField.setAccessible(true); @@ -93,8 +94,7 @@ public class SingleProtocolConnectionManagerTest { // Test whether closePromise's listener removes entry connectionClient.getClosePromise().await(); - while (protocolMap.containsKey(url.getAddress())) { - } + while (protocolMap.containsKey(url.getAddress())) {} Assertions.assertNull(protocolMap.get(url.getAddress())); } @@ -103,17 +103,18 @@ public class SingleProtocolConnectionManagerTest { AbstractConnectionClient connectionClient = connectionManager.connect(url, new DefaultPuHandler()); { - Consumer consumer1 = connection -> Assertions.assertEquals("empty", connection.getUrl().getProtocol()); + Consumer consumer1 = connection -> + Assertions.assertEquals("empty", connection.getUrl().getProtocol()); connectionManager.forEachConnection(consumer1); } { - Consumer consumer2 = connection -> Assertions.assertNotEquals("not-empty", connection.getUrl().getProtocol()); + Consumer consumer2 = connection -> + Assertions.assertNotEquals("not-empty", connection.getUrl().getProtocol()); connectionManager.forEachConnection(consumer2); } connectionClient.close(); - } } diff --git a/dubbo-remoting/dubbo-remoting-zookeeper-api/pom.xml b/dubbo-remoting/dubbo-remoting-zookeeper-api/pom.xml index 56063aac1d..4f140f5f49 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper-api/pom.xml +++ b/dubbo-remoting/dubbo-remoting-zookeeper-api/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-remoting - ${revision} - ../pom.xml - - dubbo-remoting-zookeeper-api - jar - ${project.artifactId} - The zookeeper remoting module of dubbo project - - false - 3.4.14 - 4.3.0 - - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - + 4.0.0 + + org.apache.dubbo + dubbo-remoting + ${revision} + ../pom.xml + + dubbo-remoting-zookeeper-api + jar + ${project.artifactId} + The zookeeper remoting module of dubbo project + + false + 3.4.14 + 4.3.0 + + + + org.apache.dubbo + dubbo-common + ${project.parent.version} + - - org.apache.dubbo - dubbo-test-common - ${project.parent.version} - test - - + + org.apache.dubbo + dubbo-test-common + ${project.parent.version} + test + + diff --git a/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/RemotingScopeModelInitializer.java b/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/RemotingScopeModelInitializer.java index 30f6cdf309..820f45e2b8 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/RemotingScopeModelInitializer.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/RemotingScopeModelInitializer.java @@ -33,30 +33,34 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FA */ public class RemotingScopeModelInitializer implements ScopeModelInitializer { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RemotingScopeModelInitializer.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(RemotingScopeModelInitializer.class); @Override - public void initializeFrameworkModel(FrameworkModel frameworkModel) { - - } + public void initializeFrameworkModel(FrameworkModel frameworkModel) {} @Override public void initializeApplicationModel(ApplicationModel applicationModel) { applicationModel.addDestroyListener(m -> { // destroy zookeeper clients if any try { - List transporters = applicationModel.getExtensionLoader(ZookeeperTransporter.class).getLoadedExtensionInstances(); + List transporters = applicationModel + .getExtensionLoader(ZookeeperTransporter.class) + .getLoadedExtensionInstances(); for (ZookeeperTransporter zkTransporter : transporters) { zkTransporter.destroy(); } } catch (Exception e) { - logger.error(TRANSPORT_FAILED_DESTROY_ZOOKEEPER, "", "", "Error encountered while destroying ZookeeperTransporter: " + e.getMessage(), e); + logger.error( + TRANSPORT_FAILED_DESTROY_ZOOKEEPER, + "", + "", + "Error encountered while destroying ZookeeperTransporter: " + e.getMessage(), + e); } }); } @Override - public void initializeModuleModel(ModuleModel moduleModel) { - - } + public void initializeModuleModel(ModuleModel moduleModel) {} } diff --git a/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/AbstractZookeeperClient.java b/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/AbstractZookeeperClient.java index 9f5d3c7bf5..e830246617 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/AbstractZookeeperClient.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/AbstractZookeeperClient.java @@ -34,7 +34,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOO public abstract class AbstractZookeeperClient implements ZookeeperClient { - protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractZookeeperClient.class); + protected static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(AbstractZookeeperClient.class); // may hang up to wait name resolution up to 10s protected int DEFAULT_CONNECTION_TIMEOUT_MS = 30 * 1000; @@ -44,9 +45,11 @@ public abstract class AbstractZookeeperClient stateListeners = new CopyOnWriteArraySet<>(); - private final ConcurrentMap> childListeners = new ConcurrentHashMap<>(); + private final ConcurrentMap> childListeners = + new ConcurrentHashMap<>(); - private final ConcurrentMap> listeners = new ConcurrentHashMap<>(); + private final ConcurrentMap> listeners = + new ConcurrentHashMap<>(); private volatile boolean closed = false; @@ -63,7 +66,7 @@ public abstract class AbstractZookeeperClient addChildListener(String path, final ChildListener listener) { - ConcurrentMap listeners = ConcurrentHashMapUtils.computeIfAbsent(childListeners, path, k -> new ConcurrentHashMap<>()); - TargetChildListener targetListener = ConcurrentHashMapUtils.computeIfAbsent(listeners, listener, k -> createTargetChildListener(path, k)); + ConcurrentMap listeners = + ConcurrentHashMapUtils.computeIfAbsent(childListeners, path, k -> new ConcurrentHashMap<>()); + TargetChildListener targetListener = + ConcurrentHashMapUtils.computeIfAbsent(listeners, listener, k -> createTargetChildListener(path, k)); return addTargetChildListener(path, targetListener); } @@ -119,8 +124,10 @@ public abstract class AbstractZookeeperClient dataListenerMap = ConcurrentHashMapUtils.computeIfAbsent(listeners, path, k -> new ConcurrentHashMap<>()); - TargetDataListener targetListener = ConcurrentHashMapUtils.computeIfAbsent(dataListenerMap, listener, k -> createTargetDataListener(path, k)); + ConcurrentMap dataListenerMap = + ConcurrentHashMapUtils.computeIfAbsent(listeners, path, k -> new ConcurrentHashMap<>()); + TargetDataListener targetListener = ConcurrentHashMapUtils.computeIfAbsent( + dataListenerMap, listener, k -> createTargetDataListener(path, k)); addTargetDataListener(path, targetListener, executor); } @@ -256,5 +263,4 @@ public abstract class AbstractZookeeperClient addressList = getURLBackupAddress(url); // The field define the zookeeper server , including protocol, host, port, username, password - if ((zookeeperClient = fetchAndUpdateZookeeperClientCache(addressList)) != null && zookeeperClient.isConnected()) { + if ((zookeeperClient = fetchAndUpdateZookeeperClientCache(addressList)) != null + && zookeeperClient.isConnected()) { logger.info("find valid zookeeper client from the cache for address: " + url); return zookeeperClient; } // avoid creating too many connections, so add lock synchronized (zookeeperClientMap) { - if ((zookeeperClient = fetchAndUpdateZookeeperClientCache(addressList)) != null && zookeeperClient.isConnected()) { + if ((zookeeperClient = fetchAndUpdateZookeeperClientCache(addressList)) != null + && zookeeperClient.isConnected()) { logger.info("find valid zookeeper client from the cache for address: " + url); return zookeeperClient; } @@ -165,8 +167,14 @@ public abstract class AbstractZookeeperTransporter implements ZookeeperTransport parameterMap.put(RemotingConstants.BACKUP_KEY, url.getParameter(RemotingConstants.BACKUP_KEY)); } - return new ServiceConfigURL(url.getProtocol(), url.getUsername(), url.getPassword(), url.getHost(), url.getPort(), - ZookeeperTransporter.class.getName(), parameterMap); + return new ServiceConfigURL( + url.getProtocol(), + url.getUsername(), + url.getPassword(), + url.getHost(), + url.getPort(), + ZookeeperTransporter.class.getName(), + parameterMap); } /** diff --git a/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ChildListener.java b/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ChildListener.java index 0e876aff3e..5ada2815a8 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ChildListener.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ChildListener.java @@ -21,5 +21,4 @@ import java.util.List; public interface ChildListener { void childChanged(String path, List children); - } diff --git a/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/EventType.java b/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/EventType.java index 791e7e3044..9e28803647 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/EventType.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/EventType.java @@ -30,8 +30,7 @@ public enum EventType { CONNECTION_LOST(12), INITIALIZED(10); - - private final int intValue; // Integer representation of value + private final int intValue; // Integer representation of value // for sending over wire EventType(int intValue) { diff --git a/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/StateListener.java b/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/StateListener.java index ca4dbe09ae..202b6cc63b 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/StateListener.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/StateListener.java @@ -29,5 +29,4 @@ public interface StateListener { int NEW_SESSION_CREATED = 4; void stateChanged(int connected); - } diff --git a/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperClient.java b/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperClient.java index bb6f78dba4..b2877cd259 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperClient.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperClient.java @@ -123,5 +123,4 @@ public interface ZookeeperClient { ConfigItem getConfigItem(String path); boolean checkExists(String path); - } diff --git a/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperTransporter.java b/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperTransporter.java index 36bb5cd3e2..f73bc6b1a7 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperTransporter.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper-api/src/main/java/org/apache/dubbo/remoting/zookeeper/ZookeeperTransporter.java @@ -34,7 +34,8 @@ public interface ZookeeperTransporter { void destroy(); static ZookeeperTransporter getExtension(ApplicationModel applicationModel) { - ExtensionLoader extensionLoader = applicationModel.getExtensionLoader(ZookeeperTransporter.class); + ExtensionLoader extensionLoader = + applicationModel.getExtensionLoader(ZookeeperTransporter.class); return isHighVersionCurator() ? extensionLoader.getExtension(CURATOR_5) : extensionLoader.getExtension(CURATOR); } diff --git a/dubbo-remoting/dubbo-remoting-zookeeper-curator5/pom.xml b/dubbo-remoting/dubbo-remoting-zookeeper-curator5/pom.xml index b19b96a14c..e786281cce 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper-curator5/pom.xml +++ b/dubbo-remoting/dubbo-remoting-zookeeper-curator5/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - org.apache.dubbo - dubbo-remoting - ${revision} - ../pom.xml - - dubbo-remoting-zookeeper-curator5 - jar - ${project.artifactId} - The zookeeper curator5 remoting module of dubbo project - - false - 5.1.0 - 3.7.2 - + + 4.0.0 + + org.apache.dubbo + dubbo-remoting + ${revision} + ../pom.xml + + dubbo-remoting-zookeeper-curator5 + jar + ${project.artifactId} + The zookeeper curator5 remoting module of dubbo project + + false + 5.1.0 + 3.7.2 + - - - org.apache.dubbo - dubbo-remoting-zookeeper-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - org.apache.curator - curator-framework - ${curator5_version} - - - org.apache.curator - curator-recipes - ${curator5_version} - - - org.apache.zookeeper - zookeeper - ${zookeeper_version} - + + + org.apache.dubbo + dubbo-remoting-zookeeper-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-common + ${project.parent.version} + + + org.apache.curator + curator-framework + ${curator5_version} + + + org.apache.curator + curator-recipes + ${curator5_version} + + + org.apache.zookeeper + zookeeper + ${zookeeper_version} + - - org.apache.dubbo - dubbo-native - ${project.parent.version} - - + + org.apache.dubbo + dubbo-native + ${project.parent.version} + + diff --git a/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperClient.java b/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperClient.java index 028ebb6fe4..65b6bd6797 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperClient.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperClient.java @@ -26,6 +26,14 @@ import org.apache.dubbo.remoting.zookeeper.DataListener; import org.apache.dubbo.remoting.zookeeper.EventType; import org.apache.dubbo.remoting.zookeeper.StateListener; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; + import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.ACLProvider; @@ -45,23 +53,17 @@ import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Executor; -import java.util.concurrent.TimeUnit; - import static org.apache.dubbo.common.constants.CommonConstants.SESSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_CONNECT_REGISTRY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION; +public class Curator5ZookeeperClient + extends AbstractZookeeperClient< + Curator5ZookeeperClient.NodeCacheListenerImpl, Curator5ZookeeperClient.CuratorWatcherImpl> { -public class Curator5ZookeeperClient extends AbstractZookeeperClient { - - protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(Curator5ZookeeperClient.class); + protected static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(Curator5ZookeeperClient.class); private static final Charset CHARSET = StandardCharsets.UTF_8; private final CuratorFramework client; @@ -73,10 +75,10 @@ public class Curator5ZookeeperClient extends AbstractZookeeperClient 0) { builder = builder.authorization("digest", userInformation.getBytes()); @@ -98,11 +100,16 @@ public class Curator5ZookeeperClient extends AbstractZookeeperClient memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.INVOKE_DECLARED_METHODS); memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); @@ -46,9 +46,10 @@ public class Curator5ZookeeperReflectionTypeDescriberRegistrar implements Reflec return new TypeDescriber(className, null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } - private TypeDescriber buildTypeDescriberWithDeclaredConstructors(Class c){ + private TypeDescriber buildTypeDescriberWithDeclaredConstructors(Class c) { Set memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); - return new TypeDescriber(c.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); + return new TypeDescriber( + c.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } } diff --git a/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperClientTest.java b/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperClientTest.java index dc1de17c45..50e96f9354 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperClientTest.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperClientTest.java @@ -20,6 +20,12 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigItem; import org.apache.dubbo.remoting.zookeeper.ChildListener; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; @@ -31,12 +37,6 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; - import static org.awaitility.Awaitility.await; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; @@ -54,9 +54,12 @@ class Curator5ZookeeperClientTest { @BeforeAll public static void setUp() throws Exception { zookeeperConnectionAddress1 = System.getProperty("zookeeper.connection.address.1"); - zookeeperServerPort1 = Integer.parseInt(zookeeperConnectionAddress1.substring(zookeeperConnectionAddress1.lastIndexOf(":") + 1)); - curatorClient = new Curator5ZookeeperClient(URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")); - client = CuratorFrameworkFactory.newClient("127.0.0.1:" + zookeeperServerPort1, new ExponentialBackoffRetry(1000, 3)); + zookeeperServerPort1 = Integer.parseInt( + zookeeperConnectionAddress1.substring(zookeeperConnectionAddress1.lastIndexOf(":") + 1)); + curatorClient = new Curator5ZookeeperClient( + URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")); + client = CuratorFrameworkFactory.newClient( + "127.0.0.1:" + zookeeperServerPort1, new ExponentialBackoffRetry(1000, 3)); client.start(); } @@ -96,7 +99,6 @@ class Curator5ZookeeperClientTest { countDownLatch.await(); } - @Test void testWithInvalidServer() { Assertions.assertThrows(IllegalStateException.class, () -> { @@ -227,23 +229,25 @@ class Curator5ZookeeperClientTest { // test create failed when others create success String path = "/dubbo/mapping/org.apache.dubbo.demo.DemoService"; AtomicReference runnable = new AtomicReference<>(); - Curator5ZookeeperClient curatorClient = new Curator5ZookeeperClient(URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { - @Override - protected void createPersistent(String path, String data, boolean faultTolerant) { - if (runnable.get() != null) { - runnable.get().run(); - } - super.createPersistent(path, data, faultTolerant); - } + Curator5ZookeeperClient curatorClient = + new Curator5ZookeeperClient( + URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { + @Override + protected void createPersistent(String path, String data, boolean faultTolerant) { + if (runnable.get() != null) { + runnable.get().run(); + } + super.createPersistent(path, data, faultTolerant); + } - @Override - protected void update(String path, String data, int version) { - if (runnable.get() != null) { - runnable.get().run(); - } - super.update(path, data, version); - } - }; + @Override + protected void update(String path, String data, int version) { + if (runnable.get() != null) { + runnable.get().run(); + } + super.update(path, data, version); + } + }; curatorClient.delete(path); runnable.set(() -> { @@ -253,7 +257,8 @@ class Curator5ZookeeperClientTest { throw new RuntimeException(e); } }); - Assertions.assertThrows(IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", false, 0)); + Assertions.assertThrows( + IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", false, 0)); Assertions.assertEquals("version x", curatorClient.getContent(path)); client.setData().forPath(path, "version 1".getBytes(StandardCharsets.UTF_8)); @@ -267,7 +272,8 @@ class Curator5ZookeeperClientTest { } }); int version1 = ((Stat) configItem.getTicket()).getVersion(); - Assertions.assertThrows(IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 2", false, version1)); + Assertions.assertThrows( + IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 2", false, version1)); Assertions.assertEquals("version x", curatorClient.getContent(path)); runnable.set(null); @@ -283,11 +289,13 @@ class Curator5ZookeeperClientTest { void testPersistentCas2() { // test update failed when others create success String path = "/dubbo/mapping/org.apache.dubbo.demo.DemoService"; - Curator5ZookeeperClient curatorClient = new Curator5ZookeeperClient(URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")); + Curator5ZookeeperClient curatorClient = new Curator5ZookeeperClient( + URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")); curatorClient.delete(path); curatorClient.createOrUpdate(path, "version x", false); - Assertions.assertThrows(IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", false, null)); + Assertions.assertThrows( + IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", false, null)); Assertions.assertEquals("version x", curatorClient.getContent(path)); curatorClient.close(); @@ -297,23 +305,25 @@ class Curator5ZookeeperClientTest { void testPersistentNonVersion() { String path = "/dubbo/metadata/org.apache.dubbo.demo.DemoService"; AtomicReference runnable = new AtomicReference<>(); - Curator5ZookeeperClient curatorClient = new Curator5ZookeeperClient(URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { - @Override - protected void createPersistent(String path, String data, boolean faultTolerant) { - if (runnable.get() != null) { - runnable.get().run(); - } - super.createPersistent(path, data, faultTolerant); - } + Curator5ZookeeperClient curatorClient = + new Curator5ZookeeperClient( + URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { + @Override + protected void createPersistent(String path, String data, boolean faultTolerant) { + if (runnable.get() != null) { + runnable.get().run(); + } + super.createPersistent(path, data, faultTolerant); + } - @Override - protected void update(String path, String data, int version) { - if (runnable.get() != null) { - runnable.get().run(); - } - super.update(path, data, version); - } - }; + @Override + protected void update(String path, String data, int version) { + if (runnable.get() != null) { + runnable.get().run(); + } + super.update(path, data, version); + } + }; curatorClient.delete(path); curatorClient.createOrUpdate(path, "version 0", false); @@ -352,23 +362,25 @@ class Curator5ZookeeperClientTest { // test create failed when others create success String path = "/dubbo/mapping/org.apache.dubbo.demo.DemoService"; AtomicReference runnable = new AtomicReference<>(); - Curator5ZookeeperClient curatorClient = new Curator5ZookeeperClient(URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { - @Override - protected void createEphemeral(String path, String data, boolean faultTolerant) { - if (runnable.get() != null) { - runnable.get().run(); - } - super.createPersistent(path, data, faultTolerant); - } + Curator5ZookeeperClient curatorClient = + new Curator5ZookeeperClient( + URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { + @Override + protected void createEphemeral(String path, String data, boolean faultTolerant) { + if (runnable.get() != null) { + runnable.get().run(); + } + super.createPersistent(path, data, faultTolerant); + } - @Override - protected void update(String path, String data, int version) { - if (runnable.get() != null) { - runnable.get().run(); - } - super.update(path, data, version); - } - }; + @Override + protected void update(String path, String data, int version) { + if (runnable.get() != null) { + runnable.get().run(); + } + super.update(path, data, version); + } + }; curatorClient.delete(path); runnable.set(() -> { @@ -378,7 +390,8 @@ class Curator5ZookeeperClientTest { throw new RuntimeException(e); } }); - Assertions.assertThrows(IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", true, 0)); + Assertions.assertThrows( + IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", true, 0)); Assertions.assertEquals("version x", curatorClient.getContent(path)); client.setData().forPath(path, "version 1".getBytes(StandardCharsets.UTF_8)); @@ -392,7 +405,8 @@ class Curator5ZookeeperClientTest { } }); int version1 = ((Stat) configItem.getTicket()).getVersion(); - Assertions.assertThrows(IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 2", true, version1)); + Assertions.assertThrows( + IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 2", true, version1)); Assertions.assertEquals("version x", curatorClient.getContent(path)); runnable.set(null); @@ -408,11 +422,13 @@ class Curator5ZookeeperClientTest { void testEphemeralCas2() { // test update failed when others create success String path = "/dubbo/mapping/org.apache.dubbo.demo.DemoService"; - Curator5ZookeeperClient curatorClient = new Curator5ZookeeperClient(URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")); + Curator5ZookeeperClient curatorClient = new Curator5ZookeeperClient( + URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")); curatorClient.delete(path); curatorClient.createOrUpdate(path, "version x", true); - Assertions.assertThrows(IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", true, null)); + Assertions.assertThrows( + IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", true, null)); Assertions.assertEquals("version x", curatorClient.getContent(path)); curatorClient.close(); @@ -422,23 +438,25 @@ class Curator5ZookeeperClientTest { void testEphemeralNonVersion() { String path = "/dubbo/metadata/org.apache.dubbo.demo.DemoService"; AtomicReference runnable = new AtomicReference<>(); - Curator5ZookeeperClient curatorClient = new Curator5ZookeeperClient(URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { - @Override - protected void createPersistent(String path, String data, boolean faultTolerant) { - if (runnable.get() != null) { - runnable.get().run(); - } - super.createPersistent(path, data, faultTolerant); - } + Curator5ZookeeperClient curatorClient = + new Curator5ZookeeperClient( + URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { + @Override + protected void createPersistent(String path, String data, boolean faultTolerant) { + if (runnable.get() != null) { + runnable.get().run(); + } + super.createPersistent(path, data, faultTolerant); + } - @Override - protected void update(String path, String data, int version) { - if (runnable.get() != null) { - runnable.get().run(); - } - super.update(path, data, version); - } - }; + @Override + protected void update(String path, String data, int version) { + if (runnable.get() != null) { + runnable.get().run(); + } + super.update(path, data, version); + } + }; curatorClient.delete(path); curatorClient.createOrUpdate(path, "version 0", true); diff --git a/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperTransporterTest.java b/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperTransporterTest.java index 1418d2fc3d..f94f4e0053 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperTransporterTest.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperTransporterTest.java @@ -39,7 +39,8 @@ class Curator5ZookeeperTransporterTest { @BeforeEach public void setUp() { - zookeeperClient = new Curator5ZookeeperTransporter().connect(URL.valueOf(zookeeperConnectionAddress1 + "/service")); + zookeeperClient = + new Curator5ZookeeperTransporter().connect(URL.valueOf(zookeeperConnectionAddress1 + "/service")); curatorZookeeperTransporter = new Curator5ZookeeperTransporter(); } diff --git a/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper/curator5/support/AbstractZookeeperTransporterTest.java b/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper/curator5/support/AbstractZookeeperTransporterTest.java index a90d735e4e..5b3eac8968 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper/curator5/support/AbstractZookeeperTransporterTest.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper/curator5/support/AbstractZookeeperTransporterTest.java @@ -21,13 +21,13 @@ import org.apache.dubbo.remoting.zookeeper.AbstractZookeeperTransporter; import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; import org.apache.dubbo.remoting.zookeeper.curator5.Curator5ZookeeperTransporter; +import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.List; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNull.nullValue; @@ -46,13 +46,16 @@ class AbstractZookeeperTransporterTest { public static void beforeAll() { zookeeperConnectionAddress1 = System.getProperty("zookeeper.connection.address.1"); zookeeperConnectionAddress2 = System.getProperty("zookeeper.connection.address.2"); - zookeeperServerPort1 = Integer.parseInt(zookeeperConnectionAddress1.substring(zookeeperConnectionAddress1.lastIndexOf(":") + 1)); - zookeeperServerPort2 = Integer.parseInt(zookeeperConnectionAddress2.substring(zookeeperConnectionAddress2.lastIndexOf(":") + 1)); + zookeeperServerPort1 = Integer.parseInt( + zookeeperConnectionAddress1.substring(zookeeperConnectionAddress1.lastIndexOf(":") + 1)); + zookeeperServerPort2 = Integer.parseInt( + zookeeperConnectionAddress2.substring(zookeeperConnectionAddress2.lastIndexOf(":") + 1)); } @BeforeEach public void setUp() throws Exception { - zookeeperClient = new Curator5ZookeeperTransporter().connect(URL.valueOf(zookeeperConnectionAddress1 + "/service")); + zookeeperClient = + new Curator5ZookeeperTransporter().connect(URL.valueOf(zookeeperConnectionAddress1 + "/service")); abstractZookeeperTransporter = new Curator5ZookeeperTransporter(); } @@ -64,7 +67,9 @@ class AbstractZookeeperTransporterTest { @Test void testGetURLBackupAddress() { - URL url = URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + 9099 + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); + URL url = URL.valueOf( + zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + 9099 + + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); List stringList = abstractZookeeperTransporter.getURLBackupAddress(url); Assertions.assertEquals(stringList.size(), 2); Assertions.assertEquals(stringList.get(0), "127.0.0.1:" + zookeeperServerPort1); @@ -73,7 +78,9 @@ class AbstractZookeeperTransporterTest { @Test void testGetURLBackupAddressNoBack() { - URL url = URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); + URL url = URL.valueOf( + zookeeperConnectionAddress1 + + "/org.apache.dubbo.registry.RegistryService?application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); List stringList = abstractZookeeperTransporter.getURLBackupAddress(url); Assertions.assertEquals(stringList.size(), 1); Assertions.assertEquals(stringList.get(0), "127.0.0.1:" + zookeeperServerPort1); @@ -81,16 +88,27 @@ class AbstractZookeeperTransporterTest { @Test void testFetchAndUpdateZookeeperClientCache() { - URL url = URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + zookeeperServerPort1 + ",127.0.0.1:" + zookeeperServerPort2 + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); + URL url = URL.valueOf( + zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + + zookeeperServerPort1 + ",127.0.0.1:" + zookeeperServerPort2 + + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); ZookeeperClient newZookeeperClient = abstractZookeeperTransporter.connect(url); - //just for connected + // just for connected newZookeeperClient.getContent("/dubbo/test"); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), + newZookeeperClient); - URL url2 = URL.valueOf("zookeeper://127.0.0.1:" + zookeeperServerPort1 + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); + URL url2 = URL.valueOf( + "zookeeper://127.0.0.1:" + zookeeperServerPort1 + + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); checkFetchAndUpdateCacheNotNull(url2); - URL url3 = URL.valueOf("zookeeper://127.0.0.1:8778/org.apache.dubbo.metadata.store.MetadataReport?backup=127.0.0.1:" + zookeeperServerPort2 + "&address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); + URL url3 = URL.valueOf( + "zookeeper://127.0.0.1:8778/org.apache.dubbo.metadata.store.MetadataReport?backup=127.0.0.1:" + + zookeeperServerPort2 + + "&address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); checkFetchAndUpdateCacheNotNull(url3); } @@ -102,80 +120,120 @@ class AbstractZookeeperTransporterTest { @Test void testRepeatConnect() { - URL url = URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); - URL url2 = URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); + URL url = URL.valueOf( + zookeeperConnectionAddress1 + + "/org.apache.dubbo.registry.RegistryService?application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); + URL url2 = URL.valueOf( + zookeeperConnectionAddress1 + + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); ZookeeperClient newZookeeperClient = abstractZookeeperTransporter.connect(url); - //just for connected + // just for connected newZookeeperClient.getContent("/dubbo/test"); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), + newZookeeperClient); Assertions.assertTrue(newZookeeperClient.isConnected()); ZookeeperClient newZookeeperClient2 = abstractZookeeperTransporter.connect(url2); - //just for connected + // just for connected newZookeeperClient2.getContent("/dubbo/test"); Assertions.assertEquals(newZookeeperClient, newZookeeperClient2); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), + newZookeeperClient); } @Test void testNotRepeatConnect() { - URL url = URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); - URL url2 = URL.valueOf(zookeeperConnectionAddress2 + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); + URL url = URL.valueOf( + zookeeperConnectionAddress1 + + "/org.apache.dubbo.registry.RegistryService?application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); + URL url2 = URL.valueOf( + zookeeperConnectionAddress2 + + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); ZookeeperClient newZookeeperClient = abstractZookeeperTransporter.connect(url); - //just for connected + // just for connected newZookeeperClient.getContent("/dubbo/test"); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), + newZookeeperClient); ZookeeperClient newZookeeperClient2 = abstractZookeeperTransporter.connect(url2); - //just for connected + // just for connected newZookeeperClient2.getContent("/dubbo/test"); Assertions.assertNotEquals(newZookeeperClient, newZookeeperClient2); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort2), newZookeeperClient2); - + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort2), + newZookeeperClient2); } @Test void testRepeatConnectForBackUpAdd() { - URL url = URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + zookeeperServerPort1 + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); - URL url2 = URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.metadata.store.MetadataReport?backup=127.0.0.1:" + zookeeperServerPort2 + "&address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); + URL url = URL.valueOf( + zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + + zookeeperServerPort1 + + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); + URL url2 = URL.valueOf( + zookeeperConnectionAddress1 + "/org.apache.dubbo.metadata.store.MetadataReport?backup=127.0.0.1:" + + zookeeperServerPort2 + + "&address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); ZookeeperClient newZookeeperClient = abstractZookeeperTransporter.connect(url); - //just for connected + // just for connected newZookeeperClient.getContent("/dubbo/test"); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), + newZookeeperClient); ZookeeperClient newZookeeperClient2 = abstractZookeeperTransporter.connect(url2); - //just for connected + // just for connected newZookeeperClient2.getContent("/dubbo/test"); Assertions.assertEquals(newZookeeperClient, newZookeeperClient2); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort2), newZookeeperClient2); - + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort2), + newZookeeperClient2); } @Test void testRepeatConnectForNoMatchBackUpAdd() { - URL url = URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + zookeeperServerPort1 + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); - URL url2 = URL.valueOf(zookeeperConnectionAddress2 + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); + URL url = URL.valueOf( + zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + + zookeeperServerPort1 + + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); + URL url2 = URL.valueOf( + zookeeperConnectionAddress2 + + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); ZookeeperClient newZookeeperClient = abstractZookeeperTransporter.connect(url); - //just for connected + // just for connected newZookeeperClient.getContent("/dubbo/test"); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), + newZookeeperClient); ZookeeperClient newZookeeperClient2 = abstractZookeeperTransporter.connect(url2); - //just for connected + // just for connected newZookeeperClient2.getContent("/dubbo/test"); Assertions.assertNotEquals(newZookeeperClient, newZookeeperClient2); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort2), newZookeeperClient2); - + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort2), + newZookeeperClient2); } @Test diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml index e5e0b7d785..ef9990c082 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml +++ b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-remoting - ${revision} - ../pom.xml - - dubbo-remoting-zookeeper - jar - ${project.artifactId} - The zookeeper remoting module of dubbo project - - false - 3.4.14 - 4.3.0 - - - - org.apache.dubbo - dubbo-remoting-zookeeper-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - org.apache.curator - curator-recipes - ${curator_version} - - - org.apache.curator - curator-framework - ${curator_version} - - - org.apache.curator - curator-x-discovery - ${curator_version} - + 4.0.0 + + org.apache.dubbo + dubbo-remoting + ${revision} + ../pom.xml + + dubbo-remoting-zookeeper + jar + ${project.artifactId} + The zookeeper remoting module of dubbo project + + false + 3.4.14 + 4.3.0 + + + + org.apache.dubbo + dubbo-remoting-zookeeper-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-common + ${project.parent.version} + + + org.apache.curator + curator-recipes + ${curator_version} + + + org.apache.curator + curator-framework + ${curator_version} + + + org.apache.curator + curator-x-discovery + ${curator_version} + - - org.apache.dubbo - dubbo-native - ${project.parent.version} - + + org.apache.dubbo + dubbo-native + ${project.parent.version} + - - org.apache.zookeeper - zookeeper - ${zookeeper_version} - + + org.apache.zookeeper + zookeeper + ${zookeeper_version} + - - org.apache.dubbo - dubbo-test-common - ${project.parent.version} - test - - + + org.apache.dubbo + dubbo-test-common + ${project.parent.version} + test + + diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java index dc4a5d3fab..e9a99f38b4 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java @@ -28,6 +28,17 @@ import org.apache.dubbo.remoting.zookeeper.DataListener; import org.apache.dubbo.remoting.zookeeper.EventType; import org.apache.dubbo.remoting.zookeeper.StateListener; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.ACLProvider; @@ -47,26 +58,17 @@ import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Executor; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - import static org.apache.dubbo.common.constants.CommonConstants.SESSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_CONNECT_REGISTRY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION; +public class CuratorZookeeperClient + extends AbstractZookeeperClient< + CuratorZookeeperClient.NodeCacheListenerImpl, CuratorZookeeperClient.CuratorWatcherImpl> { -public class CuratorZookeeperClient extends AbstractZookeeperClient { - - protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CuratorZookeeperClient.class); + protected static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(CuratorZookeeperClient.class); private static final Charset CHARSET = StandardCharsets.UTF_8; private final CuratorFramework client; @@ -78,10 +80,10 @@ public class CuratorZookeeperClient extends AbstractZookeeperClient Optional.ofNullable(childListener) - .ifPresent(c -> { - try { - c.childChanged(path, client.getChildren().usingWatcher(CuratorWatcherImpl.this).forPath(path)); - } catch (Exception e) { - logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "client get children error", e); - } - }); + Runnable task = () -> Optional.ofNullable(childListener).ifPresent(c -> { + try { + c.childChanged( + path, + client.getChildren() + .usingWatcher(CuratorWatcherImpl.this) + .forPath(path)); + } catch (Exception e) { + logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "client get children error", e); + } + }); initExecutorIfNecessary(); if (!closed && CURATOR_WATCHER_EXECUTOR_SERVICE != null) { CURATOR_WATCHER_EXECUTOR_SERVICE.execute(task); @@ -515,28 +529,50 @@ public class CuratorZookeeperClient extends AbstractZookeeperClient c){ + private TypeDescriber buildTypeDescriberWithDeclaredMethods(Class c) { Set memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.INVOKE_DECLARED_METHODS); - return new TypeDescriber(c.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); + return new TypeDescriber( + c.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } - private TypeDescriber buildTypeDescriberWithDeclaredConstructors(Class c){ + private TypeDescriber buildTypeDescriberWithDeclaredConstructors(Class c) { Set memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); - return new TypeDescriber(c.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); + return new TypeDescriber( + c.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } } diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClientTest.java b/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClientTest.java index 7ece96bc82..818b3f9555 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClientTest.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClientTest.java @@ -20,6 +20,12 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigItem; import org.apache.dubbo.remoting.zookeeper.ChildListener; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; @@ -34,13 +40,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.DisabledForJreRange; import org.junit.jupiter.api.condition.JRE; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; - import static org.awaitility.Awaitility.await; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; @@ -59,13 +58,16 @@ class CuratorZookeeperClientTest { @BeforeAll public static void beforeAll() { zookeeperConnectionAddress1 = System.getProperty("zookeeper.connection.address.1"); - zookeeperServerPort1 = Integer.parseInt(zookeeperConnectionAddress1.substring(zookeeperConnectionAddress1.lastIndexOf(":") + 1)); + zookeeperServerPort1 = Integer.parseInt( + zookeeperConnectionAddress1.substring(zookeeperConnectionAddress1.lastIndexOf(":") + 1)); } @BeforeEach public void setUp() throws Exception { - curatorClient = new CuratorZookeeperClient(URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")); - client = CuratorFrameworkFactory.newClient("127.0.0.1:" + zookeeperServerPort1, new ExponentialBackoffRetry(1000, 3)); + curatorClient = new CuratorZookeeperClient( + URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")); + client = CuratorFrameworkFactory.newClient( + "127.0.0.1:" + zookeeperServerPort1, new ExponentialBackoffRetry(1000, 3)); client.start(); } @@ -105,7 +107,6 @@ class CuratorZookeeperClientTest { countDownLatch.await(); } - @Test void testWithInvalidServer() { Assertions.assertThrows(IllegalStateException.class, () -> { @@ -246,29 +247,30 @@ class CuratorZookeeperClientTest { await().until(() -> atomicInteger.get() > currentCount3); } - @Test void testPersistentCas1() throws Exception { // test create failed when others create success String path = "/dubbo/mapping/org.apache.dubbo.demo.DemoService"; AtomicReference runnable = new AtomicReference<>(); - CuratorZookeeperClient curatorClient = new CuratorZookeeperClient(URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { - @Override - protected void createPersistent(String path, String data, boolean faultTolerant) { - if (runnable.get() != null) { - runnable.get().run(); - } - super.createPersistent(path, data, faultTolerant); - } + CuratorZookeeperClient curatorClient = + new CuratorZookeeperClient( + URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { + @Override + protected void createPersistent(String path, String data, boolean faultTolerant) { + if (runnable.get() != null) { + runnable.get().run(); + } + super.createPersistent(path, data, faultTolerant); + } - @Override - protected void update(String path, String data, int version) { - if (runnable.get() != null) { - runnable.get().run(); - } - super.update(path, data, version); - } - }; + @Override + protected void update(String path, String data, int version) { + if (runnable.get() != null) { + runnable.get().run(); + } + super.update(path, data, version); + } + }; curatorClient.delete(path); runnable.set(() -> { @@ -278,7 +280,8 @@ class CuratorZookeeperClientTest { throw new RuntimeException(e); } }); - Assertions.assertThrows(IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", false, 0)); + Assertions.assertThrows( + IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", false, 0)); Assertions.assertEquals("version x", curatorClient.getContent(path)); client.setData().forPath(path, "version 1".getBytes(StandardCharsets.UTF_8)); @@ -292,7 +295,8 @@ class CuratorZookeeperClientTest { } }); int version1 = ((Stat) configItem.getTicket()).getVersion(); - Assertions.assertThrows(IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 2", false, version1)); + Assertions.assertThrows( + IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 2", false, version1)); Assertions.assertEquals("version x", curatorClient.getContent(path)); runnable.set(null); @@ -308,11 +312,13 @@ class CuratorZookeeperClientTest { void testPersistentCas2() { // test update failed when others create success String path = "/dubbo/mapping/org.apache.dubbo.demo.DemoService"; - CuratorZookeeperClient curatorClient = new CuratorZookeeperClient(URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")); + CuratorZookeeperClient curatorClient = new CuratorZookeeperClient( + URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")); curatorClient.delete(path); curatorClient.createOrUpdate(path, "version x", false); - Assertions.assertThrows(IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", false, null)); + Assertions.assertThrows( + IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", false, null)); Assertions.assertEquals("version x", curatorClient.getContent(path)); curatorClient.close(); @@ -322,23 +328,25 @@ class CuratorZookeeperClientTest { void testPersistentNonVersion() { String path = "/dubbo/metadata/org.apache.dubbo.demo.DemoService"; AtomicReference runnable = new AtomicReference<>(); - CuratorZookeeperClient curatorClient = new CuratorZookeeperClient(URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { - @Override - protected void createPersistent(String path, String data, boolean faultTolerant) { - if (runnable.get() != null) { - runnable.get().run(); - } - super.createPersistent(path, data, faultTolerant); - } + CuratorZookeeperClient curatorClient = + new CuratorZookeeperClient( + URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { + @Override + protected void createPersistent(String path, String data, boolean faultTolerant) { + if (runnable.get() != null) { + runnable.get().run(); + } + super.createPersistent(path, data, faultTolerant); + } - @Override - protected void update(String path, String data, int version) { - if (runnable.get() != null) { - runnable.get().run(); - } - super.update(path, data, version); - } - }; + @Override + protected void update(String path, String data, int version) { + if (runnable.get() != null) { + runnable.get().run(); + } + super.update(path, data, version); + } + }; curatorClient.delete(path); curatorClient.createOrUpdate(path, "version 0", false); @@ -377,23 +385,25 @@ class CuratorZookeeperClientTest { // test create failed when others create success String path = "/dubbo/mapping/org.apache.dubbo.demo.DemoService"; AtomicReference runnable = new AtomicReference<>(); - CuratorZookeeperClient curatorClient = new CuratorZookeeperClient(URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { - @Override - protected void createEphemeral(String path, String data, boolean faultTolerant) { - if (runnable.get() != null) { - runnable.get().run(); - } - super.createPersistent(path, data, faultTolerant); - } + CuratorZookeeperClient curatorClient = + new CuratorZookeeperClient( + URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { + @Override + protected void createEphemeral(String path, String data, boolean faultTolerant) { + if (runnable.get() != null) { + runnable.get().run(); + } + super.createPersistent(path, data, faultTolerant); + } - @Override - protected void update(String path, String data, int version) { - if (runnable.get() != null) { - runnable.get().run(); - } - super.update(path, data, version); - } - }; + @Override + protected void update(String path, String data, int version) { + if (runnable.get() != null) { + runnable.get().run(); + } + super.update(path, data, version); + } + }; curatorClient.delete(path); runnable.set(() -> { @@ -403,7 +413,8 @@ class CuratorZookeeperClientTest { throw new RuntimeException(e); } }); - Assertions.assertThrows(IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", true, 0)); + Assertions.assertThrows( + IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", true, 0)); Assertions.assertEquals("version x", curatorClient.getContent(path)); client.setData().forPath(path, "version 1".getBytes(StandardCharsets.UTF_8)); @@ -417,7 +428,8 @@ class CuratorZookeeperClientTest { } }); int version1 = ((Stat) configItem.getTicket()).getVersion(); - Assertions.assertThrows(IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 2", true, version1)); + Assertions.assertThrows( + IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 2", true, version1)); Assertions.assertEquals("version x", curatorClient.getContent(path)); runnable.set(null); @@ -433,11 +445,13 @@ class CuratorZookeeperClientTest { void testEphemeralCas2() { // test update failed when others create success String path = "/dubbo/mapping/org.apache.dubbo.demo.DemoService"; - CuratorZookeeperClient curatorClient = new CuratorZookeeperClient(URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")); + CuratorZookeeperClient curatorClient = new CuratorZookeeperClient( + URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")); curatorClient.delete(path); curatorClient.createOrUpdate(path, "version x", true); - Assertions.assertThrows(IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", true, null)); + Assertions.assertThrows( + IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", true, null)); Assertions.assertEquals("version x", curatorClient.getContent(path)); curatorClient.close(); @@ -447,23 +461,25 @@ class CuratorZookeeperClientTest { void testEphemeralNonVersion() { String path = "/dubbo/metadata/org.apache.dubbo.demo.DemoService"; AtomicReference runnable = new AtomicReference<>(); - CuratorZookeeperClient curatorClient = new CuratorZookeeperClient(URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { - @Override - protected void createPersistent(String path, String data, boolean faultTolerant) { - if (runnable.get() != null) { - runnable.get().run(); - } - super.createPersistent(path, data, faultTolerant); - } + CuratorZookeeperClient curatorClient = + new CuratorZookeeperClient( + URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { + @Override + protected void createPersistent(String path, String data, boolean faultTolerant) { + if (runnable.get() != null) { + runnable.get().run(); + } + super.createPersistent(path, data, faultTolerant); + } - @Override - protected void update(String path, String data, int version) { - if (runnable.get() != null) { - runnable.get().run(); - } - super.update(path, data, version); - } - }; + @Override + protected void update(String path, String data, int version) { + if (runnable.get() != null) { + runnable.get().run(); + } + super.update(path, data, version); + } + }; curatorClient.delete(path); curatorClient.createOrUpdate(path, "version 0", true); @@ -496,5 +512,4 @@ class CuratorZookeeperClientTest { curatorClient.close(); } - } diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperTransporterTest.java b/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperTransporterTest.java index 8831ab6527..328107ae13 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperTransporterTest.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperTransporterTest.java @@ -42,7 +42,8 @@ class CuratorZookeeperTransporterTest { @BeforeEach public void setUp() throws Exception { - zookeeperClient = new CuratorZookeeperTransporter().connect(URL.valueOf(zookeeperConnectionAddress1 + "/service")); + zookeeperClient = + new CuratorZookeeperTransporter().connect(URL.valueOf(zookeeperConnectionAddress1 + "/service")); curatorZookeeperTransporter = new CuratorZookeeperTransporter(); } @@ -51,5 +52,4 @@ class CuratorZookeeperTransporterTest { assertThat(zookeeperClient, not(nullValue())); zookeeperClient.close(); } - } diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator/support/AbstractZookeeperTransporterTest.java b/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator/support/AbstractZookeeperTransporterTest.java index 506a4f41af..37cc93c0f2 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator/support/AbstractZookeeperTransporterTest.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator/support/AbstractZookeeperTransporterTest.java @@ -21,6 +21,8 @@ import org.apache.dubbo.remoting.zookeeper.AbstractZookeeperTransporter; import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; import org.apache.dubbo.remoting.zookeeper.curator.CuratorZookeeperTransporter; +import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; @@ -28,8 +30,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.DisabledForJreRange; import org.junit.jupiter.api.condition.JRE; -import java.util.List; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNull.nullValue; @@ -49,14 +49,16 @@ class AbstractZookeeperTransporterTest { public static void beforeAll() { zookeeperConnectionAddress1 = System.getProperty("zookeeper.connection.address.1"); zookeeperConnectionAddress2 = System.getProperty("zookeeper.connection.address.2"); - zookeeperServerPort1 = Integer.parseInt(zookeeperConnectionAddress1.substring(zookeeperConnectionAddress1.lastIndexOf(":") + 1)); - zookeeperServerPort2 = Integer.parseInt(zookeeperConnectionAddress2.substring(zookeeperConnectionAddress2.lastIndexOf(":") + 1)); + zookeeperServerPort1 = Integer.parseInt( + zookeeperConnectionAddress1.substring(zookeeperConnectionAddress1.lastIndexOf(":") + 1)); + zookeeperServerPort2 = Integer.parseInt( + zookeeperConnectionAddress2.substring(zookeeperConnectionAddress2.lastIndexOf(":") + 1)); } @BeforeEach public void setUp() throws Exception { - zookeeperClient = new CuratorZookeeperTransporter().connect(URL.valueOf("zookeeper://127.0.0.1:" + - zookeeperServerPort1 + "/service")); + zookeeperClient = new CuratorZookeeperTransporter() + .connect(URL.valueOf("zookeeper://127.0.0.1:" + zookeeperServerPort1 + "/service")); abstractZookeeperTransporter = new CuratorZookeeperTransporter(); } @@ -68,7 +70,9 @@ class AbstractZookeeperTransporterTest { @Test void testGetURLBackupAddress() { - URL url = URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + 9099 + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); + URL url = URL.valueOf( + zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + 9099 + + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); List stringList = abstractZookeeperTransporter.getURLBackupAddress(url); Assertions.assertEquals(stringList.size(), 2); Assertions.assertEquals(stringList.get(0), "127.0.0.1:" + zookeeperServerPort1); @@ -77,7 +81,9 @@ class AbstractZookeeperTransporterTest { @Test void testGetURLBackupAddressNoBack() { - URL url = URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); + URL url = URL.valueOf( + zookeeperConnectionAddress1 + + "/org.apache.dubbo.registry.RegistryService?application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); List stringList = abstractZookeeperTransporter.getURLBackupAddress(url); Assertions.assertEquals(stringList.size(), 1); Assertions.assertEquals(stringList.get(0), "127.0.0.1:" + zookeeperServerPort1); @@ -85,16 +91,27 @@ class AbstractZookeeperTransporterTest { @Test void testFetchAndUpdateZookeeperClientCache() { - URL url = URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + zookeeperServerPort1 + ",127.0.0.1:" + zookeeperServerPort2 + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); + URL url = URL.valueOf( + zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + + zookeeperServerPort1 + ",127.0.0.1:" + zookeeperServerPort2 + + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); ZookeeperClient newZookeeperClient = abstractZookeeperTransporter.connect(url); - //just for connected + // just for connected newZookeeperClient.getContent("/dubbo/test"); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), + newZookeeperClient); - URL url2 = URL.valueOf("zookeeper://127.0.0.1:" + zookeeperServerPort1 + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); + URL url2 = URL.valueOf( + "zookeeper://127.0.0.1:" + zookeeperServerPort1 + + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); checkFetchAndUpdateCacheNotNull(url2); - URL url3 = URL.valueOf("zookeeper://127.0.0.1:8778/org.apache.dubbo.metadata.store.MetadataReport?backup=127.0.0.1:" + zookeeperServerPort2 + "&address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); + URL url3 = URL.valueOf( + "zookeeper://127.0.0.1:8778/org.apache.dubbo.metadata.store.MetadataReport?backup=127.0.0.1:" + + zookeeperServerPort2 + + "&address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); checkFetchAndUpdateCacheNotNull(url3); } @@ -106,80 +123,120 @@ class AbstractZookeeperTransporterTest { @Test void testRepeatConnect() { - URL url = URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); - URL url2 = URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); + URL url = URL.valueOf( + zookeeperConnectionAddress1 + + "/org.apache.dubbo.registry.RegistryService?application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); + URL url2 = URL.valueOf( + zookeeperConnectionAddress1 + + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); ZookeeperClient newZookeeperClient = abstractZookeeperTransporter.connect(url); - //just for connected + // just for connected newZookeeperClient.getContent("/dubbo/test"); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), + newZookeeperClient); Assertions.assertTrue(newZookeeperClient.isConnected()); ZookeeperClient newZookeeperClient2 = abstractZookeeperTransporter.connect(url2); - //just for connected + // just for connected newZookeeperClient2.getContent("/dubbo/test"); Assertions.assertEquals(newZookeeperClient, newZookeeperClient2); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), + newZookeeperClient); } @Test void testNotRepeatConnect() { - URL url = URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); - URL url2 = URL.valueOf(zookeeperConnectionAddress2 + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); + URL url = URL.valueOf( + zookeeperConnectionAddress1 + + "/org.apache.dubbo.registry.RegistryService?application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); + URL url2 = URL.valueOf( + zookeeperConnectionAddress2 + + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); ZookeeperClient newZookeeperClient = abstractZookeeperTransporter.connect(url); - //just for connected + // just for connected newZookeeperClient.getContent("/dubbo/test"); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), + newZookeeperClient); ZookeeperClient newZookeeperClient2 = abstractZookeeperTransporter.connect(url2); - //just for connected + // just for connected newZookeeperClient2.getContent("/dubbo/test"); Assertions.assertNotEquals(newZookeeperClient, newZookeeperClient2); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort2), newZookeeperClient2); - + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort2), + newZookeeperClient2); } @Test void testRepeatConnectForBackUpAdd() { - URL url = URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + zookeeperServerPort1 + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); - URL url2 = URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.metadata.store.MetadataReport?backup=127.0.0.1:" + zookeeperServerPort2 + "&address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); + URL url = URL.valueOf( + zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + + zookeeperServerPort1 + + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); + URL url2 = URL.valueOf( + zookeeperConnectionAddress1 + "/org.apache.dubbo.metadata.store.MetadataReport?backup=127.0.0.1:" + + zookeeperServerPort2 + + "&address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); ZookeeperClient newZookeeperClient = abstractZookeeperTransporter.connect(url); - //just for connected + // just for connected newZookeeperClient.getContent("/dubbo/test"); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), + newZookeeperClient); ZookeeperClient newZookeeperClient2 = abstractZookeeperTransporter.connect(url2); - //just for connected + // just for connected newZookeeperClient2.getContent("/dubbo/test"); Assertions.assertEquals(newZookeeperClient, newZookeeperClient2); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort2), newZookeeperClient2); - + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort2), + newZookeeperClient2); } @Test void testRepeatConnectForNoMatchBackUpAdd() { - URL url = URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + zookeeperServerPort1 + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); - URL url2 = URL.valueOf(zookeeperConnectionAddress2 + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); + URL url = URL.valueOf( + zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + + zookeeperServerPort1 + + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828"); + URL url2 = URL.valueOf( + zookeeperConnectionAddress2 + + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); ZookeeperClient newZookeeperClient = abstractZookeeperTransporter.connect(url); - //just for connected + // just for connected newZookeeperClient.getContent("/dubbo/test"); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), + newZookeeperClient); ZookeeperClient newZookeeperClient2 = abstractZookeeperTransporter.connect(url2); - //just for connected + // just for connected newZookeeperClient2.getContent("/dubbo/test"); Assertions.assertNotEquals(newZookeeperClient, newZookeeperClient2); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); - Assertions.assertEquals(abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort2), newZookeeperClient2); - + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); + Assertions.assertEquals( + abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort2), + newZookeeperClient2); } @Test diff --git a/dubbo-remoting/pom.xml b/dubbo-remoting/pom.xml index f50a4a97ea..1a1d0cd0c4 100644 --- a/dubbo-remoting/pom.xml +++ b/dubbo-remoting/pom.xml @@ -16,37 +16,37 @@ limitations under the License. --> - 4.0.0 - - org.apache.dubbo - dubbo-parent - ${revision} - ../pom.xml - - dubbo-remoting - pom - ${project.artifactId} - The remoting module of dubbo project - - false - - - dubbo-remoting-api - dubbo-remoting-http - dubbo-remoting-netty - dubbo-remoting-zookeeper-api - dubbo-remoting-zookeeper - dubbo-remoting-zookeeper-curator5 - dubbo-remoting-netty4 - dubbo-remoting-http12 - + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + + dubbo-remoting + pom + ${project.artifactId} + The remoting module of dubbo project + + dubbo-remoting-api + dubbo-remoting-http + dubbo-remoting-netty + dubbo-remoting-zookeeper-api + dubbo-remoting-zookeeper + dubbo-remoting-zookeeper-curator5 + dubbo-remoting-netty4 + dubbo-remoting-http12 + + + false + - - - org.apache.dubbo - dubbo-test-check - ${project.parent.version} - test - - + + + org.apache.dubbo + dubbo-test-check + ${project.parent.version} + test + + diff --git a/dubbo-rpc/dubbo-rpc-api/pom.xml b/dubbo-rpc/dubbo-rpc-api/pom.xml index a408832bcd..93c0f77cbc 100644 --- a/dubbo-rpc/dubbo-rpc-api/pom.xml +++ b/dubbo-rpc/dubbo-rpc-api/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-rpc - ${revision} - ../pom.xml - - dubbo-rpc-api - jar - ${project.artifactId} - The rpc module of dubbo project - - false - - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - org.apache.dubbo - dubbo-serialization-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-api - ${project.parent.version} - - - com.alibaba - hessian-lite - test - - - org.slf4j - slf4j-log4j12 - test - - + 4.0.0 + + org.apache.dubbo + dubbo-rpc + ${revision} + ../pom.xml + + dubbo-rpc-api + jar + ${project.artifactId} + The rpc module of dubbo project + + false + + + + org.apache.dubbo + dubbo-common + ${project.parent.version} + + + org.apache.dubbo + dubbo-serialization-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-remoting-api + ${project.parent.version} + + + com.alibaba + hessian-lite + test + + + org.slf4j + slf4j-log4j12 + test + + diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AppResponse.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AppResponse.java index a41bc386cd..5e3906b732 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AppResponse.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AppResponse.java @@ -61,8 +61,7 @@ public class AppResponse implements Result { private final Map attributes = new HashMap<>(); - public AppResponse() { - } + public AppResponse() {} public AppResponse(Invocation invocation) { this.setAttribute(INVOCATION_KEY, invocation); @@ -88,10 +87,12 @@ public class AppResponse implements Result { } catch (Exception e) { // ignore } - if (Dubbo2CompactUtils.isEnabled() && Dubbo2RpcExceptionUtils.isRpcExceptionClassLoaded() - && (exception instanceof RpcException) && !Dubbo2RpcExceptionUtils.getRpcExceptionClass().isAssignableFrom(exception.getClass())) { - RpcException recreated = Dubbo2RpcExceptionUtils.newRpcException(((RpcException) exception).getCode(), - exception.getMessage(), exception.getCause()); + if (Dubbo2CompactUtils.isEnabled() + && Dubbo2RpcExceptionUtils.isRpcExceptionClassLoaded() + && (exception instanceof RpcException) + && !Dubbo2RpcExceptionUtils.getRpcExceptionClass().isAssignableFrom(exception.getClass())) { + RpcException recreated = Dubbo2RpcExceptionUtils.newRpcException( + ((RpcException) exception).getCode(), exception.getMessage(), exception.getCause()); if (recreated != null) { recreated.setStackTrace(exception.getStackTrace()); throw recreated; @@ -233,22 +234,26 @@ public class AppResponse implements Result { @Override public Result whenCompleteWithContext(BiConsumer fn) { - throw new UnsupportedOperationException("AppResponse represents an concrete business response, there will be no status changes, you should get internal values directly."); + throw new UnsupportedOperationException( + "AppResponse represents an concrete business response, there will be no status changes, you should get internal values directly."); } @Override public CompletableFuture thenApply(Function fn) { - throw new UnsupportedOperationException("AppResponse represents an concrete business response, there will be no status changes, you should get internal values directly."); + throw new UnsupportedOperationException( + "AppResponse represents an concrete business response, there will be no status changes, you should get internal values directly."); } @Override public Result get() throws InterruptedException, ExecutionException { - throw new UnsupportedOperationException("AppResponse represents an concrete business response, there will be no status changes, you should get internal values directly."); + throw new UnsupportedOperationException( + "AppResponse represents an concrete business response, there will be no status changes, you should get internal values directly."); } @Override public Result get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { - throw new UnsupportedOperationException("AppResponse represents an concrete business response, there will be no status changes, you should get internal values directly."); + throw new UnsupportedOperationException( + "AppResponse represents an concrete business response, there will be no status changes, you should get internal values directly."); } public void clear() { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncContextImpl.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncContextImpl.java index 4ff3368aa0..26ecb91008 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncContextImpl.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncContextImpl.java @@ -45,7 +45,8 @@ public class AsyncContextImpl implements AsyncContext { future.complete(value); } } else { - throw new IllegalStateException("The async response has probably been wrote back by another thread, or the asyncContext has been closed."); + throw new IllegalStateException( + "The async response has probably been wrote back by another thread, or the asyncContext has been closed."); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncRpcResult.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncRpcResult.java index 39e5cceb74..4f9551ff6e 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncRpcResult.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncRpcResult.java @@ -69,13 +69,15 @@ public class AsyncRpcResult implements Result { /** * Whether set future to Thread Local when invocation mode is sync */ - private static final boolean setFutureWhenSync = Boolean.parseBoolean(System.getProperty(CommonConstants.SET_FUTURE_IN_SYNC_MODE, "true")); + private static final boolean setFutureWhenSync = + Boolean.parseBoolean(System.getProperty(CommonConstants.SET_FUTURE_IN_SYNC_MODE, "true")); public AsyncRpcResult(CompletableFuture future, Invocation invocation) { this.responseFuture = future; this.invocation = invocation; RpcInvocation rpcInvocation = (RpcInvocation) invocation; - if ((rpcInvocation.get(PROVIDER_ASYNC_KEY) != null || InvokeMode.SYNC != rpcInvocation.getInvokeMode()) && !future.isDone()) { + if ((rpcInvocation.get(PROVIDER_ASYNC_KEY) != null || InvokeMode.SYNC != rpcInvocation.getInvokeMode()) + && !future.isDone()) { async = true; this.storedContext = RpcContext.clearAndStoreContext(); } else { @@ -115,7 +117,11 @@ public class AsyncRpcResult implements Result { } } catch (Exception e) { // This should not happen in normal request process; - logger.error(PROXY_ERROR_ASYNC_RESPONSE, "", "", "Got exception when trying to fetch the underlying result from AsyncRpcResult."); + logger.error( + PROXY_ERROR_ASYNC_RESPONSE, + "", + "", + "Got exception when trying to fetch the underlying result from AsyncRpcResult."); throw new RpcException(e); } } @@ -137,7 +143,11 @@ public class AsyncRpcResult implements Result { } } catch (Exception e) { // This should not happen in normal request process; - logger.error(PROXY_ERROR_ASYNC_RESPONSE, "", "", "Got exception when trying to fetch the underlying result from AsyncRpcResult."); + logger.error( + PROXY_ERROR_ASYNC_RESPONSE, + "", + "", + "Got exception when trying to fetch the underlying result from AsyncRpcResult."); throw new RpcException(e); } } @@ -162,7 +172,11 @@ public class AsyncRpcResult implements Result { } } catch (Exception e) { // This should not happen in normal request process; - logger.error(PROXY_ERROR_ASYNC_RESPONSE, "", "", "Got exception when trying to fetch the underlying result from AsyncRpcResult."); + logger.error( + PROXY_ERROR_ASYNC_RESPONSE, + "", + "", + "Got exception when trying to fetch the underlying result from AsyncRpcResult."); throw new RpcException(e); } @@ -204,7 +218,8 @@ public class AsyncRpcResult implements Result { if (restTime > 0) { threadlessExecutor.waitAndDrain(deadline); } else { - throw new TimeoutException("Timeout after " + unit.toMillis(timeout) + "ms waiting for result."); + throw new TimeoutException( + "Timeout after " + unit.toMillis(timeout) + "ms waiting for result."); } } } finally { @@ -362,4 +377,3 @@ public class AsyncRpcResult implements Result { return method != null ? new AppResponse(defaultReturn(method.getReturnClass())) : new AppResponse(); } } - diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/CancellationContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/CancellationContext.java index 49ebc93b0a..8142066231 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/CancellationContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/CancellationContext.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc; import java.io.Closeable; @@ -29,26 +28,20 @@ public class CancellationContext implements Closeable { private Throwable cancellationCause; private boolean cancelled; - public void addListener( - final CancellationListener cancellationListener, final Executor executor) { + public void addListener(final CancellationListener cancellationListener, final Executor executor) { addListener(cancellationListener, executor, null); } - public void addListener( - final CancellationListener cancellationListener) { + public void addListener(final CancellationListener cancellationListener) { addListener(cancellationListener, Runnable::run, null); } - public void addListener( - final CancellationListener cancellationListener, - final RpcServiceContext context) { + public void addListener(final CancellationListener cancellationListener, final RpcServiceContext context) { addListener(cancellationListener, Runnable::run, context); } public void addListener( - final CancellationListener cancellationListener, - final Executor executor, - final RpcServiceContext context) { + final CancellationListener cancellationListener, final Executor executor, final RpcServiceContext context) { addListenerInternal(new ExecutableListener(executor, cancellationListener, context)); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/CancellationListener.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/CancellationListener.java index 5f32510094..5e3573ca60 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/CancellationListener.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/CancellationListener.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc; /** @@ -28,5 +27,4 @@ public interface CancellationListener { * @param context the newly cancelled context. */ void cancelled(RpcServiceContext context); - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Constants.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Constants.java index 1cdb86d347..e660ae1634 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Constants.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Constants.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc; public interface Constants { diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ExecutableListener.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ExecutableListener.java index edfc05a49d..d3935df028 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ExecutableListener.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ExecutableListener.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -24,7 +23,6 @@ import java.util.concurrent.Executor; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_NOTIFY_EVENT; - public class ExecutableListener implements Runnable { private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(ExecutableListener.class); @@ -43,7 +41,6 @@ public class ExecutableListener implements Runnable { this(executor, listener, null); } - public void deliver() { try { executor.execute(this); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Exporter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Exporter.java index fd3d58bc8e..15d3022f1a 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Exporter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Exporter.java @@ -50,5 +50,4 @@ public interface Exporter { * unregister from registry */ void unregister(); - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ExporterListener.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ExporterListener.java index 68197469b4..8d16129d87 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ExporterListener.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ExporterListener.java @@ -42,5 +42,4 @@ public interface ExporterListener { * @see org.apache.dubbo.rpc.Exporter#unexport() */ void unexported(Exporter exporter); - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Filter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Filter.java index 79fea6e866..ae2c2026cb 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Filter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Filter.java @@ -66,6 +66,4 @@ import org.apache.dubbo.common.extension.SPI; * @see org.apache.dubbo.rpc.filter.TpsLimitFilter */ @SPI(scope = ExtensionScope.MODULE) -public interface Filter extends BaseFilter { -} - +public interface Filter extends BaseFilter {} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/FutureContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/FutureContext.java index d17a244b15..c125fb3c9c 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/FutureContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/FutureContext.java @@ -48,7 +48,8 @@ public class FutureContext { /** * Whether clear future once get */ - private final static boolean clearFutureAfterGet = Boolean.parseBoolean(System.getProperty(CommonConstants.CLEAR_FUTURE_AFTER_GET, "false")); + private static final boolean clearFutureAfterGet = + Boolean.parseBoolean(System.getProperty(CommonConstants.CLEAR_FUTURE_AFTER_GET, "false")); /** * get future. @@ -122,5 +123,4 @@ public class FutureContext { this.setFuture(new FutureAdapter(compatibleFuture)); } } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Invocation.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Invocation.java index b40fa05e8a..7f4e3f534a 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Invocation.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Invocation.java @@ -48,7 +48,6 @@ public interface Invocation { */ String getMethodName(); - /** * get the interface name * @@ -70,9 +69,7 @@ public interface Invocation { * @return parameter's signature */ default String[] getCompatibleParamSignatures() { - return Stream.of(getParameterTypes()) - .map(Class::getName) - .toArray(String[]::new); + return Stream.of(getParameterTypes()).map(Class::getName).toArray(String[]::new); } /** @@ -157,7 +154,8 @@ public interface Invocation { ServiceModel getServiceModel(); default ModuleModel getModuleModel() { - return ScopeModelUtil.getModuleModel(getServiceModel() == null ? null : getServiceModel().getModuleModel()); + return ScopeModelUtil.getModuleModel( + getServiceModel() == null ? null : getServiceModel().getModuleModel()); } Object put(Object key, Object value); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/InvokeMode.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/InvokeMode.java index a97a0be61f..fec363900d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/InvokeMode.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/InvokeMode.java @@ -17,7 +17,7 @@ package org.apache.dubbo.rpc; public enum InvokeMode { - - SYNC, ASYNC, FUTURE; - + SYNC, + ASYNC, + FUTURE; } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Invoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Invoker.java index 6bf3a3a3ce..0151b89959 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Invoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Invoker.java @@ -42,5 +42,4 @@ public interface Invoker extends Node { * @throws RpcException */ Result invoke(Invocation invocation) throws RpcException; - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/InvokerListener.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/InvokerListener.java index b81de6ab4c..94f0bc6937 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/InvokerListener.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/InvokerListener.java @@ -40,5 +40,4 @@ public interface InvokerListener { * @see org.apache.dubbo.rpc.Invoker#destroy() */ void destroyed(Invoker invoker); - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/PathResolver.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/PathResolver.java index 83c5979cb8..ba8d17cdcc 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/PathResolver.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/PathResolver.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc; import org.apache.dubbo.common.constants.CommonConstants; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/PenetrateAttachmentSelector.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/PenetrateAttachmentSelector.java index 13bad8aa2e..906e867ae0 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/PenetrateAttachmentSelector.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/PenetrateAttachmentSelector.java @@ -29,7 +29,11 @@ public interface PenetrateAttachmentSelector { * * @return attachment pass to next hop */ - Map select(Invocation invocation, RpcContextAttachment clientAttachment, RpcContextAttachment serverAttachment); - Map selectReverse(Invocation invocation, RpcContextAttachment clientResponseContext, RpcContextAttachment serverResponseContext); + Map select( + Invocation invocation, RpcContextAttachment clientAttachment, RpcContextAttachment serverAttachment); + Map selectReverse( + Invocation invocation, + RpcContextAttachment clientResponseContext, + RpcContextAttachment serverResponseContext); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Protocol.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Protocol.java index 0bbc24f34c..910d030e40 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Protocol.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Protocol.java @@ -115,5 +115,4 @@ public interface Protocol { default List getServers() { return Collections.emptyList(); } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ProtocolServer.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ProtocolServer.java index 08141111e5..eb3e1700e5 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ProtocolServer.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ProtocolServer.java @@ -31,8 +31,7 @@ public interface ProtocolServer { return null; } - default void setRemotingServers(RemotingServer server) { - } + default void setRemotingServers(RemotingServer server) {} String getAddress(); @@ -42,8 +41,7 @@ public interface ProtocolServer { return null; } - default void reset(URL url) { - } + default void reset(URL url) {} void close(); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ProxyFactory.java index dcd51ac092..c681c0ddea 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ProxyFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ProxyFactory.java @@ -58,5 +58,4 @@ public interface ProxyFactory { */ @Adaptive({PROXY_KEY}) Invoker getInvoker(T proxy, Class type, URL url) throws RpcException; - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Result.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Result.java index b0dd6f6286..cd3b4a7bfd 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Result.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Result.java @@ -29,7 +29,6 @@ import java.util.concurrent.TimeoutException; import java.util.function.BiConsumer; import java.util.function.Function; - /** * (API, Prototype, NonThreadSafe) * diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcConstants.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcConstants.java index 18e6ed3c15..f771aea066 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcConstants.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcConstants.java @@ -28,10 +28,8 @@ import org.apache.dubbo.common.constants.RemotingConstants; * @deprecated Replace to org.apache.dubbo.common.Constants */ @Deprecated -public final class RpcConstants implements CommonConstants, QosConstants, FilterConstants, - RegistryConstants, RemotingConstants { - - private RpcConstants() { - } +public final class RpcConstants + implements CommonConstants, QosConstants, FilterConstants, RegistryConstants, RemotingConstants { + private RpcConstants() {} } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java index 33a302e03a..12d00716cf 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.java @@ -29,7 +29,6 @@ import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; - /** * Thread local context. (API, ThreadLocal, ThreadSafe) *

    @@ -56,52 +55,56 @@ public class RpcContext { /** * use internal thread local to improve performance */ + private static final InternalThreadLocal CLIENT_RESPONSE_LOCAL = + new InternalThreadLocal() { + @Override + protected RpcContextAttachment initialValue() { + return new RpcContextAttachment(); + } + }; - private static final InternalThreadLocal CLIENT_RESPONSE_LOCAL = new InternalThreadLocal() { - @Override - protected RpcContextAttachment initialValue() { - return new RpcContextAttachment(); - } - }; + private static final InternalThreadLocal SERVER_RESPONSE_LOCAL = + new InternalThreadLocal() { + @Override + protected RpcContextAttachment initialValue() { + return new RpcContextAttachment(); + } + }; - private static final InternalThreadLocal SERVER_RESPONSE_LOCAL = new InternalThreadLocal() { - @Override - protected RpcContextAttachment initialValue() { - return new RpcContextAttachment(); - } - }; + private static final InternalThreadLocal CLIENT_ATTACHMENT = + new InternalThreadLocal() { + @Override + protected RpcContextAttachment initialValue() { + return new RpcContextAttachment(); + } + }; - private static final InternalThreadLocal CLIENT_ATTACHMENT = new InternalThreadLocal() { - @Override - protected RpcContextAttachment initialValue() { - return new RpcContextAttachment(); - } - }; + private static final InternalThreadLocal SERVER_ATTACHMENT = + new InternalThreadLocal() { + @Override + protected RpcContextAttachment initialValue() { + return new RpcContextAttachment(); + } + }; - private static final InternalThreadLocal SERVER_ATTACHMENT = new InternalThreadLocal() { - @Override - protected RpcContextAttachment initialValue() { - return new RpcContextAttachment(); - } - }; - - private static final InternalThreadLocal SERVICE_CONTEXT = new InternalThreadLocal() { - @Override - protected RpcServiceContext initialValue() { - return new RpcServiceContext(); - } - }; + private static final InternalThreadLocal SERVICE_CONTEXT = + new InternalThreadLocal() { + @Override + protected RpcServiceContext initialValue() { + return new RpcServiceContext(); + } + }; /** * use by cancel call */ - private static final InternalThreadLocal CANCELLATION_CONTEXT = new InternalThreadLocal() { - @Override - protected CancellationContext initialValue() { - return new CancellationContext(); - } - }; - + private static final InternalThreadLocal CANCELLATION_CONTEXT = + new InternalThreadLocal() { + @Override + protected CancellationContext initialValue() { + return new CancellationContext(); + } + }; public static CancellationContext getCancellationContext() { return CANCELLATION_CONTEXT.get(); @@ -117,8 +120,7 @@ public class RpcContext { private boolean remove = true; - protected RpcContext() { - } + protected RpcContext() {} /** * get server side context. ( A <-- B , in B side) @@ -180,7 +182,7 @@ public class RpcContext { public static void removeServerContext() { RpcContextAttachment rpcContextAttachment = RpcContext.getServerContext(); - for(String key : rpcContextAttachment.attachments.keySet()) { + for (String key : rpcContextAttachment.attachments.keySet()) { rpcContextAttachment.remove(key); } } @@ -603,7 +605,11 @@ public class RpcContext { */ @Experimental("Experiment api for supporting Object transmission") public Map getObjectAttachments() { - Map result = new HashMap<>((int) ((CLIENT_ATTACHMENT.get().attachments.size() + SERVER_ATTACHMENT.get().attachments.size()) / .75) + 1); + Map result = + new HashMap<>((int) ((CLIENT_ATTACHMENT.get().attachments.size() + + SERVER_ATTACHMENT.get().attachments.size()) + / .75) + + 1); result.putAll(SERVER_ATTACHMENT.get().attachments); result.putAll(CLIENT_ATTACHMENT.get().attachments); return result; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContextAttachment.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContextAttachment.java index 850a8dd641..e0c70c38ac 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContextAttachment.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContextAttachment.java @@ -22,13 +22,12 @@ import org.apache.dubbo.common.utils.CollectionUtils; import java.util.HashMap; import java.util.Map; -public class RpcContextAttachment extends RpcContext{ +public class RpcContextAttachment extends RpcContext { protected volatile Map attachments = new HashMap<>(); // only useful on provider side. protected AsyncContext asyncContext; - protected RpcContextAttachment() { - } + protected RpcContextAttachment() {} /** * @return diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcException.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcException.java index 4d6876fd41..5d076adeda 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcException.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcException.java @@ -111,7 +111,7 @@ public class RpcException extends RuntimeException { return code == SERIALIZATION_EXCEPTION; } - public boolean isAuthorization(){ + public boolean isAuthorization() { return code == AUTHORIZATION_EXCEPTION; } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java index e46a6b274f..4c69c49933 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.java @@ -16,6 +16,16 @@ */ package org.apache.dubbo.rpc; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.utils.ReflectUtils; +import org.apache.dubbo.common.utils.StringUtils; +import org.apache.dubbo.rpc.model.FrameworkModel; +import org.apache.dubbo.rpc.model.MethodDescriptor; +import org.apache.dubbo.rpc.model.ProviderModel; +import org.apache.dubbo.rpc.model.ServiceDescriptor; +import org.apache.dubbo.rpc.model.ServiceModel; +import org.apache.dubbo.rpc.support.RpcUtils; + import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.Type; @@ -32,16 +42,6 @@ import java.util.concurrent.locks.ReentrantLock; import java.util.function.Consumer; import java.util.stream.Stream; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.ReflectUtils; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.rpc.model.FrameworkModel; -import org.apache.dubbo.rpc.model.MethodDescriptor; -import org.apache.dubbo.rpc.model.ProviderModel; -import org.apache.dubbo.rpc.model.ServiceDescriptor; -import org.apache.dubbo.rpc.model.ServiceModel; -import org.apache.dubbo.rpc.support.RpcUtils; - import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; @@ -100,8 +100,7 @@ public class RpcInvocation implements Invocation, Serializable { * @deprecated only for test */ @Deprecated - public RpcInvocation() { - } + public RpcInvocation() {} /** * Deep clone of an invocation @@ -119,10 +118,18 @@ public class RpcInvocation implements Invocation, Serializable { * @param invoker target invoker */ public RpcInvocation(Invocation invocation, Invoker invoker) { - this(invocation.getTargetServiceUniqueName(), invocation.getServiceModel(), invocation.getMethodName(), invocation.getServiceName(), - invocation.getProtocolServiceKey(), invocation.getParameterTypes(), invocation.getArguments(), - invocation.copyObjectAttachments(), invocation.getInvoker(), invocation.getAttributes(), - invocation instanceof RpcInvocation ? ((RpcInvocation) invocation).getInvokeMode() : null); + this( + invocation.getTargetServiceUniqueName(), + invocation.getServiceModel(), + invocation.getMethodName(), + invocation.getServiceName(), + invocation.getProtocolServiceKey(), + invocation.getParameterTypes(), + invocation.getArguments(), + invocation.copyObjectAttachments(), + invocation.getInvoker(), + invocation.getAttributes(), + invocation instanceof RpcInvocation ? ((RpcInvocation) invocation).getInvokeMode() : null); if (invoker != null) { URL url = invoker.getUrl(); setAttachment(PATH_KEY, url.getPath()); @@ -150,16 +157,49 @@ public class RpcInvocation implements Invocation, Serializable { /** * To create a brand-new invocation */ - public RpcInvocation(ServiceModel serviceModel, String methodName, String interfaceName, String protocolServiceKey, Class[] parameterTypes, Object[] arguments) { - this(null, serviceModel, methodName, interfaceName, protocolServiceKey, parameterTypes, arguments, null, null, null, null); + public RpcInvocation( + ServiceModel serviceModel, + String methodName, + String interfaceName, + String protocolServiceKey, + Class[] parameterTypes, + Object[] arguments) { + this( + null, + serviceModel, + methodName, + interfaceName, + protocolServiceKey, + parameterTypes, + arguments, + null, + null, + null, + null); } /** * @deprecated deprecated, will be removed in 3.1.x */ @Deprecated - public RpcInvocation(ServiceModel serviceModel, Method method, String interfaceName, String protocolServiceKey, Object[] arguments) { - this(null, serviceModel, method.getName(), interfaceName, protocolServiceKey, method.getParameterTypes(), arguments, null, null, null, null); + public RpcInvocation( + ServiceModel serviceModel, + Method method, + String interfaceName, + String protocolServiceKey, + Object[] arguments) { + this( + null, + serviceModel, + method.getName(), + interfaceName, + protocolServiceKey, + method.getParameterTypes(), + arguments, + null, + null, + null, + null); } /** @@ -167,81 +207,245 @@ public class RpcInvocation implements Invocation, Serializable { */ @Deprecated public RpcInvocation(Method method, String interfaceName, String protocolServiceKey, Object[] arguments) { - this(null, null, method.getName(), interfaceName, protocolServiceKey, method.getParameterTypes(), arguments, null, null, null, null); + this( + null, + null, + method.getName(), + interfaceName, + protocolServiceKey, + method.getParameterTypes(), + arguments, + null, + null, + null, + null); } /** * @deprecated deprecated, will be removed in 3.1.x */ @Deprecated - public RpcInvocation(ServiceModel serviceModel, Method method, String interfaceName, String protocolServiceKey, Object[] arguments, Map attachment, Map attributes) { - this(null, serviceModel, method.getName(), interfaceName, protocolServiceKey, method.getParameterTypes(), arguments, attachment, null, attributes, null); + public RpcInvocation( + ServiceModel serviceModel, + Method method, + String interfaceName, + String protocolServiceKey, + Object[] arguments, + Map attachment, + Map attributes) { + this( + null, + serviceModel, + method.getName(), + interfaceName, + protocolServiceKey, + method.getParameterTypes(), + arguments, + attachment, + null, + attributes, + null); } /** * @deprecated deprecated, will be removed in 3.1.x */ @Deprecated - public RpcInvocation(Method method, String interfaceName, String protocolServiceKey, Object[] arguments, Map attachment, Map attributes) { - this(null, null, method.getName(), interfaceName, protocolServiceKey, method.getParameterTypes(), arguments, attachment, null, attributes, null); + public RpcInvocation( + Method method, + String interfaceName, + String protocolServiceKey, + Object[] arguments, + Map attachment, + Map attributes) { + this( + null, + null, + method.getName(), + interfaceName, + protocolServiceKey, + method.getParameterTypes(), + arguments, + attachment, + null, + attributes, + null); } /** * @deprecated deprecated, will be removed in 3.1.x */ @Deprecated - public RpcInvocation(String methodName, String interfaceName, String protocolServiceKey, Class[] parameterTypes, Object[] arguments) { - this(null, null, methodName, interfaceName, protocolServiceKey, parameterTypes, arguments, null, null, null, null); + public RpcInvocation( + String methodName, + String interfaceName, + String protocolServiceKey, + Class[] parameterTypes, + Object[] arguments) { + this( + null, + null, + methodName, + interfaceName, + protocolServiceKey, + parameterTypes, + arguments, + null, + null, + null, + null); } /** * @deprecated deprecated, will be removed in 3.1.x */ @Deprecated - public RpcInvocation(ServiceModel serviceModel, String methodName, String interfaceName, String protocolServiceKey, Class[] parameterTypes, Object[] arguments, Map attachments) { - this(null, serviceModel, methodName, interfaceName, protocolServiceKey, parameterTypes, arguments, attachments, null, null, null); + public RpcInvocation( + ServiceModel serviceModel, + String methodName, + String interfaceName, + String protocolServiceKey, + Class[] parameterTypes, + Object[] arguments, + Map attachments) { + this( + null, + serviceModel, + methodName, + interfaceName, + protocolServiceKey, + parameterTypes, + arguments, + attachments, + null, + null, + null); } /** * @deprecated deprecated, will be removed in 3.1.x */ @Deprecated - public RpcInvocation(String methodName, String interfaceName, String protocolServiceKey, Class[] parameterTypes, Object[] arguments, Map attachments) { - this(null, null, methodName, interfaceName, protocolServiceKey, parameterTypes, arguments, attachments, null, null, null); + public RpcInvocation( + String methodName, + String interfaceName, + String protocolServiceKey, + Class[] parameterTypes, + Object[] arguments, + Map attachments) { + this( + null, + null, + methodName, + interfaceName, + protocolServiceKey, + parameterTypes, + arguments, + attachments, + null, + null, + null); } /** * @deprecated deprecated, will be removed in 3.1.x */ @Deprecated - public RpcInvocation(String methodName, String interfaceName, String protocolServiceKey, Class[] parameterTypes, Object[] arguments, - Map attachments, Invoker invoker, Map attributes) { - this(null, null, methodName, interfaceName, protocolServiceKey, parameterTypes, arguments, attachments, invoker, attributes, null); + public RpcInvocation( + String methodName, + String interfaceName, + String protocolServiceKey, + Class[] parameterTypes, + Object[] arguments, + Map attachments, + Invoker invoker, + Map attributes) { + this( + null, + null, + methodName, + interfaceName, + protocolServiceKey, + parameterTypes, + arguments, + attachments, + invoker, + attributes, + null); } /** * @deprecated deprecated, will be removed in 3.1.x */ @Deprecated - public RpcInvocation(ServiceModel serviceModel, String methodName, String interfaceName, String protocolServiceKey, Class[] parameterTypes, Object[] arguments, - Map attachments, Invoker invoker, Map attributes) { - this(null, serviceModel, methodName, interfaceName, protocolServiceKey, parameterTypes, arguments, attachments, invoker, attributes, null); + public RpcInvocation( + ServiceModel serviceModel, + String methodName, + String interfaceName, + String protocolServiceKey, + Class[] parameterTypes, + Object[] arguments, + Map attachments, + Invoker invoker, + Map attributes) { + this( + null, + serviceModel, + methodName, + interfaceName, + protocolServiceKey, + parameterTypes, + arguments, + attachments, + invoker, + attributes, + null); } /** * @deprecated deprecated, will be removed in 3.1.x */ @Deprecated - public RpcInvocation(ServiceModel serviceModel, String methodName, String interfaceName, String protocolServiceKey, Class[] parameterTypes, Object[] arguments, - Map attachments, Invoker invoker, Map attributes, InvokeMode invokeMode) { - this(null, serviceModel, methodName, interfaceName, protocolServiceKey, parameterTypes, arguments, attachments, invoker, attributes, invokeMode); + public RpcInvocation( + ServiceModel serviceModel, + String methodName, + String interfaceName, + String protocolServiceKey, + Class[] parameterTypes, + Object[] arguments, + Map attachments, + Invoker invoker, + Map attributes, + InvokeMode invokeMode) { + this( + null, + serviceModel, + methodName, + interfaceName, + protocolServiceKey, + parameterTypes, + arguments, + attachments, + invoker, + attributes, + invokeMode); } /** * To create a brand-new invocation */ - public RpcInvocation(String targetServiceUniqueName, ServiceModel serviceModel, String methodName, String interfaceName, String protocolServiceKey, Class[] parameterTypes, Object[] arguments, - Map attachments, Invoker invoker, Map attributes, InvokeMode invokeMode) { + public RpcInvocation( + String targetServiceUniqueName, + ServiceModel serviceModel, + String methodName, + String interfaceName, + String protocolServiceKey, + Class[] parameterTypes, + Object[] arguments, + Map attachments, + Invoker invoker, + Map attributes, + InvokeMode invokeMode) { this.targetServiceUniqueName = targetServiceUniqueName; this.serviceModel = serviceModel; this.methodName = methodName; @@ -262,14 +466,11 @@ public class RpcInvocation implements Invocation, Serializable { serviceDescriptor.set(serviceModel.getServiceModel()); } else if (StringUtils.isNotEmpty(interfaceName)) { // TODO: Multi Instance compatible mode - FrameworkModel.defaultModel() - .getServiceRepository() - .allProviderModels() - .stream() - .map(ProviderModel::getServiceModel) - .filter(s -> interfaceName.equals(s.getInterfaceName())) - .findFirst() - .ifPresent(serviceDescriptor::set); + FrameworkModel.defaultModel().getServiceRepository().allProviderModels().stream() + .map(ProviderModel::getServiceModel) + .filter(s -> interfaceName.equals(s.getInterfaceName())) + .findFirst() + .ifPresent(serviceDescriptor::set); } if (serviceDescriptor.get() != null) { @@ -282,10 +483,10 @@ public class RpcInvocation implements Invocation, Serializable { } } - if (parameterTypesDesc == null) { this.parameterTypesDesc = ReflectUtils.getDesc(this.getParameterTypes()); - this.compatibleParamSignatures = Stream.of(this.parameterTypes).map(Class::getName).toArray(String[]::new); + this.compatibleParamSignatures = + Stream.of(this.parameterTypes).map(Class::getName).toArray(String[]::new); this.returnTypes = RpcUtils.getReturnTypes(this); this.returnType = RpcUtils.getReturnType(this); } @@ -688,8 +889,6 @@ public class RpcInvocation implements Invocation, Serializable { @Override public String toString() { - return "RpcInvocation [methodName=" + methodName + ", parameterTypes=" - + Arrays.toString(parameterTypes) + "]"; + return "RpcInvocation [methodName=" + methodName + ", parameterTypes=" + Arrays.toString(parameterTypes) + "]"; } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcScopeModelInitializer.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcScopeModelInitializer.java index d246431565..cfde6bc9cc 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcScopeModelInitializer.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcScopeModelInitializer.java @@ -33,12 +33,8 @@ public class RpcScopeModelInitializer implements ScopeModelInitializer { } @Override - public void initializeApplicationModel(ApplicationModel applicationModel) { - - } + public void initializeApplicationModel(ApplicationModel applicationModel) {} @Override - public void initializeModuleModel(ModuleModel moduleModel) { - - } + public void initializeModuleModel(ModuleModel moduleModel) {} } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcServerContextAttachment.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcServerContextAttachment.java index c1bcdd79e6..4a35342ea5 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcServerContextAttachment.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcServerContextAttachment.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc; import java.util.Collection; @@ -152,9 +151,12 @@ public class RpcServerContextAttachment extends RpcContextAttachment { } private Map getAttachments() { - Map clientResponse = RpcContext.getClientResponseContext().getObjectAttachments(); - Map serverResponse = RpcContext.getServerResponseContext().getObjectAttachments(); - Map result = new HashMap<>((int) (clientResponse.size() + serverResponse.size() / 0.75) + 1); + Map clientResponse = + RpcContext.getClientResponseContext().getObjectAttachments(); + Map serverResponse = + RpcContext.getServerResponseContext().getObjectAttachments(); + Map result = + new HashMap<>((int) (clientResponse.size() + serverResponse.size() / 0.75) + 1); result.putAll(clientResponse); result.putAll(serverResponse); return result; @@ -167,20 +169,26 @@ public class RpcServerContextAttachment extends RpcContextAttachment { @Override public boolean isEmpty() { - return RpcContext.getClientResponseContext().getObjectAttachments().isEmpty() && - RpcContext.getServerResponseContext().getObjectAttachments().isEmpty(); + return RpcContext.getClientResponseContext().getObjectAttachments().isEmpty() + && RpcContext.getServerResponseContext() + .getObjectAttachments() + .isEmpty(); } @Override public boolean containsKey(Object key) { - return RpcContext.getClientResponseContext().getObjectAttachments().containsKey(key) || - RpcContext.getServerResponseContext().getObjectAttachments().containsKey(key); + return RpcContext.getClientResponseContext().getObjectAttachments().containsKey(key) + || RpcContext.getServerResponseContext() + .getObjectAttachments() + .containsKey(key); } @Override public boolean containsValue(Object value) { - return RpcContext.getClientResponseContext().getObjectAttachments().containsValue(value) || - RpcContext.getServerResponseContext().getObjectAttachments().containsValue(value); + return RpcContext.getClientResponseContext().getObjectAttachments().containsValue(value) + || RpcContext.getServerResponseContext() + .getObjectAttachments() + .containsValue(value); } @Override diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcServiceContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcServiceContext.java index c0f11894fd..5a8a640bd6 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcServiceContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcServiceContext.java @@ -36,8 +36,7 @@ import static org.apache.dubbo.rpc.Constants.RETURN_KEY; public class RpcServiceContext extends RpcContext { - protected RpcServiceContext() { - } + protected RpcServiceContext() {} // RPC service context updated before each service call. private URL consumerUrl; @@ -62,8 +61,10 @@ public class RpcServiceContext extends RpcContext { @Deprecated private List> invokers; + @Deprecated private Invoker invoker; + @Deprecated private Invocation invocation; @@ -381,8 +382,10 @@ public class RpcServiceContext extends RpcContext { */ @Override public String getLocalHost() { - String host = localAddress == null ? null : - localAddress.getAddress() == null ? localAddress.getHostName() + String host = localAddress == null + ? null + : localAddress.getAddress() == null + ? localAddress.getHostName() : NetUtils.filterLocalHost(localAddress.getAddress().getHostAddress()); if (host == null || host.length() == 0) { return NetUtils.getLocalHost(); @@ -407,8 +410,10 @@ public class RpcServiceContext extends RpcContext { */ @Override public String getRemoteHost() { - return remoteAddress == null ? null : - remoteAddress.getAddress() == null ? remoteAddress.getHostName() + return remoteAddress == null + ? null + : remoteAddress.getAddress() == null + ? remoteAddress.getHostName() : NetUtils.filterLocalHost(remoteAddress.getAddress().getHostAddress()); } @@ -514,7 +519,7 @@ public class RpcServiceContext extends RpcContext { try { setAttachment(ASYNC_KEY, Boolean.TRUE.toString()); final T o = callable.call(); - //local invoke will return directly + // local invoke will return directly if (o != null) { if (o instanceof CompletableFuture) { return (CompletableFuture) o; @@ -659,5 +664,4 @@ public class RpcServiceContext extends RpcContext { return this; } } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcStatus.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcStatus.java index 6ea826a116..30de38825d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcStatus.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcStatus.java @@ -33,11 +33,11 @@ import java.util.concurrent.atomic.AtomicLong; */ public class RpcStatus { - private static final ConcurrentMap SERVICE_STATISTICS = new ConcurrentHashMap(); + private static final ConcurrentMap SERVICE_STATISTICS = + new ConcurrentHashMap(); private static final ConcurrentMap> METHOD_STATISTICS = - new ConcurrentHashMap>(); + new ConcurrentHashMap>(); private final ConcurrentMap values = new ConcurrentHashMap(); @@ -50,8 +50,7 @@ public class RpcStatus { private final AtomicLong failedMaxElapsed = new AtomicLong(); private final AtomicLong succeededMaxElapsed = new AtomicLong(); - private RpcStatus() { - } + private RpcStatus() {} /** * @param url @@ -77,7 +76,8 @@ public class RpcStatus { */ public static RpcStatus getStatus(URL url, String methodName) { String uri = url.toIdentityString(); - ConcurrentMap map = ConcurrentHashMapUtils.computeIfAbsent(METHOD_STATISTICS, uri, k -> new ConcurrentHashMap<>()); + ConcurrentMap map = + ConcurrentHashMapUtils.computeIfAbsent(METHOD_STATISTICS, uri, k -> new ConcurrentHashMap<>()); return ConcurrentHashMapUtils.computeIfAbsent(map, methodName, k -> new RpcStatus()); } @@ -316,6 +316,4 @@ public class RpcStatus { } return getTotal(); } - - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ServerService.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ServerService.java index b00c6ef616..7228ca5202 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ServerService.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ServerService.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc; import org.apache.dubbo.common.URL; @@ -25,5 +24,4 @@ public interface ServerService { Invoker getInvoker(URL url); ServiceDescriptor getServiceDescriptor(); - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/TimeoutCountDown.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/TimeoutCountDown.java index 0e4910f947..c1ad880a2a 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/TimeoutCountDown.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/TimeoutCountDown.java @@ -58,9 +58,11 @@ public final class TimeoutCountDown implements Comparable { public long elapsedMillis() { if (isExpired()) { - return timeoutInMillis + TimeUnit.MILLISECONDS.convert(System.nanoTime() - deadlineInNanos, TimeUnit.NANOSECONDS); + return timeoutInMillis + + TimeUnit.MILLISECONDS.convert(System.nanoTime() - deadlineInNanos, TimeUnit.NANOSECONDS); } else { - return timeoutInMillis - TimeUnit.MILLISECONDS.convert(deadlineInNanos - System.nanoTime(), TimeUnit.NANOSECONDS); + return timeoutInMillis + - TimeUnit.MILLISECONDS.convert(deadlineInNanos - System.nanoTime(), TimeUnit.NANOSECONDS); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ZoneDetector.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ZoneDetector.java index 9f842f4b92..93a12d26ce 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ZoneDetector.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ZoneDetector.java @@ -28,5 +28,4 @@ public interface ZoneDetector { String getZoneOfCurrentRequest(Invocation invocation); String isZoneForcingEnabled(Invocation invocation, String zone); - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/cluster/filter/ClusterFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/cluster/filter/ClusterFilter.java index 6497d3b687..56e59d6a33 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/cluster/filter/ClusterFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/cluster/filter/ClusterFilter.java @@ -21,5 +21,4 @@ import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.rpc.BaseFilter; @SPI(scope = ExtensionScope.MODULE) -public interface ClusterFilter extends BaseFilter { -} +public interface ClusterFilter extends BaseFilter {} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java index 0f705ce965..01de872947 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java @@ -61,7 +61,8 @@ public class CompatibleFilter implements Filter, Filter.Listener { Object value = appResponse.getValue(); if (value != null) { try { - Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes()); + Method method = invoker.getInterface() + .getMethod(invocation.getMethodName(), invocation.getParameterTypes()); Class type = method.getReturnType(); Object newValue; String serialization = UrlUtils.serializationOrDefault(invoker.getUrl()); @@ -70,8 +71,10 @@ public class CompatibleFilter implements Filter, Filter.Listener { Type gtype = method.getGenericReturnType(); newValue = PojoUtils.realize(value, type, gtype); } else if (!type.isInstance(value)) { - //if local service interface's method's return type is not instance of return value - newValue = PojoUtils.isPojo(type) ? PojoUtils.realize(value, type) : CompatibleTypeUtils.compatibleTypeConvert(value, type); + // if local service interface's method's return type is not instance of return value + newValue = PojoUtils.isPojo(type) + ? PojoUtils.realize(value, type) + : CompatibleTypeUtils.compatibleTypeConvert(value, type); } else { newValue = value; @@ -87,7 +90,5 @@ public class CompatibleFilter implements Filter, Filter.Listener { } @Override - public void onError(Throwable t, Invoker invoker, Invocation invocation) { - - } + public void onError(Throwable t, Invoker invoker, Invocation invocation) {} } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java index 228cc44a82..1cbabd45d0 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java @@ -52,7 +52,12 @@ public class DeprecatedFilter implements Filter { if (!LOGGED.contains(key)) { LOGGED.add(key); if (invoker.getUrl().getMethodParameter(RpcUtils.getMethodName(invocation), DEPRECATED_KEY, false)) { - LOGGER.error(COMMON_UNSUPPORTED_INVOKER, "", "", "The service method " + invoker.getInterface().getName() + "." + getMethodSignature(invocation) + " is DEPRECATED! Declare from " + invoker.getUrl()); + LOGGER.error( + COMMON_UNSUPPORTED_INVOKER, + "", + "", + "The service method " + invoker.getInterface().getName() + "." + getMethodSignature(invocation) + + " is DEPRECATED! Declare from " + invoker.getUrl()); } } return invoker.invoke(invocation); @@ -76,5 +81,4 @@ public class DeprecatedFilter implements Filter { buf.append(')'); return buf.toString(); } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/EchoFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/EchoFilter.java index f3dbe01c6f..760aab3c6b 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/EchoFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/EchoFilter.java @@ -40,5 +40,4 @@ public class EchoFilter implements Filter { } return invoker.invoke(inv); } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExceptionFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExceptionFilter.java index 9265bad595..0fc159967a 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExceptionFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExceptionFilter.java @@ -35,7 +35,6 @@ import java.lang.reflect.Method; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION; - /** * ExceptionInvokerFilter *

    @@ -67,7 +66,8 @@ public class ExceptionFilter implements Filter, Filter.Listener { } // directly throw if the exception appears in the signature try { - Method method = invoker.getInterface().getMethod(RpcUtils.getMethodName(invocation), invocation.getParameterTypes()); + Method method = invoker.getInterface() + .getMethod(RpcUtils.getMethodName(invocation), invocation.getParameterTypes()); Class[] exceptionClasses = method.getExceptionTypes(); for (Class exceptionClass : exceptionClasses) { if (exception.getClass().equals(exceptionClass)) { @@ -79,10 +79,16 @@ public class ExceptionFilter implements Filter, Filter.Listener { } // for the exception not found in method's signature, print ERROR message in server's log. - logger.error(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", - "Got unchecked and undeclared exception which called by " + RpcContext.getServiceContext().getRemoteHost() + - ". service: " + invoker.getInterface().getName() + ", method: " + RpcUtils.getMethodName(invocation) + - ", exception: " + exception.getClass().getName() + ": " + exception.getMessage(), exception); + logger.error( + CONFIG_FILTER_VALIDATION_EXCEPTION, + "", + "", + "Got unchecked and undeclared exception which called by " + + RpcContext.getServiceContext().getRemoteHost() + ". service: " + + invoker.getInterface().getName() + ", method: " + RpcUtils.getMethodName(invocation) + + ", exception: " + + exception.getClass().getName() + ": " + exception.getMessage(), + exception); // directly throw if exception class and interface class are in the same jar file. String serviceFile = ReflectUtils.getCodeBase(invoker.getInterface()); @@ -92,7 +98,9 @@ public class ExceptionFilter implements Filter, Filter.Listener { } // directly throw if it's JDK exception String className = exception.getClass().getName(); - if (className.startsWith("java.") || className.startsWith("javax.") || className.startsWith("jakarta.")) { + if (className.startsWith("java.") + || className.startsWith("javax.") + || className.startsWith("jakarta.")) { return; } // directly throw if it's dubbo exception @@ -103,20 +111,32 @@ public class ExceptionFilter implements Filter, Filter.Listener { // otherwise, wrap with RuntimeException and throw back to the client appResponse.setException(new RuntimeException(StringUtils.toString(exception))); } catch (Throwable e) { - logger.warn(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", - "Fail to ExceptionFilter when called by " + RpcContext.getServiceContext().getRemoteHost() + - ". service: " + invoker.getInterface().getName() + ", method: " + RpcUtils.getMethodName(invocation) + - ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e); + logger.warn( + CONFIG_FILTER_VALIDATION_EXCEPTION, + "", + "", + "Fail to ExceptionFilter when called by " + + RpcContext.getServiceContext().getRemoteHost() + ". service: " + + invoker.getInterface().getName() + ", method: " + RpcUtils.getMethodName(invocation) + + ", exception: " + + e.getClass().getName() + ": " + e.getMessage(), + e); } } } @Override public void onError(Throwable e, Invoker invoker, Invocation invocation) { - logger.error(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", - "Got unchecked and undeclared exception which called by " + RpcContext.getServiceContext().getRemoteHost() + - ". service: " + invoker.getInterface().getName() + ", method: " + RpcUtils.getMethodName(invocation) + - ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e); + logger.error( + CONFIG_FILTER_VALIDATION_EXCEPTION, + "", + "", + "Got unchecked and undeclared exception which called by " + + RpcContext.getServiceContext().getRemoteHost() + ". service: " + + invoker.getInterface().getName() + ", method: " + RpcUtils.getMethodName(invocation) + + ", exception: " + + e.getClass().getName() + ": " + e.getMessage(), + e); } // For test purpose @@ -124,4 +144,3 @@ public class ExceptionFilter implements Filter, Filter.Listener { this.logger = logger; } } - diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ProfilerServerFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ProfilerServerFilter.java index 36aa5c8ca0..5899f7c0d1 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ProfilerServerFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ProfilerServerFilter.java @@ -44,8 +44,9 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_TIMEOU @Activate(group = PROVIDER, order = Integer.MIN_VALUE) public class ProfilerServerFilter implements Filter, BaseFilter.Listener { - private final static String CLIENT_IP_KEY = "client_ip"; - private final static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ProfilerServerFilter.class); + private static final String CLIENT_IP_KEY = "client_ip"; + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ProfilerServerFilter.class); @Override public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { @@ -53,7 +54,8 @@ public class ProfilerServerFilter implements Filter, BaseFilter.Listener { ProfilerEntry bizProfiler; Object localInvokeProfiler = invocation.get(Profiler.PROFILER_KEY); if (localInvokeProfiler instanceof ProfilerEntry) { - bizProfiler = Profiler.enter((ProfilerEntry) localInvokeProfiler, "Receive request. Local server invoke begin."); + bizProfiler = Profiler.enter( + (ProfilerEntry) localInvokeProfiler, "Receive request. Local server invoke begin."); } else { bizProfiler = Profiler.start("Receive request. Server invoke begin."); } @@ -86,6 +88,7 @@ public class ProfilerServerFilter implements Filter, BaseFilter.Listener { } } } + private void addAdaptiveResponse(Result appResponse, Invocation invocation) { String adaptiveLoadAttachment = invocation.getAttachment(Constants.ADAPTIVE_LOADBALANCE_ATTACHMENT_KEY); if (StringUtils.isNotEmpty(adaptiveLoadAttachment)) { @@ -93,9 +96,13 @@ public class ProfilerServerFilter implements Filter, BaseFilter.Listener { StringBuilder sb = new StringBuilder(64); sb.append("curTime:").append(System.currentTimeMillis()); - sb.append(COMMA_SEPARATOR).append("load:").append(operatingSystemMXBean.getSystemLoadAverage() * 100 / operatingSystemMXBean.getAvailableProcessors() ); + sb.append(COMMA_SEPARATOR) + .append("load:") + .append(operatingSystemMXBean.getSystemLoadAverage() + * 100 + / operatingSystemMXBean.getAvailableProcessors()); - appResponse.setAttachment(Constants.ADAPTIVE_LOADBALANCE_ATTACHMENT_KEY,sb.toString()); + appResponse.setAttachment(Constants.ADAPTIVE_LOADBALANCE_ATTACHMENT_KEY, sb.toString()); } } @@ -103,23 +110,38 @@ public class ProfilerServerFilter implements Filter, BaseFilter.Listener { Long timeout = RpcUtils.convertToNumber(invocation.getObjectAttachmentWithoutConvert(TIMEOUT_KEY)); if (timeout == null) { - timeout = (long) invoker.getUrl().getMethodPositiveParameter(RpcUtils.getMethodName(invocation), TIMEOUT_KEY, DEFAULT_TIMEOUT); + timeout = (long) invoker.getUrl() + .getMethodPositiveParameter(RpcUtils.getMethodName(invocation), TIMEOUT_KEY, DEFAULT_TIMEOUT); } long usage = profiler.getEndTime() - profiler.getStartTime(); if (((usage / (1000_000L * ProfilerSwitch.getWarnPercent())) > timeout) && timeout != -1) { StringBuilder attachment = new StringBuilder(); invocation.foreachAttachment((entry) -> { - attachment.append(entry.getKey()).append("=").append(entry.getValue()).append(";\n"); + attachment + .append(entry.getKey()) + .append("=") + .append(entry.getValue()) + .append(";\n"); }); - logger.warn(PROXY_TIMEOUT_RESPONSE, "", "", - String.format("[Dubbo-Provider] execute service %s#%s cost %d.%06d ms, this invocation almost (maybe already) timeout. Timeout: %dms\n" + - "client: %s\n" + - "invocation context:\n%s" + - "thread info: \n%s", - invocation.getTargetServiceUniqueName(), RpcUtils.getMethodName(invocation), usage / 1000_000, usage % 1000_000, timeout, - invocation.get(CLIENT_IP_KEY), attachment, Profiler.buildDetail(profiler))); + logger.warn( + PROXY_TIMEOUT_RESPONSE, + "", + "", + String.format( + "[Dubbo-Provider] execute service %s#%s cost %d.%06d ms, this invocation almost (maybe already) timeout. Timeout: %dms\n" + + "client: %s\n" + + "invocation context:\n%s" + + "thread info: \n%s", + invocation.getTargetServiceUniqueName(), + RpcUtils.getMethodName(invocation), + usage / 1000_000, + usage % 1000_000, + timeout, + invocation.get(CLIENT_IP_KEY), + attachment, + Profiler.buildDetail(profiler))); } } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/RpcExceptionFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/RpcExceptionFilter.java index 3531dab50e..859edff0f8 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/RpcExceptionFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/RpcExceptionFilter.java @@ -24,7 +24,6 @@ import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; - /** * RpcExceptionFilter *

    @@ -53,8 +52,5 @@ public class RpcExceptionFilter implements Filter, Filter.Listener { } @Override - public void onError(Throwable e, Invoker invoker, Invocation invocation) { - - } + public void onError(Throwable e, Invoker invoker, Invocation invocation) {} } - diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TimeoutFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TimeoutFilter.java index dac40680de..28a061e5b1 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TimeoutFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TimeoutFilter.java @@ -52,15 +52,17 @@ public class TimeoutFilter implements Filter, Filter.Listener { TimeoutCountDown countDown = (TimeoutCountDown) obj; if (countDown.isExpired()) { if (logger.isWarnEnabled()) { - logger.warn(PROXY_TIMEOUT_REQUEST, "", "", "invoke timed out. method: " + RpcUtils.getMethodName(invocation) + - " url is " + invoker.getUrl() + ", invoke elapsed " + countDown.elapsedMillis() + " ms."); + logger.warn( + PROXY_TIMEOUT_REQUEST, + "", + "", + "invoke timed out. method: " + RpcUtils.getMethodName(invocation) + " url is " + + invoker.getUrl() + ", invoke elapsed " + countDown.elapsedMillis() + " ms."); } } } } @Override - public void onError(Throwable t, Invoker invoker, Invocation invocation) { - - } + public void onError(Throwable t, Invoker invoker, Invocation invocation) {} } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/DeprecatedInvokerListener.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/DeprecatedInvokerListener.java index 4ec9a15f5c..a18345cc30 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/DeprecatedInvokerListener.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/DeprecatedInvokerListener.java @@ -31,13 +31,18 @@ import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY; @Activate(DEPRECATED_KEY) public class DeprecatedInvokerListener extends InvokerListenerAdapter { - private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(DeprecatedInvokerListener.class); + private static final ErrorTypeAwareLogger LOGGER = + LoggerFactory.getErrorTypeAwareLogger(DeprecatedInvokerListener.class); @Override public void referred(Invoker invoker) throws RpcException { if (invoker.getUrl().getParameter(DEPRECATED_KEY, false)) { - LOGGER.error(PROXY_UNSUPPORTED_INVOKER,"","","The service " + invoker.getInterface().getName() + " is DEPRECATED! Declare from " + invoker.getUrl()); + LOGGER.error( + PROXY_UNSUPPORTED_INVOKER, + "", + "", + "The service " + invoker.getInterface().getName() + " is DEPRECATED! Declare from " + + invoker.getUrl()); } } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ExporterListenerAdapter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ExporterListenerAdapter.java index 001bc9c5c5..825cbb7c50 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ExporterListenerAdapter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ExporterListenerAdapter.java @@ -26,11 +26,8 @@ import org.apache.dubbo.rpc.RpcException; public abstract class ExporterListenerAdapter implements ExporterListener { @Override - public void exported(Exporter exporter) throws RpcException { - } + public void exported(Exporter exporter) throws RpcException {} @Override - public void unexported(Exporter exporter) throws RpcException { - } - + public void unexported(Exporter exporter) throws RpcException {} } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/InjvmExporterListener.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/InjvmExporterListener.java index f4dbd0b557..c36e79f301 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/InjvmExporterListener.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/InjvmExporterListener.java @@ -25,7 +25,6 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; - /** * The InjvmExporterListener class is an implementation of the ExporterListenerAdapter abstract class, *

    @@ -74,7 +73,6 @@ public class InjvmExporterListener extends ExporterListenerAdapter { super.exported(exporter); } - /** * Overrides the unexported method to remove the given exporter from the exporters ConcurrentHashMap, *

    @@ -130,6 +128,4 @@ public class InjvmExporterListener extends ExporterListenerAdapter { exporterChangeListeners.remove(listenerKey); } } - - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/InvokerListenerAdapter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/InvokerListenerAdapter.java index ebe5a9ea4c..d5c95788dd 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/InvokerListenerAdapter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/InvokerListenerAdapter.java @@ -26,11 +26,8 @@ import org.apache.dubbo.rpc.RpcException; public abstract class InvokerListenerAdapter implements InvokerListener { @Override - public void referred(Invoker invoker) throws RpcException { - } + public void referred(Invoker invoker) throws RpcException {} @Override - public void destroyed(Invoker invoker) { - } - + public void destroyed(Invoker invoker) {} } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ListenerExporterWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ListenerExporterWrapper.java index b5eb3c52cb..d60171c7f2 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ListenerExporterWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ListenerExporterWrapper.java @@ -33,7 +33,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILE */ public class ListenerExporterWrapper implements Exporter { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ListenerExporterWrapper.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ListenerExporterWrapper.class); private final Exporter exporter; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ListenerInvokerWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ListenerInvokerWrapper.java index 2dd6d9c7e8..7a69a0dcf5 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ListenerInvokerWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ListenerInvokerWrapper.java @@ -35,7 +35,8 @@ import java.util.function.Consumer; */ public class ListenerInvokerWrapper implements Invoker { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ListenerInvokerWrapper.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ListenerInvokerWrapper.class); private final Invoker invoker; @@ -50,7 +51,6 @@ public class ListenerInvokerWrapper implements Invoker { listenerEvent(listener -> listener.referred(invoker)); } - @Override public Class getInterface() { return invoker.getInterface(); @@ -101,7 +101,12 @@ public class ListenerInvokerWrapper implements Invoker { try { consumer.accept(listener); } catch (RuntimeException t) { - logger.error(LoggerCodeConstants.INTERNAL_ERROR, "wrapped listener internal error", "", t.getMessage(), t); + logger.error( + LoggerCodeConstants.INTERNAL_ERROR, + "wrapped listener internal error", + "", + t.getMessage(), + t); exception = t; } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractExporter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractExporter.java index a9fd653bfa..1d11fbe53e 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractExporter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractExporter.java @@ -51,7 +51,7 @@ public abstract class AbstractExporter implements Exporter { } @Override - final public void unexport() { + public final void unexport() { if (unexported) { return; } @@ -61,24 +61,18 @@ public abstract class AbstractExporter implements Exporter { } @Override - public void register() { - - } + public void register() {} @Override - public void unregister() { - - } + public void unregister() {} /** * subclasses need to override this method to destroy resources. */ - public void afterUnExport() { - } + public void afterUnExport() {} @Override public String toString() { return getInvoker().toString(); } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractInvoker.java index 555ac3ac18..556c0e9e5f 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractInvoker.java @@ -22,13 +22,13 @@ import org.apache.dubbo.common.Version; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.common.serialize.SerializationException; import org.apache.dubbo.common.threadpool.ThreadlessExecutor; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.common.serialize.SerializationException; import org.apache.dubbo.remoting.TimeoutException; import org.apache.dubbo.remoting.utils.UrlUtils; import org.apache.dubbo.rpc.AsyncRpcResult; @@ -92,7 +92,8 @@ public abstract class AbstractInvoker implements Invoker { /** * Whether set future to Thread Local when invocation mode is sync */ - private static final boolean setFutureWhenSync = Boolean.parseBoolean(System.getProperty(CommonConstants.SET_FUTURE_IN_SYNC_MODE, "true")); + private static final boolean setFutureWhenSync = + Boolean.parseBoolean(System.getProperty(CommonConstants.SET_FUTURE_IN_SYNC_MODE, "true")); // -- Constructor @@ -114,11 +115,8 @@ public abstract class AbstractInvoker implements Invoker { this.type = type; this.url = url; - this.attachment = attachment == null - ? null - : Collections.unmodifiableMap(attachment); + this.attachment = attachment == null ? null : Collections.unmodifiableMap(attachment); this.version = url.getVersion(DEFAULT_VERSION); - } private static Map convertAttachment(URL url, String[] keys) { @@ -175,7 +173,13 @@ public abstract class AbstractInvoker implements Invoker { public Result invoke(Invocation inv) throws RpcException { // if invoker is destroyed due to address refresh from registry, let's allow the current invoke to proceed if (isDestroyed()) { - logger.warn(PROTOCOL_FAILED_REQUEST, "", "", "Invoker for service " + this + " on consumer " + NetUtils.getLocalHost() + " is destroyed, " + ", dubbo version is " + Version.getVersion() + ", this invoker should not be used any longer"); + logger.warn( + PROTOCOL_FAILED_REQUEST, + "", + "", + "Invoker for service " + this + " on consumer " + NetUtils.getLocalHost() + " is destroyed, " + + ", dubbo version is " + Version.getVersion() + + ", this invoker should not be used any longer"); } RpcInvocation invocation = (RpcInvocation) inv; @@ -231,7 +235,8 @@ public abstract class AbstractInvoker implements Invoker { } // client context attachment - Map clientContextAttachments = RpcContext.getClientAttachment().getObjectAttachments(); + Map clientContextAttachments = + RpcContext.getClientAttachment().getObjectAttachments(); if (CollectionUtils.isNotEmptyMap(clientContextAttachments)) { invocation.addObjectAttachmentsIfAbsent(clientContextAttachments); } @@ -287,21 +292,43 @@ public abstract class AbstractInvoker implements Invoker { asyncResult.get(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); - throw new RpcException("Interrupted unexpectedly while waiting for remote result to return! method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); + throw new RpcException( + "Interrupted unexpectedly while waiting for remote result to return! method: " + + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), + e); } catch (ExecutionException e) { Throwable rootCause = e.getCause(); if (rootCause instanceof TimeoutException) { - throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "Invoke remote method timeout. method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); + throw new RpcException( + RpcException.TIMEOUT_EXCEPTION, + "Invoke remote method timeout. method: " + invocation.getMethodName() + ", provider: " + + getUrl() + ", cause: " + e.getMessage(), + e); } else if (rootCause instanceof RemotingException) { - throw new RpcException(RpcException.NETWORK_EXCEPTION, "Failed to invoke remote method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); + throw new RpcException( + RpcException.NETWORK_EXCEPTION, + "Failed to invoke remote method: " + invocation.getMethodName() + ", provider: " + getUrl() + + ", cause: " + e.getMessage(), + e); } else if (rootCause instanceof SerializationException) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, "Invoke remote method failed cause by serialization error. remote method: " + - invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); + throw new RpcException( + RpcException.SERIALIZATION_EXCEPTION, + "Invoke remote method failed cause by serialization error. remote method: " + + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), + e); } else { - throw new RpcException(RpcException.UNKNOWN_EXCEPTION, "Fail to invoke remote method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); + throw new RpcException( + RpcException.UNKNOWN_EXCEPTION, + "Fail to invoke remote method: " + invocation.getMethodName() + ", provider: " + getUrl() + + ", cause: " + e.getMessage(), + e); } } catch (java.util.concurrent.TimeoutException e) { - throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "Invoke remote method timeout. method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); + throw new RpcException( + RpcException.TIMEOUT_EXCEPTION, + "Invoke remote method timeout. method: " + invocation.getMethodName() + ", provider: " + getUrl() + + ", cause: " + e.getMessage(), + e); } catch (Throwable e) { throw new RpcException(e.getMessage(), e); } @@ -313,7 +340,8 @@ public abstract class AbstractInvoker implements Invoker { if (InvokeMode.SYNC == RpcUtils.getInvokeMode(getUrl(), inv)) { return new ThreadlessExecutor(); } - return ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()).getExecutor(url); + return ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()) + .getExecutor(url); } /** diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java index 25a3068693..2fe17714f3 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java @@ -71,7 +71,6 @@ public abstract class AbstractProtocol implements Protocol, ScopeModelAware { private final Set optimizers = new ConcurrentHashSet<>(); - @Override public void setFrameworkModel(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; @@ -93,7 +92,8 @@ public abstract class AbstractProtocol implements Protocol, ScopeModelAware { protected void loadServerProperties(ProtocolServer server) { // read and hold config before destroy - int serverShutdownTimeout = ConfigurationUtils.getServerShutdownTimeout(server.getUrl().getScopeModel()); + int serverShutdownTimeout = + ConfigurationUtils.getServerShutdownTimeout(server.getUrl().getScopeModel()); server.getAttributes().put(SHUTDOWN_WAIT_KEY, serverShutdownTimeout); } @@ -148,7 +148,6 @@ public abstract class AbstractProtocol implements Protocol, ScopeModelAware { return Collections.unmodifiableCollection(exporterMap.values()); } - protected void optimizeSerialization(URL url) throws RpcException { String className = url.getParameter(OPTIMIZER_KEY, ""); if (StringUtils.isEmpty(className) || optimizers.contains(className)) { @@ -160,7 +159,8 @@ public abstract class AbstractProtocol implements Protocol, ScopeModelAware { try { Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className); if (!SerializationOptimizer.class.isAssignableFrom(clazz)) { - throw new RpcException("The serialization optimizer " + className + " isn't an instance of " + SerializationOptimizer.class.getName()); + throw new RpcException("The serialization optimizer " + className + " isn't an instance of " + + SerializationOptimizer.class.getName()); } SerializationOptimizer optimizer = (SerializationOptimizer) clazz.newInstance(); @@ -180,7 +180,6 @@ public abstract class AbstractProtocol implements Protocol, ScopeModelAware { } catch (InstantiationException | IllegalAccessException e) { throw new RpcException("Cannot instantiate the serialization optimizer class: " + className, e); - } } @@ -189,7 +188,7 @@ public abstract class AbstractProtocol implements Protocol, ScopeModelAware { if (url.getParameter(ANYHOST_KEY, false)) { bindIp = ANYHOST_VALUE; } - return NetUtils.getIpByHost(bindIp) + ":" + url.getParameter(org.apache.dubbo.remoting.Constants.BIND_PORT_KEY, url.getPort()); + return NetUtils.getIpByHost(bindIp) + ":" + + url.getParameter(org.apache.dubbo.remoting.Constants.BIND_PORT_KEY, url.getPort()); } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java index e1727c38ca..843754a1dd 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol; import org.apache.dubbo.common.Parameters; @@ -55,8 +54,7 @@ public abstract class AbstractProxyProtocol extends AbstractProtocol { protected ProxyFactory proxyFactory; - public AbstractProxyProtocol() { - } + public AbstractProxyProtocol() {} public AbstractProxyProtocol(Class... exceptions) { for (Class exception : exceptions) { @@ -87,7 +85,8 @@ public abstract class AbstractProxyProtocol extends AbstractProtocol { return exporter; } } - final Runnable runnable = doExport(proxyFactory.getProxy(invoker, true), invoker.getInterface(), invoker.getUrl()); + final Runnable runnable = + doExport(proxyFactory.getProxy(invoker, true), invoker.getInterface(), invoker.getUrl()); exporter = new AbstractExporter(invoker) { @Override public void afterUnExport() { @@ -151,8 +150,10 @@ public abstract class AbstractProxyProtocol extends AbstractProtocol { } protected RpcException getRpcException(Class type, URL url, Invocation invocation, Throwable e) { - RpcException re = new RpcException("Failed to invoke remote service: " + type + ", method: " - + invocation.getMethodName() + ", cause: " + e.getMessage(), e); + RpcException re = new RpcException( + "Failed to invoke remote service: " + type + ", method: " + invocation.getMethodName() + ", cause: " + + e.getMessage(), + e); re.setCode(getErrorCode(e)); return re; } @@ -237,14 +238,10 @@ public abstract class AbstractProxyProtocol extends AbstractProtocol { } @Override - public void reset(Parameters parameters) { - - } + public void reset(Parameters parameters) {} @Override - public void reset(URL url) { - - } + public void reset(URL url) {} @Override public URL getUrl() { @@ -262,35 +259,23 @@ public abstract class AbstractProxyProtocol extends AbstractProtocol { } @Override - public void send(Object message) throws RemotingException { - - } + public void send(Object message) throws RemotingException {} @Override - public void send(Object message, boolean sent) throws RemotingException { - - } + public void send(Object message, boolean sent) throws RemotingException {} @Override - public void close() { - - } + public void close() {} @Override - public void close(int timeout) { - - } + public void close(int timeout) {} @Override - public void startClose() { - - } + public void startClose() {} @Override public boolean isClosed() { return false; } } - - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/InvokerWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/InvokerWrapper.java index a2e0dae3b5..fe4bf6b462 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/InvokerWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/InvokerWrapper.java @@ -60,5 +60,4 @@ public class InvokerWrapper implements Invoker { public void destroy() { invoker.destroy(); } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/PermittedSerializationKeeper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/PermittedSerializationKeeper.java index 7bc8d12017..55d2c09aa7 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/PermittedSerializationKeeper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/PermittedSerializationKeeper.java @@ -38,7 +38,8 @@ public class PermittedSerializationKeeper { private final Set globalPermittedSerializationIds = new ConcurrentHashSet<>(); public void registerService(URL url) { - Set set = ConcurrentHashMapUtils.computeIfAbsent(serviceToSerializationId, keyWithoutGroup(url.getServiceKey()), k -> new ConcurrentHashSet<>()); + Set set = ConcurrentHashMapUtils.computeIfAbsent( + serviceToSerializationId, keyWithoutGroup(url.getServiceKey()), k -> new ConcurrentHashSet<>()); Collection serializations = UrlUtils.allSerializations(url); for (String serialization : serializations) { Byte id = CodecSupport.getIDByName(serialization); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapper.java index 0071fa66ce..421e1148e7 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapper.java @@ -65,13 +65,17 @@ public class ProtocolListenerWrapper implements Protocol { if (UrlUtils.isRegistry(invoker.getUrl())) { return protocol.export(invoker); } - List exporterListeners = ScopeModelUtil.getExtensionLoader(ExporterListener.class, invoker.getUrl().getScopeModel()) - .getActivateExtension(invoker.getUrl(), EXPORTER_LISTENER_KEY); + List exporterListeners = ScopeModelUtil.getExtensionLoader( + ExporterListener.class, invoker.getUrl().getScopeModel()) + .getActivateExtension(invoker.getUrl(), EXPORTER_LISTENER_KEY); if (LOCAL_PROTOCOL.equals(invoker.getUrl().getProtocol())) { - exporterListeners.add(invoker.getUrl().getOrDefaultFrameworkModel().getBeanFactory().getBean(InjvmExporterListener.class)); + exporterListeners.add(invoker.getUrl() + .getOrDefaultFrameworkModel() + .getBeanFactory() + .getBean(InjvmExporterListener.class)); } - return new ListenerExporterWrapper(protocol.export(invoker), - Collections.unmodifiableList(exporterListeners)); + return new ListenerExporterWrapper( + protocol.export(invoker), Collections.unmodifiableList(exporterListeners)); } @Override @@ -82,10 +86,11 @@ public class ProtocolListenerWrapper implements Protocol { Invoker invoker = protocol.refer(type, url); if (StringUtils.isEmpty(url.getParameter(REGISTRY_CLUSTER_TYPE_KEY))) { - invoker = new ListenerInvokerWrapper<>(invoker, - Collections.unmodifiableList( - ScopeModelUtil.getExtensionLoader(InvokerListener.class, invoker.getUrl().getScopeModel()) - .getActivateExtension(url, INVOKER_LISTENER_KEY))); + invoker = new ListenerInvokerWrapper<>( + invoker, + Collections.unmodifiableList(ScopeModelUtil.getExtensionLoader( + InvokerListener.class, invoker.getUrl().getScopeModel()) + .getActivateExtension(url, INVOKER_LISTENER_KEY))); } return invoker; } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolSecurityWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolSecurityWrapper.java index e02dc7920d..4f83bcf42e 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolSecurityWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolSecurityWrapper.java @@ -41,7 +41,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERR public class ProtocolSecurityWrapper implements Protocol { private final Protocol protocol; - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ProtocolSecurityWrapper.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ProtocolSecurityWrapper.class); public ProtocolSecurityWrapper(Protocol protocol) { if (protocol == null) { @@ -61,22 +62,22 @@ public class ProtocolSecurityWrapper implements Protocol { ServiceModel serviceModel = invoker.getUrl().getServiceModel(); ScopeModel scopeModel = invoker.getUrl().getScopeModel(); SerializeSecurityConfigurator serializeSecurityConfigurator = ScopeModelUtil.getModuleModel(scopeModel) - .getBeanFactory().getBean(SerializeSecurityConfigurator.class); + .getBeanFactory() + .getBean(SerializeSecurityConfigurator.class); serializeSecurityConfigurator.refreshStatus(); serializeSecurityConfigurator.refreshCheck(); - Optional.ofNullable(invoker.getInterface()) - .ifPresent(serializeSecurityConfigurator::registerInterface); + Optional.ofNullable(invoker.getInterface()).ifPresent(serializeSecurityConfigurator::registerInterface); Optional.ofNullable(serviceModel) - .map(ServiceModel::getServiceModel) - .map(ServiceDescriptor::getServiceInterfaceClass) - .ifPresent(serializeSecurityConfigurator::registerInterface); + .map(ServiceModel::getServiceModel) + .map(ServiceDescriptor::getServiceInterfaceClass) + .ifPresent(serializeSecurityConfigurator::registerInterface); Optional.ofNullable(serviceModel) - .map(ServiceModel::getServiceMetadata) - .map(ServiceMetadata::getServiceType) - .ifPresent(serializeSecurityConfigurator::registerInterface); + .map(ServiceModel::getServiceMetadata) + .map(ServiceMetadata::getServiceType) + .ifPresent(serializeSecurityConfigurator::registerInterface); } catch (Throwable t) { logger.error(INTERNAL_ERROR, "", "", "Failed to register interface for security check", t); } @@ -89,19 +90,20 @@ public class ProtocolSecurityWrapper implements Protocol { ServiceModel serviceModel = url.getServiceModel(); ScopeModel scopeModel = url.getScopeModel(); SerializeSecurityConfigurator serializeSecurityConfigurator = ScopeModelUtil.getModuleModel(scopeModel) - .getBeanFactory().getBean(SerializeSecurityConfigurator.class); + .getBeanFactory() + .getBean(SerializeSecurityConfigurator.class); serializeSecurityConfigurator.refreshStatus(); serializeSecurityConfigurator.refreshCheck(); Optional.ofNullable(serviceModel) - .map(ServiceModel::getServiceModel) - .map(ServiceDescriptor::getServiceInterfaceClass) - .ifPresent(serializeSecurityConfigurator::registerInterface); + .map(ServiceModel::getServiceModel) + .map(ServiceDescriptor::getServiceInterfaceClass) + .ifPresent(serializeSecurityConfigurator::registerInterface); Optional.ofNullable(serviceModel) - .map(ServiceModel::getServiceMetadata) - .map(ServiceMetadata::getServiceType) - .ifPresent(serializeSecurityConfigurator::registerInterface); + .map(ServiceModel::getServiceMetadata) + .map(ServiceMetadata::getServiceType) + .ifPresent(serializeSecurityConfigurator::registerInterface); serializeSecurityConfigurator.registerInterface(type); } catch (Throwable t) { logger.error(INTERNAL_ERROR, "", "", "Failed to register interface for security check", t); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolSerializationWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolSerializationWrapper.java index dfaaffc827..7edb260f8a 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolSerializationWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolSerializationWrapper.java @@ -43,7 +43,10 @@ public class ProtocolSerializationWrapper implements Protocol { @Override public Exporter export(Invoker invoker) throws RpcException { - getFrameworkModel(invoker.getUrl().getScopeModel()).getBeanFactory().getBean(PermittedSerializationKeeper.class).registerService(invoker.getUrl()); + getFrameworkModel(invoker.getUrl().getScopeModel()) + .getBeanFactory() + .getBean(PermittedSerializationKeeper.class) + .registerService(invoker.getUrl()); return protocol.export(invoker); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ReferenceCountInvokerWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ReferenceCountInvokerWrapper.java index 4558113b72..a3a3291681 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ReferenceCountInvokerWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ReferenceCountInvokerWrapper.java @@ -32,7 +32,8 @@ import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ReferenceCountInvokerWrapper implements Invoker { - private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ReferenceCountInvokerWrapper.class); + private final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ReferenceCountInvokerWrapper.class); private final Invoker invoker; private final ReadWriteLock lock = new ReentrantReadWriteLock(); @@ -55,12 +56,15 @@ public class ReferenceCountInvokerWrapper implements Invoker { @Override public void destroy() { try { - int timeout = ConfigurationUtils.getServerShutdownTimeout(invoker.getUrl().getScopeModel()); - boolean locked = lock.writeLock().tryLock( - timeout, TimeUnit.MILLISECONDS); + int timeout = + ConfigurationUtils.getServerShutdownTimeout(invoker.getUrl().getScopeModel()); + boolean locked = lock.writeLock().tryLock(timeout, TimeUnit.MILLISECONDS); if (!locked) { - logger.warn(LoggerCodeConstants.PROTOCOL_CLOSED_SERVER, "", "", - "Failed to wait for invocation end in " + timeout + "ms."); + logger.warn( + LoggerCodeConstants.PROTOCOL_CLOSED_SERVER, + "", + "", + "Failed to wait for invocation end in " + timeout + "ms."); } destroyed.set(true); } catch (InterruptedException e) { @@ -71,8 +75,12 @@ public class ReferenceCountInvokerWrapper implements Invoker { } catch (IllegalMonitorStateException ignore) { // ignore if lock failed, maybe in a long invoke } catch (Throwable t) { - logger.warn(LoggerCodeConstants.PROTOCOL_CLOSED_SERVER, "", "", - "Unexpected error occurred when releasing write lock, cause: " + t.getMessage(), t); + logger.warn( + LoggerCodeConstants.PROTOCOL_CLOSED_SERVER, + "", + "", + "Unexpected error occurred when releasing write lock, cause: " + t.getMessage(), + t); } } invoker.destroy(); @@ -88,8 +96,11 @@ public class ReferenceCountInvokerWrapper implements Invoker { try { lock.readLock().lock(); if (destroyed.get()) { - logger.warn(LoggerCodeConstants.PROTOCOL_CLOSED_SERVER, "", "", - "Remote invoker has been destroyed, and unable to invoke anymore."); + logger.warn( + LoggerCodeConstants.PROTOCOL_CLOSED_SERVER, + "", + "", + "Remote invoker has been destroyed, and unable to invoke anymore."); throw new RpcException("This invoker has been destroyed!"); } return invoker.invoke(invocation); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/FutureAdapter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/FutureAdapter.java index 33332406da..efdf85f7b0 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/FutureAdapter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/FutureAdapter.java @@ -55,10 +55,10 @@ public class FutureAdapter extends CompletableFuture { // TODO figure out the meaning of cancel in DefaultFuture. @Override public boolean cancel(boolean mayInterruptIfRunning) { -// Invocation invocation = invocationSoftReference.get(); -// if (invocation != null) { -// invocation.getInvoker().invoke(cancel); -// } + // Invocation invocation = invocationSoftReference.get(); + // if (invocation != null) { + // invocation.getInvoker().invoke(cancel); + // } return appResponseFuture.cancel(mayInterruptIfRunning); } @@ -95,5 +95,4 @@ public class FutureAdapter extends CompletableFuture { throw new RpcException(e); } } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java index 84db02b564..1ae8f71e68 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java @@ -79,7 +79,9 @@ public class FutureFilter implements ClusterFilter, ClusterFilter.Listener { return; } if (onInvokeMethod == null || onInvokeInst == null) { - throw new IllegalStateException("service:" + invoker.getUrl().getServiceKey() + " has a oninvoke callback config , but no such " + (onInvokeMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); + throw new IllegalStateException( + "service:" + invoker.getUrl().getServiceKey() + " has a oninvoke callback config , but no such " + + (onInvokeMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); } if (!onInvokeMethod.isAccessible()) { onInvokeMethod.setAccessible(true); @@ -104,13 +106,15 @@ public class FutureFilter implements ClusterFilter, ClusterFilter.Listener { final Method onReturnMethod = asyncMethodInfo.getOnreturnMethod(); final Object onReturnInst = asyncMethodInfo.getOnreturnInstance(); - //not set onreturn callback + // not set onreturn callback if (onReturnMethod == null && onReturnInst == null) { return; } if (onReturnMethod == null || onReturnInst == null) { - throw new IllegalStateException("service:" + invoker.getUrl().getServiceKey() + " has a onreturn callback config , but no such " + (onReturnMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); + throw new IllegalStateException( + "service:" + invoker.getUrl().getServiceKey() + " has a onreturn callback config , but no such " + + (onReturnMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); } if (!onReturnMethod.isAccessible()) { onReturnMethod.setAccessible(true); @@ -130,7 +134,7 @@ public class FutureFilter implements ClusterFilter, ClusterFilter.Listener { System.arraycopy(args, 0, params, 1, args.length); } } else { - params = new Object[]{result}; + params = new Object[] {result}; } try { onReturnMethod.invoke(onReturnInst, params); @@ -150,12 +154,14 @@ public class FutureFilter implements ClusterFilter, ClusterFilter.Listener { final Method onthrowMethod = asyncMethodInfo.getOnthrowMethod(); final Object onthrowInst = asyncMethodInfo.getOnthrowInstance(); - //onthrow callback not configured + // onthrow callback not configured if (onthrowMethod == null && onthrowInst == null) { return; } if (onthrowMethod == null || onthrowInst == null) { - throw new IllegalStateException("service:" + invoker.getUrl().getServiceKey() + " has a onthrow callback config , but no such " + (onthrowMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); + throw new IllegalStateException( + "service:" + invoker.getUrl().getServiceKey() + " has a onthrow callback config , but no such " + + (onthrowMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); } if (!onthrowMethod.isAccessible()) { onthrowMethod.setAccessible(true); @@ -177,14 +183,26 @@ public class FutureFilter implements ClusterFilter, ClusterFilter.Listener { System.arraycopy(args, 0, params, 1, args.length); } } else { - params = new Object[]{exception}; + params = new Object[] {exception}; } onthrowMethod.invoke(onthrowInst, params); } catch (Throwable e) { - logger.error(PROTOCOL_FAILED_REQUEST, "", "", RpcUtils.getMethodName(invocation) + ".call back method invoke error . callback method :" + onthrowMethod + ", url:" + invoker.getUrl(), e); + logger.error( + PROTOCOL_FAILED_REQUEST, + "", + "", + RpcUtils.getMethodName(invocation) + ".call back method invoke error . callback method :" + + onthrowMethod + ", url:" + invoker.getUrl(), + e); } } else { - logger.error(PROTOCOL_FAILED_REQUEST, "", "", RpcUtils.getMethodName(invocation) + ".call back method invoke error . callback method :" + onthrowMethod + ", url:" + invoker.getUrl(), exception); + logger.error( + PROTOCOL_FAILED_REQUEST, + "", + "", + RpcUtils.getMethodName(invocation) + ".call back method invoke error . callback method :" + + onthrowMethod + ", url:" + invoker.getUrl(), + exception); } } @@ -203,5 +221,4 @@ public class FutureFilter implements ClusterFilter, ClusterFilter.Listener { return ((ConsumerModel) serviceModel).getAsyncInfo(methodName); } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractFallbackJdkProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractFallbackJdkProxyFactory.java index e48d12ea78..112306ad02 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractFallbackJdkProxyFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractFallbackJdkProxyFactory.java @@ -42,15 +42,32 @@ public abstract class AbstractFallbackJdkProxyFactory extends AbstractProxyFacto String factoryName = getClass().getSimpleName(); try { Invoker invoker = jdkProxyFactory.getInvoker(proxy, type, url); - logger.error(PROXY_FAILED, "", "", "Failed to generate invoker by " + factoryName + " failed. Fallback to use JDK proxy success. " + - "Interfaces: " + type, throwable); + logger.error( + PROXY_FAILED, + "", + "", + "Failed to generate invoker by " + factoryName + " failed. Fallback to use JDK proxy success. " + + "Interfaces: " + type, + throwable); // log out error return invoker; } catch (Throwable fromJdk) { - logger.error(PROXY_FAILED, "", "", "Failed to generate invoker by " + factoryName + " failed. Fallback to use JDK proxy is also failed. " + - "Interfaces: " + type + " Javassist Error.", throwable); - logger.error(PROXY_FAILED, "", "", "Failed to generate invoker by " + factoryName + " failed. Fallback to use JDK proxy is also failed. " + - "Interfaces: " + type + " JDK Error.", fromJdk); + logger.error( + PROXY_FAILED, + "", + "", + "Failed to generate invoker by " + factoryName + + " failed. Fallback to use JDK proxy is also failed. " + "Interfaces: " + type + + " Javassist Error.", + throwable); + logger.error( + PROXY_FAILED, + "", + "", + "Failed to generate invoker by " + factoryName + + " failed. Fallback to use JDK proxy is also failed. " + "Interfaces: " + type + + " JDK Error.", + fromJdk); throw throwable; } } @@ -65,14 +82,31 @@ public abstract class AbstractFallbackJdkProxyFactory extends AbstractProxyFacto String factoryName = getClass().getSimpleName(); try { T proxy = jdkProxyFactory.getProxy(invoker, interfaces); - logger.error(PROXY_FAILED, "", "", "Failed to generate proxy by " + factoryName + " failed. Fallback to use JDK proxy success. " + - "Interfaces: " + Arrays.toString(interfaces), throwable); + logger.error( + PROXY_FAILED, + "", + "", + "Failed to generate proxy by " + factoryName + " failed. Fallback to use JDK proxy success. " + + "Interfaces: " + Arrays.toString(interfaces), + throwable); return proxy; } catch (Throwable fromJdk) { - logger.error(PROXY_FAILED, "", "", "Failed to generate proxy by " + factoryName + " failed. Fallback to use JDK proxy is also failed. " + - "Interfaces: " + Arrays.toString(interfaces) + " Javassist Error.", throwable); - logger.error(PROXY_FAILED, "", "", "Failed to generate proxy by " + factoryName + " failed. Fallback to use JDK proxy is also failed. " + - "Interfaces: " + Arrays.toString(interfaces) + " JDK Error.", fromJdk); + logger.error( + PROXY_FAILED, + "", + "", + "Failed to generate proxy by " + factoryName + + " failed. Fallback to use JDK proxy is also failed. " + "Interfaces: " + + Arrays.toString(interfaces) + " Javassist Error.", + throwable); + logger.error( + PROXY_FAILED, + "", + "", + "Failed to generate proxy by " + factoryName + + " failed. Fallback to use JDK proxy is also failed. " + "Interfaces: " + + Arrays.toString(interfaces) + " JDK Error.", + fromJdk); throw throwable; } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java index 8219bb74db..87215d2919 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.java @@ -42,11 +42,10 @@ import static org.apache.dubbo.rpc.Constants.INTERFACES; * AbstractProxyFactory */ public abstract class AbstractProxyFactory implements ProxyFactory { - private static final Class[] INTERNAL_INTERFACES = new Class[]{ - EchoService.class, Destroyable.class - }; + private static final Class[] INTERNAL_INTERFACES = new Class[] {EchoService.class, Destroyable.class}; - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractProxyFactory.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(AbstractProxyFactory.class); @Override public T getProxy(Invoker invoker) throws RpcException { @@ -68,7 +67,6 @@ public abstract class AbstractProxyFactory implements ProxyFactory { } catch (Throwable e) { // ignore } - } } @@ -83,8 +81,9 @@ public abstract class AbstractProxyFactory implements ProxyFactory { // ignore } - if (GenericService.class.isAssignableFrom(invoker.getInterface()) && - Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isGenericServiceClassLoaded()) { + if (GenericService.class.isAssignableFrom(invoker.getInterface()) + && Dubbo2CompactUtils.isEnabled() + && Dubbo2CompactUtils.isGenericServiceClassLoaded()) { interfaces.add(Dubbo2CompactUtils.getGenericServiceClass()); } if (!GenericService.class.isAssignableFrom(invoker.getInterface())) { @@ -108,7 +107,12 @@ public abstract class AbstractProxyFactory implements ProxyFactory { } interfaces.remove(invoker.getInterface()); - logger.error(PROXY_UNSUPPORTED_INVOKER, "", "", "Error occur when creating proxy. Invoker is in generic mode. Trying to create proxy without real interface class.", t); + logger.error( + PROXY_UNSUPPORTED_INVOKER, + "", + "", + "Error occur when creating proxy. Invoker is in generic mode. Trying to create proxy without real interface class.", + t); return getProxy(invoker, interfaces.toArray(new Class[0])); } else { throw t; @@ -133,5 +137,4 @@ public abstract class AbstractProxyFactory implements ProxyFactory { } public abstract T getProxy(Invoker invoker, Class[] types); - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyInvoker.java index 871fe9672c..58f573cd50 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyInvoker.java @@ -81,8 +81,7 @@ public abstract class AbstractProxyInvoker implements Invoker { } @Override - public void destroy() { - } + public void destroy() {} @Override public Result invoke(Invocation invocation) throws RpcException { @@ -91,13 +90,15 @@ public abstract class AbstractProxyInvoker implements Invoker { if (ProfilerSwitch.isEnableSimpleProfiler()) { Object fromInvocation = invocation.get(Profiler.PROFILER_KEY); if (fromInvocation instanceof ProfilerEntry) { - ProfilerEntry profiler = Profiler.enter((ProfilerEntry) fromInvocation, "Receive request. Server biz impl invoke begin."); + ProfilerEntry profiler = Profiler.enter( + (ProfilerEntry) fromInvocation, "Receive request. Server biz impl invoke begin."); invocation.put(Profiler.PROFILER_KEY, profiler); originEntry = Profiler.setToBizProfiler(profiler); } } - Object value = doInvoke(proxy, invocation.getMethodName(), invocation.getParameterTypes(), invocation.getArguments()); + Object value = doInvoke( + proxy, invocation.getMethodName(), invocation.getParameterTypes(), invocation.getArguments()); CompletableFuture future = wrapWithFuture(value, invocation); CompletableFuture appResponseFuture = future.handle((obj, t) -> { @@ -115,12 +116,21 @@ public abstract class AbstractProxyInvoker implements Invoker { }); return new AsyncRpcResult(appResponseFuture, invocation); } catch (InvocationTargetException e) { - if (RpcContext.getServiceContext().isAsyncStarted() && !RpcContext.getServiceContext().stopAsync()) { - logger.error(PROXY_ERROR_ASYNC_RESPONSE, "", "", "Provider async started, but got an exception from the original method, cannot write the exception back to consumer because an async result may have returned the new thread.", e); + if (RpcContext.getServiceContext().isAsyncStarted() + && !RpcContext.getServiceContext().stopAsync()) { + logger.error( + PROXY_ERROR_ASYNC_RESPONSE, + "", + "", + "Provider async started, but got an exception from the original method, cannot write the exception back to consumer because an async result may have returned the new thread.", + e); } return AsyncRpcResult.newDefaultAsyncResult(null, e.getTargetException(), invocation); } catch (Throwable e) { - throw new RpcException("Failed to invoke remote proxy method " + invocation.getMethodName() + " to " + getUrl() + ", cause: " + e.getMessage(), e); + throw new RpcException( + "Failed to invoke remote proxy method " + invocation.getMethodName() + " to " + getUrl() + + ", cause: " + e.getMessage(), + e); } finally { if (ProfilerSwitch.isEnableSimpleProfiler()) { Object fromInvocation = invocation.get(Profiler.PROFILER_KEY); @@ -134,7 +144,6 @@ public abstract class AbstractProxyInvoker implements Invoker { Profiler.setToBizProfiler(originEntry); } } - } private CompletableFuture wrapWithFuture(Object value, Invocation invocation) { @@ -148,12 +157,11 @@ public abstract class AbstractProxyInvoker implements Invoker { return CompletableFuture.completedFuture(value); } - protected abstract Object doInvoke(T proxy, String methodName, Class[] parameterTypes, Object[] arguments) throws Throwable; + protected abstract Object doInvoke(T proxy, String methodName, Class[] parameterTypes, Object[] arguments) + throws Throwable; @Override public String toString() { return getInterface() + " -> " + (getUrl() == null ? " " : getUrl().toString()); } - - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvocationUtil.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvocationUtil.java index cc4c258f6a..1e8cd988f4 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvocationUtil.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvocationUtil.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.proxy; import org.apache.dubbo.common.URL; @@ -34,7 +33,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_TIMEOUT_REQUEST; public class InvocationUtil { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(InvokerInvocationHandler.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(InvokerInvocationHandler.class); public static Object invoke(Invoker invoker, RpcInvocation rpcInvocation) throws Throwable { RpcContext.RestoreServiceContext originServiceContext = RpcContext.storeServiceContext(); @@ -51,39 +51,51 @@ public class InvocationUtil { ProfilerEntry parentProfiler = Profiler.getBizProfiler(); ProfilerEntry bizProfiler; if (parentProfiler != null) { - bizProfiler = Profiler.enter(parentProfiler, - "Receive request. Client invoke begin. ServiceKey: " + serviceKey + " MethodName:" + rpcInvocation.getMethodName()); + bizProfiler = Profiler.enter( + parentProfiler, + "Receive request. Client invoke begin. ServiceKey: " + serviceKey + " MethodName:" + + rpcInvocation.getMethodName()); } else { - bizProfiler = Profiler.start("Receive request. Client invoke begin. ServiceKey: " + serviceKey + " " + "MethodName:" + rpcInvocation.getMethodName()); + bizProfiler = Profiler.start("Receive request. Client invoke begin. ServiceKey: " + serviceKey + " " + + "MethodName:" + rpcInvocation.getMethodName()); } rpcInvocation.put(Profiler.PROFILER_KEY, bizProfiler); try { return invoker.invoke(rpcInvocation).recreate(); } finally { Profiler.release(bizProfiler); - Long timeout = RpcUtils.convertToNumber(rpcInvocation.getObjectAttachmentWithoutConvert(TIMEOUT_KEY)); + Long timeout = + RpcUtils.convertToNumber(rpcInvocation.getObjectAttachmentWithoutConvert(TIMEOUT_KEY)); if (timeout == null) { - timeout = (long) url.getMethodPositiveParameter(rpcInvocation.getMethodName(), - TIMEOUT_KEY, - DEFAULT_TIMEOUT); + timeout = (long) url.getMethodPositiveParameter( + rpcInvocation.getMethodName(), TIMEOUT_KEY, DEFAULT_TIMEOUT); } long usage = bizProfiler.getEndTime() - bizProfiler.getStartTime(); if ((usage / (1000_000L * ProfilerSwitch.getWarnPercent())) > timeout) { StringBuilder attachment = new StringBuilder(); rpcInvocation.foreachAttachment((entry) -> { - attachment.append(entry.getKey()).append("=").append(entry.getValue()).append(";\n"); + attachment + .append(entry.getKey()) + .append("=") + .append(entry.getValue()) + .append(";\n"); }); - logger.warn(PROXY_TIMEOUT_REQUEST, "", "", String.format( - "[Dubbo-Consumer] execute service %s#%s cost %d.%06d ms, this invocation almost (maybe already) timeout. Timeout: %dms\n" + "invocation context:\n%s" + "thread info: \n%s", - rpcInvocation.getProtocolServiceKey(), - rpcInvocation.getMethodName(), - usage / 1000_000, - usage % 1000_000, - timeout, - attachment, - Profiler.buildDetail(bizProfiler))); + logger.warn( + PROXY_TIMEOUT_REQUEST, + "", + "", + String.format( + "[Dubbo-Consumer] execute service %s#%s cost %d.%06d ms, this invocation almost (maybe already) timeout. Timeout: %dms\n" + + "invocation context:\n%s" + "thread info: \n%s", + rpcInvocation.getProtocolServiceKey(), + rpcInvocation.getMethodName(), + usage / 1000_000, + usage % 1000_000, + timeout, + attachment, + Profiler.buildDetail(bizProfiler))); } } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandler.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandler.java index 255a5ad089..a95022524f 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandler.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandler.java @@ -66,7 +66,13 @@ public class InvokerInvocationHandler implements InvocationHandler { } else if (parameterTypes.length == 1 && "equals".equals(methodName)) { return invoker.equals(args[0]); } - RpcInvocation rpcInvocation = new RpcInvocation(serviceModel, method.getName(), invoker.getInterface().getName(), protocolServiceKey, method.getParameterTypes(), args); + RpcInvocation rpcInvocation = new RpcInvocation( + serviceModel, + method.getName(), + invoker.getInterface().getName(), + protocolServiceKey, + method.getParameterTypes(), + args); if (serviceModel instanceof ConsumerModel) { rpcInvocation.put(Constants.CONSUMER_MODEL, serviceModel); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/MethodInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/MethodInvoker.java index 8f7df1f86a..ed4a199f54 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/MethodInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/MethodInvoker.java @@ -40,7 +40,8 @@ public interface MethodInvoker { } @Override - public Object invoke(Object instance, String methodName, Class[] parameterTypes, Object[] arguments) throws Throwable { + public Object invoke(Object instance, String methodName, Class[] parameterTypes, Object[] arguments) + throws Throwable { return method.invoke(instance, arguments); } } @@ -57,13 +58,15 @@ public interface MethodInvoker { } @Override - public Object invoke(Object instance, String methodName, Class[] parameterTypes, Object[] arguments) throws Throwable { + public Object invoke(Object instance, String methodName, Class[] parameterTypes, Object[] arguments) + throws Throwable { for (MethodMeta meta : methods) { if (Arrays.equals(meta.getParametersType(), parameterTypes)) { return meta.getMethod().invoke(instance, arguments); } } - throw new NoSuchMethodException(instance.getClass().getName() + "." + methodName + Arrays.toString(parameterTypes)); + throw new NoSuchMethodException( + instance.getClass().getName() + "." + methodName + Arrays.toString(parameterTypes)); } private static class MethodMeta { @@ -105,10 +108,12 @@ public interface MethodInvoker { } @Override - public Object invoke(Object instance, String methodName, Class[] parameterTypes, Object[] arguments) throws Throwable { + public Object invoke(Object instance, String methodName, Class[] parameterTypes, Object[] arguments) + throws Throwable { MethodInvoker invoker = invokers.get(methodName); if (invoker == null) { - throw new NoSuchMethodException(instance.getClass().getName() + "." + methodName + Arrays.toString(parameterTypes)); + throw new NoSuchMethodException( + instance.getClass().getName() + "." + methodName + Arrays.toString(parameterTypes)); } return invoker.invoke(instance, methodName, parameterTypes, arguments); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/javassist/JavassistProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/javassist/JavassistProxyFactory.java index 4d341b2ec9..93695bde04 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/javassist/JavassistProxyFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/javassist/JavassistProxyFactory.java @@ -35,7 +35,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED * JavassistRpcProxyFactory */ public class JavassistProxyFactory extends AbstractProxyFactory { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(JavassistProxyFactory.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(JavassistProxyFactory.class); private final JdkProxyFactory jdkProxyFactory = new JdkProxyFactory(); @Override @@ -47,14 +48,29 @@ public class JavassistProxyFactory extends AbstractProxyFactory { // try fall back to JDK proxy factory try { T proxy = jdkProxyFactory.getProxy(invoker, interfaces); - logger.error(PROXY_FAILED, "", "", "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy success. " + - "Interfaces: " + Arrays.toString(interfaces), fromJavassist); + logger.error( + PROXY_FAILED, + "", + "", + "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy success. " + + "Interfaces: " + Arrays.toString(interfaces), + fromJavassist); return proxy; } catch (Throwable fromJdk) { - logger.error(PROXY_FAILED, "", "", "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. " + - "Interfaces: " + Arrays.toString(interfaces) + " Javassist Error.", fromJavassist); - logger.error(PROXY_FAILED, "", "", "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. " + - "Interfaces: " + Arrays.toString(interfaces) + " JDK Error.", fromJdk); + logger.error( + PROXY_FAILED, + "", + "", + "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. " + + "Interfaces: " + Arrays.toString(interfaces) + " Javassist Error.", + fromJavassist); + logger.error( + PROXY_FAILED, + "", + "", + "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. " + + "Interfaces: " + Arrays.toString(interfaces) + " JDK Error.", + fromJdk); throw fromJavassist; } } @@ -64,12 +80,12 @@ public class JavassistProxyFactory extends AbstractProxyFactory { public Invoker getInvoker(T proxy, Class type, URL url) { try { // TODO Wrapper cannot handle this scenario correctly: the classname contains '$' - final Wrapper wrapper = Wrapper.getWrapper(proxy.getClass().getName().indexOf('$') < 0 ? proxy.getClass() : type); + final Wrapper wrapper = + Wrapper.getWrapper(proxy.getClass().getName().indexOf('$') < 0 ? proxy.getClass() : type); return new AbstractProxyInvoker(proxy, type, url) { @Override - protected Object doInvoke(T proxy, String methodName, - Class[] parameterTypes, - Object[] arguments) throws Throwable { + protected Object doInvoke(T proxy, String methodName, Class[] parameterTypes, Object[] arguments) + throws Throwable { return wrapper.invokeMethod(proxy, methodName, parameterTypes, arguments); } }; @@ -77,18 +93,32 @@ public class JavassistProxyFactory extends AbstractProxyFactory { // try fall back to JDK proxy factory try { Invoker invoker = jdkProxyFactory.getInvoker(proxy, type, url); - logger.error(PROXY_FAILED, "", "", "Failed to generate invoker by Javassist failed. Fallback to use JDK proxy success. " + - "Interfaces: " + type, fromJavassist); + logger.error( + PROXY_FAILED, + "", + "", + "Failed to generate invoker by Javassist failed. Fallback to use JDK proxy success. " + + "Interfaces: " + type, + fromJavassist); // log out error return invoker; } catch (Throwable fromJdk) { - logger.error(PROXY_FAILED, "", "", "Failed to generate invoker by Javassist failed. Fallback to use JDK proxy is also failed. " + - "Interfaces: " + type + " Javassist Error.", fromJavassist); - logger.error(PROXY_FAILED, "", "", "Failed to generate invoker by Javassist failed. Fallback to use JDK proxy is also failed. " + - "Interfaces: " + type + " JDK Error.", fromJdk); + logger.error( + PROXY_FAILED, + "", + "", + "Failed to generate invoker by Javassist failed. Fallback to use JDK proxy is also failed. " + + "Interfaces: " + type + " Javassist Error.", + fromJavassist); + logger.error( + PROXY_FAILED, + "", + "", + "Failed to generate invoker by Javassist failed. Fallback to use JDK proxy is also failed. " + + "Interfaces: " + type + " JDK Error.", + fromJdk); throw fromJavassist; } } } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/jdk/JdkProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/jdk/JdkProxyFactory.java index 9cf31df9f2..2e74a0de79 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/jdk/JdkProxyFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/jdk/JdkProxyFactory.java @@ -33,20 +33,19 @@ public class JdkProxyFactory extends AbstractProxyFactory { @Override @SuppressWarnings("unchecked") public T getProxy(Invoker invoker, Class[] interfaces) { - return (T) Proxy.newProxyInstance(invoker.getInterface().getClassLoader(), interfaces, new InvokerInvocationHandler(invoker)); + return (T) Proxy.newProxyInstance( + invoker.getInterface().getClassLoader(), interfaces, new InvokerInvocationHandler(invoker)); } @Override public Invoker getInvoker(T proxy, Class type, URL url) { return new AbstractProxyInvoker(proxy, type, url) { @Override - protected Object doInvoke(T proxy, String methodName, - Class[] parameterTypes, - Object[] arguments) throws Throwable { + protected Object doInvoke(T proxy, String methodName, Class[] parameterTypes, Object[] arguments) + throws Throwable { Method method = proxy.getClass().getMethod(methodName, parameterTypes); return method.invoke(proxy, arguments); } }; } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapper.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapper.java index 9721df43ec..7a41c52bb7 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapper.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapper.java @@ -48,7 +48,8 @@ import static org.apache.dubbo.rpc.Constants.STUB_KEY; */ public class StubProxyFactoryWrapper implements ProxyFactory { - private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(StubProxyFactoryWrapper.class); + private static final ErrorTypeAwareLogger LOGGER = + LoggerFactory.getErrorTypeAwareLogger(StubProxyFactoryWrapper.class); private final ProxyFactory proxyFactory; @@ -80,15 +81,19 @@ public class StubProxyFactoryWrapper implements ProxyFactory { try { Class stubClass = ReflectUtils.forName(stub); if (!serviceType.isAssignableFrom(stubClass)) { - throw new IllegalStateException("The stub implementation class " + stubClass.getName() + " not implement interface " + serviceType.getName()); + throw new IllegalStateException("The stub implementation class " + stubClass.getName() + + " not implement interface " + serviceType.getName()); } try { Constructor constructor = ReflectUtils.findConstructor(stubClass, serviceType); - proxy = (T) constructor.newInstance(new Object[]{proxy}); - //export stub service + proxy = (T) constructor.newInstance(new Object[] {proxy}); + // export stub service URLBuilder urlBuilder = URLBuilder.from(url); if (url.getParameter(STUB_EVENT_KEY, DEFAULT_STUB_EVENT)) { - urlBuilder.addParameter(STUB_EVENT_METHODS_KEY, StringUtils.join(Wrapper.getWrapper(proxy.getClass()).getDeclaredMethodNames(), ",")); + urlBuilder.addParameter( + STUB_EVENT_METHODS_KEY, + StringUtils.join( + Wrapper.getWrapper(proxy.getClass()).getDeclaredMethodNames(), ",")); urlBuilder.addParameter(IS_SERVER_KEY, Boolean.FALSE.toString()); try { export(proxy, invoker.getInterface(), urlBuilder.build()); @@ -97,16 +102,26 @@ public class StubProxyFactoryWrapper implements ProxyFactory { } } } catch (NoSuchMethodException e) { - throw new IllegalStateException("No such constructor \"public " + stubClass.getSimpleName() + "(" + serviceType.getName() + ")\" in stub implementation class " + stubClass.getName(), e); + throw new IllegalStateException( + "No such constructor \"public " + stubClass.getSimpleName() + "(" + + serviceType.getName() + ")\" in stub implementation class " + + stubClass.getName(), + e); } } catch (Throwable t) { - LOGGER.error(PROXY_FAILED_EXPORT_SERVICE, "", "", "Failed to create stub implementation class " + stub + " in consumer " + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion() + ", cause: " + t.getMessage(), t); + LOGGER.error( + PROXY_FAILED_EXPORT_SERVICE, + "", + "", + "Failed to create stub implementation class " + stub + " in consumer " + + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion() + + ", cause: " + t.getMessage(), + t); // ignore } } } return proxy; - } @Override @@ -123,5 +138,4 @@ public class StubProxyFactoryWrapper implements ProxyFactory { private Exporter export(T instance, Class type, URL url) { return protocol.export(proxyFactory.getInvoker(instance, type, url)); } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/BiStreamMethodHandler.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/BiStreamMethodHandler.java index eca018dfa3..b67670552e 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/BiStreamMethodHandler.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/BiStreamMethodHandler.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.stub; import org.apache.dubbo.common.stream.StreamObserver; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/FutureToObserverAdaptor.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/FutureToObserverAdaptor.java index 16a69a6457..771c155503 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/FutureToObserverAdaptor.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/FutureToObserverAdaptor.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.stub; import org.apache.dubbo.common.stream.StreamObserver; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/ServerStreamMethodHandler.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/ServerStreamMethodHandler.java index f90b0b7742..c9342b4c7c 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/ServerStreamMethodHandler.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/ServerStreamMethodHandler.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.stub; import org.apache.dubbo.common.stream.StreamObserver; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubInvoker.java index 994becda56..3f5350b0bd 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubInvoker.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.stub; import org.apache.dubbo.common.URL; @@ -26,15 +25,14 @@ public class StubInvoker extends AbstractProxyInvoker { private final Map> handlers; - public StubInvoker(T proxy, URL url, Class type, - Map> handlers) { + public StubInvoker(T proxy, URL url, Class type, Map> handlers) { super(proxy, type, url); this.handlers = handlers; } @Override - protected Object doInvoke(T proxy, String methodName, Class[] parameterTypes, - Object[] arguments) throws Throwable { + protected Object doInvoke(T proxy, String methodName, Class[] parameterTypes, Object[] arguments) + throws Throwable { return handlers.get(methodName).invoke(arguments); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubMethodHandler.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubMethodHandler.java index 1a7b8d2b22..465390d89f 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubMethodHandler.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubMethodHandler.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.stub; import java.util.concurrent.CompletableFuture; @@ -36,4 +35,3 @@ public interface StubMethodHandler { */ CompletableFuture invoke(Object[] arguments); } - diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubProxyFactory.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubProxyFactory.java index c8d0efacda..f626031a83 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubProxyFactory.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubProxyFactory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.stub; import org.apache.dubbo.common.URL; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubSuppliers.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubSuppliers.java index a56e52f643..0da4da185a 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubSuppliers.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubSuppliers.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.stub; import org.apache.dubbo.common.utils.ReflectUtils; @@ -33,17 +32,17 @@ public class StubSuppliers { public static void addDescriptor(String interfaceName, ServiceDescriptor serviceDescriptor) { SERVICE_DESCRIPTOR_MAP.put(interfaceName, serviceDescriptor); } + public static void addSupplier(String interfaceName, Function, Object> supplier) { STUB_SUPPLIERS.put(interfaceName, supplier); } public static T createStub(String interfaceName, Invoker invoker) { - //TODO DO not hack here + // TODO DO not hack here if (!STUB_SUPPLIERS.containsKey(interfaceName)) { ReflectUtils.forName(stubClassName(interfaceName)); if (!STUB_SUPPLIERS.containsKey(interfaceName)) { - throw new IllegalStateException( - "Can not find any stub supplier for " + interfaceName); + throw new IllegalStateException("Can not find any stub supplier for " + interfaceName); } } return (T) STUB_SUPPLIERS.get(interfaceName).apply(invoker); @@ -57,12 +56,11 @@ public class StubSuppliers { } public static ServiceDescriptor getServiceDescriptor(String interfaceName) { - //TODO DO not hack here + // TODO DO not hack here if (!SERVICE_DESCRIPTOR_MAP.containsKey(interfaceName)) { ReflectUtils.forName(stubClassName(interfaceName)); if (!SERVICE_DESCRIPTOR_MAP.containsKey(interfaceName)) { - throw new IllegalStateException( - "Can not find any stub supplier for " + interfaceName); + throw new IllegalStateException("Can not find any stub supplier for " + interfaceName); } } return SERVICE_DESCRIPTOR_MAP.get(interfaceName); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/UnaryStubMethodHandler.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/UnaryStubMethodHandler.java index 81e069fa63..9a1ddca338 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/UnaryStubMethodHandler.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/UnaryStubMethodHandler.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.stub; import org.apache.dubbo.common.stream.StreamObserver; diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/Dubbo2RpcExceptionUtils.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/Dubbo2RpcExceptionUtils.java index 548e6807bc..076aa95cc8 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/Dubbo2RpcExceptionUtils.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/Dubbo2RpcExceptionUtils.java @@ -41,7 +41,8 @@ public class Dubbo2RpcExceptionUtils { } } - private static Constructor loadConstructor(Class... parameterTypes) { + private static Constructor loadConstructor( + Class... parameterTypes) { if (RPC_EXCEPTION_CLASS == null) { return null; } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java index 6605d93d2d..94d48c72fb 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java @@ -60,10 +60,11 @@ public class RpcUtils { public static Class getReturnType(Invocation invocation) { try { - if (invocation != null && invocation.getInvoker() != null - && invocation.getInvoker().getUrl() != null - && invocation.getInvoker().getInterface() != GenericService.class - && !invocation.getMethodName().startsWith("$")) { + if (invocation != null + && invocation.getInvoker() != null + && invocation.getInvoker().getUrl() != null + && invocation.getInvoker().getInterface() != GenericService.class + && !invocation.getMethodName().startsWith("$")) { String service = invocation.getInvoker().getUrl().getServiceInterface(); if (StringUtils.isNotEmpty(service)) { Method method = getMethodByService(invocation, service); @@ -78,10 +79,11 @@ public class RpcUtils { public static Type[] getReturnTypes(Invocation invocation) { try { - if (invocation != null && invocation.getInvoker() != null - && invocation.getInvoker().getUrl() != null - && invocation.getInvoker().getInterface() != GenericService.class - && !invocation.getMethodName().startsWith("$")) { + if (invocation != null + && invocation.getInvoker() != null + && invocation.getInvoker().getUrl() != null + && invocation.getInvoker().getInterface() != GenericService.class + && !invocation.getMethodName().startsWith("$")) { Type[] returnTypes = null; if (invocation instanceof RpcInvocation) { returnTypes = ((RpcInvocation) invocation).getReturnTypes(); @@ -137,9 +139,9 @@ public class RpcUtils { public static String getMethodName(Invocation invocation) { if ($INVOKE.equals(invocation.getMethodName()) - && invocation.getArguments() != null - && invocation.getArguments().length > 0 - && invocation.getArguments()[0] instanceof String) { + && invocation.getArguments() != null + && invocation.getArguments().length > 0 + && invocation.getArguments()[0] instanceof String) { return (String) invocation.getArguments()[0]; } return invocation.getMethodName(); @@ -147,9 +149,9 @@ public class RpcUtils { public static Object[] getArguments(Invocation invocation) { if ($INVOKE.equals(invocation.getMethodName()) - && invocation.getArguments() != null - && invocation.getArguments().length > 2 - && invocation.getArguments()[2] instanceof Object[]) { + && invocation.getArguments() != null + && invocation.getArguments().length > 2 + && invocation.getArguments()[2] instanceof Object[]) { return (Object[]) invocation.getArguments()[2]; } return invocation.getArguments(); @@ -157,9 +159,9 @@ public class RpcUtils { public static Class[] getParameterTypes(Invocation invocation) { if ($INVOKE.equals(invocation.getMethodName()) - && invocation.getArguments() != null - && invocation.getArguments().length > 1 - && invocation.getArguments()[1] instanceof String[]) { + && invocation.getArguments() != null + && invocation.getArguments().length > 1 + && invocation.getArguments()[1] instanceof String[]) { String[] types = (String[]) invocation.getArguments()[1]; if (types == null) { return new Class[0]; @@ -207,7 +209,8 @@ public class RpcUtils { // check parameterTypesDesc to fix CVE-2020-1948 public static boolean isGenericCall(String parameterTypesDesc, String method) { - return ($INVOKE.equals(method) || $INVOKE_ASYNC.equals(method)) && GENERIC_PARAMETER_DESC.equals(parameterTypesDesc); + return ($INVOKE.equals(method) || $INVOKE_ASYNC.equals(method)) + && GENERIC_PARAMETER_DESC.equals(parameterTypesDesc); } // check parameterTypesDesc to fix CVE-2020-1948 @@ -244,8 +247,9 @@ public class RpcUtils { private static Method getMethodByService(Invocation invocation, String service) throws NoSuchMethodException { Class invokerInterface = invocation.getInvoker().getInterface(); - Class cls = invokerInterface != null ? ReflectUtils.forName(invokerInterface.getClassLoader(), service) - : ReflectUtils.forName(service); + Class cls = invokerInterface != null + ? ReflectUtils.forName(invokerInterface.getClassLoader(), service) + : ReflectUtils.forName(service); Method method = cls.getMethod(invocation.getMethodName(), invocation.getParameterTypes()); if (method.getReturnType() == void.class) { return null; @@ -265,7 +269,8 @@ public class RpcUtils { return timeout; } - public static long getTimeout(URL url, String methodName, RpcContext context, Invocation invocation, long defaultTimeout) { + public static long getTimeout( + URL url, String methodName, RpcContext context, Invocation invocation, long defaultTimeout) { long timeout = defaultTimeout; Object timeoutFromContext = context.getObjectAttachment(TIMEOUT_KEY); Object timeoutFromInvocation = invocation.getObjectAttachment(TIMEOUT_KEY); @@ -285,7 +290,8 @@ public class RpcUtils { int timeout = (int) defaultTimeout; if (countdown == null) { if (url != null) { - timeout = (int) RpcUtils.getTimeout(url, methodName, RpcContext.getClientAttachment(), invocation, defaultTimeout); + timeout = (int) RpcUtils.getTimeout( + url, methodName, RpcContext.getClientAttachment(), invocation, defaultTimeout); if (url.getMethodParameter(methodName, ENABLE_TIMEOUT_COUNTDOWN_KEY, false)) { // pass timeout to remote server invocation.setObjectAttachment(TIMEOUT_ATTACHMENT_KEY, timeout); diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/AppResponseTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/AppResponseTest.java index df26ab2402..2990c61ef1 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/AppResponseTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/AppResponseTest.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.rpc; +import java.util.HashMap; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.HashMap; - import static org.junit.jupiter.api.Assumptions.assumeFalse; class AppResponseTest { @@ -45,7 +45,7 @@ class AppResponseTest { StackTraceElement[] stackTrace = appResponse.getException().getStackTrace(); Assertions.assertNotNull(stackTrace); - Assertions.assertEquals(0,stackTrace.length); + Assertions.assertEquals(0, stackTrace.length); } @Test @@ -71,7 +71,7 @@ class AppResponseTest { StackTraceElement[] stackTrace = appResponse.getException().getStackTrace(); Assertions.assertNotNull(stackTrace); - Assertions.assertEquals(0,stackTrace.length); + Assertions.assertEquals(0, stackTrace.length); } private Throwable buildEmptyStackTraceException() { @@ -120,5 +120,4 @@ class AppResponseTest { response.setObjectAttachments(map); Assertions.assertEquals(map, response.getObjectAttachments()); } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/CancellationContextTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/CancellationContextTest.java index f6fd20b09d..02eb431ffd 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/CancellationContextTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/CancellationContextTest.java @@ -14,14 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc; +import java.util.concurrent.CountDownLatch; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.concurrent.CountDownLatch; - /** * {@link CancellationContext} */ @@ -57,5 +56,4 @@ class CancellationContextTest { }); latch.await(); } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/CustomArgument.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/CustomArgument.java index ae4c3a3ab3..5cae1c2071 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/CustomArgument.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/CustomArgument.java @@ -26,8 +26,8 @@ public class CustomArgument implements Serializable { Type type; String name; - public CustomArgument() { - } + public CustomArgument() {} + public CustomArgument(Type type, String name) { super(); this.type = type; diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/DemoRequest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/DemoRequest.java index d30bc23733..8efd2205d4 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/DemoRequest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/DemoRequest.java @@ -21,7 +21,6 @@ import java.io.Serializable; /** * TestRequest. */ - class DemoRequest implements Serializable { private static final long serialVersionUID = -2579095288792344869L; diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/FutureContextTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/FutureContextTest.java index df2d19b394..a152ddda36 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/FutureContextTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/FutureContextTest.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.rpc; +import java.util.concurrent.CompletableFuture; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.concurrent.CompletableFuture; - /** * */ @@ -32,7 +32,9 @@ class FutureContextTest { FutureContext.getContext().setFuture(CompletableFuture.completedFuture("future from thread1")); try { Thread.sleep(500); - Assertions.assertEquals("future from thread1", FutureContext.getContext().getCompletableFuture().get()); + Assertions.assertEquals( + "future from thread1", + FutureContext.getContext().getCompletableFuture().get()); } catch (Exception e) { e.printStackTrace(); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/PenetrateAttachmentSelectorTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/PenetrateAttachmentSelectorTest.java index 21ff35c2b4..b90e8bb2aa 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/PenetrateAttachmentSelectorTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/PenetrateAttachmentSelectorTest.java @@ -20,13 +20,13 @@ import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.Map; import java.util.Set; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + /** * {@link PenetrateAttachmentSelector} */ @@ -34,12 +34,14 @@ class PenetrateAttachmentSelectorTest { @Test void test() { - ExtensionLoader selectorExtensionLoader = ApplicationModel.defaultModel().getExtensionLoader(PenetrateAttachmentSelector.class); + ExtensionLoader selectorExtensionLoader = + ApplicationModel.defaultModel().getExtensionLoader(PenetrateAttachmentSelector.class); Set supportedSelectors = selectorExtensionLoader.getSupportedExtensions(); Map allSelected = new HashMap<>(); if (CollectionUtils.isNotEmpty(supportedSelectors)) { for (String supportedSelector : supportedSelectors) { - Map selected = selectorExtensionLoader.getExtension(supportedSelector).select(null, null, null); + Map selected = + selectorExtensionLoader.getExtension(supportedSelector).select(null, null, null); allSelected.putAll(selected); } } @@ -48,12 +50,14 @@ class PenetrateAttachmentSelectorTest { @Test public void testSelectReverse() { - ExtensionLoader selectorExtensionLoader = ApplicationModel.defaultModel().getExtensionLoader(PenetrateAttachmentSelector.class); + ExtensionLoader selectorExtensionLoader = + ApplicationModel.defaultModel().getExtensionLoader(PenetrateAttachmentSelector.class); Set supportedSelectors = selectorExtensionLoader.getSupportedExtensions(); Map allSelected = new HashMap<>(); if (CollectionUtils.isNotEmpty(supportedSelectors)) { for (String supportedSelector : supportedSelectors) { - Map selected = selectorExtensionLoader.getExtension(supportedSelector).selectReverse(null, null, null); + Map selected = + selectorExtensionLoader.getExtension(supportedSelector).selectReverse(null, null, null); allSelected.putAll(selected); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcContextTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcContextTest.java index e6d26ff8fe..b6ce8339e0 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcContextTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcContextTest.java @@ -18,9 +18,6 @@ package org.apache.dubbo.rpc; import org.apache.dubbo.common.URL; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.Collection; import java.util.HashMap; import java.util.Map; @@ -28,6 +25,9 @@ import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class RpcContextTest { @Test @@ -38,7 +38,7 @@ class RpcContextTest { RpcContext.removeClientAttachment(); // if null, will return the initialize value. - //Assertions.assertNull(RpcContext.getContext()); + // Assertions.assertNull(RpcContext.getContext()); Assertions.assertNotNull(RpcContext.getClientAttachment()); Assertions.assertNotEquals(rpcContext, RpcContext.getClientAttachment()); @@ -47,7 +47,6 @@ class RpcContextTest { RpcContext.removeServerContext(); Assertions.assertNotEquals(serverRpcContext, RpcContext.getServerContext()); - } @Test @@ -74,8 +73,8 @@ class RpcContextTest { RpcContext context = RpcContext.getServiceContext(); - //TODO fix npe - //context.isProviderSide(); + // TODO fix npe + // context.isProviderSide(); context.setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1")); Assertions.assertFalse(context.isConsumerSide()); @@ -154,7 +153,8 @@ class RpcContextTest { Assertions.assertTrue(rpcContext.isAsyncStarted()); asyncContext.write(new Object()); - Assertions.assertTrue(((AsyncContextImpl) asyncContext).getInternalFuture().isDone()); + Assertions.assertTrue( + ((AsyncContextImpl) asyncContext).getInternalFuture().isDone()); rpcContext.stopAsync(); Assertions.assertTrue(rpcContext.isAsyncStarted()); @@ -204,6 +204,7 @@ class RpcContextTest { rpcContext.setObjectAttachments(map); Assertions.assertEquals(map, rpcContext.getObjectAttachments()); } + @Test public void say() { final String key = "user-attachment"; @@ -215,15 +216,13 @@ class RpcContextTest { } @Test - void testRestore() { - - } + void testRestore() {} @Test public void testRpcServerContextAttachment() { RpcContextAttachment attachment = RpcContext.getServerContext(); - attachment.setAttachment("key_1","value_1"); - attachment.setAttachment("key_2","value_2"); + attachment.setAttachment("key_1", "value_1"); + attachment.setAttachment("key_2", "value_2"); Assertions.assertEquals("value_1", attachment.getAttachment("key_1")); Assertions.assertEquals(null, attachment.getAttachment("aaa")); attachment.removeAttachment("key_1"); @@ -263,23 +262,22 @@ class RpcContextTest { Assertions.assertEquals("value_7", objectMap1.get("key_7")); Assertions.assertEquals("value_8", objectMap1.get("key_8")); attachment.clearAttachments(); - } @Test public void testRpcServerContextClearAttachment() { RpcServerContextAttachment attachment = new RpcServerContextAttachment(); - attachment.setAttachment("key_1","value_1"); - attachment.setAttachment("key_2","value_2"); - attachment.setAttachment("key_3","value_3"); + attachment.setAttachment("key_1", "value_1"); + attachment.setAttachment("key_2", "value_2"); + attachment.setAttachment("key_3", "value_3"); attachment.clearAttachments(); Assertions.assertEquals(null, attachment.getAttachment("key_1")); Assertions.assertEquals(null, attachment.getAttachment("key_2")); Assertions.assertEquals(null, attachment.getAttachment("key_3")); - attachment.setObjectAttachment("key_1","value_1"); - attachment.setObjectAttachment("key_2","value_2"); - attachment.setObjectAttachment("key_3","value_3"); + attachment.setObjectAttachment("key_1", "value_1"); + attachment.setObjectAttachment("key_2", "value_2"); + attachment.setObjectAttachment("key_3", "value_3"); attachment.clearAttachments(); Assertions.assertEquals(null, attachment.getAttachment("key_1")); Assertions.assertEquals(null, attachment.getAttachment("key_2")); @@ -299,8 +297,9 @@ class RpcContextTest { @Test public void testObjectAttachmentMap() { - RpcServerContextAttachment attachment = new RpcServerContextAttachment(); - RpcServerContextAttachment.ObjectAttachmentMap objectAttachmentMap = new RpcServerContextAttachment.ObjectAttachmentMap(attachment); + RpcServerContextAttachment attachment = new RpcServerContextAttachment(); + RpcServerContextAttachment.ObjectAttachmentMap objectAttachmentMap = + new RpcServerContextAttachment.ObjectAttachmentMap(attachment); objectAttachmentMap.put("key_1", "value_1"); Set keySet = objectAttachmentMap.keySet(); Assertions.assertEquals(true, keySet.contains("key_1")); @@ -317,8 +316,8 @@ class RpcContextTest { objectAttachmentMap.remove("key_1"); Assertions.assertEquals(null, objectAttachmentMap.get("key_1")); Map map = new HashMap<>(); - map.put("key_3","value_3"); - map.put("key_4","value_4"); + map.put("key_3", "value_3"); + map.put("key_4", "value_4"); objectAttachmentMap.putAll(map); Assertions.assertEquals("value_3", objectAttachmentMap.get("key_3")); Assertions.assertEquals("value_4", objectAttachmentMap.get("key_4")); @@ -328,8 +327,9 @@ class RpcContextTest { @Test public void testClearAttachmentMap() { - RpcServerContextAttachment attachment = new RpcServerContextAttachment(); - RpcServerContextAttachment.ObjectAttachmentMap objectAttachmentMap = new RpcServerContextAttachment.ObjectAttachmentMap(attachment); + RpcServerContextAttachment attachment = new RpcServerContextAttachment(); + RpcServerContextAttachment.ObjectAttachmentMap objectAttachmentMap = + new RpcServerContextAttachment.ObjectAttachmentMap(attachment); objectAttachmentMap.put("key_1", "value_1"); objectAttachmentMap.put("key_2", "value_2"); objectAttachmentMap.put("key_3", "value_3"); diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcInvocationTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcInvocationTest.java index 461867efef..0933bc42fb 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcInvocationTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcInvocationTest.java @@ -59,6 +59,7 @@ class RpcInvocationTest { rpcInvocation.addInvokedInvoker(invoker3); rpcInvocation.addInvokedInvoker(invoker3); - Assertions.assertEquals(Arrays.asList(invoker1, invoker2, invoker3, invoker3), rpcInvocation.getInvokedInvokers()); + Assertions.assertEquals( + Arrays.asList(invoker1, invoker2, invoker3, invoker3), rpcInvocation.getInvokedInvokers()); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcStatusTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcStatusTest.java index 0ed74bf531..efa938e803 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcStatusTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcStatusTest.java @@ -20,15 +20,15 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.rpc.support.DemoService; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + /** * {@link RpcStatus} */ @@ -59,7 +59,6 @@ class RpcStatusTest { Assertions.assertTrue(flag); flag = RpcStatus.beginCount(url, methodName, max); Assertions.assertFalse(flag); - } @Test @@ -93,7 +92,6 @@ class RpcStatusTest { startLatch.countDown(); endLatch.await(); Assertions.assertEquals(successCount.get(), max); - } @Test diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/TimeoutCountDownTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/TimeoutCountDownTest.java index 5a37f30743..3ef36b4493 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/TimeoutCountDownTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/TimeoutCountDownTest.java @@ -14,14 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc; +import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.concurrent.TimeUnit; - class TimeoutCountDownTest { @Test diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/CompatibleFilterFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/CompatibleFilterFilterTest.java index d07d58452d..d5931e7f3d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/CompatibleFilterFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/CompatibleFilterFilterTest.java @@ -52,8 +52,8 @@ class CompatibleFilterFilterTest { void testInvokerGeneric() { invocation = mock(RpcInvocation.class); given(invocation.getMethodName()).willReturn("$enumlength"); - given(invocation.getParameterTypes()).willReturn(new Class[]{Enum.class}); - given(invocation.getArguments()).willReturn(new Object[]{"hello"}); + given(invocation.getParameterTypes()).willReturn(new Class[] {Enum.class}); + given(invocation.getArguments()).willReturn(new Object[] {"hello"}); invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); @@ -72,8 +72,8 @@ class CompatibleFilterFilterTest { void testResultHasException() { invocation = mock(RpcInvocation.class); given(invocation.getMethodName()).willReturn("enumlength"); - given(invocation.getParameterTypes()).willReturn(new Class[]{Enum.class}); - given(invocation.getArguments()).willReturn(new Object[]{"hello"}); + given(invocation.getParameterTypes()).willReturn(new Class[] {Enum.class}); + given(invocation.getArguments()).willReturn(new Object[] {"hello"}); invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); @@ -93,8 +93,8 @@ class CompatibleFilterFilterTest { void testInvokerJsonPojoSerialization() throws Exception { invocation = mock(RpcInvocation.class); given(invocation.getMethodName()).willReturn("enumlength"); - given(invocation.getParameterTypes()).willReturn(new Class[]{Type[].class}); - given(invocation.getArguments()).willReturn(new Object[]{"hello"}); + given(invocation.getParameterTypes()).willReturn(new Class[] {Type[].class}); + given(invocation.getArguments()).willReturn(new Object[] {"hello"}); invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); @@ -116,8 +116,8 @@ class CompatibleFilterFilterTest { void testInvokerNonJsonEnumSerialization() throws Exception { invocation = mock(RpcInvocation.class); given(invocation.getMethodName()).willReturn("enumlength"); - given(invocation.getParameterTypes()).willReturn(new Class[]{Type[].class}); - given(invocation.getArguments()).willReturn(new Object[]{"hello"}); + given(invocation.getParameterTypes()).willReturn(new Class[] {Type[].class}); + given(invocation.getArguments()).willReturn(new Object[] {"hello"}); invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); @@ -139,28 +139,28 @@ class CompatibleFilterFilterTest { void testInvokerNonJsonNonPojoSerialization() { invocation = mock(RpcInvocation.class); given(invocation.getMethodName()).willReturn("echo"); - given(invocation.getParameterTypes()).willReturn(new Class[]{String.class}); - given(invocation.getArguments()).willReturn(new Object[]{"hello"}); + given(invocation.getParameterTypes()).willReturn(new Class[] {String.class}); + given(invocation.getArguments()).willReturn(new Object[] {"hello"}); invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); given(invoker.getInterface()).willReturn(DemoService.class); AppResponse result = new AppResponse(); - result.setValue(new String[]{"High"}); + result.setValue(new String[] {"High"}); given(invoker.invoke(invocation)).willReturn(result); URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); given(invoker.getUrl()).willReturn(url); Result filterResult = compatibleFilter.invoke(invoker, invocation); - assertArrayEquals(new String[]{"High"}, (String[]) filterResult.getValue()); + assertArrayEquals(new String[] {"High"}, (String[]) filterResult.getValue()); } @Test void testInvokerNonJsonPojoSerialization() { invocation = mock(RpcInvocation.class); given(invocation.getMethodName()).willReturn("echo"); - given(invocation.getParameterTypes()).willReturn(new Class[]{String.class}); - given(invocation.getArguments()).willReturn(new Object[]{"hello"}); + given(invocation.getParameterTypes()).willReturn(new Class[] {String.class}); + given(invocation.getArguments()).willReturn(new Object[] {"hello"}); invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/DeprecatedFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/DeprecatedFilterTest.java index 8809dc8ba8..750d54d795 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/DeprecatedFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/DeprecatedFilterTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.filter; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.LogUtil; import org.apache.dubbo.rpc.Filter; @@ -41,8 +40,10 @@ class DeprecatedFilterTest { URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1&echo." + DEPRECATED_KEY + "=true"); LogUtil.start(); deprecatedFilter.invoke(new MyInvoker(url), new MockInvocation()); - assertEquals(1, - LogUtil.findMessage("The service method org.apache.dubbo.rpc.support.DemoService.echo(String) is DEPRECATED")); + assertEquals( + 1, + LogUtil.findMessage( + "The service method org.apache.dubbo.rpc.support.DemoService.echo(String) is DEPRECATED")); LogUtil.stop(); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/EchoFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/EchoFilterTest.java index 3408b2ebc5..bf89c7032d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/EchoFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/EchoFilterTest.java @@ -59,12 +59,13 @@ class EchoFilterTest { Invocation createMockRpcInvocation() { Invocation invocation = mock(RpcInvocation.class); - given(invocation.getParameterTypes()).willReturn(new Class[]{Enum.class}); - given(invocation.getArguments()).willReturn(new Object[]{"hello"}); + given(invocation.getParameterTypes()).willReturn(new Class[] {Enum.class}); + given(invocation.getArguments()).willReturn(new Object[] {"hello"}); given(invocation.getObjectAttachments()).willReturn(null); return invocation; } - Invoker createMockInvoker(Invocation invocation){ + + Invoker createMockInvoker(Invocation invocation) { Invoker invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); given(invoker.getInterface()).willReturn(DemoService.class); diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExceptionFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExceptionFilterTest.java index b2cae229e9..76c964d8cf 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExceptionFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExceptionFilterTest.java @@ -53,7 +53,8 @@ class ExceptionFilterTest { RpcException exception = new RpcException("TestRpcException"); ExceptionFilter exceptionFilter = new ExceptionFilter(); - RpcInvocation invocation = new RpcInvocation("sayHello", DemoService.class.getName(), "", new Class[]{String.class}, new Object[]{"world"}); + RpcInvocation invocation = new RpcInvocation( + "sayHello", DemoService.class.getName(), "", new Class[] {String.class}, new Object[] {"world"}); Invoker invoker = mock(Invoker.class); given(invoker.getInterface()).willReturn(DemoService.class); given(invoker.invoke(eq(invocation))).willThrow(exception); @@ -66,9 +67,14 @@ class ExceptionFilterTest { exceptionFilter.onError(e, invoker, invocation); } - failsafeLogger.error(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", eq("Got unchecked and undeclared exception which called by 127.0.0.1. service: " - + DemoService.class.getName() + ", method: sayHello, exception: " - + RpcException.class.getName() + ": TestRpcException"), eq(exception)); + failsafeLogger.error( + CONFIG_FILTER_VALIDATION_EXCEPTION, + "", + "", + eq("Got unchecked and undeclared exception which called by 127.0.0.1. service: " + + DemoService.class.getName() + ", method: sayHello, exception: " + + RpcException.class.getName() + ": TestRpcException"), + eq(exception)); RpcContext.removeContext(); } @@ -77,7 +83,8 @@ class ExceptionFilterTest { void testJavaException() { ExceptionFilter exceptionFilter = new ExceptionFilter(); - RpcInvocation invocation = new RpcInvocation("sayHello", DemoService.class.getName(), "", new Class[]{String.class}, new Object[]{"world"}); + RpcInvocation invocation = new RpcInvocation( + "sayHello", DemoService.class.getName(), "", new Class[] {String.class}, new Object[] {"world"}); AppResponse appResponse = new AppResponse(); appResponse.setException(new IllegalArgumentException("java")); @@ -89,7 +96,6 @@ class ExceptionFilterTest { Result newResult = exceptionFilter.invoke(invoker, invocation); Assertions.assertEquals(appResponse.getException(), newResult.getException()); - } @SuppressWarnings("unchecked") @@ -97,7 +103,8 @@ class ExceptionFilterTest { void testRuntimeException() { ExceptionFilter exceptionFilter = new ExceptionFilter(); - RpcInvocation invocation = new RpcInvocation("sayHello", DemoService.class.getName(), "", new Class[]{String.class}, new Object[]{"world"}); + RpcInvocation invocation = new RpcInvocation( + "sayHello", DemoService.class.getName(), "", new Class[] {String.class}, new Object[] {"world"}); AppResponse appResponse = new AppResponse(); appResponse.setException(new LocalException("localException")); @@ -109,7 +116,6 @@ class ExceptionFilterTest { Result newResult = exceptionFilter.invoke(invoker, invocation); Assertions.assertEquals(appResponse.getException(), newResult.getException()); - } @SuppressWarnings("unchecked") @@ -117,13 +123,13 @@ class ExceptionFilterTest { void testConvertToRunTimeException() throws Exception { ExceptionFilter exceptionFilter = new ExceptionFilter(); - RpcInvocation invocation = new RpcInvocation("sayHello", DemoService.class.getName(), "", new Class[]{String.class}, new Object[]{"world"}); + RpcInvocation invocation = new RpcInvocation( + "sayHello", DemoService.class.getName(), "", new Class[] {String.class}, new Object[] {"world"}); AppResponse mockRpcResult = new AppResponse(); mockRpcResult.setException(new HessianException("hessian")); Result mockAsyncResult = AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation); - Invoker invoker = mock(Invoker.class); when(invoker.invoke(invocation)).thenReturn(mockAsyncResult); when(invoker.getInterface()).thenReturn(DemoService.class); @@ -137,5 +143,4 @@ class ExceptionFilterTest { Assertions.assertEquals(appResponse.getException().getClass(), RuntimeException.class); } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TimeoutFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TimeoutFilterTest.java index 3613f54007..878d2b78c4 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TimeoutFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TimeoutFilterTest.java @@ -41,7 +41,9 @@ class TimeoutFilterTest { Invoker invoker = Mockito.mock(Invoker.class); when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result")); - when(invoker.getUrl()).thenReturn(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&timeout=" + timeout)); + when(invoker.getUrl()) + .thenReturn( + URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&timeout=" + timeout)); Invocation invocation = Mockito.mock(Invocation.class); when(invocation.getMethodName()).thenReturn("testInvokeWithoutTimeout"); @@ -62,6 +64,5 @@ class TimeoutFilterTest { Result result = timeoutFilter.invoke(invoker, invocation); Assertions.assertEquals("Dubbo", result.getValue()); - } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/protocol/CountInvokerListener.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/protocol/CountInvokerListener.java index 420bbf7a54..c1c78ca04e 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/protocol/CountInvokerListener.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/protocol/CountInvokerListener.java @@ -22,10 +22,9 @@ import org.apache.dubbo.rpc.RpcException; import java.util.concurrent.atomic.AtomicInteger; - public class CountInvokerListener implements InvokerListener { - private final static AtomicInteger counter = new AtomicInteger(0); + private static final AtomicInteger counter = new AtomicInteger(0); @Override public void referred(Invoker invoker) throws RpcException { @@ -34,9 +33,7 @@ public class CountInvokerListener implements InvokerListener { } @Override - public void destroyed(Invoker invoker) { - - } + public void destroyed(Invoker invoker) {} public static int getCounter() { return counter.get(); diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapperTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapperTest.java index d902559af9..56491e09d4 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapperTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapperTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol; - import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; @@ -38,34 +37,39 @@ class ProtocolListenerWrapperTest { @Test void testLoadingListenerForLocalReference() { // verify that no listener is loaded by default - URL urlWithoutListener = URL.valueOf("injvm://127.0.0.1/DemoService") - .addParameter(INTERFACE_KEY, DemoService.class.getName()); - AbstractInvoker invokerWithoutListener = new AbstractInvoker(DemoService.class, urlWithoutListener) { - @Override - protected Result doInvoke(Invocation invocation) throws Throwable { - return null; - } - }; + URL urlWithoutListener = + URL.valueOf("injvm://127.0.0.1/DemoService").addParameter(INTERFACE_KEY, DemoService.class.getName()); + AbstractInvoker invokerWithoutListener = + new AbstractInvoker(DemoService.class, urlWithoutListener) { + @Override + protected Result doInvoke(Invocation invocation) throws Throwable { + return null; + } + }; Protocol protocolWithoutListener = mock(Protocol.class); - when(protocolWithoutListener.refer(DemoService.class, urlWithoutListener)).thenReturn(invokerWithoutListener); + when(protocolWithoutListener.refer(DemoService.class, urlWithoutListener)) + .thenReturn(invokerWithoutListener); - ProtocolListenerWrapper protocolListenerWrapperWithoutListener = new ProtocolListenerWrapper(protocolWithoutListener); + ProtocolListenerWrapper protocolListenerWrapperWithoutListener = + new ProtocolListenerWrapper(protocolWithoutListener); Invoker invoker = protocolListenerWrapperWithoutListener.refer(DemoService.class, urlWithoutListener); Assertions.assertTrue(invoker instanceof ListenerInvokerWrapper); - Assertions.assertEquals(0, ((ListenerInvokerWrapper) invoker).getListeners().size()); + Assertions.assertEquals( + 0, ((ListenerInvokerWrapper) invoker).getListeners().size()); // verify that if the invoker.listener is configured, then load the specified listener URL urlWithListener = URL.valueOf("injvm://127.0.0.1/DemoService") - .addParameter(INTERFACE_KEY, DemoService.class.getName()) - .addParameter(INVOKER_LISTENER_KEY, "count"); - AbstractInvoker invokerWithListener = new AbstractInvoker(DemoService.class, urlWithListener) { - @Override - protected Result doInvoke(Invocation invocation) throws Throwable { - return null; - } - }; + .addParameter(INTERFACE_KEY, DemoService.class.getName()) + .addParameter(INVOKER_LISTENER_KEY, "count"); + AbstractInvoker invokerWithListener = + new AbstractInvoker(DemoService.class, urlWithListener) { + @Override + protected Result doInvoke(Invocation invocation) throws Throwable { + return null; + } + }; Protocol protocol = mock(Protocol.class); when(protocol.refer(DemoService.class, urlWithListener)).thenReturn(invokerWithListener); @@ -81,33 +85,38 @@ class ProtocolListenerWrapperTest { void testLoadingListenerForRemoteReference() { // verify that no listener is loaded by default URL urlWithoutListener = URL.valueOf("dubbo://127.0.0.1:20880/DemoService") - .addParameter(INTERFACE_KEY, DemoService.class.getName()); - AbstractInvoker invokerWithoutListener = new AbstractInvoker(DemoService.class, urlWithoutListener) { - @Override - protected Result doInvoke(Invocation invocation) throws Throwable { - return null; - } - }; + .addParameter(INTERFACE_KEY, DemoService.class.getName()); + AbstractInvoker invokerWithoutListener = + new AbstractInvoker(DemoService.class, urlWithoutListener) { + @Override + protected Result doInvoke(Invocation invocation) throws Throwable { + return null; + } + }; Protocol protocolWithoutListener = mock(Protocol.class); - when(protocolWithoutListener.refer(DemoService.class, urlWithoutListener)).thenReturn(invokerWithoutListener); + when(protocolWithoutListener.refer(DemoService.class, urlWithoutListener)) + .thenReturn(invokerWithoutListener); - ProtocolListenerWrapper protocolListenerWrapperWithoutListener = new ProtocolListenerWrapper(protocolWithoutListener); + ProtocolListenerWrapper protocolListenerWrapperWithoutListener = + new ProtocolListenerWrapper(protocolWithoutListener); Invoker invoker = protocolListenerWrapperWithoutListener.refer(DemoService.class, urlWithoutListener); Assertions.assertTrue(invoker instanceof ListenerInvokerWrapper); - Assertions.assertEquals(0, ((ListenerInvokerWrapper) invoker).getListeners().size()); + Assertions.assertEquals( + 0, ((ListenerInvokerWrapper) invoker).getListeners().size()); // verify that if the invoker.listener is configured, then load the specified listener URL urlWithListener = URL.valueOf("dubbo://127.0.0.1:20880/DemoService") - .addParameter(INTERFACE_KEY, DemoService.class.getName()) - .addParameter(INVOKER_LISTENER_KEY, "count"); - AbstractInvoker invokerWithListener = new AbstractInvoker(DemoService.class, urlWithListener) { - @Override - protected Result doInvoke(Invocation invocation) throws Throwable { - return null; - } - }; + .addParameter(INTERFACE_KEY, DemoService.class.getName()) + .addParameter(INVOKER_LISTENER_KEY, "count"); + AbstractInvoker invokerWithListener = + new AbstractInvoker(DemoService.class, urlWithListener) { + @Override + protected Result doInvoke(Invocation invocation) throws Throwable { + return null; + } + }; Protocol protocol = mock(Protocol.class); when(protocol.refer(DemoService.class, urlWithListener)).thenReturn(invokerWithListener); @@ -118,6 +127,4 @@ class ProtocolListenerWrapperTest { Assertions.assertTrue(invoker instanceof ListenerInvokerWrapper); Assertions.assertEquals(1, CountInvokerListener.getCounter()); } - - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java index 5a19c2f4d8..188c7f603a 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java @@ -24,8 +24,8 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.filter.ClusterFilter; import org.apache.dubbo.rpc.protocol.dubbo.filter.FutureFilter; - import org.apache.dubbo.rpc.support.DemoService; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -46,8 +46,8 @@ class FutureFilterTest { public static void setUp() { invocation = new RpcInvocation(); invocation.setMethodName("echo"); - invocation.setParameterTypes(new Class[]{Enum.class}); - invocation.setArguments(new Object[]{"hello"}); + invocation.setParameterTypes(new Class[] {Enum.class}); + invocation.setArguments(new Object[] {"hello"}); } @Test diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/AbstractProxyTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/AbstractProxyTest.java index 52091590a4..09158b38df 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/AbstractProxyTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/AbstractProxyTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.proxy; import org.apache.dubbo.common.URL; @@ -27,11 +26,10 @@ import org.apache.dubbo.rpc.support.DemoService; import org.apache.dubbo.rpc.support.DemoServiceImpl; import org.apache.dubbo.rpc.support.MyInvoker; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.Arrays; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public abstract class AbstractProxyTest { @@ -51,13 +49,19 @@ public abstract class AbstractProxyTest { Assertions.assertTrue(Arrays.asList(proxy.getClass().getInterfaces()).contains(Destroyable.class)); Assertions.assertTrue(Arrays.asList(proxy.getClass().getInterfaces()).contains(EchoService.class)); - Assertions.assertEquals(invoker.invoke(new RpcInvocation("echo", DemoService.class.getName(), DemoService.class.getName() + ":dubbo", new Class[]{String.class}, new Object[]{"aa"})).getValue() - , proxy.echo("aa")); + Assertions.assertEquals( + invoker.invoke(new RpcInvocation( + "echo", + DemoService.class.getName(), + DemoService.class.getName() + ":dubbo", + new Class[] {String.class}, + new Object[] {"aa"})) + .getValue(), + proxy.echo("aa")); - Destroyable destroyable = (Destroyable)proxy; + Destroyable destroyable = (Destroyable) proxy; destroyable.$destroy(); Assertions.assertTrue(invoker.isDestroyed()); - } @Test @@ -70,9 +74,14 @@ public abstract class AbstractProxyTest { Assertions.assertEquals(invoker.getInterface(), DemoService.class); - Assertions.assertEquals(invoker.invoke(new RpcInvocation("echo", DemoService.class.getName(), DemoService.class.getName() + ":dubbo", new Class[]{String.class}, new Object[]{"aa"})).getValue(), + Assertions.assertEquals( + invoker.invoke(new RpcInvocation( + "echo", + DemoService.class.getName(), + DemoService.class.getName() + ":dubbo", + new Class[] {String.class}, + new Object[] {"aa"})) + .getValue(), origin.echo("aa")); - } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/DemoRequest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/DemoRequest.java index 28c100ae7a..34347e0153 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/DemoRequest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/DemoRequest.java @@ -21,7 +21,6 @@ import java.io.Serializable; /** * TestRequest. */ - class DemoRequest implements Serializable { private static final long serialVersionUID = -2579095288792344869L; diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/DemoServiceImpl.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/DemoServiceImpl.java index c61176b2d7..95536a95a9 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/DemoServiceImpl.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/DemoServiceImpl.java @@ -21,7 +21,6 @@ import org.apache.dubbo.rpc.RpcContext; /** * DemoServiceImpl */ - public class DemoServiceImpl implements DemoService { public DemoServiceImpl() { super(); @@ -44,25 +43,23 @@ public class DemoServiceImpl implements DemoService { } public int getSize(String[] strs) { - if (strs == null) - return -1; + if (strs == null) return -1; return strs.length; } public int getSize(Object[] os) { - if (os == null) - return -1; + if (os == null) return -1; return os.length; } public Object invoke(String service, String method) throws Exception { - System.out.println("RpcContext.getServerAttachment().getRemoteHost()=" + RpcContext.getServiceContext().getRemoteHost()); + System.out.println("RpcContext.getServerAttachment().getRemoteHost()=" + + RpcContext.getServiceContext().getRemoteHost()); return service + ":" + method; } public Type enumlength(Type... types) { - if (types.length == 0) - return Type.Lower; + if (types.length == 0) return Type.Lower; return types[0]; } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandlerTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandlerTest.java index e4b1266de7..6b2b8b33e2 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandlerTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandlerTest.java @@ -19,13 +19,13 @@ package org.apache.dubbo.rpc.proxy; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invoker; +import java.lang.reflect.Method; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.lang.reflect.Method; - import static org.mockito.Mockito.when; class InvokerInvocationHandlerTest { @@ -48,8 +48,7 @@ class InvokerInvocationHandlerTest { when(invoker.toString()).thenReturn(methodName); Method method = invoker.getClass().getMethod(methodName); - Object result = invokerInvocationHandler.invoke(null, method, new Object[]{}); + Object result = invokerInvocationHandler.invoke(null, method, new Object[] {}); Assertions.assertEquals(methodName, result); } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/MethodInvokerTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/MethodInvokerTest.java index e2be1938d2..4969cf8efc 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/MethodInvokerTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/MethodInvokerTest.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.rpc.proxy; +import java.util.Map; + import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.Map; - import static org.junit.jupiter.api.Assertions.assertInstanceOf; class MethodInvokerTest { @@ -32,7 +32,8 @@ class MethodInvokerTest { MethodInvoker methodInvoker = MethodInvoker.newInstance(RemoteServiceImpl.class); assertInstanceOf(MethodInvoker.CompositeMethodInvoker.class, methodInvoker); - MethodInvoker.CompositeMethodInvoker compositeMethodInvoker = (MethodInvoker.CompositeMethodInvoker) methodInvoker; + MethodInvoker.CompositeMethodInvoker compositeMethodInvoker = + (MethodInvoker.CompositeMethodInvoker) methodInvoker; Map invokers = compositeMethodInvoker.getInvokers(); MethodInvoker getThreadNameMethodInvoker = invokers.get(singleMethodName); assertInstanceOf(MethodInvoker.SingleMethodInvoker.class, getThreadNameMethodInvoker); @@ -40,14 +41,18 @@ class MethodInvokerTest { assertInstanceOf(MethodInvoker.OverloadMethodInvoker.class, sayHelloMethodInvoker); RemoteServiceImpl remoteService = Mockito.mock(RemoteServiceImpl.class); - //invoke success, SingleMethodInvoker does not check parameter types + // invoke success, SingleMethodInvoker does not check parameter types methodInvoker.invoke(remoteService, singleMethodName, new Class[0], new Object[0]); - methodInvoker.invoke(remoteService, singleMethodName, new Class[]{Object.class, Object.class, Object.class}, new Object[0]); + methodInvoker.invoke( + remoteService, singleMethodName, new Class[] {Object.class, Object.class, Object.class}, new Object[0]); Mockito.verify(remoteService, Mockito.times(2)).getThreadName(); - methodInvoker.invoke(remoteService, overloadMethodName, new Class[]{String.class}, new Object[]{"Hello arg1"}); + methodInvoker.invoke( + remoteService, overloadMethodName, new Class[] {String.class}, new Object[] {"Hello arg1"}); Mockito.verify(remoteService, Mockito.times(1)).sayHello("Hello arg1"); - methodInvoker.invoke(remoteService, overloadMethodName, new Class[]{String.class, String.class}, new Object[]{"Hello arg1", "Hello arg2"}); + methodInvoker.invoke(remoteService, overloadMethodName, new Class[] {String.class, String.class}, new Object[] { + "Hello arg1", "Hello arg2" + }); Mockito.verify(remoteService, Mockito.times(1)).sayHello("Hello arg1", "Hello arg2"); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/RemoteServiceImpl.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/RemoteServiceImpl.java index 54b3420ba2..87c0ab083f 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/RemoteServiceImpl.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/RemoteServiceImpl.java @@ -22,7 +22,8 @@ import java.rmi.RemoteException; public class RemoteServiceImpl implements RemoteService { public String getThreadName() throws RemoteException { - System.out.println("RpcContext.getServerAttachment().getRemoteHost()=" + RpcContext.getServiceContext().getRemoteHost()); + System.out.println("RpcContext.getServerAttachment().getRemoteHost()=" + + RpcContext.getServiceContext().getRemoteHost()); return Thread.currentThread().getName(); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/Type.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/Type.java index bf59a4baa5..96f4bd1896 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/Type.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/Type.java @@ -17,5 +17,7 @@ package org.apache.dubbo.rpc.proxy; public enum Type { - High, Normal, Lower + High, + Normal, + Lower } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/javassist/JavassistProxyFactoryTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/javassist/JavassistProxyFactoryTest.java index b2b0f8f203..0c81e72db5 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/javassist/JavassistProxyFactoryTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/javassist/JavassistProxyFactoryTest.java @@ -23,5 +23,4 @@ class JavassistProxyFactoryTest extends AbstractProxyTest { static { factory = new JavassistProxyFactory(); } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/jdk/JdkProxyFactoryTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/jdk/JdkProxyFactoryTest.java index 57b401e114..a11f43558f 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/jdk/JdkProxyFactoryTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/jdk/JdkProxyFactoryTest.java @@ -23,5 +23,4 @@ class JdkProxyFactoryTest extends AbstractProxyTest { static { factory = new JdkProxyFactory(); } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapperTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapperTest.java index 57b50e95e0..7af61e41fe 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapperTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapperTest.java @@ -52,6 +52,5 @@ class StubProxyFactoryWrapperTest { DemoService proxy = stubProxyFactoryWrapper.getProxy(invoker, false); Assertions.assertTrue(proxy instanceof DemoServiceStub); Mockito.verify(protocol, Mockito.times(1)).export(Mockito.any()); - } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/BiStreamMethodHandlerTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/BiStreamMethodHandlerTest.java index 7f2138edb8..4f2a09032c 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/BiStreamMethodHandlerTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/BiStreamMethodHandlerTest.java @@ -14,29 +14,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.stub; import org.apache.dubbo.common.stream.StreamObserver; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + class BiStreamMethodHandlerTest { @Test void invoke() throws ExecutionException, InterruptedException, TimeoutException { StreamObserver responseObserver = Mockito.mock(StreamObserver.class); - BiStreamMethodHandler handler = new BiStreamMethodHandler<>( - o -> responseObserver); - CompletableFuture> future = handler.invoke( - new Object[]{responseObserver}); + BiStreamMethodHandler handler = new BiStreamMethodHandler<>(o -> responseObserver); + CompletableFuture> future = handler.invoke(new Object[] {responseObserver}); Assertions.assertEquals(responseObserver, future.get(1, TimeUnit.SECONDS)); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/FutureToObserverAdaptorTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/FutureToObserverAdaptorTest.java index 1cfe2784b3..14701b0a79 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/FutureToObserverAdaptorTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/FutureToObserverAdaptorTest.java @@ -14,17 +14,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.stub; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.fail; class FutureToObserverAdaptorTest { diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/ServerStreamMethodHandlerTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/ServerStreamMethodHandlerTest.java index c27a495c7c..c9f758b5ef 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/ServerStreamMethodHandlerTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/ServerStreamMethodHandlerTest.java @@ -14,19 +14,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.stub; import org.apache.dubbo.common.stream.StreamObserver; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; @@ -39,25 +38,20 @@ class ServerStreamMethodHandlerTest { AtomicInteger completeCounter = new AtomicInteger(); AtomicInteger errorCounter = new AtomicInteger(); StreamObserver responseObserver = Mockito.mock(StreamObserver.class); - doAnswer(o -> nextCounter.incrementAndGet()) - .when(responseObserver).onNext(anyString()); - doAnswer(o -> completeCounter.incrementAndGet()) - .when(responseObserver).onCompleted(); - doAnswer(o -> errorCounter.incrementAndGet()) - .when(responseObserver).onError(any(Throwable.class)); + doAnswer(o -> nextCounter.incrementAndGet()).when(responseObserver).onNext(anyString()); + doAnswer(o -> completeCounter.incrementAndGet()).when(responseObserver).onCompleted(); + doAnswer(o -> errorCounter.incrementAndGet()).when(responseObserver).onError(any(Throwable.class)); BiConsumer> consumer = (s, stringStreamObserver) -> { for (int i = 0; i < 10; i++) { stringStreamObserver.onNext(s + i); } stringStreamObserver.onCompleted(); }; - ServerStreamMethodHandler handler = new ServerStreamMethodHandler<>( - consumer); - CompletableFuture future = handler.invoke(new Object[]{"test", responseObserver}); + ServerStreamMethodHandler handler = new ServerStreamMethodHandler<>(consumer); + CompletableFuture future = handler.invoke(new Object[] {"test", responseObserver}); Assertions.assertTrue(future.isDone()); Assertions.assertEquals(10, nextCounter.get()); Assertions.assertEquals(0, errorCounter.get()); Assertions.assertEquals(1, completeCounter.get()); } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubInvokerTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubInvokerTest.java index 0a115eb445..c98428aaf7 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubInvokerTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubInvokerTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.stub; import org.apache.dubbo.common.URL; @@ -24,13 +23,13 @@ import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.support.DemoService; import org.apache.dubbo.rpc.support.DemoServiceImpl; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.Collections; import java.util.Map; import java.util.function.BiConsumer; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class StubInvokerTest { private final URL url = URL.valueOf("tri://0.0.0.0:50051/" + DemoService.class.getName()); @@ -39,10 +38,10 @@ class StubInvokerTest { o.onNext("hello," + a); o.onCompleted(); }; - private final Map> methodMap = Collections.singletonMap( - methodName, new UnaryStubMethodHandler<>(func)); - private final StubInvoker invoker = new StubInvoker<>(new DemoServiceImpl(), url, - DemoService.class, methodMap); + private final Map> methodMap = + Collections.singletonMap(methodName, new UnaryStubMethodHandler<>(func)); + private final StubInvoker invoker = + new StubInvoker<>(new DemoServiceImpl(), url, DemoService.class, methodMap); @Test void getUrl() { @@ -68,7 +67,7 @@ class StubInvokerTest { void invoke() { RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName(methodName); - invocation.setArguments(new Object[]{"test"}); + invocation.setArguments(new Object[] {"test"}); Result result = invoker.invoke(invocation); Object value = result.getValue(); Assertions.assertEquals("hello,test", value); diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubProxyFactoryTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubProxyFactoryTest.java index 899d939348..de8abf39e8 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubProxyFactoryTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubProxyFactoryTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.stub; import org.apache.dubbo.common.URL; @@ -33,24 +32,19 @@ class StubProxyFactoryTest { private final StubProxyFactory factory = new StubProxyFactory(); private final Invoker invoker2 = Mockito.mock(Invoker.class); - @Test void getProxy() { Invoker invoker = Mockito.mock(Invoker.class); URL url = Mockito.mock(URL.class); - when(invoker.getUrl()) - .thenReturn(url); + when(invoker.getUrl()).thenReturn(url); String service = "SERV_PROX"; - when(url.getServiceInterface()) - .thenReturn(service); + when(url.getServiceInterface()).thenReturn(service); StubSuppliers.addSupplier(service, i -> invoker); Assertions.assertEquals(invoker, factory.getProxy(invoker)); Assertions.assertEquals(invoker, factory.getProxy(invoker, false)); } - private interface MockInterface { - - } + private interface MockInterface {} private class MockStub implements ServerService, MockInterface { @@ -68,7 +62,6 @@ class StubProxyFactoryTest { @Test void getInvoker() { URL url = Mockito.mock(URL.class); - Assertions.assertEquals(invoker2, - factory.getInvoker(new MockStub(), MockInterface.class, url)); + Assertions.assertEquals(invoker2, factory.getInvoker(new MockStub(), MockInterface.class, url)); } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubSuppliersTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubSuppliersTest.java index 76347e9f6b..c6718e9ab7 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubSuppliersTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubSuppliersTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.stub; import org.apache.dubbo.rpc.Invoker; diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/DemoService.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/DemoService.java index 571b8a55c3..6fe533b28d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/DemoService.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/DemoService.java @@ -41,7 +41,7 @@ public interface DemoService { Type enumlength(Type... types); -// Type enumlength(Type type); + // Type enumlength(Type type); String get(CustomArgument arg1); @@ -62,5 +62,4 @@ public interface DemoService { CompletableFuture> testReturnType5(String str); void $invoke(String s1, String s2); - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/DemoServiceImpl.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/DemoServiceImpl.java index d1ed931da0..9ed2780d39 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/DemoServiceImpl.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/DemoServiceImpl.java @@ -26,7 +26,6 @@ import java.util.concurrent.CompletableFuture; /** * DemoServiceImpl */ - public class DemoServiceImpl implements DemoService { public DemoServiceImpl() { super(); @@ -49,25 +48,23 @@ public class DemoServiceImpl implements DemoService { } public int getSize(String[] strs) { - if (strs == null) - return -1; + if (strs == null) return -1; return strs.length; } public int getSize(Object[] os) { - if (os == null) - return -1; + if (os == null) return -1; return os.length; } public Object invoke(String service, String method) throws Exception { - System.out.println("RpcContext.getServerAttachment().getRemoteHost()=" + RpcContext.getServiceContext().getRemoteHost()); + System.out.println("RpcContext.getServerAttachment().getRemoteHost()=" + + RpcContext.getServiceContext().getRemoteHost()); return service + ":" + method; } public Type enumlength(Type... types) { - if (types.length == 0) - return Type.Lower; + if (types.length == 0) return Type.Lower; return types[0]; } @@ -122,7 +119,5 @@ public class DemoServiceImpl implements DemoService { } @Override - public void $invoke(String s1, String s2) { - - } + public void $invoke(String s1, String s2) {} } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/DemoServiceStub.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/DemoServiceStub.java index 2b13b36cb2..c03abd55f7 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/DemoServiceStub.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/DemoServiceStub.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.rpc.support; -public class DemoServiceStub extends DemoServiceImpl{ +public class DemoServiceStub extends DemoServiceImpl { private DemoService demoService; public DemoServiceStub(DemoService demoService) { diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/LocalException.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/LocalException.java index 89086b332d..bd43df71c8 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/LocalException.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/LocalException.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.support; public class LocalException extends RuntimeException { @@ -22,5 +21,4 @@ public class LocalException extends RuntimeException { public LocalException(String message) { super(message); } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java index ae8a69cc5d..ffcabd8d47 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.java @@ -68,11 +68,11 @@ public class MockInvocation extends RpcInvocation { } public Class[] getParameterTypes() { - return new Class[]{String.class}; + return new Class[] {String.class}; } public Object[] getArguments() { - return new Object[]{"aa"}; + return new Object[] {"aa"}; } public Map getAttachments() { @@ -119,9 +119,7 @@ public class MockInvocation extends RpcInvocation { } @Override - public void setServiceModel(ServiceModel serviceModel) { - - } + public void setServiceModel(ServiceModel serviceModel) {} @Override public ServiceModel getServiceModel() { @@ -164,5 +162,4 @@ public class MockInvocation extends RpcInvocation { } return result; } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java index f2dbe07081..670a3f7885 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.java @@ -86,5 +86,4 @@ public class MyInvoker implements Invoker { public String toString() { return "MyInvoker.toString()"; } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/PenetrateAttachmentSelectorMock.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/PenetrateAttachmentSelectorMock.java index 9f74ef1cf1..57f55b14d3 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/PenetrateAttachmentSelectorMock.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/PenetrateAttachmentSelectorMock.java @@ -26,15 +26,20 @@ import java.util.Map; public class PenetrateAttachmentSelectorMock implements PenetrateAttachmentSelector { @Override - public Map select(Invocation invocation, RpcContextAttachment clientAttachment, RpcContextAttachment serverAttachment) { + public Map select( + Invocation invocation, RpcContextAttachment clientAttachment, RpcContextAttachment serverAttachment) { Map objectAttachments = RpcContext.getServerAttachment().getObjectAttachments(); objectAttachments.put("testKey", "testVal"); return objectAttachments; } @Override - public Map selectReverse(Invocation invocation, RpcContextAttachment clientResponseContext, RpcContextAttachment serverResponseContext) { - Map objectAttachments = RpcContext.getServerResponseContext().getObjectAttachments(); + public Map selectReverse( + Invocation invocation, + RpcContextAttachment clientResponseContext, + RpcContextAttachment serverResponseContext) { + Map objectAttachments = + RpcContext.getServerResponseContext().getObjectAttachments(); objectAttachments.put("reverseKey", "reverseVal"); return objectAttachments; } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RpcUtilsTest.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RpcUtilsTest.java index 1c2f5df7be..c3b1fb143f 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RpcUtilsTest.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RpcUtilsTest.java @@ -24,17 +24,17 @@ import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleServiceRepository; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.CsvSource; - import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; import static org.apache.dubbo.rpc.Constants.AUTO_ATTACH_INVOCATIONID_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -50,14 +50,16 @@ class RpcUtilsTest { * regular scenario: async invocation in URL * verify: 1. whether invocationId is set correctly, 2. idempotent or not */ - Invoker createMockInvoker(URL url){ + Invoker createMockInvoker(URL url) { Invoker invoker = createMockInvoker(); given(invoker.getUrl()).willReturn(url); - return invoker; + return invoker; } - Invoker createMockInvoker(){ - return mock(Invoker.class); + + Invoker createMockInvoker() { + return mock(Invoker.class); } + @Test void testAttachInvocationIdIfAsync_normal() { URL url = URL.valueOf("dubbo://localhost/?test.async=true"); @@ -125,49 +127,55 @@ class RpcUtilsTest { void testGetReturnType() { Class demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); - Invoker invoker = createMockInvoker(URL.valueOf( - "test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService")); + Invoker invoker = createMockInvoker( + URL.valueOf( + "test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService")); // void sayHello(String name); - RpcInvocation inv = new RpcInvocation("sayHello", serviceName, "", new Class[] {String.class}, null, null, invoker, null); + RpcInvocation inv = new RpcInvocation( + "sayHello", serviceName, "", new Class[] {String.class}, null, null, invoker, null); Class returnType = RpcUtils.getReturnType(inv); Assertions.assertNull(returnType); - //String echo(String text); - RpcInvocation inv1 = new RpcInvocation("echo", serviceName, "", new Class[] {String.class}, null, null, invoker, null); + // String echo(String text); + RpcInvocation inv1 = + new RpcInvocation("echo", serviceName, "", new Class[] {String.class}, null, null, invoker, null); Class returnType1 = RpcUtils.getReturnType(inv1); Assertions.assertNotNull(returnType1); Assertions.assertEquals(String.class, returnType1); - //int getSize(String[] strs); - RpcInvocation inv2 = new RpcInvocation("getSize", serviceName, "", new Class[] {String[].class}, null, null, invoker, null); + // int getSize(String[] strs); + RpcInvocation inv2 = new RpcInvocation( + "getSize", serviceName, "", new Class[] {String[].class}, null, null, invoker, null); Class returnType2 = RpcUtils.getReturnType(inv2); Assertions.assertNotNull(returnType2); Assertions.assertEquals(int.class, returnType2); - //Person getPerson(Person person); - RpcInvocation inv3 = new RpcInvocation("getPerson", serviceName, "", new Class[] {Person.class}, null, null, invoker, null); + // Person getPerson(Person person); + RpcInvocation inv3 = new RpcInvocation( + "getPerson", serviceName, "", new Class[] {Person.class}, null, null, invoker, null); Class returnType3 = RpcUtils.getReturnType(inv3); Assertions.assertNotNull(returnType3); Assertions.assertEquals(Person.class, returnType3); - //List testReturnType1(String str); - RpcInvocation inv4 = - new RpcInvocation("testReturnType1", serviceName, "", new Class[] {String.class}, null, null, invoker, null); + // List testReturnType1(String str); + RpcInvocation inv4 = new RpcInvocation( + "testReturnType1", serviceName, "", new Class[] {String.class}, null, null, invoker, null); Class returnType4 = RpcUtils.getReturnType(inv4); Assertions.assertNotNull(returnType4); Assertions.assertEquals(List.class, returnType4); - } @Test void testGetReturnTypesUseCache() throws Exception { Class demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); - Invoker invoker = createMockInvoker(URL.valueOf( - "test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService")); + Invoker invoker = createMockInvoker( + URL.valueOf( + "test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService")); - RpcInvocation inv = new RpcInvocation("testReturnType", serviceName, "", new Class[] {String.class}, null, null, invoker, null); + RpcInvocation inv = new RpcInvocation( + "testReturnType", serviceName, "", new Class[] {String.class}, null, null, invoker, null); Type[] types = RpcUtils.getReturnTypes(inv); Assertions.assertNotNull(types); Assertions.assertEquals(2, types.length); @@ -175,17 +183,18 @@ class RpcUtilsTest { Assertions.assertEquals(String.class, types[1]); Assertions.assertArrayEquals(types, inv.getReturnTypes()); - RpcInvocation inv1 = - new RpcInvocation("testReturnType1", serviceName, "", new Class[] {String.class}, null, null, invoker, null); + RpcInvocation inv1 = new RpcInvocation( + "testReturnType1", serviceName, "", new Class[] {String.class}, null, null, invoker, null); java.lang.reflect.Type[] types1 = RpcUtils.getReturnTypes(inv1); Assertions.assertNotNull(types1); Assertions.assertEquals(2, types1.length); Assertions.assertEquals(List.class, types1[0]); - Assertions.assertEquals(demoServiceClass.getMethod("testReturnType1", String.class).getGenericReturnType(), types1[1]); + Assertions.assertEquals( + demoServiceClass.getMethod("testReturnType1", String.class).getGenericReturnType(), types1[1]); Assertions.assertArrayEquals(types1, inv1.getReturnTypes()); - RpcInvocation inv2 = - new RpcInvocation("testReturnType2", serviceName, "", new Class[] {String.class}, null, null, invoker, null); + RpcInvocation inv2 = new RpcInvocation( + "testReturnType2", serviceName, "", new Class[] {String.class}, null, null, invoker, null); java.lang.reflect.Type[] types2 = RpcUtils.getReturnTypes(inv2); Assertions.assertNotNull(types2); Assertions.assertEquals(2, types2.length); @@ -193,18 +202,19 @@ class RpcUtilsTest { Assertions.assertEquals(String.class, types2[1]); Assertions.assertArrayEquals(types2, inv2.getReturnTypes()); - RpcInvocation inv3 = - new RpcInvocation("testReturnType3", serviceName, "", new Class[] {String.class}, null, null, invoker, null); + RpcInvocation inv3 = new RpcInvocation( + "testReturnType3", serviceName, "", new Class[] {String.class}, null, null, invoker, null); java.lang.reflect.Type[] types3 = RpcUtils.getReturnTypes(inv3); Assertions.assertNotNull(types3); Assertions.assertEquals(2, types3.length); Assertions.assertEquals(List.class, types3[0]); - java.lang.reflect.Type genericReturnType3 = demoServiceClass.getMethod("testReturnType3", String.class).getGenericReturnType(); + java.lang.reflect.Type genericReturnType3 = + demoServiceClass.getMethod("testReturnType3", String.class).getGenericReturnType(); Assertions.assertEquals(((ParameterizedType) genericReturnType3).getActualTypeArguments()[0], types3[1]); Assertions.assertArrayEquals(types3, inv3.getReturnTypes()); - RpcInvocation inv4 = - new RpcInvocation("testReturnType4", serviceName, "", new Class[] {String.class}, null, null, invoker, null); + RpcInvocation inv4 = new RpcInvocation( + "testReturnType4", serviceName, "", new Class[] {String.class}, null, null, invoker, null); java.lang.reflect.Type[] types4 = RpcUtils.getReturnTypes(inv4); Assertions.assertNotNull(types4); Assertions.assertEquals(2, types4.length); @@ -212,13 +222,14 @@ class RpcUtilsTest { Assertions.assertNull(types4[1]); Assertions.assertArrayEquals(types4, inv4.getReturnTypes()); - RpcInvocation inv5 = - new RpcInvocation("testReturnType5", serviceName, "", new Class[] {String.class}, null, null, invoker, null); + RpcInvocation inv5 = new RpcInvocation( + "testReturnType5", serviceName, "", new Class[] {String.class}, null, null, invoker, null); java.lang.reflect.Type[] types5 = RpcUtils.getReturnTypes(inv5); Assertions.assertNotNull(types5); Assertions.assertEquals(2, types5.length); Assertions.assertEquals(Map.class, types5[0]); - java.lang.reflect.Type genericReturnType5 = demoServiceClass.getMethod("testReturnType5", String.class).getGenericReturnType(); + java.lang.reflect.Type genericReturnType5 = + demoServiceClass.getMethod("testReturnType5", String.class).getGenericReturnType(); Assertions.assertEquals(((ParameterizedType) genericReturnType5).getActualTypeArguments()[0], types5[1]); Assertions.assertArrayEquals(types5, inv5.getReturnTypes()); } @@ -227,10 +238,12 @@ class RpcUtilsTest { void testGetReturnTypesWithoutCache() throws Exception { Class demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); - Invoker invoker = createMockInvoker(URL.valueOf( - "test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService")); + Invoker invoker = createMockInvoker( + URL.valueOf( + "test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService")); - RpcInvocation inv = new RpcInvocation("testReturnType", serviceName, "", new Class[] {String.class}, null, null, invoker, null); + RpcInvocation inv = new RpcInvocation( + "testReturnType", serviceName, "", new Class[] {String.class}, null, null, invoker, null); inv.setReturnTypes(null); Type[] types = RpcUtils.getReturnTypes(inv); Assertions.assertNotNull(types); @@ -238,17 +251,18 @@ class RpcUtilsTest { Assertions.assertEquals(String.class, types[0]); Assertions.assertEquals(String.class, types[1]); - RpcInvocation inv1 = - new RpcInvocation("testReturnType1", serviceName, "", new Class[] {String.class}, null, null, invoker, null); + RpcInvocation inv1 = new RpcInvocation( + "testReturnType1", serviceName, "", new Class[] {String.class}, null, null, invoker, null); inv1.setReturnTypes(null); java.lang.reflect.Type[] types1 = RpcUtils.getReturnTypes(inv1); Assertions.assertNotNull(types1); Assertions.assertEquals(2, types1.length); Assertions.assertEquals(List.class, types1[0]); - Assertions.assertEquals(demoServiceClass.getMethod("testReturnType1", String.class).getGenericReturnType(), types1[1]); + Assertions.assertEquals( + demoServiceClass.getMethod("testReturnType1", String.class).getGenericReturnType(), types1[1]); - RpcInvocation inv2 = - new RpcInvocation("testReturnType2", serviceName, "", new Class[] {String.class}, null, null, invoker, null); + RpcInvocation inv2 = new RpcInvocation( + "testReturnType2", serviceName, "", new Class[] {String.class}, null, null, invoker, null); inv2.setReturnTypes(null); java.lang.reflect.Type[] types2 = RpcUtils.getReturnTypes(inv2); Assertions.assertNotNull(types2); @@ -256,18 +270,19 @@ class RpcUtilsTest { Assertions.assertEquals(String.class, types2[0]); Assertions.assertEquals(String.class, types2[1]); - RpcInvocation inv3 = - new RpcInvocation("testReturnType3", serviceName, "", new Class[] {String.class}, null, null, invoker, null); + RpcInvocation inv3 = new RpcInvocation( + "testReturnType3", serviceName, "", new Class[] {String.class}, null, null, invoker, null); inv3.setReturnTypes(null); java.lang.reflect.Type[] types3 = RpcUtils.getReturnTypes(inv3); Assertions.assertNotNull(types3); Assertions.assertEquals(2, types3.length); Assertions.assertEquals(List.class, types3[0]); - java.lang.reflect.Type genericReturnType3 = demoServiceClass.getMethod("testReturnType3", String.class).getGenericReturnType(); + java.lang.reflect.Type genericReturnType3 = + demoServiceClass.getMethod("testReturnType3", String.class).getGenericReturnType(); Assertions.assertEquals(((ParameterizedType) genericReturnType3).getActualTypeArguments()[0], types3[1]); - RpcInvocation inv4 = - new RpcInvocation("testReturnType4", serviceName, "", new Class[] {String.class}, null, null, invoker, null); + RpcInvocation inv4 = new RpcInvocation( + "testReturnType4", serviceName, "", new Class[] {String.class}, null, null, invoker, null); inv4.setReturnTypes(null); java.lang.reflect.Type[] types4 = RpcUtils.getReturnTypes(inv4); Assertions.assertNotNull(types4); @@ -275,101 +290,109 @@ class RpcUtilsTest { Assertions.assertNull(types4[0]); Assertions.assertNull(types4[1]); - RpcInvocation inv5 = - new RpcInvocation("testReturnType5", serviceName, "", new Class[] {String.class}, null, null, invoker, null); + RpcInvocation inv5 = new RpcInvocation( + "testReturnType5", serviceName, "", new Class[] {String.class}, null, null, invoker, null); inv5.setReturnTypes(null); java.lang.reflect.Type[] types5 = RpcUtils.getReturnTypes(inv5); Assertions.assertNotNull(types5); Assertions.assertEquals(2, types5.length); Assertions.assertEquals(Map.class, types5[0]); - java.lang.reflect.Type genericReturnType5 = demoServiceClass.getMethod("testReturnType5", String.class).getGenericReturnType(); + java.lang.reflect.Type genericReturnType5 = + demoServiceClass.getMethod("testReturnType5", String.class).getGenericReturnType(); Assertions.assertEquals(((ParameterizedType) genericReturnType5).getActualTypeArguments()[0], types5[1]); } - @Test void testGetReturnTypesWhenGeneric() throws Exception { Class demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); - Invoker invoker = createMockInvoker(URL.valueOf( - "test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService")); + Invoker invoker = createMockInvoker( + URL.valueOf( + "test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService")); - RpcInvocation inv = new RpcInvocation("testReturnType", serviceName, "", new Class[] {String.class}, null, null, invoker, null); + RpcInvocation inv = new RpcInvocation( + "testReturnType", serviceName, "", new Class[] {String.class}, null, null, invoker, null); inv.setMethodName($INVOKE); Type[] types = RpcUtils.getReturnTypes(inv); Assertions.assertNull(types); - RpcInvocation inv1 = - new RpcInvocation("testReturnType1", serviceName, "", new Class[] {String.class}, null, null, invoker, null); + RpcInvocation inv1 = new RpcInvocation( + "testReturnType1", serviceName, "", new Class[] {String.class}, null, null, invoker, null); inv1.setMethodName($INVOKE); java.lang.reflect.Type[] types1 = RpcUtils.getReturnTypes(inv1); Assertions.assertNull(types1); - RpcInvocation inv2 = - new RpcInvocation("testReturnType2", serviceName, "", new Class[] {String.class}, null, null, invoker, null); + RpcInvocation inv2 = new RpcInvocation( + "testReturnType2", serviceName, "", new Class[] {String.class}, null, null, invoker, null); inv2.setMethodName($INVOKE); java.lang.reflect.Type[] types2 = RpcUtils.getReturnTypes(inv2); Assertions.assertNull(types2); - RpcInvocation inv3 = - new RpcInvocation("testReturnType3", serviceName, "", new Class[] {String.class}, null, null, invoker, null); + RpcInvocation inv3 = new RpcInvocation( + "testReturnType3", serviceName, "", new Class[] {String.class}, null, null, invoker, null); inv3.setMethodName($INVOKE); java.lang.reflect.Type[] types3 = RpcUtils.getReturnTypes(inv3); Assertions.assertNull(types3); - RpcInvocation inv4 = - new RpcInvocation("testReturnType4", serviceName, "", new Class[] {String.class}, null, null, invoker, null); + RpcInvocation inv4 = new RpcInvocation( + "testReturnType4", serviceName, "", new Class[] {String.class}, null, null, invoker, null); inv4.setMethodName($INVOKE); java.lang.reflect.Type[] types4 = RpcUtils.getReturnTypes(inv4); Assertions.assertNull(types4); - RpcInvocation inv5 = - new RpcInvocation("testReturnType5", serviceName, "", new Class[] {String.class}, null, null, invoker, null); + RpcInvocation inv5 = new RpcInvocation( + "testReturnType5", serviceName, "", new Class[] {String.class}, null, null, invoker, null); inv5.setMethodName($INVOKE); java.lang.reflect.Type[] types5 = RpcUtils.getReturnTypes(inv5); Assertions.assertNull(types5); } + @Test void testGetParameterTypes() { Class demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); - Invoker invoker =createMockInvoker(); + Invoker invoker = createMockInvoker(); // void sayHello(String name); - RpcInvocation inv1 = new RpcInvocation("sayHello", serviceName, "", - new Class[] {String.class}, null, null, invoker, null); + RpcInvocation inv1 = new RpcInvocation( + "sayHello", serviceName, "", new Class[] {String.class}, null, null, invoker, null); Class[] parameterTypes1 = RpcUtils.getParameterTypes(inv1); Assertions.assertNotNull(parameterTypes1); Assertions.assertEquals(1, parameterTypes1.length); Assertions.assertEquals(String.class, parameterTypes1[0]); - //long timestamp(); + // long timestamp(); RpcInvocation inv2 = new RpcInvocation("timestamp", serviceName, "", null, null, null, invoker, null); Class[] parameterTypes2 = RpcUtils.getParameterTypes(inv2); Assertions.assertEquals(0, parameterTypes2.length); - //Type enumlength(Type... types); - RpcInvocation inv3 = new RpcInvocation("enumlength", serviceName, "", - new Class[] {Type.class, Type.class}, null, null, invoker, null); + // Type enumlength(Type... types); + RpcInvocation inv3 = new RpcInvocation( + "enumlength", serviceName, "", new Class[] {Type.class, Type.class}, null, null, invoker, null); Class[] parameterTypes3 = RpcUtils.getParameterTypes(inv3); Assertions.assertNotNull(parameterTypes3); Assertions.assertEquals(2, parameterTypes3.length); Assertions.assertEquals(Type.class, parameterTypes3[0]); Assertions.assertEquals(Type.class, parameterTypes3[1]); - //byte getbyte(byte arg); - RpcInvocation inv4 = new RpcInvocation("getbyte", serviceName, "", - new Class[] {byte.class}, null, null, invoker, null); + // byte getbyte(byte arg); + RpcInvocation inv4 = + new RpcInvocation("getbyte", serviceName, "", new Class[] {byte.class}, null, null, invoker, null); Class[] parameterTypes4 = RpcUtils.getParameterTypes(inv4); Assertions.assertNotNull(parameterTypes4); Assertions.assertEquals(1, parameterTypes4.length); Assertions.assertEquals(byte.class, parameterTypes4[0]); - //void $invoke(String s1, String s2); - RpcInvocation inv5 = new RpcInvocation("$invoke", serviceName, "", + // void $invoke(String s1, String s2); + RpcInvocation inv5 = new RpcInvocation( + "$invoke", + serviceName, + "", new Class[] {String.class, String[].class}, new Object[] {"method", new String[] {"java.lang.String", "void", "java.lang.Object"}}, - null, invoker, null); + null, + invoker, + null); Class[] parameterTypes5 = RpcUtils.getParameterTypes(inv5); Assertions.assertNotNull(parameterTypes5); Assertions.assertEquals(3, parameterTypes5.length); @@ -379,42 +402,38 @@ class RpcUtilsTest { } @ParameterizedTest - @CsvSource({ - "echo", - "stringLength", - "testReturnType" - }) + @CsvSource({"echo", "stringLength", "testReturnType"}) public void testGetMethodName(String methodName) { Class demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); - Invoker invoker =createMockInvoker(); + Invoker invoker = createMockInvoker(); - RpcInvocation inv1 = new RpcInvocation(methodName, serviceName, "", - new Class[] {String.class}, null, null, invoker, null); + RpcInvocation inv1 = new RpcInvocation( + methodName, serviceName, "", new Class[] {String.class}, null, null, invoker, null); String actual = RpcUtils.getMethodName(inv1); Assertions.assertNotNull(actual); Assertions.assertEquals(methodName, actual); } @ParameterizedTest - @CsvSource({ - "hello", - "apache", - "dubbo" - }) + @CsvSource({"hello", "apache", "dubbo"}) public void testGet_$invoke_MethodName(String method) { Class demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); - Invoker invoker =createMockInvoker(); + Invoker invoker = createMockInvoker(); - RpcInvocation inv = new RpcInvocation("$invoke", serviceName, "", + RpcInvocation inv = new RpcInvocation( + "$invoke", + serviceName, + "", new Class[] {String.class, String[].class}, new Object[] {method, new String[] {"java.lang.String", "void", "java.lang.Object"}}, - null, invoker, null); + null, + invoker, + null); String actual = RpcUtils.getMethodName(inv); Assertions.assertNotNull(actual); Assertions.assertEquals(method, actual); - } @Test @@ -422,17 +441,23 @@ class RpcUtilsTest { Object[] args = new Object[] {"hello", "dubbo", 520}; Class demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); - Invoker invoker =createMockInvoker(); + Invoker invoker = createMockInvoker(); - RpcInvocation inv = new RpcInvocation("$invoke", serviceName, "", + RpcInvocation inv = new RpcInvocation( + "$invoke", + serviceName, + "", new Class[] {String.class, String[].class, Object[].class}, new Object[] {"method", new String[] {}, args}, - null, invoker, null); + null, + invoker, + null); Object[] arguments = RpcUtils.getArguments(inv); for (int i = 0; i < args.length; i++) { Assertions.assertNotNull(arguments[i]); - Assertions.assertEquals(args[i].getClass().getName(), arguments[i].getClass().getName()); + Assertions.assertEquals( + args[i].getClass().getName(), arguments[i].getClass().getName()); Assertions.assertEquals(args[i], arguments[i]); } } @@ -442,15 +467,20 @@ class RpcUtilsTest { Object[] args = new Object[] {"hello", "dubbo", 520}; Class demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); - Invoker invoker =createMockInvoker(); + Invoker invoker = createMockInvoker(); URL url = URL.valueOf( "test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService"); - RpcInvocation inv = new RpcInvocation("test", serviceName, "", + RpcInvocation inv = new RpcInvocation( + "test", + serviceName, + "", new Class[] {String.class, String[].class, Object[].class}, new Object[] {"method", new String[] {}, args}, - null, invoker, null); + null, + invoker, + null); Assertions.assertFalse(RpcUtils.isAsync(url, inv)); inv.setInvokeMode(InvokeMode.ASYNC); @@ -459,9 +489,12 @@ class RpcUtilsTest { @Test void testIsGenericCall() { - Assertions.assertTrue(RpcUtils.isGenericCall("Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/Object;", "$invoke")); - Assertions.assertTrue(RpcUtils.isGenericCall("Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/Object;", "$invokeAsync")); - Assertions.assertFalse(RpcUtils.isGenericCall("Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/Object;", "testMethod")); + Assertions.assertTrue( + RpcUtils.isGenericCall("Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/Object;", "$invoke")); + Assertions.assertTrue( + RpcUtils.isGenericCall("Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/Object;", "$invokeAsync")); + Assertions.assertFalse( + RpcUtils.isGenericCall("Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/Object;", "testMethod")); } @Test @@ -470,21 +503,25 @@ class RpcUtilsTest { Assertions.assertFalse(RpcUtils.isEcho("Ljava/lang/Object;", "testMethod")); Assertions.assertFalse(RpcUtils.isEcho("Ljava/lang/String;", "$echo")); } + @Test void testIsReturnTypeFuture() { Class demoServiceClass = DemoService.class; String serviceName = demoServiceClass.getName(); - Invoker invoker = createMockInvoker(URL.valueOf( - "test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService")); + Invoker invoker = createMockInvoker( + URL.valueOf( + "test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService")); - RpcInvocation inv = new RpcInvocation("testReturnType", serviceName, "", new Class[] {String.class}, null, null, invoker, null); + RpcInvocation inv = new RpcInvocation( + "testReturnType", serviceName, "", new Class[] {String.class}, null, null, invoker, null); Assertions.assertFalse(RpcUtils.isReturnTypeFuture(inv)); - ModuleServiceRepository repository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); + ModuleServiceRepository repository = + ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); repository.registerService(demoServiceClass); - inv = new RpcInvocation("testReturnType4", serviceName, "", new Class[] {String.class}, null, null, invoker, null); + inv = new RpcInvocation( + "testReturnType4", serviceName, "", new Class[] {String.class}, null, null, invoker, null); Assertions.assertTrue(RpcUtils.isReturnTypeFuture(inv)); } - } diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RuntimeExceptionInvoker.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RuntimeExceptionInvoker.java index 63d497f9aa..46006ac1b7 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RuntimeExceptionInvoker.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RuntimeExceptionInvoker.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.support; import org.apache.dubbo.common.URL; diff --git a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/Type.java b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/Type.java index 22ded46777..b5368d2b38 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/Type.java +++ b/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/Type.java @@ -17,5 +17,7 @@ package org.apache.dubbo.rpc.support; public enum Type { - High, Normal, Lower + High, + Normal, + Lower } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/pom.xml b/dubbo-rpc/dubbo-rpc-dubbo/pom.xml index 5e8338eed6..8d450d04cc 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/pom.xml +++ b/dubbo-rpc/dubbo-rpc-dubbo/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-rpc - ${revision} - ../pom.xml - - dubbo-rpc-dubbo - jar - ${project.artifactId} - The default rpc module of dubbo project - - false - - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-cluster - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.parent.version} - test - - - io.netty - netty-all - test - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-serialization-jdk - ${project.parent.version} - test - + 4.0.0 + + org.apache.dubbo + dubbo-rpc + ${revision} + ../pom.xml + + dubbo-rpc-dubbo + jar + ${project.artifactId} + The default rpc module of dubbo project + + false + + + + org.apache.dubbo + dubbo-rpc-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-remoting-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-cluster + ${project.parent.version} + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.parent.version} + test + + + io.netty + netty-all + test + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-serialization-jdk + ${project.parent.version} + test + - - javax.validation - validation-api - test - - - org.hibernate - hibernate-validator - test - - - org.glassfish - javax.el - test - - - org.slf4j - slf4j-log4j12 - test - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - alphabetical - - - - + + javax.validation + validation-api + test + + + org.hibernate + hibernate-validator + test + + + org.glassfish + javax.el + test + + + org.slf4j + slf4j-log4j12 + test + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + alphabetical + + + + diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ByteAccessor.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ByteAccessor.java index 405edadaa0..1457243047 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ByteAccessor.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ByteAccessor.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.dubbo; import org.apache.dubbo.common.extension.SPI; diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java index 7c15e8a26e..6750751e6a 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java @@ -72,7 +72,8 @@ import static org.apache.dubbo.rpc.protocol.dubbo.Constants.IS_CALLBACK_SERVICE; * callback service helper */ public class CallbackServiceCodec { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CallbackServiceCodec.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(CallbackServiceCodec.class); private static final byte CALLBACK_NONE = 0x0; private static final byte CALLBACK_CREATE = 0x1; @@ -88,7 +89,8 @@ public class CallbackServiceCodec { this.frameworkModel = frameworkModel; proxyFactory = frameworkModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); protocolSPI = frameworkModel.getExtensionLoader(Protocol.class).getExtension(DUBBO_PROTOCOL); - dubboProtocol = (DubboProtocol) frameworkModel.getExtensionLoader(Protocol.class).getExtension(DubboProtocol.NAME, false); + dubboProtocol = (DubboProtocol) + frameworkModel.getExtensionLoader(Protocol.class).getExtension(DubboProtocol.NAME, false); } private static byte isCallBack(URL url, String protocolServiceKey, String methodName, int argIndex) { @@ -118,7 +120,8 @@ public class CallbackServiceCodec { * @throws IOException */ @SuppressWarnings({"unchecked", "rawtypes"}) - private String exportOrUnexportCallbackService(Channel channel, RpcInvocation inv, URL url, Class clazz, Object inst, Boolean export) throws IOException { + private String exportOrUnexportCallbackService( + Channel channel, RpcInvocation inv, URL url, Class clazz, Object inst, Boolean export) throws IOException { int instid = System.identityHashCode(inst); Map params = new HashMap<>(3); @@ -142,11 +145,15 @@ public class CallbackServiceCodec { } tmpMap.putAll(params); - tmpMap.remove(VERSION_KEY);// doesn't need to distinguish version for callback - tmpMap.remove(Constants.BIND_PORT_KEY); //callback doesn't needs bind.port + tmpMap.remove(VERSION_KEY); // doesn't need to distinguish version for callback + tmpMap.remove(Constants.BIND_PORT_KEY); // callback doesn't needs bind.port tmpMap.put(INTERFACE_KEY, clazz.getName()); - URL exportUrl = new ServiceConfigURL(DubboProtocol.NAME, channel.getLocalAddress().getAddress().getHostAddress(), - channel.getLocalAddress().getPort(), clazz.getName() + "." + instid, tmpMap); + URL exportUrl = new ServiceConfigURL( + DubboProtocol.NAME, + channel.getLocalAddress().getAddress().getHostAddress(), + channel.getLocalAddress().getPort(), + clazz.getName() + "." + instid, + tmpMap); // no need to generate multiple exporters for different channel in the same JVM, cache key cannot collide. String cacheKey = getClientSideCallbackServiceCacheKey(instid); @@ -157,18 +164,31 @@ public class CallbackServiceCodec { if (!isInstancesOverLimit(channel, url, clazz.getName(), instid, false)) { ModuleModel moduleModel; if (inv.getServiceModel() == null) { - //TODO should get scope model from url? + // TODO should get scope model from url? moduleModel = ApplicationModel.defaultModel().getDefaultModule(); - logger.error(PROTOCOL_FAILED_LOAD_MODEL, "", "", "Unable to get Service Model from Invocation. Please check if your invocation failed! " + - "This error only happen in UT cases! Invocation:" + inv); + logger.error( + PROTOCOL_FAILED_LOAD_MODEL, + "", + "", + "Unable to get Service Model from Invocation. Please check if your invocation failed! " + + "This error only happen in UT cases! Invocation:" + inv); } else { moduleModel = inv.getServiceModel().getModuleModel(); } - ServiceDescriptor serviceDescriptor = moduleModel.getServiceRepository().registerService(clazz); - ServiceMetadata serviceMetadata = new ServiceMetadata(clazz.getName() + "." + instid, exportUrl.getGroup(), exportUrl.getVersion(), clazz); - String serviceKey = BaseServiceMetadata.buildServiceKey(exportUrl.getPath(), group, exportUrl.getVersion()); - ProviderModel providerModel = new ProviderModel(serviceKey, inst, serviceDescriptor, moduleModel, serviceMetadata, ClassUtils.getClassLoader(clazz)); + ServiceDescriptor serviceDescriptor = + moduleModel.getServiceRepository().registerService(clazz); + ServiceMetadata serviceMetadata = new ServiceMetadata( + clazz.getName() + "." + instid, exportUrl.getGroup(), exportUrl.getVersion(), clazz); + String serviceKey = + BaseServiceMetadata.buildServiceKey(exportUrl.getPath(), group, exportUrl.getVersion()); + ProviderModel providerModel = new ProviderModel( + serviceKey, + inst, + serviceDescriptor, + moduleModel, + serviceMetadata, + ClassUtils.getClassLoader(clazz)); moduleModel.getServiceRepository().registerProvider(providerModel); exportUrl = exportUrl.setScopeModel(moduleModel); @@ -199,7 +219,8 @@ public class CallbackServiceCodec { * @param url */ @SuppressWarnings("unchecked") - private Object referOrDestroyCallbackService(Channel channel, URL url, Class clazz, Invocation inv, int instid, boolean isRefer) { + private Object referOrDestroyCallbackService( + Channel channel, URL url, Class clazz, Invocation inv, int instid, boolean isRefer) { Object proxy; String invokerCacheKey = getServerSideCallbackInvokerCacheKey(channel, clazz.getName(), instid); String proxyCacheKey = getServerSideCallbackServiceCacheKey(channel, clazz.getName(), instid); @@ -207,31 +228,38 @@ public class CallbackServiceCodec { String countkey = getServerSideCountKey(channel, clazz.getName()); if (isRefer) { if (proxy == null) { - URL referurl = URL.valueOf("callback://" + url.getAddress() + "/" + clazz.getName() + "?" + INTERFACE_KEY + "=" + clazz.getName()); - referurl = referurl.addParametersIfAbsent(url.getParameters()).removeParameter(METHODS_KEY).addParameter(SIDE_KEY, CONSUMER_SIDE); + URL referurl = URL.valueOf("callback://" + url.getAddress() + "/" + clazz.getName() + "?" + + INTERFACE_KEY + "=" + clazz.getName()); + referurl = referurl.addParametersIfAbsent(url.getParameters()) + .removeParameter(METHODS_KEY) + .addParameter(SIDE_KEY, CONSUMER_SIDE); if (!isInstancesOverLimit(channel, referurl, clazz.getName(), instid, true)) { - url.getOrDefaultApplicationModel().getDefaultModule().getServiceRepository().registerService(clazz); + url.getOrDefaultApplicationModel() + .getDefaultModule() + .getServiceRepository() + .registerService(clazz); @SuppressWarnings("rawtypes") Invoker invoker = new ChannelWrappedInvoker(clazz, channel, referurl, String.valueOf(instid)); FilterChainBuilder builder = getFilterChainBuilder(url); invoker = builder.buildInvokerChain(invoker, REFERENCE_FILTER_KEY, CommonConstants.CONSUMER); invoker = builder.buildInvokerChain(invoker, REFERENCE_FILTER_KEY, CommonConstants.CALLBACK); - + proxy = proxyFactory.getProxy(invoker); channel.setAttribute(proxyCacheKey, proxy); channel.setAttribute(invokerCacheKey, invoker); increaseInstanceCount(channel, countkey); - //convert error fail fast . - //ignore concurrent problem. + // convert error fail fast . + // ignore concurrent problem. Set> callbackInvokers = (Set>) channel.getAttribute(CHANNEL_CALLBACK_KEY); if (callbackInvokers == null) { callbackInvokers = new ConcurrentHashSet<>(1); channel.setAttribute(CHANNEL_CALLBACK_KEY, callbackInvokers); } callbackInvokers.add(invoker); - logger.info("method " + RpcUtils.getMethodName(inv) + " include a callback service :" + invoker.getUrl() + ", a proxy :" + invoker + " has been created."); + logger.info("method " + RpcUtils.getMethodName(inv) + " include a callback service :" + + invoker.getUrl() + ", a proxy :" + invoker + " has been created."); } } } else { @@ -256,7 +284,8 @@ public class CallbackServiceCodec { } private FilterChainBuilder getFilterChainBuilder(URL url) { - return ScopeModelUtil.getExtensionLoader(FilterChainBuilder.class, url.getScopeModel()).getDefaultExtension(); + return ScopeModelUtil.getExtensionLoader(FilterChainBuilder.class, url.getScopeModel()) + .getDefaultExtension(); } private static String getClientSideCallbackServiceCacheKey(int instid) { @@ -264,7 +293,8 @@ public class CallbackServiceCodec { } private static String getServerSideCallbackServiceCacheKey(Channel channel, String interfaceClass, int instid) { - return CALLBACK_SERVICE_PROXY_KEY + "." + System.identityHashCode(channel) + "." + interfaceClass + "." + instid; + return CALLBACK_SERVICE_PROXY_KEY + "." + System.identityHashCode(channel) + "." + interfaceClass + "." + + instid; } private static String getServerSideCallbackInvokerCacheKey(Channel channel, String interfaceClass, int instid) { @@ -279,13 +309,17 @@ public class CallbackServiceCodec { return CALLBACK_SERVICE_PROXY_KEY + "." + System.identityHashCode(channel) + "." + interfaceClass + ".COUNT"; } - private static boolean isInstancesOverLimit(Channel channel, URL url, String interfaceClass, int instid, boolean isServer) { - Integer count = (Integer) channel.getAttribute(isServer ? getServerSideCountKey(channel, interfaceClass) : getClientSideCountKey(interfaceClass)); + private static boolean isInstancesOverLimit( + Channel channel, URL url, String interfaceClass, int instid, boolean isServer) { + Integer count = (Integer) channel.getAttribute( + isServer ? getServerSideCountKey(channel, interfaceClass) : getClientSideCountKey(interfaceClass)); int limit = url.getParameter(CALLBACK_INSTANCES_LIMIT_KEY, DEFAULT_CALLBACK_INSTANCES); if (count != null && count >= limit) { - //client side error - throw new IllegalStateException("interface " + interfaceClass + " `s callback instances num exceed providers limit :" + limit - + " ,current num: " + (count + 1) + ". The new callback service will not work !!! you can cancle the callback service which exported before. channel :" + channel); + // client side error + throw new IllegalStateException("interface " + interfaceClass + + " `s callback instances num exceed providers limit :" + limit + " ,current num: " + (count + 1) + + ". The new callback service will not work !!! you can cancle the callback service which exported before. channel :" + + channel); } else { return false; } @@ -293,7 +327,7 @@ public class CallbackServiceCodec { private static void increaseInstanceCount(Channel channel, String countkey) { try { - //ignore concurrent problem? + // ignore concurrent problem? Integer count = (Integer) channel.getAttribute(countkey); if (count == null) { count = 1; @@ -328,18 +362,24 @@ public class CallbackServiceCodec { Class[] pts = inv.getParameterTypes(); switch (callbackStatus) { case CallbackServiceCodec.CALLBACK_CREATE: - inv.setAttachment(INV_ATT_CALLBACK_KEY + paraIndex, exportOrUnexportCallbackService(channel, inv, url, pts[paraIndex], args[paraIndex], true)); + inv.setAttachment( + INV_ATT_CALLBACK_KEY + paraIndex, + exportOrUnexportCallbackService(channel, inv, url, pts[paraIndex], args[paraIndex], true)); return null; case CallbackServiceCodec.CALLBACK_DESTROY: - inv.setAttachment(INV_ATT_CALLBACK_KEY + paraIndex, exportOrUnexportCallbackService(channel, inv, url, pts[paraIndex], args[paraIndex], false)); + inv.setAttachment( + INV_ATT_CALLBACK_KEY + paraIndex, + exportOrUnexportCallbackService(channel, inv, url, pts[paraIndex], args[paraIndex], false)); return null; default: return args[paraIndex]; } } - public Object decodeInvocationArgument(Channel channel, RpcInvocation inv, Class[] pts, int paraIndex, Object inObject) throws IOException { - // if it's a callback, create proxy on client side, callback interface on client side can be invoked through channel + public Object decodeInvocationArgument( + Channel channel, RpcInvocation inv, Class[] pts, int paraIndex, Object inObject) throws IOException { + // if it's a callback, create proxy on client side, callback interface on client side can be invoked through + // channel // need get URL from channel and env when decode URL url = null; try { @@ -354,14 +394,26 @@ public class CallbackServiceCodec { switch (callbackstatus) { case CallbackServiceCodec.CALLBACK_CREATE: try { - return referOrDestroyCallbackService(channel, url, pts[paraIndex], inv, Integer.parseInt(inv.getAttachment(INV_ATT_CALLBACK_KEY + paraIndex)), true); + return referOrDestroyCallbackService( + channel, + url, + pts[paraIndex], + inv, + Integer.parseInt(inv.getAttachment(INV_ATT_CALLBACK_KEY + paraIndex)), + true); } catch (Exception e) { logger.error(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", e.getMessage(), e); throw new IOException(StringUtils.toString(e)); } case CallbackServiceCodec.CALLBACK_DESTROY: try { - return referOrDestroyCallbackService(channel, url, pts[paraIndex], inv, Integer.parseInt(inv.getAttachment(INV_ATT_CALLBACK_KEY + paraIndex)), false); + return referOrDestroyCallbackService( + channel, + url, + pts[paraIndex], + inv, + Integer.parseInt(inv.getAttachment(INV_ATT_CALLBACK_KEY + paraIndex)), + false); } catch (Exception e) { throw new IOException(StringUtils.toString(e)); } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java index 71645f8dc6..7fda985f27 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java @@ -56,7 +56,7 @@ class ChannelWrappedInvoker extends AbstractInvoker { private final ExchangeClient currentClient; ChannelWrappedInvoker(Class serviceType, Channel channel, URL url, String serviceKey) { - super(serviceType, url, new String[]{GROUP_KEY, TOKEN_KEY}); + super(serviceType, url, new String[] {GROUP_KEY, TOKEN_KEY}); this.channel = channel; this.serviceKey = serviceKey; this.currentClient = new HeaderExchangeClient(new ChannelWrapper(this.channel), false); @@ -81,10 +81,12 @@ class ChannelWrappedInvoker extends AbstractInvoker { try { if (RpcUtils.isOneway(getUrl(), inv)) { // may have concurrency issue - currentClient.send(request, getUrl().getMethodParameter(RpcUtils.getMethodName(invocation), SENT_KEY, false)); + currentClient.send( + request, getUrl().getMethodParameter(RpcUtils.getMethodName(invocation), SENT_KEY, false)); return AsyncRpcResult.newDefaultAsyncResult(invocation); } else { - CompletableFuture appResponseFuture = currentClient.request(request).thenApply(AppResponse.class::cast); + CompletableFuture appResponseFuture = + currentClient.request(request).thenApply(AppResponse.class::cast); return new AsyncRpcResult(appResponseFuture, inv); } } catch (RpcException e) { @@ -100,12 +102,12 @@ class ChannelWrappedInvoker extends AbstractInvoker { @Override public void destroy() { -// super.destroy(); -// try { -// channel.close(); -// } catch (Throwable t) { -// logger.warn(t.getMessage(), t); -// } + // super.destroy(); + // try { + // channel.close(); + // } catch (Throwable t) { + // logger.warn(t.getMessage(), t); + // } } public static class ChannelWrapper extends ClientDelegate { @@ -179,9 +181,7 @@ class ChannelWrappedInvoker extends AbstractInvoker { } @Override - public void reconnect() throws RemotingException { - - } + public void reconnect() throws RemotingException {} @Override public void send(Object message) throws RemotingException { diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/Constants.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/Constants.java index fa0eca0281..d54b646add 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/Constants.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/Constants.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.dubbo; /** @@ -55,11 +54,9 @@ public interface Constants { boolean DEFAULT_LAZY_REQUEST_WITH_WARNING = false; - String ON_CONNECT_KEY = "onconnect"; String ON_DISCONNECT_KEY = "ondisconnect"; String ASYNC_METHOD_INFO = "async-method-info"; - } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java index 49cdac2313..7c197597ee 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java @@ -64,7 +64,8 @@ import static org.apache.dubbo.rpc.Constants.SERIALIZATION_SECURITY_CHECK_KEY; public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Decodeable { - protected static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(DecodeableRpcInvocation.class); + protected static final ErrorTypeAwareLogger log = + LoggerFactory.getErrorTypeAwareLogger(DecodeableRpcInvocation.class); protected final transient Channel channel; @@ -80,9 +81,11 @@ public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Dec protected final transient Supplier callbackServiceCodecFactory; - private static final boolean CHECK_SERIALIZATION = Boolean.parseBoolean(System.getProperty(SERIALIZATION_SECURITY_CHECK_KEY, "true")); + private static final boolean CHECK_SERIALIZATION = + Boolean.parseBoolean(System.getProperty(SERIALIZATION_SECURITY_CHECK_KEY, "true")); - public DecodeableRpcInvocation(FrameworkModel frameworkModel, Channel channel, Request request, InputStream is, byte id) { + public DecodeableRpcInvocation( + FrameworkModel frameworkModel, Channel channel, Request request, InputStream is, byte id) { this.frameworkModel = frameworkModel; Assert.notNull(channel, "channel == null"); Assert.notNull(request, "request == null"); @@ -91,8 +94,8 @@ public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Dec this.request = request; this.inputStream = is; this.serializationType = id; - this.callbackServiceCodecFactory = CacheableSupplier.newSupplier(() -> - new CallbackServiceCodec(frameworkModel)); + this.callbackServiceCodecFactory = + CacheableSupplier.newSupplier(() -> new CallbackServiceCodec(frameworkModel)); } @Override @@ -122,8 +125,7 @@ public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Dec int contentLength = input.available(); getAttributes().put(Constants.CONTENT_LENGTH_KEY, contentLength); - ObjectInput in = CodecSupport.getSerialization(serializationType) - .deserialize(channel.getUrl(), input); + ObjectInput in = CodecSupport.getSerialization(serializationType).deserialize(channel.getUrl(), input); this.put(SERIALIZATION_ID_KEY, serializationType); String dubboVersion = in.readUTF(); @@ -147,9 +149,11 @@ public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Dec ClassLoader originClassLoader = Thread.currentThread().getContextClassLoader(); try { if (CHECK_SERIALIZATION) { - PermittedSerializationKeeper keeper = frameworkModel.getBeanFactory().getBean(PermittedSerializationKeeper.class); + PermittedSerializationKeeper keeper = + frameworkModel.getBeanFactory().getBean(PermittedSerializationKeeper.class); if (!keeper.checkSerializationPermitted(keyWithoutGroup, serializationType)) { - throw new IOException("Unexpected serialization id:" + serializationType + " received from network, please check if the peer send the right id."); + throw new IOException("Unexpected serialization id:" + serializationType + + " received from network, please check if the peer send the right id."); } } Object[] args = DubboCodec.EMPTY_OBJECT_ARRAY; @@ -159,9 +163,9 @@ public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Dec if (pts == DubboCodec.EMPTY_CLASS_ARRAY) { if (RpcUtils.isGenericCall(desc, getMethodName())) { // Should recreate here for each invocation because the parameterTypes may be changed by user. - pts = new Class[]{String.class, String[].class, Object[].class}; + pts = new Class[] {String.class, String[].class, Object[].class}; } else if (RpcUtils.isEcho(desc, getMethodName())) { - pts = new Class[]{Object.class}; + pts = new Class[] {Object.class}; } else { throw new IllegalArgumentException("Service not found:" + path + ", " + getMethodName()); } @@ -187,7 +191,6 @@ public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Dec return this; } - protected void decodeArgument(Channel channel, Class[] pts, Object[] args) throws IOException { CallbackServiceCodec callbackServiceCodec = callbackServiceCodecFactory.get(); for (int i = 0; i < args.length; i++) { @@ -195,15 +198,15 @@ public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Dec } setArguments(args); - String targetServiceName = buildKey(getAttachment(PATH_KEY), - getAttachment(GROUP_KEY), - getAttachment(VERSION_KEY)); + String targetServiceName = + buildKey(getAttachment(PATH_KEY), getAttachment(GROUP_KEY), getAttachment(VERSION_KEY)); setTargetServiceUniqueName(targetServiceName); } protected Class[] drawPts(String path, String version, String desc, Class[] pts) { FrameworkServiceRepository repository = frameworkModel.getServiceRepository(); - List providerModels = repository.lookupExportedServicesWithoutGroup(keyWithoutGroup(path, version)); + List providerModels = + repository.lookupExportedServicesWithoutGroup(keyWithoutGroup(path, version)); ServiceDescriptor serviceDescriptor = null; if (CollectionUtils.isNotEmpty(providerModels)) { for (ProviderModel providerModel : providerModels) { @@ -234,7 +237,8 @@ public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Dec // switch TCCL if (CollectionUtils.isNotEmpty(providerModels)) { if (providerModels.size() == 1) { - Thread.currentThread().setContextClassLoader(providerModels.get(0).getClassLoader()); + Thread.currentThread() + .setContextClassLoader(providerModels.get(0).getClassLoader()); } else { // try all providerModels' classLoader can load pts, use the first one for (ProviderModel providerModel : providerModels) { @@ -272,17 +276,18 @@ public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Dec private void checkPayload(String serviceKey) throws IOException { ProviderModel providerModel = - frameworkModel.getServiceRepository().lookupExportedServiceWithoutGroup(serviceKey); + frameworkModel.getServiceRepository().lookupExportedServiceWithoutGroup(serviceKey); if (providerModel != null) { - String payloadStr = (String) providerModel.getServiceMetadata().getAttachments().get(PAYLOAD); + String payloadStr = + (String) providerModel.getServiceMetadata().getAttachments().get(PAYLOAD); if (payloadStr != null) { int payload = Integer.parseInt(payloadStr); if (payload <= 0) { return; } if (request.getPayload() > payload) { - ExceedPayloadLimitException e = new ExceedPayloadLimitException( - "Data length too large: " + request.getPayload() + ", max payload: " + payload + ", channel: " + channel); + ExceedPayloadLimitException e = new ExceedPayloadLimitException("Data length too large: " + + request.getPayload() + ", max payload: " + payload + ", channel: " + channel); log.error(TRANSPORT_EXCEED_PAYLOAD_LIMIT, "", "", e.getMessage(), e); throw e; } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java index ea6f94ed89..0469f9567a 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java @@ -88,10 +88,10 @@ public class DecodeableRpcResult extends AppResponse implements Codec, Decodeabl // switch TCCL if (invocation != null && invocation.getServiceModel() != null) { - Thread.currentThread().setContextClassLoader(invocation.getServiceModel().getClassLoader()); + Thread.currentThread() + .setContextClassLoader(invocation.getServiceModel().getClassLoader()); } - ObjectInput in = CodecSupport.getSerialization(serializationType) - .deserialize(channel.getUrl(), input); + ObjectInput in = CodecSupport.getSerialization(serializationType).deserialize(channel.getUrl(), input); byte flag = in.readByte(); switch (flag) { @@ -130,17 +130,21 @@ public class DecodeableRpcResult extends AppResponse implements Codec, Decodeabl if (invocation != null) { Configuration systemConfiguration = null; try { - systemConfiguration = ConfigurationUtils.getSystemConfiguration(channel.getUrl().getScopeModel()); + systemConfiguration = ConfigurationUtils.getSystemConfiguration( + channel.getUrl().getScopeModel()); } catch (Exception e) { - // Because the Environment may be destroyed during the offline process, the configuration cannot be obtained. + // Because the Environment may be destroyed during the offline process, the configuration cannot + // be obtained. // Exceptions are ignored here, and normal decoding is guaranteed. } - if (systemConfiguration == null || systemConfiguration.getBoolean(SERIALIZATION_SECURITY_CHECK_KEY, true)) { + if (systemConfiguration == null + || systemConfiguration.getBoolean(SERIALIZATION_SECURITY_CHECK_KEY, true)) { Object serializationTypeObj = invocation.get(SERIALIZATION_ID_KEY); if (serializationTypeObj != null) { if ((byte) serializationTypeObj != serializationType) { - throw new IOException("Unexpected serialization id:" + serializationType + " received from network, please check if the peer send the right id."); + throw new IOException("Unexpected serialization id:" + serializationType + + " received from network, please check if the peer send the right id."); } } } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java index c775ae50a0..bb446fcb15 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java @@ -81,9 +81,10 @@ public class DubboCodec extends ExchangeCodec { this.frameworkModel = frameworkModel; callbackServiceCodec = new CallbackServiceCodec(frameworkModel); customByteAccessor = Optional.ofNullable(System.getProperty(BYTE_ACCESSOR_KEY)) - .filter(StringUtils::isNotBlank) - .map(key -> frameworkModel.getExtensionLoader(ByteAccessor.class).getExtension(key)) - .orElse(null); + .filter(StringUtils::isNotBlank) + .map(key -> + frameworkModel.getExtensionLoader(ByteAccessor.class).getExtension(key)) + .orElse(null); } @Override @@ -109,7 +110,8 @@ public class DubboCodec extends ExchangeCodec { // heart beat response data is always null; data = null; } else { - ObjectInput in = CodecSupport.deserialize(channel.getUrl(), new ByteArrayInputStream(eventPayload), proto); + ObjectInput in = CodecSupport.deserialize( + channel.getUrl(), new ByteArrayInputStream(eventPayload), proto); data = decodeEventData(channel, in, eventPayload); } } else { @@ -117,26 +119,21 @@ public class DubboCodec extends ExchangeCodec { Invocation inv = (Invocation) getRequestData(channel, res, id); if (channel.getUrl().getParameter(DECODE_IN_IO_THREAD_KEY, DEFAULT_DECODE_IN_IO_THREAD)) { if (customByteAccessor != null) { - result = customByteAccessor.getRpcResult(channel, res, - new UnsafeByteArrayInputStream(readMessageData(is)), - inv, proto); + result = customByteAccessor.getRpcResult( + channel, res, new UnsafeByteArrayInputStream(readMessageData(is)), inv, proto); } else { - result = new DecodeableRpcResult(channel, res, - new UnsafeByteArrayInputStream(readMessageData(is)), - inv, proto); + result = new DecodeableRpcResult( + channel, res, new UnsafeByteArrayInputStream(readMessageData(is)), inv, proto); } result.decode(); } else { if (customByteAccessor != null) { - result = customByteAccessor.getRpcResult(channel, res, - new UnsafeByteArrayInputStream(readMessageData(is)), - inv, proto); + result = customByteAccessor.getRpcResult( + channel, res, new UnsafeByteArrayInputStream(readMessageData(is)), inv, proto); } else { - result = new DecodeableRpcResult(channel, res, - new UnsafeByteArrayInputStream(readMessageData(is)), - inv, proto); + result = new DecodeableRpcResult( + channel, res, new UnsafeByteArrayInputStream(readMessageData(is)), inv, proto); } - } data = result; } @@ -172,7 +169,8 @@ public class DubboCodec extends ExchangeCodec { req.setVersion(Version.getProtocolVersion()); req.setTwoWay((flag & FLAG_TWOWAY) != 0); - ObjectInput in = CodecSupport.deserialize(channel.getUrl(), new ByteArrayInputStream(eventPayload), proto); + ObjectInput in = CodecSupport.deserialize( + channel.getUrl(), new ByteArrayInputStream(eventPayload), proto); data = decodeEventData(channel, in, eventPayload); } req.setEvent(true); @@ -188,18 +186,28 @@ public class DubboCodec extends ExchangeCodec { DecodeableRpcInvocation inv; if (isDecodeDataInIoThread(channel)) { if (customByteAccessor != null) { - inv = customByteAccessor.getRpcInvocation(channel, req, new UnsafeByteArrayInputStream(readMessageData(is)), proto); + inv = customByteAccessor.getRpcInvocation( + channel, req, new UnsafeByteArrayInputStream(readMessageData(is)), proto); } else { - inv = new DecodeableRpcInvocation(frameworkModel, channel, req, new UnsafeByteArrayInputStream(readMessageData(is)), proto); + inv = new DecodeableRpcInvocation( + frameworkModel, + channel, + req, + new UnsafeByteArrayInputStream(readMessageData(is)), + proto); } inv.decode(); } else { if (customByteAccessor != null) { - inv = customByteAccessor.getRpcInvocation(channel, req, - new UnsafeByteArrayInputStream(readMessageData(is)), proto); + inv = customByteAccessor.getRpcInvocation( + channel, req, new UnsafeByteArrayInputStream(readMessageData(is)), proto); } else { - inv = new DecodeableRpcInvocation(frameworkModel, channel, req, - new UnsafeByteArrayInputStream(readMessageData(is)), proto); + inv = new DecodeableRpcInvocation( + frameworkModel, + channel, + req, + new UnsafeByteArrayInputStream(readMessageData(is)), + proto); } } data = inv; @@ -233,10 +241,11 @@ public class DubboCodec extends ExchangeCodec { return true; } - boolean decodeDataInIoThread = channel.getUrl().getParameter(DECODE_IN_IO_THREAD_KEY, DEFAULT_DECODE_IN_IO_THREAD); + boolean decodeDataInIoThread = + channel.getUrl().getParameter(DECODE_IN_IO_THREAD_KEY, DEFAULT_DECODE_IN_IO_THREAD); if (isIsolated && !decodeDataInIoThread) { - log.info("Because thread pool isolation is enabled on the dubbo protocol, the body can only be decoded " + - "on the io thread, and the parameter[" + DECODE_IN_IO_THREAD_KEY + "] will be ignored"); + log.info("Because thread pool isolation is enabled on the dubbo protocol, the body can only be decoded " + + "on the io thread, and the parameter[" + DECODE_IN_IO_THREAD_KEY + "] will be ignored"); // Why? because obtaining the isolated thread pool requires the serviceKey of the service, // and this part must be decoded before it can be obtained (more see DubboExecutorSupport) channel.setAttribute(DECODE_IN_IO_THREAD_KEY, true); @@ -252,7 +261,7 @@ public class DubboCodec extends ExchangeCodec { is.read(result); return result; } - return new byte[]{}; + return new byte[] {}; } @Override @@ -266,7 +275,8 @@ public class DubboCodec extends ExchangeCodec { } @Override - protected void encodeRequestData(Channel channel, ObjectOutput out, Object data, String version) throws IOException { + protected void encodeRequestData(Channel channel, ObjectOutput out, Object data, String version) + throws IOException { RpcInvocation inv = (RpcInvocation) data; out.writeUTF(version); @@ -290,7 +300,8 @@ public class DubboCodec extends ExchangeCodec { } @Override - protected void encodeResponseData(Channel channel, ObjectOutput out, Object data, String version) throws IOException { + protected void encodeResponseData(Channel channel, ObjectOutput out, Object data, String version) + throws IOException { Result result = (Result) data; // currently, the version value in Response records the version of Request boolean attach = Version.isSupportResponseAttachment(version); @@ -333,5 +344,4 @@ public class DubboCodec extends ExchangeCodec { } return DubboCodecSupport.getResponseSerialization(channel.getUrl(), (AppResponse) res.getResult()); } - } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodecSupport.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodecSupport.java index 97dccf5232..ed97a0d034 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodecSupport.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodecSupport.java @@ -33,7 +33,9 @@ public class DubboCodecSupport { if (serializationTypeObj != null) { return CodecSupport.getSerializationById((byte) serializationTypeObj); } - return url.getOrDefaultFrameworkModel().getExtensionLoader(Serialization.class).getExtension(UrlUtils.serializationOrDefault(url)); + return url.getOrDefaultFrameworkModel() + .getExtensionLoader(Serialization.class) + .getExtension(UrlUtils.serializationOrDefault(url)); } public static Serialization getResponseSerialization(URL url, AppResponse appResponse) { @@ -45,6 +47,8 @@ public class DubboCodecSupport { return CodecSupport.getSerializationById((byte) serializationTypeObj); } } - return url.getOrDefaultFrameworkModel().getExtensionLoader(Serialization.class).getExtension(UrlUtils.serializationOrDefault(url)); + return url.getOrDefaultFrameworkModel() + .getExtensionLoader(Serialization.class) + .getExtension(UrlUtils.serializationOrDefault(url)); } } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodec.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodec.java index b37ab75df0..8fa74a209f 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodec.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodec.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.dubbo; import org.apache.dubbo.remoting.Channel; @@ -94,5 +93,4 @@ public final class DubboCountCodec implements Codec2 { } } } - } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboExporter.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboExporter.java index 28099ea355..266cf3ef4e 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboExporter.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboExporter.java @@ -42,5 +42,4 @@ public class DubboExporter extends AbstractExporter { public void afterUnExport() { exporterMap.remove(key, this); } - } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboGracefulShutdown.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboGracefulShutdown.java index f1a324e01a..707f71e1fe 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboGracefulShutdown.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboGracefulShutdown.java @@ -34,7 +34,8 @@ import static org.apache.dubbo.common.constants.CommonConstants.WRITEABLE_EVENT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE_STREAM; public class DubboGracefulShutdown implements GracefulShutdown { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboGracefulShutdown.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(DubboGracefulShutdown.class); private final DubboProtocol dubboProtocol; public DubboGracefulShutdown(DubboProtocol dubboProtocol) { @@ -63,7 +64,9 @@ public class DubboGracefulShutdown implements GracefulShutdown { for (Channel channel : channels) { try { if (channel.isConnected()) { - channel.send(request, channel.getUrl().getParameter(Constants.CHANNEL_READONLYEVENT_SENT_KEY, true)); + channel.send( + request, + channel.getUrl().getParameter(Constants.CHANNEL_READONLYEVENT_SENT_KEY, true)); } } catch (RemotingException e) { if (e.getCause() instanceof ClosedChannelException) { diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java index 25657a26cb..2b2463defe 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java @@ -64,21 +64,21 @@ public class DubboInvoker extends AbstractInvoker { private final AtomicPositiveInteger index = new AtomicPositiveInteger(); - private final ReentrantLock destroyLock = new ReentrantLock(); private final Set> invokers; private final int serverShutdownTimeout; - private static final boolean setFutureWhenSync = Boolean.parseBoolean(System.getProperty(CommonConstants.SET_FUTURE_IN_SYNC_MODE, "true")); + private static final boolean setFutureWhenSync = + Boolean.parseBoolean(System.getProperty(CommonConstants.SET_FUTURE_IN_SYNC_MODE, "true")); public DubboInvoker(Class serviceType, URL url, ClientsProvider clientsProvider) { this(serviceType, url, clientsProvider, null); } public DubboInvoker(Class serviceType, URL url, ClientsProvider clientsProvider, Set> invokers) { - super(serviceType, url, new String[]{INTERFACE_KEY, GROUP_KEY, TOKEN_KEY}); + super(serviceType, url, new String[] {INTERFACE_KEY, GROUP_KEY, TOKEN_KEY}); this.clientsProvider = clientsProvider; this.invokers = invokers; this.serverShutdownTimeout = ConfigurationUtils.getServerShutdownTimeout(getUrl().getScopeModel()); @@ -103,9 +103,12 @@ public class DubboInvoker extends AbstractInvoker { int timeout = RpcUtils.calculateTimeout(getUrl(), invocation, methodName, DEFAULT_TIMEOUT); if (timeout <= 0) { - return AsyncRpcResult.newDefaultAsyncResult(new RpcException(RpcException.TIMEOUT_TERMINATE, - "No time left for making the following call: " + invocation.getServiceName() + "." - + RpcUtils.getMethodName(invocation) + ", terminate directly."), invocation); + return AsyncRpcResult.newDefaultAsyncResult( + new RpcException( + RpcException.TIMEOUT_TERMINATE, + "No time left for making the following call: " + invocation.getServiceName() + "." + + RpcUtils.getMethodName(invocation) + ", terminate directly."), + invocation); } invocation.setAttachment(TIMEOUT_KEY, String.valueOf(timeout)); @@ -128,7 +131,7 @@ public class DubboInvoker extends AbstractInvoker { request.setTwoWay(true); ExecutorService executor = getCallbackExecutor(getUrl(), inv); CompletableFuture appResponseFuture = - currentClient.request(request, timeout, executor).thenApply(AppResponse.class::cast); + currentClient.request(request, timeout, executor).thenApply(AppResponse.class::cast); // save for 2.6.x compatibility, for example, TraceFilter in Zipkin uses com.alibaba.xxx.FutureAdapter if (setFutureWhenSync || ((RpcInvocation) invocation).getInvokeMode() != InvokeMode.SYNC) { FutureContext.getContext().setCompatibleFuture(appResponseFuture); @@ -138,9 +141,14 @@ public class DubboInvoker extends AbstractInvoker { return result; } } catch (TimeoutException e) { - throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "Invoke remote method timeout. method: " + RpcUtils.getMethodName(invocation) + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); + throw new RpcException( + RpcException.TIMEOUT_EXCEPTION, + "Invoke remote method timeout. method: " + RpcUtils.getMethodName(invocation) + ", provider: " + + getUrl() + ", cause: " + e.getMessage(), + e); } catch (RemotingException e) { - String remoteExpMsg = "Failed to invoke remote method: " + RpcUtils.getMethodName(invocation) + ", provider: " + getUrl() + ", cause: " + e.getMessage(); + String remoteExpMsg = "Failed to invoke remote method: " + RpcUtils.getMethodName(invocation) + + ", provider: " + getUrl() + ", cause: " + e.getMessage(); if (e.getCause() instanceof IOException && e.getCause().getCause() instanceof SerializationException) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, remoteExpMsg, e); } else { @@ -156,7 +164,7 @@ public class DubboInvoker extends AbstractInvoker { } for (ExchangeClient client : clientsProvider.getClients()) { if (client.isConnected() && !client.hasAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY)) { - //cannot write == not Available ? + // cannot write == not Available ? return true; } } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboIsolationExecutorSupport.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboIsolationExecutorSupport.java index 231aa546ca..fd8aef43f7 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboIsolationExecutorSupport.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboIsolationExecutorSupport.java @@ -29,7 +29,8 @@ import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceModel; public class DubboIsolationExecutorSupport extends AbstractIsolationExecutorSupport { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboIsolationExecutorSupport.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(DubboIsolationExecutorSupport.class); private final FrameworkServiceRepository frameworkServiceRepository; private final DubboProtocol dubboProtocol; diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java index 958db3aad8..a8bd3c0c02 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java @@ -89,7 +89,6 @@ import static org.apache.dubbo.rpc.protocol.dubbo.Constants.ON_CONNECT_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.ON_DISCONNECT_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.SHARE_CONNECTIONS_KEY; - /** * dubbo protocol support. */ @@ -118,16 +117,23 @@ public class DubboProtocol extends AbstractProtocol { public CompletableFuture reply(ExchangeChannel channel, Object message) throws RemotingException { if (!(message instanceof Invocation)) { - throw new RemotingException(channel, "Unsupported request: " - + (message == null ? null : (message.getClass().getName() + ": " + message)) - + ", channel: consumer: " + channel.getRemoteAddress() + " --> provider: " + channel.getLocalAddress()); + throw new RemotingException( + channel, + "Unsupported request: " + + (message == null + ? null + : (message.getClass().getName() + ": " + message)) + + ", channel: consumer: " + channel.getRemoteAddress() + " --> provider: " + + channel.getLocalAddress()); } Invocation inv = (Invocation) message; Invoker invoker = inv.getInvoker() == null ? getInvoker(channel, inv) : inv.getInvoker(); // switch TCCL if (invoker.getUrl().getServiceModel() != null) { - Thread.currentThread().setContextClassLoader(invoker.getUrl().getServiceModel().getClassLoader()); + Thread.currentThread() + .setContextClassLoader( + invoker.getUrl().getServiceModel().getClassLoader()); } // need to consider backward-compatibility if it's a callback if (Boolean.TRUE.toString().equals(inv.getObjectAttachmentWithoutConvert(IS_CALLBACK_SERVICE_INVOKE))) { @@ -145,10 +151,15 @@ public class DubboProtocol extends AbstractProtocol { } } if (!hasMethod) { - logger.warn(PROTOCOL_FAILED_REFER_INVOKER, "", "", new IllegalStateException("The methodName " + inv.getMethodName() - + " not found in callback service interface ,invoke will be ignored." - + " please update the api interface. url is:" - + invoker.getUrl()) + " ,invocation is :" + inv); + logger.warn( + PROTOCOL_FAILED_REFER_INVOKER, + "", + "", + new IllegalStateException("The methodName " + inv.getMethodName() + + " not found in callback service interface ,invoke will be ignored." + + " please update the api interface. url is:" + + invoker.getUrl()) + + " ,invocation is :" + inv); return null; } } @@ -189,7 +200,13 @@ public class DubboProtocol extends AbstractProtocol { } received(channel, invocation); } catch (Throwable t) { - logger.warn(PROTOCOL_FAILED_REFER_INVOKER, "", "", "Failed to invoke event method " + invocation.getMethodName() + "(), cause: " + t.getMessage(), t); + logger.warn( + PROTOCOL_FAILED_REFER_INVOKER, + "", + "", + "Failed to invoke event method " + invocation.getMethodName() + "(), cause: " + + t.getMessage(), + t); } } } @@ -199,12 +216,12 @@ public class DubboProtocol extends AbstractProtocol { Invoker invoker = getInvoker(channel, invocation); } catch (RemotingException e) { String serviceKey = serviceKey( - 0, - (String) invocation.getObjectAttachmentWithoutConvert(PATH_KEY), - (String) invocation.getObjectAttachmentWithoutConvert(VERSION_KEY), - (String) invocation.getObjectAttachmentWithoutConvert(GROUP_KEY) - ); - throw new RemotingException(channel, "The stub service[" + serviceKey + "] is not found, it may not be exported yet"); + 0, + (String) invocation.getObjectAttachmentWithoutConvert(PATH_KEY), + (String) invocation.getObjectAttachmentWithoutConvert(VERSION_KEY), + (String) invocation.getObjectAttachmentWithoutConvert(GROUP_KEY)); + throw new RemotingException( + channel, "The stub service[" + serviceKey + "] is not found, it may not be exported yet"); } } @@ -223,7 +240,13 @@ public class DubboProtocol extends AbstractProtocol { return null; } - RpcInvocation invocation = new RpcInvocation(url.getServiceModel(), method, url.getParameter(INTERFACE_KEY), "", new Class[0], new Object[0]); + RpcInvocation invocation = new RpcInvocation( + url.getServiceModel(), + method, + url.getParameter(INTERFACE_KEY), + "", + new Class[0], + new Object[0]); invocation.setAttachment(PATH_KEY, url.getPath()); invocation.setAttachment(GROUP_KEY, url.getGroup()); invocation.setAttachment(INTERFACE_KEY, url.getParameter(INTERFACE_KEY)); @@ -244,7 +267,9 @@ public class DubboProtocol extends AbstractProtocol { */ @Deprecated public static DubboProtocol getDubboProtocol() { - return (DubboProtocol) FrameworkModel.defaultModel().getExtensionLoader(Protocol.class).getExtension(DubboProtocol.NAME, false); + return (DubboProtocol) FrameworkModel.defaultModel() + .getExtensionLoader(Protocol.class) + .getExtension(DubboProtocol.NAME, false); } public static DubboProtocol getDubboProtocol(ScopeModel scopeModel) { @@ -254,9 +279,9 @@ public class DubboProtocol extends AbstractProtocol { private boolean isClientSide(Channel channel) { InetSocketAddress address = channel.getRemoteAddress(); URL url = channel.getUrl(); - return url.getPort() == address.getPort() && - NetUtils.filterLocalHost(channel.getUrl().getIp()) - .equals(NetUtils.filterLocalHost(address.getAddress().getHostAddress())); + return url.getPort() == address.getPort() + && NetUtils.filterLocalHost(channel.getUrl().getIp()) + .equals(NetUtils.filterLocalHost(address.getAddress().getHostAddress())); } Invoker getInvoker(Channel channel, Invocation inv) throws RemotingException { @@ -265,10 +290,11 @@ public class DubboProtocol extends AbstractProtocol { int port = channel.getLocalAddress().getPort(); String path = (String) inv.getObjectAttachmentWithoutConvert(PATH_KEY); - //if it's stub service on client side(after enable stubevent, usually is set up onconnect or ondisconnect method) + // if it's stub service on client side(after enable stubevent, usually is set up onconnect or ondisconnect + // method) isStubServiceInvoke = Boolean.TRUE.toString().equals(inv.getObjectAttachmentWithoutConvert(STUB_EVENT_KEY)); if (isStubServiceInvoke) { - //when a stub service export to local, it usually can't be exposed to port + // when a stub service export to local, it usually can't be exposed to port port = 0; } @@ -279,17 +305,17 @@ public class DubboProtocol extends AbstractProtocol { inv.setObjectAttachment(IS_CALLBACK_SERVICE_INVOKE, Boolean.TRUE.toString()); } - String serviceKey = serviceKey( - port, - path, - (String) inv.getObjectAttachmentWithoutConvert(VERSION_KEY), - (String) inv.getObjectAttachmentWithoutConvert(GROUP_KEY) - ); + String serviceKey = serviceKey(port, path, (String) inv.getObjectAttachmentWithoutConvert(VERSION_KEY), (String) + inv.getObjectAttachmentWithoutConvert(GROUP_KEY)); DubboExporter exporter = (DubboExporter) exporterMap.get(serviceKey); if (exporter == null) { - throw new RemotingException(channel, "Not found exported service: " + serviceKey + " in " + exporterMap.keySet() + ", may be version or group mismatch " + - ", channel: consumer: " + channel.getRemoteAddress() + " --> provider: " + channel.getLocalAddress() + ", message:" + getInvocationWithoutData(inv)); + throw new RemotingException( + channel, + "Not found exported service: " + serviceKey + " in " + exporterMap.keySet() + + ", may be version or group mismatch " + ", channel: consumer: " + + channel.getRemoteAddress() + " --> provider: " + channel.getLocalAddress() + ", message:" + + getInvocationWithoutData(inv)); } Invoker invoker = exporter.getInvoker(); @@ -315,17 +341,20 @@ public class DubboProtocol extends AbstractProtocol { String key = serviceKey(url); DubboExporter exporter = new DubboExporter(invoker, key, exporterMap); - //export a stub service for dispatching event + // export a stub service for dispatching event boolean isStubSupportEvent = url.getParameter(STUB_EVENT_KEY, DEFAULT_STUB_EVENT); boolean isCallbackService = url.getParameter(IS_CALLBACK_SERVICE, false); if (isStubSupportEvent && !isCallbackService) { String stubServiceMethods = url.getParameter(STUB_EVENT_METHODS_KEY); if (stubServiceMethods == null || stubServiceMethods.length() == 0) { if (logger.isWarnEnabled()) { - logger.warn(PROTOCOL_UNSUPPORTED, "", "", "consumer [" + url.getParameter(INTERFACE_KEY) + - "], has set stub proxy support event ,but no stub methods founded."); + logger.warn( + PROTOCOL_UNSUPPORTED, + "", + "", + "consumer [" + url.getParameter(INTERFACE_KEY) + + "], has set stub proxy support event ,but no stub methods founded."); } - } } @@ -367,15 +396,18 @@ public class DubboProtocol extends AbstractProtocol { private ProtocolServer createServer(URL url) { url = URLBuilder.from(url) - // send readonly event when server closes, it's enabled by default - .addParameterIfAbsent(CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString()) - // enable heartbeat by default - .addParameterIfAbsent(HEARTBEAT_KEY, String.valueOf(DEFAULT_HEARTBEAT)) - .addParameter(CODEC_KEY, DubboCodec.NAME) - .build(); + // send readonly event when server closes, it's enabled by default + .addParameterIfAbsent(CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString()) + // enable heartbeat by default + .addParameterIfAbsent(HEARTBEAT_KEY, String.valueOf(DEFAULT_HEARTBEAT)) + .addParameter(CODEC_KEY, DubboCodec.NAME) + .build(); String transporter = url.getParameter(SERVER_KEY, DEFAULT_REMOTING_SERVER); - if (StringUtils.isNotEmpty(transporter) && !url.getOrDefaultFrameworkModel().getExtensionLoader(Transporter.class).hasExtension(transporter)) { + if (StringUtils.isNotEmpty(transporter) + && !url.getOrDefaultFrameworkModel() + .getExtensionLoader(Transporter.class) + .hasExtension(transporter)) { throw new RpcException("Unsupported server type: " + transporter + ", url: " + url); } @@ -387,7 +419,10 @@ public class DubboProtocol extends AbstractProtocol { } transporter = url.getParameter(CLIENT_KEY); - if (StringUtils.isNotEmpty(transporter) && !url.getOrDefaultFrameworkModel().getExtensionLoader(Transporter.class).hasExtension(transporter)) { + if (StringUtils.isNotEmpty(transporter) + && !url.getOrDefaultFrameworkModel() + .getExtensionLoader(Transporter.class) + .hasExtension(transporter)) { throw new RpcException("Unsupported client type: " + transporter); } @@ -396,7 +431,6 @@ public class DubboProtocol extends AbstractProtocol { return protocolServer; } - @Override public Invoker refer(Class type, URL url) throws RpcException { checkDestroyed(); @@ -424,16 +458,16 @@ public class DubboProtocol extends AbstractProtocol { * The xml configuration should have a higher priority than properties. */ String shareConnectionsStr = StringUtils.isBlank(url.getParameter(SHARE_CONNECTIONS_KEY, (String) null)) - ? ConfigurationUtils.getProperty(url.getOrDefaultApplicationModel(), SHARE_CONNECTIONS_KEY, DEFAULT_SHARE_CONNECTIONS) - : url.getParameter(SHARE_CONNECTIONS_KEY, (String) null); + ? ConfigurationUtils.getProperty( + url.getOrDefaultApplicationModel(), SHARE_CONNECTIONS_KEY, DEFAULT_SHARE_CONNECTIONS) + : url.getParameter(SHARE_CONNECTIONS_KEY, (String) null); connections = Integer.parseInt(shareConnectionsStr); return getSharedClient(url, connections); } - List clients = IntStream.range(0, connections) - .mapToObj((i) -> initClient(url)) - .collect(Collectors.toList()); + List clients = + IntStream.range(0, connections).mapToObj((i) -> initClient(url)).collect(Collectors.toList()); return new ExclusiveClientsProvider(clients); } @@ -453,15 +487,18 @@ public class DubboProtocol extends AbstractProtocol { if (originValue != null && originValue.increaseCount()) { return originValue; } else { - return new SharedClientsProvider(this, originKey, buildReferenceCountExchangeClientList(url, expectedConnectNum)); + return new SharedClientsProvider( + this, originKey, buildReferenceCountExchangeClientList(url, expectedConnectNum)); } }); } protected void scheduleRemoveSharedClient(String key, SharedClientsProvider sharedClient) { - this.frameworkModel.getBeanFactory().getBean(FrameworkExecutorRepository.class) - .getSharedExecutor() - .submit(() -> referenceClientMap.remove(key, sharedClient)); + this.frameworkModel + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class) + .getSharedExecutor() + .submit(() -> referenceClientMap.remove(key, sharedClient)); } /** @@ -509,16 +546,30 @@ public class DubboProtocol extends AbstractProtocol { String str = url.getParameter(CLIENT_KEY, url.getParameter(SERVER_KEY, DEFAULT_REMOTING_CLIENT)); // BIO is not allowed since it has severe performance issue. - if (StringUtils.isNotEmpty(str) && !url.getOrDefaultFrameworkModel().getExtensionLoader(Transporter.class).hasExtension(str)) { - throw new RpcException("Unsupported client type: " + str + "," + - " supported client type is " + StringUtils.join(url.getOrDefaultFrameworkModel().getExtensionLoader(Transporter.class).getSupportedExtensions(), " ")); + if (StringUtils.isNotEmpty(str) + && !url.getOrDefaultFrameworkModel() + .getExtensionLoader(Transporter.class) + .hasExtension(str)) { + throw new RpcException("Unsupported client type: " + str + "," + " supported client type is " + + StringUtils.join( + url.getOrDefaultFrameworkModel() + .getExtensionLoader(Transporter.class) + .getSupportedExtensions(), + " ")); } try { ScopeModel scopeModel = url.getScopeModel(); int heartbeat = UrlUtils.getHeartbeat(url); // Replace InstanceAddressURL with ServiceConfigURL. - url = new ServiceConfigURL(DubboCodec.NAME, url.getUsername(), url.getPassword(), url.getHost(), url.getPort(), url.getPath(), url.getAllParameters()); + url = new ServiceConfigURL( + DubboCodec.NAME, + url.getUsername(), + url.getPassword(), + url.getHost(), + url.getPort(), + url.getPath(), + url.getAllParameters()); url = url.addParameter(CODEC_KEY, DubboCodec.NAME); // enable heartbeat by default url = url.addParameterIfAbsent(HEARTBEAT_KEY, Integer.toString(heartbeat)); @@ -526,8 +577,8 @@ public class DubboProtocol extends AbstractProtocol { // connection should be lazy return url.getParameter(LAZY_CONNECT_KEY, false) - ? new LazyConnectExchangeClient(url, requestHandler) - : Exchangers.connect(url, requestHandler); + ? new LazyConnectExchangeClient(url, requestHandler) + : Exchangers.connect(url, requestHandler); } catch (RemotingException e) { throw new RpcException("Fail to create remoting client for service(" + url + "): " + e.getMessage(), e); } @@ -559,7 +610,12 @@ public class DubboProtocol extends AbstractProtocol { server.close(ConfigurationUtils.reCalShutdownTime(getServerShutdownTimeout(protocolServer))); } catch (Throwable t) { - logger.warn(PROTOCOL_ERROR_CLOSE_SERVER, "", "", "Close dubbo server [" + server.getLocalAddress() + "] failed: " + t.getMessage(), t); + logger.warn( + PROTOCOL_ERROR_CLOSE_SERVER, + "", + "", + "Close dubbo server [" + server.getLocalAddress() + "] failed: " + t.getMessage(), + t); } } serverMap.clear(); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ExclusiveClientsProvider.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ExclusiveClientsProvider.java index b570421378..c00d271b15 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ExclusiveClientsProvider.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ExclusiveClientsProvider.java @@ -25,7 +25,8 @@ import java.util.List; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_CLIENT; public class ExclusiveClientsProvider implements ClientsProvider { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ExclusiveClientsProvider.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ExclusiveClientsProvider.class); private final List clients; public ExclusiveClientsProvider(List clients) { diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java index 7454df2b8f..e4cb6f639e 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java @@ -47,7 +47,8 @@ import static org.apache.dubbo.rpc.protocol.dubbo.Constants.LAZY_REQUEST_WITH_WA @SuppressWarnings("deprecation") final class LazyConnectExchangeClient implements ExchangeClient { - private final static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(LazyConnectExchangeClient.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(LazyConnectExchangeClient.class); private final boolean requestWithWarning; private final URL url; private final ExchangeHandler requestHandler; @@ -119,7 +120,8 @@ final class LazyConnectExchangeClient implements ExchangeClient { } @Override - public CompletableFuture request(Object request, int timeout, ExecutorService executor) throws RemotingException { + public CompletableFuture request(Object request, int timeout, ExecutorService executor) + throws RemotingException { warning(); checkClient(); return client.request(request, timeout, executor); @@ -131,7 +133,12 @@ final class LazyConnectExchangeClient implements ExchangeClient { private void warning() { if (requestWithWarning) { if (warningCount.get() % warningPeriod == 0) { - logger.warn(PROTOCOL_FAILED_REQUEST, "", "", url.getAddress() + " " + url.getServiceKey() + " safe guard client , should not be called ,must have a bug."); + logger.warn( + PROTOCOL_FAILED_REQUEST, + "", + "", + url.getAddress() + " " + url.getServiceKey() + + " safe guard client , should not be called ,must have a bug."); } warningCount.incrementAndGet(); } @@ -268,8 +275,8 @@ final class LazyConnectExchangeClient implements ExchangeClient { } if (!isConnected() && !needReconnect) { - throw new IllegalStateException("LazyConnectExchangeClient is not connected normally, " + - "and send.reconnect is configured as false, the request fails quickly" + url); + throw new IllegalStateException("LazyConnectExchangeClient is not connected normally, " + + "and send.reconnect is configured as false, the request fails quickly" + url); } } } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java index 22cc722cf0..f5acca0f21 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.dubbo; - import org.apache.dubbo.common.Parameters; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -40,7 +39,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAI @SuppressWarnings("deprecation") final class ReferenceCountExchangeClient implements ExchangeClient { - private final static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ReferenceCountExchangeClient.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ReferenceCountExchangeClient.class); private final URL url; private final AtomicInteger referenceCount = new AtomicInteger(0); private final AtomicInteger disconnectCount = new AtomicInteger(0); @@ -90,7 +90,8 @@ final class ReferenceCountExchangeClient implements ExchangeClient { } @Override - public CompletableFuture request(Object request, int timeout, ExecutorService executor) throws RemotingException { + public CompletableFuture request(Object request, int timeout, ExecutorService executor) + throws RemotingException { return client.request(request, timeout, executor); } @@ -185,7 +186,12 @@ final class ReferenceCountExchangeClient implements ExchangeClient { private void replaceWithLazyClient() { // start warning at second replaceWithLazyClient() if (disconnectCount.getAndIncrement() % warningPeriod == 1) { - logger.warn(PROTOCOL_FAILED_REQUEST, "", "", url.getAddress() + " " + url.getServiceKey() + " safe guard client , should not be called ,must have a bug."); + logger.warn( + PROTOCOL_FAILED_REQUEST, + "", + "", + url.getAddress() + " " + url.getServiceKey() + + " safe guard client , should not be called ,must have a bug."); } // the order of judgment in the if statement cannot be changed. @@ -218,4 +224,3 @@ final class ReferenceCountExchangeClient implements ExchangeClient { this.shutdownWaitTime = shutdownWaitTime; } } - diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/SharedClientsProvider.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/SharedClientsProvider.java index 83ca0cfce2..9f97a919ad 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/SharedClientsProvider.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/SharedClientsProvider.java @@ -27,12 +27,14 @@ import java.util.Objects; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_CLIENT; public class SharedClientsProvider implements ClientsProvider { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SharedClientsProvider.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(SharedClientsProvider.class); private final DubboProtocol dubboProtocol; private final String addressKey; private final List clients; - public SharedClientsProvider(DubboProtocol dubboProtocol, String addressKey, List clients) { + public SharedClientsProvider( + DubboProtocol dubboProtocol, String addressKey, List clients) { this.dubboProtocol = dubboProtocol; this.addressKey = addressKey; this.clients = clients; @@ -84,8 +86,9 @@ public class SharedClientsProvider implements ClientsProvider { // As long as one client is not available, you need to replace the unavailable client with the available one. return referenceCountExchangeClients.stream() - .noneMatch(referenceCountExchangeClient -> referenceCountExchangeClient == null - || referenceCountExchangeClient.getCount() <= 0 || referenceCountExchangeClient.isClosed()); + .noneMatch(referenceCountExchangeClient -> referenceCountExchangeClient == null + || referenceCountExchangeClient.getCount() <= 0 + || referenceCountExchangeClient.isClosed()); } /** @@ -98,8 +101,8 @@ public class SharedClientsProvider implements ClientsProvider { return; } referenceCountExchangeClients.stream() - .filter(Objects::nonNull) - .forEach(ReferenceCountExchangeClient::incrementAndGetCount); + .filter(Objects::nonNull) + .forEach(ReferenceCountExchangeClient::incrementAndGetCount); } /** @@ -129,5 +132,4 @@ public class SharedClientsProvider implements ClientsProvider { logger.warn(PROTOCOL_ERROR_CLOSE_CLIENT, "", "", t.getMessage(), t); } } - } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/pu/DubboDetector.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/pu/DubboDetector.java index d39c8e30d8..acda082428 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/pu/DubboDetector.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/pu/DubboDetector.java @@ -26,16 +26,15 @@ import java.nio.ByteBuffer; import static java.lang.Math.min; public class DubboDetector implements ProtocolDetector { - private final ChannelBuffer Preface = new ByteBufferBackedChannelBuffer( - ByteBuffer.wrap(new byte[]{(byte)0xda, (byte)0xbb}) - ); + private final ChannelBuffer Preface = + new ByteBufferBackedChannelBuffer(ByteBuffer.wrap(new byte[] {(byte) 0xda, (byte) 0xbb})); @Override public Result detect(ChannelBuffer in) { int prefaceLen = Preface.readableBytes(); int bytesRead = min(in.readableBytes(), prefaceLen); - if (bytesRead ==0 || !ChannelBuffers.prefixEquals(in, Preface, bytesRead)) { + if (bytesRead == 0 || !ChannelBuffers.prefixEquals(in, Preface, bytesRead)) { return Result.unrecognized(); } if (bytesRead == prefaceLen) { diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/pu/DubboWireProtocol.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/pu/DubboWireProtocol.java index ba83394002..96200b5f11 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/pu/DubboWireProtocol.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/pu/DubboWireProtocol.java @@ -31,7 +31,6 @@ public class DubboWireProtocol extends AbstractWireProtocol { super(new DubboDetector()); } - @Override public void configServerProtocolHandler(URL url, ChannelOperator operator) { List handlers = new ArrayList<>(); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/status/ServerStatusChecker.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/status/ServerStatusChecker.java index 451b682362..e096d7b1dc 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/status/ServerStatusChecker.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/status/ServerStatusChecker.java @@ -57,5 +57,4 @@ public class ServerStatusChecker implements StatusChecker { } return new Status(level, buf.toString()); } - } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/status/ThreadPoolStatusChecker.java b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/status/ThreadPoolStatusChecker.java index cccf18f733..878e3ef987 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/status/ThreadPoolStatusChecker.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/status/ThreadPoolStatusChecker.java @@ -41,7 +41,8 @@ public class ThreadPoolStatusChecker implements StatusChecker { @Override public Status check() { - DataStore dataStore = applicationModel.getExtensionLoader(DataStore.class).getDefaultExtension(); + DataStore dataStore = + applicationModel.getExtensionLoader(DataStore.class).getDefaultExtension(); Map executors = dataStore.get(CommonConstants.EXECUTOR_SERVICE_COMPONENT_KEY); StringBuilder msg = new StringBuilder(); @@ -62,12 +63,22 @@ public class ThreadPoolStatusChecker implements StatusChecker { if (msg.length() > 0) { msg.append(';'); } - msg.append("Pool status:").append(lvl).append(", max:").append(tp.getMaximumPoolSize()).append(", core:") - .append(tp.getCorePoolSize()).append(", largest:").append(tp.getLargestPoolSize()).append(", active:") - .append(tp.getActiveCount()).append(", task:").append(tp.getTaskCount()).append(", service port: ").append(port); + msg.append("Pool status:") + .append(lvl) + .append(", max:") + .append(tp.getMaximumPoolSize()) + .append(", core:") + .append(tp.getCorePoolSize()) + .append(", largest:") + .append(tp.getLargestPoolSize()) + .append(", active:") + .append(tp.getActiveCount()) + .append(", task:") + .append(tp.getTaskCount()) + .append(", service port: ") + .append(port); } } return msg.length() == 0 ? new Status(Status.Level.UNKNOWN) : new Status(level, msg.toString()); } - } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ArgumentCallbackTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ArgumentCallbackTest.java index 7d5123f4c7..c26d136ae1 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ArgumentCallbackTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ArgumentCallbackTest.java @@ -28,18 +28,18 @@ import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.model.ModuleServiceRepository; import org.apache.dubbo.rpc.protocol.dubbo.support.ProtocolUtils; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.CALLBACK_INSTANCES_LIMIT_KEY; class ArgumentCallbackTest { @@ -62,7 +62,8 @@ class ArgumentCallbackTest { // export one service first, to test connection sharing serviceURL = serviceURL.addParameter("connections", 1); URL hellourl = serviceURL.setPath(IHelloService.class.getName()); - ModuleServiceRepository serviceRepository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); + ModuleServiceRepository serviceRepository = + ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); serviceRepository.registerService(IDemoService.class); serviceRepository.registerService(IHelloService.class); hello_exporter = ProtocolUtils.export(new HelloServiceImpl(), IHelloService.class, hellourl); @@ -70,30 +71,39 @@ class ArgumentCallbackTest { } void referService() { - ApplicationModel.defaultModel().getDefaultModule().getServiceRepository().registerService(IDemoService.class); + ApplicationModel.defaultModel() + .getDefaultModule() + .getServiceRepository() + .registerService(IDemoService.class); demoProxy = (IDemoService) ProtocolUtils.refer(IDemoService.class, consumerUrl); } @BeforeEach - public void setUp() { - } + public void setUp() {} public void initOrResetUrl(int callbacks, int timeout) { int port = NetUtils.getAvailablePort(); - consumerUrl = serviceURL = URL.valueOf("dubbo://127.0.0.1:" + port + "/" + IDemoService.class.getName() + "?group=test" - + "&xxx.0.callback=true" - + "&xxx2.0.callback=true" - + "&unxxx2.0.callback=false" - + "&timeout=" + timeout - + "&retries=0" - + "&" + CALLBACK_INSTANCES_LIMIT_KEY + "=" + callbacks) - .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()) - .setServiceModel(new ConsumerModel(IDemoService.class.getName(), null, null, - ApplicationModel.defaultModel().getDefaultModule(), null, null, ClassUtils.getClassLoader(IDemoService.class))); + consumerUrl = serviceURL = URL.valueOf( + "dubbo://127.0.0.1:" + port + "/" + IDemoService.class.getName() + "?group=test" + + "&xxx.0.callback=true" + + "&xxx2.0.callback=true" + + "&unxxx2.0.callback=false" + + "&timeout=" + timeout + + "&retries=0" + + "&" + CALLBACK_INSTANCES_LIMIT_KEY + "=" + callbacks) + .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()) + .setServiceModel(new ConsumerModel( + IDemoService.class.getName(), + null, + null, + ApplicationModel.defaultModel().getDefaultModule(), + null, + null, + ClassUtils.getClassLoader(IDemoService.class))); // uncomment is unblock invoking -// serviceURL = serviceURL.addParameter("yyy."+Constants.ASYNC_KEY,String.valueOf(true)); -// consumerUrl = consumerUrl.addParameter("yyy."+Constants.ASYNC_KEY,String.valueOf(true)); + // serviceURL = serviceURL.addParameter("yyy."+Constants.ASYNC_KEY,String.valueOf(true)); + // consumerUrl = consumerUrl.addParameter("yyy."+Constants.ASYNC_KEY,String.valueOf(true)); } public void initOrResetService() { @@ -121,17 +131,20 @@ class ArgumentCallbackTest { final AtomicInteger count = new AtomicInteger(0); - demoProxy.xxx(new IDemoCallback() { - public String yyy(String msg) { - System.out.println("Received callback: " + msg); - count.incrementAndGet(); - return "ok"; - } - }, "other custom args", 10, 100); + demoProxy.xxx( + new IDemoCallback() { + public String yyy(String msg) { + System.out.println("Received callback: " + msg); + count.incrementAndGet(); + return "ok"; + } + }, + "other custom args", + 10, + 100); System.out.println("Async..."); assertCallbackCount(10, 100, count); destroyService(); - } @Test @@ -141,19 +154,21 @@ class ArgumentCallbackTest { initOrResetService(); final AtomicInteger count = new AtomicInteger(0); - demoProxy.xxx(new IDemoCallback() { - public String yyy(String msg) { - System.out.println("Received callback: " + msg); - count.incrementAndGet(); - return "ok"; - } - }, "other custom args", 10, 100); + demoProxy.xxx( + new IDemoCallback() { + public String yyy(String msg) { + System.out.println("Received callback: " + msg); + count.incrementAndGet(); + return "ok"; + } + }, + "other custom args", + 10, + 100); System.out.println("Async..."); -// Thread.sleep(10000000); + // Thread.sleep(10000000); assertCallbackCount(10, 100, count); destroyService(); - - } @Test @@ -213,21 +228,29 @@ class ArgumentCallbackTest { // it needs manually specified. initOrResetService(); final AtomicInteger count = new AtomicInteger(0); - demoProxy.xxx(new IDemoCallback() { - public String yyy(String msg) { - System.out.println("Received callback: " + msg); - count.incrementAndGet(); - return "ok"; - } - }, "other custom args", 10, 100); + demoProxy.xxx( + new IDemoCallback() { + public String yyy(String msg) { + System.out.println("Received callback: " + msg); + count.incrementAndGet(); + return "ok"; + } + }, + "other custom args", + 10, + 100); - demoProxy.xxx(new IDemoCallback() { - public String yyy(String msg) { - System.out.println("Received callback: " + msg); - count.incrementAndGet(); - return "ok"; - } - }, "other custom args", 10, 100); + demoProxy.xxx( + new IDemoCallback() { + public String yyy(String msg) { + System.out.println("Received callback: " + msg); + count.incrementAndGet(); + return "ok"; + } + }, + "other custom args", + 10, + 100); destroyService(); }); } @@ -241,21 +264,29 @@ class ArgumentCallbackTest { serviceURL = serviceURL.addParameter(CALLBACK_INSTANCES_LIMIT_KEY, 1 + ""); initOrResetService(); final AtomicInteger count = new AtomicInteger(0); - demoProxy.xxx(new IDemoCallback() { - public String yyy(String msg) { - System.out.println("Received callback: " + msg); - count.incrementAndGet(); - return "ok"; - } - }, "other custom args", 10, 100); + demoProxy.xxx( + new IDemoCallback() { + public String yyy(String msg) { + System.out.println("Received callback: " + msg); + count.incrementAndGet(); + return "ok"; + } + }, + "other custom args", + 10, + 100); - demoProxy.xxx(new IDemoCallback() { - public String yyy(String msg) { - System.out.println("Received callback: " + msg); - count.incrementAndGet(); - return "ok"; - } - }, "other custom args", 10, 100); + demoProxy.xxx( + new IDemoCallback() { + public String yyy(String msg) { + System.out.println("Received callback: " + msg); + count.incrementAndGet(); + return "ok"; + } + }, + "other custom args", + 10, + 100); destroyService(); }); } @@ -306,7 +337,6 @@ class ArgumentCallbackTest { public String sayHello() { return "hello"; } - } class DemoServiceImpl implements IDemoService { @@ -360,7 +390,8 @@ class ArgumentCallbackTest { List callbacksCopy = new ArrayList(callbacks); for (IDemoCallback callback : callbacksCopy) { try { - callback.yyy("this is callback msg,current time is :" + System.currentTimeMillis()); + callback.yyy("this is callback msg,current time is :" + + System.currentTimeMillis()); } catch (Exception e) { e.printStackTrace(); callbacks.remove(callback); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocationTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocationTest.java index f4a39cf5d0..3433c42134 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocationTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocationTest.java @@ -36,11 +36,11 @@ import org.apache.dubbo.rpc.protocol.PermittedSerializationKeeper; import org.apache.dubbo.rpc.protocol.dubbo.decode.MockChannel; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; +import java.io.IOException; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.io.IOException; - import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; @@ -55,7 +55,8 @@ class DecodeableRpcInvocationTest { void test() throws Exception { // Simulate the data called by the client(The called data is stored in invocation and written to the buffer) URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 9103, DemoService.class.getName(), VERSION_KEY, "1.0.0"); - RpcInvocation inv = new RpcInvocation(null, "sayHello", DemoService.class.getName(), "", new Class[]{String.class}, new String[]{"yug"}); + RpcInvocation inv = new RpcInvocation( + null, "sayHello", DemoService.class.getName(), "", new Class[] {String.class}, new String[] {"yug"}); inv.setObjectAttachment(PATH_KEY, url.getPath()); inv.setObjectAttachment(VERSION_KEY, url.getVersion()); inv.setObjectAttachment(DUBBO_VERSION_KEY, DUBBO_VERSION); @@ -68,27 +69,37 @@ class DecodeableRpcInvocationTest { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); - applicationModel.getDefaultModule().getServiceRepository().registerService(DemoService.class.getName(), DemoService.class); - frameworkModel.getBeanFactory().getBean(PermittedSerializationKeeper.class) - .registerService(url); + applicationModel + .getDefaultModule() + .getServiceRepository() + .registerService(DemoService.class.getName(), DemoService.class); + frameworkModel + .getBeanFactory() + .getBean(PermittedSerializationKeeper.class) + .registerService(url); // Simulate the server to decode Channel channel = new MockChannel(); Request request = new Request(1); ChannelBufferInputStream is = new ChannelBufferInputStream(buffer, buffer.readableBytes()); - DecodeableRpcInvocation decodeableRpcInvocation = new DecodeableRpcInvocation(frameworkModel, channel, request, is, proto); + DecodeableRpcInvocation decodeableRpcInvocation = + new DecodeableRpcInvocation(frameworkModel, channel, request, is, proto); decodeableRpcInvocation.decode(); - // Verify that the decodeableRpcInvocation data decoded by the server is consistent with the invocation data of the client + // Verify that the decodeableRpcInvocation data decoded by the server is consistent with the invocation data of + // the client Assertions.assertEquals(request.getVersion(), DUBBO_VERSION); Assertions.assertEquals(decodeableRpcInvocation.getObjectAttachment(DUBBO_VERSION_KEY), DUBBO_VERSION); - Assertions.assertEquals(decodeableRpcInvocation.getObjectAttachment(VERSION_KEY), inv.getObjectAttachment(VERSION_KEY)); - Assertions.assertEquals(decodeableRpcInvocation.getObjectAttachment(PATH_KEY), inv.getObjectAttachment(PATH_KEY)); + Assertions.assertEquals( + decodeableRpcInvocation.getObjectAttachment(VERSION_KEY), inv.getObjectAttachment(VERSION_KEY)); + Assertions.assertEquals( + decodeableRpcInvocation.getObjectAttachment(PATH_KEY), inv.getObjectAttachment(PATH_KEY)); Assertions.assertEquals(decodeableRpcInvocation.getMethodName(), inv.getMethodName()); Assertions.assertEquals(decodeableRpcInvocation.getParameterTypesDesc(), inv.getParameterTypesDesc()); Assertions.assertArrayEquals(decodeableRpcInvocation.getParameterTypes(), inv.getParameterTypes()); Assertions.assertArrayEquals(decodeableRpcInvocation.getArguments(), inv.getArguments()); - Assertions.assertTrue(CollectionUtils.mapEquals(decodeableRpcInvocation.getObjectAttachments(), inv.getObjectAttachments())); + Assertions.assertTrue( + CollectionUtils.mapEquals(decodeableRpcInvocation.getObjectAttachments(), inv.getObjectAttachments())); Assertions.assertEquals(decodeableRpcInvocation.getTargetServiceUniqueName(), inv.getTargetServiceUniqueName()); frameworkModel.destroy(); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResultTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResultTest.java index 89fa8c44db..3c289238ef 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResultTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResultTest.java @@ -43,14 +43,14 @@ import org.apache.dubbo.rpc.protocol.dubbo.decode.MockChannel; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoServiceImpl; +import java.io.IOException; +import java.io.InputStream; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.IOException; -import java.io.InputStream; - import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.Constants.SERIALIZATION_ID_KEY; @@ -76,12 +76,17 @@ class DecodeableRpcResultTest { @Test void test() throws Exception { - // Mock a rpcInvocation, this rpcInvocation is usually generated by the client request, and stored in Request#data + // Mock a rpcInvocation, this rpcInvocation is usually generated by the client request, and stored in + // Request#data Byte proto = CodecSupport.getIDByName(DefaultSerializationSelector.getDefaultRemotingSerialization()); URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 9103, DemoService.class.getName(), VERSION_KEY, "1.0.0"); ServiceDescriptor serviceDescriptor = repository.registerService(DemoService.class); - ProviderModel providerModel = new ProviderModel(url.getServiceKey(), new DemoServiceImpl(), serviceDescriptor, null, null); - RpcInvocation rpcInvocation = new RpcInvocation(providerModel, "echo", DemoService.class.getName(), "", new Class[]{String.class}, new String[]{"yug"}); + ProviderModel providerModel = + new ProviderModel(url.getServiceKey(), new DemoServiceImpl(), serviceDescriptor, null, null); + RpcInvocation rpcInvocation = new RpcInvocation( + providerModel, "echo", DemoService.class.getName(), "", new Class[] {String.class}, new String[] { + "yug" + }); rpcInvocation.put(SERIALIZATION_ID_KEY, proto); // Mock a response result returned from the server and write to the buffer @@ -98,9 +103,11 @@ class DecodeableRpcResultTest { decodeableRpcResult.decode(); // Verify RESPONSE_VALUE_WITH_ATTACHMENTS - // Verify that the decodeableRpcResult decoded by the client is consistent with the response returned by the server + // Verify that the decodeableRpcResult decoded by the client is consistent with the response returned by the + // server Assertions.assertEquals(decodeableRpcResult.getValue(), result.getValue()); - Assertions.assertTrue(CollectionUtils.mapEquals(decodeableRpcResult.getObjectAttachments(), result.getObjectAttachments())); + Assertions.assertTrue( + CollectionUtils.mapEquals(decodeableRpcResult.getObjectAttachments(), result.getObjectAttachments())); // Verify RESPONSE_WITH_EXCEPTION_WITH_ATTACHMENTS Response exResponse = new Response(2); @@ -111,9 +118,11 @@ class DecodeableRpcResultTest { is = new ChannelBufferInputStream(buffer, buffer.readableBytes()); decodeableRpcResult = new DecodeableRpcResult(channel, response, is, rpcInvocation, proto); decodeableRpcResult.decode(); - Assertions.assertEquals(((RpcException) decodeableRpcResult.getException()).getCode(), ((RpcException) exResult.getException()).getCode()); - Assertions.assertTrue(CollectionUtils.mapEquals(decodeableRpcResult.getObjectAttachments(), exResult.getObjectAttachments())); - + Assertions.assertEquals( + ((RpcException) decodeableRpcResult.getException()).getCode(), + ((RpcException) exResult.getException()).getCode()); + Assertions.assertTrue( + CollectionUtils.mapEquals(decodeableRpcResult.getObjectAttachments(), exResult.getObjectAttachments())); } private ChannelBuffer writeBuffer(URL url, Response response, Byte proto, boolean writeEx) throws IOException { @@ -136,6 +145,4 @@ class DecodeableRpcResultTest { outputStream.close(); return buffer; } - - } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodecTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodecTest.java index 59e1f4c5a2..0d4933339c 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodecTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodecTest.java @@ -30,13 +30,13 @@ import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.dubbo.decode.MockChannel; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.rpc.Constants.INPUT_KEY; import static org.apache.dubbo.rpc.Constants.OUTPUT_KEY; @@ -53,7 +53,8 @@ class DubboCountCodecTest { for (int i = 0; i < 10; i++) { Request request = new Request(i); futures.add(DefaultFuture.newFuture(channel, request, 1000, null)); - RpcInvocation rpcInvocation = new RpcInvocation(null, "echo", DemoService.class.getName(), "", new Class[]{String.class}, new String[]{"yug"}); + RpcInvocation rpcInvocation = new RpcInvocation( + null, "echo", DemoService.class.getName(), "", new Class[] {String.class}, new String[] {"yug"}); request.setData(rpcInvocation); dubboCountCodec.encode(channel, buffer, request); } @@ -87,5 +88,4 @@ class DubboCountCodecTest { futures.forEach(DefaultFuture::cancel); } - } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvailableTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvailableTest.java index 9766e3bba7..def9df1b6e 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvailableTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvailableTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.dubbo; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; @@ -28,6 +27,9 @@ import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.dubbo.support.ProtocolUtils; +import java.lang.reflect.Field; +import java.util.List; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -35,9 +37,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import java.lang.reflect.Field; -import java.util.List; - import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; /** @@ -45,11 +44,11 @@ import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KE */ class DubboInvokerAvailableTest { private static DubboProtocol protocol; - private static ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + private static ProxyFactory proxy = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); @BeforeAll - public static void setUpBeforeClass() { - } + public static void setUpBeforeClass() {} @BeforeEach public void setUp() throws Exception { @@ -94,7 +93,8 @@ class DubboInvokerAvailableTest { @Test void test_normal_channel_close_wait_gracefully() { int testPort = NetUtils.getAvailablePort(); - URL url = URL.valueOf("dubbo://127.0.0.1:" + testPort + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?scope=true&lazy=false"); + URL url = URL.valueOf("dubbo://127.0.0.1:" + testPort + + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?scope=true&lazy=false"); Exporter exporter = ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); Exporter exporter0 = ProtocolUtils.export(new DemoServiceImpl0(), IDemoService.class, url); @@ -118,7 +118,8 @@ class DubboInvokerAvailableTest { @Test void test_NoInvokers() throws Exception { int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?connections=1"); + URL url = URL.valueOf( + "dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?connections=1"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); DubboInvoker invoker = (DubboInvoker) protocol.protocolBindingRefer(IDemoService.class, url); @@ -126,13 +127,13 @@ class DubboInvokerAvailableTest { ExchangeClient[] clients = getClients(invoker); clients[0].close(); Assertions.assertFalse(invoker.isAvailable()); - } @Test void test_Lazy_ChannelReadOnly() throws Exception { int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?lazy=true&connections=1&timeout=10000"); + URL url = URL.valueOf("dubbo://127.0.0.1:" + port + + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?lazy=true&connections=1&timeout=10000"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); Invoker invoker = protocol.refer(IDemoService.class, url); @@ -141,7 +142,7 @@ class DubboInvokerAvailableTest { ExchangeClient exchangeClient = getClients((DubboInvoker) invoker)[0]; Assertions.assertFalse(exchangeClient.isClosed()); exchangeClient.setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); - //invoke method --> init client + // invoke method --> init client IDemoService service = (IDemoService) proxy.getProxy(invoker); Assertions.assertEquals("ok", service.get()); Assertions.assertFalse(invoker.isAvailable()); @@ -160,14 +161,16 @@ class DubboInvokerAvailableTest { @Test public void testPreferSerialization() throws Exception { int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?lazy=true&connections=1&timeout=10000&serialization=fastjson&prefer_serialization=fastjson2,hessian2"); + URL url = URL.valueOf( + "dubbo://127.0.0.1:" + port + + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?lazy=true&connections=1&timeout=10000&serialization=fastjson&prefer_serialization=fastjson2,hessian2"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); Invoker invoker = protocol.refer(IDemoService.class, url); Assertions.assertTrue(invoker.isAvailable()); ExchangeClient exchangeClient = getClients((DubboInvoker) invoker)[0]; Assertions.assertFalse(exchangeClient.isClosed()); - //invoke method --> init client + // invoke method --> init client IDemoService service = (IDemoService) proxy.getProxy(invoker); Assertions.assertEquals("ok", service.get()); } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboLazyConnectTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboLazyConnectTest.java index 6a0fed5d12..6cb0e99dca 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboLazyConnectTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboLazyConnectTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.dubbo; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.RpcException; @@ -36,12 +35,10 @@ import static org.apache.dubbo.common.constants.CommonConstants.LAZY_CONNECT_KEY class DubboLazyConnectTest { @BeforeAll - public static void setUpBeforeClass() { - } + public static void setUpBeforeClass() {} @BeforeEach - public void setUp() { - } + public void setUp() {} @AfterAll public static void tearDownAfterClass() { @@ -60,7 +57,8 @@ class DubboLazyConnectTest { @Test void testSticky2() { int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?" + LAZY_CONNECT_KEY + "=true"); + URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?" + + LAZY_CONNECT_KEY + "=true"); ProtocolUtils.refer(IDemoService.class, url); } @@ -68,7 +66,8 @@ class DubboLazyConnectTest { void testSticky3() { Assertions.assertThrows(IllegalStateException.class, () -> { int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?" + LAZY_CONNECT_KEY + "=true"); + URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?" + + LAZY_CONNECT_KEY + "=true"); IDemoService service = ProtocolUtils.refer(IDemoService.class, url); service.get(); }); @@ -77,7 +76,8 @@ class DubboLazyConnectTest { @Test void testSticky4() { int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?" + LAZY_CONNECT_KEY + "=true&timeout=20000"); + URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?" + + LAZY_CONNECT_KEY + "=true&timeout=20000"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocolTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocolTest.java index 580527240d..bfa8fabd15 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocolTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.dubbo; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; @@ -39,6 +38,12 @@ import org.apache.dubbo.rpc.protocol.dubbo.support.RemoteServiceImpl; import org.apache.dubbo.rpc.protocol.dubbo.support.Type; import org.apache.dubbo.rpc.service.EchoService; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -46,53 +51,64 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - import static org.junit.jupiter.api.Assertions.assertEquals; /** * ProxiesTest */ - class DubboProtocolTest { - private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + private Protocol protocol = + ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); + private ProxyFactory proxy = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); @AfterAll public static void after() { ProtocolUtils.closeAll(); - ApplicationModel.defaultModel().getDefaultModule().getServiceRepository().unregisterService(DemoService.class); + ApplicationModel.defaultModel() + .getDefaultModule() + .getServiceRepository() + .unregisterService(DemoService.class); } @BeforeAll public static void setup() { - ApplicationModel.defaultModel().getDefaultModule().getServiceRepository().registerService(DemoService.class); + ApplicationModel.defaultModel() + .getDefaultModule() + .getServiceRepository() + .registerService(DemoService.class); } @Test void testDemoProtocol() { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); - protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange"))); - service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange").addParameter("timeout", - 3000L))); - assertEquals(service.getSize(new String[]{"", "", ""}), 3); + protocol.export(proxy.getInvoker( + service, + DemoService.class, + URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange"))); + service = proxy.getProxy(protocol.refer( + DemoService.class, + URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange") + .addParameter("timeout", 3000L))); + assertEquals(service.getSize(new String[] {"", "", ""}), 3); } @Test void testDubboProtocol() throws Exception { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); - protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName()))); - service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName()).addParameter("timeout", - 3000L))); - assertEquals(service.enumlength(new Type[]{}), Type.Lower); + protocol.export(proxy.getInvoker( + service, + DemoService.class, + URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName()))); + service = proxy.getProxy(protocol.refer( + DemoService.class, + URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName()) + .addParameter("timeout", 3000L))); + assertEquals(service.enumlength(new Type[] {}), Type.Lower); assertEquals(service.getSize(null), -1); - assertEquals(service.getSize(new String[]{"", "", ""}), 3); + assertEquals(service.getSize(new String[] {"", "", ""}), 3); Map map = new HashMap(); map.put("aa", "bb"); Set set = service.keys(map); @@ -100,88 +116,100 @@ class DubboProtocolTest { assertEquals(set.iterator().next(), "aa"); service.invoke("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "", "invoke"); - service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?client=netty").addParameter("timeout", - 3000L))); + service = proxy.getProxy(protocol.refer( + DemoService.class, + URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?client=netty") + .addParameter("timeout", 3000L))); // test netty client StringBuffer buf = new StringBuffer(); - for (int i = 0; i < 1024 * 32 + 32; i++) - buf.append('A'); + for (int i = 0; i < 1024 * 32 + 32; i++) buf.append('A'); System.out.println(service.stringLength(buf.toString())); // cast to EchoService - EchoService echo = proxy.getProxy(protocol.refer(EchoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?client=netty").addParameter("timeout", - 3000L))); + EchoService echo = proxy.getProxy(protocol.refer( + EchoService.class, + URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?client=netty") + .addParameter("timeout", 3000L))); assertEquals(echo.$echo(buf.toString()), buf.toString()); assertEquals(echo.$echo("test"), "test"); assertEquals(echo.$echo("abcdefg"), "abcdefg"); assertEquals(echo.$echo(1234), 1234); } -// @Test -// public void testDubboProtocolWithMina() throws Exception { -// DemoService service = new DemoServiceImpl(); -// int port = NetUtils.getAvailablePort(); -// protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName()).addParameter(Constants.SERVER_KEY, "mina"))); -// service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName()).addParameter(Constants.CLIENT_KEY, "mina").addParameter("timeout", -// 3000L))); -// for (int i = 0; i < 10; i++) { -// assertEquals(service.enumlength(new Type[]{}), Type.Lower); -// assertEquals(service.getSize(null), -1); -// assertEquals(service.getSize(new String[]{"", "", ""}), 3); -// } -// Map map = new HashMap(); -// map.put("aa", "bb"); -// for (int i = 0; i < 10; i++) { -// Set set = service.keys(map); -// assertEquals(set.size(), 1); -// assertEquals(set.iterator().next(), "aa"); -// service.invoke("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "", "invoke"); -// } -// -// service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?client=mina").addParameter("timeout", -// 3000L))); -// // test netty client -// StringBuffer buf = new StringBuffer(); -// for (int i = 0; i < 1024 * 32 + 32; i++) -// buf.append('A'); -// System.out.println(service.stringLength(buf.toString())); -// -// // cast to EchoService -// EchoService echo = proxy.getProxy(protocol.refer(EchoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?client=mina").addParameter("timeout", -// 3000L))); -// for (int i = 0; i < 10; i++) { -// assertEquals(echo.$echo(buf.toString()), buf.toString()); -// assertEquals(echo.$echo("test"), "test"); -// assertEquals(echo.$echo("abcdefg"), "abcdefg"); -// assertEquals(echo.$echo(1234), 1234); -// } -// } + // @Test + // public void testDubboProtocolWithMina() throws Exception { + // DemoService service = new DemoServiceImpl(); + // int port = NetUtils.getAvailablePort(); + // protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + // + DemoService.class.getName()).addParameter(Constants.SERVER_KEY, "mina"))); + // service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + + // DemoService.class.getName()).addParameter(Constants.CLIENT_KEY, "mina").addParameter("timeout", + // 3000L))); + // for (int i = 0; i < 10; i++) { + // assertEquals(service.enumlength(new Type[]{}), Type.Lower); + // assertEquals(service.getSize(null), -1); + // assertEquals(service.getSize(new String[]{"", "", ""}), 3); + // } + // Map map = new HashMap(); + // map.put("aa", "bb"); + // for (int i = 0; i < 10; i++) { + // Set set = service.keys(map); + // assertEquals(set.size(), 1); + // assertEquals(set.iterator().next(), "aa"); + // service.invoke("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "", "invoke"); + // } + // + // service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + + // DemoService.class.getName() + "?client=mina").addParameter("timeout", + // 3000L))); + // // test netty client + // StringBuffer buf = new StringBuffer(); + // for (int i = 0; i < 1024 * 32 + 32; i++) + // buf.append('A'); + // System.out.println(service.stringLength(buf.toString())); + // + // // cast to EchoService + // EchoService echo = proxy.getProxy(protocol.refer(EchoService.class, URL.valueOf("dubbo://127.0.0.1:" + + // port + "/" + DemoService.class.getName() + "?client=mina").addParameter("timeout", + // 3000L))); + // for (int i = 0; i < 10; i++) { + // assertEquals(echo.$echo(buf.toString()), buf.toString()); + // assertEquals(echo.$echo("test"), "test"); + // assertEquals(echo.$echo("abcdefg"), "abcdefg"); + // assertEquals(echo.$echo(1234), 1234); + // } + // } @Test void testDubboProtocolMultiService() throws Exception { -// DemoService service = new DemoServiceImpl(); -// protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + DemoService.class.getName()))); -// service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + DemoService.class.getName()).addParameter("timeout", -// 3000L))); + // DemoService service = new DemoServiceImpl(); + // protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + + // DemoService.class.getName()))); + // service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + + // DemoService.class.getName()).addParameter("timeout", + // 3000L))); RemoteService remote = new RemoteServiceImpl(); - ApplicationModel.defaultModel().getDefaultModule().getServiceRepository().registerService(RemoteService.class); + ApplicationModel.defaultModel() + .getDefaultModule() + .getServiceRepository() + .registerService(RemoteService.class); int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/" + RemoteService.class.getName()).addParameter("timeout", - 3000L); + URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/" + RemoteService.class.getName()) + .addParameter("timeout", 3000L); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); protocol.export(proxy.getInvoker(remote, RemoteService.class, url)); remote = proxy.getProxy(protocol.refer(RemoteService.class, url)); -// service.sayHello("world"); + // service.sayHello("world"); // test netty client -// assertEquals("world", service.echo("world")); + // assertEquals("world", service.echo("world")); assertEquals("hello world@" + RemoteServiceImpl.class.getName(), remote.sayHello("world")); -// can't find target service addresses + // can't find target service addresses EchoService remoteEcho = (EchoService) remote; assertEquals(remoteEcho.$echo("ok"), "ok"); } @@ -190,12 +218,16 @@ class DubboProtocolTest { void testPerm() { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); - protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange"))); - service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange").addParameter("timeout", - 3000L))); + protocol.export(proxy.getInvoker( + service, + DemoService.class, + URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange"))); + service = proxy.getProxy(protocol.refer( + DemoService.class, + URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange") + .addParameter("timeout", 3000L))); long start = System.currentTimeMillis(); - for (int i = 0; i < 100; i++) - service.getSize(new String[]{"", "", ""}); + for (int i = 0; i < 100; i++) service.getSize(new String[] {"", "", ""}); System.out.println("take:" + (System.currentTimeMillis() - start)); } @@ -204,14 +236,22 @@ class DubboProtocolTest { public void testNonSerializedParameter() { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); - protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange"))); - service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange").addParameter("timeout", - 3000L))); + protocol.export(proxy.getInvoker( + service, + DemoService.class, + URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange"))); + service = proxy.getProxy(protocol.refer( + DemoService.class, + URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange") + .addParameter("timeout", 3000L))); try { service.nonSerializedParameter(new NonSerialized()); Assertions.fail(); } catch (RpcException e) { - Assertions.assertTrue(e.getMessage().contains("org.apache.dubbo.rpc.protocol.dubbo.support.NonSerialized must implement java.io.Serializable")); + Assertions.assertTrue( + e.getMessage() + .contains( + "org.apache.dubbo.rpc.protocol.dubbo.support.NonSerialized must implement java.io.Serializable")); } } @@ -220,28 +260,39 @@ class DubboProtocolTest { public void testReturnNonSerialized() { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); - protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange"))); - service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange").addParameter("timeout", - 3000L))); + protocol.export(proxy.getInvoker( + service, + DemoService.class, + URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange"))); + service = proxy.getProxy(protocol.refer( + DemoService.class, + URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange") + .addParameter("timeout", 3000L))); try { service.returnNonSerialized(); Assertions.fail(); } catch (RpcException e) { - Assertions.assertTrue(e.getMessage().contains("org.apache.dubbo.rpc.protocol.dubbo.support.NonSerialized must implement java.io.Serializable")); + Assertions.assertTrue( + e.getMessage() + .contains( + "org.apache.dubbo.rpc.protocol.dubbo.support.NonSerialized must implement java.io.Serializable")); } } + @Disabled @Test void testRemoteApplicationName() throws Exception { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange").addParameter("timeout", - 3000L).addParameter("application", "consumer"); + URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange") + .addParameter("timeout", 3000L) + .addParameter("application", "consumer"); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); protocol.export(proxy.getInvoker(service, DemoService.class, url)); Invoker invoker = protocol.refer(DemoService.class, url); - Invocation invocation = new RpcInvocation("getRemoteApplicationName", DemoService.class.getName(), "", new Class[0], new Object[0]); + Invocation invocation = new RpcInvocation( + "getRemoteApplicationName", DemoService.class.getName(), "", new Class[0], new Object[0]); List> invokers = Arrays.asList(invoker); Directory dic = Mockito.mock(Directory.class); Mockito.when(dic.list(invocation)).thenReturn(invokers); @@ -259,17 +310,21 @@ class DubboProtocolTest { void testPayloadOverException() { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); - protocol.export(proxy.getInvoker(service, DemoService.class, - URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName()).addParameter("payload", 10 * 1024))); - service = proxy.getProxy(protocol.refer(DemoService.class, - URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName()).addParameter("timeout", - 6000L).addParameter("payload", 160))); + protocol.export(proxy.getInvoker( + service, + DemoService.class, + URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName()) + .addParameter("payload", 10 * 1024))); + service = proxy.getProxy(protocol.refer( + DemoService.class, + URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName()) + .addParameter("timeout", 6000L) + .addParameter("payload", 160))); try { service.download(300); Assertions.fail(); } catch (Exception expected) { Assertions.assertTrue(expected.getMessage().contains("Data length too large")); } - } } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ImplicitCallBackTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ImplicitCallBackTest.java deleted file mode 100644 index 89f90fc472..0000000000 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ImplicitCallBackTest.java +++ /dev/null @@ -1,406 +0,0 @@ -///* -// * Licensed to the Apache Software Foundation (ASF) under one or more -// * contributor license agreements. See the NOTICE file distributed with -// * this work for additional information regarding copyright ownership. -// * The ASF licenses this file to You 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 org.apache.dubbo.rpc.protocol.dubbo; -// -// -//import org.apache.dubbo.common.URL; -//import org.apache.dubbo.common.utils.NetUtils; -//import org.apache.dubbo.rpc.Exporter; -//import org.apache.dubbo.rpc.Invoker; -//import org.apache.dubbo.rpc.RpcContext; -//import org.apache.dubbo.rpc.model.ApplicationModel; -//import org.apache.dubbo.rpc.model.ConsumerMethodModel; -//import org.apache.dubbo.rpc.model.ConsumerModel; -//import org.apache.dubbo.rpc.model.ServiceMetadata; -//import org.apache.dubbo.rpc.protocol.dubbo.support.ProtocolUtils; -// -//import org.junit.jupiter.api.AfterEach; -//import org.junit.jupiter.api.Assertions; -//import org.junit.jupiter.api.BeforeEach; -//import org.junit.jupiter.api.Test; -// -//import java.io.Serializable; -//import java.lang.reflect.Method; -//import java.util.ArrayList; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -//import java.util.concurrent.ExecutionException; -//import java.util.concurrent.Future; -//import java.util.concurrent.TimeUnit; -// -//import static org.apache.dubbo.rpc.Constants.ASYNC_KEY; -// -//public class ImplicitCallBackTest { -// -// protected Exporter exporter = null; -// protected Invoker reference = null; -// -// protected URL serviceURL = null; -// protected URL consumerUrl = null; -// Method onReturnMethod; -// Method onThrowMethod; -// Method onInvokeMethod; -// NofifyImpl notify = new NofifyImpl(); -// //================================================================================================ -// IDemoService demoProxy = null; -// -// @BeforeEach -// public void setUp() throws SecurityException, NoSuchMethodException { -// onReturnMethod = Nofify.class.getMethod("onreturn", new Class[]{Person.class, Integer.class}); -// onThrowMethod = Nofify.class.getMethod("onthrow", new Class[]{Throwable.class, Integer.class}); -// onInvokeMethod = Nofify.class.getMethod("oninvoke", new Class[]{Integer.class}); -// } -// -// @AfterEach -// public void tearDown() { -// ProtocolUtils.closeAll(); -// } -// -// public void initOrResetService() { -// destroyService(); -// exportService(); -// referService(); -// } -// -// public void initOrResetExService() { -// destroyService(); -// exportExService(); -// referService(); -// } -// -// public void destroyService() { -// demoProxy = null; -// try { -// if (exporter != null) exporter.unexport(); -// if (reference != null) reference.destroy(); -// } catch (Exception e) { -// } -// } -// -// void referService() { -// demoProxy = (IDemoService) ProtocolUtils.refer(IDemoService.class, consumerUrl); -// } -// -// public void exportService() { -// exporter = ProtocolUtils.export(new NormalDemoService(), IDemoService.class, serviceURL); -// } -// -// public void exportExService() { -// exporter = ProtocolUtils.export(new ExceptionDemoExService(), IDemoService.class, serviceURL); -// } -// -// public void initOrResetUrl(boolean isAsync) throws Exception { -// int port = NetUtils.getAvailablePort(); -// consumerUrl = serviceURL = URL.valueOf("dubbo://127.0.0.1:" + port + "/" + IDemoService.class.getName() + "?group=" + System.nanoTime() + "&async=" + isAsync + "&timeout=100000&reference.filter=future"); -// } -// -// public void initImplicitCallBackURL_onlyOnthrow() throws Exception { -// Map attitudes = new HashMap<>(); -// ConsumerMethodModel.AsyncMethodInfo asyncMethodInfo = new ConsumerMethodModel.AsyncMethodInfo(); -// asyncMethodInfo.setOnthrowInstance(notify); -// asyncMethodInfo.setOnthrowMethod(onThrowMethod); -// ServiceMetadata metada = new ServiceMetadata(); -// -// ConsumerModel consumerModel = new ConsumerModel(consumerUrl.getServiceInterface(), "Dubbo", "1.0.0", IDemoService.class); -// consumerModel.getMethodModel("get").addAttribute(ASYNC_KEY, asyncMethodInfo); -// ApplicationModel.initConsumerModel(consumerUrl.getServiceKey(), consumerModel); -// } -// -// //================================================================================================ -// -// public void initImplicitCallBackURL_onlyOnreturn() throws Exception { -// Map attitudes = new HashMap<>(); -// ConsumerMethodModel.AsyncMethodInfo asyncMethodInfo = new ConsumerMethodModel.AsyncMethodInfo(); -// asyncMethodInfo.setOnreturnInstance(notify); -// asyncMethodInfo.setOnreturnMethod(onReturnMethod); -// ConsumerModel consumerModel = new ConsumerModel(consumerUrl.getServiceInterface(), "Dubbo", "1.0.0", IDemoService.class); -// consumerModel.getMethodModel("get").addAttribute(ASYNC_KEY, asyncMethodInfo); -// ApplicationModel.initConsumerModel(consumerUrl.getServiceKey(), consumerModel); -// } -// -// public void initImplicitCallBackURL_onlyOninvoke() throws Exception { -// Map attitudes = new HashMap<>(); -// ConsumerMethodModel.AsyncMethodInfo asyncMethodInfo = new ConsumerMethodModel.AsyncMethodInfo(); -// asyncMethodInfo.setOninvokeInstance(notify); -// asyncMethodInfo.setOninvokeMethod(onInvokeMethod); -// ConsumerModel consumerModel = new ConsumerModel(consumerUrl.getServiceInterface(), "Dubbo", "1.0.0", IDemoService.class); -// consumerModel.getMethodModel("get").addAttribute(ASYNC_KEY, asyncMethodInfo); -// ApplicationModel.initConsumerModel(consumerUrl.getServiceKey(), consumerModel); -// } -// -// @Test -// public void test_CloseCallback() throws Exception { -// initOrResetUrl(false); -// initOrResetService(); -// Person ret = demoProxy.get(1); -// Assertions.assertEquals(1, ret.getId()); -// destroyService(); -// } -// -// @Test -// public void test_Sync_Onreturn() throws Exception { -// initOrResetUrl(false); -// initOrResetService(); -// initImplicitCallBackURL_onlyOnreturn(); -// -// int requestId = 2; -// Person ret = demoProxy.get(requestId); -// Assertions.assertEquals(requestId, ret.getId()); -// for (int i = 0; i < 10; i++) { -// if (!notify.ret.containsKey(requestId)) { -// Thread.sleep(200); -// } else { -// break; -// } -// } -// Assertions.assertEquals(requestId, notify.ret.get(requestId).getId()); -// destroyService(); -// } -// -// @Test -// public void test_Ex_OnReturn() throws Exception { -// initOrResetUrl(true); -// initOrResetExService(); -// initImplicitCallBackURL_onlyOnreturn(); -// -// -// int requestId = 2; -// Person ret = demoProxy.get(requestId); -// Assertions.assertNull(ret); -// for (int i = 0; i < 10; i++) { -// if (!notify.errors.containsKey(requestId)) { -// Thread.sleep(200); -// } else { -// break; -// } -// } -// Assertions.assertTrue(!notify.errors.containsKey(requestId)); -// destroyService(); -// } -// -// @Test -// public void test_Ex_OnInvoke() throws Exception { -// initOrResetUrl(true); -// initOrResetExService(); -// initImplicitCallBackURL_onlyOninvoke(); -// -// int requestId = 2; -// Person ret = demoProxy.get(requestId); -// Assertions.assertNull(ret); -// for (int i = 0; i < 10; i++) { -// if (!notify.inv.contains(requestId)) { -// Thread.sleep(200); -// } else { -// break; -// } -// } -// Assertions.assertTrue(notify.inv.contains(requestId)); -// destroyService(); -// } -// -// @Test -// public void test_Ex_Onthrow() throws Exception { -// initOrResetUrl(true); -// initOrResetExService(); -// initImplicitCallBackURL_onlyOnthrow(); -// -// int requestId = 2; -// Person ret = demoProxy.get(requestId); -// Assertions.assertNull(ret); -// for (int i = 0; i < 10; i++) { -// if (!notify.errors.containsKey(requestId)) { -// Thread.sleep(200); -// } else { -// break; -// } -// } -// Assertions.assertTrue(notify.errors.containsKey(requestId)); -// Assertions.assertTrue(notify.errors.get(requestId) instanceof Throwable); -// destroyService(); -// } -// -// @Test -// public void test_Sync_NoFuture() throws Exception { -// initOrResetUrl(false); -// initOrResetService(); -// initImplicitCallBackURL_onlyOnreturn(); -// -// int requestId = 2; -// Person ret = demoProxy.get(requestId); -// Assertions.assertEquals(requestId, ret.getId()); -// Future pFuture = RpcContext.getContext().getFuture(); -// Assertions.assertEquals(ret, pFuture.get()); -// destroyService(); -// } -// -// @Test -// public void test_Async_Future() throws Exception { -// initOrResetUrl(true); -// initOrResetService(); -// -// int requestId = 2; -// Person ret = demoProxy.get(requestId); -// Assertions.assertNull(ret); -// Future pFuture = RpcContext.getContext().getFuture(); -// ret = pFuture.get(1000 * 1000, TimeUnit.MICROSECONDS); -// Assertions.assertEquals(requestId, ret.getId()); -// destroyService(); -// } -// -// @Test -// public void test_Async_Future_Multi() throws Exception { -// initOrResetUrl(true); -// initOrResetService(); -// -// int requestId1 = 1; -// Person ret = demoProxy.get(requestId1); -// Assertions.assertNull(ret); -// Future p1Future = RpcContext.getContext().getFuture(); -// -// int requestId2 = 1; -// Person ret2 = demoProxy.get(requestId2); -// Assertions.assertNull(ret2); -// Future p2Future = RpcContext.getContext().getFuture(); -// -// ret = p1Future.get(1000 * 1000, TimeUnit.MICROSECONDS); -// ret2 = p2Future.get(1000 * 1000, TimeUnit.MICROSECONDS); -// Assertions.assertEquals(requestId1, ret.getId()); -// Assertions.assertEquals(requestId2, ret.getId()); -// destroyService(); -// } -// -// @Test -// public void test_Async_Future_Ex() throws Throwable { -// Assertions.assertThrows(RuntimeException.class, () -> { -// try { -// initOrResetUrl(true); -// initOrResetExService(); -// -// int requestId = 2; -// Person ret = demoProxy.get(requestId); -// Assertions.assertNull(ret); -// Future pFuture = RpcContext.getContext().getFuture(); -// ret = pFuture.get(1000 * 1000, TimeUnit.MICROSECONDS); -// Assertions.assertEquals(requestId, ret.getId()); -// } catch (ExecutionException e) { -// throw e.getCause(); -// } finally { -// destroyService(); -// } -// }); -// } -// -// @Test -// public void test_Normal_Ex() throws Exception { -// Assertions.assertThrows(RuntimeException.class, () -> { -// initOrResetUrl(false); -// initOrResetExService(); -// -// int requestId = 2; -// Person ret = demoProxy.get(requestId); -// Assertions.assertEquals(requestId, ret.getId()); -// }); -// } -// -// interface Nofify { -// void onreturn(Person msg, Integer id); -// -// void onthrow(Throwable ex, Integer id); -// -// void oninvoke(Integer id); -// } -// -// interface IDemoService { -// Person get(int id); -// } -// -// public static class Person implements Serializable { -// private static final long serialVersionUID = 1L; -// private int id; -// private String name; -// private int age; -// -// public Person(int id, String name, int age) { -// this.id = id; -// this.name = name; -// this.age = age; -// } -// -// public String getName() { -// return name; -// } -// -// public void setName(String name) { -// this.name = name; -// } -// -// public int getAge() { -// return age; -// } -// -// public void setAge(int age) { -// this.age = age; -// } -// -// public int getId() { -// return id; -// } -// -// public void setId(int id) { -// this.id = id; -// } -// -// @Override -// public String toString() { -// return "Person [name=" + name + ", age=" + age + "]"; -// } -// } -// -// class NofifyImpl implements Nofify { -// public List inv = new ArrayList(); -// public Map ret = new HashMap(); -// public Map errors = new HashMap(); -// public boolean exd = false; -// -// public void onreturn(Person msg, Integer id) { -// System.out.println("onNotify:" + msg); -// ret.put(id, msg); -// } -// -// public void onthrow(Throwable ex, Integer id) { -// errors.put(id, ex); -//// ex.printStackTrace(); -// } -// -// public void oninvoke(Integer id) { -// inv.add(id); -// } -// } -// -// class NormalDemoService implements IDemoService { -// public Person get(int id) { -// return new Person(id, "charles", 4); -// } -// } -// -// class ExceptionDemoExService implements IDemoService { -// public Person get(int id) { -// throw new RuntimeException("request persion id is :" + id); -// } -// } -//} diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/MultiThreadTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/MultiThreadTest.java index a28f9c1d01..bcfdaafaad 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/MultiThreadTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/MultiThreadTest.java @@ -27,39 +27,48 @@ import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoServiceImpl; import org.apache.dubbo.rpc.protocol.dubbo.support.ProtocolUtils; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class MultiThreadTest { - private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + private Protocol protocol = + ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); + private ProxyFactory proxy = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); @AfterEach public void after() { ProtocolUtils.closeAll(); - ApplicationModel.defaultModel().getDefaultModule().getServiceRepository().destroy(); + ApplicationModel.defaultModel() + .getDefaultModule() + .getServiceRepository() + .destroy(); } @Test void testDubboMultiThreadInvoke() throws Exception { - ApplicationModel.defaultModel().getDefaultModule().getServiceRepository().registerService("TestService", DemoService.class); + ApplicationModel.defaultModel() + .getDefaultModule() + .getServiceRepository() + .registerService("TestService", DemoService.class); int port = NetUtils.getAvailablePort(); - Exporter rpcExporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/TestService"))); + Exporter rpcExporter = protocol.export(proxy.getInvoker( + new DemoServiceImpl(), DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/TestService"))); final AtomicInteger counter = new AtomicInteger(); - final DemoService service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/TestService"))); - Assertions.assertEquals(service.getSize(new String[]{"123", "456", "789"}), 3); + final DemoService service = proxy.getProxy( + protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/TestService"))); + Assertions.assertEquals(service.getSize(new String[] {"123", "456", "789"}), 3); final StringBuffer sb = new StringBuffer(); - for (int i = 0; i < 1024 * 64 + 32; i++) - sb.append('A'); + for (int i = 0; i < 1024 * 64 + 32; i++) sb.append('A'); Assertions.assertEquals(sb.toString(), service.echo(sb.toString())); ExecutorService exec = Executors.newFixedThreadPool(10); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java index 1c18774e56..eeb7d42687 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java @@ -28,12 +28,6 @@ import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.protocol.dubbo.support.ProtocolUtils; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; @@ -41,13 +35,20 @@ import java.util.Comparator; import java.util.List; import java.util.Objects; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.LAZY_REQUEST_WITH_WARNING_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.SHARE_CONNECTIONS_KEY; class ReferenceCountExchangeClientTest { - public static ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + public static ProxyFactory proxy = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Exporter demoExporter; Exporter helloExporter; Invoker demoServiceInvoker; @@ -59,8 +60,7 @@ class ReferenceCountExchangeClientTest { String errorMsg = "safe guard client , should not be called ,must have a bug"; @BeforeAll - public static void setUpBeforeClass() throws Exception { - } + public static void setUpBeforeClass() throws Exception {} @AfterAll public static void tearDownAfterClass() { @@ -76,12 +76,13 @@ class ReferenceCountExchangeClientTest { } public static Exporter export(T instance, Class type, URL url) { - return ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(DubboProtocol.NAME).export(proxy.getInvoker(instance, type, url)); + return ExtensionLoader.getExtensionLoader(Protocol.class) + .getExtension(DubboProtocol.NAME) + .export(proxy.getInvoker(instance, type, url)); } @BeforeEach - public void setUp() throws Exception { - } + public void setUp() throws Exception {} /** * test connection sharing @@ -174,7 +175,8 @@ class ReferenceCountExchangeClientTest { Assertions.fail(); } - // client has been replaced with lazy client, close status is false because a new lazy client's exchange client is null. + // client has been replaced with lazy client, close status is false because a new lazy client's exchange client + // is null. Assertions.assertFalse(client.isClosed(), "client status close"); // invoker status is available because the default value of associated lazy client's initial state is true. Assertions.assertTrue(helloServiceInvoker.isAvailable(), "invoker status unavailable"); @@ -283,7 +285,8 @@ class ReferenceCountExchangeClientTest { } private List getInvokerClientList(Invoker invoker) { - @SuppressWarnings("rawtypes") DubboInvoker dInvoker = (DubboInvoker) invoker; + @SuppressWarnings("rawtypes") + DubboInvoker dInvoker = (DubboInvoker) invoker; try { Field clientField = DubboInvoker.class.getDeclaredField("clientsProvider"); clientField.setAccessible(true); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/RpcFilterTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/RpcFilterTest.java index 13beb738bd..0e3ac37f84 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/RpcFilterTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/RpcFilterTest.java @@ -32,8 +32,10 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class RpcFilterTest { - private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + private Protocol protocol = + ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); + private ProxyFactory proxy = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); @AfterEach public void after() { @@ -44,8 +46,12 @@ class RpcFilterTest { void testRpcFilter() throws Exception { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.support.DemoService?service.filter=echo"); - ApplicationModel.defaultModel().getDefaultModule().getServiceRepository().registerService(DemoService.class); + URL url = URL.valueOf("dubbo://127.0.0.1:" + port + + "/org.apache.dubbo.rpc.protocol.dubbo.support.DemoService?service.filter=echo"); + ApplicationModel.defaultModel() + .getDefaultModule() + .getServiceRepository() + .registerService(DemoService.class); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); protocol.export(proxy.getInvoker(service, DemoService.class, url)); service = proxy.getProxy(protocol.refer(DemoService.class, url)); @@ -56,5 +62,4 @@ class RpcFilterTest { Assertions.assertEquals(echo.$echo("abcdefg"), "abcdefg"); Assertions.assertEquals(echo.$echo(1234), 1234); } - } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/DubboTelnetDecodeTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/DubboTelnetDecodeTest.java index 9f05c81fe2..ee6a9ab716 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/DubboTelnetDecodeTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/DubboTelnetDecodeTest.java @@ -40,6 +40,11 @@ import org.apache.dubbo.rpc.protocol.dubbo.DecodeableRpcInvocation; import org.apache.dubbo.rpc.protocol.dubbo.DubboCodec; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.embedded.EmbeddedChannel; @@ -49,11 +54,6 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import java.io.IOException; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - /** * These junit tests aim to test unpack and stick pack of dubbo and telnet */ @@ -72,14 +72,14 @@ class DubboTelnetDecodeTest { @BeforeAll public static void setup() { - ModuleServiceRepository serviceRepository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); + ModuleServiceRepository serviceRepository = + ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); serviceRepository.registerService(DemoService.class); } @AfterAll public static void teardown() { FrameworkModel.defaultModel().destroy(); - } /** @@ -97,23 +97,21 @@ class DubboTelnetDecodeTest { URL url = new ServiceConfigURL("dubbo", "localhost", 22226); NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler()); - MockHandler mockHandler = new MockHandler(null, - new MultiMessageHandler( - new DecodeHandler( - new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { - @Override - public CompletableFuture reply(ExchangeChannel channel, Object msg) { - if (checkDubboDecoded(msg)) { - dubbo.incrementAndGet(); - } - return getDefaultFuture(); - } - })))); + MockHandler mockHandler = new MockHandler( + null, + new MultiMessageHandler(new DecodeHandler( + new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { + @Override + public CompletableFuture reply(ExchangeChannel channel, Object msg) { + if (checkDubboDecoded(msg)) { + dubbo.incrementAndGet(); + } + return getDefaultFuture(); + } + })))); ch = new LocalEmbeddedChannel(); - ch.pipeline() - .addLast("decoder", adapter.getDecoder()) - .addLast("handler", mockHandler); + ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("handler", mockHandler); ch.writeInbound(dubboByteBuf); } catch (Exception e) { @@ -144,24 +142,22 @@ class DubboTelnetDecodeTest { URL url = new ServiceConfigURL("dubbo", "localhost", 22226); NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler()); - MockHandler mockHandler = new MockHandler((msg) -> { - if (checkTelnetDecoded(msg)) { - telnet.incrementAndGet(); - } - }, - new MultiMessageHandler( - new DecodeHandler( - new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { - @Override - public CompletableFuture reply(ExchangeChannel channel, Object msg) { - return getDefaultFuture(); - } - })))); + MockHandler mockHandler = new MockHandler( + (msg) -> { + if (checkTelnetDecoded(msg)) { + telnet.incrementAndGet(); + } + }, + new MultiMessageHandler(new DecodeHandler( + new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { + @Override + public CompletableFuture reply(ExchangeChannel channel, Object msg) { + return getDefaultFuture(); + } + })))); ch = new LocalEmbeddedChannel(); - ch.pipeline() - .addLast("decoder", adapter.getDecoder()) - .addLast("handler", mockHandler); + ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("handler", mockHandler); ch.writeInbound(telnetByteBuf); } catch (Exception e) { @@ -207,28 +203,26 @@ class DubboTelnetDecodeTest { URL url = new ServiceConfigURL("dubbo", "localhost", 22226); NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler()); - MockHandler mockHandler = new MockHandler((msg) -> { - if (checkTelnetDecoded(msg)) { - telnetDubbo.incrementAndGet(); - } - }, - new MultiMessageHandler( - new DecodeHandler( - new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { - @Override - public CompletableFuture reply(ExchangeChannel channel, Object msg) { - if (checkDubboDecoded(msg)) { - telnetDubbo.incrementAndGet(); - } + MockHandler mockHandler = new MockHandler( + (msg) -> { + if (checkTelnetDecoded(msg)) { + telnetDubbo.incrementAndGet(); + } + }, + new MultiMessageHandler(new DecodeHandler( + new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { + @Override + public CompletableFuture reply(ExchangeChannel channel, Object msg) { + if (checkDubboDecoded(msg)) { + telnetDubbo.incrementAndGet(); + } - return getDefaultFuture(); - } - })))); + return getDefaultFuture(); + } + })))); ch = new LocalEmbeddedChannel(); - ch.pipeline() - .addLast("decoder", adapter.getDecoder()) - .addLast("handler", mockHandler); + ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("handler", mockHandler); ch.writeInbound(telnetByteBuf); ch.writeInbound(Unpooled.wrappedBuffer(Unpooled.wrappedBuffer("\n".getBytes()), dubboByteBuf)); @@ -279,24 +273,22 @@ class DubboTelnetDecodeTest { URL url = new ServiceConfigURL("dubbo", "localhost", 22226); NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler()); - MockHandler mockHandler = new MockHandler((msg) -> { - if (checkTelnetDecoded(msg)) { - telnetTelnet.incrementAndGet(); - } - }, - new MultiMessageHandler( - new DecodeHandler( - new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { - @Override - public CompletableFuture reply(ExchangeChannel channel, Object msg) { - return getDefaultFuture(); - } - })))); + MockHandler mockHandler = new MockHandler( + (msg) -> { + if (checkTelnetDecoded(msg)) { + telnetTelnet.incrementAndGet(); + } + }, + new MultiMessageHandler(new DecodeHandler( + new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { + @Override + public CompletableFuture reply(ExchangeChannel channel, Object msg) { + return getDefaultFuture(); + } + })))); ch = new LocalEmbeddedChannel(); - ch.pipeline() - .addLast("decoder", adapter.getDecoder()) - .addLast("handler", mockHandler); + ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("handler", mockHandler); ch.writeInbound(firstByteBuf); ch.writeInbound(secondByteBuf); @@ -343,30 +335,27 @@ class DubboTelnetDecodeTest { ByteBuf secondLeftDubboByteBuf = dubboByteBuf.copy(50, dubboByteBuf.readableBytes() - 50); ByteBuf secondDubboByteBuf = Unpooled.wrappedBuffer(secondLeftDubboByteBuf, dubboByteBuf); - EmbeddedChannel ch = null; try { Codec2 codec = ExtensionLoader.getExtensionLoader(Codec2.class).getExtension("dubbo"); URL url = new ServiceConfigURL("dubbo", "localhost", 22226); NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler()); - MockHandler mockHandler = new MockHandler(null, - new MultiMessageHandler( - new DecodeHandler( - new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { - @Override - public CompletableFuture reply(ExchangeChannel channel, Object msg) { - if (checkDubboDecoded(msg)) { - dubboDubbo.incrementAndGet(); - } - return getDefaultFuture(); - } - })))); + MockHandler mockHandler = new MockHandler( + null, + new MultiMessageHandler(new DecodeHandler( + new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { + @Override + public CompletableFuture reply(ExchangeChannel channel, Object msg) { + if (checkDubboDecoded(msg)) { + dubboDubbo.incrementAndGet(); + } + return getDefaultFuture(); + } + })))); ch = new LocalEmbeddedChannel(); - ch.pipeline() - .addLast("decoder", adapter.getDecoder()) - .addLast("handler", mockHandler); + ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("handler", mockHandler); ch.writeInbound(firstDubboByteBuf); ch.writeInbound(secondDubboByteBuf); @@ -417,27 +406,25 @@ class DubboTelnetDecodeTest { URL url = new ServiceConfigURL("dubbo", "localhost", 22226); NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler()); - MockHandler mockHandler = new MockHandler((msg) -> { - if (checkTelnetDecoded(msg)) { - dubboTelnet.incrementAndGet(); - } - }, - new MultiMessageHandler( - new DecodeHandler( - new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { - @Override - public CompletableFuture reply(ExchangeChannel channel, Object msg) { - if (checkDubboDecoded(msg)) { - dubboTelnet.incrementAndGet(); - } - return getDefaultFuture(); - } - })))); + MockHandler mockHandler = new MockHandler( + (msg) -> { + if (checkTelnetDecoded(msg)) { + dubboTelnet.incrementAndGet(); + } + }, + new MultiMessageHandler(new DecodeHandler( + new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { + @Override + public CompletableFuture reply(ExchangeChannel channel, Object msg) { + if (checkDubboDecoded(msg)) { + dubboTelnet.incrementAndGet(); + } + return getDefaultFuture(); + } + })))); ch = new LocalEmbeddedChannel(); - ch.pipeline() - .addLast("decoder", adapter.getDecoder()) - .addLast("handler", mockHandler); + ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("handler", mockHandler); ch.writeInbound(firstDubboByteBuf); ch.writeInbound(secondByteBuf); @@ -458,9 +445,9 @@ class DubboTelnetDecodeTest { Request request = new Request(); RpcInvocation rpcInvocation = new RpcInvocation(); rpcInvocation.setMethodName("sayHello"); - rpcInvocation.setParameterTypes(new Class[]{String.class}); - rpcInvocation.setParameterTypesDesc(ReflectUtils.getDesc(new Class[]{String.class})); - rpcInvocation.setArguments(new String[]{"dubbo"}); + rpcInvocation.setParameterTypes(new Class[] {String.class}); + rpcInvocation.setParameterTypesDesc(ReflectUtils.getDesc(new Class[] {String.class})); + rpcInvocation.setArguments(new String[] {"dubbo"}); rpcInvocation.setAttachment("path", DemoService.class.getName()); rpcInvocation.setAttachment("interface", DemoService.class.getName()); rpcInvocation.setAttachment("version", "0.0.0"); @@ -475,9 +462,11 @@ class DubboTelnetDecodeTest { // register // frameworkModel.getServiceRepository().registerProviderUrl(); - FrameworkModel.defaultModel().getBeanFactory().getBean(PermittedSerializationKeeper.class) - .registerService(URL.valueOf("dubbo://127.0.0.1:20880/" + DemoService.class.getName() + "?version=0.0.0")); - + FrameworkModel.defaultModel() + .getBeanFactory() + .getBean(PermittedSerializationKeeper.class) + .registerService( + URL.valueOf("dubbo://127.0.0.1:20880/" + DemoService.class.getName() + "?version=0.0.0")); return dubboByteBuf; } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/LocalEmbeddedChannel.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/LocalEmbeddedChannel.java index adc590d751..df11f5c342 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/LocalEmbeddedChannel.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/LocalEmbeddedChannel.java @@ -18,11 +18,11 @@ package org.apache.dubbo.rpc.protocol.dubbo.decode; import org.apache.dubbo.common.utils.NetUtils; -import io.netty.channel.embedded.EmbeddedChannel; - import java.net.InetSocketAddress; import java.net.SocketAddress; +import io.netty.channel.embedded.EmbeddedChannel; + public class LocalEmbeddedChannel extends EmbeddedChannel { public SocketAddress localAddress() { return new InetSocketAddress(20883); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/MockChannel.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/MockChannel.java index 4667000069..46ae895c1c 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/MockChannel.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/MockChannel.java @@ -29,9 +29,7 @@ import java.util.function.Consumer; public class MockChannel implements Channel { private Consumer consumer; - public MockChannel() { - - } + public MockChannel() {} public MockChannel(Consumer consumer) { this.consumer = consumer; @@ -58,14 +56,10 @@ public class MockChannel implements Channel { } @Override - public void setAttribute(String key, Object value) { - - } + public void setAttribute(String key, Object value) {} @Override - public void removeAttribute(String key) { - - } + public void removeAttribute(String key) {} @Override public URL getUrl() { @@ -90,24 +84,16 @@ public class MockChannel implements Channel { } @Override - public void send(Object message, boolean sent) throws RemotingException { - - } + public void send(Object message, boolean sent) throws RemotingException {} @Override - public void close() { - - } + public void close() {} @Override - public void close(int timeout) { - - } + public void close(int timeout) {} @Override - public void startClose() { - - } + public void startClose() {} @Override public boolean isClosed() { diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/MockChannelHandler.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/MockChannelHandler.java index 492929706d..f15a32a77c 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/MockChannelHandler.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/MockChannelHandler.java @@ -45,14 +45,13 @@ public class MockChannelHandler implements ChannelHandler { @Override public void received(Channel channel, Object message) throws RemotingException { - //echo + // echo channel.send(message); } @Override public void caught(Channel channel, Throwable exception) throws RemotingException { throw new RemotingException(channel, exception); - } public Set getChannels() { diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/MockHandler.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/MockHandler.java index f4f432a733..8c58663646 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/MockHandler.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/MockHandler.java @@ -18,11 +18,11 @@ package org.apache.dubbo.rpc.protocol.dubbo.decode; import org.apache.dubbo.remoting.ChannelHandler; +import java.util.function.Consumer; + import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; -import java.util.function.Consumer; - public class MockHandler extends ChannelDuplexHandler { private final Consumer consumer; diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/ChannelHandlersTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/ChannelHandlersTest.java index 4876dd7b85..f2e4ab7acd 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/ChannelHandlersTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/ChannelHandlersTest.java @@ -21,6 +21,7 @@ import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.transport.MultiMessageHandler; import org.apache.dubbo.remoting.transport.dispatcher.ChannelHandlers; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/ConnectChannelHandlerTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/ConnectChannelHandlerTest.java index 352a8c2738..2781a361d6 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/ConnectChannelHandlerTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/ConnectChannelHandlerTest.java @@ -22,14 +22,15 @@ import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.transport.dispatcher.connection.ConnectionOrderedChannelHandler; import org.apache.dubbo.rpc.model.ApplicationModel; + +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.atomic.AtomicInteger; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.atomic.AtomicInteger; - class ConnectChannelHandlerTest extends WrappedChannelHandlerTest { @BeforeEach @@ -51,7 +52,7 @@ class ConnectChannelHandlerTest extends WrappedChannelHandlerTest { handler.disconnected(new MockedChannel()); Assertions.assertTrue(executor.getActiveCount() <= 1, executor.getActiveCount() + " must <=1"); } - //queue.size + // queue.size Assertions.assertEquals(taskCount - 1, executor.getQueue().size()); for (int i = 0; i < taskCount; i++) { @@ -62,13 +63,13 @@ class ConnectChannelHandlerTest extends WrappedChannelHandlerTest { Assertions.assertEquals(taskCount, executor.getCompletedTaskCount()); } - @Test //biz error should not throw and affect biz thread. + @Test // biz error should not throw and affect biz thread. public void testConnectBizError() throws RemotingException { handler = new ConnectionOrderedChannelHandler(new BizChannelHandler(true), url); handler.connected(new MockedChannel()); } - @Test //biz error should not throw and affect biz thread. + @Test // biz error should not throw and affect biz thread. public void testDisconnectBizError() throws RemotingException { handler = new ConnectionOrderedChannelHandler(new BizChannelHandler(true), url); handler.disconnected(new MockedChannel()); @@ -94,13 +95,13 @@ class ConnectChannelHandlerTest extends WrappedChannelHandlerTest { }); } - //throw ChannelEventRunnable.runtimeExeception(int logger) not in execute exception - @Test//(expected = RemotingException.class) + // throw ChannelEventRunnable.runtimeExeception(int logger) not in execute exception + @Test // (expected = RemotingException.class) public void testMessageReceivedBizError() throws RemotingException { handler.received(new MockedChannel(), ""); } - //throw ChannelEventRunnable.runtimeExeception(int logger) not in execute exception + // throw ChannelEventRunnable.runtimeExeception(int logger) not in execute exception @Test void testCaughtBizError() throws RemotingException { handler.caught(new MockedChannel(), new BizException()); @@ -134,13 +135,15 @@ class ConnectChannelHandlerTest extends WrappedChannelHandlerTest { Request req = new Request(); req.setHeartbeat(true); final AtomicInteger count = new AtomicInteger(0); - handler.received(new MockedChannel() { - @Override - public void send(Object message) throws RemotingException { - Assertions.assertTrue(((Response) message).isHeartbeat(), "response.heartbeat"); - count.incrementAndGet(); - } - }, req); + handler.received( + new MockedChannel() { + @Override + public void send(Object message) throws RemotingException { + Assertions.assertTrue(((Response) message).isHeartbeat(), "response.heartbeat"); + count.incrementAndGet(); + } + }, + req); Assertions.assertEquals(1, count.get(), "channel.send must be invoke"); } } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/MockedChannel.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/MockedChannel.java index baa35eac69..c5bec9d7af 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/MockedChannel.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/MockedChannel.java @@ -36,7 +36,6 @@ public class MockedChannel implements Channel { super(); } - @Override public URL getUrl() { return url; @@ -55,8 +54,7 @@ public class MockedChannel implements Channel { } @Override - public void send(Object message) throws RemotingException { - } + public void send(Object message) throws RemotingException {} @Override public void send(Object message, boolean sent) throws RemotingException { diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/MockedChannelHandler.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/MockedChannelHandler.java index f2dc66abba..0f95be38af 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/MockedChannelHandler.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/MockedChannelHandler.java @@ -45,14 +45,13 @@ public class MockedChannelHandler implements ChannelHandler { @Override public void received(Channel channel, Object message) throws RemotingException { - //echo + // echo channel.send(message); } @Override public void caught(Channel channel, Throwable exception) throws RemotingException { throw new RemotingException(channel, exception); - } public Set getChannels() { diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/WrappedChannelHandlerTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/WrappedChannelHandlerTest.java index e0e567d9b8..a95d9ba229 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/WrappedChannelHandlerTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/WrappedChannelHandlerTest.java @@ -27,13 +27,14 @@ import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.exchange.support.DefaultFuture; import org.apache.dubbo.remoting.transport.dispatcher.WrappedChannelHandler; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.util.concurrent.ExecutorService; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.fail; class WrappedChannelHandlerTest { @@ -47,10 +48,7 @@ class WrappedChannelHandlerTest { } @Test - void test_Execute_Error() throws RemotingException { - - } - + void test_Execute_Error() throws RemotingException {} protected Object getField(Object obj, String fieldName, int parentdepth) { try { @@ -124,7 +122,8 @@ class WrappedChannelHandlerTest { Channel channel = new MockedChannel(); Request request = new Request(10); ExecutorService sharedExecutor = ExtensionLoader.getExtensionLoader(ExecutorRepository.class) - .getDefaultExtension().createExecutorIfAbsent(url); + .getDefaultExtension() + .createExecutorIfAbsent(url); DefaultFuture future = DefaultFuture.newFuture(channel, request, 1000, null); preferredExecutorService = handler.getPreferredExecutorService(response); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/status/ServerStatusCheckerTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/status/ServerStatusCheckerTest.java index 6061be5c79..40c4921530 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/status/ServerStatusCheckerTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/status/ServerStatusCheckerTest.java @@ -22,15 +22,15 @@ import org.apache.dubbo.rpc.ProtocolServer; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; import org.apache.dubbo.rpc.protocol.dubbo.decode.MockChannel; +import java.net.InetSocketAddress; +import java.util.Arrays; +import java.util.List; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; -import java.net.InetSocketAddress; -import java.util.Arrays; -import java.util.List; - /** * {@link ServerStatusChecker} */ @@ -49,10 +49,10 @@ class ServerStatusCheckerTest { Mockito.when(dubboProtocol.getServers()).thenReturn(servers); Mockito.when(protocolServer.getRemotingServer()).thenReturn(remotingServer); Mockito.when(remotingServer.isBound()).thenReturn(true); - Mockito.when(remotingServer.getLocalAddress()).thenReturn(InetSocketAddress.createUnresolved("127.0.0.1", 9999)); + Mockito.when(remotingServer.getLocalAddress()) + .thenReturn(InetSocketAddress.createUnresolved("127.0.0.1", 9999)); Mockito.when(remotingServer.getChannels()).thenReturn(Arrays.asList(new MockChannel())); - try (MockedStatic mockDubboProtocol = Mockito.mockStatic(DubboProtocol.class)) { mockDubboProtocol.when(() -> DubboProtocol.getDubboProtocol()).thenReturn(dubboProtocol); status = serverStatusChecker.check(); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/status/ThreadPoolStatusCheckerTest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/status/ThreadPoolStatusCheckerTest.java index 6b26f368d3..eb3321dd63 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/status/ThreadPoolStatusCheckerTest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/status/ThreadPoolStatusCheckerTest.java @@ -22,12 +22,12 @@ import org.apache.dubbo.common.status.Status; import org.apache.dubbo.common.store.DataStore; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + /** * {@link ThreadPoolStatusChecker} */ @@ -35,7 +35,8 @@ class ThreadPoolStatusCheckerTest { @Test void test() { - DataStore dataStore = ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension(); + DataStore dataStore = + ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension(); ExecutorService executorService1 = Executors.newFixedThreadPool(1); ExecutorService executorService2 = Executors.newFixedThreadPool(10); dataStore.put(CommonConstants.EXECUTOR_SERVICE_COMPONENT_KEY, "8888", executorService1); @@ -44,9 +45,10 @@ class ThreadPoolStatusCheckerTest { ThreadPoolStatusChecker threadPoolStatusChecker = new ThreadPoolStatusChecker(ApplicationModel.defaultModel()); Status status = threadPoolStatusChecker.check(); Assertions.assertEquals(status.getLevel(), Status.Level.WARN); - Assertions.assertEquals(status.getMessage(), - "Pool status:WARN, max:1, core:1, largest:0, active:0, task:0, service port: 8888;" - + "Pool status:OK, max:10, core:10, largest:0, active:0, task:0, service port: 8889"); + Assertions.assertEquals( + status.getMessage(), + "Pool status:WARN, max:1, core:1, largest:0, active:0, task:0, service port: 8888;" + + "Pool status:OK, max:10, core:10, largest:0, active:0, task:0, service port: 8889"); // reset executorService1.shutdown(); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/CustomArgument.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/CustomArgument.java index 952c8b27c5..96bac4f56a 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/CustomArgument.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/CustomArgument.java @@ -18,15 +18,14 @@ package org.apache.dubbo.rpc.protocol.dubbo.support; import java.io.Serializable; - @SuppressWarnings("serial") public class CustomArgument implements Serializable { Type type; String name; - public CustomArgument() { - } + public CustomArgument() {} + public CustomArgument(Type type, String name) { super(); this.type = type; diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/DemoRequest.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/DemoRequest.java index 5a9e7451b4..e44a171f41 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/DemoRequest.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/DemoRequest.java @@ -21,7 +21,6 @@ import java.io.Serializable; /** * TestRequest. */ - class DemoRequest implements Serializable { private static final long serialVersionUID = -2579095288792344869L; diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/DemoService.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/DemoService.java index ed1d584280..55a7dc6ee5 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/DemoService.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/DemoService.java @@ -19,11 +19,9 @@ package org.apache.dubbo.rpc.protocol.dubbo.support; import java.util.Map; import java.util.Set; - /** * TestService */ - public interface DemoService { void sayHello(String name); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/DemoServiceImpl.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/DemoServiceImpl.java index f31081dca0..ad1255ecac 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/DemoServiceImpl.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/DemoServiceImpl.java @@ -51,25 +51,23 @@ public class DemoServiceImpl implements DemoService { } public int getSize(String[] strs) { - if (strs == null) - return -1; + if (strs == null) return -1; return strs.length; } public int getSize(Object[] os) { - if (os == null) - return -1; + if (os == null) return -1; return os.length; } public Object invoke(String service, String method) throws Exception { - System.out.println("RpcContext.getServerAttachment().getRemoteHost()=" + RpcContext.getServiceContext().getRemoteHost()); + System.out.println("RpcContext.getServerAttachment().getRemoteHost()=" + + RpcContext.getServiceContext().getRemoteHost()); return service + ":" + method; } public Type enumlength(Type... types) { - if (types.length == 0) - return Type.Lower; + if (types.length == 0) return Type.Lower; return types[0]; } @@ -97,8 +95,7 @@ public class DemoServiceImpl implements DemoService { return map == null ? null : map.keySet(); } - public void nonSerializedParameter(NonSerialized ns) { - } + public void nonSerializedParameter(NonSerialized ns) {} public NonSerialized returnNonSerialized() { return new NonSerialized(); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/EnumBak.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/EnumBak.java index 4903c4e445..9969cb5b0f 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/EnumBak.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/EnumBak.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.dubbo.support; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; @@ -26,28 +25,32 @@ import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.service.GenericService; +import java.util.HashMap; +import java.util.Map; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import java.util.HashMap; -import java.util.Map; - public class EnumBak { - private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + private Protocol protocol = + ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); + private ProxyFactory proxy = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); @Test public void testNormal() { int port = NetUtils.getAvailablePort(); URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?proxy=jdk" + "&interface=" + DemoService.class.getName() - + "&timeout=" + Integer.MAX_VALUE - ); + + "&timeout=" + Integer.MAX_VALUE); DemoService demo = new DemoServiceImpl(); - ApplicationModel.defaultModel().getDefaultModule().getServiceRepository().registerService("test", DemoService.class); + ApplicationModel.defaultModel() + .getDefaultModule() + .getServiceRepository() + .registerService("test", DemoService.class); Invoker invoker = proxy.getInvoker(demo, DemoService.class, serviceurl); protocol.export(invoker); @@ -55,11 +58,11 @@ public class EnumBak { URL consumerurl = serviceurl; Invoker reference = protocol.refer(DemoService.class, consumerurl); DemoService demoProxy = (DemoService) proxy.getProxy(reference); -// System.out.println(demoProxy.getThreadName()); + // System.out.println(demoProxy.getThreadName()); System.out.println(demoProxy.getInt(Integer.MIN_VALUE)); Assertions.assertEquals(Integer.MIN_VALUE, demoProxy.getInt(Integer.MIN_VALUE)); -// invoker.destroy(); + // invoker.destroy(); reference.destroy(); } @@ -67,8 +70,7 @@ public class EnumBak { @Test public void testExportService() throws InterruptedException { int port = NetUtils.getAvailablePort(); - URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?proxy=jdk&timeout=" + Integer.MAX_VALUE - ); + URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?proxy=jdk&timeout=" + Integer.MAX_VALUE); DemoService demo = new DemoServiceImpl(); Invoker invoker = proxy.getInvoker(demo, DemoService.class, serviceurl); protocol.export(invoker); @@ -76,24 +78,26 @@ public class EnumBak { EnumBak.class.wait(); } -// URL consumerurl = serviceurl; -// Invoker reference = protocol.refer(DemoService.class, consumerurl); -// DemoService demoProxy = (DemoService)proxyFactory.createProxy(reference); -//// System.out.println(demoProxy.getThreadName()); -// System.out.println("byte:"+demoProxy.getbyte((byte)-128)); -// -// invoker.destroy(); -// reference.destroy(); + // URL consumerurl = serviceurl; + // Invoker reference = protocol.refer(DemoService.class, consumerurl); + // DemoService demoProxy = (DemoService)proxyFactory.createProxy(reference); + //// System.out.println(demoProxy.getThreadName()); + // System.out.println("byte:"+demoProxy.getbyte((byte)-128)); + // + // invoker.destroy(); + // reference.destroy(); } @Test public void testNormalEnum() { int port = NetUtils.getAvailablePort(); - URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE - ); + URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE); DemoService demo = new DemoServiceImpl(); - ApplicationModel.defaultModel().getDefaultModule().getServiceRepository().registerService("test", DemoService.class); + ApplicationModel.defaultModel() + .getDefaultModule() + .getServiceRepository() + .registerService("test", DemoService.class); Invoker invoker = proxy.getInvoker(demo, DemoService.class, serviceurl); protocol.export(invoker); @@ -114,10 +118,12 @@ public class EnumBak { @Test public void testEnumCompat() { int port = NetUtils.getAvailablePort(); - URL consumerurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE - ); + URL consumerurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE); - ApplicationModel.defaultModel().getDefaultModule().getServiceRepository().registerService(DemoService.class); + ApplicationModel.defaultModel() + .getDefaultModule() + .getServiceRepository() + .registerService(DemoService.class); Invoker reference = protocol.refer(DemoService.class, consumerurl); DemoService demoProxy = (DemoService) proxy.getProxy(reference); @@ -132,12 +138,12 @@ public class EnumBak { @Test public void testGenricEnumCompat() { int port = NetUtils.getAvailablePort(); - URL consumerurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE - ); + URL consumerurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE); Invoker reference = protocol.refer(GenericService.class, consumerurl); GenericService demoProxy = (GenericService) proxy.getProxy(reference); - Object obj = demoProxy.$invoke("enumlength", new String[]{Type[].class.getName()}, new Object[]{new Type[]{Type.High, Type.High}}); + Object obj = demoProxy.$invoke( + "enumlength", new String[] {Type[].class.getName()}, new Object[] {new Type[] {Type.High, Type.High}}); System.out.println("obj---------->" + obj); reference.destroy(); } @@ -148,8 +154,7 @@ public class EnumBak { public void testGenricCustomArg() { int port = NetUtils.getAvailablePort(); - URL consumerurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=2000000" - ); + URL consumerurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=2000000"); Invoker reference = protocol.refer(GenericService.class, consumerurl); GenericService demoProxy = (GenericService) proxy.getProxy(reference); @@ -157,7 +162,7 @@ public class EnumBak { arg.put("type", "High"); arg.put("name", "hi"); - Object obj = demoProxy.$invoke("get", new String[]{"org.apache.dubbo.rpc.CustomArgument"}, new Object[]{arg}); + Object obj = demoProxy.$invoke("get", new String[] {"org.apache.dubbo.rpc.CustomArgument"}, new Object[] {arg}); System.out.println("obj---------->" + obj); reference.destroy(); } @@ -166,23 +171,21 @@ public class EnumBak { @Test public void testGenericExport() throws InterruptedException { int port = NetUtils.getAvailablePort(); - //port = 20880; - URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE - ); + // port = 20880; + URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE); DemoService demo = new DemoServiceImpl(); Invoker invoker = proxy.getInvoker(demo, DemoService.class, serviceurl); protocol.export(invoker); - - //SERVER + // SERVER Thread.sleep(Integer.MAX_VALUE); } + @Disabled @Test public void testGenericEnum() throws InterruptedException { int port = NetUtils.getAvailablePort(); - URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE - ); + URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE); DemoService demo = new DemoServiceImpl(); Invoker invoker = proxy.getInvoker(demo, DemoService.class, serviceurl); protocol.export(invoker); @@ -192,7 +195,8 @@ public class EnumBak { Invoker reference = protocol.refer(GenericService.class, consumerurl); GenericService demoProxy = (GenericService) proxy.getProxy(reference); - Object obj = demoProxy.$invoke("enumlength", new String[]{Type[].class.getName()}, new Object[]{new Type[]{Type.High, Type.High}}); + Object obj = demoProxy.$invoke( + "enumlength", new String[] {Type[].class.getName()}, new Object[] {new Type[] {Type.High, Type.High}}); System.out.println("obj---------->" + obj); invoker.destroy(); diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/Man.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/Man.java index 0d584d0213..158acb353e 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/Man.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/Man.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.dubbo.support; - import java.io.Serializable; /** diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/NonSerialized.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/NonSerialized.java index 1ec80e5c0c..8c7ab677b9 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/NonSerialized.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/NonSerialized.java @@ -19,6 +19,4 @@ package org.apache.dubbo.rpc.protocol.dubbo.support; /** * NonSerialized */ -public class NonSerialized { - -} +public class NonSerialized {} diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/ProtocolUtils.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/ProtocolUtils.java index e614b2652e..625dc6b198 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/ProtocolUtils.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/ProtocolUtils.java @@ -29,21 +29,22 @@ import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; */ public class ProtocolUtils { - public static T refer(Class type, String url) { return refer(type, URL.valueOf(url)); } public static T refer(Class type, URL url) { FrameworkModel frameworkModel = url.getOrDefaultFrameworkModel(); - ProxyFactory proxy = frameworkModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + ProxyFactory proxy = + frameworkModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Protocol protocol = frameworkModel.getExtensionLoader(Protocol.class).getAdaptiveExtension(); return proxy.getProxy(protocol.refer(type, url)); } public static Invoker referInvoker(Class type, URL url) { FrameworkModel frameworkModel = url.getOrDefaultFrameworkModel(); - ProxyFactory proxy = frameworkModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + ProxyFactory proxy = + frameworkModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Protocol protocol = frameworkModel.getExtensionLoader(Protocol.class).getAdaptiveExtension(); return (Invoker) protocol.refer(type, url); } @@ -54,7 +55,8 @@ public class ProtocolUtils { public static Exporter export(T instance, Class type, URL url) { FrameworkModel frameworkModel = url.getOrDefaultFrameworkModel(); - ProxyFactory proxy = frameworkModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + ProxyFactory proxy = + frameworkModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Protocol protocol = frameworkModel.getExtensionLoader(Protocol.class).getAdaptiveExtension(); return protocol.export(proxy.getInvoker(instance, type, url)); } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/RemoteServiceImpl.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/RemoteServiceImpl.java index 0c0cd09f6e..88f6520830 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/RemoteServiceImpl.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/RemoteServiceImpl.java @@ -22,7 +22,8 @@ import java.rmi.RemoteException; public class RemoteServiceImpl implements RemoteService { public String getThreadName() throws RemoteException { - System.out.println("RpcContext.getServerAttachment().getRemoteHost()=" + RpcContext.getServiceContext().getRemoteHost()); + System.out.println("RpcContext.getServerAttachment().getRemoteHost()=" + + RpcContext.getServiceContext().getRemoteHost()); return Thread.currentThread().getName(); } diff --git a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/Type.java b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/Type.java index 984c6c6436..51715e99cc 100644 --- a/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/Type.java +++ b/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/Type.java @@ -17,5 +17,7 @@ package org.apache.dubbo.rpc.protocol.dubbo.support; public enum Type { - High, Normal, Lower + High, + Normal, + Lower } diff --git a/dubbo-rpc/dubbo-rpc-injvm/pom.xml b/dubbo-rpc/dubbo-rpc-injvm/pom.xml index a74078d832..66d86080a3 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/pom.xml +++ b/dubbo-rpc/dubbo-rpc-injvm/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-rpc - ${revision} - ../pom.xml - - dubbo-rpc-injvm - jar - ${project.artifactId} - The injvm rpc module of dubbo project - - false - - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.parent.version} - test - - + 4.0.0 + + org.apache.dubbo + dubbo-rpc + ${revision} + ../pom.xml + + dubbo-rpc-injvm + jar + ${project.artifactId} + The injvm rpc module of dubbo project + + false + + + + org.apache.dubbo + dubbo-rpc-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.parent.version} + test + + diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/DefaultParamDeepCopyUtil.java b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/DefaultParamDeepCopyUtil.java index c02bdd34f9..0b6ede8afe 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/DefaultParamDeepCopyUtil.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/DefaultParamDeepCopyUtil.java @@ -31,15 +31,17 @@ import java.io.IOException; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_DESERIALIZE; public class DefaultParamDeepCopyUtil implements ParamDeepCopyUtil { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DefaultParamDeepCopyUtil.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(DefaultParamDeepCopyUtil.class); - public final static String NAME = "default"; + public static final String NAME = "default"; @Override @SuppressWarnings({"unchecked"}) public T copy(URL url, Object src, Class targetClass) { - Serialization serialization = url.getOrDefaultFrameworkModel().getExtensionLoader(Serialization.class).getExtension( - UrlUtils.serializationOrDefault(url)); + Serialization serialization = url.getOrDefaultFrameworkModel() + .getExtensionLoader(Serialization.class) + .getExtension(UrlUtils.serializationOrDefault(url)); try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { ObjectOutput objectOutput = serialization.serialize(url, outputStream); @@ -57,7 +59,6 @@ public class DefaultParamDeepCopyUtil implements ParamDeepCopyUtil { logger.error(PROTOCOL_ERROR_DESERIALIZE, "", "", "Unable to deep copy parameter to target class.", e); } - if (src.getClass().equals(targetClass)) { return (T) src; } else { diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmExporter.java b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmExporter.java index bc38844265..f0fdbb1df1 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmExporter.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmExporter.java @@ -42,5 +42,4 @@ public class InjvmExporter extends AbstractExporter { public void afterUnExport() { exporterMap.remove(key); } - } diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmInvoker.java b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmInvoker.java index 0ebdca71e8..8712d20230 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmInvoker.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmInvoker.java @@ -72,15 +72,17 @@ public class InjvmInvoker extends AbstractInvoker { private final boolean shouldIgnoreSameModule; - private static final boolean setFutureWhenSync = Boolean.parseBoolean(System.getProperty(CommonConstants.SET_FUTURE_IN_SYNC_MODE, "true")); + private static final boolean setFutureWhenSync = + Boolean.parseBoolean(System.getProperty(CommonConstants.SET_FUTURE_IN_SYNC_MODE, "true")); InjvmInvoker(Class type, URL url, String key, Map> exporterMap) { super(type, url); this.key = key; this.exporterMap = exporterMap; this.executorRepository = ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()); - this.paramDeepCopyUtil = url.getOrDefaultFrameworkModel().getExtensionLoader(ParamDeepCopyUtil.class) - .getExtension(url.getParameter(CommonConstants.INJVM_COPY_UTIL_KEY, DefaultParamDeepCopyUtil.NAME)); + this.paramDeepCopyUtil = url.getOrDefaultFrameworkModel() + .getExtensionLoader(ParamDeepCopyUtil.class) + .getExtension(url.getParameter(CommonConstants.INJVM_COPY_UTIL_KEY, DefaultParamDeepCopyUtil.NAME)); this.shouldIgnoreSameModule = url.getParameter(CommonConstants.INJVM_IGNORE_SAME_MODULE_KEY, false); } @@ -111,18 +113,22 @@ public class InjvmInvoker extends AbstractInvoker { } if (consumerUrl == null) { // no need to sync, multi-objects is acceptable and will be gc-ed. - consumerUrl = new DubboServiceAddressURL(serverURL.getUrlAddress(), serverURL.getUrlParam(), getUrl(), null); + consumerUrl = + new DubboServiceAddressURL(serverURL.getUrlAddress(), serverURL.getUrlParam(), getUrl(), null); } - int timeout = RpcUtils.calculateTimeout(consumerUrl, invocation, RpcUtils.getMethodName(invocation), DEFAULT_TIMEOUT); + int timeout = + RpcUtils.calculateTimeout(consumerUrl, invocation, RpcUtils.getMethodName(invocation), DEFAULT_TIMEOUT); if (timeout <= 0) { - return AsyncRpcResult.newDefaultAsyncResult(new RpcException(RpcException.TIMEOUT_TERMINATE, - "No time left for making the following call: " + invocation.getServiceName() + "." - + RpcUtils.getMethodName(invocation) + ", terminate directly."), invocation); + return AsyncRpcResult.newDefaultAsyncResult( + new RpcException( + RpcException.TIMEOUT_TERMINATE, + "No time left for making the following call: " + invocation.getServiceName() + "." + + RpcUtils.getMethodName(invocation) + ", terminate directly."), + invocation); } invocation.setAttachment(TIMEOUT_KEY, String.valueOf(timeout)); - String desc = ReflectUtils.getDesc(invocation.getParameterTypes()); // recreate invocation ---> deep copy parameters @@ -131,28 +137,31 @@ public class InjvmInvoker extends AbstractInvoker { if (isAsync(invoker.getUrl(), getUrl())) { ((RpcInvocation) copiedInvocation).setInvokeMode(InvokeMode.ASYNC); // use consumer executor - ExecutorService executor = executorRepository.createExecutorIfAbsent(ExecutorUtil.setThreadName(getUrl(), SERVER_THREAD_POOL_NAME)); - CompletableFuture appResponseFuture = CompletableFuture.supplyAsync(() -> { - // clear thread local before child invocation, prevent context pollution - InternalThreadLocalMap originTL = InternalThreadLocalMap.getAndRemove(); - try { - RpcContext.getServiceContext().setRemoteAddress(LOCALHOST_VALUE, 0); - RpcContext.getServiceContext().setRemoteApplicationName(getUrl().getApplication()); - Result result = invoker.invoke(copiedInvocation); - if (result.hasException()) { - AppResponse appResponse = new AppResponse(result.getException()); - appResponse.setObjectAttachments(new HashMap<>(result.getObjectAttachments())); - return appResponse; - } else { - rebuildValue(invocation, desc, result); - AppResponse appResponse = new AppResponse(result.getValue()); - appResponse.setObjectAttachments(new HashMap<>(result.getObjectAttachments())); - return appResponse; - } - } finally { - InternalThreadLocalMap.set(originTL); - } - }, executor); + ExecutorService executor = executorRepository.createExecutorIfAbsent( + ExecutorUtil.setThreadName(getUrl(), SERVER_THREAD_POOL_NAME)); + CompletableFuture appResponseFuture = CompletableFuture.supplyAsync( + () -> { + // clear thread local before child invocation, prevent context pollution + InternalThreadLocalMap originTL = InternalThreadLocalMap.getAndRemove(); + try { + RpcContext.getServiceContext().setRemoteAddress(LOCALHOST_VALUE, 0); + RpcContext.getServiceContext().setRemoteApplicationName(getUrl().getApplication()); + Result result = invoker.invoke(copiedInvocation); + if (result.hasException()) { + AppResponse appResponse = new AppResponse(result.getException()); + appResponse.setObjectAttachments(new HashMap<>(result.getObjectAttachments())); + return appResponse; + } else { + rebuildValue(invocation, desc, result); + AppResponse appResponse = new AppResponse(result.getValue()); + appResponse.setObjectAttachments(new HashMap<>(result.getObjectAttachments())); + return appResponse; + } + } finally { + InternalThreadLocalMap.set(originTL); + } + }, + executor); // save for 2.6.x compatibility, for example, TraceFilter in Zipkin uses com.alibaba.xxx.FutureAdapter if (setFutureWhenSync || ((RpcInvocation) invocation).getInvokeMode() != InvokeMode.SYNC) { FutureContext.getContext().setCompatibleFuture(appResponseFuture); @@ -199,7 +208,6 @@ public class InjvmInvoker extends AbstractInvoker { future.complete(rpcResult); } return new AsyncRpcResult(future, invocation); - } } @@ -225,15 +233,23 @@ public class InjvmInvoker extends AbstractInvoker { String methodName = invocation.getMethodName(); ServiceModel consumerServiceModel = invocation.getServiceModel(); - boolean shouldSkip = shouldIgnoreSameModule && consumerServiceModel != null && - Objects.equals(providerServiceModel.getModuleModel(), consumerServiceModel.getModuleModel()); + boolean shouldSkip = shouldIgnoreSameModule + && consumerServiceModel != null + && Objects.equals(providerServiceModel.getModuleModel(), consumerServiceModel.getModuleModel()); if (CommonConstants.$INVOKE.equals(methodName) || shouldSkip) { // generic invoke, skip copy arguments - RpcInvocation copiedInvocation = new RpcInvocation(invocation.getTargetServiceUniqueName(), - providerServiceModel, methodName, invocation.getServiceName(), invocation.getProtocolServiceKey(), - invocation.getParameterTypes(), invocation.getArguments(), invocation.copyObjectAttachments(), - invocation.getInvoker(), new HashMap<>(), - invocation instanceof RpcInvocation ? ((RpcInvocation) invocation).getInvokeMode() : null); + RpcInvocation copiedInvocation = new RpcInvocation( + invocation.getTargetServiceUniqueName(), + providerServiceModel, + methodName, + invocation.getServiceName(), + invocation.getProtocolServiceKey(), + invocation.getParameterTypes(), + invocation.getArguments(), + invocation.copyObjectAttachments(), + invocation.getInvoker(), + new HashMap<>(), + invocation instanceof RpcInvocation ? ((RpcInvocation) invocation).getInvokeMode() : null); copiedInvocation.setInvoker(invoker); return copiedInvocation; } @@ -259,11 +275,18 @@ public class InjvmInvoker extends AbstractInvoker { realArgument = args; } - RpcInvocation copiedInvocation = new RpcInvocation(invocation.getTargetServiceUniqueName(), - providerServiceModel, methodName, invocation.getServiceName(), invocation.getProtocolServiceKey(), - pts, realArgument, invocation.copyObjectAttachments(), - invocation.getInvoker(), new HashMap<>(), - invocation instanceof RpcInvocation ? ((RpcInvocation) invocation).getInvokeMode() : null); + RpcInvocation copiedInvocation = new RpcInvocation( + invocation.getTargetServiceUniqueName(), + providerServiceModel, + methodName, + invocation.getServiceName(), + invocation.getProtocolServiceKey(), + pts, + realArgument, + invocation.copyObjectAttachments(), + invocation.getInvoker(), + new HashMap<>(), + invocation instanceof RpcInvocation ? ((RpcInvocation) invocation).getInvokeMode() : null); copiedInvocation.setInvoker(invoker); return copiedInvocation; } finally { diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java index 9f361054f3..c4955e7ce7 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/main/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocol.java @@ -83,7 +83,6 @@ public class InjvmProtocol extends AbstractProtocol { return new InjvmInvoker(serviceType, url, url.getServiceKey(), exporterMap); } - public boolean isInjvmRefer(URL url) { String scope = url.getParameter(SCOPE_KEY); // Since injvm protocol is configured explicitly, we don't need to set any extra flag, use normal refer process. diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/Empty.java b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/Empty.java index 6a9678c25c..cd89dd14ba 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/Empty.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/Empty.java @@ -16,5 +16,4 @@ */ package demo; -public class Empty { -} +public class Empty {} diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/MultiClassLoaderServiceImpl.java b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/MultiClassLoaderServiceImpl.java index b315aa2e4e..b546238ef3 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/MultiClassLoaderServiceImpl.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/MultiClassLoaderServiceImpl.java @@ -22,7 +22,9 @@ public class MultiClassLoaderServiceImpl implements MultiClassLoaderService { private AtomicReference innerRequestReference; private AtomicReference innerResultReference; - public MultiClassLoaderServiceImpl(AtomicReference innerRequestReference, AtomicReference innerResultReference) { + public MultiClassLoaderServiceImpl( + AtomicReference innerRequestReference, + AtomicReference innerResultReference) { this.innerRequestReference = innerRequestReference; this.innerResultReference = innerResultReference; } diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/MultiClassLoaderServiceRequest.java b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/MultiClassLoaderServiceRequest.java index 9dd67ca5a5..0d07661d13 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/MultiClassLoaderServiceRequest.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/MultiClassLoaderServiceRequest.java @@ -18,5 +18,4 @@ package demo; import java.io.Serializable; -public class MultiClassLoaderServiceRequest implements Serializable { -} +public class MultiClassLoaderServiceRequest implements Serializable {} diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/MultiClassLoaderServiceResult.java b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/MultiClassLoaderServiceResult.java index c4ed2aa702..f4d2b96a45 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/MultiClassLoaderServiceResult.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/demo/MultiClassLoaderServiceResult.java @@ -18,5 +18,4 @@ package demo; import java.io.Serializable; -public class MultiClassLoaderServiceResult implements Serializable { -} +public class MultiClassLoaderServiceResult implements Serializable {} diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/DemoRequest.java b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/DemoRequest.java index 3925531c88..d9f580037e 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/DemoRequest.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/DemoRequest.java @@ -21,7 +21,6 @@ import java.io.Serializable; /** * TestRequest. */ - class DemoRequest implements Serializable { private static final long serialVersionUID = -2579095288792344869L; diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/DemoService.java b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/DemoService.java index 9a09ed9617..0009ff5b00 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/DemoService.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/DemoService.java @@ -19,7 +19,6 @@ package org.apache.dubbo.rpc.protocol.injvm; /** * TestService */ - public interface DemoService { void sayHello(String name); diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/DemoServiceImpl.java b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/DemoServiceImpl.java index b4d2314a6d..7d364b2bcc 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/DemoServiceImpl.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/DemoServiceImpl.java @@ -21,7 +21,6 @@ import org.apache.dubbo.rpc.RpcContext; /** * DemoServiceImpl */ - public class DemoServiceImpl implements DemoService { public DemoServiceImpl() { super(); @@ -44,25 +43,23 @@ public class DemoServiceImpl implements DemoService { } public int getSize(String[] strs) { - if (strs == null) - return -1; + if (strs == null) return -1; return strs.length; } public int getSize(Object[] os) { - if (os == null) - return -1; + if (os == null) return -1; return os.length; } public Object invoke(String service, String method) throws Exception { - System.out.println("RpcContext.getServerAttachment().getRemoteHost()=" + RpcContext.getServiceContext().getRemoteHost()); + System.out.println("RpcContext.getServerAttachment().getRemoteHost()=" + + RpcContext.getServiceContext().getRemoteHost()); return service + ":" + method; } public Type enumlength(Type... types) { - if (types.length == 0) - return Type.Lower; + if (types.length == 0) return Type.Lower; return types[0]; } diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmClassLoaderTest.java b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmClassLoaderTest.java index a12c1893a5..45534ff5ba 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmClassLoaderTest.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmClassLoaderTest.java @@ -31,18 +31,6 @@ import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; -import demo.Empty; -import demo.MultiClassLoaderService; -import demo.MultiClassLoaderServiceImpl; -import demo.MultiClassLoaderServiceRequest; -import demo.MultiClassLoaderServiceResult; -import javassist.CannotCompileException; -import javassist.ClassPool; -import javassist.CtClass; -import javassist.NotFoundException; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -50,11 +38,27 @@ import java.lang.reflect.Constructor; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReference; +import javassist.CannotCompileException; +import javassist.ClassPool; +import javassist.CtClass; +import javassist.NotFoundException; + +import demo.Empty; +import demo.MultiClassLoaderService; +import demo.MultiClassLoaderServiceImpl; +import demo.MultiClassLoaderServiceRequest; +import demo.MultiClassLoaderServiceResult; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; class InjvmClassLoaderTest { @Test void testDifferentClassLoaderRequest() throws Exception { - String basePath = DemoService.class.getProtectionDomain().getCodeSource().getLocation().getFile(); + String basePath = DemoService.class + .getProtectionDomain() + .getCodeSource() + .getLocation() + .getFile(); basePath = java.net.URLDecoder.decode(basePath, "UTF-8"); TestClassLoader1 classLoader1 = new TestClassLoader1(basePath); TestClassLoader1 classLoader2 = new TestClassLoader1(basePath); @@ -76,22 +80,21 @@ class InjvmClassLoaderTest { AtomicReference innerRequestReference = new AtomicReference(); AtomicReference innerResultReference = new AtomicReference(); innerResultReference.set(resultClazzCustom1.getDeclaredConstructor().newInstance()); - Constructor declaredConstructor = clazz1impl.getDeclaredConstructor(AtomicReference.class, AtomicReference.class); - + Constructor declaredConstructor = + clazz1impl.getDeclaredConstructor(AtomicReference.class, AtomicReference.class); // export provider - ProxyFactory proxyFactory = moduleModel.getExtensionLoader(ProxyFactory.class).getExtension("javassist"); + ProxyFactory proxyFactory = + moduleModel.getExtensionLoader(ProxyFactory.class).getExtension("javassist"); Protocol protocol = moduleModel.getExtensionLoader(Protocol.class).getAdaptiveExtension(); Object providerInstance = declaredConstructor.newInstance(innerRequestReference, innerResultReference); - URL url = URL.valueOf("injvm://localhost:0/" + MultiClassLoaderServiceImpl.class.getName() + "?interface=" + MultiClassLoaderServiceImpl.class.getName()); - ServiceDescriptor providerServiceDescriptor = moduleModel.getServiceRepository().registerService(clazz1); - ProviderModel providerModel = new ProviderModel( - url.getServiceKey(), - providerInstance, - providerServiceDescriptor, - null, - null); + URL url = URL.valueOf("injvm://localhost:0/" + MultiClassLoaderServiceImpl.class.getName() + "?interface=" + + MultiClassLoaderServiceImpl.class.getName()); + ServiceDescriptor providerServiceDescriptor = + moduleModel.getServiceRepository().registerService(clazz1); + ProviderModel providerModel = + new ProviderModel(url.getServiceKey(), providerInstance, providerServiceDescriptor, null, null); providerModel.setClassLoader(classLoader1); URL providerUrl = url.setScopeModel(moduleModel).setServiceModel(providerModel); @@ -106,9 +109,16 @@ class InjvmClassLoaderTest { classLoader3.loadedClass.put(resultClazzCustom3.getName(), resultClazzCustom3); // refer consumer - ServiceDescriptor consumerServiceDescriptor = moduleModel.getServiceRepository().registerService(clazz2); - ConsumerModel consumerModel = new ConsumerModel(clazz2.getName(), null, consumerServiceDescriptor, - ApplicationModel.defaultModel().getDefaultModule(), null, null, ClassUtils.getClassLoader(clazz2)); + ServiceDescriptor consumerServiceDescriptor = + moduleModel.getServiceRepository().registerService(clazz2); + ConsumerModel consumerModel = new ConsumerModel( + clazz2.getName(), + null, + consumerServiceDescriptor, + ApplicationModel.defaultModel().getDefaultModule(), + null, + null, + ClassUtils.getClassLoader(clazz2)); consumerModel.setClassLoader(classLoader3); URL consumerUrl = url.setScopeModel(moduleModel).setServiceModel(consumerModel); @@ -116,20 +126,23 @@ class InjvmClassLoaderTest { java.lang.reflect.Method callBean1 = object1.getClass().getDeclaredMethod("call", requestClazzOrigin); callBean1.setAccessible(true); - Object result1 = callBean1.invoke(object1, requestClazzCustom2.getDeclaredConstructor().newInstance()); + Object result1 = callBean1.invoke( + object1, requestClazzCustom2.getDeclaredConstructor().newInstance()); // invoke result should load from classLoader3 ( sub classLoader of classLoader2 --> consumer side classLoader) Assertions.assertEquals(resultClazzCustom3, result1.getClass()); Assertions.assertNotEquals(classLoader2, result1.getClass().getClassLoader()); // invoke reqeust param should load from classLoader1 ( provider side classLoader ) - Assertions.assertEquals(classLoader1, innerRequestReference.get().getClass().getClassLoader()); + Assertions.assertEquals( + classLoader1, innerRequestReference.get().getClass().getClassLoader()); exporter.unexport(); applicationModel.destroy(); } - private Class compileCustomRequest(ClassLoader classLoader) throws NotFoundException, CannotCompileException, ClassNotFoundException { + private Class compileCustomRequest(ClassLoader classLoader) + throws NotFoundException, CannotCompileException, ClassNotFoundException { CtClassBuilder builder = new CtClassBuilder(); builder.setClassName(MultiClassLoaderServiceRequest.class.getName() + "A"); builder.setSuperClassName(MultiClassLoaderServiceRequest.class.getName()); @@ -138,10 +151,15 @@ class InjvmClassLoaderTest { if (classLoader == null) { classLoader = cp.getClassLoader(); } - return cp.toClass(cls, classLoader.loadClass(Empty.class.getName()), classLoader, JavassistCompiler.class.getProtectionDomain()); + return cp.toClass( + cls, + classLoader.loadClass(Empty.class.getName()), + classLoader, + JavassistCompiler.class.getProtectionDomain()); } - private Class compileCustomResult(ClassLoader classLoader) throws NotFoundException, CannotCompileException, ClassNotFoundException { + private Class compileCustomResult(ClassLoader classLoader) + throws NotFoundException, CannotCompileException, ClassNotFoundException { CtClassBuilder builder = new CtClassBuilder(); builder.setClassName(MultiClassLoaderServiceResult.class.getName() + "A"); builder.setSuperClassName(MultiClassLoaderServiceResult.class.getName()); @@ -150,7 +168,11 @@ class InjvmClassLoaderTest { if (classLoader == null) { classLoader = cp.getClassLoader(); } - return cp.toClass(cls, classLoader.loadClass(Empty.class.getName()), classLoader, JavassistCompiler.class.getProtectionDomain()); + return cp.toClass( + cls, + classLoader.loadClass(Empty.class.getName()), + classLoader, + JavassistCompiler.class.getProtectionDomain()); } private static class TestClassLoader1 extends ClassLoader { @@ -178,7 +200,8 @@ class InjvmClassLoaderTest { return loadedClass.get(name); } if (name.startsWith("demo")) { - if (name.equals(MultiClassLoaderServiceRequest.class.getName()) || name.equals(MultiClassLoaderServiceResult.class.getName())) { + if (name.equals(MultiClassLoaderServiceRequest.class.getName()) + || name.equals(MultiClassLoaderServiceResult.class.getName())) { return super.loadClass(name, resolve); } Class aClass = this.findClass(name); @@ -197,7 +220,6 @@ class InjvmClassLoaderTest { } } - public byte[] loadClassData(String className) throws IOException { className = className.replaceAll("\\.", "/"); String path = basePath + File.separator + className + ".class"; @@ -250,7 +272,6 @@ class InjvmClassLoaderTest { } } - public byte[] loadClassData(String className) throws IOException { className = className.replaceAll("\\.", "/"); String path = basePath + File.separator + className + ".class"; diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmDeepCopyTest.java b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmDeepCopyTest.java index 80c7fba273..7ba3348030 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmDeepCopyTest.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmDeepCopyTest.java @@ -29,12 +29,12 @@ import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.io.Serializable; import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class InjvmDeepCopyTest { @Test @@ -49,26 +49,32 @@ class InjvmDeepCopyTest { Demo demo = new Demo(requestReference, responseReference); // export provider - ProxyFactory proxyFactory = moduleModel.getExtensionLoader(ProxyFactory.class).getExtension("javassist"); + ProxyFactory proxyFactory = + moduleModel.getExtensionLoader(ProxyFactory.class).getExtension("javassist"); Protocol protocol = moduleModel.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - URL url = URL.valueOf("injvm://localhost:0/" + DemoInterface.class.getName() + "?interface=" + DemoInterface.class.getName()); - ServiceDescriptor providerServiceDescriptor = moduleModel.getServiceRepository().registerService(DemoInterface.class); - ProviderModel providerModel = new ProviderModel( - url.getServiceKey(), - demo, - providerServiceDescriptor, - null, - null); + URL url = URL.valueOf( + "injvm://localhost:0/" + DemoInterface.class.getName() + "?interface=" + DemoInterface.class.getName()); + ServiceDescriptor providerServiceDescriptor = + moduleModel.getServiceRepository().registerService(DemoInterface.class); + ProviderModel providerModel = + new ProviderModel(url.getServiceKey(), demo, providerServiceDescriptor, null, null); URL providerUrl = url.setScopeModel(moduleModel).setServiceModel(providerModel); Invoker invoker = proxyFactory.getInvoker(demo, DemoInterface.class, providerUrl); Exporter exporter = protocol.export(invoker); // refer consumer - ServiceDescriptor consumerServiceDescriptor = moduleModel.getServiceRepository().registerService(DemoInterface.class); - ConsumerModel consumerModel = new ConsumerModel(DemoInterface.class.getName(), null, consumerServiceDescriptor, - ApplicationModel.defaultModel().getDefaultModule(), null, null, ClassUtils.getClassLoader(DemoInterface.class)); + ServiceDescriptor consumerServiceDescriptor = + moduleModel.getServiceRepository().registerService(DemoInterface.class); + ConsumerModel consumerModel = new ConsumerModel( + DemoInterface.class.getName(), + null, + consumerServiceDescriptor, + ApplicationModel.defaultModel().getDefaultModule(), + null, + null, + ClassUtils.getClassLoader(DemoInterface.class)); URL consumerUrl = url.setScopeModel(moduleModel).setServiceModel(consumerModel); DemoInterface stub = proxyFactory.getProxy(protocol.refer(DemoInterface.class, consumerUrl)); @@ -114,7 +120,5 @@ class InjvmDeepCopyTest { } } - private static class Data implements Serializable { - - } + private static class Data implements Serializable {} } diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java index 3ef342e8ea..983784da0b 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/InjvmProtocolTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.injvm; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.StringUtils; @@ -29,14 +28,14 @@ import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.ExecutionException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; @@ -55,12 +54,12 @@ import static org.junit.jupiter.api.Assertions.assertTrue; /** * ProxiesTest */ - class InjvmProtocolTest { - - private final Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - private final ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + private final Protocol protocol = + ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); + private final ProxyFactory proxy = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); private final List> exporters = new ArrayList<>(); @AfterEach @@ -74,47 +73,61 @@ class InjvmProtocolTest { @Test void testLocalProtocol() throws Exception { DemoService service = new DemoServiceImpl(); - Invoker invoker = proxy.getInvoker(service, DemoService.class, URL.valueOf("injvm://127.0.0.1/TestService").addParameter(INTERFACE_KEY, DemoService.class.getName()) - .setScopeModel(ApplicationModel.defaultModel().getDefaultModule())); + Invoker invoker = proxy.getInvoker( + service, + DemoService.class, + URL.valueOf("injvm://127.0.0.1/TestService") + .addParameter(INTERFACE_KEY, DemoService.class.getName()) + .setScopeModel(ApplicationModel.defaultModel().getDefaultModule())); assertTrue(invoker.isAvailable()); Exporter exporter = protocol.export(invoker); exporters.add(exporter); - service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("injvm://127.0.0.1/TestService").addParameter(INTERFACE_KEY, DemoService.class.getName()) - .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()))); - assertEquals(service.getSize(new String[]{"", "", ""}), 3); + service = proxy.getProxy(protocol.refer( + DemoService.class, + URL.valueOf("injvm://127.0.0.1/TestService") + .addParameter(INTERFACE_KEY, DemoService.class.getName()) + .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()))); + assertEquals(service.getSize(new String[] {"", "", ""}), 3); service.invoke("injvm://127.0.0.1/TestService", "invoke"); - InjvmInvoker injvmInvoker = new InjvmInvoker<>(DemoService.class, URL.valueOf("injvm://127.0.0.1/TestService"), null, new HashMap<>()); + InjvmInvoker injvmInvoker = new InjvmInvoker<>( + DemoService.class, URL.valueOf("injvm://127.0.0.1/TestService"), null, new HashMap<>()); assertFalse(injvmInvoker.isAvailable()); - } @Test void testLocalProtocolWithToken() { DemoService service = new DemoServiceImpl(); - Invoker invoker = proxy.getInvoker(service, DemoService.class, URL.valueOf("injvm://127.0.0.1/TestService?token=abc").addParameter(INTERFACE_KEY, DemoService.class.getName()) - .setScopeModel(ApplicationModel.defaultModel().getDefaultModule())); + Invoker invoker = proxy.getInvoker( + service, + DemoService.class, + URL.valueOf("injvm://127.0.0.1/TestService?token=abc") + .addParameter(INTERFACE_KEY, DemoService.class.getName()) + .setScopeModel(ApplicationModel.defaultModel().getDefaultModule())); assertTrue(invoker.isAvailable()); Exporter exporter = protocol.export(invoker); exporters.add(exporter); - service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("injvm://127.0.0.1/TestService").addParameter(INTERFACE_KEY, DemoService.class.getName()) - .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()))); - assertEquals(service.getSize(new String[]{"", "", ""}), 3); + service = proxy.getProxy(protocol.refer( + DemoService.class, + URL.valueOf("injvm://127.0.0.1/TestService") + .addParameter(INTERFACE_KEY, DemoService.class.getName()) + .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()))); + assertEquals(service.getSize(new String[] {"", "", ""}), 3); } @Test void testIsInjvmRefer() { DemoService service = new DemoServiceImpl(); URL url = URL.valueOf("injvm://127.0.0.1/TestService") - .addParameter(INTERFACE_KEY, DemoService.class.getName()).setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); + .addParameter(INTERFACE_KEY, DemoService.class.getName()) + .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Exporter exporter = protocol.export(proxy.getInvoker(service, DemoService.class, url)); exporters.add(exporter); url = url.setProtocol("dubbo"); assertTrue(InjvmProtocol.getInjvmProtocol(FrameworkModel.defaultModel()).isInjvmRefer(url)); - url = url.addParameter(GROUP_KEY, "*") - .addParameter(VERSION_KEY, "*"); + url = url.addParameter(GROUP_KEY, "*").addParameter(VERSION_KEY, "*"); assertTrue(InjvmProtocol.getInjvmProtocol(FrameworkModel.defaultModel()).isInjvmRefer(url)); url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(SCOPE_KEY, SCOPE_LOCAL); @@ -124,22 +137,26 @@ class InjvmProtocolTest { assertTrue(InjvmProtocol.getInjvmProtocol(FrameworkModel.defaultModel()).isInjvmRefer(url)); url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(SCOPE_KEY, SCOPE_REMOTE); - assertFalse(InjvmProtocol.getInjvmProtocol(FrameworkModel.defaultModel()).isInjvmRefer(url)); + assertFalse( + InjvmProtocol.getInjvmProtocol(FrameworkModel.defaultModel()).isInjvmRefer(url)); url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(GENERIC_KEY, true); - assertFalse(InjvmProtocol.getInjvmProtocol(FrameworkModel.defaultModel()).isInjvmRefer(url)); + assertFalse( + InjvmProtocol.getInjvmProtocol(FrameworkModel.defaultModel()).isInjvmRefer(url)); url = URL.valueOf("fake://127.0.0.1/TestService").addParameter("cluster", "broadcast"); - assertFalse(InjvmProtocol.getInjvmProtocol(FrameworkModel.defaultModel()).isInjvmRefer(url)); + assertFalse( + InjvmProtocol.getInjvmProtocol(FrameworkModel.defaultModel()).isInjvmRefer(url)); } @Test void testLocalProtocolAsync() throws ExecutionException, InterruptedException { DemoService service = new DemoServiceImpl(); URL url = URL.valueOf("injvm://127.0.0.1/TestService") - .addParameter(ASYNC_KEY, true) - .addParameter(INTERFACE_KEY, DemoService.class.getName()).addParameter("application", "consumer") - .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); + .addParameter(ASYNC_KEY, true) + .addParameter(INTERFACE_KEY, DemoService.class.getName()) + .addParameter("application", "consumer") + .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Invoker invoker = proxy.getInvoker(service, DemoService.class, url); assertTrue(invoker.isAvailable()); Exporter exporter = protocol.export(invoker); @@ -153,9 +170,10 @@ class InjvmProtocolTest { void testApplication() { DemoService service = new DemoServiceImpl(); URL url = URL.valueOf("injvm://127.0.0.1/TestService") - .addParameter(INTERFACE_KEY, DemoService.class.getName()).addParameter("application", "consumer") - .addParameter(APPLICATION_KEY, "test-app") - .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); + .addParameter(INTERFACE_KEY, DemoService.class.getName()) + .addParameter("application", "consumer") + .addParameter(APPLICATION_KEY, "test-app") + .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Invoker invoker = proxy.getInvoker(service, DemoService.class, url); assertTrue(invoker.isAvailable()); Exporter exporter = protocol.export(invoker); @@ -169,9 +187,10 @@ class InjvmProtocolTest { void testRemoteAddress() { DemoService service = new DemoServiceImpl(); URL url = URL.valueOf("injvm://127.0.0.1/TestService") - .addParameter(INTERFACE_KEY, DemoService.class.getName()).addParameter("application", "consumer") - .addParameter(APPLICATION_KEY, "test-app") - .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); + .addParameter(INTERFACE_KEY, DemoService.class.getName()) + .addParameter("application", "consumer") + .addParameter(APPLICATION_KEY, "test-app") + .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Invoker invoker = proxy.getInvoker(service, DemoService.class, url); assertTrue(invoker.isAvailable()); Exporter exporter = protocol.export(invoker); @@ -180,5 +199,4 @@ class InjvmProtocolTest { assertEquals("127.0.0.1:0", service.getRemoteAddress()); assertNull(RpcContext.getServiceContext().getRemoteAddress()); } - } diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/ProtocolTest.java b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/ProtocolTest.java index a2d578fac1..0a683d0968 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/ProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/ProtocolTest.java @@ -42,17 +42,22 @@ class ProtocolTest { InjvmProtocol injvm = InjvmProtocol.getInjvmProtocol(FrameworkModel.defaultModel()); } - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getExtension("javassist"); + ProxyFactory proxyFactory = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getExtension("javassist"); - URL url = URL.valueOf("injvm://localhost:0/org.apache.dubbo.rpc.support.IEcho?interface=org.apache.dubbo.rpc.support.IEcho").setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); + URL url = URL.valueOf( + "injvm://localhost:0/org.apache.dubbo.rpc.support.IEcho?interface=org.apache.dubbo.rpc.support.IEcho") + .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); Invoker invoker = proxyFactory.getInvoker(echo, IEcho.class, url); @Test void test_destroyWontCloseAllProtocol() throws Exception { - Protocol autowireProtocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); + Protocol autowireProtocol = + ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - Protocol InjvmProtocol = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("injvm"); + Protocol InjvmProtocol = + ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("injvm"); assertEquals(0, InjvmProtocol.getDefaultPort()); @@ -66,7 +71,9 @@ class ProtocolTest { try { autowireProtocol.destroy(); } catch (UnsupportedOperationException expected) { - assertThat(expected.getMessage(), containsString("of interface org.apache.dubbo.rpc.Protocol is not adaptive method!")); + assertThat( + expected.getMessage(), + containsString("of interface org.apache.dubbo.rpc.Protocol is not adaptive method!")); } assertEquals("ok2", echoProxy.echo("ok2")); diff --git a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/Type.java b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/Type.java index 05f251ede3..fce2ec79cb 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/Type.java +++ b/dubbo-rpc/dubbo-rpc-injvm/src/test/java/org/apache/dubbo/rpc/protocol/injvm/Type.java @@ -17,5 +17,7 @@ package org.apache.dubbo.rpc.protocol.injvm; public enum Type { - High, Normal, Lower + High, + Normal, + Lower } diff --git a/dubbo-rpc/dubbo-rpc-rest/pom.xml b/dubbo-rpc/dubbo-rpc-rest/pom.xml index f583a5ed8f..88c8e4cf08 100644 --- a/dubbo-rpc/dubbo-rpc-rest/pom.xml +++ b/dubbo-rpc/dubbo-rpc-rest/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-rpc - ${revision} - ../pom.xml - - dubbo-rpc-rest - jar - ${project.artifactId} - The rest rpc module of dubbo project - - false - - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-http - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.parent.version} - + 4.0.0 + + org.apache.dubbo + dubbo-rpc + ${revision} + ../pom.xml + + dubbo-rpc-rest + jar + ${project.artifactId} + The rest rpc module of dubbo project + + false + + + + org.apache.dubbo + dubbo-rpc-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-remoting-http + ${project.parent.version} + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.parent.version} + - - org.apache.dubbo - dubbo-cluster - ${project.parent.version} - + + org.apache.dubbo + dubbo-cluster + ${project.parent.version} + - - org.jboss.resteasy - resteasy-jaxrs - provided - + + org.jboss.resteasy + resteasy-jaxrs + provided + - - org.jboss.resteasy - resteasy-client - + + org.jboss.resteasy + resteasy-client + - - javax.validation - validation-api - + + javax.validation + validation-api + - + - - org.jboss.resteasy - resteasy-netty4 - provided - + + org.jboss.resteasy + resteasy-netty4 + provided + - - org.jboss.resteasy - resteasy-jdk-http - provided - + + org.jboss.resteasy + resteasy-jdk-http + provided + - - org.jboss.resteasy - resteasy-jackson-provider - provided - + + org.jboss.resteasy + resteasy-jackson-provider + provided + - - org.jboss.resteasy - resteasy-jaxb-provider - provided - + + org.jboss.resteasy + resteasy-jaxb-provider + provided + - - - io.swagger - swagger-annotations - - - javax.ws.rs - jsr311-api - - - - - io.swagger - swagger-jaxrs - - - javax.ws.rs - jsr311-api - - - + + + io.swagger + swagger-annotations + + + javax.ws.rs + jsr311-api + + + + + io.swagger + swagger-jaxrs + + + javax.ws.rs + jsr311-api + + + - - org.apache.dubbo - dubbo-serialization-jdk - ${project.parent.version} - test - + + org.apache.dubbo + dubbo-serialization-jdk + ${project.parent.version} + test + - - org.apache.dubbo - dubbo-metadata-rest - ${project.parent.version} - + + org.apache.dubbo + dubbo-metadata-rest + ${project.parent.version} + - - io.netty - netty-codec-http - provided - + + io.netty + netty-codec-http + provided + - - io.netty - netty-transport - compile - + + io.netty + netty-transport + compile + - - - org.springframework - spring-web - test - + + + org.springframework + spring-web + test + - - org.springframework - spring-context - test - + + org.springframework + spring-context + test + - - com.google.code.gson - gson - test - - - - org.springframework.cloud - spring-cloud-openfeign-core - test - - + + com.google.code.gson + gson + test + + + + org.springframework.cloud + spring-cloud-openfeign-core + test + + diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/Constants.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/Constants.java index c7d49dd316..5aa43155c4 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/Constants.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/Constants.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.rest; /** @@ -30,5 +29,4 @@ public interface Constants { // http server String NETTY_HTTP = "netty_http"; - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/PathAndInvokerMapper.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/PathAndInvokerMapper.java index c9fea955ec..bf4bcb225b 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/PathAndInvokerMapper.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/PathAndInvokerMapper.java @@ -34,10 +34,13 @@ import java.util.concurrent.ConcurrentHashMap; * save the path & metadata info mapping */ public class PathAndInvokerMapper { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PathAndInvokerMapper.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(PathAndInvokerMapper.class); - private final Map pathToServiceMapContainPathVariable = new ConcurrentHashMap<>(); - private final Map pathToServiceMapNoPathVariable = new ConcurrentHashMap<>(); + private final Map pathToServiceMapContainPathVariable = + new ConcurrentHashMap<>(); + private final Map pathToServiceMapNoPathVariable = + new ConcurrentHashMap<>(); // for http method compare 405 private final Map> pathMatcherToHttpMethodMap = new HashMap<>(); @@ -53,14 +56,19 @@ public class PathAndInvokerMapper { metadataMap.entrySet().stream().forEach(entry -> { PathMatcher pathMatcher = entry.getKey(); if (pathMatcher.hasPathVariable()) { - addPathMatcherToPathMap(pathMatcher, pathToServiceMapContainPathVariable, InvokerAndRestMethodMetadataPair.pair(invoker, entry.getValue())); + addPathMatcherToPathMap( + pathMatcher, + pathToServiceMapContainPathVariable, + InvokerAndRestMethodMetadataPair.pair(invoker, entry.getValue())); } else { - addPathMatcherToPathMap(pathMatcher, pathToServiceMapNoPathVariable, InvokerAndRestMethodMetadataPair.pair(invoker, entry.getValue())); + addPathMatcherToPathMap( + pathMatcher, + pathToServiceMapNoPathVariable, + InvokerAndRestMethodMetadataPair.pair(invoker, entry.getValue())); } }); } - /** * get rest method metadata by path matcher * @@ -80,7 +88,6 @@ public class PathAndInvokerMapper { } return null; - } /** @@ -90,32 +97,39 @@ public class PathAndInvokerMapper { */ public void removePath(PathMatcher pathMatcher) { - InvokerAndRestMethodMetadataPair containPathVariablePair = pathToServiceMapContainPathVariable.remove(pathMatcher); + InvokerAndRestMethodMetadataPair containPathVariablePair = + pathToServiceMapContainPathVariable.remove(pathMatcher); InvokerAndRestMethodMetadataPair unContainPathVariablePair = pathToServiceMapNoPathVariable.remove(pathMatcher); logger.info("dubbo rest undeploy pathMatcher:" + pathMatcher - + ", and path variable method is :" + (containPathVariablePair == null ? null : containPathVariablePair.getRestMethodMetadata().getReflectMethod()) - + ", and no path variable method is :" + (unContainPathVariablePair == null ? null : unContainPathVariablePair.getRestMethodMetadata().getReflectMethod())); - - + + ", and path variable method is :" + + (containPathVariablePair == null + ? null + : containPathVariablePair.getRestMethodMetadata().getReflectMethod()) + + ", and no path variable method is :" + + (unContainPathVariablePair == null + ? null + : unContainPathVariablePair.getRestMethodMetadata().getReflectMethod())); } - public void addPathMatcherToPathMap(PathMatcher pathMatcher, - Map pathMatcherPairMap, - InvokerAndRestMethodMetadataPair invokerRestMethodMetadataPair) { + public void addPathMatcherToPathMap( + PathMatcher pathMatcher, + Map pathMatcherPairMap, + InvokerAndRestMethodMetadataPair invokerRestMethodMetadataPair) { if (pathMatcherPairMap.containsKey(pathMatcher)) { - // cover the old service metadata when current interface is old interface & current method desc equals old`s method desc,else ,throw double check exception + // cover the old service metadata when current interface is old interface & current method desc equals + // old`s method desc,else ,throw double check exception InvokerAndRestMethodMetadataPair beforeMetadata = pathMatcherPairMap.get(pathMatcher); // true when reExport if (!invokerRestMethodMetadataPair.compareServiceMethod(beforeMetadata)) { - throw new DoublePathCheckException( - "dubbo rest double path check error, current path is: " + pathMatcher - + " ,and service method is: " + invokerRestMethodMetadataPair.getRestMethodMetadata().getReflectMethod() - + "before service method is: " + beforeMetadata.getRestMethodMetadata().getReflectMethod() - ); + throw new DoublePathCheckException("dubbo rest double path check error, current path is: " + pathMatcher + + " ,and service method is: " + + invokerRestMethodMetadataPair.getRestMethodMetadata().getReflectMethod() + + "before service method is: " + + beforeMetadata.getRestMethodMetadata().getReflectMethod()); } } @@ -123,8 +137,8 @@ public class PathAndInvokerMapper { addPathMatcherToHttpMethodsMap(pathMatcher); - - logger.info("dubbo rest deploy pathMatcher:" + pathMatcher + ", and service method is :" + invokerRestMethodMetadataPair.getRestMethodMetadata().getReflectMethod()); + logger.info("dubbo rest deploy pathMatcher:" + pathMatcher + ", and service method is :" + + invokerRestMethodMetadataPair.getRestMethodMetadata().getReflectMethod()); } private void addPathMatcherToHttpMethodsMap(PathMatcher pathMatcher) { @@ -137,13 +151,11 @@ public class PathAndInvokerMapper { httpMethods.add(pathMatcher.getHttpMethod()); pathMatcherToHttpMethodMap.put(newPathMatcher, httpMethods); - } Set httpMethods = pathMatcherToHttpMethodMap.get(newPathMatcher); httpMethods.add(newPathMatcher.getHttpMethod()); - } public boolean isHttpMethodAllowed(PathMatcher pathMatcher) { @@ -153,11 +165,9 @@ public class PathAndInvokerMapper { return false; } - Set httpMethods = pathMatcherToHttpMethodMap.get(newPathMatcher); return httpMethods.contains(newPathMatcher.getHttpMethod()); - } public String pathHttpMethods(PathMatcher pathMatcher) { @@ -167,11 +177,8 @@ public class PathAndInvokerMapper { return null; } - Set httpMethods = pathMatcherToHttpMethodMap.get(newPathMatcher); return httpMethods.toString(); - } - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/ReferenceCountedClient.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/ReferenceCountedClient.java index ada7d5c1c3..b7dbaa0263 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/ReferenceCountedClient.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/ReferenceCountedClient.java @@ -28,7 +28,8 @@ import java.util.concurrent.ConcurrentMap; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_CLIENT; public class ReferenceCountedClient extends ReferenceCountedResource { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ReferenceCountedClient.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ReferenceCountedClient.class); private ConcurrentMap> clients; private URL url; @@ -36,7 +37,11 @@ public class ReferenceCountedClient extends ReferenceCount private T client; - public ReferenceCountedClient(T client, ConcurrentMap> clients, RestClientFactory clientFactory, URL url) { + public ReferenceCountedClient( + T client, + ConcurrentMap> clients, + RestClientFactory clientFactory, + URL url) { this.client = client; this.clients = clients; this.clientFactory = clientFactory; @@ -55,7 +60,8 @@ public class ReferenceCountedClient extends ReferenceCount referenceCountedClient = clients.get(url.getAddress()); if (referenceCountedClient.isDestroyed()) { RestClient restClient = clientFactory.createRestClient(url); - clients.put(url.getAddress(), new ReferenceCountedClient(restClient, clients, clientFactory, url)); + clients.put( + url.getAddress(), new ReferenceCountedClient(restClient, clients, clientFactory, url)); return (T) restClient; } else { return (T) referenceCountedClient.client; diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestConstraintViolation.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestConstraintViolation.java index f229773b53..6447bff895 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestConstraintViolation.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestConstraintViolation.java @@ -19,6 +19,7 @@ package org.apache.dubbo.rpc.protocol.rest; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; + import java.io.Serializable; @XmlRootElement(name = "constraintViolation") @@ -37,8 +38,7 @@ public class RestConstraintViolation implements Serializable { this.value = value; } - public RestConstraintViolation() { - } + public RestConstraintViolation() {} public String getPath() { return path; diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestHeaderEnum.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestHeaderEnum.java index 9674394359..7eab6db4d6 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestHeaderEnum.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestHeaderEnum.java @@ -28,8 +28,6 @@ public enum RestHeaderEnum { CONNECTION(RestConstant.CONNECTION), REST_HEADER_PREFIX(RestConstant.REST_HEADER_PREFIX), TOKEN_KEY(RestConstant.REST_HEADER_PREFIX + RestConstant.TOKEN_KEY), - - ; private final String header; diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestInvoker.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestInvoker.java index fe3a8e9f09..5afb5fecd1 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestInvoker.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestInvoker.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest; - import org.apache.dubbo.common.URL; import org.apache.dubbo.metadata.ParameterTypesComparator; import org.apache.dubbo.metadata.rest.RestMethodMetadata; @@ -50,11 +49,12 @@ public class RestInvoker extends AbstractInvoker { private final ReferenceCountedClient referenceCountedClient; private final Set httpConnectionPreBuildIntercepts; - - public RestInvoker(Class type, URL url, - ReferenceCountedClient referenceCountedClient, - Set httpConnectionPreBuildIntercepts, - ServiceRestMetadata serviceRestMetadata) { + public RestInvoker( + Class type, + URL url, + ReferenceCountedClient referenceCountedClient, + Set httpConnectionPreBuildIntercepts, + ServiceRestMetadata serviceRestMetadata) { super(type, url); this.serviceRestMetadata = serviceRestMetadata; this.referenceCountedClient = referenceCountedClient; @@ -65,15 +65,19 @@ public class RestInvoker extends AbstractInvoker { protected Result doInvoke(Invocation invocation) { try { - Map> metadataMap = serviceRestMetadata.getMethodToServiceMap(); + Map> metadataMap = + serviceRestMetadata.getMethodToServiceMap(); // get metadata - RestMethodMetadata restMethodMetadata = metadataMap.get(invocation.getMethodName()).get(ParameterTypesComparator.getInstance(invocation.getParameterTypes())); + RestMethodMetadata restMethodMetadata = metadataMap + .get(invocation.getMethodName()) + .get(ParameterTypesComparator.getInstance(invocation.getParameterTypes())); // create requestTemplate - RequestTemplate requestTemplate = new RequestTemplate(invocation, restMethodMetadata.getRequest().getMethod(), getUrl().getAddress()); + RequestTemplate requestTemplate = new RequestTemplate( + invocation, restMethodMetadata.getRequest().getMethod(), getUrl().getAddress()); - HttpConnectionCreateContext httpConnectionCreateContext = - createHttpConnectionCreateContext(invocation, serviceRestMetadata, restMethodMetadata, requestTemplate); + HttpConnectionCreateContext httpConnectionCreateContext = createHttpConnectionCreateContext( + invocation, serviceRestMetadata, restMethodMetadata, requestTemplate); // fill real data for (HttpConnectionPreBuildIntercept intercept : httpConnectionPreBuildIntercepts) { @@ -81,7 +85,8 @@ public class RestInvoker extends AbstractInvoker { } // TODO check rest client cannot be reused - CompletableFuture future = referenceCountedClient.getClient().send(requestTemplate); + CompletableFuture future = + referenceCountedClient.getClient().send(requestTemplate); CompletableFuture responseFuture = new CompletableFuture<>(); AsyncRpcResult asyncRpcResult = new AsyncRpcResult(responseFuture, invocation); future.whenComplete((r, t) -> { @@ -102,9 +107,13 @@ public class RestInvoker extends AbstractInvoker { responseFuture.completeExceptionally(new RemoteServerInternalException(r.getMessage())); } else if (responseCode < 400) { Method reflectMethod = restMethodMetadata.getReflectMethod(); - mediaType = MediaTypeUtil.convertMediaType(reflectMethod.getReturnType(), r.getContentType()); - Object value = HttpMessageCodecManager.httpMessageDecode(r.getBody(), - reflectMethod.getReturnType(), reflectMethod.getGenericReturnType(), mediaType); + mediaType = + MediaTypeUtil.convertMediaType(reflectMethod.getReturnType(), r.getContentType()); + Object value = HttpMessageCodecManager.httpMessageDecode( + r.getBody(), + reflectMethod.getReturnType(), + reflectMethod.getGenericReturnType(), + mediaType); appResponse.setValue(value); // resolve response attribute & attachment HttpHeaderUtil.parseResponseHeader(appResponse, r); @@ -130,7 +139,11 @@ public class RestInvoker extends AbstractInvoker { * @param requestTemplate * @return */ - private HttpConnectionCreateContext createHttpConnectionCreateContext(Invocation invocation, ServiceRestMetadata serviceRestMetadata, RestMethodMetadata restMethodMetadata, RequestTemplate requestTemplate) { + private HttpConnectionCreateContext createHttpConnectionCreateContext( + Invocation invocation, + ServiceRestMetadata serviceRestMetadata, + RestMethodMetadata restMethodMetadata, + RequestTemplate requestTemplate) { HttpConnectionCreateContext httpConnectionCreateContext = new HttpConnectionCreateContext(); httpConnectionCreateContext.setRequestTemplate(requestTemplate); httpConnectionCreateContext.setRestMethodMetadata(restMethodMetadata); diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java index 9c1fc67f95..1b4a4294b0 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestProtocol.java @@ -36,7 +36,6 @@ import org.apache.dubbo.rpc.protocol.rest.annotation.metadata.MetadataResolver; import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployerManager; - import java.util.LinkedHashSet; import java.util.List; import java.util.Map; @@ -58,24 +57,26 @@ public class RestProtocol extends AbstractProtocol { private static final int DEFAULT_PORT = 80; - private final ConcurrentMap> clients = new ConcurrentHashMap<>(); + private final ConcurrentMap> clients = + new ConcurrentHashMap<>(); private final RestClientFactory clientFactory; private final Set httpConnectionPreBuildIntercepts; public RestProtocol(FrameworkModel frameworkModel) { - this.clientFactory = frameworkModel.getExtensionLoader(RestClientFactory.class).getAdaptiveExtension(); - this.httpConnectionPreBuildIntercepts = new LinkedHashSet<>(frameworkModel.getExtensionLoader(HttpConnectionPreBuildIntercept.class).getActivateExtensions()); + this.clientFactory = + frameworkModel.getExtensionLoader(RestClientFactory.class).getAdaptiveExtension(); + this.httpConnectionPreBuildIntercepts = new LinkedHashSet<>(frameworkModel + .getExtensionLoader(HttpConnectionPreBuildIntercept.class) + .getActivateExtensions()); } - @Override public int getDefaultPort() { return DEFAULT_PORT; } - @Override @SuppressWarnings("unchecked") public Exporter export(final Invoker invoker) throws RpcException { @@ -89,25 +90,22 @@ public class RestProtocol extends AbstractProtocol { } } - // resolve metadata - ServiceRestMetadata serviceRestMetadata = - MetadataResolver.resolveProviderServiceMetadata(url.getServiceModel().getProxyObject().getClass(), - url, getContextPath(url)); + ServiceRestMetadata serviceRestMetadata = MetadataResolver.resolveProviderServiceMetadata( + url.getServiceModel().getProxyObject().getClass(), url, getContextPath(url)); // check json compatibility String jsonCheckLevel = url.getUrlParam().getParameter(JSON_CHECK_LEVEL); checkJsonCompatibility(invoker.getInterface(), jsonCheckLevel); - // deploy service URL newURL = ServiceDeployerManager.deploy(url, serviceRestMetadata, invoker); // create server PortUnificationExchanger.bind(newURL, new DefaultPuHandler()); - ServiceDeployer serviceDeployer = (ServiceDeployer) newURL.getAttribute(REST_SERVICE_DEPLOYER_URL_ATTRIBUTE_KEY); - + ServiceDeployer serviceDeployer = + (ServiceDeployer) newURL.getAttribute(REST_SERVICE_DEPLOYER_URL_ATTRIBUTE_KEY); URL finalUrl = newURL; exporter = new AbstractExporter(invoker) { @@ -129,23 +127,34 @@ public class RestProtocol extends AbstractProtocol { if (!compatibility) { List unsupportedMethods = JsonCompatibilityUtil.getUnsupportedMethods(clazz); assert unsupportedMethods != null; - logger.warn("", "", "", String.format("Interface %s does not support json serialization, the specific methods are %s.", clazz.getName(), unsupportedMethods)); + logger.warn( + "", + "", + "", + String.format( + "Interface %s does not support json serialization, the specific methods are %s.", + clazz.getName(), unsupportedMethods)); } else { - logger.debug("Check json compatibility complete, all methods of {} can be serialized using json.", clazz.getName()); + logger.debug( + "Check json compatibility complete, all methods of {} can be serialized using json.", + clazz.getName()); } } else if (JSON_CHECK_LEVEL_STRICT.equals(jsonCheckLevel)) { boolean compatibility = JsonCompatibilityUtil.checkClassCompatibility(clazz); if (!compatibility) { List unsupportedMethods = JsonCompatibilityUtil.getUnsupportedMethods(clazz); assert unsupportedMethods != null; - throw new IllegalStateException(String.format("Interface %s does not support json serialization, the specific methods are %s.", clazz.getName(), unsupportedMethods)); + throw new IllegalStateException(String.format( + "Interface %s does not support json serialization, the specific methods are %s.", + clazz.getName(), unsupportedMethods)); } else { - logger.debug("Check json compatibility complete, all methods of {} can be serialized using json.", clazz.getName()); + logger.debug( + "Check json compatibility complete, all methods of {} can be serialized using json.", + clazz.getName()); } } } - @Override protected Invoker protocolBindingRefer(final Class type, final URL url) throws RpcException { @@ -154,27 +163,26 @@ public class RestProtocol extends AbstractProtocol { synchronized (clients) { refClient = clients.get(url.getAddress()); if (refClient == null || refClient.isDestroyed()) { - refClient = ConcurrentHashMapUtils.computeIfAbsent(clients, url.getAddress(), _key -> createReferenceCountedClient(url)); + refClient = ConcurrentHashMapUtils.computeIfAbsent( + clients, url.getAddress(), _key -> createReferenceCountedClient(url)); } } } refClient.retain(); - String contextPathFromUrl = getContextPath(url); // resolve metadata ServiceRestMetadata serviceRestMetadata = - MetadataResolver.resolveConsumerServiceMetadata(type, url, contextPathFromUrl); + MetadataResolver.resolveConsumerServiceMetadata(type, url, contextPathFromUrl); - Invoker invoker = new RestInvoker(type, url, - refClient, httpConnectionPreBuildIntercepts, serviceRestMetadata); + Invoker invoker = + new RestInvoker(type, url, refClient, httpConnectionPreBuildIntercepts, serviceRestMetadata); invokers.add(invoker); return invoker; } - /** * create rest ReferenceCountedClient * @@ -190,7 +198,6 @@ public class RestProtocol extends AbstractProtocol { return new ReferenceCountedClient<>(restClient, clients, clientFactory, url); } - @Override public void destroy() { if (logger.isInfoEnabled()) { @@ -244,13 +251,14 @@ public class RestProtocol extends AbstractProtocol { if (contextPath.endsWith(url.getParameter(INTERFACE_KEY))) { contextPath = contextPath.substring(0, contextPath.lastIndexOf(url.getParameter(INTERFACE_KEY))); } - return contextPath.endsWith(PATH_SEPARATOR) ? contextPath.substring(0, contextPath.length() - 1) : contextPath; + return contextPath.endsWith(PATH_SEPARATOR) + ? contextPath.substring(0, contextPath.length() - 1) + : contextPath; } else { return ""; } } - private void destroyInternal(URL url) { try { ReferenceCountedClient referenceCountedClient = clients.get(url.getAddress()); @@ -258,7 +266,13 @@ public class RestProtocol extends AbstractProtocol { clients.remove(url.getAddress()); } } catch (Exception e) { - logger.warn(PROTOCOL_ERROR_CLOSE_CLIENT, "", "", "Failed to close unused resources in rest protocol. interfaceName [" + url.getServiceInterface() + "]", e); + logger.warn( + PROTOCOL_ERROR_CLOSE_CLIENT, + "", + "", + "Failed to close unused resources in rest protocol. interfaceName [" + url.getServiceInterface() + + "]", + e); } } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestRPCInvocationUtil.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestRPCInvocationUtil.java index b3205d55ec..ffc3b6ec11 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestRPCInvocationUtil.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RestRPCInvocationUtil.java @@ -33,14 +33,14 @@ import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; import org.apache.dubbo.rpc.protocol.rest.util.HttpHeaderUtil; import org.apache.dubbo.rpc.protocol.rest.util.NoAnnotationBodyParseUtil; - import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; public class RestRPCInvocationUtil { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RestRPCInvocationUtil.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(RestRPCInvocationUtil.class); /** * service method real args parse @@ -51,12 +51,16 @@ public class RestRPCInvocationUtil { * @param servletResponse * @param restMethodMetadata */ - public static void parseMethodArgs(RpcInvocation rpcInvocation, RequestFacade request, Object servletRequest, - Object servletResponse, - RestMethodMetadata restMethodMetadata) { + public static void parseMethodArgs( + RpcInvocation rpcInvocation, + RequestFacade request, + Object servletRequest, + Object servletResponse, + RestMethodMetadata restMethodMetadata) { try { - ProviderParseContext parseContext = createParseContext(request, servletRequest, servletResponse, restMethodMetadata); + ProviderParseContext parseContext = + createParseContext(request, servletRequest, servletResponse, restMethodMetadata); Object[] args = ParamParserManager.providerParamParse(parseContext); List argInfos = parseContext.getArgInfos(); @@ -65,8 +69,8 @@ public class RestRPCInvocationUtil { // TODO set default value if (argInfo.getParamType().isPrimitive() && args[argInfo.getIndex()] == null) { throw new ParamParseException("\n dubbo provider primitive arg not exist in request, method is: " - + restMethodMetadata.getReflectMethod() + "\n type is: " + - argInfo.getParamType() + " \n and arg index is: " + argInfo.getIndex()); + + restMethodMetadata.getReflectMethod() + "\n type is: " + argInfo.getParamType() + + " \n and arg index is: " + argInfo.getIndex()); } } @@ -86,7 +90,8 @@ public class RestRPCInvocationUtil { * @param restMethodMetadata * @return */ - private static ProviderParseContext createParseContext(RequestFacade request, Object originRequest, Object originResponse, RestMethodMetadata restMethodMetadata) { + private static ProviderParseContext createParseContext( + RequestFacade request, Object originRequest, Object originResponse, RestMethodMetadata restMethodMetadata) { ProviderParseContext parseContext = new ProviderParseContext(request); parseContext.setResponse(originResponse); parseContext.setRequest(originRequest); @@ -100,7 +105,6 @@ public class RestRPCInvocationUtil { parseContext.setArrayArgs(NoAnnotationBodyParseUtil.doParse(parseContext)); } - return parseContext; } @@ -119,26 +123,27 @@ public class RestRPCInvocationUtil { rpcInvocation.setMethodName(restMethodMetadata.getMethod().getName()); // TODO set protocolServiceKey ,but no set method -// + // HttpHeaderUtil.parseRequest(rpcInvocation, request); - String serviceKey = BaseServiceMetadata.buildServiceKey(request.getHeader(RestHeaderEnum.PATH.getHeader()), - request.getHeader(RestHeaderEnum.GROUP.getHeader()), - request.getHeader(RestHeaderEnum.VERSION.getHeader())); + String serviceKey = BaseServiceMetadata.buildServiceKey( + request.getHeader(RestHeaderEnum.PATH.getHeader()), + request.getHeader(RestHeaderEnum.GROUP.getHeader()), + request.getHeader(RestHeaderEnum.VERSION.getHeader())); rpcInvocation.setTargetServiceUniqueName(serviceKey); return rpcInvocation; } - /** * get InvokerAndRestMethodMetadataPair by path matcher * * @param pathMatcher * @return */ - public static InvokerAndRestMethodMetadataPair getRestMethodMetadataAndInvokerPair(PathMatcher pathMatcher, ServiceDeployer serviceDeployer) { + public static InvokerAndRestMethodMetadataPair getRestMethodMetadataAndInvokerPair( + PathMatcher pathMatcher, ServiceDeployer serviceDeployer) { return serviceDeployer.getPathAndInvokerMapper().getRestMethodMetadata(pathMatcher); } @@ -149,23 +154,19 @@ public class RestRPCInvocationUtil { * @param request * @return */ - public static InvokerAndRestMethodMetadataPair getRestMethodMetadataAndInvokerPair(RequestFacade request) { - PathMatcher pathMather = createPathMatcher(request); return getRestMethodMetadataAndInvokerPair(pathMather, request.getServiceDeployer()); } - /** * get invoker by request * * @param request * @return */ - public static Invoker getInvokerByRequest(RequestFacade request) { PathMatcher pathMatcher = createPathMatcher(request); @@ -173,7 +174,6 @@ public class RestRPCInvocationUtil { return getInvoker(pathMatcher, request.getServiceDeployer()); } - /** * get invoker by service method *

    @@ -182,7 +182,6 @@ public class RestRPCInvocationUtil { * @param serviceMethod * @return */ - public static Invoker getInvokerByServiceInvokeMethod(Method serviceMethod, ServiceDeployer serviceDeployer) { if (serviceMethod == null) { @@ -230,6 +229,4 @@ public class RestRPCInvocationUtil { return PathMatcher.getInvokeCreatePathMatcher(path, version, group, null, method); } - - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RpcExceptionMapper.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RpcExceptionMapper.java index fe07516ba4..6336f1cf54 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RpcExceptionMapper.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/RpcExceptionMapper.java @@ -21,10 +21,8 @@ import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionHandler; import org.apache.dubbo.rpc.protocol.rest.util.ConstraintViolationExceptionConvert; - public class RpcExceptionMapper implements ExceptionHandler { - @Override public Object result(RpcException e) { @@ -40,6 +38,7 @@ public class RpcExceptionMapper implements ExceptionHandler { } private boolean violationDependency() { - return ClassUtils.isPresent("javax.validation.ConstraintViolationException", RpcExceptionMapper.class.getClassLoader()); + return ClassUtils.isPresent( + "javax.validation.ConstraintViolationException", RpcExceptionMapper.class.getClassLoader()); } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/ViolationReport.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/ViolationReport.java index 1d5346044f..0a87d6d8f3 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/ViolationReport.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/ViolationReport.java @@ -19,11 +19,12 @@ package org.apache.dubbo.rpc.protocol.rest; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; + import java.io.Serializable; import java.util.LinkedList; import java.util.List; -@XmlRootElement(name="violationReport") +@XmlRootElement(name = "violationReport") @XmlAccessorType(XmlAccessType.FIELD) public class ViolationReport implements Serializable { diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/BaseParseContext.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/BaseParseContext.java index 7a3bb2fd7b..e5de8f8e51 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/BaseParseContext.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/BaseParseContext.java @@ -16,21 +16,18 @@ */ package org.apache.dubbo.rpc.protocol.rest.annotation; - import org.apache.dubbo.metadata.rest.ArgInfo; import java.util.List; public class BaseParseContext { - protected List args; protected List argInfos; boolean isNoAnnotationMode; - public List getArgs() { return args; } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/ParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/ParamParser.java index e8af563d3e..a093b0edf9 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/ParamParser.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/ParamParser.java @@ -18,7 +18,6 @@ package org.apache.dubbo.rpc.protocol.rest.annotation; import org.apache.dubbo.metadata.rest.ArgInfo; - public interface ParamParser { void parse(T parseContext, ArgInfo argInfo); } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/ParamParserManager.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/ParamParserManager.java index 7f2ac44ec3..06bce8f6e7 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/ParamParserManager.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/ParamParserManager.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest.annotation; - import org.apache.dubbo.metadata.rest.ArgInfo; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer.BaseConsumerParamParser; @@ -28,12 +27,13 @@ import java.util.List; public class ParamParserManager { + private static final List consumerParamParsers = FrameworkModel.defaultModel() + .getExtensionLoader(BaseConsumerParamParser.class) + .getActivateExtensions(); - private static final List consumerParamParsers = - FrameworkModel.defaultModel().getExtensionLoader(BaseConsumerParamParser.class).getActivateExtensions(); - - private static final List providerParamParsers = - FrameworkModel.defaultModel().getExtensionLoader(BaseProviderParamParser.class).getActivateExtensions(); + private static final List providerParamParsers = FrameworkModel.defaultModel() + .getExtensionLoader(BaseProviderParamParser.class) + .getActivateExtensions(); /** * provider Design Description: @@ -63,7 +63,6 @@ public class ParamParserManager { return parseContext.getArgs().toArray(new Object[0]); } - /** * consumer Design Description: *

    @@ -92,6 +91,5 @@ public class ParamParserManager { // TODO add param require or default - } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/HttpConnectionCreateContext.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/HttpConnectionCreateContext.java index 494c94fa54..a251bebf08 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/HttpConnectionCreateContext.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/HttpConnectionCreateContext.java @@ -30,15 +30,12 @@ public class HttpConnectionCreateContext { private Invocation invocation; private URL url; - public HttpConnectionCreateContext() { - } - + public HttpConnectionCreateContext() {} public void setRequestTemplate(RequestTemplate requestTemplate) { this.requestTemplate = requestTemplate; } - public RequestTemplate getRequestTemplate() { return requestTemplate; } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/AddMustAttachmentIntercept.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/AddMustAttachmentIntercept.java index c5e6248d5b..49a5011625 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/AddMustAttachmentIntercept.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/AddMustAttachmentIntercept.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest.annotation.consumer.inercept; - import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metadata.rest.ServiceRestMetadata; import org.apache.dubbo.remoting.http.RequestTemplate; @@ -28,7 +27,7 @@ import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; /** * add some must attachment */ -@Activate(value = RestConstant.ADD_MUST_ATTTACHMENT,order = 1) +@Activate(value = RestConstant.ADD_MUST_ATTTACHMENT, order = 1) public class AddMustAttachmentIntercept implements HttpConnectionPreBuildIntercept { @Override @@ -37,14 +36,11 @@ public class AddMustAttachmentIntercept implements HttpConnectionPreBuildInterce RequestTemplate requestTemplate = connectionCreateContext.getRequestTemplate(); ServiceRestMetadata serviceRestMetadata = connectionCreateContext.getServiceRestMetadata(); - requestTemplate.addHeader(RestHeaderEnum.GROUP.getHeader(), serviceRestMetadata.getGroup()); requestTemplate.addHeader(RestHeaderEnum.VERSION.getHeader(), serviceRestMetadata.getVersion()); requestTemplate.addHeader(RestHeaderEnum.PATH.getHeader(), serviceRestMetadata.getServiceInterface()); - requestTemplate.addHeader(RestHeaderEnum.TOKEN_KEY.getHeader(), connectionCreateContext.getUrl().getParameter(RestConstant.TOKEN_KEY)); - - + requestTemplate.addHeader( + RestHeaderEnum.TOKEN_KEY.getHeader(), + connectionCreateContext.getUrl().getParameter(RestConstant.TOKEN_KEY)); } - - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/AttachmentIntercept.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/AttachmentIntercept.java index d1e1126f5d..c6a4a26548 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/AttachmentIntercept.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/AttachmentIntercept.java @@ -34,7 +34,7 @@ public class AttachmentIntercept implements HttpConnectionPreBuildIntercept { RequestTemplate requestTemplate = connectionCreateContext.getRequestTemplate(); - HttpHeaderUtil.addRequestAttachments(requestTemplate, connectionCreateContext.getInvocation().getObjectAttachments()); + HttpHeaderUtil.addRequestAttachments( + requestTemplate, connectionCreateContext.getInvocation().getObjectAttachments()); } - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/ParamParseIntercept.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/ParamParseIntercept.java index 52a31f293a..e1d155d266 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/ParamParseIntercept.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/ParamParseIntercept.java @@ -34,7 +34,6 @@ public class ParamParseIntercept implements HttpConnectionPreBuildIntercept { @Override public void intercept(HttpConnectionCreateContext connectionCreateContext) { - RequestTemplate requestTemplate = connectionCreateContext.getRequestTemplate(); Object[] arguments = connectionCreateContext.getInvocation().getArguments(); @@ -43,10 +42,10 @@ public class ParamParseIntercept implements HttpConnectionPreBuildIntercept { requestTemplate.body(arguments, Object[].class); } else { ConsumerParseContext consumerParseContext = new ConsumerParseContext(requestTemplate); - consumerParseContext.setArgInfos(connectionCreateContext.getRestMethodMetadata().getArgInfos()); + consumerParseContext.setArgInfos( + connectionCreateContext.getRestMethodMetadata().getArgInfos()); consumerParseContext.setArgs(Arrays.asList(arguments)); ParamParserManager.consumerParamParse(consumerParseContext); - } } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/PathVariableIntercept.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/PathVariableIntercept.java index 9837d352b8..a8ef83d867 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/PathVariableIntercept.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/PathVariableIntercept.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest.annotation.consumer.inercept; - import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metadata.rest.ArgInfo; import org.apache.dubbo.metadata.rest.PathUtil; @@ -32,7 +31,7 @@ import java.util.List; /** * resolve method args from path */ -@Activate(value = RestConstant.PATH_INTERCEPT,order = 4) +@Activate(value = RestConstant.PATH_INTERCEPT, order = 4) public class PathVariableIntercept implements HttpConnectionPreBuildIntercept { @Override @@ -44,11 +43,10 @@ public class PathVariableIntercept implements HttpConnectionPreBuildIntercept { List argInfos = restMethodMetadata.getArgInfos(); // path variable parse - String path = PathUtil.resolvePathVariable(restMethodMetadata.getRequest().getPath(), argInfos, Arrays.asList(connectionCreateContext.getInvocation().getArguments())); + String path = PathUtil.resolvePathVariable( + restMethodMetadata.getRequest().getPath(), + argInfos, + Arrays.asList(connectionCreateContext.getInvocation().getArguments())); requestTemplate.path(path); - - } - - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/RequestHeaderIntercept.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/RequestHeaderIntercept.java index 8bfbfbfbfe..d6fb6f8bf8 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/RequestHeaderIntercept.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/RequestHeaderIntercept.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest.annotation.consumer.inercept; - import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.metadata.rest.RestMethodMetadata; import org.apache.dubbo.remoting.http.RequestTemplate; @@ -40,12 +39,10 @@ public class RequestHeaderIntercept implements HttpConnectionPreBuildIntercept { RestMethodMetadata restMethodMetadata = connectionCreateContext.getRestMethodMetadata(); RequestTemplate requestTemplate = connectionCreateContext.getRequestTemplate(); - Set consumes = restMethodMetadata.getRequest().getConsumes(); requestTemplate.addHeaders(RestHeaderEnum.CONTENT_TYPE.getHeader(), consumes); - Collection produces = restMethodMetadata.getRequest().getProduces(); if (produces == null || produces.isEmpty()) { requestTemplate.addHeader(RestHeaderEnum.ACCEPT.getHeader(), RestConstant.DEFAULT_ACCEPT); @@ -53,13 +50,10 @@ public class RequestHeaderIntercept implements HttpConnectionPreBuildIntercept { requestTemplate.addHeaders(RestHeaderEnum.ACCEPT.getHeader(), produces); } -// URL url = connectionCreateContext.getUrl(); - - -// requestTemplate.addKeepAliveHeader(url.getParameter(RestConstant.KEEP_ALIVE_TIMEOUT_PARAM,RestConstant.KEEP_ALIVE_TIMEOUT)); + // URL url = connectionCreateContext.getUrl(); + // + // requestTemplate.addKeepAliveHeader(url.getParameter(RestConstant.KEEP_ALIVE_TIMEOUT_PARAM,RestConstant.KEEP_ALIVE_TIMEOUT)); } - - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/SerializeBodyIntercept.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/SerializeBodyIntercept.java index 22d6ab32b8..6e898cea56 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/SerializeBodyIntercept.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/consumer/inercept/SerializeBodyIntercept.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest.annotation.consumer.inercept; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.LoggerCodeConstants; import org.apache.dubbo.common.extension.Activate; @@ -40,7 +39,8 @@ import java.util.Collection; @Activate(value = RestConstant.SERIALIZE_INTERCEPT, order = Integer.MAX_VALUE) public class SerializeBodyIntercept implements HttpConnectionPreBuildIntercept { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SerializeBodyIntercept.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(SerializeBodyIntercept.class); @Override public void intercept(HttpConnectionCreateContext connectionCreateContext) { @@ -50,30 +50,32 @@ public class SerializeBodyIntercept implements HttpConnectionPreBuildIntercept { return; } - try { Object unSerializedBody = requestTemplate.getUnSerializedBody(); URL url = connectionCreateContext.getUrl(); // TODO pool ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Collection headers = requestTemplate.getHeaders(RestConstant.CONTENT_TYPE); - MediaType mediaType = MediaTypeUtil.convertMediaType(requestTemplate.getBodyType(), headers.toArray(new String[0])); + MediaType mediaType = + MediaTypeUtil.convertMediaType(requestTemplate.getBodyType(), headers.toArray(new String[0])); // add mediaType by targetClass serialize if (mediaType != null && !mediaType.equals(MediaType.ALL_VALUE)) { headers.clear(); headers.add(mediaType.value); } - HttpMessageCodecManager.httpMessageEncode(outputStream, unSerializedBody, url, mediaType, requestTemplate.getBodyType()); + HttpMessageCodecManager.httpMessageEncode( + outputStream, unSerializedBody, url, mediaType, requestTemplate.getBodyType()); requestTemplate.serializeBody(outputStream.toByteArray()); outputStream.close(); } catch (Exception e) { - logger.error(LoggerCodeConstants.PROTOCOL_ERROR_DESERIALIZE, "", "", "Rest SerializeBodyIntercept serialize error: {}", e); + logger.error( + LoggerCodeConstants.PROTOCOL_ERROR_DESERIALIZE, + "", + "", + "Rest SerializeBodyIntercept serialize error: {}", + e); throw new RpcException(e); } - - } - - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/metadata/MetadataResolver.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/metadata/MetadataResolver.java index 6433af7dce..26a1d13955 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/metadata/MetadataResolver.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/metadata/MetadataResolver.java @@ -22,10 +22,8 @@ import org.apache.dubbo.metadata.rest.ServiceRestMetadata; import org.apache.dubbo.metadata.rest.ServiceRestMetadataResolver; import org.apache.dubbo.rpc.protocol.rest.exception.CodeStyleNotSupportException; - public class MetadataResolver { - private MetadataResolver() { - } + private MetadataResolver() {} /** * for consumer @@ -35,12 +33,15 @@ public class MetadataResolver { * @return rest metadata * @throws CodeStyleNotSupportException not support type */ - public static ServiceRestMetadata resolveConsumerServiceMetadata(Class targetClass, URL url, String contextPathFromUrl) { - ExtensionLoader extensionLoader = url.getOrDefaultApplicationModel().getExtensionLoader(ServiceRestMetadataResolver.class); + public static ServiceRestMetadata resolveConsumerServiceMetadata( + Class targetClass, URL url, String contextPathFromUrl) { + ExtensionLoader extensionLoader = + url.getOrDefaultApplicationModel().getExtensionLoader(ServiceRestMetadataResolver.class); for (ServiceRestMetadataResolver serviceRestMetadataResolver : extensionLoader.getActivateExtensions()) { if (serviceRestMetadataResolver.supports(targetClass, true)) { - ServiceRestMetadata serviceRestMetadata = new ServiceRestMetadata(url.getServiceInterface(), url.getVersion(), url.getGroup(), true); + ServiceRestMetadata serviceRestMetadata = + new ServiceRestMetadata(url.getServiceInterface(), url.getVersion(), url.getGroup(), true); serviceRestMetadata.setContextPathFromUrl(contextPathFromUrl); ServiceRestMetadata resolve = serviceRestMetadataResolver.resolve(targetClass, serviceRestMetadata); return resolve; @@ -48,23 +49,26 @@ public class MetadataResolver { } // TODO support Dubbo style service - throw new CodeStyleNotSupportException("service is: " + targetClass + ", only support " + extensionLoader.getSupportedExtensions() + " annotation"); + throw new CodeStyleNotSupportException("service is: " + targetClass + ", only support " + + extensionLoader.getSupportedExtensions() + " annotation"); } - - public static ServiceRestMetadata resolveProviderServiceMetadata(Class serviceImpl, URL url, String contextPathFromUrl) { - ExtensionLoader extensionLoader = url.getOrDefaultApplicationModel().getExtensionLoader(ServiceRestMetadataResolver.class); + public static ServiceRestMetadata resolveProviderServiceMetadata( + Class serviceImpl, URL url, String contextPathFromUrl) { + ExtensionLoader extensionLoader = + url.getOrDefaultApplicationModel().getExtensionLoader(ServiceRestMetadataResolver.class); for (ServiceRestMetadataResolver serviceRestMetadataResolver : extensionLoader.getActivateExtensions()) { boolean supports = serviceRestMetadataResolver.supports(serviceImpl); if (supports) { - ServiceRestMetadata serviceRestMetadata = new ServiceRestMetadata(url.getServiceInterface(), url.getVersion(), url.getGroup(), false); + ServiceRestMetadata serviceRestMetadata = + new ServiceRestMetadata(url.getServiceInterface(), url.getVersion(), url.getGroup(), false); serviceRestMetadata.setContextPathFromUrl(contextPathFromUrl); ServiceRestMetadata resolve = serviceRestMetadataResolver.resolve(serviceImpl, serviceRestMetadata); return resolve; } } - throw new CodeStyleNotSupportException("service is:" + serviceImpl + ",just support rest or spring-web annotation"); + throw new CodeStyleNotSupportException( + "service is:" + serviceImpl + ",just support rest or spring-web annotation"); } - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/BaseConsumerParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/BaseConsumerParamParser.java index 74c2ca1521..6393daca5f 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/BaseConsumerParamParser.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/BaseConsumerParamParser.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer; - import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.metadata.rest.ArgInfo; diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/BodyConsumerParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/BodyConsumerParamParser.java index 0632ca3474..3c300861e9 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/BodyConsumerParamParser.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/BodyConsumerParamParser.java @@ -28,14 +28,11 @@ public class BodyConsumerParamParser implements BaseConsumerParamParser { @Override public void parse(ConsumerParseContext parseContext, ArgInfo argInfo) { - List args = parseContext.getArgs(); RequestTemplate requestTemplate = parseContext.getRequestTemplate(); - requestTemplate.body(args.get(argInfo.getIndex()),argInfo.getParamType()); - - + requestTemplate.body(args.get(argInfo.getIndex()), argInfo.getParamType()); } @Override diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/ConsumerParseContext.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/ConsumerParseContext.java index 672b30e4de..c6833f4056 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/ConsumerParseContext.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/ConsumerParseContext.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.consumer; - import org.apache.dubbo.remoting.http.RequestTemplate; import org.apache.dubbo.rpc.protocol.rest.annotation.BaseParseContext; @@ -30,5 +29,4 @@ public class ConsumerParseContext extends BaseParseContext { public RequestTemplate getRequestTemplate() { return requestTemplate; } - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/FormConsumerParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/FormConsumerParamParser.java index 2b2e04f1ba..e4fdbb0c0b 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/FormConsumerParamParser.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/FormConsumerParamParser.java @@ -38,7 +38,6 @@ public class FormConsumerParamParser implements BaseConsumerParamParser { @Override public void parse(ConsumerParseContext parseContext, ArgInfo argInfo) { - List args = parseContext.getArgs(); RequestTemplate requestTemplate = parseContext.getRequestTemplate(); @@ -48,7 +47,6 @@ public class FormConsumerParamParser implements BaseConsumerParamParser { return; } - Map> tmp = new HashMap<>(); if (DataParseUtils.isTextType(value.getClass())) { tmp.put(argInfo.getAnnotationNameAttribute(), Arrays.asList(String.valueOf(value))); @@ -59,11 +57,9 @@ public class FormConsumerParamParser implements BaseConsumerParamParser { Set allFieldNames = ReflectUtils.getAllFieldNames(value.getClass()); allFieldNames.stream().forEach(entry -> { - - Object fieldValue = ReflectUtils.getFieldValue(value, entry); - tmp.put(String.valueOf(entry), Arrays.asList(String.valueOf(fieldValue))); - } - ); + Object fieldValue = ReflectUtils.getFieldValue(value, entry); + tmp.put(String.valueOf(entry), Arrays.asList(String.valueOf(fieldValue))); + }); requestTemplate.body(tmp, Map.class); } @@ -72,8 +68,6 @@ public class FormConsumerParamParser implements BaseConsumerParamParser { if (CollectionUtils.isEmpty(headers)) { requestTemplate.addHeader(RestConstant.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE.value); } - - } @Override diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/HeaderConsumerParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/HeaderConsumerParamParser.java index d99a01164d..c62f1750a0 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/HeaderConsumerParamParser.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/HeaderConsumerParamParser.java @@ -38,7 +38,6 @@ public class HeaderConsumerParamParser implements BaseConsumerParamParser { return; } - // Map if (Map.class.isAssignableFrom(argInfo.getParamType())) { Map headerValues = (Map) headerValue; @@ -48,9 +47,7 @@ public class HeaderConsumerParamParser implements BaseConsumerParamParser { } else { // others requestTemplate.addHeader(argInfo.getAnnotationNameAttribute(), headerValue); - } - } @Override diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/ParameterConsumerParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/ParameterConsumerParamParser.java index 11509a7965..65f8fe30e8 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/ParameterConsumerParamParser.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/consumer/ParameterConsumerParamParser.java @@ -38,7 +38,6 @@ public class ParameterConsumerParamParser implements BaseConsumerParamParser { return; } - if (Map.class.isAssignableFrom(argInfo.getParamType())) { Map paramValues = (Map) paramValue; for (Object name : paramValues.keySet()) { @@ -46,10 +45,7 @@ public class ParameterConsumerParamParser implements BaseConsumerParamParser { } } else { requestTemplate.addParam(argInfo.getAnnotationNameAttribute(), paramValue); - - } - } @Override diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/BaseProviderParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/BaseProviderParamParser.java index 58ca9abcbb..a10a70d18b 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/BaseProviderParamParser.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/BaseProviderParamParser.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider; - import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.metadata.rest.ParamType; @@ -25,13 +24,11 @@ import org.apache.dubbo.rpc.protocol.rest.annotation.ParamParser; @SPI(scope = ExtensionScope.FRAMEWORK) public interface BaseProviderParamParser extends ParamParser { - default boolean matchParseType(Class paramAnno) { ParamType paramAnnotType = getParamType(); return paramAnnotType.supportAnno(paramAnno); } - ParamType getParamType(); } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/BodyProviderParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/BodyProviderParamParser.java index a92d5cf51f..ef851c8112 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/BodyProviderParamParser.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/BodyProviderParamParser.java @@ -27,7 +27,6 @@ import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodecManager; import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; import org.apache.dubbo.rpc.protocol.rest.util.MediaTypeUtil; - /** * body param parse */ @@ -42,7 +41,8 @@ public class BodyProviderParamParser extends ProviderParamParser { try { String contentType = parseContext.getRequestFacade().getHeader(RestHeaderEnum.CONTENT_TYPE.getHeader()); MediaType mediaType = MediaTypeUtil.convertMediaType(argInfo.getParamType(), contentType); - Object param = HttpMessageCodecManager.httpMessageDecode(request.getInputStream(), argInfo.getParamType(), argInfo.actualReflectType(), mediaType); + Object param = HttpMessageCodecManager.httpMessageDecode( + request.getInputStream(), argInfo.getParamType(), argInfo.actualReflectType(), mediaType); parseContext.setValueByIndex(argInfo.getIndex(), param); } catch (Throwable e) { throw new ParamParseException("dubbo rest protocol provider body param parser error: " + e.getMessage()); diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/HeaderProviderParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/HeaderProviderParamParser.java index 43990a2d84..baa630058e 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/HeaderProviderParamParser.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/HeaderProviderParamParser.java @@ -17,10 +17,11 @@ package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider; import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; -import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; import org.apache.dubbo.metadata.rest.ArgInfo; import org.apache.dubbo.metadata.rest.ParamType; +import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; +import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; + import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.Map; @@ -45,16 +46,12 @@ public class HeaderProviderParamParser extends ProviderParamParser { } parseContext.setValueByIndex(argInfo.getIndex(), headerMap); return; - } - String header = request.getHeader(argInfo.getAnnotationNameAttribute()); Object headerValue = paramTypeConvert(argInfo.getParamType(), header); - parseContext.setValueByIndex(argInfo.getIndex(), headerValue); - } @Override diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/NoAnnotationParamProviderParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/NoAnnotationParamProviderParamParser.java index 0970232d6b..353c07b9e9 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/NoAnnotationParamProviderParamParser.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/NoAnnotationParamProviderParamParser.java @@ -22,7 +22,6 @@ import org.apache.dubbo.metadata.rest.ArgInfo; import org.apache.dubbo.metadata.rest.ParamType; import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; - /** * body param parse * users can custom NoAnnotationParamProviderParamParser @@ -44,8 +43,6 @@ public class NoAnnotationParamProviderParamParser extends ProviderParamParser { Object convertArg = JsonUtils.toJavaObject(JsonUtils.toJson(arg), argInfo.actualReflectType()); parseContext.setValueByIndex(index, convertArg); - - } @Override diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ParamProviderParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ParamProviderParamParser.java index ca0b7dc234..91a1eb9250 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ParamProviderParamParser.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ParamProviderParamParser.java @@ -16,12 +16,11 @@ */ package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider; - import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; -import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; import org.apache.dubbo.metadata.rest.ArgInfo; import org.apache.dubbo.metadata.rest.ParamType; +import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; +import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; import java.util.Enumeration; import java.util.LinkedHashMap; @@ -35,7 +34,7 @@ public class ParamProviderParamParser extends ProviderParamParser { @Override protected void doParse(ProviderParseContext parseContext, ArgInfo argInfo) { - //TODO MAP convert + // TODO MAP convert RequestFacade request = parseContext.getRequestFacade(); if (Map.class.isAssignableFrom(argInfo.getParamType())) { @@ -49,7 +48,6 @@ public class ParamProviderParamParser extends ProviderParamParser { } parseContext.setValueByIndex(argInfo.getIndex(), paramMap); return; - } String param = request.getParameter(argInfo.getAnnotationNameAttribute()); diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/PathProviderParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/PathProviderParamParser.java index 7b81d9cd5d..2d5e9e92b1 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/PathProviderParamParser.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/PathProviderParamParser.java @@ -16,12 +16,10 @@ */ package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider; - import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; import org.apache.dubbo.metadata.rest.ArgInfo; import org.apache.dubbo.metadata.rest.ParamType; - +import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; /** * path param parse @@ -36,7 +34,6 @@ public class PathProviderParamParser extends ProviderParamParser { Object pathVariableValue = paramTypeConvert(argInfo.getParamType(), pathVariable); parseContext.setValueByIndex(argInfo.getIndex(), pathVariableValue); - } @Override diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ProviderParamParser.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ProviderParamParser.java index 6178232d04..e37aab2516 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ProviderParamParser.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ProviderParamParser.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider; - import org.apache.dubbo.metadata.rest.ArgInfo; import org.apache.dubbo.rpc.protocol.rest.util.DataParseUtils; @@ -32,8 +31,5 @@ public abstract class ProviderParamParser implements BaseProviderParamParser { protected Object paramTypeConvert(Class targetType, String value) { return DataParseUtils.stringTypeConvert(targetType, value); - } - - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ProviderParseContext.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ProviderParseContext.java index 462acfa347..78f92fa04f 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ProviderParseContext.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/annotation/param/parse/provider/ProviderParseContext.java @@ -16,20 +16,16 @@ */ package org.apache.dubbo.rpc.protocol.rest.annotation.param.parse.provider; - import org.apache.dubbo.rpc.protocol.rest.annotation.BaseParseContext; import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; - public class ProviderParseContext extends BaseParseContext { - private RequestFacade requestFacade; private Object response; private Object request; private Object[] arrayArgs; - public ProviderParseContext(RequestFacade request) { this.requestFacade = request; } @@ -64,7 +60,6 @@ public class ProviderParseContext extends BaseParseContext { String[] split = getRequestFacade().getRequestURI().split("/"); return split[urlSplitIndex]; - } public Object[] getArrayArgs() { @@ -73,6 +68,5 @@ public class ProviderParseContext extends BaseParseContext { public void setArrayArgs(Object[] objects) { this.arrayArgs = objects; - } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/config/FeignClientAnnotationConfigPostProcessor.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/config/FeignClientAnnotationConfigPostProcessor.java index 8c10e25277..4f62417a28 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/config/FeignClientAnnotationConfigPostProcessor.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/config/FeignClientAnnotationConfigPostProcessor.java @@ -28,7 +28,6 @@ import java.lang.annotation.Annotation; /** * parsing @FeignClient service name attribute to replace reference config provided by */ - @Activate public class FeignClientAnnotationConfigPostProcessor implements CommonConfigPostProcessor { @@ -37,15 +36,15 @@ public class FeignClientAnnotationConfigPostProcessor implements CommonConfigPos appendParametersFromInterfaceClassMetadata(referenceConfig.getInterfaceClass(), referenceConfig); } - - public static void appendParametersFromInterfaceClassMetadata(Class interfaceClass, ReferenceConfigBase referenceConfig) { + public static void appendParametersFromInterfaceClassMetadata( + Class interfaceClass, ReferenceConfigBase referenceConfig) { if (interfaceClass == null) { return; } - Class feignClientAnno = (Class) ClassUtils.forNameAndTryCatch("org.springframework.cloud.openfeign.FeignClient"); - + Class feignClientAnno = (Class) + ClassUtils.forNameAndTryCatch("org.springframework.cloud.openfeign.FeignClient"); if (feignClientAnno == null || !AnnotationUtils.isAnnotationPresent(interfaceClass, feignClientAnno)) { return; @@ -61,7 +60,5 @@ public class FeignClientAnnotationConfigPostProcessor implements CommonConfigPos } referenceConfig.setProvidedBy(serviceName); - - } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/constans/RestConstant.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/constans/RestConstant.java index 2c62f5cec0..2e15db4396 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/constans/RestConstant.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/constans/RestConstant.java @@ -48,7 +48,6 @@ public interface RestConstant { String DEFAULT_ACCEPT = "*/*"; String REST_HEADER_PREFIX = "rest-service-"; - // http String MAX_INITIAL_LINE_LENGTH_PARAM = "max.initial.line.length"; String MAX_HEADER_SIZE_PARAM = "max.header.size"; @@ -73,6 +72,4 @@ public interface RestConstant { * ServerAttachment pathAndInvokerMapper key */ String PATH_AND_INVOKER_MAPPER = "pathAndInvokerMapper"; - - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/deploy/ServiceDeployer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/deploy/ServiceDeployer.java index 1830dc2e86..df724b03b8 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/deploy/ServiceDeployer.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/deploy/ServiceDeployer.java @@ -41,40 +41,37 @@ import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATT public class ServiceDeployer { - private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); - private final PathAndInvokerMapper pathAndInvokerMapper = new PathAndInvokerMapper(); private final ExceptionMapper exceptionMapper = createExceptionMapper(); private final Set extensions = new HashSet<>(); - public void deploy(ServiceRestMetadata serviceRestMetadata, Invoker invoker) { Map pathToServiceMapContainPathVariable = - serviceRestMetadata.getPathContainPathVariableToServiceMap(); + serviceRestMetadata.getPathContainPathVariableToServiceMap(); pathAndInvokerMapper.addPathAndInvoker(pathToServiceMapContainPathVariable, invoker); Map pathToServiceMapUnContainPathVariable = - serviceRestMetadata.getPathUnContainPathVariableToServiceMap(); + serviceRestMetadata.getPathUnContainPathVariableToServiceMap(); pathAndInvokerMapper.addPathAndInvoker(pathToServiceMapUnContainPathVariable, invoker); } public void undeploy(ServiceRestMetadata serviceRestMetadata) { Map pathToServiceMapContainPathVariable = - serviceRestMetadata.getPathContainPathVariableToServiceMap(); + serviceRestMetadata.getPathContainPathVariableToServiceMap(); pathToServiceMapContainPathVariable.keySet().stream().forEach(pathAndInvokerMapper::removePath); Map pathToServiceMapUnContainPathVariable = - serviceRestMetadata.getPathUnContainPathVariableToServiceMap(); + serviceRestMetadata.getPathUnContainPathVariableToServiceMap(); pathToServiceMapUnContainPathVariable.keySet().stream().forEach(pathAndInvokerMapper::removePath); - } public void registerExtension(URL url) { - for (String clazz : COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, RpcExceptionMapper.class.getName()))) { + for (String clazz : COMMA_SPLIT_PATTERN.split( + url.getParameter(Constants.EXTENSION_KEY, RpcExceptionMapper.class.getName()))) { if (StringUtils.isEmpty(clazz)) { continue; @@ -87,15 +84,12 @@ public class ServiceDeployer { exceptionMapper.registerMapper(clazz); } else { - extensions.add(aClass.newInstance()); } } catch (Exception e) { logger.warn("", "", "dubbo rest registerExtension error: ", e.getMessage(), e); } - - } } @@ -126,7 +120,6 @@ public class ServiceDeployer { return exts; } - for (Object extension : extensions) { if (extensionClass.isAssignableFrom(extension.getClass())) { exts.add((T) extension); @@ -137,13 +130,13 @@ public class ServiceDeployer { } private ExceptionMapper createExceptionMapper() { - if (ClassUtils.isPresent("javax.ws.rs.ext.ExceptionMapper", Thread.currentThread().getContextClassLoader())) { + if (ClassUtils.isPresent( + "javax.ws.rs.ext.ExceptionMapper", Thread.currentThread().getContextClassLoader())) { return new RestEasyExceptionMapper(); } return new ExceptionMapper(); } - public boolean isMethodAllowed(PathMatcher pathMatcher) { return pathAndInvokerMapper.isHttpMethodAllowed(pathMatcher); } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/deploy/ServiceDeployerManager.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/deploy/ServiceDeployerManager.java index ff93b26133..97bc84982f 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/deploy/ServiceDeployerManager.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/deploy/ServiceDeployerManager.java @@ -33,18 +33,16 @@ import static org.apache.dubbo.remoting.Constants.SERVER_KEY; public class ServiceDeployerManager { private static final ConcurrentMap serviceDeployers = new ConcurrentHashMap<>(); - public static URL deploy(URL currentURL, ServiceRestMetadata serviceRestMetadata, Invoker invoker) { AtomicBoolean isNewCreate = new AtomicBoolean(); - ServiceDeployer newServiceDeployer = ConcurrentHashMapUtils.computeIfAbsent(serviceDeployers, currentURL.getAddress(), address -> { - ServiceDeployer serviceDeployer = new ServiceDeployer(); - isNewCreate.set(true); - return serviceDeployer; - - }); - + ServiceDeployer newServiceDeployer = + ConcurrentHashMapUtils.computeIfAbsent(serviceDeployers, currentURL.getAddress(), address -> { + ServiceDeployer serviceDeployer = new ServiceDeployer(); + isNewCreate.set(true); + return serviceDeployer; + }); // register service newServiceDeployer.deploy(serviceRestMetadata, invoker); @@ -62,18 +60,15 @@ public class ServiceDeployerManager { return currentURL; } - URL tmp = currentURL; // adapt to older rest versions if (REST_SERVER.contains(tmp.getParameter(SERVER_KEY))) { tmp = tmp.addParameter(SERVER_KEY, PORT_UNIFICATION_NETTY4_SERVER); } - return tmp; } - public static void close() { serviceDeployers.clear(); } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/CodeStyleNotSupportException.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/CodeStyleNotSupportException.java index d2c6c5849d..979994750e 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/CodeStyleNotSupportException.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/CodeStyleNotSupportException.java @@ -19,7 +19,7 @@ package org.apache.dubbo.rpc.protocol.rest.exception; /** * only support spring mvc & jaxrs annotation */ -public class CodeStyleNotSupportException extends RestException{ +public class CodeStyleNotSupportException extends RestException { public CodeStyleNotSupportException(String message) { super(message); diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/MediaTypeUnSupportException.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/MediaTypeUnSupportException.java index 7c3d922e44..29af0d7f1f 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/MediaTypeUnSupportException.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/MediaTypeUnSupportException.java @@ -16,7 +16,7 @@ */ package org.apache.dubbo.rpc.protocol.rest.exception; -public class MediaTypeUnSupportException extends RestException{ +public class MediaTypeUnSupportException extends RestException { public MediaTypeUnSupportException(String message) { super(message); } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/PathNoFoundException.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/PathNoFoundException.java index a8b2751fb3..e3ced44086 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/PathNoFoundException.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/PathNoFoundException.java @@ -19,7 +19,7 @@ package org.apache.dubbo.rpc.protocol.rest.exception; /** * response code : 404 path no found exception */ -public class PathNoFoundException extends RestException{ +public class PathNoFoundException extends RestException { public PathNoFoundException(String message) { super(message); diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/RemoteServerInternalException.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/RemoteServerInternalException.java index a552562dee..fce0964b67 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/RemoteServerInternalException.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/RemoteServerInternalException.java @@ -22,6 +22,6 @@ package org.apache.dubbo.rpc.protocol.rest.exception; public class RemoteServerInternalException extends RestException { public RemoteServerInternalException(String message) { - super("dubbo http rest protocol remote error :"+message); + super("dubbo http rest protocol remote error :" + message); } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/UnSupportContentTypeException.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/UnSupportContentTypeException.java index d4ad67b3b2..6ab784e854 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/UnSupportContentTypeException.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/UnSupportContentTypeException.java @@ -22,6 +22,7 @@ public class UnSupportContentTypeException extends MediaTypeUnSupportException { public UnSupportContentTypeException(String message) { - super("Current Support content type: " + MediaType.getAllContentType() + "; Do not support content type" + message); + super("Current Support content type: " + MediaType.getAllContentType() + "; Do not support content type" + + message); } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionHandler.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionHandler.java index 3a1c7fa99a..0c6f9fd5fc 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionHandler.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionHandler.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.rest.exception.mapper; - public interface ExceptionHandler { Object result(E exception); @@ -25,6 +23,4 @@ public interface ExceptionHandler { default int status() { return 200; } - - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionHandlerResult.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionHandlerResult.java index c0b890da7b..7c5109cace 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionHandlerResult.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionHandlerResult.java @@ -20,9 +20,7 @@ public class ExceptionHandlerResult { private int status; private Object entity; - public ExceptionHandlerResult() { - - } + public ExceptionHandlerResult() {} public ExceptionHandlerResult setStatus(int status) { this.status = status; @@ -48,9 +46,6 @@ public class ExceptionHandlerResult { @Override public String toString() { - return "ExceptionHandlerResult{" + - "status=" + status + - ", entity=" + entity + - '}'; + return "ExceptionHandlerResult{" + "status=" + status + ", entity=" + entity + '}'; } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionMapper.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionMapper.java index 0ed07c7bc9..c220499296 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionMapper.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionMapper.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.rest.exception.mapper; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -33,7 +32,6 @@ import java.util.concurrent.ConcurrentHashMap; public class ExceptionMapper { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); - private final Map, ExceptionHandler> exceptionHandlerMap = new ConcurrentHashMap<>(); private final Map allExceptionHandlers = new ConcurrentHashMap<>(); @@ -46,7 +44,6 @@ public class ExceptionMapper { return ExceptionHandlerResult.build().setEntity(result).setStatus(exceptionHandler.status()); } - public Object getExceptionHandler(Class causeClass) { return getExceptionHandler(allExceptionHandlers, causeClass); @@ -72,10 +69,8 @@ public class ExceptionMapper { return allExceptionHandlers.containsKey(throwable.getClass()); } - public void registerMapper(Class exceptionHandler) { - try { List methods = getExceptionHandlerMethods(exceptionHandler); @@ -107,19 +102,22 @@ public class ExceptionMapper { List> constructors = ReflectUtils.getConstructList(exceptionHandler); if (constructors.isEmpty()) { - throw new RuntimeException("dubbo rest exception mapper register mapper need exception handler exist no construct declare, current class is: " + exceptionHandler); + throw new RuntimeException( + "dubbo rest exception mapper register mapper need exception handler exist no construct declare, current class is: " + + exceptionHandler); } - // if exceptionHandler is inner class , no arg construct don`t appear , so newInstance don`t use noArgConstruct - Object handler = constructors.get(0).newInstance(new Object[constructors.get(0).getParameterCount()]); + // if exceptionHandler is inner class , no arg construct don`t appear , so newInstance don`t use + // noArgConstruct + Object handler = constructors + .get(0) + .newInstance(new Object[constructors.get(0).getParameterCount()]); putExtensionToMap(exceptions, handler); } catch (Exception e) { throw new RuntimeException("dubbo rest protocol exception mapper register error ", e); } - - } protected void putExtensionToMap(Set> exceptions, Object handler) { @@ -151,19 +149,24 @@ public class ExceptionMapper { try { registerMapper(ReflectUtils.findClass(exceptionMapper)); } catch (Exception e) { - logger.warn("", e.getMessage(), "", "dubbo rest protocol exception mapper register error ,and current exception mapper is :" + exceptionMapper); + logger.warn( + "", + e.getMessage(), + "", + "dubbo rest protocol exception mapper register error ,and current exception mapper is :" + + exceptionMapper); } - } - public void unRegisterMapper(Class exception) { exceptionHandlerMap.remove(exception); } public static boolean isSupport(Class exceptionHandler) { try { - return ExceptionHandler.class.isAssignableFrom(exceptionHandler) || ReflectUtils.findClassTryException("javax.ws.rs.ext.ExceptionMapper").isAssignableFrom(exceptionHandler); + return ExceptionHandler.class.isAssignableFrom(exceptionHandler) + || ReflectUtils.findClassTryException("javax.ws.rs.ext.ExceptionMapper") + .isAssignableFrom(exceptionHandler); } catch (Exception e) { return false; } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/RestEasyExceptionMapper.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/RestEasyExceptionMapper.java index 221bbb4e6e..6731dd04ed 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/RestEasyExceptionMapper.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/RestEasyExceptionMapper.java @@ -19,6 +19,7 @@ package org.apache.dubbo.rpc.protocol.rest.exception.mapper; import org.apache.dubbo.rpc.protocol.rest.util.ReflectUtils; import javax.ws.rs.core.Response; + import java.lang.reflect.Method; import java.util.List; import java.util.Map; @@ -31,7 +32,6 @@ public class RestEasyExceptionMapper extends ExceptionMapper { private final Map, javax.ws.rs.ext.ExceptionMapper> exceptionMappers = new ConcurrentHashMap<>(); - protected List getExceptionHandlerMethods(Class exceptionHandler) { if (!javax.ws.rs.ext.ExceptionMapper.class.isAssignableFrom(exceptionHandler)) { return super.getExceptionHandlerMethods(exceptionHandler); @@ -58,6 +58,4 @@ public class RestEasyExceptionMapper extends ExceptionMapper { return ExceptionHandlerResult.build().setStatus(response.getStatus()).setEntity(response.getEntity()); } - - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/ResteasyContext.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/ResteasyContext.java index 2134381842..d1e6ec0fa4 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/ResteasyContext.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/ResteasyContext.java @@ -16,10 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest.extension.resteasy; -import io.netty.buffer.ByteBuf; -import io.netty.handler.codec.http.HttpContent; -import io.netty.handler.codec.http.HttpHeaders; -import io.netty.handler.codec.http.HttpRequest; import org.apache.dubbo.common.URL; import org.apache.dubbo.metadata.rest.media.MediaType; import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; @@ -31,6 +27,20 @@ import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; import org.apache.dubbo.rpc.protocol.rest.request.NettyRequestFacade; import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; import org.apache.dubbo.rpc.protocol.rest.util.MediaTypeUtil; + +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.container.ContainerResponseFilter; +import javax.ws.rs.core.MultivaluedMap; + +import java.io.IOException; +import java.net.URI; +import java.util.List; +import java.util.Map; + +import io.netty.buffer.ByteBuf; +import io.netty.handler.codec.http.HttpContent; +import io.netty.handler.codec.http.HttpHeaders; +import io.netty.handler.codec.http.HttpRequest; import org.jboss.resteasy.core.interception.ResponseContainerRequestContext; import org.jboss.resteasy.plugins.server.netty.NettyHttpRequest; import org.jboss.resteasy.plugins.server.netty.NettyUtil; @@ -39,20 +49,11 @@ import org.jboss.resteasy.specimpl.ResteasyHttpHeaders; import org.jboss.resteasy.spi.HttpResponse; import org.jboss.resteasy.spi.ResteasyUriInfo; -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.container.ContainerResponseFilter; -import javax.ws.rs.core.MultivaluedMap; -import java.io.IOException; -import java.net.URI; -import java.util.List; -import java.util.Map; - public interface ResteasyContext { String HTTP_PROTOCOL = "http://"; String HTTP = "http"; String HTTPS_PROTOCOL = "https://"; - /** * return extensions that are filtered by extension type * @@ -63,11 +64,10 @@ public interface ResteasyContext { default List getExtension(ServiceDeployer serviceDeployer, Class extension) { return serviceDeployer.getExtensions(extension); - } - default DubboPreMatchContainerRequestContext convertHttpRequestToContainerRequestContext(RequestFacade requestFacade, ContainerRequestFilter[] requestFilters) { - + default DubboPreMatchContainerRequestContext convertHttpRequestToContainerRequestContext( + RequestFacade requestFacade, ContainerRequestFilter[] requestFilters) { NettyRequestFacade nettyRequestFacade = (NettyRequestFacade) requestFacade; HttpRequest request = (HttpRequest) requestFacade.getRequest(); @@ -78,7 +78,8 @@ public interface ResteasyContext { try { byte[] inputStream = requestFacade.getInputStream(); - ByteBuf buffer = nettyRequestFacade.getNettyChannelContext().alloc().buffer(); + ByteBuf buffer = + nettyRequestFacade.getNettyChannelContext().alloc().buffer(); buffer.writeBytes(inputStream); nettyRequest.setContentBuffer(buffer); } catch (IOException e) { @@ -86,7 +87,6 @@ public interface ResteasyContext { } return new DubboPreMatchContainerRequestContext(nettyRequest, requestFilters, null); - } default ResteasyUriInfo extractUriInfo(HttpRequest request) { @@ -112,31 +112,47 @@ public interface ResteasyContext { default NettyHttpRequest createNettyHttpRequest(NettyRequestFacade nettyRequestFacade, HttpRequest request) { ResteasyHttpHeaders headers = NettyUtil.extractHttpHeaders(request); ResteasyUriInfo uriInfo = extractUriInfo(request); - NettyHttpRequest nettyRequest = new NettyHttpRequest(nettyRequestFacade.getNettyChannelContext(), headers, uriInfo, request.getMethod().name(), - null, null, HttpHeaders.is100ContinueExpected(request)); + NettyHttpRequest nettyRequest = new NettyHttpRequest( + nettyRequestFacade.getNettyChannelContext(), + headers, + uriInfo, + request.getMethod().name(), + null, + null, + HttpHeaders.is100ContinueExpected(request)); return nettyRequest; } - default NettyHttpRequest createNettyHttpRequest(RequestFacade requestFacade) { NettyRequestFacade nettyRequestFacade = (NettyRequestFacade) requestFacade; HttpRequest request = (HttpRequest) requestFacade.getRequest(); ResteasyHttpHeaders headers = NettyUtil.extractHttpHeaders(request); ResteasyUriInfo uriInfo = extractUriInfo(request); - NettyHttpRequest nettyRequest = new NettyHttpRequest(nettyRequestFacade.getNettyChannelContext(), headers, uriInfo, request.getMethod().name(), - null, null, HttpHeaders.is100ContinueExpected(request)); + NettyHttpRequest nettyRequest = new NettyHttpRequest( + nettyRequestFacade.getNettyChannelContext(), + headers, + uriInfo, + request.getMethod().name(), + null, + null, + HttpHeaders.is100ContinueExpected(request)); return nettyRequest; } - default void writeResteasyResponse(URL url, RequestFacade requestFacade, NettyHttpResponse response, BuiltResponse restResponse) throws Exception { + default void writeResteasyResponse( + URL url, RequestFacade requestFacade, NettyHttpResponse response, BuiltResponse restResponse) + throws Exception { if (restResponse.getMediaType() != null) { - MediaType mediaType = MediaTypeUtil.convertMediaType(restResponse.getEntityClass(), restResponse.getMediaType().toString()); - ServiceInvokeRestFilter.writeResult(response, url, restResponse.getEntity(), restResponse.getEntityClass(), mediaType); + MediaType mediaType = MediaTypeUtil.convertMediaType( + restResponse.getEntityClass(), restResponse.getMediaType().toString()); + ServiceInvokeRestFilter.writeResult( + response, url, restResponse.getEntity(), restResponse.getEntityClass(), mediaType); } else { - ServiceInvokeRestFilter.writeResult(response, requestFacade, url, restResponse.getEntity(), restResponse.getEntityClass()); + ServiceInvokeRestFilter.writeResult( + response, requestFacade, url, restResponse.getEntity(), restResponse.getEntityClass()); } } @@ -160,13 +176,19 @@ public interface ResteasyContext { } } - default DubboContainerResponseContextImpl createContainerResponseContext(Object originRequest, RequestFacade request, HttpResponse httpResponse, BuiltResponse jaxrsResponse, ContainerResponseFilter[] responseFilters) { + default DubboContainerResponseContextImpl createContainerResponseContext( + Object originRequest, + RequestFacade request, + HttpResponse httpResponse, + BuiltResponse jaxrsResponse, + ContainerResponseFilter[] responseFilters) { - NettyHttpRequest nettyHttpRequest = originRequest == null ? createNettyHttpRequest(request) : (NettyHttpRequest) originRequest; + NettyHttpRequest nettyHttpRequest = + originRequest == null ? createNettyHttpRequest(request) : (NettyHttpRequest) originRequest; ResponseContainerRequestContext requestContext = new ResponseContainerRequestContext(nettyHttpRequest); - DubboContainerResponseContextImpl responseContext = new DubboContainerResponseContextImpl(nettyHttpRequest, httpResponse, jaxrsResponse, - requestContext, responseFilters, null, null); + DubboContainerResponseContextImpl responseContext = new DubboContainerResponseContextImpl( + nettyHttpRequest, httpResponse, jaxrsResponse, requestContext, responseFilters, null, null); return responseContext; } @@ -175,6 +197,4 @@ public interface ResteasyContext { ChunkOutputStream outputStream = (ChunkOutputStream) response.getOutputStream(); outputStream.reset(); } - - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboBuiltResponse.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboBuiltResponse.java index 1a034c2891..30af535744 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboBuiltResponse.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboBuiltResponse.java @@ -33,7 +33,6 @@ public class DubboBuiltResponse extends BuiltResponse { this.status = status; } - @Override public void setEntity(Object entity) { if (entity == null) { diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboContainerResponseContextImpl.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboContainerResponseContextImpl.java index 65246fcd57..4812038a0c 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboContainerResponseContextImpl.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboContainerResponseContextImpl.java @@ -18,6 +18,28 @@ package org.apache.dubbo.rpc.protocol.rest.extension.resteasy.filter; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.container.ContainerResponseFilter; +import javax.ws.rs.core.EntityTag; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.Link; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.NewCookie; +import javax.ws.rs.core.Response; + +import java.io.IOException; +import java.io.OutputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.net.URI; +import java.util.Date; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; + import org.jboss.resteasy.core.Dispatcher; import org.jboss.resteasy.core.ServerResponseWriter; import org.jboss.resteasy.core.SynchronousDispatcher; @@ -30,28 +52,9 @@ import org.jboss.resteasy.spi.HttpResponse; import org.jboss.resteasy.spi.ResteasyAsynchronousResponse; import org.jboss.resteasy.spi.ResteasyProviderFactory; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.container.ContainerResponseFilter; -import javax.ws.rs.core.EntityTag; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.Link; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.NewCookie; -import javax.ws.rs.core.Response; -import java.io.IOException; -import java.io.OutputStream; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; -import java.net.URI; -import java.util.Date; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.function.Consumer; - public class DubboContainerResponseContextImpl implements SuspendableContainerResponseContext { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboContainerResponseContextImpl.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(DubboContainerResponseContextImpl.class); protected final HttpRequest request; protected final HttpResponse httpResponse; @@ -68,10 +71,14 @@ public class DubboContainerResponseContextImpl implements SuspendableContainerRe private Consumer onComplete; private boolean weSuspended; - - public DubboContainerResponseContextImpl(final HttpRequest request, final HttpResponse httpResponse, final BuiltResponse serverResponse, - final ResponseContainerRequestContext requestContext, final ContainerResponseFilter[] responseFilters, - final Consumer onComplete, final ServerResponseWriter.RunnableWithIOException continuation) { + public DubboContainerResponseContextImpl( + final HttpRequest request, + final HttpResponse httpResponse, + final BuiltResponse serverResponse, + final ResponseContainerRequestContext requestContext, + final ContainerResponseFilter[] responseFilters, + final Consumer onComplete, + final ServerResponseWriter.RunnableWithIOException continuation) { this.request = request; this.httpResponse = httpResponse; this.jaxrsResponse = serverResponse; @@ -126,9 +133,9 @@ public class DubboContainerResponseContextImpl implements SuspendableContainerRe public void setEntity(Object entity) { if (entity != null && jaxrsResponse.getEntity() != null) { if (logger.isDebugEnabled()) { - logger.debug("Dubbo container response context filter set entity ,before entity is: " + jaxrsResponse.getEntity() + "and after entity is: " + entity); + logger.debug("Dubbo container response context filter set entity ,before entity is: " + + jaxrsResponse.getEntity() + "and after entity is: " + entity); } - } jaxrsResponse.setEntity(entity); // it resets the entity in a response filter which results @@ -141,7 +148,8 @@ public class DubboContainerResponseContextImpl implements SuspendableContainerRe public void setEntity(Object entity, Annotation[] annotations, MediaType mediaType) { if (entity != null && jaxrsResponse.getEntity() != null) { if (logger.isDebugEnabled()) { - logger.debug("Dubbo container response context filter set entity ,before entity is: " + jaxrsResponse.getEntity() + "and after entity is: " + entity); + logger.debug("Dubbo container response context filter set entity ,before entity is: " + + jaxrsResponse.getEntity() + "and after entity is: " + entity); } } jaxrsResponse.setEntity(entity); @@ -262,18 +270,15 @@ public class DubboContainerResponseContextImpl implements SuspendableContainerRe return jaxrsResponse.getHeaderString(name); } - @Override public synchronized void suspend() { - if (continuation == null) - throw new RuntimeException("Suspend not supported yet"); + if (continuation == null) throw new RuntimeException("Suspend not supported yet"); suspended = true; } @Override public synchronized void resume() { - if (!suspended) - throw new RuntimeException("Cannot resume: not suspended"); + if (!suspended) throw new RuntimeException("Cannot resume: not suspended"); if (inFilter) { // suspend/resume within filter, same thread: just ignore and move on suspended = false; @@ -281,7 +286,8 @@ public class DubboContainerResponseContextImpl implements SuspendableContainerRe } // go on, but with proper exception handling - try (ResteasyProviderFactory.CloseableContext c = ResteasyProviderFactory.addCloseableContextDataLevel(contextDataMap)) { + try (ResteasyProviderFactory.CloseableContext c = + ResteasyProviderFactory.addCloseableContextDataLevel(contextDataMap)) { filter(); } catch (Throwable t) { // don't throw to client @@ -291,14 +297,14 @@ public class DubboContainerResponseContextImpl implements SuspendableContainerRe @Override public synchronized void resume(Throwable t) { - if (!suspended) - throw new RuntimeException("Cannot resume: not suspended"); + if (!suspended) throw new RuntimeException("Cannot resume: not suspended"); if (inFilter) { // not suspended, or suspend/abortWith within filter, same thread: collect and move on throwable = t; suspended = false; } else { - try (ResteasyProviderFactory.CloseableContext c = ResteasyProviderFactory.addCloseableContextDataLevel(contextDataMap)) { + try (ResteasyProviderFactory.CloseableContext c = + ResteasyProviderFactory.addCloseableContextDataLevel(contextDataMap)) { writeException(t); } } @@ -343,8 +349,7 @@ public class DubboContainerResponseContextImpl implements SuspendableContainerRe } if (throwable != null) { // handle the case where we've been suspended by a previous filter - if (filterReturnIsMeaningful) - SynchronousDispatcher.rethrow(throwable); + if (filterReturnIsMeaningful) SynchronousDispatcher.rethrow(throwable); else { writeException(throwable); return; @@ -356,8 +361,7 @@ public class DubboContainerResponseContextImpl implements SuspendableContainerRe // some frameworks don't support async request filters, in which case suspend() is forbidden // so if we get here we're still synchronous and don't have a continuation, which must be in // the caller - if (continuation == null) - return; + if (continuation == null) return; // if we've never been suspended, the caller is valid so let it handle any exception if (filterReturnIsMeaningful) { @@ -372,11 +376,18 @@ public class DubboContainerResponseContextImpl implements SuspendableContainerRe onComplete.accept(null); if (weSuspended) { // if we're the ones who turned the request async, nobody will call complete() for us, so we have to - HttpServletRequest httpServletRequest = (HttpServletRequest) contextDataMap.get(HttpServletRequest.class); + HttpServletRequest httpServletRequest = + (HttpServletRequest) contextDataMap.get(HttpServletRequest.class); httpServletRequest.getAsyncContext().complete(); } } catch (IOException e) { - logger.error("", "Dubbo container response context filter error", "request method is: " + request.getHttpMethod() + "and request uri is:" + request.getUri().getPath(), "", e); + logger.error( + "", + "Dubbo container response context filter error", + "request method is: " + request.getHttpMethod() + "and request uri is:" + + request.getUri().getPath(), + "", + e); } } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboPreMatchContainerRequestContext.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboPreMatchContainerRequestContext.java index 3369659e60..4964f1792d 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboPreMatchContainerRequestContext.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/DubboPreMatchContainerRequestContext.java @@ -16,13 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest.extension.resteasy.filter; -import org.jboss.resteasy.core.interception.jaxrs.SuspendableContainerRequestContext; -import org.jboss.resteasy.plugins.server.netty.NettyHttpRequest; -import org.jboss.resteasy.specimpl.BuiltResponse; -import org.jboss.resteasy.specimpl.ResteasyHttpHeaders; -import org.jboss.resteasy.spi.ApplicationException; -import org.jboss.resteasy.spi.ResteasyProviderFactory; - import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.MediaType; @@ -31,6 +24,7 @@ import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; + import java.io.IOException; import java.io.InputStream; import java.net.URI; @@ -43,6 +37,13 @@ import java.util.Locale; import java.util.Map; import java.util.function.Supplier; +import org.jboss.resteasy.core.interception.jaxrs.SuspendableContainerRequestContext; +import org.jboss.resteasy.plugins.server.netty.NettyHttpRequest; +import org.jboss.resteasy.specimpl.BuiltResponse; +import org.jboss.resteasy.specimpl.ResteasyHttpHeaders; +import org.jboss.resteasy.spi.ApplicationException; +import org.jboss.resteasy.spi.ResteasyProviderFactory; + public class DubboPreMatchContainerRequestContext implements SuspendableContainerRequestContext { protected final NettyHttpRequest httpRequest; protected Response response; @@ -56,9 +57,10 @@ public class DubboPreMatchContainerRequestContext implements SuspendableContaine private Throwable throwable; private boolean startedContinuation; - - public DubboPreMatchContainerRequestContext(final NettyHttpRequest request, - final ContainerRequestFilter[] requestFilters, final Supplier continuation) { + public DubboPreMatchContainerRequestContext( + final NettyHttpRequest request, + final ContainerRequestFilter[] requestFilters, + final Supplier continuation) { this.httpRequest = request; this.requestFilters = requestFilters; this.continuation = continuation; @@ -200,15 +202,15 @@ public class DubboPreMatchContainerRequestContext implements SuspendableContaine @Override public synchronized void suspend() { - if (continuation == null) - throw new RuntimeException("Suspend not supported yet"); + if (continuation == null) throw new RuntimeException("Suspend not supported yet"); suspended = true; } @Override public synchronized void abortWith(Response response) { if (suspended && !inFilter) { - try (ResteasyProviderFactory.CloseableContext c = ResteasyProviderFactory.addCloseableContextDataLevel(contextDataMap)) { + try (ResteasyProviderFactory.CloseableContext c = + ResteasyProviderFactory.addCloseableContextDataLevel(contextDataMap)) { httpRequest.getAsyncContext().getAsyncResponse().resume(response); } } else { @@ -220,8 +222,7 @@ public class DubboPreMatchContainerRequestContext implements SuspendableContaine @Override public synchronized void resume() { - if (!suspended) - throw new RuntimeException("Cannot resume: not suspended"); + if (!suspended) throw new RuntimeException("Cannot resume: not suspended"); if (inFilter) { // suspend/resume within filter, same thread: just ignore and move on suspended = false; @@ -229,7 +230,8 @@ public class DubboPreMatchContainerRequestContext implements SuspendableContaine } // go on, but with proper exception handling - try (ResteasyProviderFactory.CloseableContext c = ResteasyProviderFactory.addCloseableContextDataLevel(contextDataMap)) { + try (ResteasyProviderFactory.CloseableContext c = + ResteasyProviderFactory.addCloseableContextDataLevel(contextDataMap)) { filter(); } catch (Throwable t) { // don't throw to client @@ -239,14 +241,14 @@ public class DubboPreMatchContainerRequestContext implements SuspendableContaine @Override public synchronized void resume(Throwable t) { - if (!suspended) - throw new RuntimeException("Cannot resume: not suspended"); + if (!suspended) throw new RuntimeException("Cannot resume: not suspended"); if (inFilter) { // not suspended, or suspend/abortWith within filter, same thread: collect and move on throwable = t; suspended = false; } else { - try (ResteasyProviderFactory.CloseableContext c = ResteasyProviderFactory.addCloseableContextDataLevel(contextDataMap)) { + try (ResteasyProviderFactory.CloseableContext c = + ResteasyProviderFactory.addCloseableContextDataLevel(contextDataMap)) { writeException(t); } } @@ -297,8 +299,7 @@ public class DubboPreMatchContainerRequestContext implements SuspendableContaine // so if we get here we're still synchronous and don't have a continuation, which must be in // the caller startedContinuation = true; - if (continuation == null) - return null; + if (continuation == null) return null; // in any case, return the continuation: sync will use it, and async will ignore it return continuation.get(); } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyNettyHttpResponse.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyNettyHttpResponse.java index 1b05c72220..826f84df70 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyNettyHttpResponse.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyNettyHttpResponse.java @@ -17,16 +17,18 @@ package org.apache.dubbo.rpc.protocol.rest.extension.resteasy.filter; import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; -import org.jboss.resteasy.specimpl.MultivaluedMapImpl; -import org.jboss.resteasy.spi.HttpResponse; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.NewCookie; + import java.io.IOException; import java.io.OutputStream; import java.util.List; import java.util.Map; +import org.jboss.resteasy.specimpl.MultivaluedMapImpl; +import org.jboss.resteasy.spi.HttpResponse; + public class ResteasyNettyHttpResponse implements HttpResponse { private NettyHttpResponse response; @@ -44,7 +46,6 @@ public class ResteasyNettyHttpResponse implements HttpResponse { } } - @Override public int getStatus() { return response.getStatus(); @@ -72,9 +73,7 @@ public class ResteasyNettyHttpResponse implements HttpResponse { } @Override - public void addNewCookie(NewCookie cookie) { - - } + public void addNewCookie(NewCookie cookie) {} @Override public void sendError(int status) throws IOException { @@ -99,7 +98,5 @@ public class ResteasyNettyHttpResponse implements HttpResponse { } @Override - public void flushBuffer() throws IOException { - - } + public void flushBuffer() throws IOException {} } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyRequestContainerFilterAdapter.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyRequestContainerFilterAdapter.java index 851da89a2f..6cb0aa07d9 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyRequestContainerFilterAdapter.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyRequestContainerFilterAdapter.java @@ -24,17 +24,23 @@ import org.apache.dubbo.rpc.protocol.rest.filter.RestRequestFilter; import org.apache.dubbo.rpc.protocol.rest.filter.context.RestFilterContext; import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; -import org.jboss.resteasy.specimpl.BuiltResponse; import javax.ws.rs.container.ContainerRequestFilter; + import java.util.List; +import org.jboss.resteasy.specimpl.BuiltResponse; - -@Activate(value = "resteasy", onClass = {"javax.ws.rs.container.ContainerRequestFilter", "org.jboss.resteasy.plugins.server.netty.NettyHttpRequest", "org.jboss.resteasy.plugins.server.netty.NettyHttpResponse"}, order = Integer.MAX_VALUE - 1) +@Activate( + value = "resteasy", + onClass = { + "javax.ws.rs.container.ContainerRequestFilter", + "org.jboss.resteasy.plugins.server.netty.NettyHttpRequest", + "org.jboss.resteasy.plugins.server.netty.NettyHttpResponse" + }, + order = Integer.MAX_VALUE - 1) public class ResteasyRequestContainerFilterAdapter implements RestRequestFilter, ResteasyContext { - @Override public void filter(RestFilterContext restFilterContext) throws Exception { @@ -43,15 +49,16 @@ public class ResteasyRequestContainerFilterAdapter implements RestRequestFilter, URL url = restFilterContext.getUrl(); NettyHttpResponse response = restFilterContext.getResponse(); - List containerRequestFilters = getExtension(serviceDeployer, ContainerRequestFilter.class); + List containerRequestFilters = + getExtension(serviceDeployer, ContainerRequestFilter.class); if (containerRequestFilters.isEmpty()) { return; } - - DubboPreMatchContainerRequestContext containerRequestContext = convertHttpRequestToContainerRequestContext(requestFacade, containerRequestFilters.toArray(new ContainerRequestFilter[0])); + DubboPreMatchContainerRequestContext containerRequestContext = convertHttpRequestToContainerRequestContext( + requestFacade, containerRequestFilters.toArray(new ContainerRequestFilter[0])); // set resteasy request for save user`s custom request attribute restFilterContext.setOriginRequest(containerRequestContext.getHttpRequest()); @@ -70,9 +77,5 @@ public class ResteasyRequestContainerFilterAdapter implements RestRequestFilter, } catch (Throwable e) { throw new RuntimeException("dubbo rest resteasy ContainerRequestFilter write response encode error", e); } - - } - - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyResponseContainerFilterAdapter.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyResponseContainerFilterAdapter.java index 89ea8a6e21..35e008e7f0 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyResponseContainerFilterAdapter.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/filter/ResteasyResponseContainerFilterAdapter.java @@ -24,23 +24,32 @@ import org.apache.dubbo.rpc.protocol.rest.filter.RestResponseFilter; import org.apache.dubbo.rpc.protocol.rest.filter.context.RestFilterContext; import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; -import org.jboss.resteasy.spi.HttpResponse; import javax.ws.rs.container.ContainerResponseFilter; + import java.util.List; -@Activate(value = "resteasy", order = Integer.MAX_VALUE - 1000, onClass = {"org.jboss.resteasy.specimpl.BuiltResponse", "javax.ws.rs.container.ContainerResponseFilter", "org.jboss.resteasy.spi.HttpResponse", "org.jboss.resteasy.plugins.server.netty.NettyHttpResponse"}) +import org.jboss.resteasy.spi.HttpResponse; + +@Activate( + value = "resteasy", + order = Integer.MAX_VALUE - 1000, + onClass = { + "org.jboss.resteasy.specimpl.BuiltResponse", + "javax.ws.rs.container.ContainerResponseFilter", + "org.jboss.resteasy.spi.HttpResponse", + "org.jboss.resteasy.plugins.server.netty.NettyHttpResponse" + }) public class ResteasyResponseContainerFilterAdapter implements RestResponseFilter, ResteasyContext { @Override public void filter(RestFilterContext restFilterContext) throws Exception { - ServiceDeployer serviceDeployer = restFilterContext.getServiceDeployer(); RequestFacade requestFacade = restFilterContext.getRequestFacade(); NettyHttpResponse response = restFilterContext.getResponse(); URL url = restFilterContext.getUrl(); - List containerRequestFilters = getExtension(serviceDeployer, ContainerResponseFilter.class); - + List containerRequestFilters = + getExtension(serviceDeployer, ContainerResponseFilter.class); if (containerRequestFilters.isEmpty()) { return; @@ -48,12 +57,17 @@ public class ResteasyResponseContainerFilterAdapter implements RestResponseFilte // response filter entity first - // build jaxrsResponse from rest netty response - DubboBuiltResponse dubboBuiltResponse = new DubboBuiltResponse(response.getResponseBody(), response.getStatus(), response.getEntityClass()); + DubboBuiltResponse dubboBuiltResponse = + new DubboBuiltResponse(response.getResponseBody(), response.getStatus(), response.getEntityClass()); // NettyHttpResponse wrapper HttpResponse httpResponse = new ResteasyNettyHttpResponse(response); - DubboContainerResponseContextImpl containerResponseContext = createContainerResponseContext(restFilterContext.getOriginRequest(),requestFacade, httpResponse, dubboBuiltResponse, containerRequestFilters.toArray(new ContainerResponseFilter[0])); + DubboContainerResponseContextImpl containerResponseContext = createContainerResponseContext( + restFilterContext.getOriginRequest(), + requestFacade, + httpResponse, + dubboBuiltResponse, + containerRequestFilters.toArray(new ContainerResponseFilter[0])); containerResponseContext.filter(); // user reset entity @@ -65,8 +79,5 @@ public class ResteasyResponseContainerFilterAdapter implements RestResponseFilte addResponseHeaders(response, httpResponse.getOutputHeaders()); restFilterContext.setComplete(true); - } - - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/intercept/DubboServerWriterInterceptorContext.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/intercept/DubboServerWriterInterceptorContext.java index 1a793b6b33..f1697edd80 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/intercept/DubboServerWriterInterceptorContext.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/intercept/DubboServerWriterInterceptorContext.java @@ -18,27 +18,49 @@ package org.apache.dubbo.rpc.protocol.rest.extension.resteasy.intercept; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; -import org.jboss.resteasy.core.interception.ServerWriterInterceptorContext; -import org.jboss.resteasy.spi.HttpRequest; -import org.jboss.resteasy.spi.ResteasyProviderFactory; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.WriterInterceptor; + import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; +import org.jboss.resteasy.core.interception.ServerWriterInterceptorContext; +import org.jboss.resteasy.spi.HttpRequest; +import org.jboss.resteasy.spi.ResteasyProviderFactory; + public class DubboServerWriterInterceptorContext extends ServerWriterInterceptorContext { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboServerWriterInterceptorContext.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(DubboServerWriterInterceptorContext.class); - public DubboServerWriterInterceptorContext(WriterInterceptor[] interceptors, ResteasyProviderFactory providerFactory, Object entity, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap headers, OutputStream outputStream, HttpRequest request) { - super(interceptors, providerFactory, entity, type, genericType, annotations, mediaType, headers, outputStream, request); + public DubboServerWriterInterceptorContext( + WriterInterceptor[] interceptors, + ResteasyProviderFactory providerFactory, + Object entity, + Class type, + Type genericType, + Annotation[] annotations, + MediaType mediaType, + MultivaluedMap headers, + OutputStream outputStream, + HttpRequest request) { + super( + interceptors, + providerFactory, + entity, + type, + genericType, + annotations, + mediaType, + headers, + outputStream, + request); } - @Override public void proceed() throws IOException, WebApplicationException { logger.debug("Dubbo server writer intercept context: " + getClass().getName() + " Method : proceed"); @@ -47,7 +69,8 @@ public class DubboServerWriterInterceptorContext extends ServerWriterInterceptor return; } else { - logger.debug("Dubbo server writer intercept context WriterInterceptor: " + interceptors[index].getClass().getName()); + logger.debug("Dubbo server writer intercept context WriterInterceptor: " + + interceptors[index].getClass().getName()); interceptors[index++].aroundWriteTo(this); } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/intercept/ResteasyWriterInterceptorAdapter.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/intercept/ResteasyWriterInterceptorAdapter.java index 60d7b63eff..5116fce40e 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/intercept/ResteasyWriterInterceptorAdapter.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/extension/resteasy/intercept/ResteasyWriterInterceptorAdapter.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest.extension.resteasy.intercept; -import org.apache.commons.io.IOUtils; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.protocol.rest.RestHeaderEnum; @@ -26,26 +25,34 @@ import org.apache.dubbo.rpc.protocol.rest.filter.RestResponseInterceptor; import org.apache.dubbo.rpc.protocol.rest.filter.context.RestInterceptContext; import org.apache.dubbo.rpc.protocol.rest.netty.NettyHttpResponse; import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.WriterInterceptor; + +import java.io.ByteArrayOutputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.List; + +import org.apache.commons.io.IOUtils; import org.jboss.resteasy.core.interception.AbstractWriterInterceptorContext; import org.jboss.resteasy.plugins.server.netty.NettyHttpRequest; import org.jboss.resteasy.specimpl.MultivaluedMapImpl; import org.jboss.resteasy.spi.HttpRequest; import org.jboss.resteasy.spi.ResteasyProviderFactory; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.ext.WriterInterceptor; -import java.io.ByteArrayOutputStream; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; -import java.util.List; - -@Activate(value = "resteasy", onClass = {"javax.ws.rs.ext.WriterInterceptorContext", "org.jboss.resteasy.plugins.server.netty.NettyHttpRequest", "org.jboss.resteasy.plugins.server.netty.NettyHttpResponse"}) +@Activate( + value = "resteasy", + onClass = { + "javax.ws.rs.ext.WriterInterceptorContext", + "org.jboss.resteasy.plugins.server.netty.NettyHttpRequest", + "org.jboss.resteasy.plugins.server.netty.NettyHttpResponse" + }) public class ResteasyWriterInterceptorAdapter implements RestResponseInterceptor, ResteasyContext { private ResteasyProviderFactory resteasyProviderFactory = getResteasyProviderFactory(); - @Override public void intercept(RestInterceptContext restResponseInterceptor) throws Exception { @@ -57,7 +64,6 @@ public class ResteasyWriterInterceptorAdapter implements RestResponseInterceptor Class type = rpcInvocation.getReturnType(); - List extension = serviceDeployer.getExtensions(WriterInterceptor.class); if (extension.isEmpty()) { @@ -78,7 +84,8 @@ public class ResteasyWriterInterceptorAdapter implements RestResponseInterceptor MediaType mediaType = MediaType.valueOf(value); - AbstractWriterInterceptorContext writerContext = getAbstractWriterInterceptorContext(restRequest, extension, result, type, type, mediaType, os, headers); + AbstractWriterInterceptorContext writerContext = getAbstractWriterInterceptorContext( + restRequest, extension, result, type, type, mediaType, os, headers); writerContext.proceed(); ByteArrayOutputStream outputStream = (ByteArrayOutputStream) writerContext.getOutputStream(); @@ -100,27 +107,32 @@ public class ResteasyWriterInterceptorAdapter implements RestResponseInterceptor } finally { IOUtils.close(os); } - } - - private AbstractWriterInterceptorContext getAbstractWriterInterceptorContext(HttpRequest request, - List extension, - Object entity, - Class type, - Type genericType, - MediaType mediaType, - ByteArrayOutputStream os, - MultivaluedMap headers) { - AbstractWriterInterceptorContext writerContext = new DubboServerWriterInterceptorContext(extension.toArray(new WriterInterceptor[0]), - resteasyProviderFactory, entity, type, genericType, new Annotation[0], mediaType, - headers, os, request); + private AbstractWriterInterceptorContext getAbstractWriterInterceptorContext( + HttpRequest request, + List extension, + Object entity, + Class type, + Type genericType, + MediaType mediaType, + ByteArrayOutputStream os, + MultivaluedMap headers) { + AbstractWriterInterceptorContext writerContext = new DubboServerWriterInterceptorContext( + extension.toArray(new WriterInterceptor[0]), + resteasyProviderFactory, + entity, + type, + genericType, + new Annotation[0], + mediaType, + headers, + os, + request); return writerContext; } protected ResteasyProviderFactory getResteasyProviderFactory() { return new ResteasyProviderFactory(); } - - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestFilter.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestFilter.java index 3bdb40457b..dc7608de8a 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestFilter.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestFilter.java @@ -24,5 +24,4 @@ import org.apache.dubbo.rpc.protocol.rest.filter.context.RestFilterContext; public interface RestFilter { void filter(RestFilterContext restFilterContext) throws Exception; - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestRequestFilter.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestRequestFilter.java index 7ed9419504..da5a2c9a75 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestRequestFilter.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestRequestFilter.java @@ -23,6 +23,4 @@ import org.apache.dubbo.common.extension.SPI; * Rest filter will be invoked before http handler */ @SPI(scope = ExtensionScope.FRAMEWORK) -public interface RestRequestFilter extends RestFilter { - -} +public interface RestRequestFilter extends RestFilter {} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestResponseFilter.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestResponseFilter.java index 200202dced..97fdf00c94 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestResponseFilter.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestResponseFilter.java @@ -23,6 +23,4 @@ import org.apache.dubbo.common.extension.SPI; * Rest response filter will be invoked when response is written to channel */ @SPI(scope = ExtensionScope.FRAMEWORK) -public interface RestResponseFilter extends RestFilter { - -} +public interface RestResponseFilter extends RestFilter {} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestResponseInterceptor.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestResponseInterceptor.java index 33a32ec108..8e824301ad 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestResponseInterceptor.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/RestResponseInterceptor.java @@ -27,5 +27,4 @@ import org.apache.dubbo.rpc.protocol.rest.filter.context.RestInterceptContext; public interface RestResponseInterceptor { void intercept(RestInterceptContext restResponseInterceptor) throws Exception; - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/ServiceInvokeRestFilter.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/ServiceInvokeRestFilter.java index 72508ce868..8c0d04a467 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/ServiceInvokeRestFilter.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/ServiceInvokeRestFilter.java @@ -16,8 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest.filter; -import io.netty.handler.codec.http.FullHttpRequest; -import io.netty.handler.codec.http.HttpRequest; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -48,6 +46,9 @@ import org.apache.dubbo.rpc.protocol.rest.util.MediaTypeUtil; import java.util.List; import java.util.Objects; +import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.handler.codec.http.HttpRequest; + @Activate(value = "invoke", order = Integer.MAX_VALUE) public class ServiceInvokeRestFilter implements RestRequestFilter { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); @@ -55,7 +56,8 @@ public class ServiceInvokeRestFilter implements RestRequestFilter { private final List restResponseInterceptors; public ServiceInvokeRestFilter(FrameworkModel frameworkModel) { - restResponseInterceptors = frameworkModel.getExtensionLoader(RestResponseInterceptor.class).getActivateExtensions(); + restResponseInterceptors = + frameworkModel.getExtensionLoader(RestResponseInterceptor.class).getActivateExtensions(); } @Override @@ -64,22 +66,23 @@ public class ServiceInvokeRestFilter implements RestRequestFilter { FullHttpRequest nettyHttpRequest = nettyRequestFacade.getRequest(); - doHandler(nettyHttpRequest, - restFilterContext.getResponse(), - restFilterContext.getRequestFacade(), - restFilterContext.getUrl(), - restFilterContext.getOriginRequest(), - restFilterContext.getServiceDeployer()); - + doHandler( + nettyHttpRequest, + restFilterContext.getResponse(), + restFilterContext.getRequestFacade(), + restFilterContext.getUrl(), + restFilterContext.getOriginRequest(), + restFilterContext.getServiceDeployer()); } - - private void doHandler(HttpRequest nettyHttpRequest, - NettyHttpResponse nettyHttpResponse, - RequestFacade request, - URL url, - Object originRequest,// resteasy request - ServiceDeployer serviceDeployer) throws Exception { + private void doHandler( + HttpRequest nettyHttpRequest, + NettyHttpResponse nettyHttpResponse, + RequestFacade request, + URL url, + Object originRequest, // resteasy request + ServiceDeployer serviceDeployer) + throws Exception { PathMatcher pathMatcher = RestRPCInvocationUtil.createPathMatcher(request); // path NoFound 404 @@ -87,23 +90,24 @@ public class ServiceInvokeRestFilter implements RestRequestFilter { throw new PathNoFoundException("rest service Path no found, current path info:" + pathMatcher); } - // method disallowed if (!serviceDeployer.isMethodAllowed(pathMatcher)) { - nettyHttpResponse.sendError(405, "service require request method is : " - + serviceDeployer.pathHttpMethods(pathMatcher) - + ", but current request method is: " + request.getMethod() - ); + nettyHttpResponse.sendError( + 405, + "service require request method is : " + + serviceDeployer.pathHttpMethods(pathMatcher) + + ", but current request method is: " + request.getMethod()); return; } // compare http method and acquire metadata by request - InvokerAndRestMethodMetadataPair restMethodMetadataPair = RestRPCInvocationUtil.getRestMethodMetadataAndInvokerPair(pathMatcher.compareHttpMethod(true), serviceDeployer); + InvokerAndRestMethodMetadataPair restMethodMetadataPair = + RestRPCInvocationUtil.getRestMethodMetadataAndInvokerPair( + pathMatcher.compareHttpMethod(true), serviceDeployer); Invoker invoker = restMethodMetadataPair.getInvoker(); RestMethodMetadata restMethodMetadata = restMethodMetadataPair.getRestMethodMetadata(); - // content-type support judge,throw unSupportException acceptSupportJudge(request, restMethodMetadata.getReflectMethod().getReturnType()); @@ -111,7 +115,8 @@ public class ServiceInvokeRestFilter implements RestRequestFilter { RpcInvocation rpcInvocation = RestRPCInvocationUtil.createBaseRpcInvocation(request, restMethodMetadata); // parse method real args - RestRPCInvocationUtil.parseMethodArgs(rpcInvocation, request, nettyHttpRequest, nettyHttpResponse, restMethodMetadata); + RestRPCInvocationUtil.parseMethodArgs( + rpcInvocation, request, nettyHttpRequest, nettyHttpResponse, restMethodMetadata); // execute business method invoke Result result = invoker.invoke(rpcInvocation); @@ -121,35 +126,40 @@ public class ServiceInvokeRestFilter implements RestRequestFilter { if (result.hasException()) { Throwable exception = result.getException(); - logger.error("", exception.getMessage(), "", "dubbo rest protocol provider Invoker invoke error", exception); + logger.error( + "", exception.getMessage(), "", "dubbo rest protocol provider Invoker invoke error", exception); if (serviceDeployer.getExceptionMapper().hasExceptionMapper(exception)) { - ExceptionHandlerResult exceptionToResult = serviceDeployer.getExceptionMapper().exceptionToResult(result.getException()); - writeResult(nettyHttpResponse, request, url, exceptionToResult.getEntity(), rpcInvocation.getReturnType()); + ExceptionHandlerResult exceptionToResult = + serviceDeployer.getExceptionMapper().exceptionToResult(result.getException()); + writeResult( + nettyHttpResponse, request, url, exceptionToResult.getEntity(), rpcInvocation.getReturnType()); nettyHttpResponse.setStatus(exceptionToResult.getStatus()); } else { - nettyHttpResponse.sendError(500, - "\n dubbo rest business exception, error cause is: " - + result.getException().getCause() - + "\n message is: " + result.getException().getMessage() - + "\n stacktrace is: " + stackTraceToString(exception)); + nettyHttpResponse.sendError( + 500, + "\n dubbo rest business exception, error cause is: " + + result.getException().getCause() + + "\n message is: " + result.getException().getMessage() + + "\n stacktrace is: " + stackTraceToString(exception)); } } try { - RestInterceptContext restFilterContext = new RestInterceptContext(url, request, nettyHttpResponse, serviceDeployer, result.getValue(), rpcInvocation); + RestInterceptContext restFilterContext = new RestInterceptContext( + url, request, nettyHttpResponse, serviceDeployer, result.getValue(), rpcInvocation); // set filter request restFilterContext.setOriginRequest(originRequest); // invoke the intercept chain before Result write to response executeResponseIntercepts(restFilterContext); } catch (Exception exception) { - logger.error("", exception.getMessage(), "", "dubbo rest protocol execute ResponseIntercepts error", exception); + logger.error( + "", exception.getMessage(), "", "dubbo rest protocol execute ResponseIntercepts error", exception); throw exception; } } - /** * write return value by accept * @@ -159,17 +169,22 @@ public class ServiceInvokeRestFilter implements RestRequestFilter { * @param returnType * @throws Exception */ - public static void writeResult(NettyHttpResponse nettyHttpResponse, RequestFacade request, URL url, Object value, Class returnType) throws Exception { + public static void writeResult( + NettyHttpResponse nettyHttpResponse, RequestFacade request, URL url, Object value, Class returnType) + throws Exception { MediaType mediaType = getAcceptMediaType(request, returnType); writeResult(nettyHttpResponse, url, value, returnType, mediaType); } - - public static void writeResult(NettyHttpResponse nettyHttpResponse, URL url, Object value, Class returnType, MediaType mediaType) throws Exception { - MessageCodecResultPair booleanMediaTypePair = HttpMessageCodecManager.httpMessageEncode(nettyHttpResponse.getOutputStream(), value, url, mediaType, returnType); + public static void writeResult( + NettyHttpResponse nettyHttpResponse, URL url, Object value, Class returnType, MediaType mediaType) + throws Exception { + MessageCodecResultPair booleanMediaTypePair = HttpMessageCodecManager.httpMessageEncode( + nettyHttpResponse.getOutputStream(), value, url, mediaType, returnType); // reset raw response result nettyHttpResponse.setResponseBody(value); - nettyHttpResponse.addOutputHeaders(RestHeaderEnum.CONTENT_TYPE.getHeader(), booleanMediaTypePair.getMediaType().value); + nettyHttpResponse.addOutputHeaders( + RestHeaderEnum.CONTENT_TYPE.getHeader(), booleanMediaTypePair.getMediaType().value); } /** @@ -203,16 +218,13 @@ public class ServiceInvokeRestFilter implements RestRequestFilter { throw e; } - if (!accept.contains(mediaType.value)) { throw e; } - } } - public static String stackTraceToString(Throwable throwable) { StackTraceElement[] stackTrace = throwable.getStackTrace(); @@ -232,7 +244,6 @@ public class ServiceInvokeRestFilter implements RestRequestFilter { */ public void executeResponseIntercepts(RestInterceptContext restFilterContext) throws Exception { - for (RestResponseInterceptor restResponseInterceptor : restResponseInterceptors) { restResponseInterceptor.intercept(restFilterContext); @@ -240,8 +251,6 @@ public class ServiceInvokeRestFilter implements RestRequestFilter { if (restFilterContext.complete()) { break; } - } - } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/ServiceInvokeRestResponseInterceptor.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/ServiceInvokeRestResponseInterceptor.java index c3832efbca..db3c3d8f25 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/ServiceInvokeRestResponseInterceptor.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/ServiceInvokeRestResponseInterceptor.java @@ -30,6 +30,11 @@ public class ServiceInvokeRestResponseInterceptor implements RestResponseInterce @Override public void intercept(RestInterceptContext restInterceptContext) throws Exception { - writeResult(restInterceptContext.getResponse(), restInterceptContext.getRequestFacade(), restInterceptContext.getUrl(), restInterceptContext.getResult(), restInterceptContext.getRpcInvocation().getReturnType()); + writeResult( + restInterceptContext.getResponse(), + restInterceptContext.getRequestFacade(), + restInterceptContext.getUrl(), + restInterceptContext.getResult(), + restInterceptContext.getRpcInvocation().getReturnType()); } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/FilterContext.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/FilterContext.java index d40c41e27e..c9544f47d8 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/FilterContext.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/FilterContext.java @@ -23,7 +23,6 @@ import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; public interface FilterContext { - URL getUrl(); RequestFacade getRequestFacade(); @@ -36,7 +35,7 @@ public interface FilterContext { void setComplete(boolean complete); - Object getOriginRequest(); + Object getOriginRequest(); Object getOriginResponse(); } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/RestFilterContext.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/RestFilterContext.java index bf2be29d45..dd3e2c5102 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/RestFilterContext.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/RestFilterContext.java @@ -30,7 +30,8 @@ public class RestFilterContext implements FilterContext { protected Object originRequest; protected Object originResponse; - public RestFilterContext(URL url, RequestFacade requestFacade, NettyHttpResponse response, ServiceDeployer serviceDeployer) { + public RestFilterContext( + URL url, RequestFacade requestFacade, NettyHttpResponse response, ServiceDeployer serviceDeployer) { this.url = url; this.requestFacade = requestFacade; this.response = response; diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/RestInterceptContext.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/RestInterceptContext.java index ee4ba10bd6..9ba91ae87d 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/RestInterceptContext.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/filter/context/RestInterceptContext.java @@ -24,11 +24,16 @@ import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; public class RestInterceptContext extends RestFilterContext { - private Object result; private RpcInvocation rpcInvocation; - public RestInterceptContext(URL url, RequestFacade requestFacade, NettyHttpResponse response, ServiceDeployer serviceDeployer, Object result, RpcInvocation rpcInvocation) { + public RestInterceptContext( + URL url, + RequestFacade requestFacade, + NettyHttpResponse response, + ServiceDeployer serviceDeployer, + Object result, + RpcInvocation rpcInvocation) { super(url, requestFacade, response, serviceDeployer); this.result = result; this.rpcInvocation = rpcInvocation; diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/handler/NettyHttpHandler.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/handler/NettyHttpHandler.java index c8aff6afc2..55b24de256 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/handler/NettyHttpHandler.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/handler/NettyHttpHandler.java @@ -37,7 +37,6 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; - /** * netty http request handler */ @@ -48,12 +47,15 @@ public class NettyHttpHandler implements HttpHandler restRequestFilters; private final List restResponseFilters; - public NettyHttpHandler(ServiceDeployer serviceDeployer, URL url) { this.serviceDeployer = serviceDeployer; this.url = url; - restRequestFilters = new ArrayList<>(url.getOrDefaultFrameworkModel().getExtensionLoader(RestRequestFilter.class).getActivateExtensions()); - restResponseFilters = new ArrayList<>(url.getOrDefaultFrameworkModel().getExtensionLoader(RestResponseFilter.class).getActivateExtensions()); + restRequestFilters = new ArrayList<>(url.getOrDefaultFrameworkModel() + .getExtensionLoader(RestRequestFilter.class) + .getActivateExtensions()); + restResponseFilters = new ArrayList<>(url.getOrDefaultFrameworkModel() + .getExtensionLoader(RestResponseFilter.class) + .getActivateExtensions()); } @Override @@ -73,7 +75,8 @@ public class NettyHttpHandler implements HttpHandler */ @SPI(scope = ExtensionScope.FRAMEWORK) -public interface HttpMessageCodec extends HttpMessageDecode, HttpMessageEncode { - +public interface HttpMessageCodec + extends HttpMessageDecode, HttpMessageEncode { /** * content-type support judge @@ -46,5 +45,4 @@ public interface HttpMessageCodec extends HttpMessage boolean typeSupport(Class targetType); MediaType contentType(); - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageCodecManager.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageCodecManager.java index eb34605eda..212ebb4ffb 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageCodecManager.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageCodecManager.java @@ -27,42 +27,45 @@ import java.lang.reflect.Type; import java.util.Set; public class HttpMessageCodecManager { - private static final Set httpMessageCodecs = - FrameworkModel.defaultModel().getExtensionLoader(HttpMessageCodec.class).getSupportedExtensionInstances(); + private static final Set httpMessageCodecs = FrameworkModel.defaultModel() + .getExtensionLoader(HttpMessageCodec.class) + .getSupportedExtensionInstances(); - - public static Object httpMessageDecode(byte[] body, Class type, Type actualType, MediaType mediaType) throws Exception { + public static Object httpMessageDecode(byte[] body, Class type, Type actualType, MediaType mediaType) + throws Exception { if (body == null || body.length == 0) { return null; } for (HttpMessageCodec httpMessageCodec : httpMessageCodecs) { if (httpMessageCodec.contentTypeSupport(mediaType, type) || typeJudge(mediaType, type, httpMessageCodec)) { - return httpMessageCodec.decode(body, type,actualType); + return httpMessageCodec.decode(body, type, actualType); } } throw new UnSupportContentTypeException("UnSupport content-type :" + mediaType.value); } - public static MessageCodecResultPair httpMessageEncode(OutputStream outputStream, Object unSerializedBody, URL url, MediaType mediaType, Class bodyType) throws Exception { - + public static MessageCodecResultPair httpMessageEncode( + OutputStream outputStream, Object unSerializedBody, URL url, MediaType mediaType, Class bodyType) + throws Exception { if (unSerializedBody == null) { for (HttpMessageCodec httpMessageCodec : httpMessageCodecs) { - if (httpMessageCodec.contentTypeSupport(mediaType, bodyType) || typeJudge(mediaType, bodyType, httpMessageCodec)) { + if (httpMessageCodec.contentTypeSupport(mediaType, bodyType) + || typeJudge(mediaType, bodyType, httpMessageCodec)) { return MessageCodecResultPair.pair(false, httpMessageCodec.contentType()); } } } for (HttpMessageCodec httpMessageCodec : httpMessageCodecs) { - if (httpMessageCodec.contentTypeSupport(mediaType, bodyType) || typeJudge(mediaType, bodyType, httpMessageCodec)) { + if (httpMessageCodec.contentTypeSupport(mediaType, bodyType) + || typeJudge(mediaType, bodyType, httpMessageCodec)) { httpMessageCodec.encode(outputStream, unSerializedBody, url); return MessageCodecResultPair.pair(true, httpMessageCodec.contentType()); } } - throw new UnSupportContentTypeException("UnSupport content-type :" + mediaType.value); } @@ -76,7 +79,8 @@ public class HttpMessageCodecManager { */ private static boolean typeJudge(MediaType mediaType, Class bodyType, HttpMessageCodec httpMessageCodec) { return (MediaType.ALL_VALUE.equals(mediaType) || mediaType == null) - && bodyType != null && httpMessageCodec.typeSupport(bodyType); + && bodyType != null + && httpMessageCodec.typeSupport(bodyType); } public static MediaType typeSupport(Class type) { @@ -85,11 +89,8 @@ public class HttpMessageCodecManager { if (httpMessageCodec.typeSupport(type)) { return httpMessageCodec.contentType(); } - } return null; } - - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageDecode.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageDecode.java index b072a8a9c2..8b32281600 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageDecode.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageDecode.java @@ -16,12 +16,9 @@ */ package org.apache.dubbo.rpc.protocol.rest.message; - import java.lang.reflect.Type; public interface HttpMessageDecode { - Object decode(InputStream body, Class targetType,Type actualTYpe) throws Exception; - - + Object decode(InputStream body, Class targetType, Type actualTYpe) throws Exception; } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageEncode.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageEncode.java index 6d35d9c43e..8ae427ec5e 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageEncode.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/HttpMessageEncode.java @@ -16,13 +16,9 @@ */ package org.apache.dubbo.rpc.protocol.rest.message; - import org.apache.dubbo.common.URL; - - public interface HttpMessageEncode { void encode(OutputStream outputStream, Object unSerializedBody, URL url) throws Exception; - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/MediaTypeMatcher.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/MediaTypeMatcher.java index 6db52df861..71152a81fa 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/MediaTypeMatcher.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/MediaTypeMatcher.java @@ -22,23 +22,18 @@ import java.util.ArrayList; import java.util.List; public enum MediaTypeMatcher { - - MULTI_VALUE(createMediaList(MediaType.APPLICATION_FORM_URLENCODED_VALUE)), APPLICATION_JSON(createMediaList(MediaType.APPLICATION_JSON_VALUE)), TEXT_PLAIN(createMediaList(MediaType.TEXT_PLAIN, MediaType.OCTET_STREAM)), TEXT_XML(createMediaList(MediaType.TEXT_XML)), - ; private List mediaTypes; - MediaTypeMatcher(List mediaTypes) { this.mediaTypes = mediaTypes; } - private static List createMediaList(MediaType... mediaTypes) { List mediaTypeList = getDefaultList(); @@ -58,6 +53,4 @@ public enum MediaTypeMatcher { public boolean mediaSupport(MediaType mediaType) { return mediaTypes.contains(mediaType); } - - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/ByteArrayCodec.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/ByteArrayCodec.java index ff15fc5663..2dc0a85ad7 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/ByteArrayCodec.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/ByteArrayCodec.java @@ -30,7 +30,6 @@ import java.lang.reflect.Type; @Activate("byteArray") public class ByteArrayCodec implements HttpMessageCodec { - @Override public Object decode(byte[] body, Class targetType, Type type) throws Exception { return body; @@ -51,7 +50,6 @@ public class ByteArrayCodec implements HttpMessageCodec { return MediaType.OCTET_STREAM; } - @Override public void encode(OutputStream outputStream, Object unSerializedBody, URL url) throws Exception { outputStream.write((byte[]) unSerializedBody); diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/JsonCodec.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/JsonCodec.java index 96fde0a09a..0c3cedf8e9 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/JsonCodec.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/JsonCodec.java @@ -62,13 +62,11 @@ public class JsonCodec implements HttpMessageCodec { return MediaType.APPLICATION_JSON_VALUE; } - @Override public void encode(OutputStream outputStream, Object unSerializedBody, URL url) throws Exception { outputStream.write(JsonUtils.toJson(unSerializedBody).getBytes(StandardCharsets.UTF_8)); } - public static final void addUnSupportClass(Class unSupportClass) { unSupportClasses.add(unSupportClass); } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/MultiValueCodec.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/MultiValueCodec.java index ee11bb5954..a78f793c7b 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/MultiValueCodec.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/MultiValueCodec.java @@ -38,10 +38,9 @@ import java.util.Set; @Activate("multiValue") public class MultiValueCodec implements HttpMessageCodec { - @Override public Object decode(byte[] body, Class targetType, Type type) throws Exception { - Object map = DataParseUtils.multipartFormConvert(body,targetType); + Object map = DataParseUtils.multipartFormConvert(body, targetType); Map valuesMap = (Map) map; if (Map.class.isAssignableFrom(targetType)) { return map; @@ -57,10 +56,8 @@ public class MultiValueCodec implements HttpMessageCodec { } return DataParseUtils.stringTypeConvert(targetType, String.valueOf(((List) value).get(0))); - } else { - Map beanPropertyFields = ReflectUtils.getBeanPropertyFields(targetType); Object emptyObject = ReflectUtils.getEmptyObject(targetType); @@ -69,7 +66,11 @@ public class MultiValueCodec implements HttpMessageCodec { try { List values = (List) valuesMap.get(entry.getKey()); String value = values == null ? null : String.valueOf(values.get(0)); - entry.getValue().set(emptyObject, DataParseUtils.stringTypeConvert(entry.getValue().getType(), value)); + entry.getValue() + .set( + emptyObject, + DataParseUtils.stringTypeConvert( + entry.getValue().getType(), value)); } catch (IllegalAccessException e) { } @@ -77,10 +78,8 @@ public class MultiValueCodec implements HttpMessageCodec { return emptyObject; } - } - @Override public boolean contentTypeSupport(MediaType mediaType, Class targetType) { return MediaTypeMatcher.MULTI_VALUE.mediaSupport(mediaType); diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/ResteasyResponseCodec.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/ResteasyResponseCodec.java index 9717df88d7..0cb0efc7b1 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/ResteasyResponseCodec.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/ResteasyResponseCodec.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.rest.message.codec; import org.apache.dubbo.common.URL; diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/StringCodec.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/StringCodec.java index 726c007f67..4f939ea7fb 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/StringCodec.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/StringCodec.java @@ -31,7 +31,6 @@ import java.nio.charset.StandardCharsets; @Activate("string") public class StringCodec implements HttpMessageCodec { - @Override public Object decode(byte[] body, Class targetType, Type type) throws Exception { if (body == null || body.length == 0) { @@ -41,7 +40,7 @@ public class StringCodec implements HttpMessageCodec { } @Override - public boolean contentTypeSupport(MediaType mediaType,Class targetType) { + public boolean contentTypeSupport(MediaType mediaType, Class targetType) { return String.class.equals(targetType); } @@ -55,10 +54,8 @@ public class StringCodec implements HttpMessageCodec { return MediaType.TEXT_PLAIN; } - @Override public void encode(OutputStream outputStream, Object unSerializedBody, URL url) throws Exception { outputStream.write(((String) unSerializedBody).getBytes(StandardCharsets.UTF_8)); } - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/TextCodec.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/TextCodec.java index 69c4eaa35a..16f13bd413 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/TextCodec.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/TextCodec.java @@ -38,7 +38,6 @@ public class TextCodec implements HttpMessageCodec { return DataParseUtils.stringTypeConvert(targetType, new String(body, StandardCharsets.UTF_8)); } - @Override public boolean contentTypeSupport(MediaType mediaType, Class targetType) { return MediaTypeMatcher.TEXT_PLAIN.mediaSupport(mediaType); diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/XMLCodec.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/XMLCodec.java index d24d27a85f..f696c91e8e 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/XMLCodec.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/message/codec/XMLCodec.java @@ -22,41 +22,40 @@ import org.apache.dubbo.metadata.rest.media.MediaType; import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodec; import org.apache.dubbo.rpc.protocol.rest.message.MediaTypeMatcher; -import org.xml.sax.InputSource; - import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.Source; import javax.xml.transform.sax.SAXSource; + import java.io.OutputStream; import java.io.StringReader; import java.lang.reflect.Type; +import org.xml.sax.InputSource; + /** * body content-type is xml */ @Activate("xml") public class XMLCodec implements HttpMessageCodec { - @Override public Object decode(byte[] body, Class targetType, Type type) throws Exception { - SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setFeature("http://xml.org/sax/features/external-general-entities", false); spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); // Do unmarshall operation - Source xmlSource = new SAXSource(spf.newSAXParser().getXMLReader(), new InputSource(new StringReader(new String(body)))); + Source xmlSource = + new SAXSource(spf.newSAXParser().getXMLReader(), new InputSource(new StringReader(new String(body)))); JAXBContext context = JAXBContext.newInstance(targetType); Unmarshaller unmarshaller = context.createUnmarshaller(); return unmarshaller.unmarshal(xmlSource); - } @Override @@ -74,12 +73,10 @@ public class XMLCodec implements HttpMessageCodec { return MediaType.TEXT_XML; } - @Override public void encode(OutputStream outputStream, Object unSerializedBody, URL url) throws Exception { - Marshaller marshaller = JAXBContext.newInstance(unSerializedBody.getClass()).createMarshaller(); + Marshaller marshaller = + JAXBContext.newInstance(unSerializedBody.getClass()).createMarshaller(); marshaller.marshal(unSerializedBody, outputStream); } - - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ChunkOutputStream.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ChunkOutputStream.java index 0e9d9bb904..dcc602ba01 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ChunkOutputStream.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/ChunkOutputStream.java @@ -16,15 +16,15 @@ */ package org.apache.dubbo.rpc.protocol.rest.netty; +import org.apache.dubbo.remoting.transport.ExceedPayloadLimitException; + +import java.io.IOException; +import java.io.OutputStream; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.DefaultHttpContent; -import org.apache.dubbo.remoting.transport.ExceedPayloadLimitException; - -import java.io.IOException; -import java.io.OutputStream; public class ChunkOutputStream extends OutputStream { final ByteBuf buffer; @@ -51,8 +51,7 @@ public class ChunkOutputStream extends OutputStream { } private void throwExceedPayloadLimitException(int dataSize) throws ExceedPayloadLimitException { - throw new ExceedPayloadLimitException( - "Data length too large: " + dataSize + ", max payload: " + chunkSize); + throw new ExceedPayloadLimitException("Data length too large: " + dataSize + ", max payload: " + chunkSize); } public void reset() { @@ -66,7 +65,6 @@ public class ChunkOutputStream extends OutputStream { super.close(); } - @Override public void write(byte[] b, int off, int len) throws IOException { int dataLengthLeftToWrite = len; @@ -86,6 +84,4 @@ public class ChunkOutputStream extends OutputStream { buffer.clear(); super.flush(); } - } - diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/HttpResponse.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/HttpResponse.java index 890fe039b9..888547bf5b 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/HttpResponse.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/HttpResponse.java @@ -16,13 +16,11 @@ */ package org.apache.dubbo.rpc.protocol.rest.netty; - import java.io.IOException; import java.io.OutputStream; import java.util.List; import java.util.Map; - public interface HttpResponse { int getStatus(); @@ -34,7 +32,6 @@ public interface HttpResponse { void setOutputStream(OutputStream os); - void sendError(int status) throws IOException; void sendError(int status, String message) throws IOException; @@ -48,8 +45,5 @@ public interface HttpResponse { void flushBuffer() throws IOException; - void addOutputHeaders(String name, String value); - } - diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/NettyHttpResponse.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/NettyHttpResponse.java index 4ed2c5525b..72256f53e9 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/NettyHttpResponse.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/NettyHttpResponse.java @@ -16,6 +16,18 @@ */ package org.apache.dubbo.rpc.protocol.rest.netty; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.metadata.rest.media.MediaType; +import org.apache.dubbo.remoting.Constants; +import org.apache.dubbo.rpc.protocol.rest.RestHeaderEnum; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; @@ -27,23 +39,9 @@ import io.netty.handler.codec.http.HttpHeaders.Names; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.LastHttpContent; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.metadata.rest.media.MediaType; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.rpc.protocol.rest.RestHeaderEnum; - - -import java.io.IOException; -import java.io.OutputStream; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; - /** * netty http response */ @@ -65,7 +63,7 @@ public class NettyHttpResponse implements HttpResponse { this(ctx, keepAlive, null, url); } - public NettyHttpResponse(final ChannelHandlerContext ctx, final boolean keepAlive, HttpMethod method, URL url) { + public NettyHttpResponse(final ChannelHandlerContext ctx, final boolean keepAlive, HttpMethod method, URL url) { outputHeaders = new HashMap<>(); this.method = method; os = new ChunkOutputStream(this, ctx, url.getParameter(Constants.PAYLOAD_KEY, Constants.DEFAULT_PAYLOAD)); @@ -73,7 +71,6 @@ public class NettyHttpResponse implements HttpResponse { this.keepAlive = keepAlive; } - public void setOutputStream(OutputStream os) { this.os = os; } @@ -101,7 +98,6 @@ public class NettyHttpResponse implements HttpResponse { return os; } - @Override public void sendError(int status) throws IOException { sendError(status, null); @@ -114,7 +110,6 @@ public class NettyHttpResponse implements HttpResponse { if (message != null) { getOutputStream().write(message.getBytes(StandardCharsets.UTF_8)); } - } @Override @@ -155,7 +150,6 @@ public class NettyHttpResponse implements HttpResponse { transformHeaders(this, res); } - public void prepareChunkStream() { committed = true; DefaultHttpResponse response = getDefaultHttpResponse(); @@ -164,8 +158,7 @@ public class NettyHttpResponse implements HttpResponse { } public void finish() throws IOException { - if (os != null) - os.flush(); + if (os != null) os.flush(); ChannelFuture future; if (isCommitted()) { // if committed this means the output stream was used. @@ -183,8 +176,7 @@ public class NettyHttpResponse implements HttpResponse { @Override public void flushBuffer() throws IOException { - if (os != null) - os.flush(); + if (os != null) os.flush(); ctx.flush(); } @@ -202,20 +194,21 @@ public class NettyHttpResponse implements HttpResponse { } @SuppressWarnings({"rawtypes", "unchecked"}) - public static void transformHeaders(NettyHttpResponse nettyResponse, io.netty.handler.codec.http.HttpResponse response) { -// if (nettyResponse.isKeepAlive()) { -// response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); -// } else { -// response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); -// } + public static void transformHeaders( + NettyHttpResponse nettyResponse, io.netty.handler.codec.http.HttpResponse response) { + // if (nettyResponse.isKeepAlive()) { + // response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); + // } else { + // response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); + // } - for (Map.Entry> entry : nettyResponse.getOutputHeaders().entrySet()) { + for (Map.Entry> entry : + nettyResponse.getOutputHeaders().entrySet()) { String key = entry.getKey(); for (String value : entry.getValue()) { response.headers().set(key, value); } } - } public Object getResponseBody() { diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/RestHttpRequestDecoder.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/RestHttpRequestDecoder.java index d5233c3e10..f89d229d9a 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/RestHttpRequestDecoder.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/netty/RestHttpRequestDecoder.java @@ -14,17 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.rest.netty; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.MessageToMessageDecoder; - -import java.io.IOException; -import java.util.List; -import java.util.concurrent.Executor; - -import io.netty.handler.codec.http.HttpHeaders; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -35,8 +26,15 @@ import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; import org.apache.dubbo.rpc.protocol.rest.handler.NettyHttpHandler; import org.apache.dubbo.rpc.protocol.rest.request.NettyRequestFacade; -import static org.apache.dubbo.config.Constants.SERVER_THREAD_POOL_NAME; +import java.io.IOException; +import java.util.List; +import java.util.concurrent.Executor; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.MessageToMessageDecoder; +import io.netty.handler.codec.http.HttpHeaders; + +import static org.apache.dubbo.config.Constants.SERVER_THREAD_POOL_NAME; public class RestHttpRequestDecoder extends MessageToMessageDecoder { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); @@ -46,22 +44,23 @@ public class RestHttpRequestDecoder extends MessageToMessageDecoder out) throws Exception { + protected void decode( + ChannelHandlerContext ctx, io.netty.handler.codec.http.FullHttpRequest request, List out) + throws Exception { boolean keepAlive = HttpHeaders.isKeepAlive(request); - NettyHttpResponse nettyHttpResponse = new NettyHttpResponse(ctx, keepAlive,url); - NettyRequestFacade requestFacade = new NettyRequestFacade(request, ctx,serviceDeployer); + NettyHttpResponse nettyHttpResponse = new NettyHttpResponse(ctx, keepAlive, url); + NettyRequestFacade requestFacade = new NettyRequestFacade(request, ctx, serviceDeployer); executor.execute(() -> { @@ -70,20 +69,22 @@ public class RestHttpRequestDecoder extends MessageToMessageDecoder list) throws Exception { + protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List list) + throws Exception { // Will use the first five bytes to detect a protocol. if (byteBuf.readableBytes() < 5) { return; @@ -85,8 +99,10 @@ public class SslServerTlsHandler extends ByteToMessageDecoder { return; } - CertManager certManager = url.getOrDefaultFrameworkModel().getBeanFactory().getBean(CertManager.class); - ProviderCert providerConnectionConfig = certManager.getProviderConnectionConfig(url, channelHandlerContext.channel().remoteAddress()); + CertManager certManager = + url.getOrDefaultFrameworkModel().getBeanFactory().getBean(CertManager.class); + ProviderCert providerConnectionConfig = certManager.getProviderConnectionConfig( + url, channelHandlerContext.channel().remoteAddress()); if (providerConnectionConfig == null) { ChannelPipeline p = channelHandlerContext.pipeline(); @@ -119,5 +135,4 @@ public class SslServerTlsHandler extends ByteToMessageDecoder { p.addLast("unificationA", new SslServerTlsHandler(url, true)); p.remove(this); } - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pair/InvokerAndRestMethodMetadataPair.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pair/InvokerAndRestMethodMetadataPair.java index 70380c986b..2b11f75a16 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pair/InvokerAndRestMethodMetadataPair.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pair/InvokerAndRestMethodMetadataPair.java @@ -43,7 +43,6 @@ public class InvokerAndRestMethodMetadataPair { return restMethodMetadata; } - public static InvokerAndRestMethodMetadataPair pair(Invoker invoker, RestMethodMetadata restMethodMetadata) { return new InvokerAndRestMethodMetadataPair(invoker, restMethodMetadata); } @@ -63,21 +62,17 @@ public class InvokerAndRestMethodMetadataPair { return false; } - Method beforeServiceMethod = beforeMetadata.getRestMethodMetadata().getReflectMethod(); Method currentReflectMethod = this.restMethodMetadata.getReflectMethod(); if (beforeServiceMethod.getName().equals(currentReflectMethod.getName()) // method name - // method param types - && Arrays.toString(beforeServiceMethod.getParameterTypes()).equals(Arrays.toString(currentReflectMethod.getParameterTypes()))) { + // method param types + && Arrays.toString(beforeServiceMethod.getParameterTypes()) + .equals(Arrays.toString(currentReflectMethod.getParameterTypes()))) { return true; } return false; - - } - - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pair/MessageCodecResultPair.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pair/MessageCodecResultPair.java index 00b3154c0a..9f1deeaac6 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pair/MessageCodecResultPair.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pair/MessageCodecResultPair.java @@ -32,13 +32,11 @@ public class MessageCodecResultPair { */ MediaType mediaType; - public MessageCodecResultPair(boolean coded, MediaType mediaType) { this.coded = coded; this.mediaType = mediaType; } - public boolean isCoded() { return coded; } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pu/RestHttp1Detector.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pu/RestHttp1Detector.java index e1c52591d0..3e083e14cd 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pu/RestHttp1Detector.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pu/RestHttp1Detector.java @@ -23,7 +23,6 @@ import org.apache.dubbo.rpc.model.FrameworkModel; /** * rest http protocol detector */ - public class RestHttp1Detector extends AbstractHttpProtocolDetector { private static final char[][] HTTP_METHODS_PREFIX = getHttpMethodsPrefix(); diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pu/RestHttp1WireProtocol.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pu/RestHttp1WireProtocol.java index 7d88e97287..6d661cdba3 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pu/RestHttp1WireProtocol.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pu/RestHttp1WireProtocol.java @@ -28,14 +28,14 @@ import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; import org.apache.dubbo.rpc.protocol.rest.netty.RestHttpRequestDecoder; -import io.netty.handler.codec.http.HttpObjectAggregator; -import io.netty.handler.codec.http.HttpRequestDecoder; -import io.netty.handler.codec.http.HttpResponseEncoder; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import io.netty.handler.codec.http.HttpObjectAggregator; +import io.netty.handler.codec.http.HttpRequestDecoder; +import io.netty.handler.codec.http.HttpResponseEncoder; + import static org.apache.dubbo.common.constants.CommonConstants.REST_SERVICE_DEPLOYER_URL_ATTRIBUTE_KEY; @Activate(order = Integer.MAX_VALUE) @@ -47,11 +47,9 @@ public class RestHttp1WireProtocol extends AbstractWireProtocol implements Scope super(new RestHttp1Detector(frameworkModel)); } - @Override public void configServerProtocolHandler(URL url, ChannelOperator operator) { - // h1 upgrade to don`t response 101 ,cause there is no h1 stream handler // TODO add h1 stream handler @@ -63,17 +61,19 @@ public class RestHttp1WireProtocol extends AbstractWireProtocol implements Scope serviceDeployer = emptyServiceDeployer; } - List channelHandlers = Arrays.asList(new HttpRequestDecoder( - url.getParameter(RestConstant.MAX_INITIAL_LINE_LENGTH_PARAM, RestConstant.MAX_INITIAL_LINE_LENGTH), - url.getParameter(RestConstant.MAX_HEADER_SIZE_PARAM, RestConstant.MAX_HEADER_SIZE), - url.getParameter(RestConstant.MAX_CHUNK_SIZE_PARAM, RestConstant.MAX_CHUNK_SIZE)), - new HttpObjectAggregator(url.getParameter(RestConstant.MAX_REQUEST_SIZE_PARAM, RestConstant.MAX_REQUEST_SIZE)), - new HttpResponseEncoder(), new RestHttpRequestDecoder(url, serviceDeployer)); - + List channelHandlers = Arrays.asList( + new HttpRequestDecoder( + url.getParameter( + RestConstant.MAX_INITIAL_LINE_LENGTH_PARAM, RestConstant.MAX_INITIAL_LINE_LENGTH), + url.getParameter(RestConstant.MAX_HEADER_SIZE_PARAM, RestConstant.MAX_HEADER_SIZE), + url.getParameter(RestConstant.MAX_CHUNK_SIZE_PARAM, RestConstant.MAX_CHUNK_SIZE)), + new HttpObjectAggregator( + url.getParameter(RestConstant.MAX_REQUEST_SIZE_PARAM, RestConstant.MAX_REQUEST_SIZE)), + new HttpResponseEncoder(), + new RestHttpRequestDecoder(url, serviceDeployer)); List handlers = new ArrayList<>(); handlers.add(new ChannelHandlerPretender(channelHandlers)); operator.configChannelHandler(handlers); } - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/request/NettyRequestFacade.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/request/NettyRequestFacade.java index ef8b07f4aa..3fba2d33a4 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/request/NettyRequestFacade.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/request/NettyRequestFacade.java @@ -16,12 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest.request; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.ByteBufInputStream; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.socket.nio.NioSocketChannel; -import io.netty.handler.codec.http.FullHttpRequest; -import io.netty.handler.codec.http.HttpContent; import org.apache.dubbo.common.utils.IOUtils; import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; @@ -34,28 +28,30 @@ import java.util.List; import java.util.ListIterator; import java.util.Map; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufInputStream; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.handler.codec.http.HttpContent; + /** * netty request facade */ public class NettyRequestFacade extends RequestFacade { - private ChannelHandlerContext context; - public NettyRequestFacade(Object request, ChannelHandlerContext context) { super((FullHttpRequest) request); this.context = context; - } public NettyRequestFacade(Object request, ChannelHandlerContext context, ServiceDeployer serviceDeployer) { super((FullHttpRequest) request, serviceDeployer); this.context = context; - } - protected void initHeaders() { for (Map.Entry header : request.headers()) { @@ -77,7 +73,7 @@ public class NettyRequestFacade extends RequestFacade { List values = headers.get(name); - if (values == null && name != null){ + if (values == null && name != null) { values = headers.get(name.toLowerCase()); } @@ -86,7 +82,6 @@ public class NettyRequestFacade extends RequestFacade { } else { return values.get(0); } - } @Override @@ -98,7 +93,6 @@ public class NettyRequestFacade extends RequestFacade { list = new ArrayList<>(); } - ListIterator stringListIterator = list.listIterator(); return new Enumeration() { @@ -114,7 +108,6 @@ public class NettyRequestFacade extends RequestFacade { }; } - @Override public Enumeration getHeaderNames() { @@ -149,13 +142,11 @@ public class NettyRequestFacade extends RequestFacade { return null; } - @Override public String getRequestURI() { return request.uri(); } - @Override public String getParameter(String name) { ArrayList strings = parameters.get(name); @@ -163,7 +154,6 @@ public class NettyRequestFacade extends RequestFacade { String value = null; if (strings != null && !strings.isEmpty()) { value = strings.get(0); - } return value; } @@ -184,7 +174,6 @@ public class NettyRequestFacade extends RequestFacade { return iterator.next(); } }; - } @Override @@ -204,10 +193,8 @@ public class NettyRequestFacade extends RequestFacade { map.put(entry.getKey(), entry.getValue().toArray(new String[0])); }); return map; - } - @Override public String getRemoteAddr() { return getChannel().remoteAddress().getHostString(); @@ -259,7 +246,6 @@ public class NettyRequestFacade extends RequestFacade { } } - } public ChannelHandlerContext getNettyChannelContext() { diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/request/RequestFacade.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/request/RequestFacade.java index ab0dcbf484..e908a55239 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/request/RequestFacade.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/request/RequestFacade.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest.request; - import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.protocol.rest.deploy.ServiceDeployer; @@ -52,10 +51,7 @@ public abstract class RequestFacade { this.serviceDeployer = serviceDeployer; } - protected void initHeaders() { - - } - + protected void initHeaders() {} protected void initParameters() { String requestURI = getRequestURI(); @@ -84,7 +80,6 @@ public abstract class RequestFacade { parameters.put(name, values); } values.add(value); - } } } else { @@ -92,22 +87,18 @@ public abstract class RequestFacade { } } - public T getRequest() { return request; } public abstract String getHeader(String name); - public abstract Enumeration getHeaders(String name); - public abstract Enumeration getHeaderNames(); public abstract String getMethod(); - public abstract String getPath(); public abstract String getContextPath(); diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/support/ContentType.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/support/ContentType.java index 14579668ba..8e586b5e15 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/support/ContentType.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/support/ContentType.java @@ -20,7 +20,8 @@ import javax.ws.rs.core.MediaType; public class ContentType { - public static final String APPLICATION_JSON_UTF_8 = MediaType.APPLICATION_JSON + "; " + MediaType.CHARSET_PARAMETER + "=UTF-8"; + public static final String APPLICATION_JSON_UTF_8 = + MediaType.APPLICATION_JSON + "; " + MediaType.CHARSET_PARAMETER + "=UTF-8"; public static final String TEXT_XML_UTF_8 = MediaType.TEXT_XML + "; " + MediaType.CHARSET_PARAMETER + "=UTF-8"; public static final String TEXT_PLAIN_UTF_8 = MediaType.TEXT_PLAIN + "; " + MediaType.CHARSET_PARAMETER + "=UTF-8"; } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/ConstraintViolationExceptionConvert.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/ConstraintViolationExceptionConvert.java index df0e34f057..0663703e69 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/ConstraintViolationExceptionConvert.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/ConstraintViolationExceptionConvert.java @@ -25,16 +25,14 @@ import javax.validation.ConstraintViolationException; public class ConstraintViolationExceptionConvert { - - public static Object handleConstraintViolationException(RpcException rpcException) { ConstraintViolationException cve = (ConstraintViolationException) rpcException.getCause(); ViolationReport report = new ViolationReport(); for (ConstraintViolation cv : cve.getConstraintViolations()) { report.addConstraintViolation(new RestConstraintViolation( - cv.getPropertyPath().toString(), - cv.getMessage(), - cv.getInvalidValue() == null ? "null" : cv.getInvalidValue().toString())); + cv.getPropertyPath().toString(), + cv.getMessage(), + cv.getInvalidValue() == null ? "null" : cv.getInvalidValue().toString())); } return report; } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/DataParseUtils.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/DataParseUtils.java index 9737c152c4..ceeae1c745 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/DataParseUtils.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/DataParseUtils.java @@ -58,7 +58,6 @@ public class DataParseUtils { } return value; - } public static boolean isTextType(Class targetType) { @@ -66,12 +65,13 @@ public class DataParseUtils { return false; } - return targetType == Boolean.class || targetType == boolean.class || - targetType == String.class || - Number.class.isAssignableFrom(targetType) || targetType.isPrimitive(); + return targetType == Boolean.class + || targetType == boolean.class + || targetType == String.class + || Number.class.isAssignableFrom(targetType) + || targetType.isPrimitive(); } - /** * content-type text * @@ -149,14 +149,12 @@ public class DataParseUtils { } return object.toString().getBytes(); - } public static Object jsonConvert(Type targetType, byte[] body) throws Exception { return JsonUtils.toJavaObject(new String(body, StandardCharsets.UTF_8), targetType); } - public static Object multipartFormConvert(byte[] body, Charset charset, Class targetType) throws Exception { String[] pairs = tokenizeToStringArray(new String(body, StandardCharsets.UTF_8), "&"); Object result = MultiValueCreator.providerCreateMultiValueMap(targetType); @@ -178,13 +176,12 @@ public class DataParseUtils { return multipartFormConvert(body, Charset.defaultCharset(), targetType); } - public static String[] tokenizeToStringArray(String str, String delimiters) { return tokenizeToStringArray(str, delimiters, true, true); } - public static String[] tokenizeToStringArray(String str, String delimiters, boolean trimTokens, - boolean ignoreEmptyTokens) { + public static String[] tokenizeToStringArray( + String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) { if (str == null) { return null; } else { diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/HttpHeaderUtil.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/HttpHeaderUtil.java index 194d7de464..5388e7b27e 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/HttpHeaderUtil.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/HttpHeaderUtil.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.rest.util; import org.apache.dubbo.common.utils.StringUtils; @@ -37,7 +36,6 @@ import java.util.Map; public class HttpHeaderUtil { - /** * convert attachment to Map> * @@ -66,7 +64,6 @@ public class HttpHeaderUtil { return attachments; } - /** * add consumer attachment to request * @@ -79,24 +76,24 @@ public class HttpHeaderUtil { attachments.entrySet().forEach(attachment -> { requestTemplate.addHeaders(appendPrefixToAttachRealHeader(attachment.getKey()), attachment.getValue()); }); - } - /** * add provider attachment to response * * @param nettyHttpResponse */ public static void addResponseAttachments(NettyHttpResponse nettyHttpResponse) { - Map> attachments = createAttachments(RpcContext.getServerContext().getObjectAttachments()); + Map> attachments = + createAttachments(RpcContext.getServerContext().getObjectAttachments()); attachments.entrySet().stream().forEach(attachment -> { - nettyHttpResponse.getOutputHeaders().put(appendPrefixToAttachRealHeader(attachment.getKey()), attachment.getValue()); + nettyHttpResponse + .getOutputHeaders() + .put(appendPrefixToAttachRealHeader(attachment.getKey()), attachment.getValue()); }); } - /** * parse rest request header attachment & header * @@ -118,11 +115,9 @@ public class HttpHeaderUtil { // attachment rpcInvocation.setAttachment(subRestAttachRealHeaderPrefix(header.trim()), requestFacade.getHeader(header)); - } } - /** * for judge rest header or rest attachment * @@ -160,7 +155,6 @@ public class HttpHeaderUtil { return RestHeaderEnum.REST_HEADER_PREFIX.getHeader() + header; } - /** * parse request attribute * @param rpcInvocation @@ -178,7 +172,6 @@ public class HttpHeaderUtil { rpcInvocation.put(RestConstant.LOCAL_PORT, localPort); } - /** * parse request * @param rpcInvocation @@ -211,7 +204,5 @@ public class HttpHeaderUtil { appResponse.setAttribute(header, entry.getValue()); } }); - - } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/MediaTypeUtil.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/MediaTypeUtil.java index 55a9783b12..57093dc2e5 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/MediaTypeUtil.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/MediaTypeUtil.java @@ -27,7 +27,6 @@ public class MediaTypeUtil { private static final List mediaTypes = MediaType.getSupportMediaTypes(); - /** * return first match , if any multiple content-type ,acquire mediaType by targetClass type .if contentTypes is empty * @@ -54,6 +53,5 @@ public class MediaTypeUtil { } throw new UnSupportContentTypeException(Arrays.toString(contentTypes)); - } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/MultiValueCreator.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/MultiValueCreator.java index 8a391b9955..31e9112ff2 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/MultiValueCreator.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/MultiValueCreator.java @@ -16,21 +16,19 @@ */ package org.apache.dubbo.rpc.protocol.rest.util; - import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.lang.reflect.Method; import java.util.Map; - public class MultiValueCreator { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MultiValueCreator.class); - private final static String SPRING_MultiValueMapImpl = "org.springframework.util.LinkedMultiValueMap"; - private final static String SPRING_MultiValueMap = "org.springframework.util.MultiValueMap"; - private final static String JAVAX_MultiValueMapImpl = "org.jboss.resteasy.specimpl.MultivaluedMapImpl"; - private final static String JAVAX_MultiValueMap = "javax.ws.rs.core.MultivaluedMap"; + private static final String SPRING_MultiValueMapImpl = "org.springframework.util.LinkedMultiValueMap"; + private static final String SPRING_MultiValueMap = "org.springframework.util.MultiValueMap"; + private static final String JAVAX_MultiValueMapImpl = "org.jboss.resteasy.specimpl.MultivaluedMapImpl"; + private static final String JAVAX_MultiValueMap = "javax.ws.rs.core.MultivaluedMap"; private static Class springMultiValueMapImplClass = null; private static Class springMultiValueMapClass = null; @@ -49,10 +47,8 @@ public class MultiValueCreator { jaxrsMultiValueMapClass = ReflectUtils.findClassTryException(JAVAX_MultiValueMap); jaxrsMultiValueMapImplClass = ReflectUtils.findClassTryException(JAVAX_MultiValueMapImpl); jaxrsMultiValueMapAdd = ReflectUtils.getMethodByName(jaxrsMultiValueMapImplClass, "add"); - } - public static Object providerCreateMultiValueMap(Class targetType) { try { if (typeJudge(springMultiValueMapClass, targetType)) { @@ -61,14 +57,18 @@ public class MultiValueCreator { return jaxrsMultiValueMapImplClass.getDeclaredConstructor().newInstance(); } } catch (Exception e) { - logger.error("", e.getMessage(), "current param type is: " + targetType + "and support type is : " + springMultiValueMapClass + "or" + jaxrsMultiValueMapClass, - "dubbo rest form content-type param construct error,un support param type: ", e); + logger.error( + "", + e.getMessage(), + "current param type is: " + targetType + "and support type is : " + springMultiValueMapClass + "or" + + jaxrsMultiValueMapClass, + "dubbo rest form content-type param construct error,un support param type: ", + e); } return null; } - private static boolean typeJudge(Class parent, Class targetType) { if (parent == null) { return false; @@ -94,11 +94,9 @@ public class MultiValueCreator { multiValueMapAdd = jaxrsMultiValueMapAdd; } - ReflectUtils.invokeAndTryCatch(multiValueMap, multiValueMapAdd, new Object[]{key, value}); + ReflectUtils.invokeAndTryCatch(multiValueMap, multiValueMapAdd, new Object[] {key, value}); } catch (Exception e) { logger.error("", e.getMessage(), "", "dubbo rest form content-type param add data error: ", e); } } - - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/NoAnnotationBodyParseUtil.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/NoAnnotationBodyParseUtil.java index 11ecc4fc95..02461cc0d7 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/NoAnnotationBodyParseUtil.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/NoAnnotationBodyParseUtil.java @@ -24,13 +24,14 @@ import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; public class NoAnnotationBodyParseUtil { - public static Object[] doParse(ProviderParseContext parseContext) { RequestFacade request = parseContext.getRequestFacade(); try { Class objectArraysType = Object[].class; - MediaType mediaType = MediaTypeUtil.convertMediaType(objectArraysType, MediaType.APPLICATION_JSON_VALUE.value); - Object[] params = (Object[]) HttpMessageCodecManager.httpMessageDecode(request.getInputStream(), objectArraysType, objectArraysType, mediaType); + MediaType mediaType = + MediaTypeUtil.convertMediaType(objectArraysType, MediaType.APPLICATION_JSON_VALUE.value); + Object[] params = (Object[]) HttpMessageCodecManager.httpMessageDecode( + request.getInputStream(), objectArraysType, objectArraysType, mediaType); return params; } catch (Throwable e) { throw new ParamParseException("dubbo rest protocol provider body param parser error: " + e.getMessage()); diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/NumberUtils.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/NumberUtils.java index 77a87b7308..d59680fdd0 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/NumberUtils.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/NumberUtils.java @@ -47,17 +47,15 @@ public class NumberUtils { return (T) new BigDecimal(trimmed); } else { throw new IllegalArgumentException( - "Cannot convert String [" + text + "] to target class [" + targetClass.getName() + "]"); + "Cannot convert String [" + text + "] to target class [" + targetClass.getName() + "]"); } } - private static boolean isHexNumber(String value) { int index = (value.startsWith("-") ? 1 : 0); return (value.startsWith("0x", index) || value.startsWith("0X", index) || value.startsWith("#", index)); } - private static BigInteger decodeBigInteger(String value) { int radix = 10; int index = 0; @@ -101,7 +99,6 @@ public class NumberUtils { return sb.toString(); } - public static Object numberToBytes(Number number) { if (number instanceof Byte) { @@ -122,8 +119,5 @@ public class NumberUtils { } return number; - - } - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/ReflectUtils.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/ReflectUtils.java index b2734d081b..627ad1c195 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/ReflectUtils.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/util/ReflectUtils.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest.util; - import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -30,13 +29,11 @@ public class ReflectUtils { public static Class findClass(String name, ClassLoader classLoader) throws ClassNotFoundException { return classLoader.loadClass(name); - } public static Class findClass(String name) throws ClassNotFoundException { return findClass(Thread.currentThread().getContextClassLoader(), name); - } public static Class findClassAndTryCatch(String name, ClassLoader classLoader) { @@ -47,7 +44,6 @@ public class ReflectUtils { } return null; - } public static Class findClass(ClassLoader classLoader, String... name) throws ClassNotFoundException { @@ -66,7 +62,6 @@ public class ReflectUtils { throw new ClassNotFoundException(); } - public static Class findClassTryException(ClassLoader classLoader, String... name) { try { @@ -75,7 +70,6 @@ public class ReflectUtils { } return null; - } public static List getMethodByNameList(Class clazz, String name) { @@ -98,7 +92,6 @@ public class ReflectUtils { return new ArrayList<>(methods); } - try { filterMethod(name, methods, clazz.getMethods()); } catch (Exception e) { @@ -123,15 +116,12 @@ public class ReflectUtils { } return new ArrayList>(methods); - - } private static void filterConstructMethod(Set> methods, Constructor[] declaredMethods) { for (Constructor constructor : declaredMethods) { methods.add(constructor); } - } private static void filterMethod(String name, Set methodList, Method[] methods) { @@ -158,7 +148,8 @@ public class ReflectUtils { return findClassTryException(Thread.currentThread().getContextClassLoader(), name); } - public static Object invoke(Object object, Method method, Object[] params) throws InvocationTargetException, IllegalAccessException { + public static Object invoke(Object object, Method method, Object[] params) + throws InvocationTargetException, IllegalAccessException { return method.invoke(object, params); } @@ -171,6 +162,4 @@ public class ReflectUtils { return null; } - - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DataParseUtilsTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DataParseUtilsTest.java index 93b8ed9585..845c34aaea 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DataParseUtilsTest.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DataParseUtilsTest.java @@ -17,11 +17,12 @@ package org.apache.dubbo.rpc.protocol.rest; import org.apache.dubbo.rpc.protocol.rest.util.DataParseUtils; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + public class DataParseUtilsTest { @Test void testJsonConvert() throws Exception { @@ -29,10 +30,9 @@ public class DataParseUtilsTest { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); DataParseUtils.writeJsonContent(User.getInstance(), byteArrayOutputStream); - Assertions.assertEquals("{\"age\":18,\"id\":404,\"name\":\"dubbo\"}".getBytes().length, - byteArrayOutputStream.toByteArray().length); - - + Assertions.assertEquals( + "{\"age\":18,\"id\":404,\"name\":\"dubbo\"}".getBytes().length, + byteArrayOutputStream.toByteArray().length); } @Test @@ -56,7 +56,5 @@ public class DataParseUtilsTest { convert = DataParseUtils.stringTypeConvert(Integer.class, "1"); Assertions.assertEquals(1, convert); - - } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DemoService.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DemoService.java index 803c133020..53cbc758e9 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DemoService.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DemoService.java @@ -16,10 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest; - -import io.netty.handler.codec.http.DefaultFullHttpRequest; -import org.jboss.resteasy.annotations.Form; - import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.GET; @@ -30,10 +26,14 @@ import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; + import java.util.List; import java.util.Map; import java.util.Set; +import io.netty.handler.codec.http.DefaultFullHttpRequest; +import org.jboss.resteasy.annotations.Form; + @Path("/demoService") public interface DemoService { @GET @@ -153,5 +153,4 @@ public interface DemoService { @POST @Path("/formBody") User formBody(@Form User user); - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DemoServiceImpl.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DemoServiceImpl.java index 0bdd95cc4c..69c5cbc710 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DemoServiceImpl.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/DemoServiceImpl.java @@ -16,22 +16,23 @@ */ package org.apache.dubbo.rpc.protocol.rest; - -import io.netty.handler.codec.http.DefaultFullHttpRequest; import org.apache.dubbo.rpc.RpcContext; import javax.ws.rs.Consumes; import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; -import javax.ws.rs.HeaderParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; + import java.util.List; import java.util.Map; import java.util.Set; +import io.netty.handler.codec.http.DefaultFullHttpRequest; + @Path("/demoService") public class DemoServiceImpl implements DemoService { private static Map context; @@ -51,7 +52,6 @@ public class DemoServiceImpl implements DemoService { return number; } - public boolean isCalled() { return called; } @@ -77,9 +77,7 @@ public class DemoServiceImpl implements DemoService { } @Override - public void request(DefaultFullHttpRequest defaultFullHttpRequest) { - - } + public void request(DefaultFullHttpRequest defaultFullHttpRequest) {} @Override public String testMapParam(Map params) { @@ -111,7 +109,6 @@ public class DemoServiceImpl implements DemoService { return param; } - @Override public String noStringHeader(String header) { return header; @@ -146,7 +143,6 @@ public class DemoServiceImpl implements DemoService { return a + b; } - @GET @Path("/error") @Override @@ -158,7 +154,6 @@ public class DemoServiceImpl implements DemoService { return context; } - @Override public List list(List users) { return users; @@ -189,5 +184,4 @@ public class DemoServiceImpl implements DemoService { user.setName("formBody"); return user; } - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ExceptionMapperTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ExceptionMapperTest.java index a432ef552b..330439ab60 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ExceptionMapperTest.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ExceptionMapperTest.java @@ -19,44 +19,33 @@ package org.apache.dubbo.rpc.protocol.rest; import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionHandler; import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionHandlerResult; import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionMapper; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; - public class ExceptionMapperTest { private final ExceptionMapper exceptionMapper = new ExceptionMapper(); @Test void testRegister() { - exceptionMapper.registerMapper(TestExceptionHandler.class); - ExceptionHandlerResult result = exceptionMapper.exceptionToResult(new RuntimeException("test")); - Assertions.assertEquals("test", result.getEntity()); - - } @Test void testExceptionNoArgConstruct() { - Assertions.assertThrows(RuntimeException.class, () -> { exceptionMapper.registerMapper(TestExceptionHandlerException.class); - }); - - } - public class TestExceptionHandler implements ExceptionHandler { - @Override public Object result(RuntimeException exception) { return exception.getMessage(); @@ -65,12 +54,9 @@ public class ExceptionMapperTest { class TestExceptionHandlerException implements ExceptionHandler { - @Override public Object result(RuntimeException exception) { return exception.getMessage(); } } - - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/FeignClientRestProtocolTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/FeignClientRestProtocolTest.java index 2b44a3e96f..89cc9bc27c 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/FeignClientRestProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/FeignClientRestProtocolTest.java @@ -29,16 +29,18 @@ import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.protocol.rest.mvc.feign.FeignClientController; import org.apache.dubbo.rpc.protocol.rest.mvc.feign.FeignClientControllerImpl; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; - public class FeignClientRestProtocolTest { - private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); - private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - private final ModuleServiceRepository repository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); - + private Protocol protocol = + ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); + private ProxyFactory proxy = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + private final ModuleServiceRepository repository = + ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); @AfterEach public void tearDown() { @@ -46,32 +48,28 @@ public class FeignClientRestProtocolTest { FrameworkModel.destroyAll(); } - @Test void testRestProtocol() { - URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.mvc.feign.FeignClientController"); + URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() + + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.mvc.feign.FeignClientController"); FeignClientController server = new FeignClientControllerImpl(); url = this.registerProvider(url, server, DemoService.class); - Exporter exporter = protocol.export(proxy.getInvoker(server, FeignClientController.class, url)); + Exporter exporter = + protocol.export(proxy.getInvoker(server, FeignClientController.class, url)); - FeignClientController feignClientController = this.proxy.getProxy(protocol.refer(FeignClientController.class, url)); + FeignClientController feignClientController = + this.proxy.getProxy(protocol.refer(FeignClientController.class, url)); - Assertions.assertEquals("hello, feign",feignClientController.hello()); + Assertions.assertEquals("hello, feign", feignClientController.hello()); exporter.unexport(); } - private URL registerProvider(URL url, Object impl, Class interfaceClass) { ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass); - ProviderModel providerModel = new ProviderModel( - url.getServiceKey(), - impl, - serviceDescriptor, - null, - null); + ProviderModel providerModel = new ProviderModel(url.getServiceKey(), impl, serviceDescriptor, null, null); repository.registerProvider(providerModel); return url.setServiceModel(providerModel); } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/HttpMessageCodecManagerTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/HttpMessageCodecManagerTest.java index b0f368e74b..06c0ff5e18 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/HttpMessageCodecManagerTest.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/HttpMessageCodecManagerTest.java @@ -21,11 +21,12 @@ import org.apache.dubbo.rpc.protocol.rest.message.HttpMessageCodecManager; import org.apache.dubbo.rpc.protocol.rest.message.codec.XMLCodec; import org.apache.dubbo.rpc.protocol.rest.pair.MessageCodecResultPair; import org.apache.dubbo.rpc.protocol.rest.rest.RegistrationResult; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + public class HttpMessageCodecManagerTest { @Test @@ -34,15 +35,20 @@ public class HttpMessageCodecManagerTest { RegistrationResult registrationResult = new RegistrationResult(); registrationResult.setId(1l); - HttpMessageCodecManager.httpMessageEncode(byteArrayOutputStream, - registrationResult, null, MediaType.TEXT_XML, null); + HttpMessageCodecManager.httpMessageEncode( + byteArrayOutputStream, registrationResult, null, MediaType.TEXT_XML, null); - Object o = HttpMessageCodecManager.httpMessageDecode(byteArrayOutputStream.toByteArray(), RegistrationResult.class, RegistrationResult.class, MediaType.TEXT_XML); + Object o = HttpMessageCodecManager.httpMessageDecode( + byteArrayOutputStream.toByteArray(), + RegistrationResult.class, + RegistrationResult.class, + MediaType.TEXT_XML); Assertions.assertEquals(registrationResult, o); byteArrayOutputStream = new ByteArrayOutputStream(); - MessageCodecResultPair messageCodecResultPair = HttpMessageCodecManager.httpMessageEncode(byteArrayOutputStream, null, null, null, RegistrationResult.class); + MessageCodecResultPair messageCodecResultPair = HttpMessageCodecManager.httpMessageEncode( + byteArrayOutputStream, null, null, null, RegistrationResult.class); MediaType mediaType = messageCodecResultPair.getMediaType(); @@ -51,7 +57,5 @@ public class HttpMessageCodecManagerTest { XMLCodec xmlCodec = new XMLCodec(); Assertions.assertEquals(false, xmlCodec.typeSupport(null)); - - } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/JaxrsRestProtocolTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/JaxrsRestProtocolTest.java index 265f45d277..e68969817d 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/JaxrsRestProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/JaxrsRestProtocolTest.java @@ -35,14 +35,12 @@ import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleServiceRepository; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; - import org.apache.dubbo.rpc.protocol.rest.annotation.metadata.MetadataResolver; import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; import org.apache.dubbo.rpc.protocol.rest.exception.DoublePathCheckException; import org.apache.dubbo.rpc.protocol.rest.exception.ResteasyExceptionMapper; import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionHandler; import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionMapper; - import org.apache.dubbo.rpc.protocol.rest.filter.TraceRequestAndResponseFilter; import org.apache.dubbo.rpc.protocol.rest.rest.AnotherUserRestService; import org.apache.dubbo.rpc.protocol.rest.rest.AnotherUserRestServiceImpl; @@ -53,12 +51,6 @@ import org.apache.dubbo.rpc.protocol.rest.rest.RestDemoService; import org.apache.dubbo.rpc.protocol.rest.rest.RestDemoServiceImpl; import org.apache.dubbo.rpc.protocol.rest.rest.TestGetInvokerService; import org.apache.dubbo.rpc.protocol.rest.rest.TestGetInvokerServiceImpl; -import org.hamcrest.CoreMatchers; -import org.jboss.resteasy.specimpl.MultivaluedMapImpl; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; @@ -67,6 +59,13 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import org.hamcrest.CoreMatchers; +import org.jboss.resteasy.specimpl.MultivaluedMapImpl; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + import static org.apache.dubbo.remoting.Constants.SERVER_KEY; import static org.apache.dubbo.rpc.protocol.rest.Constants.EXTENSION_KEY; import static org.hamcrest.CoreMatchers.equalTo; @@ -75,11 +74,15 @@ import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; class JaxrsRestProtocolTest { - private final Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); - private final ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + private final Protocol protocol = + ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); + private final ProxyFactory proxy = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); private final int availablePort = NetUtils.getAvailablePort(); - private final URL exportUrl = URL.valueOf("rest://127.0.0.1:" + availablePort + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.DemoService"); - private final ModuleServiceRepository repository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); + private final URL exportUrl = URL.valueOf( + "rest://127.0.0.1:" + availablePort + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.DemoService"); + private final ModuleServiceRepository repository = + ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); private final ExceptionMapper exceptionMapper = new ExceptionMapper(); private static final String SERVER = "netty4"; @@ -91,7 +94,8 @@ class JaxrsRestProtocolTest { @Test void testRestProtocol() { - URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.DemoService"); + URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() + + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.DemoService"); DemoServiceImpl server = new DemoServiceImpl(); @@ -114,7 +118,6 @@ class JaxrsRestProtocolTest { exporter.unexport(); } - @Test void testAnotherUserRestProtocolByDifferentRestClient() { testAnotherUserRestProtocol(org.apache.dubbo.remoting.Constants.OK_HTTP); @@ -122,20 +125,19 @@ class JaxrsRestProtocolTest { testAnotherUserRestProtocol(org.apache.dubbo.remoting.Constants.URL_CONNECTION); } - void testAnotherUserRestProtocol(String restClient) { URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() - + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.rest.AnotherUserRestService&" - + org.apache.dubbo.remoting.Constants.CLIENT_KEY + "=" + restClient); + + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.rest.AnotherUserRestService&" + + org.apache.dubbo.remoting.Constants.CLIENT_KEY + "=" + restClient); AnotherUserRestServiceImpl server = new AnotherUserRestServiceImpl(); url = this.registerProvider(url, server, DemoService.class); - Exporter exporter = protocol.export(proxy.getInvoker(server, AnotherUserRestService.class, url)); + Exporter exporter = + protocol.export(proxy.getInvoker(server, AnotherUserRestService.class, url)); Invoker invoker = protocol.refer(AnotherUserRestService.class, url); - AnotherUserRestService client = proxy.getProxy(invoker); User result = client.getUser(123l); @@ -156,7 +158,6 @@ class JaxrsRestProtocolTest { Assertions.assertEquals("h1", client.headerMap(map)); Assertions.assertEquals(null, client.headerMap(null)); - invoker.destroy(); exporter.unexport(); } @@ -166,13 +167,15 @@ class JaxrsRestProtocolTest { DemoServiceImpl server = new DemoServiceImpl(); Assertions.assertFalse(server.isCalled()); int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("rest://127.0.0.1:" + port + "/a/b/c?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.DemoService"); + URL url = URL.valueOf("rest://127.0.0.1:" + port + + "/a/b/c?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.DemoService"); url = this.registerProvider(url, server, DemoService.class); Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, url)); - url = URL.valueOf("rest://127.0.0.1:" + port + "/a/b/c/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.DemoService"); + url = URL.valueOf("rest://127.0.0.1:" + port + + "/a/b/c/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.DemoService"); Invoker invoker = protocol.refer(DemoService.class, url); DemoService client = proxy.getProxy(invoker); String result = client.sayHello("haha"); @@ -206,7 +209,8 @@ class JaxrsRestProtocolTest { URL url = this.registerProvider(exportUrl, server, DemoService.class); URL nettyUrl = url.addParameter(SERVER_KEY, SERVER); - Exporter exporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, nettyUrl)); + Exporter exporter = + protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); @@ -255,7 +259,10 @@ class JaxrsRestProtocolTest { Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, url)); - RpcInvocation rpcInvocation = new RpcInvocation("hello", DemoService.class.getName(), "", new Class[]{Integer.class, Integer.class}, new Integer[]{2, 3}); + RpcInvocation rpcInvocation = new RpcInvocation( + "hello", DemoService.class.getName(), "", new Class[] {Integer.class, Integer.class}, new Integer[] { + 2, 3 + }); Result result = exporter.getInvoker().invoke(rpcInvocation); assertThat(result.getValue(), CoreMatchers.is(5)); @@ -268,7 +275,7 @@ class JaxrsRestProtocolTest { URL url = this.registerProvider(exportUrl, server, DemoService.class); URL nettyUrl = url.addParameter(SERVER_KEY, SERVER) - .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.support.LoggingFilter"); + .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.support.LoggingFilter"); Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); @@ -289,7 +296,7 @@ class JaxrsRestProtocolTest { // use RpcContextFilter URL nettyUrl = url.addParameter(SERVER_KEY, SERVER) - .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.RpcContextFilter"); + .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.RpcContextFilter"); Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); @@ -369,12 +376,10 @@ class JaxrsRestProtocolTest { DemoService server = new DemoServiceImpl(); URL nettyUrl = this.registerProvider(exportUrl, server, DemoService.class); - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - Long number = demoService.testFormBody(18l); Assertions.assertEquals(18l, number); @@ -387,18 +392,18 @@ class JaxrsRestProtocolTest { DemoService server = new DemoServiceImpl(); URL nettyUrl = this.registerProvider(exportUrl, server, DemoService.class); - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - URL referUrl = URL.valueOf("rest://127.0.0.1:" + availablePort + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.rest.RestDemoForTestException"); + URL referUrl = URL.valueOf("rest://127.0.0.1:" + availablePort + + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.rest.RestDemoForTestException"); - RestDemoForTestException restDemoForTestException = this.proxy.getProxy(protocol.refer(RestDemoForTestException.class, referUrl)); + RestDemoForTestException restDemoForTestException = + this.proxy.getProxy(protocol.refer(RestDemoForTestException.class, referUrl)); restDemoForTestException.test404(); exporter.unexport(); }); - } @Test @@ -407,18 +412,18 @@ class JaxrsRestProtocolTest { DemoService server = new DemoServiceImpl(); URL nettyUrl = this.registerProvider(exportUrl, server, DemoService.class); - Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - URL referUrl = URL.valueOf("rest://127.0.0.1:" + availablePort + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.rest.RestDemoForTestException"); + URL referUrl = URL.valueOf("rest://127.0.0.1:" + availablePort + + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.rest.RestDemoForTestException"); - RestDemoForTestException restDemoForTestException = this.proxy.getProxy(protocol.refer(RestDemoForTestException.class, referUrl)); + RestDemoForTestException restDemoForTestException = + this.proxy.getProxy(protocol.refer(RestDemoForTestException.class, referUrl)); restDemoForTestException.test400("abc", "edf"); exporter.unexport(); }); - } @Test @@ -428,7 +433,7 @@ class JaxrsRestProtocolTest { URL url = this.registerProvider(exportUrl, server, DemoService.class); URL nettyUrl = url.addParameter(SERVER_KEY, SERVER) - .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.support.LoggingFilter"); + .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.support.LoggingFilter"); Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); @@ -446,36 +451,31 @@ class JaxrsRestProtocolTest { exporter.unexport(); } - @Test void testDoubleCheckException() { - Assertions.assertThrows(DoublePathCheckException.class, () -> { - DemoService server = new DemoServiceImpl(); - Invoker invoker = proxy.getInvoker(server, DemoService.class, exportUrl); PathAndInvokerMapper pathAndInvokerMapper = new PathAndInvokerMapper(); - ServiceRestMetadata serviceRestMetadata = MetadataResolver.resolveConsumerServiceMetadata(DemoService.class, exportUrl, ""); + ServiceRestMetadata serviceRestMetadata = + MetadataResolver.resolveConsumerServiceMetadata(DemoService.class, exportUrl, ""); - Map pathContainPathVariableToServiceMap = serviceRestMetadata.getPathUnContainPathVariableToServiceMap(); + Map pathContainPathVariableToServiceMap = + serviceRestMetadata.getPathUnContainPathVariableToServiceMap(); - Invoker invokerNew = proxy.getInvoker(new TestInterface() { - }, TestInterface.class, exportUrl); + Invoker invokerNew = + proxy.getInvoker(new TestInterface() {}, TestInterface.class, exportUrl); pathAndInvokerMapper.addPathAndInvoker(pathContainPathVariableToServiceMap, invoker); pathAndInvokerMapper.addPathAndInvoker(pathContainPathVariableToServiceMap, invokerNew); }); - - } - public static interface TestInterface{} - + public static interface TestInterface {} @Test void testMapParam() { @@ -484,7 +484,7 @@ class JaxrsRestProtocolTest { URL url = this.registerProvider(exportUrl, server, DemoService.class); URL nettyUrl = url.addParameter(SERVER_KEY, SERVER) - .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.support.LoggingFilter"); + .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.support.LoggingFilter"); Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); @@ -493,11 +493,9 @@ class JaxrsRestProtocolTest { params.put("param", "P1"); ; - Map headers = new HashMap<>(); headers.put("header", "H1"); - Assertions.assertEquals("P1", demoService.testMapParam(params)); Assertions.assertEquals("H1", demoService.testMapHeader(headers)); @@ -508,7 +506,6 @@ class JaxrsRestProtocolTest { exporter.unexport(); } - @Test void testNoArgParam() { DemoService server = new DemoServiceImpl(); @@ -516,12 +513,11 @@ class JaxrsRestProtocolTest { URL url = this.registerProvider(exportUrl, server, DemoService.class); URL nettyUrl = url.addParameter(SERVER_KEY, SERVER) - .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.support.LoggingFilter"); + .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.support.LoggingFilter"); Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - Assertions.assertEquals(null, demoService.noStringHeader(null)); Assertions.assertEquals(null, demoService.noStringParam(null)); Assertions.assertThrows(RpcException.class, () -> { @@ -547,12 +543,10 @@ class JaxrsRestProtocolTest { DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - Assertions.assertEquals("Hello, hello", demoService.sayHello("hello")); exporter.unexport(); } - @Test void testHttpMethods() { testHttpMethod(org.apache.dubbo.remoting.Constants.OK_HTTP); @@ -564,20 +558,19 @@ class JaxrsRestProtocolTest { HttpMethodService server = new HttpMethodServiceImpl(); URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() - + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.rest.HttpMethodService&" - + org.apache.dubbo.remoting.Constants.CLIENT_KEY + "=" + restClient); + + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.rest.HttpMethodService&" + + org.apache.dubbo.remoting.Constants.CLIENT_KEY + "=" + restClient); url = this.registerProvider(url, server, HttpMethodService.class); Exporter exporter = protocol.export(proxy.getInvoker(server, HttpMethodService.class, url)); HttpMethodService demoService = this.proxy.getProxy(protocol.refer(HttpMethodService.class, url)); - String expect = "hello"; Assertions.assertEquals(null, demoService.sayHelloHead()); Assertions.assertEquals(expect, demoService.sayHelloDelete("hello")); Assertions.assertEquals(expect, demoService.sayHelloGet("hello")); Assertions.assertEquals(expect, demoService.sayHelloOptions("hello")); -// Assertions.assertEquals(expect, demoService.sayHelloPatch("hello")); + // Assertions.assertEquals(expect, demoService.sayHelloPatch("hello")); Assertions.assertEquals(expect, demoService.sayHelloPost("hello")); Assertions.assertEquals(expect, demoService.sayHelloPut("hello")); exporter.unexport(); @@ -595,8 +588,7 @@ class JaxrsRestProtocolTest { void test405() { int availablePort = NetUtils.getAvailablePort(); URL url = URL.valueOf("rest://127.0.0.1:" + availablePort - + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.rest.RestDemoService&" - ); + + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.rest.RestDemoService&"); RestDemoServiceImpl server = new RestDemoServiceImpl(); @@ -605,22 +597,18 @@ class JaxrsRestProtocolTest { Exporter exporter = protocol.export(proxy.getInvoker(server, RestDemoService.class, url)); URL consumer = URL.valueOf("rest://127.0.0.1:" + availablePort - + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.rest.RestDemoForTestException&" - ); + + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.rest.RestDemoForTestException&"); consumer = this.registerProvider(consumer, server, RestDemoForTestException.class); Invoker invoker = protocol.refer(RestDemoForTestException.class, consumer); - RestDemoForTestException client = proxy.getProxy(invoker); Assertions.assertThrows(RpcException.class, () -> { client.testMethodDisallowed("aaa"); - }); - invoker.destroy(); exporter.unexport(); } @@ -628,16 +616,18 @@ class JaxrsRestProtocolTest { @Test void testGetInvoker() { Assertions.assertDoesNotThrow(() -> { - URL exportUrl = URL.valueOf("rest://127.0.0.1:" + availablePort + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.rest.TestGetInvokerService"); + URL exportUrl = URL.valueOf("rest://127.0.0.1:" + availablePort + + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.rest.TestGetInvokerService"); TestGetInvokerService server = new TestGetInvokerServiceImpl(); URL url = this.registerProvider(exportUrl, server, DemoService.class); - Exporter exporter = protocol.export(proxy.getInvoker(server, TestGetInvokerService.class, url)); - - TestGetInvokerService invokerService = this.proxy.getProxy(protocol.refer(TestGetInvokerService.class, url)); + Exporter exporter = + protocol.export(proxy.getInvoker(server, TestGetInvokerService.class, url)); + TestGetInvokerService invokerService = + this.proxy.getProxy(protocol.refer(TestGetInvokerService.class, url)); String invoker = invokerService.getInvoker(); Assertions.assertEquals("success", invoker); @@ -653,13 +643,12 @@ class JaxrsRestProtocolTest { URL url = this.registerProvider(exportUrl, server, DemoService.class); URL nettyUrl = url.addParameter(SERVER_KEY, "netty") - .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.filter.TestContainerRequestFilter"); + .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.filter.TestContainerRequestFilter"); Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - Assertions.assertEquals("return-success", demoService.sayHello("hello")); exporter.unexport(); } @@ -671,13 +660,12 @@ class JaxrsRestProtocolTest { URL url = this.registerProvider(exportUrl, server, DemoService.class); URL nettyUrl = url.addParameter(SERVER_KEY, "netty") - .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.intercept.DynamicTraceInterceptor"); + .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.intercept.DynamicTraceInterceptor"); Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - Assertions.assertEquals("intercept", demoService.sayHello("hello")); exporter.unexport(); } @@ -689,13 +677,12 @@ class JaxrsRestProtocolTest { URL url = this.registerProvider(exportUrl, server, DemoService.class); URL nettyUrl = url.addParameter(SERVER_KEY, "netty") - .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.filter.TraceFilter"); + .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.filter.TraceFilter"); Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - Assertions.assertEquals("response-filter", demoService.sayHello("hello")); exporter.unexport(); } @@ -712,8 +699,9 @@ class JaxrsRestProtocolTest { DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - - Assertions.assertEquals(User.getInstance(), demoService.list(Arrays.asList(User.getInstance())).get(0)); + Assertions.assertEquals( + User.getInstance(), + demoService.list(Arrays.asList(User.getInstance())).get(0)); HashSet objects = new HashSet<>(); objects.add(User.getInstance()); @@ -743,46 +731,41 @@ class JaxrsRestProtocolTest { nettyUrl = url.addParameter("SERVER_KEY", "netty"); exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - exporter.unexport(); } @Test void testBody() { - Assertions.assertThrowsExactly(RpcException.class, () -> { DemoService server = new DemoServiceImpl(); URL url = this.registerProvider(exportUrl, server, DemoService.class); - URL nettyUrl = url.addParameter(org.apache.dubbo.remoting.Constants.PAYLOAD_KEY, 1024); + URL nettyUrl = url.addParameter(org.apache.dubbo.remoting.Constants.PAYLOAD_KEY, 1024); Exporter exporter = protocol.export(proxy.getInvoker(server, DemoService.class, nettyUrl)); - DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); List users = new ArrayList<>(); for (int i = 0; i < 10000; i++) { users.add(User.getInstance()); - } demoService.list(users); exporter.unexport(); }); - } - @Test void testRequestAndResponseFilter() { DemoService server = new DemoServiceImpl(); - URL exportUrl = URL.valueOf("rest://127.0.0.1:" + availablePort + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.DemoService&extension=" - + TraceRequestAndResponseFilter.class.getName()); + URL exportUrl = URL.valueOf("rest://127.0.0.1:" + availablePort + + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.DemoService&extension=" + + TraceRequestAndResponseFilter.class.getName()); URL nettyUrl = this.registerProvider(exportUrl, server, DemoService.class); @@ -790,7 +773,6 @@ class JaxrsRestProtocolTest { DemoService demoService = this.proxy.getProxy(protocol.refer(DemoService.class, nettyUrl)); - Assertions.assertEquals("header-result", demoService.sayHello("hello")); exporter.unexport(); } @@ -809,18 +791,13 @@ class JaxrsRestProtocolTest { User user = demoService.formBody(User.getInstance()); - Assertions.assertEquals("formBody",user.getName()); + Assertions.assertEquals("formBody", user.getName()); exporter.unexport(); } private URL registerProvider(URL url, Object impl, Class interfaceClass) { ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass); - ProviderModel providerModel = new ProviderModel( - url.getServiceKey(), - impl, - serviceDescriptor, - null, - null); + ProviderModel providerModel = new ProviderModel(url.getServiceKey(), impl, serviceDescriptor, null, null); repository.registerProvider(providerModel); return url.setServiceModel(providerModel); } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/JsonCompatibilityCheckTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/JsonCompatibilityCheckTest.java index 2f871f2078..e714e60107 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/JsonCompatibilityCheckTest.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/JsonCompatibilityCheckTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.rest; import org.apache.dubbo.common.URL; @@ -23,7 +22,6 @@ import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; -import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleServiceRepository; import org.apache.dubbo.rpc.model.ProviderModel; @@ -39,16 +37,18 @@ import static org.apache.dubbo.rpc.protocol.rest.constans.RestConstant.JSON_CHEC import static org.apache.dubbo.rpc.protocol.rest.constans.RestConstant.JSON_CHECK_LEVEL_STRICT; import static org.apache.dubbo.rpc.protocol.rest.constans.RestConstant.JSON_CHECK_LEVEL_WARN; - public class JsonCompatibilityCheckTest { private final int availablePort = NetUtils.getAvailablePort(); - private final URL exportUrl = URL.valueOf("rest://127.0.0.1:" + availablePort + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.compatibility.RestDemoService"); - private final ModuleServiceRepository repository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); - - private final Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); - private final ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + private final URL exportUrl = URL.valueOf("rest://127.0.0.1:" + availablePort + + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.compatibility.RestDemoService"); + private final ModuleServiceRepository repository = + ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); + private final Protocol protocol = + ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); + private final ProxyFactory proxy = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); @Test public void testJsonCheckDisabled() { @@ -97,12 +97,7 @@ public class JsonCompatibilityCheckTest { private URL registerProvider(URL url, Object impl, Class interfaceClass) { ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass); - ProviderModel providerModel = new ProviderModel( - url.getServiceKey(), - impl, - serviceDescriptor, - null, - null); + ProviderModel providerModel = new ProviderModel(url.getServiceKey(), impl, serviceDescriptor, null, null); repository.registerProvider(providerModel); return url.setServiceModel(providerModel); } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/MediaTypeUtilTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/MediaTypeUtilTest.java index bfb2e0005d..84db93b516 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/MediaTypeUtilTest.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/MediaTypeUtilTest.java @@ -19,6 +19,7 @@ package org.apache.dubbo.rpc.protocol.rest; import org.apache.dubbo.metadata.rest.media.MediaType; import org.apache.dubbo.rpc.protocol.rest.exception.UnSupportContentTypeException; import org.apache.dubbo.rpc.protocol.rest.util.MediaTypeUtil; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -29,30 +30,26 @@ public class MediaTypeUtilTest { Assertions.assertThrows(UnSupportContentTypeException.class, () -> { MediaTypeUtil.convertMediaType(null, "aaaaa"); - }); - - } @Test void testConvertMediaType() { - MediaType mediaType = MediaTypeUtil.convertMediaType(null, new String[]{MediaType.APPLICATION_JSON_VALUE.value}); + MediaType mediaType = + MediaTypeUtil.convertMediaType(null, new String[] {MediaType.APPLICATION_JSON_VALUE.value}); Assertions.assertEquals(MediaType.APPLICATION_JSON_VALUE, mediaType); - mediaType = MediaTypeUtil.convertMediaType(int.class, null); Assertions.assertEquals(MediaType.TEXT_PLAIN, mediaType); - mediaType = MediaTypeUtil.convertMediaType(null, new String[]{MediaType.ALL_VALUE.value}); + mediaType = MediaTypeUtil.convertMediaType(null, new String[] {MediaType.ALL_VALUE.value}); Assertions.assertEquals(MediaType.APPLICATION_JSON_VALUE, mediaType); - mediaType = MediaTypeUtil.convertMediaType(String.class, new String[]{MediaType.TEXT_XML.value}); + mediaType = MediaTypeUtil.convertMediaType(String.class, new String[] {MediaType.TEXT_XML.value}); Assertions.assertEquals(MediaType.TEXT_XML, mediaType); - } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NettyRequestFacadeTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NettyRequestFacadeTest.java index de5f70776f..87a30ad32c 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NettyRequestFacadeTest.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NettyRequestFacadeTest.java @@ -16,12 +16,7 @@ */ package org.apache.dubbo.rpc.protocol.rest; -import io.netty.handler.codec.http.DefaultFullHttpRequest; -import io.netty.handler.codec.http.HttpMethod; -import io.netty.handler.codec.http.HttpVersion; import org.apache.dubbo.rpc.protocol.rest.request.NettyRequestFacade; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; @@ -29,21 +24,27 @@ import java.util.Enumeration; import java.util.List; import java.util.Map; +import io.netty.handler.codec.http.DefaultFullHttpRequest; +import io.netty.handler.codec.http.HttpMethod; +import io.netty.handler.codec.http.HttpVersion; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + public class NettyRequestFacadeTest { @Test void testMethod() { String uri = "/a/b?c=c&d=d"; - DefaultFullHttpRequest defaultFullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri); + DefaultFullHttpRequest defaultFullHttpRequest = + new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri); defaultFullHttpRequest.headers().add("h1", "a"); defaultFullHttpRequest.headers().add("h1", "b"); defaultFullHttpRequest.headers().add("h2", "c"); NettyRequestFacade nettyRequestFacade = new NettyRequestFacade(defaultFullHttpRequest, null); - - Assertions.assertArrayEquals(new String[]{"c"}, nettyRequestFacade.getParameterValues("c")); + Assertions.assertArrayEquals(new String[] {"c"}, nettyRequestFacade.getParameterValues("c")); Enumeration parameterNames = nettyRequestFacade.getParameterNames(); List names = new ArrayList<>(); @@ -64,10 +65,8 @@ public class NettyRequestFacadeTest { Assertions.assertArrayEquals(Arrays.asList("h1", "h2").toArray(), heads.toArray()); - Assertions.assertEquals(uri, nettyRequestFacade.getRequestURI()); - Assertions.assertEquals("c", nettyRequestFacade.getHeader("h2")); Assertions.assertEquals("d", nettyRequestFacade.getParameter("d")); @@ -76,11 +75,10 @@ public class NettyRequestFacadeTest { Assertions.assertEquals(null, nettyRequestFacade.getParameterValues("e")); - Assertions.assertArrayEquals(new String[]{"d"}, nettyRequestFacade.getParameterValues("d")); + Assertions.assertArrayEquals(new String[] {"d"}, nettyRequestFacade.getParameterValues("d")); Enumeration h1s = nettyRequestFacade.getHeaders("h1"); - heads = new ArrayList<>(); while (h1s.hasMoreElements()) { @@ -88,15 +86,13 @@ public class NettyRequestFacadeTest { heads.add(h1s.nextElement()); } - Assertions.assertArrayEquals(new String[]{"a","b"}, heads.toArray()); + Assertions.assertArrayEquals(new String[] {"a", "b"}, heads.toArray()); Map parameterMap = nettyRequestFacade.getParameterMap(); + Assertions.assertArrayEquals(new String[] {"c"}, parameterMap.get("c")); + Assertions.assertArrayEquals(new String[] {"d"}, parameterMap.get("d")); - Assertions.assertArrayEquals(new String[]{"c"},parameterMap.get("c")); - Assertions.assertArrayEquals(new String[]{"d"},parameterMap.get("d")); - - Assertions.assertEquals("GET",nettyRequestFacade.getMethod()); - + Assertions.assertEquals("GET", nettyRequestFacade.getMethod()); } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NoAnnotationRestProtocolTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NoAnnotationRestProtocolTest.java index b7a7b439bf..ce9a2502fe 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NoAnnotationRestProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NoAnnotationRestProtocolTest.java @@ -33,18 +33,20 @@ import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.protocol.rest.noannotation.NoAnnotationDemoService; import org.apache.dubbo.rpc.protocol.rest.noannotation.NoAnnotationDemoServiceImpl; +import java.util.Arrays; +import java.util.List; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.List; - - class NoAnnotationRestProtocolTest { - private final Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); - private final ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - private final ModuleServiceRepository repository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); + private final Protocol protocol = + ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); + private final ProxyFactory proxy = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + private final ModuleServiceRepository repository = + ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); @AfterEach public void tearDown() { @@ -73,16 +75,17 @@ class NoAnnotationRestProtocolTest { } void testRestProtocol() { - URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.noannotation.NoAnnotationDemoService"); + URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() + + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.noannotation.NoAnnotationDemoService"); NoAnnotationDemoServiceImpl server = new NoAnnotationDemoServiceImpl(); url = this.registerProvider(url, server, DemoService.class); - Exporter exporter = protocol.export(proxy.getInvoker(server, NoAnnotationDemoService.class, url)); + Exporter exporter = + protocol.export(proxy.getInvoker(server, NoAnnotationDemoService.class, url)); Invoker invoker = protocol.refer(NoAnnotationDemoService.class, url); - NoAnnotationDemoService client = proxy.getProxy(invoker); Object result = client.sayHello("haha"); Assertions.assertEquals("Hello, haha", result); @@ -93,14 +96,14 @@ class NoAnnotationRestProtocolTest { User user = client.user(User.getInstance()); Assertions.assertEquals("invoked", user.getName()); - Assertions.assertEquals(User.getInstance(),client.userList(Arrays.asList(User.getInstance())).get(0)); - + Assertions.assertEquals( + User.getInstance(), + client.userList(Arrays.asList(User.getInstance())).get(0)); invoker.destroy(); exporter.unexport(); } - @Test void testAnotherUserRestProtocolByDifferentRestClient() { testAnotherUserRestProtocol(org.apache.dubbo.remoting.Constants.OK_HTTP); @@ -108,20 +111,19 @@ class NoAnnotationRestProtocolTest { testAnotherUserRestProtocol(org.apache.dubbo.remoting.Constants.URL_CONNECTION); } - void testAnotherUserRestProtocol(String restClient) { URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() - + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.noannotation.NoAnnotationDemoService&" - + org.apache.dubbo.remoting.Constants.CLIENT_KEY + "=" + restClient); + + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.noannotation.NoAnnotationDemoService&" + + org.apache.dubbo.remoting.Constants.CLIENT_KEY + "=" + restClient); NoAnnotationDemoService server = new NoAnnotationDemoServiceImpl(); url = this.registerProvider(url, server, DemoService.class); - Exporter exporter = protocol.export(proxy.getInvoker(server, NoAnnotationDemoService.class, url)); + Exporter exporter = + protocol.export(proxy.getInvoker(server, NoAnnotationDemoService.class, url)); Invoker invoker = protocol.refer(NoAnnotationDemoService.class, url); - NoAnnotationDemoService client = proxy.getProxy(invoker); String name = "no-annotation"; String result = client.sayHello(name); @@ -132,15 +134,9 @@ class NoAnnotationRestProtocolTest { exporter.unexport(); } - private URL registerProvider(URL url, Object impl, Class interfaceClass) { ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass); - ProviderModel providerModel = new ProviderModel( - url.getServiceKey(), - impl, - serviceDescriptor, - null, - null); + ProviderModel providerModel = new ProviderModel(url.getServiceKey(), impl, serviceDescriptor, null, null); repository.registerProvider(providerModel); return url.setServiceModel(providerModel); } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NumberUtilsTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NumberUtilsTest.java index a726e38cc5..58cf56f916 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NumberUtilsTest.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/NumberUtilsTest.java @@ -18,13 +18,14 @@ package org.apache.dubbo.rpc.protocol.rest; import org.apache.dubbo.rpc.protocol.rest.util.DataParseUtils; import org.apache.dubbo.rpc.protocol.rest.util.NumberUtils; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + public class NumberUtilsTest { void testParseNumber(String numberStr) { int integer = NumberUtils.parseNumber(numberStr, Integer.class); @@ -62,8 +63,6 @@ public class NumberUtilsTest { BigInteger f = NumberUtils.parseNumber(numberStr, BigInteger.class); Assertions.assertEquals(1, f.intValue()); - - } @Test @@ -77,32 +76,32 @@ public class NumberUtilsTest { Assertions.assertArrayEquals(except, bytes); - except = new byte[]{49}; + except = new byte[] {49}; bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(Byte.valueOf("1")); Assertions.assertArrayEquals(except, bytes); - except = new byte[]{49}; + except = new byte[] {49}; bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(Short.valueOf("1")); Assertions.assertArrayEquals(except, bytes); - except = new byte[]{49}; + except = new byte[] {49}; bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(Long.valueOf("1")); Assertions.assertArrayEquals(except, bytes); - except = new byte[]{49}; + except = new byte[] {49}; bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(BigDecimal.valueOf(1)); Assertions.assertArrayEquals(except, bytes); - except = new byte[]{116, 114, 117, 101}; + except = new byte[] {116, 114, 117, 101}; bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(Boolean.TRUE); Assertions.assertArrayEquals(except, bytes); - except = new byte[]{116, 114, 117, 101}; + except = new byte[] {116, 114, 117, 101}; bytes = (byte[]) DataParseUtils.objectTextConvertToByteArray(true); Assertions.assertArrayEquals(except, bytes); @@ -111,8 +110,6 @@ public class NumberUtilsTest { except = User.getInstance().toString().getBytes(StandardCharsets.UTF_8); Assertions.assertArrayEquals(except, bytes); - - } @Test @@ -121,10 +118,8 @@ public class NumberUtilsTest { testParseNumber("0X0001"); testParseNumber("0x0001"); testParseNumber("#1"); - } - @Test void testUnHexNumber() { String numberStr = "1"; @@ -160,18 +155,14 @@ public class NumberUtilsTest { Assertions.assertThrowsExactly(IllegalArgumentException.class, () -> { Object abc = NumberUtils.parseNumber("abc", Object.class); - }); Assertions.assertThrowsExactly(IllegalArgumentException.class, () -> { Object abc = NumberUtils.parseNumber(null, Object.class); - }); Assertions.assertThrowsExactly(IllegalArgumentException.class, () -> { Object abc = NumberUtils.parseNumber("1", null); - }); } - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ResteasyResponseTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ResteasyResponseTest.java index 1c831beea4..7c9d7caece 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ResteasyResponseTest.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ResteasyResponseTest.java @@ -24,21 +24,26 @@ import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.model.*; import org.apache.dubbo.rpc.protocol.rest.rest.RestDemoService; import org.apache.dubbo.rpc.protocol.rest.rest.RestDemoServiceImpl; + +import javax.ws.rs.core.Response; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import javax.ws.rs.core.Response; - import static org.apache.dubbo.remoting.Constants.SERVER_KEY; public class ResteasyResponseTest { - private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); - private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + private Protocol protocol = + ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); + private ProxyFactory proxy = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); private final int availablePort = NetUtils.getAvailablePort(); - private final URL exportUrl = URL.valueOf("rest://127.0.0.1:" + availablePort + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.rest.RestDemoService"); - private final ModuleServiceRepository repository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); + private final URL exportUrl = URL.valueOf("rest://127.0.0.1:" + availablePort + + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.rest.RestDemoService"); + private final ModuleServiceRepository repository = + ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); private static final String SERVER = "netty4"; @AfterEach @@ -46,6 +51,7 @@ public class ResteasyResponseTest { protocol.destroy(); FrameworkModel.destroyAll(); } + @Test void testResponse() { RestDemoService server = new RestDemoServiceImpl(); @@ -64,16 +70,8 @@ public class ResteasyResponseTest { private URL registerProvider(URL url, Object impl, Class interfaceClass) { ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass); - ProviderModel providerModel = new ProviderModel( - url.getServiceKey(), - impl, - serviceDescriptor, - null, - null); + ProviderModel providerModel = new ProviderModel(url.getServiceKey(), impl, serviceDescriptor, null, null); repository.registerProvider(providerModel); return url.setServiceModel(providerModel); } - - - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RpcExceptionMapperTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RpcExceptionMapperTest.java index 2749282ea7..fdb3ffdf2f 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RpcExceptionMapperTest.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/RpcExceptionMapperTest.java @@ -17,19 +17,19 @@ package org.apache.dubbo.rpc.protocol.rest; import org.apache.dubbo.rpc.RpcException; - import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionHandler; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Answers; -import org.mockito.internal.util.collections.Sets; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import java.util.LinkedList; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Answers; +import org.mockito.internal.util.collections.Sets; + import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; @@ -64,7 +64,6 @@ class RpcExceptionMapperTest { RpcException rpcException = new RpcException(); Object response = exceptionMapper.result(rpcException); - assertThat(response, not(nullValue())); assertThat(response, instanceOf(String.class)); } @@ -80,12 +79,9 @@ class RpcExceptionMapperTest { String value = "value"; restConstraintViolation.setValue(value); - Assertions.assertEquals(message, restConstraintViolation.getMessage()); Assertions.assertEquals(path, restConstraintViolation.getPath()); Assertions.assertEquals(value, restConstraintViolation.getValue()); - - } @Test @@ -93,20 +89,16 @@ class RpcExceptionMapperTest { ViolationReport violationReport = new ViolationReport(); - RestConstraintViolation restConstraintViolation = new RestConstraintViolation("path", "message", "value"); violationReport.addConstraintViolation(restConstraintViolation); Assertions.assertEquals(1, violationReport.getConstraintViolations().size()); - violationReport = new ViolationReport(); violationReport.setConstraintViolations(new LinkedList<>()); Assertions.assertEquals(0, violationReport.getConstraintViolations().size()); - - } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ServiceConfigTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ServiceConfigTest.java index e37f646c08..8fab22157f 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ServiceConfigTest.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/ServiceConfigTest.java @@ -32,16 +32,19 @@ import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.protocol.rest.constans.RestConstant; import org.apache.dubbo.rpc.protocol.rest.mvc.SpringControllerService; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; - public class ServiceConfigTest { - private final Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); - private final ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - private final ModuleServiceRepository repository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); + private final Protocol protocol = + ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); + private final ProxyFactory proxy = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + private final ModuleServiceRepository repository = + ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); @AfterEach public void tearDown() { @@ -53,13 +56,15 @@ public class ServiceConfigTest { void testControllerService() throws Exception { int availablePort = NetUtils.getAvailablePort(); - URL url = URL.valueOf("rest://127.0.0.1:" + availablePort + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.mvc.SpringControllerService"); + URL url = URL.valueOf("rest://127.0.0.1:" + availablePort + + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.mvc.SpringControllerService"); SpringControllerService server = new SpringControllerService(); url = this.registerProvider(url, server, SpringControllerService.class); - Exporter exporter = protocol.export(proxy.getInvoker(server, SpringControllerService.class, url)); + Exporter exporter = + protocol.export(proxy.getInvoker(server, SpringControllerService.class, url)); OKHttpRestClient okHttpRestClient = new OKHttpRestClient(new HttpClientConfig()); @@ -71,20 +76,13 @@ public class ServiceConfigTest { byte[] body = okHttpRestClient.send(requestTemplate).get().getBody(); - Assertions.assertEquals("dubbo", new String(body)); exporter.unexport(); } - private URL registerProvider(URL url, Object impl, Class interfaceClass) { ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass); - ProviderModel providerModel = new ProviderModel( - url.getServiceKey(), - impl, - serviceDescriptor, - null, - null); + ProviderModel providerModel = new ProviderModel(url.getServiceKey(), impl, serviceDescriptor, null, null); repository.registerProvider(providerModel); return url.setServiceModel(providerModel); } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/SpringMvcRestProtocolTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/SpringMvcRestProtocolTest.java index 62ff7101b1..274117756c 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/SpringMvcRestProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/SpringMvcRestProtocolTest.java @@ -35,10 +35,13 @@ import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionHandler; import org.apache.dubbo.rpc.protocol.rest.exception.mapper.ExceptionMapper; import org.apache.dubbo.rpc.protocol.rest.mvc.SpringDemoServiceImpl; - import org.apache.dubbo.rpc.protocol.rest.mvc.SpringRestDemoService; import org.apache.dubbo.rpc.protocol.rest.rest.AnotherUserRestService; import org.apache.dubbo.rpc.protocol.rest.rest.AnotherUserRestServiceImpl; + +import java.util.Arrays; +import java.util.Map; + import org.hamcrest.CoreMatchers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; @@ -46,9 +49,6 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.util.LinkedMultiValueMap; -import java.util.Arrays; -import java.util.Map; - import static org.apache.dubbo.remoting.Constants.SERVER_KEY; import static org.apache.dubbo.rpc.protocol.rest.Constants.EXTENSION_KEY; import static org.hamcrest.CoreMatchers.equalTo; @@ -57,16 +57,20 @@ import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; public class SpringMvcRestProtocolTest { - private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); - private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); + private Protocol protocol = + ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("rest"); + private ProxyFactory proxy = + ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); private static URL getUrl() { - return URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.mvc.SpringRestDemoService"); + return URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() + + "/rest?interface=org.apache.dubbo.rpc.protocol.rest.mvc.SpringRestDemoService"); } private static final String SERVER = "netty4"; - private final ModuleServiceRepository repository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); + private final ModuleServiceRepository repository = + ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); private final ExceptionMapper exceptionMapper = new ExceptionMapper(); @@ -80,7 +84,6 @@ public class SpringMvcRestProtocolTest { return new SpringDemoServiceImpl(); } - public Class getServerClass() { return SpringRestDemoService.class; } @@ -96,10 +99,10 @@ public class SpringMvcRestProtocolTest { return protocol.export(proxy.getInvoker(server, getServerClass(), url)); } - @Test void testRestProtocol() { - URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.mvc.SpringRestDemoService"); + URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() + + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.mvc.SpringRestDemoService"); SpringRestDemoService server = getServerImpl(); @@ -123,19 +126,19 @@ public class SpringMvcRestProtocolTest { exporter.unexport(); } - @Test void testAnotherUserRestProtocol() { - URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.rest.AnotherUserRestService"); + URL url = URL.valueOf("rest://127.0.0.1:" + NetUtils.getAvailablePort() + + "/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.rest.AnotherUserRestService"); AnotherUserRestServiceImpl server = new AnotherUserRestServiceImpl(); url = this.registerProvider(url, server, SpringRestDemoService.class); - Exporter exporter = protocol.export(proxy.getInvoker(server, AnotherUserRestService.class, url)); + Exporter exporter = + protocol.export(proxy.getInvoker(server, AnotherUserRestService.class, url)); Invoker invoker = protocol.refer(AnotherUserRestService.class, url); - AnotherUserRestService client = proxy.getProxy(invoker); User result = client.getUser(123l); @@ -160,13 +163,15 @@ public class SpringMvcRestProtocolTest { SpringRestDemoService server = getServerImpl(); Assertions.assertFalse(server.isCalled()); int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("rest://127.0.0.1:" + port + "/a/b/c?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.mvc.SpringRestDemoService"); + URL url = URL.valueOf("rest://127.0.0.1:" + port + + "/a/b/c?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.mvc.SpringRestDemoService"); url = this.registerProvider(url, server, SpringRestDemoService.class); Exporter exporter = getExport(url, server); - url = URL.valueOf("rest://127.0.0.1:" + port + "/a/b/c/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.mvc.SpringRestDemoService"); + url = URL.valueOf("rest://127.0.0.1:" + port + + "/a/b/c/?version=1.0.0&interface=org.apache.dubbo.rpc.protocol.rest.mvc.SpringRestDemoService"); Invoker invoker = protocol.refer(SpringRestDemoService.class, url); SpringRestDemoService client = proxy.getProxy(invoker); String result = client.sayHello("haha"); @@ -199,7 +204,6 @@ public class SpringMvcRestProtocolTest { URL nettyUrl = this.registerProvider(getUrl(), server, SpringRestDemoService.class); - Exporter exporter = getExport(nettyUrl, server); SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); @@ -234,7 +238,8 @@ public class SpringMvcRestProtocolTest { Exporter exporter = getExport(nettyUrl, server); - SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); + SpringRestDemoService demoService = + this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); demoService.error(); }); @@ -248,7 +253,12 @@ public class SpringMvcRestProtocolTest { Exporter exporter = getExport(url, server); - RpcInvocation rpcInvocation = new RpcInvocation("hello", SpringRestDemoService.class.getName(), "", new Class[]{Integer.class, Integer.class}, new Integer[]{2, 3}); + RpcInvocation rpcInvocation = new RpcInvocation( + "hello", + SpringRestDemoService.class.getName(), + "", + new Class[] {Integer.class, Integer.class}, + new Integer[] {2, 3}); Result result = exporter.getInvoker().invoke(rpcInvocation); assertThat(result.getValue(), CoreMatchers.is(5)); @@ -270,6 +280,7 @@ public class SpringMvcRestProtocolTest { exporter.unexport(); } + @Disabled @Test void testRpcContextFilter() { @@ -278,8 +289,8 @@ public class SpringMvcRestProtocolTest { URL nettyUrl = this.registerProvider(getUrl(), server, SpringRestDemoService.class); // use RpcContextFilter -// URL nettyUrl = url.addParameter(SERVER_KEY, "netty") -// .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.RpcContextFilter"); + // URL nettyUrl = url.addParameter(SERVER_KEY, "netty") + // .addParameter(EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.RpcContextFilter"); Exporter exporter = getExport(nettyUrl, server); SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); @@ -322,7 +333,6 @@ public class SpringMvcRestProtocolTest { assertThat(protocol.getDefaultPort(), is(80)); } - @Test void testExceptionMapper() { @@ -332,22 +342,20 @@ public class SpringMvcRestProtocolTest { Exporter exporter = getExceptionHandlerExport(exceptionUrl, server); - - SpringRestDemoService referDemoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, exceptionUrl)); + SpringRestDemoService referDemoService = + this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, exceptionUrl)); Assertions.assertEquals("test-exception", referDemoService.error()); exporter.unexport(); } - @Test void testFormConsumerParser() { SpringRestDemoService server = getServerImpl(); URL nettyUrl = this.registerProvider(getUrl(), server, SpringRestDemoService.class); - Exporter exporter = getExport(nettyUrl, server); SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); @@ -373,7 +381,6 @@ public class SpringMvcRestProtocolTest { URL nettyUrl = this.registerProvider(getUrl(), server, SpringRestDemoService.class); - Exporter exporter = getExport(nettyUrl, server); SpringRestDemoService demoService = this.proxy.getProxy(protocol.refer(SpringRestDemoService.class, nettyUrl)); @@ -401,12 +408,7 @@ public class SpringMvcRestProtocolTest { private URL registerProvider(URL url, Object impl, Class interfaceClass) { ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass); - ProviderModel providerModel = new ProviderModel( - url.getServiceKey(), - impl, - serviceDescriptor, - null, - null); + ProviderModel providerModel = new ProviderModel(url.getServiceKey(), impl, serviceDescriptor, null, null); repository.registerProvider(providerModel); return url.setServiceModel(providerModel); } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/Apple.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/Apple.java index 2122660f6a..4185dd5944 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/Apple.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/Apple.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.rest.compatibility; public class Apple implements Fruit { diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/Fruit.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/Fruit.java index c7c36aa4c3..a05779be61 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/Fruit.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/Fruit.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.rest.compatibility; public interface Fruit { diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/RestDemoService.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/RestDemoService.java index a487b37a47..b0b9b37017 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/RestDemoService.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/compatibility/RestDemoService.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.rest.compatibility; import javax.ws.rs.Consumes; diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TestContainerRequestFilter.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TestContainerRequestFilter.java index 5aede99fb5..f7305bac58 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TestContainerRequestFilter.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TestContainerRequestFilter.java @@ -21,8 +21,8 @@ import javax.ws.rs.Priorities; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.Response; -import java.io.IOException; +import java.io.IOException; @Priority(Priorities.USER) public class TestContainerRequestFilter implements ContainerRequestFilter { diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TraceFilter.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TraceFilter.java index 13ed1669f2..cc2a0717b1 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TraceFilter.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TraceFilter.java @@ -1,20 +1,18 @@ /* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. + * 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 org.apache.dubbo.rpc.protocol.rest.filter; @@ -24,6 +22,7 @@ import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; + import java.io.IOException; @Priority(Priorities.USER) @@ -31,15 +30,15 @@ public class TraceFilter implements ContainerRequestFilter, ContainerResponseFil @Override public void filter(ContainerRequestContext requestContext) throws IOException { - System.out.println("Request filter invoked: " + requestContext.getUriInfo().getAbsolutePath()); + System.out.println( + "Request filter invoked: " + requestContext.getUriInfo().getAbsolutePath()); } @Override - public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws - - IOException { + public void filter( + ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) + throws IOException { containerResponseContext.setEntity("response-filter"); System.out.println("Response filter invoked."); - } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TraceRequestAndResponseFilter.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TraceRequestAndResponseFilter.java index b6ca0f1e9f..6837327941 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TraceRequestAndResponseFilter.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/filter/TraceRequestAndResponseFilter.java @@ -1,20 +1,18 @@ /* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. + * 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 org.apache.dubbo.rpc.protocol.rest.filter; @@ -24,6 +22,7 @@ import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; + import java.io.IOException; @Priority(Priorities.USER) @@ -32,16 +31,15 @@ public class TraceRequestAndResponseFilter implements ContainerRequestFilter, Co @Override public void filter(ContainerRequestContext requestContext) throws IOException { - requestContext.getHeaders().add("test-response","header-result"); + requestContext.getHeaders().add("test-response", "header-result"); } @Override - public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws - - IOException { + public void filter( + ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) + throws IOException { String headerString = containerRequestContext.getHeaderString("test-response"); containerResponseContext.setEntity(headerString); - } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerApiListingResourceTest.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerApiListingResourceTest.java index 5da404374a..3bca879806 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerApiListingResourceTest.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/DubboSwaggerApiListingResourceTest.java @@ -16,19 +16,20 @@ */ package org.apache.dubbo.rpc.protocol.rest.integration.swagger; -import io.swagger.models.Swagger; -import org.jboss.resteasy.spi.ResteasyUriInfo; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.ws.rs.core.Application; import javax.ws.rs.core.Response; + import java.net.URI; import java.util.HashSet; import java.util.Set; +import io.swagger.models.Swagger; +import org.jboss.resteasy.spi.ResteasyUriInfo; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -40,7 +41,7 @@ class DubboSwaggerApiListingResourceTest { @Test void test() throws Exception { - DubboSwaggerApiListingResource resource = new DubboSwaggerApiListingResource(); + DubboSwaggerApiListingResource resource = new DubboSwaggerApiListingResource(); app = mock(Application.class); sc = mock(ServletConfig.class); @@ -50,13 +51,12 @@ class DubboSwaggerApiListingResourceTest { when(sc.getServletContext()).thenReturn(mock(ServletContext.class)); when(app.getClasses()).thenReturn(sets); - Response response = resource.getListingJson(app, sc, - null, new ResteasyUriInfo(new URI("http://rest.test"))); + Response response = resource.getListingJson(app, sc, null, new ResteasyUriInfo(new URI("http://rest.test"))); Assertions.assertNotNull(response); - Swagger swagger = (Swagger)response.getEntity(); - Assertions.assertEquals("SwaggerService",swagger.getTags().get(0).getName()); - Assertions.assertEquals("/demoService/hello",swagger.getPaths().keySet().toArray()[0].toString()); + Swagger swagger = (Swagger) response.getEntity(); + Assertions.assertEquals("SwaggerService", swagger.getTags().get(0).getName()); + Assertions.assertEquals( + "/demoService/hello", swagger.getPaths().keySet().toArray()[0].toString()); } - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/SwaggerService.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/SwaggerService.java index 8c00af46fa..6c35edc89c 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/SwaggerService.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/integration/swagger/SwaggerService.java @@ -16,13 +16,13 @@ */ package org.apache.dubbo.rpc.protocol.rest.integration.swagger; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; - import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + @Path("/demoService") @Api(value = "SwaggerService") public interface SwaggerService { @@ -30,5 +30,4 @@ public interface SwaggerService { @Path("/hello") @ApiOperation(value = "hello") Integer hello(@QueryParam("a") Integer a, @QueryParam("b") Integer b); - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/intercept/DynamicTraceInterceptor.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/intercept/DynamicTraceInterceptor.java index c2e5887051..66c62ecda9 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/intercept/DynamicTraceInterceptor.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/intercept/DynamicTraceInterceptor.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest.intercept; - import javax.annotation.Priority; import javax.ws.rs.Priorities; import javax.ws.rs.WebApplicationException; @@ -24,23 +23,25 @@ import javax.ws.rs.ext.ReaderInterceptor; import javax.ws.rs.ext.ReaderInterceptorContext; import javax.ws.rs.ext.WriterInterceptor; import javax.ws.rs.ext.WriterInterceptorContext; + import java.io.IOException; import java.nio.charset.StandardCharsets; @Priority(Priorities.USER) public class DynamicTraceInterceptor implements ReaderInterceptor, WriterInterceptor { - public DynamicTraceInterceptor() { - } + public DynamicTraceInterceptor() {} @Override - public Object aroundReadFrom(ReaderInterceptorContext readerInterceptorContext) throws IOException, WebApplicationException { + public Object aroundReadFrom(ReaderInterceptorContext readerInterceptorContext) + throws IOException, WebApplicationException { System.out.println("Dynamic reader interceptor invoked"); return readerInterceptorContext.proceed(); } @Override - public void aroundWriteTo(WriterInterceptorContext writerInterceptorContext) throws IOException, WebApplicationException { + public void aroundWriteTo(WriterInterceptorContext writerInterceptorContext) + throws IOException, WebApplicationException { System.out.println("Dynamic writer interceptor invoked"); writerInterceptorContext.getOutputStream().write("intercept".getBytes(StandardCharsets.UTF_8)); writerInterceptorContext.proceed(); diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/SpringDemoServiceImpl.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/SpringDemoServiceImpl.java index 38a26a6caf..f5d92787c0 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/SpringDemoServiceImpl.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/SpringDemoServiceImpl.java @@ -16,26 +16,24 @@ */ package org.apache.dubbo.rpc.protocol.rest.mvc; - import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.protocol.rest.User; -import org.springframework.util.LinkedMultiValueMap; import java.util.List; import java.util.Map; +import org.springframework.util.LinkedMultiValueMap; + public class SpringDemoServiceImpl implements SpringRestDemoService { private static Map context; private boolean called; - @Override public String sayHello(String name) { called = true; return "Hello, " + name; } - @Override public boolean isCalled() { return called; @@ -67,7 +65,6 @@ public class SpringDemoServiceImpl implements SpringRestDemoService { return a + b; } - @Override public String error() { throw new RuntimeException(); @@ -77,7 +74,6 @@ public class SpringDemoServiceImpl implements SpringRestDemoService { return context; } - @Override public int primitiveInt(int a, int b) { return a + b; @@ -97,7 +93,4 @@ public class SpringDemoServiceImpl implements SpringRestDemoService { public long primitiveShort(short a, Long b, int c) { return a + b; } - - - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/SpringRestDemoService.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/SpringRestDemoService.java index adb461bf4a..b2bcd08e0f 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/SpringRestDemoService.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/SpringRestDemoService.java @@ -16,8 +16,10 @@ */ package org.apache.dubbo.rpc.protocol.rest.mvc; - import org.apache.dubbo.rpc.protocol.rest.User; + +import java.util.List; + import org.springframework.http.MediaType; import org.springframework.util.LinkedMultiValueMap; import org.springframework.web.bind.annotation.RequestBody; @@ -26,8 +28,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; -import java.util.List; - @RequestMapping("/demoService") public interface SpringRestDemoService { @RequestMapping(value = "/hello", method = RequestMethod.GET) @@ -41,10 +41,16 @@ public interface SpringRestDemoService { boolean isCalled(); - @RequestMapping(value = "/testFormBody", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) + @RequestMapping( + value = "/testFormBody", + method = RequestMethod.POST, + consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) String testFormBody(@RequestBody User user); - @RequestMapping(value = "/testFormMapBody", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) + @RequestMapping( + value = "/testFormMapBody", + method = RequestMethod.POST, + consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) List testFormMapBody(@RequestBody LinkedMultiValueMap map); @RequestMapping(value = "/testHeader", method = RequestMethod.POST, consumes = MediaType.TEXT_PLAIN_VALUE) @@ -62,7 +68,6 @@ public interface SpringRestDemoService { @RequestMapping(method = RequestMethod.GET, value = "/primitiveByte") long primitiveByte(@RequestParam("a") byte a, @RequestParam("b") Long b); - @RequestMapping(method = RequestMethod.POST, value = "/primitiveShort") long primitiveShort(@RequestParam("a") short a, @RequestParam("b") Long b, @RequestBody int c); } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/feign/FeignClientController.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/feign/FeignClientController.java index ff4baa1acb..1d8d046793 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/feign/FeignClientController.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/feign/FeignClientController.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.rest.mvc.feign; - import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/feign/FeignClientControllerImpl.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/feign/FeignClientControllerImpl.java index 591694f607..a7d4387c89 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/feign/FeignClientControllerImpl.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/mvc/feign/FeignClientControllerImpl.java @@ -16,9 +16,7 @@ */ package org.apache.dubbo.rpc.protocol.rest.mvc.feign; - - -public class FeignClientControllerImpl implements FeignClientController{ +public class FeignClientControllerImpl implements FeignClientController { @Override public String hello() { diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/noannotation/NoAnnotationDemoService.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/noannotation/NoAnnotationDemoService.java index 8970ebaf2a..267c1106b4 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/noannotation/NoAnnotationDemoService.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/noannotation/NoAnnotationDemoService.java @@ -16,12 +16,10 @@ */ package org.apache.dubbo.rpc.protocol.rest.noannotation; - import org.apache.dubbo.rpc.protocol.rest.User; import java.util.List; - public interface NoAnnotationDemoService { Integer hello(Integer a, Integer b); @@ -32,5 +30,4 @@ public interface NoAnnotationDemoService { User user(User user); List userList(List users); - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/noannotation/NoAnnotationDemoServiceImpl.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/noannotation/NoAnnotationDemoServiceImpl.java index 4160e51575..e29313375a 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/noannotation/NoAnnotationDemoServiceImpl.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/noannotation/NoAnnotationDemoServiceImpl.java @@ -16,15 +16,12 @@ */ package org.apache.dubbo.rpc.protocol.rest.noannotation; - import org.apache.dubbo.rpc.protocol.rest.User; import java.util.List; - public class NoAnnotationDemoServiceImpl implements NoAnnotationDemoService { - @Override public Integer hello(Integer a, Integer b) { return a + b; @@ -37,7 +34,7 @@ public class NoAnnotationDemoServiceImpl implements NoAnnotationDemoService { @Override public String sayHello(String name) { - return "Hello, "+name; + return "Hello, " + name; } @Override diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/AnotherUserRestService.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/AnotherUserRestService.java index a2ecc36808..0eed7872e5 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/AnotherUserRestService.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/AnotherUserRestService.java @@ -26,6 +26,7 @@ import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; + import java.util.Map; @Path("u") @@ -60,5 +61,5 @@ public interface AnotherUserRestService { @POST @Path("headerMap") @Produces({MediaType.APPLICATION_JSON}) - String headerMap(@HeaderParam("headers") Map headers); + String headerMap(@HeaderParam("headers") Map headers); } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/AnotherUserRestServiceImpl.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/AnotherUserRestServiceImpl.java index 7a81f071fe..3e99f97bae 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/AnotherUserRestServiceImpl.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/AnotherUserRestServiceImpl.java @@ -20,10 +20,8 @@ import org.apache.dubbo.rpc.protocol.rest.User; import java.util.Map; - public class AnotherUserRestServiceImpl implements AnotherUserRestService { - @Override public User getUser(Long id) { @@ -57,6 +55,4 @@ public class AnotherUserRestServiceImpl implements AnotherUserRestService { public String headerMap(Map headers) { return headers.get("headers"); } - - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/HttpMethodService.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/HttpMethodService.java index 914da271e9..88696140a7 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/HttpMethodService.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/HttpMethodService.java @@ -55,5 +55,4 @@ public interface HttpMethodService { @Path("/sayOptions") @Consumes({javax.ws.rs.core.MediaType.TEXT_PLAIN}) String sayHelloOptions(@QueryParam("name") String name); - } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/HttpMethodServiceImpl.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/HttpMethodServiceImpl.java index f220d360f9..7dee6606c2 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/HttpMethodServiceImpl.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/HttpMethodServiceImpl.java @@ -16,8 +16,7 @@ */ package org.apache.dubbo.rpc.protocol.rest.rest; - -public class HttpMethodServiceImpl implements HttpMethodService{ +public class HttpMethodServiceImpl implements HttpMethodService { @Override public String sayHelloPost(String name) { diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RegistrationResult.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RegistrationResult.java index ff48474d16..12b0e5627d 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RegistrationResult.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RegistrationResult.java @@ -17,6 +17,7 @@ package org.apache.dubbo.rpc.protocol.rest.rest; import javax.xml.bind.annotation.XmlRootElement; + import java.io.Serializable; import java.util.Objects; @@ -28,8 +29,7 @@ public class RegistrationResult implements Serializable { private Long id; - public RegistrationResult() { - } + public RegistrationResult() {} public RegistrationResult(Long id) { this.id = id; diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RestDemoForTestException.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RestDemoForTestException.java index c6c36593f4..5ef5293a6d 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RestDemoForTestException.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RestDemoForTestException.java @@ -36,7 +36,7 @@ public interface RestDemoForTestException { @GET @Consumes({MediaType.TEXT_PLAIN}) @Path("/hello") - Integer test400(@QueryParam("a")String a,@QueryParam("b") String b); + Integer test400(@QueryParam("a") String a, @QueryParam("b") String b); @POST @Path("{uid}") diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RestDemoService.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RestDemoService.java index 56b3fd1ee7..de00e90184 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RestDemoService.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RestDemoService.java @@ -20,16 +20,15 @@ import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - @Path("/demoService") public interface RestDemoService { @GET @Path("/hello") - Integer hello(@QueryParam("a")Integer a,@QueryParam("b") Integer b); + Integer hello(@QueryParam("a") Integer a, @QueryParam("b") Integer b); @GET @Path("/findUserById") - Response findUserById(@QueryParam("id")Integer id); + Response findUserById(@QueryParam("id") Integer id); @GET @Path("/error") diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RestDemoServiceImpl.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RestDemoServiceImpl.java index b0b32ed9a8..a71f4b2095 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RestDemoServiceImpl.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/RestDemoServiceImpl.java @@ -17,16 +17,18 @@ package org.apache.dubbo.rpc.protocol.rest.rest; import org.apache.dubbo.rpc.RpcContext; -import org.jboss.resteasy.specimpl.BuiltResponse; + import javax.ws.rs.core.Response; + import java.util.HashMap; import java.util.Map; +import org.jboss.resteasy.specimpl.BuiltResponse; + public class RestDemoServiceImpl implements RestDemoService { private static Map context; private boolean called; - @Override public String sayHello(String name) { called = true; @@ -38,7 +40,6 @@ public class RestDemoServiceImpl implements RestDemoService { return number; } - public boolean isCalled() { return called; } @@ -56,9 +57,9 @@ public class RestDemoServiceImpl implements RestDemoService { @Override public Response findUserById(Integer id) { - Map content = new HashMap<>(); - content.put("username","jack"); - content.put("id",id); + Map content = new HashMap<>(); + content.put("username", "jack"); + content.put("id", id); return BuiltResponse.ok(content).build(); } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/TestGetInvokerService.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/TestGetInvokerService.java index 39b42e740b..994b7a285a 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/TestGetInvokerService.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/TestGetInvokerService.java @@ -16,14 +16,12 @@ */ package org.apache.dubbo.rpc.protocol.rest.rest; - import javax.ws.rs.GET; import javax.ws.rs.Path; @Path("/test") public interface TestGetInvokerService { - @GET @Path("/getInvoker") String getInvoker(); diff --git a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/TestGetInvokerServiceImpl.java b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/TestGetInvokerServiceImpl.java index ed66a1e3f8..e04757afcf 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/TestGetInvokerServiceImpl.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/test/java/org/apache/dubbo/rpc/protocol/rest/rest/TestGetInvokerServiceImpl.java @@ -16,17 +16,16 @@ */ package org.apache.dubbo.rpc.protocol.rest.rest; - import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.protocol.rest.RestRPCInvocationUtil; import org.apache.dubbo.rpc.protocol.rest.request.RequestFacade; -import org.junit.jupiter.api.Assertions; import java.lang.reflect.Method; -public class TestGetInvokerServiceImpl implements TestGetInvokerService { +import org.junit.jupiter.api.Assertions; +public class TestGetInvokerServiceImpl implements TestGetInvokerService { @Override public String getInvoker() { @@ -34,7 +33,6 @@ public class TestGetInvokerServiceImpl implements TestGetInvokerService { RequestFacade requestFacade = (RequestFacade) request; Invoker invokerByRequest = RestRPCInvocationUtil.getInvokerByRequest((RequestFacade) request); - Method hello = null; Method hashcode = null; try { @@ -45,10 +43,11 @@ public class TestGetInvokerServiceImpl implements TestGetInvokerService { } - Invoker invokerByServiceInvokeMethod = RestRPCInvocationUtil.getInvokerByServiceInvokeMethod(hello,requestFacade.getServiceDeployer()); - - Invoker invoker = RestRPCInvocationUtil.getInvokerByServiceInvokeMethod(hashcode,requestFacade.getServiceDeployer()); + Invoker invokerByServiceInvokeMethod = + RestRPCInvocationUtil.getInvokerByServiceInvokeMethod(hello, requestFacade.getServiceDeployer()); + Invoker invoker = + RestRPCInvocationUtil.getInvokerByServiceInvokeMethod(hashcode, requestFacade.getServiceDeployer()); Assertions.assertEquals(invokerByRequest, invokerByServiceInvokeMethod); Assertions.assertNull(invoker); diff --git a/dubbo-rpc/dubbo-rpc-triple/pom.xml b/dubbo-rpc/dubbo-rpc-triple/pom.xml index 775be67310..7d52a6682a 100644 --- a/dubbo-rpc/dubbo-rpc-triple/pom.xml +++ b/dubbo-rpc/dubbo-rpc-triple/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - org.apache.dubbo - dubbo-rpc - ${revision} - ../pom.xml - - dubbo-rpc-triple - jar - ${project.artifactId} - The triple protocol module - - false - - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-http12 - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.parent.version} - test - - - io.netty - netty-codec-http2 - - - com.google.protobuf - protobuf-java - - - org.springframework - spring-test - test - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.parent.version} - test - - - org.slf4j - slf4j-log4j12 - test - - - org.apache.commons - commons-compress - - - io.reactivex.rxjava2 - rxjava - test - - - org.xerial.snappy - snappy-java - - - io.projectreactor - reactor-core - test - - - org.apache.dubbo - dubbo-native - ${project.parent.version} - + + 4.0.0 + + org.apache.dubbo + dubbo-rpc + ${revision} + ../pom.xml + + dubbo-rpc-triple + jar + ${project.artifactId} + The triple protocol module + + false + + + + org.apache.dubbo + dubbo-rpc-api + ${project.parent.version} + + + org.apache.dubbo + dubbo-remoting-http12 + ${project.parent.version} + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.parent.version} + test + + + io.netty + netty-codec-http2 + + + com.google.protobuf + protobuf-java + + + org.springframework + spring-test + test + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.parent.version} + test + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.parent.version} + test + + + org.slf4j + slf4j-log4j12 + test + + + org.apache.commons + commons-compress + + + io.reactivex.rxjava2 + rxjava + test + + + org.xerial.snappy + snappy-java + + + io.projectreactor + reactor-core + test + + + org.apache.dubbo + dubbo-native + ${project.parent.version} + - - org.apache.dubbo - dubbo-compiler - ${project.parent.version} - provided - - - - - - kr.motd.maven - os-maven-plugin - ${maven_os_plugin_version} - - - initialize - - detect - - - - - - org.xolstice.maven.plugins - protobuf-maven-plugin - ${maven_protobuf_plugin_version} - - - com.google.protobuf:protoc:${protobuf-protoc_version}:exe:${os.detected.classifier} - - - - dubbo - org.apache.dubbo - dubbo-compiler - ${project.parent.version} - org.apache.dubbo.gen.tri.Dubbo3TripleGenerator - - - - - - - compile - - - - + + org.apache.dubbo + dubbo-compiler + ${project.parent.version} + provided + + + + + + kr.motd.maven + os-maven-plugin + ${maven_os_plugin_version} + + + + detect + + initialize + + + + + org.xolstice.maven.plugins + protobuf-maven-plugin + ${maven_protobuf_plugin_version} + + com.google.protobuf:protoc:${protobuf-protoc_version}:exe:${os.detected.classifier} + + + dubbo + org.apache.dubbo + dubbo-compiler + ${project.parent.version} + org.apache.dubbo.gen.tri.Dubbo3TripleGenerator + + + + + + + compile + + + + - - - org.apache.maven.plugins - maven-javadoc-plugin - - true - - - - + + + org.apache.maven.plugins + maven-javadoc-plugin + + true + + + + diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/StatusRpcException.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/StatusRpcException.java index 0c330f7a39..dca88a772b 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/StatusRpcException.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/StatusRpcException.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc; public class StatusRpcException extends RpcException { @@ -26,8 +25,7 @@ public class StatusRpcException extends RpcException { private final TriRpcStatus status; public StatusRpcException(TriRpcStatus status) { - super(TriRpcStatus.triCodeToDubboCode(status.code), status.toMessageWithoutCause(), - status.cause); + super(TriRpcStatus.triCodeToDubboCode(status.code), status.toMessageWithoutCause(), status.cause); this.status = status; } } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/TriRpcStatus.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/TriRpcStatus.java index 11a250bcaf..abb5db671b 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/TriRpcStatus.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/TriRpcStatus.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc; import org.apache.dubbo.common.utils.StringUtils; @@ -36,7 +35,6 @@ import static org.apache.dubbo.rpc.RpcException.UNKNOWN_EXCEPTION; /** * See https://github.com/grpc/grpc/blob/master/doc/statuscodes.md */ - public class TriRpcStatus { public static final TriRpcStatus OK = fromCode(Code.OK); @@ -169,9 +167,8 @@ public class TriRpcStatus { if (httpStatusCode >= 100 && httpStatusCode < 200) { return Code.INTERNAL; } - if (httpStatusCode == HttpResponseStatus.BAD_REQUEST.code() || - httpStatusCode == HttpResponseStatus.REQUEST_HEADER_FIELDS_TOO_LARGE.code() - ) { + if (httpStatusCode == HttpResponseStatus.BAD_REQUEST.code() + || httpStatusCode == HttpResponseStatus.REQUEST_HEADER_FIELDS_TOO_LARGE.code()) { return Code.INTERNAL; } else if (httpStatusCode == HttpResponseStatus.UNAUTHORIZED.code()) { return Code.UNAUTHENTICATED; @@ -180,9 +177,9 @@ public class TriRpcStatus { } else if (httpStatusCode == HttpResponseStatus.NOT_FOUND.code()) { return Code.UNIMPLEMENTED; } else if (httpStatusCode == HttpResponseStatus.BAD_GATEWAY.code() - || httpStatusCode == HttpResponseStatus.TOO_MANY_REQUESTS.code() - || httpStatusCode == HttpResponseStatus.SERVICE_UNAVAILABLE.code() - || httpStatusCode == HttpResponseStatus.GATEWAY_TIMEOUT.code()) { + || httpStatusCode == HttpResponseStatus.TOO_MANY_REQUESTS.code() + || httpStatusCode == HttpResponseStatus.SERVICE_UNAVAILABLE.code() + || httpStatusCode == HttpResponseStatus.GATEWAY_TIMEOUT.code()) { return Code.UNAVAILABLE; } else { return Code.UNKNOWN; @@ -238,7 +235,6 @@ public class TriRpcStatus { return msg; } - public enum Code { OK(0), CANCELLED(1), @@ -280,5 +276,4 @@ public class TriRpcStatus { throw new IllegalStateException("Can not find status for code: " + code); } } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/CancelableStreamObserver.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/CancelableStreamObserver.java index 76ae697ed4..57ceae43fa 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/CancelableStreamObserver.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/CancelableStreamObserver.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.common.stream.StreamObserver; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClassLoadUtil.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClassLoadUtil.java index 49312c67ec..be2986c413 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClassLoadUtil.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClassLoadUtil.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; public class ClassLoadUtil { diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClientStreamObserver.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClientStreamObserver.java index d20d2f56b1..00f7cb0df2 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClientStreamObserver.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ClientStreamObserver.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; - import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; @@ -32,5 +30,4 @@ public interface ClientStreamObserver extends CallStreamObserver { default void disableAutoRequest() { disableAutoFlowControl(); } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DeadlineFuture.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DeadlineFuture.java index 08160dcd74..aea45b39b3 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DeadlineFuture.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DeadlineFuture.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.common.logger.Logger; @@ -48,8 +47,8 @@ public class DeadlineFuture extends CompletableFuture { private final Timeout timeoutTask; private ExecutorService executor; private static final GlobalResourceInitializer TIME_OUT_TIMER = new GlobalResourceInitializer<>( - () -> new HashedWheelTimer(new NamedThreadFactory("dubbo-future-timeout", true), 30, - TimeUnit.MILLISECONDS), DeadlineFuture::destroy); + () -> new HashedWheelTimer(new NamedThreadFactory("dubbo-future-timeout", true), 30, TimeUnit.MILLISECONDS), + DeadlineFuture::destroy); private DeadlineFuture(String serviceName, String methodName, String address, int timeout) { this.serviceName = serviceName; @@ -57,8 +56,7 @@ public class DeadlineFuture extends CompletableFuture { this.address = address; this.timeout = timeout; TimeoutCheckTask timeoutCheckTask = new TimeoutCheckTask(); - this.timeoutTask = TIME_OUT_TIMER.get() - .newTimeout(timeoutCheckTask, timeout, TimeUnit.MILLISECONDS); + this.timeoutTask = TIME_OUT_TIMER.get().newTimeout(timeoutCheckTask, timeout, TimeUnit.MILLISECONDS); } public static void destroy() { @@ -71,8 +69,8 @@ public class DeadlineFuture extends CompletableFuture { * @param timeout timeout in Mills * @return a new DeadlineFuture */ - public static DeadlineFuture newFuture(String serviceName, String methodName, String address, - int timeout, ExecutorService executor) { + public static DeadlineFuture newFuture( + String serviceName, String methodName, String address, int timeout, ExecutorService executor) { final DeadlineFuture future = new DeadlineFuture(serviceName, methodName, address, timeout); future.setExecutor(executor); return future; @@ -126,17 +124,15 @@ public class DeadlineFuture extends CompletableFuture { // but there are also exceptions in the onResponse in the filter,which is a bit confusing. // We recommend only handling onResponse in which onError is called for handling this.complete(appResponse); - - } private String getTimeoutMessage() { long nowTimestamp = System.currentTimeMillis(); return "Waiting server-side response timeout by scan timer. start time: " - + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(start))) - + ", end time: " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format( - new Date(nowTimestamp))) + ", timeout: " + timeout + " ms, service: " + serviceName - + ", method: " + methodName; + + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(start))) + + ", end time: " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(nowTimestamp))) + + ", timeout: " + timeout + " ms, service: " + serviceName + + ", method: " + methodName; } private class TimeoutCheckTask implements TimerTask { @@ -161,12 +157,10 @@ public class DeadlineFuture extends CompletableFuture { } private void notifyTimeout() { - final TriRpcStatus status = TriRpcStatus.DEADLINE_EXCEEDED.withDescription( - getTimeoutMessage()); + final TriRpcStatus status = TriRpcStatus.DEADLINE_EXCEEDED.withDescription(getTimeoutMessage()); AppResponse timeoutResponse = new AppResponse(); timeoutResponse.setException(status.asException()); DeadlineFuture.this.doReceived(status, timeoutResponse); } } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DefaultPackableMethodFactory.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DefaultPackableMethodFactory.java index 36fb31f736..39b93b4ef3 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DefaultPackableMethodFactory.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/DefaultPackableMethodFactory.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.common.URL; @@ -28,5 +27,4 @@ public class DefaultPackableMethodFactory implements PackableMethodFactory { public PackableMethod create(MethodDescriptor methodDescriptor, URL url, String contentType) { return ReflectionPackableMethod.init(methodDescriptor, url); } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ExceptionUtils.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ExceptionUtils.java index 6f9de11f49..a1fae862b3 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ExceptionUtils.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ExceptionUtils.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.common.utils.CollectionUtils; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GrpcHttp2Protocol.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GrpcHttp2Protocol.java index 1b00e5ff09..ac86307e65 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GrpcHttp2Protocol.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GrpcHttp2Protocol.java @@ -14,11 +14,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.common.extension.Activate; @Activate -public class GrpcHttp2Protocol extends TripleHttp2Protocol { -} +public class GrpcHttp2Protocol extends TripleHttp2Protocol {} diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GrpcProtocol.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GrpcProtocol.java index 38519e4c42..79b447b491 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GrpcProtocol.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/GrpcProtocol.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.rpc.model.FrameworkModel; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Http2ProtocolDetector.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Http2ProtocolDetector.java index b651af696d..dfb9c1a590 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Http2ProtocolDetector.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/Http2ProtocolDetector.java @@ -27,7 +27,7 @@ import static java.lang.Math.min; public class Http2ProtocolDetector implements ProtocolDetector { private final ChannelBuffer clientPrefaceString = new ByteBufferBackedChannelBuffer( - Http2CodecUtil.connectionPrefaceBuf().nioBuffer()); + Http2CodecUtil.connectionPrefaceBuf().nioBuffer()); @Override public Result detect(ChannelBuffer in) { diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/PbArrayPacker.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/PbArrayPacker.java index 9a20d29f40..b91d4b940f 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/PbArrayPacker.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/PbArrayPacker.java @@ -14,12 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; -import com.google.protobuf.Message; import org.apache.dubbo.rpc.model.Pack; +import com.google.protobuf.Message; + public class PbArrayPacker implements Pack { private static final Pack PB_PACK = o -> ((Message) o).toByteArray(); @@ -37,5 +37,4 @@ public class PbArrayPacker implements Pack { } return PB_PACK.pack(obj); } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/PbUnpack.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/PbUnpack.java index f2aaa69dd0..81d12d2420 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/PbUnpack.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/PbUnpack.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.rpc.model.UnPack; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ReflectionPackableMethod.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ReflectionPackableMethod.java index b270bb0fac..d90eba24db 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ReflectionPackableMethod.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ReflectionPackableMethod.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.common.URL; @@ -30,8 +29,6 @@ import org.apache.dubbo.rpc.model.PackableMethod; import org.apache.dubbo.rpc.model.UnPack; import org.apache.dubbo.rpc.model.WrapperUnPack; -import com.google.protobuf.Message; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -40,6 +37,8 @@ import java.util.Collection; import java.util.Iterator; import java.util.stream.Stream; +import com.google.protobuf.Message; + import static org.apache.dubbo.common.constants.CommonConstants.$ECHO; import static org.apache.dubbo.common.constants.CommonConstants.PROTOBUF_MESSAGE_CLASS_NAME; @@ -66,22 +65,26 @@ public class ReflectionPackableMethod implements PackableMethod { return this.needWrapper; } - public ReflectionPackableMethod(MethodDescriptor method, URL url, String serializeName, Collection allSerialize) { + public ReflectionPackableMethod( + MethodDescriptor method, URL url, String serializeName, Collection allSerialize) { Class[] actualRequestTypes; Class actualResponseType; switch (method.getRpcType()) { case CLIENT_STREAM: case BI_STREAM: - actualRequestTypes = new Class[]{ - (Class) ((ParameterizedType) method.getMethod() - .getGenericReturnType()).getActualTypeArguments()[0]}; - actualResponseType = (Class) ((ParameterizedType) method.getMethod() - .getGenericParameterTypes()[0]).getActualTypeArguments()[0]; + actualRequestTypes = new Class[] { + (Class) + ((ParameterizedType) method.getMethod().getGenericReturnType()).getActualTypeArguments()[0] + }; + actualResponseType = + (Class) ((ParameterizedType) method.getMethod().getGenericParameterTypes()[0]) + .getActualTypeArguments()[0]; break; case SERVER_STREAM: actualRequestTypes = method.getMethod().getParameterTypes(); - actualResponseType = (Class) ((ParameterizedType) method.getMethod() - .getGenericParameterTypes()[1]).getActualTypeArguments()[0]; + actualResponseType = + (Class) ((ParameterizedType) method.getMethod().getGenericParameterTypes()[1]) + .getActualTypeArguments()[0]; break; case UNARY: actualRequestTypes = method.getParameterClasses(); @@ -100,13 +103,12 @@ public class ReflectionPackableMethod implements PackableMethod { responseUnpack = new PbUnpack<>(actualResponseType); } else { final MultipleSerialization serialization = url.getOrDefaultFrameworkModel() - .getExtensionLoader(MultipleSerialization.class) - .getExtension(url.getParameter(Constants.MULTI_SERIALIZATION_KEY, - CommonConstants.DEFAULT_KEY)); + .getExtensionLoader(MultipleSerialization.class) + .getExtension(url.getParameter(Constants.MULTI_SERIALIZATION_KEY, CommonConstants.DEFAULT_KEY)); // client - this.requestPack = new WrapRequestPack(serialization, url, serializeName, actualRequestTypes, - singleArgument); + this.requestPack = + new WrapRequestPack(serialization, url, serializeName, actualRequestTypes, singleArgument); this.responseUnpack = new WrapResponseUnpack(serialization, url, allSerialize, actualResponseType); // server @@ -119,13 +121,11 @@ public class ReflectionPackableMethod implements PackableMethod { public static ReflectionPackableMethod init(MethodDescriptor methodDescriptor, URL url) { String serializeName = UrlUtils.serializationOrDefault(url); Collection allSerialize = UrlUtils.allSerializations(url); - return new ReflectionPackableMethod( - methodDescriptor, url, serializeName, allSerialize); + return new ReflectionPackableMethod(methodDescriptor, url, serializeName, allSerialize); } static boolean isStreamType(Class type) { - return StreamObserver.class.isAssignableFrom(type) || GRPC_STREAM_CLASS.equalsIgnoreCase( - type.getName()); + return StreamObserver.class.isAssignableFrom(type) || GRPC_STREAM_CLASS.equalsIgnoreCase(type.getName()); } /** @@ -133,12 +133,11 @@ public class ReflectionPackableMethod implements PackableMethod { * * @return true if the request and response object is not generated by protobuf */ - public static boolean needWrap(MethodDescriptor methodDescriptor, Class[] parameterClasses, - Class returnClass) { + public static boolean needWrap( + MethodDescriptor methodDescriptor, Class[] parameterClasses, Class returnClass) { String methodName = methodDescriptor.getMethodName(); // generic call must be wrapped - if (CommonConstants.$INVOKE.equals(methodName) || CommonConstants.$INVOKE_ASYNC.equals( - methodName)) { + if (CommonConstants.$INVOKE.equals(methodName) || CommonConstants.$INVOKE_ASYNC.equals(methodName)) { return true; } // echo must be wrapped @@ -172,42 +171,39 @@ public class ReflectionPackableMethod implements PackableMethod { } // more than one stream param if (streamParameterCount > 1) { - throw new IllegalStateException( - "method params error: more than one Stream params. method=" + methodName); + throw new IllegalStateException("method params error: more than one Stream params. method=" + methodName); } // protobuf only support one param if (protobufParameterCount >= 2) { - throw new IllegalStateException( - "method params error: more than one protobuf params. method=" + methodName); + throw new IllegalStateException("method params error: more than one protobuf params. method=" + methodName); } // server stream support one normal param and one stream param if (streamParameterCount == 1) { if (javaParameterCount + protobufParameterCount > 1) { throw new IllegalStateException( - "method params error: server stream does not support more than one normal param." - + " method=" + methodName); + "method params error: server stream does not support more than one normal param." + " method=" + + methodName); } // server stream: void foo(Request, StreamObserver) if (!secondParameterStream) { throw new IllegalStateException( - "method params error: server stream's second param must be StreamObserver." - + " method=" + methodName); + "method params error: server stream's second param must be StreamObserver." + " method=" + + methodName); } } if (methodDescriptor.getRpcType() != MethodDescriptor.RpcType.UNARY) { if (MethodDescriptor.RpcType.SERVER_STREAM == methodDescriptor.getRpcType()) { if (!secondParameterStream) { throw new IllegalStateException( - "method params error:server stream's second param must be StreamObserver." - + " method=" + methodName); + "method params error:server stream's second param must be StreamObserver." + " method=" + + methodName); } } // param type must be consistent if (returnClassProtobuf) { if (javaParameterCount > 0) { throw new IllegalStateException( - "method params error: both normal and protobuf param found. method=" - + methodName); + "method params error: both normal and protobuf param found. method=" + methodName); } } else { if (protobufParameterCount > 0) { @@ -217,8 +213,8 @@ public class ReflectionPackableMethod implements PackableMethod { } else { if (streamParameterCount > 0) { throw new IllegalStateException( - "method params error: unary method should not contain any StreamObserver." - + " method=" + methodName); + "method params error: unary method should not contain any StreamObserver." + " method=" + + methodName); } if (protobufParameterCount > 0 && returnClassProtobuf) { return false; @@ -231,14 +227,14 @@ public class ReflectionPackableMethod implements PackableMethod { return true; } // handle grpc stub only consider gen by proto - if (GRPC_ASYNC_RETURN_CLASS.equalsIgnoreCase(returnClass.getName()) - && protobufParameterCount == 1) { + if (GRPC_ASYNC_RETURN_CLASS.equalsIgnoreCase(returnClass.getName()) && protobufParameterCount == 1) { return false; } // handle dubbo generated method if (TRI_ASYNC_RETURN_CLASS.equalsIgnoreCase(returnClass.getName())) { - Class actualReturnClass = (Class) ((ParameterizedType) methodDescriptor.getMethod() - .getGenericReturnType()).getActualTypeArguments()[0]; + Class actualReturnClass = (Class) + ((ParameterizedType) methodDescriptor.getMethod().getGenericReturnType()) + .getActualTypeArguments()[0]; boolean actualReturnClassProtobuf = isProtobufClass(actualReturnClass); if (actualReturnClassProtobuf && protobufParameterCount == 1) { return false; @@ -324,8 +320,11 @@ public class ReflectionPackableMethod implements PackableMethod { // wrapper request set serialize type String requestSerialize; - private WrapResponsePack(MultipleSerialization multipleSerialization, URL url, String defaultSerialize, - Class actualResponseType) { + private WrapResponsePack( + MultipleSerialization multipleSerialization, + URL url, + String defaultSerialize, + Class actualResponseType) { this.multipleSerialization = multipleSerialization; this.url = url; this.actualResponseType = actualResponseType; @@ -337,11 +336,11 @@ public class ReflectionPackableMethod implements PackableMethod { ByteArrayOutputStream bos = new ByteArrayOutputStream(); multipleSerialization.serialize(url, requestSerialize, actualResponseType, obj, bos); return TripleCustomerProtocolWapper.TripleResponseWrapper.Builder.newBuilder() - .setSerializeType(requestSerialize) - .setType(actualResponseType.getName()) - .setData(bos.toByteArray()) - .build() - .toByteArray(); + .setSerializeType(requestSerialize) + .setType(actualResponseType.getName()) + .setData(bos.toByteArray()) + .build() + .toByteArray(); } } @@ -353,8 +352,8 @@ public class ReflectionPackableMethod implements PackableMethod { private final Collection allSerialize; - - private WrapResponseUnpack(MultipleSerialization serialization, URL url, Collection allSerialize, Class returnClass) { + private WrapResponseUnpack( + MultipleSerialization serialization, URL url, Collection allSerialize, Class returnClass) { this.serialization = serialization; this.url = url; this.returnClass = returnClass; @@ -366,10 +365,9 @@ public class ReflectionPackableMethod implements PackableMethod { return unpack(data, false); } - public Object unpack(byte[] data, boolean isReturnTriException) throws IOException, ClassNotFoundException { - TripleCustomerProtocolWapper.TripleResponseWrapper wrapper = TripleCustomerProtocolWapper.TripleResponseWrapper - .parseFrom(data); + TripleCustomerProtocolWapper.TripleResponseWrapper wrapper = + TripleCustomerProtocolWapper.TripleResponseWrapper.parseFrom(data); final String serializeType = convertHessianFromWrapper(wrapper.getSerializeType()); CodecSupport.checkSerialization(serializeType, allSerialize); @@ -391,17 +389,18 @@ public class ReflectionPackableMethod implements PackableMethod { private final URL url; private final boolean singleArgument; - - private WrapRequestPack(MultipleSerialization multipleSerialization, - URL url, - String serialize, - Class[] actualRequestTypes, - boolean singleArgument) { + private WrapRequestPack( + MultipleSerialization multipleSerialization, + URL url, + String serialize, + Class[] actualRequestTypes, + boolean singleArgument) { this.url = url; this.serialize = convertHessianToWrapper(serialize); this.multipleSerialization = multipleSerialization; this.actualRequestTypes = actualRequestTypes; - this.argumentsType = Stream.of(actualRequestTypes).map(Class::getName).toArray(String[]::new); + this.argumentsType = + Stream.of(actualRequestTypes).map(Class::getName).toArray(String[]::new); this.singleArgument = singleArgument; } @@ -409,11 +408,12 @@ public class ReflectionPackableMethod implements PackableMethod { public byte[] pack(Object obj) throws IOException { Object[] arguments; if (singleArgument) { - arguments = new Object[]{obj}; + arguments = new Object[] {obj}; } else { arguments = (Object[]) obj; } - final TripleCustomerProtocolWapper.TripleRequestWrapper.Builder builder = TripleCustomerProtocolWapper.TripleRequestWrapper.Builder.newBuilder(); + final TripleCustomerProtocolWapper.TripleRequestWrapper.Builder builder = + TripleCustomerProtocolWapper.TripleRequestWrapper.Builder.newBuilder(); builder.setSerializeType(serialize); for (String type : argumentsType) { builder.addArgTypes(type); @@ -441,7 +441,6 @@ public class ReflectionPackableMethod implements PackableMethod { } return serializeType; } - } private class WrapRequestUnpack implements WrapperUnPack { @@ -453,8 +452,11 @@ public class ReflectionPackableMethod implements PackableMethod { private final Collection allSerialize; - - private WrapRequestUnpack(MultipleSerialization serialization, URL url, Collection allSerialize, Class[] actualRequestTypes) { + private WrapRequestUnpack( + MultipleSerialization serialization, + URL url, + Collection allSerialize, + Class[] actualRequestTypes) { this.serialization = serialization; this.url = url; this.actualRequestTypes = actualRequestTypes; @@ -462,8 +464,8 @@ public class ReflectionPackableMethod implements PackableMethod { } public Object unpack(byte[] data, boolean isReturnTriException) throws IOException, ClassNotFoundException { - TripleCustomerProtocolWapper.TripleRequestWrapper wrapper = TripleCustomerProtocolWapper.TripleRequestWrapper.parseFrom( - data); + TripleCustomerProtocolWapper.TripleRequestWrapper wrapper = + TripleCustomerProtocolWapper.TripleRequestWrapper.parseFrom(data); String wrapperSerializeType = convertHessianFromWrapper(wrapper.getSerializeType()); CodecSupport.checkSerialization(wrapperSerializeType, allSerialize); @@ -471,11 +473,9 @@ public class ReflectionPackableMethod implements PackableMethod { Object[] ret = new Object[wrapper.getArgs().size()]; ((WrapResponsePack) responsePack).requestSerialize = wrapper.getSerializeType(); for (int i = 0; i < wrapper.getArgs().size(); i++) { - ByteArrayInputStream bais = new ByteArrayInputStream( - wrapper.getArgs().get(i)); - ret[i] = serialization.deserialize(url, wrapper.getSerializeType(), - actualRequestTypes[i], - bais); + ByteArrayInputStream bais = + new ByteArrayInputStream(wrapper.getArgs().get(i)); + ret[i] = serialization.deserialize(url, wrapper.getSerializeType(), actualRequestTypes[i], bais); } return ret; } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/RequestMetadata.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/RequestMetadata.java index e60af175ff..90477e7336 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/RequestMetadata.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/RequestMetadata.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.rpc.CancellationContext; @@ -24,14 +23,14 @@ import org.apache.dubbo.rpc.protocol.tri.compressor.Compressor; import org.apache.dubbo.rpc.protocol.tri.compressor.Identity; import org.apache.dubbo.rpc.protocol.tri.stream.StreamUtils; +import java.util.Map; + import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaderValues; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http2.DefaultHttp2Headers; import io.netty.util.AsciiString; -import java.util.Map; - public class RequestMetadata { public AsciiString scheme; @@ -53,35 +52,29 @@ public class RequestMetadata { public DefaultHttp2Headers toHeaders() { DefaultHttp2Headers header = new DefaultHttp2Headers(false); header.scheme(scheme) - .authority(address) - .method(HttpMethod.POST.asciiName()) - .path("/" + service + "/" + method.getMethodName()) - .set(TripleHeaderEnum.CONTENT_TYPE_KEY.getHeader(), TripleConstant.CONTENT_PROTO) - .set(HttpHeaderNames.TE, HttpHeaderValues.TRAILERS); + .authority(address) + .method(HttpMethod.POST.asciiName()) + .path("/" + service + "/" + method.getMethodName()) + .set(TripleHeaderEnum.CONTENT_TYPE_KEY.getHeader(), TripleConstant.CONTENT_PROTO) + .set(HttpHeaderNames.TE, HttpHeaderValues.TRAILERS); setIfNotNull(header, TripleHeaderEnum.TIMEOUT.getHeader(), timeout); if (!ignoreDefaultVersion || !"1.0.0".equals(version)) { setIfNotNull(header, TripleHeaderEnum.SERVICE_VERSION.getHeader(), version); } setIfNotNull(header, TripleHeaderEnum.SERVICE_GROUP.getHeader(), group); - setIfNotNull(header, TripleHeaderEnum.CONSUMER_APP_NAME_KEY.getHeader(), - application); - setIfNotNull(header, TripleHeaderEnum.GRPC_ACCEPT_ENCODING.getHeader(), - acceptEncoding); + setIfNotNull(header, TripleHeaderEnum.CONSUMER_APP_NAME_KEY.getHeader(), application); + setIfNotNull(header, TripleHeaderEnum.GRPC_ACCEPT_ENCODING.getHeader(), acceptEncoding); if (!Identity.MESSAGE_ENCODING.equals(compressor.getMessageEncoding())) { - setIfNotNull(header, TripleHeaderEnum.GRPC_ENCODING.getHeader(), - compressor.getMessageEncoding()); + setIfNotNull(header, TripleHeaderEnum.GRPC_ENCODING.getHeader(), compressor.getMessageEncoding()); } StreamUtils.convertAttachment(header, attachments, convertNoLowerHeader); return header; } - private void setIfNotNull(DefaultHttp2Headers headers, CharSequence key, - CharSequence value) { + private void setIfNotNull(DefaultHttp2Headers headers, CharSequence key, CharSequence value) { if (value == null) { return; } headers.set(key, value); } - - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ServerStreamObserver.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ServerStreamObserver.java index 9d3a9b2641..f06ecd8408 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ServerStreamObserver.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/ServerStreamObserver.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; @@ -24,5 +23,4 @@ public interface ServerStreamObserver extends CallStreamObserver { default void disableAutoInboundFlowControl() { disableAutoFlowControl(); } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/SingleProtobufUtils.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/SingleProtobufUtils.java index 5f79dad3b7..ec51dacc7a 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/SingleProtobufUtils.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/SingleProtobufUtils.java @@ -14,11 +14,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.InvocationTargetException; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + import com.google.protobuf.BoolValue; import com.google.protobuf.BytesValue; import com.google.protobuf.DoubleValue; @@ -35,17 +41,11 @@ import com.google.protobuf.MessageLite; import com.google.protobuf.Parser; import com.google.protobuf.StringValue; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.reflect.InvocationTargetException; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - public class SingleProtobufUtils { private static final ConcurrentHashMap, Message> INST_CACHE = new ConcurrentHashMap<>(); private static final ExtensionRegistryLite GLOBAL_REGISTRY = ExtensionRegistryLite.getEmptyRegistry(); - private static final ConcurrentMap, SingleMessageMarshaller> MARSHALLER_CACHE = new ConcurrentHashMap<>(); + private static final ConcurrentMap, SingleMessageMarshaller> MARSHALLER_CACHE = + new ConcurrentHashMap<>(); static { // Built-in types need to be registered in advance @@ -93,11 +93,10 @@ public class SingleProtobufUtils { return (Parser) defaultInst.getParserForType(); } - public static T deserialize(InputStream in, Class clz) throws IOException { if (!isSupported(clz)) { - throw new IllegalArgumentException("This serialization only support google protobuf messages, but the " + - "actual input type is :" + clz.getName()); + throw new IllegalArgumentException("This serialization only support google protobuf messages, but the " + + "actual input type is :" + clz.getName()); } try { return (T) getMarshaller(clz).parse(in); @@ -133,5 +132,4 @@ public class SingleProtobufUtils { return parser.parseFrom(stream, GLOBAL_REGISTRY); } } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleConstant.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleConstant.java index 77c4998d5e..6ca934255f 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleConstant.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleConstant.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import io.netty.util.AsciiString; @@ -36,6 +35,4 @@ public class TripleConstant { public static final AsciiString HTTPS_SCHEME = AsciiString.of("https"); public static final AsciiString HTTP_SCHEME = AsciiString.of("http"); - - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleCustomerProtocolWapper.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleCustomerProtocolWapper.java index e9479375f3..ace359c3de 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleCustomerProtocolWapper.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleCustomerProtocolWapper.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.common.utils.Assert; @@ -54,7 +53,6 @@ public class TripleCustomerProtocolWapper { return length; } - public static int readRawVarint32(ByteBuffer byteBuffer) { int val = 0; int currentPosition = byteBuffer.position(); @@ -140,39 +138,32 @@ public class TripleCustomerProtocolWapper { byte[] serializeTypeBytes = serializeType.getBytes(StandardCharsets.UTF_8); byte[] serializeTypeLengthVarIntEncodeBytes = varIntEncode(serializeTypeBytes.length); totalSize += serializeTypeTagBytes.length - + serializeTypeLengthVarIntEncodeBytes.length - + serializeTypeBytes.length; + + serializeTypeLengthVarIntEncodeBytes.length + + serializeTypeBytes.length; int dataTag = makeTag(2, 2); if (data != null) { - totalSize += varIntComputeLength(dataTag) - + varIntComputeLength(data.length) - + data.length; + totalSize += varIntComputeLength(dataTag) + varIntComputeLength(data.length) + data.length; } int typeTag = makeTag(3, 2); byte[] typeTagBytes = varIntEncode(typeTag); byte[] typeBytes = type.getBytes(StandardCharsets.UTF_8); byte[] typeLengthVarIntEncodeBytes = varIntEncode(typeBytes.length); - totalSize += typeTagBytes.length - + typeLengthVarIntEncodeBytes.length - + typeBytes.length; + totalSize += typeTagBytes.length + typeLengthVarIntEncodeBytes.length + typeBytes.length; ByteBuffer byteBuffer = ByteBuffer.allocate(totalSize); byteBuffer - .put(serializeTypeTagBytes) - .put(serializeTypeLengthVarIntEncodeBytes) - .put(serializeTypeBytes); + .put(serializeTypeTagBytes) + .put(serializeTypeLengthVarIntEncodeBytes) + .put(serializeTypeBytes); if (data != null) { byteBuffer - .put(varIntEncode(dataTag)) - .put(varIntEncode(data.length)) - .put(data); + .put(varIntEncode(dataTag)) + .put(varIntEncode(data.length)) + .put(data); } - byteBuffer - .put(typeTagBytes) - .put(typeLengthVarIntEncodeBytes) - .put(typeBytes); + byteBuffer.put(typeTagBytes).put(typeLengthVarIntEncodeBytes).put(typeBytes); return byteBuffer.array(); } @@ -214,7 +205,6 @@ public class TripleCustomerProtocolWapper { } } - public static final class TripleRequestWrapper { private String serializeType; @@ -235,8 +225,7 @@ public class TripleCustomerProtocolWapper { return argTypes; } - public TripleRequestWrapper() { - } + public TripleRequestWrapper() {} public static TripleRequestWrapper parseFrom(byte[] data) { TripleRequestWrapper tripleRequestWrapper = new TripleRequestWrapper(); @@ -280,8 +269,8 @@ public class TripleCustomerProtocolWapper { byte[] serializeTypeBytes = serializeType.getBytes(StandardCharsets.UTF_8); byte[] serializeTypeLengthVarIntEncodeBytes = varIntEncode(serializeTypeBytes.length); totalSize += serializeTypeTagBytes.length - + serializeTypeLengthVarIntEncodeBytes.length - + serializeTypeBytes.length; + + serializeTypeLengthVarIntEncodeBytes.length + + serializeTypeBytes.length; int argTypeTag = makeTag(3, 2); if (CollectionUtils.isNotEmpty(argTypes)) { @@ -302,17 +291,14 @@ public class TripleCustomerProtocolWapper { ByteBuffer byteBuffer = ByteBuffer.allocate(totalSize); byteBuffer - .put(serializeTypeTagBytes) - .put(serializeTypeLengthVarIntEncodeBytes) - .put(serializeTypeBytes); + .put(serializeTypeTagBytes) + .put(serializeTypeLengthVarIntEncodeBytes) + .put(serializeTypeBytes); if (CollectionUtils.isNotEmpty(args)) { byte[] argTagBytes = varIntEncode(argTag); for (byte[] arg : args) { - byteBuffer - .put(argTagBytes) - .put(varIntEncode(arg.length)) - .put(arg); + byteBuffer.put(argTagBytes).put(varIntEncode(arg.length)).put(arg); } } @@ -321,15 +307,14 @@ public class TripleCustomerProtocolWapper { for (String argType : argTypes) { byte[] argTypeBytes = argType.getBytes(StandardCharsets.UTF_8); byteBuffer - .put(argTypeTagBytes) - .put(varIntEncode(argTypeBytes.length)) - .put(argTypeBytes); + .put(argTypeTagBytes) + .put(varIntEncode(argTypeBytes.length)) + .put(argTypeBytes); } } return byteBuffer.array(); } - public static final class Builder { private String serializeType; @@ -378,8 +363,8 @@ public class TripleCustomerProtocolWapper { } TripleRequestWrapper that = (TripleRequestWrapper) o; return Objects.equals(serializeType, that.serializeType) - && Objects.equals(args, that.args) - && Objects.equals(argTypes, that.argTypes); + && Objects.equals(args, that.args) + && Objects.equals(argTypes, that.argTypes); } @Override diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHeaderEnum.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHeaderEnum.java index 7fd92f125c..db1018e2d5 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHeaderEnum.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHeaderEnum.java @@ -14,20 +14,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.common.constants.CommonConstants; -import io.netty.handler.codec.http2.Http2Headers; - import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; -public enum TripleHeaderEnum { +import io.netty.handler.codec.http2.Http2Headers; +public enum TripleHeaderEnum { AUTHORITY_KEY(":authority"), PATH_KEY(":path"), HTTP_STATUS_KEY("http-status"), @@ -47,7 +45,6 @@ public enum TripleHeaderEnum { TRI_HEADER_CONVERT("tri-header-convert"), TRI_EXCEPTION_CODE("tri-exception-code"), - ; static final Map enumMap = new HashMap<>(); @@ -69,7 +66,6 @@ public enum TripleHeaderEnum { for (Http2Headers.PseudoHeaderName value : Http2Headers.PseudoHeaderName.values()) { excludeAttachmentsSet.add(value.value().toString()); } - } private final String header; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2FrameCodecBuilder.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2FrameCodecBuilder.java index 217b8c1496..17676fccc4 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2FrameCodecBuilder.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2FrameCodecBuilder.java @@ -14,18 +14,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; +import org.apache.dubbo.common.utils.Assert; + +import java.util.function.Consumer; + import io.netty.handler.codec.http2.DefaultHttp2Connection; import io.netty.handler.codec.http2.Http2CodecUtil; import io.netty.handler.codec.http2.Http2Connection; import io.netty.handler.codec.http2.Http2FrameCodecBuilder; import io.netty.handler.codec.http2.Http2LocalFlowController; import io.netty.handler.codec.http2.Http2RemoteFlowController; -import org.apache.dubbo.common.utils.Assert; - -import java.util.function.Consumer; public class TripleHttp2FrameCodecBuilder extends Http2FrameCodecBuilder { diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2Protocol.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2Protocol.java index 827e1d7b7d..215a2e3aaf 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2Protocol.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHttp2Protocol.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.common.URL; @@ -43,6 +42,10 @@ import org.apache.dubbo.rpc.protocol.tri.transport.TripleGoAwayHandler; import org.apache.dubbo.rpc.protocol.tri.transport.TripleServerConnectionHandler; import org.apache.dubbo.rpc.protocol.tri.transport.TripleTailHandler; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; @@ -57,10 +60,6 @@ import io.netty.handler.codec.http2.Http2StreamChannel; import io.netty.handler.flush.FlushConsolidationHandler; import io.netty.handler.logging.LogLevel; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - import static org.apache.dubbo.common.constants.CommonConstants.HEADER_FILTER_KEY; import static org.apache.dubbo.rpc.Constants.H2_SETTINGS_ENABLE_PUSH_KEY; import static org.apache.dubbo.rpc.Constants.H2_SETTINGS_HEADER_TABLE_SIZE_KEY; @@ -107,20 +106,19 @@ public class TripleHttp2Protocol extends AbstractWireProtocol implements ScopeMo public void configClientPipeline(URL url, ChannelOperator operator, ContextOperator contextOperator) { Configuration config = ConfigurationUtils.getGlobalConfiguration(url.getOrDefaultApplicationModel()); final Http2FrameCodec codec = Http2FrameCodecBuilder.forClient() - .gracefulShutdownTimeoutMillis(10000) - .initialSettings(new Http2Settings().headerTableSize( - config.getInt(H2_SETTINGS_HEADER_TABLE_SIZE_KEY, DEFAULT_SETTING_HEADER_LIST_SIZE)) - .pushEnabled(config.getBoolean(H2_SETTINGS_ENABLE_PUSH_KEY, false)) - .maxConcurrentStreams( - config.getInt(H2_SETTINGS_MAX_CONCURRENT_STREAMS_KEY, Integer.MAX_VALUE)) - .initialWindowSize( - config.getInt(H2_SETTINGS_INITIAL_WINDOW_SIZE_KEY, DEFAULT_WINDOW_INIT_SIZE)) - .maxFrameSize(config.getInt(H2_SETTINGS_MAX_FRAME_SIZE_KEY, DEFAULT_MAX_FRAME_SIZE)) - .maxHeaderListSize(config.getInt(H2_SETTINGS_MAX_HEADER_LIST_SIZE_KEY, - DEFAULT_MAX_HEADER_LIST_SIZE))) - .frameLogger(CLIENT_LOGGER) - .build(); -// codec.connection().local().flowController().frameWriter(codec.encoder().frameWriter()); + .gracefulShutdownTimeoutMillis(10000) + .initialSettings(new Http2Settings() + .headerTableSize( + config.getInt(H2_SETTINGS_HEADER_TABLE_SIZE_KEY, DEFAULT_SETTING_HEADER_LIST_SIZE)) + .pushEnabled(config.getBoolean(H2_SETTINGS_ENABLE_PUSH_KEY, false)) + .maxConcurrentStreams(config.getInt(H2_SETTINGS_MAX_CONCURRENT_STREAMS_KEY, Integer.MAX_VALUE)) + .initialWindowSize(config.getInt(H2_SETTINGS_INITIAL_WINDOW_SIZE_KEY, DEFAULT_WINDOW_INIT_SIZE)) + .maxFrameSize(config.getInt(H2_SETTINGS_MAX_FRAME_SIZE_KEY, DEFAULT_MAX_FRAME_SIZE)) + .maxHeaderListSize( + config.getInt(H2_SETTINGS_MAX_HEADER_LIST_SIZE_KEY, DEFAULT_MAX_HEADER_LIST_SIZE))) + .frameLogger(CLIENT_LOGGER) + .build(); + // codec.connection().local().flowController().frameWriter(codec.encoder().frameWriter()); List handlers = new ArrayList<>(); handlers.add(new ChannelHandlerPretender(codec)); handlers.add(new ChannelHandlerPretender(new Http2MultiplexHandler(new ChannelDuplexHandler()))); @@ -135,13 +133,13 @@ public class TripleHttp2Protocol extends AbstractWireProtocol implements ScopeMo String httpVersion = operator.detectResult().getAttribute(TripleProtocolDetector.HTTP_VERSION); List channelHandlerPretenders = new ArrayList<>(); try { - //h1 + // h1 if (TripleProtocolDetector.HttpVersion.HTTP1.getVersion().equals(httpVersion)) { configurerHttp1Handlers(url, channelHandlerPretenders); return; } - //h2 + // h2 if (TripleProtocolDetector.HttpVersion.HTTP2.getVersion().equals(httpVersion)) { configurerHttp2Handlers(url, channelHandlerPretenders); } @@ -154,7 +152,8 @@ public class TripleHttp2Protocol extends AbstractWireProtocol implements ScopeMo handlers.add(new ChannelHandlerPretender(new HttpServerCodec())); handlers.add(new ChannelHandlerPretender(new HttpObjectAggregator(Integer.MAX_VALUE))); handlers.add(new ChannelHandlerPretender(new NettyHttp1Codec())); - handlers.add(new ChannelHandlerPretender(new NettyHttp1ConnectionHandler(url, frameworkModel, DefaultHttp11ServerTransportListenerFactory.INSTANCE))); + handlers.add(new ChannelHandlerPretender(new NettyHttp1ConnectionHandler( + url, frameworkModel, DefaultHttp11ServerTransportListenerFactory.INSTANCE))); } private void configurerHttp2Handlers(URL url, List handlers) { @@ -166,28 +165,30 @@ public class TripleHttp2Protocol extends AbstractWireProtocol implements ScopeMo headFilters = Collections.emptyList(); } final Http2FrameCodec codec = TripleHttp2FrameCodecBuilder.forServer() - .customizeConnection((connection) -> connection.remote().flowController(new TriHttp2RemoteFlowController(connection, url.getOrDefaultApplicationModel()))) - .gracefulShutdownTimeoutMillis(10000) - .initialSettings(new Http2Settings().headerTableSize( - config.getInt(H2_SETTINGS_HEADER_TABLE_SIZE_KEY, DEFAULT_SETTING_HEADER_LIST_SIZE)) - .maxConcurrentStreams( - config.getInt(H2_SETTINGS_MAX_CONCURRENT_STREAMS_KEY, Integer.MAX_VALUE)) - .initialWindowSize( - config.getInt(H2_SETTINGS_INITIAL_WINDOW_SIZE_KEY, DEFAULT_WINDOW_INIT_SIZE)) - .maxFrameSize(config.getInt(H2_SETTINGS_MAX_FRAME_SIZE_KEY, DEFAULT_MAX_FRAME_SIZE)) - .maxHeaderListSize(config.getInt(H2_SETTINGS_MAX_HEADER_LIST_SIZE_KEY, - DEFAULT_MAX_HEADER_LIST_SIZE))) - .frameLogger(SERVER_LOGGER) - .build(); - final Http2MultiplexHandler handler = new Http2MultiplexHandler( - new ChannelInitializer() { - @Override - protected void initChannel(Http2StreamChannel ch) { - final ChannelPipeline p = ch.pipeline(); - p.addLast(new NettyHttp2FrameCodec()); - p.addLast(new NettyHttp2ProtocolSelectorHandler(url, frameworkModel, GenericHttp2ServerTransportListenerFactory.INSTANCE)); - } - }); + .customizeConnection((connection) -> connection + .remote() + .flowController( + new TriHttp2RemoteFlowController(connection, url.getOrDefaultApplicationModel()))) + .gracefulShutdownTimeoutMillis(10000) + .initialSettings(new Http2Settings() + .headerTableSize( + config.getInt(H2_SETTINGS_HEADER_TABLE_SIZE_KEY, DEFAULT_SETTING_HEADER_LIST_SIZE)) + .maxConcurrentStreams(config.getInt(H2_SETTINGS_MAX_CONCURRENT_STREAMS_KEY, Integer.MAX_VALUE)) + .initialWindowSize(config.getInt(H2_SETTINGS_INITIAL_WINDOW_SIZE_KEY, DEFAULT_WINDOW_INIT_SIZE)) + .maxFrameSize(config.getInt(H2_SETTINGS_MAX_FRAME_SIZE_KEY, DEFAULT_MAX_FRAME_SIZE)) + .maxHeaderListSize( + config.getInt(H2_SETTINGS_MAX_HEADER_LIST_SIZE_KEY, DEFAULT_MAX_HEADER_LIST_SIZE))) + .frameLogger(SERVER_LOGGER) + .build(); + final Http2MultiplexHandler handler = new Http2MultiplexHandler(new ChannelInitializer() { + @Override + protected void initChannel(Http2StreamChannel ch) { + final ChannelPipeline p = ch.pipeline(); + p.addLast(new NettyHttp2FrameCodec()); + p.addLast(new NettyHttp2ProtocolSelectorHandler( + url, frameworkModel, GenericHttp2ServerTransportListenerFactory.INSTANCE)); + } + }); handlers.add(new ChannelHandlerPretender(new HttpWriteQueueHandler())); handlers.add(new ChannelHandlerPretender(codec)); handlers.add(new ChannelHandlerPretender(new FlushConsolidationHandler(64, true))); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleInvoker.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleInvoker.java index 7903cf00db..76b26247cb 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleInvoker.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleInvoker.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.common.URL; @@ -59,8 +58,6 @@ import org.apache.dubbo.rpc.protocol.tri.transport.TripleWriteQueue; import org.apache.dubbo.rpc.service.ServiceDescriptorInternalCache; import org.apache.dubbo.rpc.support.RpcUtils; -import io.netty.util.AsciiString; - import java.util.Arrays; import java.util.Map; import java.util.Objects; @@ -70,6 +67,8 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.locks.ReentrantLock; +import io.netty.util.AsciiString; + import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PACKABLE_METHOD_FACTORY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; @@ -95,23 +94,27 @@ public class TripleInvoker extends AbstractInvoker { private final String acceptEncodings; private final TripleWriteQueue writeQueue = new TripleWriteQueue(256); - private static final boolean setFutureWhenSync = Boolean.parseBoolean(System.getProperty(CommonConstants.SET_FUTURE_IN_SYNC_MODE, "true")); + private static final boolean setFutureWhenSync = + Boolean.parseBoolean(System.getProperty(CommonConstants.SET_FUTURE_IN_SYNC_MODE, "true")); private final PackableMethodFactory packableMethodFactory; private final Map packableMethodCache = new ConcurrentHashMap<>(); - public TripleInvoker(Class serviceType, - URL url, - String acceptEncodings, - AbstractConnectionClient connectionClient, - Set> invokers, - ExecutorService streamExecutor) { - super(serviceType, url, new String[]{INTERFACE_KEY, GROUP_KEY, TOKEN_KEY}); + public TripleInvoker( + Class serviceType, + URL url, + String acceptEncodings, + AbstractConnectionClient connectionClient, + Set> invokers, + ExecutorService streamExecutor) { + super(serviceType, url, new String[] {INTERFACE_KEY, GROUP_KEY, TOKEN_KEY}); this.invokers = invokers; this.connectionClient = connectionClient; this.acceptEncodings = acceptEncodings; this.streamExecutor = streamExecutor; - this.packableMethodFactory = url.getOrDefaultFrameworkModel().getExtensionLoader(PackableMethodFactory.class) - .getExtension(ConfigurationUtils.getGlobalConfiguration(url.getApplicationModel()).getString(DUBBO_PACKABLE_METHOD_FACTORY, DEFAULT_KEY)); + this.packableMethodFactory = url.getOrDefaultFrameworkModel() + .getExtensionLoader(PackableMethodFactory.class) + .getExtension(ConfigurationUtils.getGlobalConfiguration(url.getApplicationModel()) + .getString(DUBBO_PACKABLE_METHOD_FACTORY, DEFAULT_KEY)); } private static AsciiString getSchemeFromUrl(URL url) { @@ -122,33 +125,37 @@ public class TripleInvoker extends AbstractInvoker { private static Compressor getCompressorFromEnv() { Configuration configuration = ConfigurationUtils.getEnvConfiguration(ApplicationModel.defaultModel()); String compressorKey = configuration.getString(COMPRESSOR_KEY, Identity.MESSAGE_ENCODING); - return Compressor.getCompressor(ScopeModelUtil.getFrameworkModel(ApplicationModel.defaultModel()), compressorKey); + return Compressor.getCompressor( + ScopeModelUtil.getFrameworkModel(ApplicationModel.defaultModel()), compressorKey); } @Override protected Result doInvoke(final Invocation invocation) { if (!connectionClient.isConnected()) { CompletableFuture future = new CompletableFuture<>(); - RpcException exception = TriRpcStatus.UNAVAILABLE.withDescription( - String.format("upstream %s is unavailable", getUrl().getAddress())) - .asException(); + RpcException exception = TriRpcStatus.UNAVAILABLE + .withDescription(String.format("upstream %s is unavailable", getUrl().getAddress())) + .asException(); future.completeExceptionally(exception); return new AsyncRpcResult(future, invocation); } - ConsumerModel consumerModel = (ConsumerModel) (invocation.getServiceModel() != null - ? invocation.getServiceModel() : getUrl().getServiceModel()); + ConsumerModel consumerModel = (ConsumerModel) + (invocation.getServiceModel() != null ? invocation.getServiceModel() : getUrl().getServiceModel()); ServiceDescriptor serviceDescriptor = consumerModel.getServiceModel(); final MethodDescriptor methodDescriptor; - boolean genericCall = RpcUtils.isGenericCall(ReflectUtils.getDesc(invocation.getParameterTypes()), invocation.getMethodName()); + boolean genericCall = RpcUtils.isGenericCall( + ReflectUtils.getDesc(invocation.getParameterTypes()), invocation.getMethodName()); if (!genericCall) { methodDescriptor = serviceDescriptor.getMethod(invocation.getMethodName(), invocation.getParameterTypes()); } else { - methodDescriptor = ServiceDescriptorInternalCache.genericService().getMethod(invocation.getMethodName(), invocation.getParameterTypes()); + methodDescriptor = ServiceDescriptorInternalCache.genericService() + .getMethod(invocation.getMethodName(), invocation.getParameterTypes()); } - ExecutorService callbackExecutor = isSync(methodDescriptor, invocation) ? new ThreadlessExecutor() : streamExecutor; - ClientCall call = new TripleClientCall(connectionClient, callbackExecutor, - getUrl().getOrDefaultFrameworkModel(), writeQueue); + ExecutorService callbackExecutor = + isSync(methodDescriptor, invocation) ? new ThreadlessExecutor() : streamExecutor; + ClientCall call = new TripleClientCall( + connectionClient, callbackExecutor, getUrl().getOrDefaultFrameworkModel(), writeQueue); AsyncRpcResult result; try { switch (methodDescriptor.getRpcType()) { @@ -167,8 +174,8 @@ public class TripleInvoker extends AbstractInvoker { } return result; } catch (Throwable t) { - final TriRpcStatus status = TriRpcStatus.INTERNAL.withCause(t) - .withDescription("Call aborted cause client exception"); + final TriRpcStatus status = + TriRpcStatus.INTERNAL.withCause(t).withDescription("Call aborted cause client exception"); RpcException e = status.asException(); try { call.cancelByLocal(e); @@ -187,40 +194,37 @@ public class TripleInvoker extends AbstractInvoker { } RpcInvocation rpcInvocation = (RpcInvocation) invocation; MethodDescriptor.RpcType rpcType = methodDescriptor.getRpcType(); - return UNARY.equals(rpcType) - && InvokeMode.SYNC.equals(rpcInvocation.getInvokeMode()); + return UNARY.equals(rpcType) && InvokeMode.SYNC.equals(rpcInvocation.getInvokeMode()); } - AsyncRpcResult invokeServerStream(MethodDescriptor methodDescriptor, Invocation invocation, - ClientCall call) { + AsyncRpcResult invokeServerStream(MethodDescriptor methodDescriptor, Invocation invocation, ClientCall call) { RequestMetadata request = createRequest(methodDescriptor, invocation, null); - StreamObserver responseObserver = (StreamObserver) invocation.getArguments()[1]; + StreamObserver responseObserver = + (StreamObserver) invocation.getArguments()[1]; final StreamObserver requestObserver = streamCall(call, request, responseObserver); requestObserver.onNext(invocation.getArguments()[0]); requestObserver.onCompleted(); return new AsyncRpcResult(CompletableFuture.completedFuture(new AppResponse()), invocation); } - AsyncRpcResult invokeBiOrClientStream(MethodDescriptor methodDescriptor, Invocation invocation, - ClientCall call) { + AsyncRpcResult invokeBiOrClientStream(MethodDescriptor methodDescriptor, Invocation invocation, ClientCall call) { final AsyncRpcResult result; RequestMetadata request = createRequest(methodDescriptor, invocation, null); - StreamObserver responseObserver = (StreamObserver) invocation.getArguments()[0]; + StreamObserver responseObserver = + (StreamObserver) invocation.getArguments()[0]; final StreamObserver requestObserver = streamCall(call, request, responseObserver); - result = new AsyncRpcResult( - CompletableFuture.completedFuture(new AppResponse(requestObserver)), invocation); + result = new AsyncRpcResult(CompletableFuture.completedFuture(new AppResponse(requestObserver)), invocation); return result; } - StreamObserver streamCall(ClientCall call, - RequestMetadata metadata, - StreamObserver responseObserver) { - ObserverToClientCallListenerAdapter listener = new ObserverToClientCallListenerAdapter( - responseObserver); + StreamObserver streamCall( + ClientCall call, RequestMetadata metadata, StreamObserver responseObserver) { + ObserverToClientCallListenerAdapter listener = new ObserverToClientCallListenerAdapter(responseObserver); StreamObserver streamObserver = call.start(metadata, listener); if (responseObserver instanceof CancelableStreamObserver) { final CancellationContext context = new CancellationContext(); - CancelableStreamObserver cancelableStreamObserver = (CancelableStreamObserver) responseObserver; + CancelableStreamObserver cancelableStreamObserver = + (CancelableStreamObserver) responseObserver; cancelableStreamObserver.setCancellationContext(context); context.addListener(context1 -> call.cancelByLocal(new IllegalStateException("Canceled by app"))); listener.setOnStartConsumer(dummy -> cancelableStreamObserver.startRequest()); @@ -229,20 +233,26 @@ public class TripleInvoker extends AbstractInvoker { return streamObserver; } - AsyncRpcResult invokeUnary(MethodDescriptor methodDescriptor, Invocation invocation, - ClientCall call, ExecutorService callbackExecutor) { + AsyncRpcResult invokeUnary( + MethodDescriptor methodDescriptor, + Invocation invocation, + ClientCall call, + ExecutorService callbackExecutor) { int timeout = RpcUtils.calculateTimeout(getUrl(), invocation, RpcUtils.getMethodName(invocation), 3000); if (timeout <= 0) { - return AsyncRpcResult.newDefaultAsyncResult(new RpcException(RpcException.TIMEOUT_TERMINATE, - "No time left for making the following call: " + invocation.getServiceName() + "." - + RpcUtils.getMethodName(invocation) + ", terminate directly."), invocation); + return AsyncRpcResult.newDefaultAsyncResult( + new RpcException( + RpcException.TIMEOUT_TERMINATE, + "No time left for making the following call: " + invocation.getServiceName() + "." + + RpcUtils.getMethodName(invocation) + ", terminate directly."), + invocation); } invocation.setAttachment(TIMEOUT_KEY, String.valueOf(timeout)); final AsyncRpcResult result; - DeadlineFuture future = DeadlineFuture.newFuture(getUrl().getPath(), - methodDescriptor.getMethodName(), getUrl().getAddress(), timeout, callbackExecutor); + DeadlineFuture future = DeadlineFuture.newFuture( + getUrl().getPath(), methodDescriptor.getMethodName(), getUrl().getAddress(), timeout, callbackExecutor); RequestMetadata request = createRequest(methodDescriptor, invocation, timeout); @@ -254,7 +264,9 @@ public class TripleInvoker extends AbstractInvoker { if (methodDescriptor.isGeneric()) { Object[] args = new Object[3]; args[0] = RpcUtils.getMethodName(invocation); - args[1] = Arrays.stream(RpcUtils.getParameterTypes(invocation)).map(Class::getName).toArray(String[]::new); + args[1] = Arrays.stream(RpcUtils.getParameterTypes(invocation)) + .map(Class::getName) + .toArray(String[]::new); args[2] = RpcUtils.getArguments(invocation); pureArgument = args; } else { @@ -275,19 +287,19 @@ public class TripleInvoker extends AbstractInvoker { return result; } - RequestMetadata createRequest(MethodDescriptor methodDescriptor, Invocation invocation, - Integer timeout) { + RequestMetadata createRequest(MethodDescriptor methodDescriptor, Invocation invocation, Integer timeout) { final String methodName = RpcUtils.getMethodName(invocation); - Objects.requireNonNull(methodDescriptor, - "MethodDescriptor not found for" + methodName + " params:" + Arrays.toString( - invocation.getCompatibleParamSignatures())); + Objects.requireNonNull( + methodDescriptor, + "MethodDescriptor not found for" + methodName + " params:" + + Arrays.toString(invocation.getCompatibleParamSignatures())); final RequestMetadata meta = new RequestMetadata(); final URL url = getUrl(); if (methodDescriptor instanceof PackableMethod) { meta.packableMethod = (PackableMethod) methodDescriptor; } else { - meta.packableMethod = packableMethodCache.computeIfAbsent(methodDescriptor, - (md) -> packableMethodFactory.create(md, url, TripleConstant.CONTENT_PROTO)); + meta.packableMethod = packableMethodCache.computeIfAbsent( + methodDescriptor, (md) -> packableMethodFactory.create(md, url, TripleConstant.CONTENT_PROTO)); } meta.convertNoLowerHeader = TripleProtocol.CONVERT_NO_LOWER_HEADER; meta.ignoreDefaultVersion = TripleProtocol.IGNORE_1_0_0_VERSION; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TriplePathResolver.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TriplePathResolver.java index f3f9ebbc68..be291bd865 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TriplePathResolver.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TriplePathResolver.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.rpc.Invoker; @@ -61,5 +60,4 @@ public class TriplePathResolver implements PathResolver { public void destroy() { path2Invoker.clear(); } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TriplePingPongHandler.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TriplePingPongHandler.java index cffb6ba10e..b2134f330f 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TriplePingPongHandler.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TriplePingPongHandler.java @@ -16,15 +16,15 @@ */ package org.apache.dubbo.rpc.protocol.tri; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http2.DefaultHttp2PingFrame; import io.netty.handler.codec.http2.Http2PingFrame; import io.netty.handler.timeout.IdleStateEvent; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - public class TriplePingPongHandler extends ChannelDuplexHandler { private final long pingAckTimeout; @@ -41,7 +41,7 @@ public class TriplePingPongHandler extends ChannelDuplexHandler { super.channelRead(ctx, msg); return; } - //cancel task when read anything, include http2 ping ack + // cancel task when read anything, include http2 ping ack pingAckTimeoutFuture.cancel(true); pingAckTimeoutFuture = null; } @@ -54,9 +54,10 @@ public class TriplePingPongHandler extends ChannelDuplexHandler { } ctx.writeAndFlush(new DefaultHttp2PingFrame(0)); if (pingAckTimeoutFuture == null) { - pingAckTimeoutFuture = ctx.executor().schedule(new CloseChannelTask(ctx), pingAckTimeout, TimeUnit.MILLISECONDS); + pingAckTimeoutFuture = + ctx.executor().schedule(new CloseChannelTask(ctx), pingAckTimeout, TimeUnit.MILLISECONDS); } - //not null means last ping ack not received + // not null means last ping ack not received } private static class CloseChannelTask implements Runnable { @@ -72,5 +73,4 @@ public class TriplePingPongHandler extends ChannelDuplexHandler { ctx.close(); } } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleProtocol.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleProtocol.java index f28d16287b..f5d0223467 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleProtocol.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleProtocol.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.common.URL; @@ -37,13 +36,13 @@ import org.apache.dubbo.rpc.protocol.AbstractProtocol; import org.apache.dubbo.rpc.protocol.tri.compressor.DeCompressor; import org.apache.dubbo.rpc.protocol.tri.service.TriBuiltinService; -import io.grpc.health.v1.HealthCheckResponse; -import io.grpc.health.v1.HealthCheckResponse.ServingStatus; - import java.util.Objects; import java.util.Set; import java.util.concurrent.ExecutorService; +import io.grpc.health.v1.HealthCheckResponse; +import io.grpc.health.v1.HealthCheckResponse.ServingStatus; + import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_CLIENT_THREADPOOL; import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY; @@ -72,16 +71,16 @@ public class TripleProtocol extends AbstractProtocol { public TripleProtocol(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; this.triBuiltinService = new TriBuiltinService(frameworkModel); - this.pathResolver = frameworkModel.getExtensionLoader(PathResolver.class) - .getDefaultExtension(); + this.pathResolver = + frameworkModel.getExtensionLoader(PathResolver.class).getDefaultExtension(); CONVERT_NO_LOWER_HEADER = ConfigurationUtils.getEnvConfiguration(ApplicationModel.defaultModel()) - .getBoolean(H2_SUPPORT_NO_LOWER_HEADER_KEY, true); + .getBoolean(H2_SUPPORT_NO_LOWER_HEADER_KEY, true); IGNORE_1_0_0_VERSION = ConfigurationUtils.getEnvConfiguration(ApplicationModel.defaultModel()) - .getBoolean(H2_IGNORE_1_0_0_KEY, false); + .getBoolean(H2_IGNORE_1_0_0_KEY, false); RESOLVE_FALLBACK_TO_DEFAULT = ConfigurationUtils.getEnvConfiguration(ApplicationModel.defaultModel()) - .getBoolean(H2_RESOLVE_FALLBACK_TO_DEFAULT_KEY, true); - Set supported = frameworkModel.getExtensionLoader(DeCompressor.class) - .getSupportedExtensions(); + .getBoolean(H2_RESOLVE_FALLBACK_TO_DEFAULT_KEY, true); + Set supported = + frameworkModel.getExtensionLoader(DeCompressor.class).getSupportedExtensions(); this.acceptEncodings = String.join(",", supported); } @@ -90,7 +89,6 @@ public class TripleProtocol extends AbstractProtocol { return 50051; } - @Override public Exporter export(Invoker invoker) throws RpcException { URL url = invoker.getUrl(); @@ -102,10 +100,12 @@ public class TripleProtocol extends AbstractProtocol { pathResolver.remove(url.getServiceModel().getServiceModel().getInterfaceName()); // set service status if (triBuiltinService.enable()) { - triBuiltinService.getHealthStatusManager() - .setStatus(url.getServiceKey(), ServingStatus.NOT_SERVING); - triBuiltinService.getHealthStatusManager() - .setStatus(url.getServiceInterface(), ServingStatus.NOT_SERVING); + triBuiltinService + .getHealthStatusManager() + .setStatus(url.getServiceKey(), ServingStatus.NOT_SERVING); + triBuiltinService + .getHealthStatusManager() + .setStatus(url.getServiceInterface(), ServingStatus.NOT_SERVING); } exporterMap.remove(key); } @@ -117,36 +117,42 @@ public class TripleProtocol extends AbstractProtocol { Invoker previous = pathResolver.add(url.getServiceKey(), invoker); if (previous != null) { - if (url.getServiceKey().equals(url.getServiceModel().getServiceModel().getInterfaceName())) { + if (url.getServiceKey() + .equals(url.getServiceModel().getServiceModel().getInterfaceName())) { logger.info("Already exists an invoker[" + previous.getUrl() + "] on path[" + url.getServiceKey() - + "], dubbo will override with invoker[" + url + "]"); + + "], dubbo will override with invoker[" + url + "]"); } else { - throw new IllegalStateException("Already exists an invoker[" + previous.getUrl() + "] on path[" + - url.getServiceKey() + "], failed to add invoker[" + url + - "] , please use unique serviceKey."); + throw new IllegalStateException( + "Already exists an invoker[" + previous.getUrl() + "] on path[" + url.getServiceKey() + + "], failed to add invoker[" + url + "] , please use unique serviceKey."); } } if (RESOLVE_FALLBACK_TO_DEFAULT) { - previous = pathResolver.addIfAbsent(url.getServiceModel().getServiceModel().getInterfaceName(), invoker); + previous = pathResolver.addIfAbsent( + url.getServiceModel().getServiceModel().getInterfaceName(), invoker); if (previous != null) { - logger.info("Already exists an invoker[" + previous.getUrl() + "] on path[" + - url.getServiceModel().getServiceModel().getInterfaceName() + - "], dubbo will skip override with invoker[" + url + "]"); + logger.info("Already exists an invoker[" + previous.getUrl() + "] on path[" + + url.getServiceModel().getServiceModel().getInterfaceName() + + "], dubbo will skip override with invoker[" + + url + "]"); } else { - logger.info("Add fallback triple invoker[" + url + "] to path[" + - url.getServiceModel().getServiceModel().getInterfaceName() + "] with invoker[" + url + "]"); + logger.info("Add fallback triple invoker[" + url + "] to path[" + + url.getServiceModel().getServiceModel().getInterfaceName() + "] with invoker[" + url + "]"); } } // set service status if (triBuiltinService.enable()) { - triBuiltinService.getHealthStatusManager() - .setStatus(url.getServiceKey(), HealthCheckResponse.ServingStatus.SERVING); - triBuiltinService.getHealthStatusManager() - .setStatus(url.getServiceInterface(), HealthCheckResponse.ServingStatus.SERVING); + triBuiltinService + .getHealthStatusManager() + .setStatus(url.getServiceKey(), HealthCheckResponse.ServingStatus.SERVING); + triBuiltinService + .getHealthStatusManager() + .setStatus(url.getServiceInterface(), HealthCheckResponse.ServingStatus.SERVING); } // init - ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()).createExecutorIfAbsent(ExecutorUtil.setThreadName(url, SERVER_THREAD_POOL_NAME)); + ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()) + .createExecutorIfAbsent(ExecutorUtil.setThreadName(url, SERVER_THREAD_POOL_NAME)); PortUnificationExchanger.bind(url, new DefaultPuHandler()); optimizeSerialization(url); @@ -158,16 +164,17 @@ public class TripleProtocol extends AbstractProtocol { optimizeSerialization(url); ExecutorService streamExecutor = getOrCreateStreamExecutor(url.getOrDefaultApplicationModel(), url); AbstractConnectionClient connectionClient = PortUnificationExchanger.connect(url, new DefaultPuHandler()); - TripleInvoker invoker = new TripleInvoker<>(type, url, acceptEncodings, - connectionClient, invokers, streamExecutor); + TripleInvoker invoker = + new TripleInvoker<>(type, url, acceptEncodings, connectionClient, invokers, streamExecutor); invokers.add(invoker); return invoker; } private ExecutorService getOrCreateStreamExecutor(ApplicationModel applicationModel, URL url) { url = url.addParameter(THREAD_NAME_KEY, CLIENT_THREAD_POOL_NAME) - .addParameterIfAbsent(THREADPOOL_KEY, DEFAULT_CLIENT_THREADPOOL); - ExecutorService executor = ExecutorRepository.getInstance(applicationModel).createExecutorIfAbsent(url); + .addParameterIfAbsent(THREADPOOL_KEY, DEFAULT_CLIENT_THREADPOOL); + ExecutorService executor = + ExecutorRepository.getInstance(applicationModel).createExecutorIfAbsent(url); Objects.requireNonNull(executor, String.format("No available executor found in %s", url)); return executor; } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/aot/TripleReflectionTypeDescriberRegistrar.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/aot/TripleReflectionTypeDescriberRegistrar.java index 1cda60bed6..0ac720184b 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/aot/TripleReflectionTypeDescriberRegistrar.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/aot/TripleReflectionTypeDescriberRegistrar.java @@ -19,8 +19,8 @@ package org.apache.dubbo.rpc.protocol.tri.aot; import org.apache.dubbo.aot.api.MemberCategory; import org.apache.dubbo.aot.api.ReflectionTypeDescriberRegistrar; import org.apache.dubbo.aot.api.TypeDescriber; -import org.apache.dubbo.rpc.protocol.tri.transport.TripleGoAwayHandler; import org.apache.dubbo.rpc.protocol.tri.transport.TripleCommandOutBoundHandler; +import org.apache.dubbo.rpc.protocol.tri.transport.TripleGoAwayHandler; import org.apache.dubbo.rpc.protocol.tri.transport.TripleHttp2ClientResponseHandler; import org.apache.dubbo.rpc.protocol.tri.transport.TripleHttp2FrameServerHandler; import org.apache.dubbo.rpc.protocol.tri.transport.TripleServerConnectionHandler; @@ -47,6 +47,7 @@ public class TripleReflectionTypeDescriberRegistrar implements ReflectionTypeDes private TypeDescriber buildTypeDescriberWithPublicMethod(Class c) { Set memberCategories = new HashSet<>(); memberCategories.add(MemberCategory.INVOKE_PUBLIC_METHODS); - return new TypeDescriber(c.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); + return new TypeDescriber( + c.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories); } } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/AbstractServerCall.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/AbstractServerCall.java index 7f687a3485..fb8f516367 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/AbstractServerCall.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/AbstractServerCall.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.call; import org.apache.dubbo.common.URL; @@ -40,16 +39,16 @@ import org.apache.dubbo.rpc.protocol.tri.observer.ServerCallToObserverAdapter; import org.apache.dubbo.rpc.protocol.tri.stream.ServerStream; import org.apache.dubbo.rpc.protocol.tri.stream.StreamUtils; -import io.netty.handler.codec.http.HttpHeaderNames; -import io.netty.handler.codec.http.HttpResponseStatus; -import io.netty.handler.codec.http2.DefaultHttp2Headers; -import io.netty.util.concurrent.Future; - import java.util.Map; import java.util.Objects; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; +import io.netty.handler.codec.http.HttpHeaderNames; +import io.netty.handler.codec.http.HttpResponseStatus; +import io.netty.handler.codec.http2.DefaultHttp2Headers; +import io.netty.util.concurrent.Future; + import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_CREATE_STREAM_TRIPLE; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_PARSE; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REQUEST; @@ -99,17 +98,16 @@ public abstract class AbstractServerCall implements ServerCall, ServerStream.Lis isNeedReturnException = needReturnException; } - AbstractServerCall(Invoker invoker, - ServerStream stream, - FrameworkModel frameworkModel, - ServiceDescriptor serviceDescriptor, - String acceptEncoding, - String serviceName, - String methodName, - Executor executor - ) { - Objects.requireNonNull(serviceDescriptor, - "No service descriptor found for " + invoker.getUrl()); + AbstractServerCall( + Invoker invoker, + ServerStream stream, + FrameworkModel frameworkModel, + ServiceDescriptor serviceDescriptor, + String acceptEncoding, + String serviceName, + String methodName, + Executor executor) { + Objects.requireNonNull(serviceDescriptor, "No service descriptor found for " + invoker.getUrl()); this.invoker = invoker; // is already serialized in the stream, so we don't need to serialize it again. this.executor = executor; @@ -121,14 +119,12 @@ public abstract class AbstractServerCall implements ServerCall, ServerStream.Lis this.acceptEncoding = acceptEncoding; } - // stream listener start @Override public void onHeader(Map requestMetadata) { this.requestMetadata = requestMetadata; if (serviceDescriptor == null) { - responseErr( - TriRpcStatus.UNIMPLEMENTED.withDescription("Service not found:" + serviceName)); + responseErr(TriRpcStatus.UNIMPLEMENTED.withDescription("Service not found:" + serviceName)); return; } startCall(); @@ -164,10 +160,17 @@ public abstract class AbstractServerCall implements ServerCall, ServerStream.Lis try { data = packableMethod.packResponse(message); } catch (Exception e) { - close(TriRpcStatus.INTERNAL.withDescription("Serialize response failed") - .withCause(e), null); - LOGGER.error(PROTOCOL_FAILED_SERIALIZE_TRIPLE, "", "", String.format("Serialize triple response failed, service=%s method=%s", - serviceName, methodName), e); + close( + TriRpcStatus.INTERNAL + .withDescription("Serialize response failed") + .withCause(e), + null); + LOGGER.error( + PROTOCOL_FAILED_SERIALIZE_TRIPLE, + "", + "", + String.format("Serialize triple response failed, service=%s method=%s", serviceName, methodName), + e); return; } if (data == null) { @@ -176,8 +179,7 @@ public abstract class AbstractServerCall implements ServerCall, ServerStream.Lis } Future future; if (compressor != null) { - int compressedFlag = - Identity.MESSAGE_ENCODING.equals(compressor.getMessageEncoding()) ? 0 : 1; + int compressedFlag = Identity.MESSAGE_ENCODING.equals(compressor.getMessageEncoding()) ? 0 : 1; final byte[] compressed = compressor.compress(data); future = stream.sendMessage(compressed, compressedFlag); } else { @@ -186,8 +188,8 @@ public abstract class AbstractServerCall implements ServerCall, ServerStream.Lis future.addListener(f -> { if (!f.isSuccess()) { cancelDual(TriRpcStatus.CANCELLED - .withDescription("Send message failed") - .withCause(f.cause())); + .withDescription("Send message failed") + .withCause(f.cause())); } }); } @@ -198,7 +200,7 @@ public abstract class AbstractServerCall implements ServerCall, ServerStream.Lis // It will enter here when there is an error in the header return; } - //Both 'onError' and 'onComplete' are termination operators. + // Both 'onError' and 'onComplete' are termination operators. // The stream will be closed when 'onError' was called, and 'onComplete' is not allowed to be called again. if (isClosed()) { return; @@ -208,17 +210,20 @@ public abstract class AbstractServerCall implements ServerCall, ServerStream.Lis @Override public final void onMessage(byte[] message, boolean isReturnTriException) { - ClassLoader tccl = Thread.currentThread() - .getContextClassLoader(); + ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { Object instance = parseSingleMessage(message); listener.onMessage(instance, message.length); } catch (Exception e) { - final TriRpcStatus status = TriRpcStatus.UNKNOWN.withDescription("Server error") - .withCause(e); + final TriRpcStatus status = + TriRpcStatus.UNKNOWN.withDescription("Server error").withCause(e); close(status, null); - LOGGER.error(PROTOCOL_FAILED_REQUEST, "", "", "Process request failed. service=" + serviceName + - " method=" + methodName, e); + LOGGER.error( + PROTOCOL_FAILED_REQUEST, + "", + "", + "Process request failed. service=" + serviceName + " method=" + methodName, + e); } finally { ClassLoadUtil.switchContextLoader(tccl); } @@ -237,7 +242,6 @@ public abstract class AbstractServerCall implements ServerCall, ServerStream.Lis } // stream listener end - public final boolean isClosed() { return closed; } @@ -249,11 +253,13 @@ public abstract class AbstractServerCall implements ServerCall, ServerStream.Lis */ protected RpcInvocation buildInvocation(MethodDescriptor methodDescriptor) { final URL url = invoker.getUrl(); - RpcInvocation inv = new RpcInvocation(url.getServiceModel(), - methodDescriptor.getMethodName(), - serviceDescriptor.getInterfaceName(), url.getProtocolServiceKey(), - methodDescriptor.getParameterClasses(), - new Object[0]); + RpcInvocation inv = new RpcInvocation( + url.getServiceModel(), + methodDescriptor.getMethodName(), + serviceDescriptor.getInterfaceName(), + url.getProtocolServiceKey(), + methodDescriptor.getParameterClasses(), + new Object[0]); inv.setTargetServiceUniqueName(url.getServiceKey()); inv.setReturnTypes(methodDescriptor.getReturnTypes()); inv.setObjectAttachments(StreamUtils.toAttachments(requestMetadata)); @@ -265,17 +271,22 @@ public abstract class AbstractServerCall implements ServerCall, ServerStream.Lis this.timeout = parseTimeoutToMills(timeout); } } catch (Throwable t) { - LOGGER.warn(PROTOCOL_FAILED_PARSE, "", "", String.format("Failed to parse request timeout set from:%s, service=%s " - + "method=%s", timeout, serviceDescriptor.getInterfaceName(), methodName)); + LOGGER.warn( + PROTOCOL_FAILED_PARSE, + "", + "", + String.format( + "Failed to parse request timeout set from:%s, service=%s " + "method=%s", + timeout, serviceDescriptor.getInterfaceName(), methodName)); } if (null != requestMetadata.get(TripleHeaderEnum.CONSUMER_APP_NAME_KEY.getHeader())) { - inv.put(TripleHeaderEnum.CONSUMER_APP_NAME_KEY, - requestMetadata.get(TripleHeaderEnum.CONSUMER_APP_NAME_KEY.getHeader())); + inv.put( + TripleHeaderEnum.CONSUMER_APP_NAME_KEY, + requestMetadata.get(TripleHeaderEnum.CONSUMER_APP_NAME_KEY.getHeader())); } return inv; } - private void sendHeader() { if (closed) { return; @@ -291,19 +302,17 @@ public abstract class AbstractServerCall implements ServerCall, ServerStream.Lis headers.set(HttpHeaderNames.ACCEPT_ENCODING, acceptEncoding); } if (compressor != null) { - headers.set(TripleHeaderEnum.GRPC_ENCODING.getHeader(), - compressor.getMessageEncoding()); + headers.set(TripleHeaderEnum.GRPC_ENCODING.getHeader(), compressor.getMessageEncoding()); } if (!exceptionCode.equals(CommonConstants.TRI_EXCEPTION_CODE_NOT_EXISTS)) { headers.set(TripleHeaderEnum.TRI_EXCEPTION_CODE.getHeader(), String.valueOf(exceptionCode)); } // send header failed will reset stream and close request observer cause no more data will be sent - stream.sendHeader(headers) - .addListener(f -> { - if (!f.isSuccess()) { - cancelDual(TriRpcStatus.INTERNAL.withCause(f.cause())); - } - }); + stream.sendHeader(headers).addListener(f -> { + if (!f.isSuccess()) { + cancelDual(TriRpcStatus.INTERNAL.withCause(f.cause())); + } + }); } private void cancelDual(TriRpcStatus status) { @@ -321,7 +330,6 @@ public abstract class AbstractServerCall implements ServerCall, ServerStream.Lis stream.cancelByLocal(TriRpcStatus.CANCELLED.withCause(throwable)); } - public void setCompression(String compression) { if (headerSent) { throw new IllegalStateException("Can not set compression after header sent"); @@ -333,12 +341,10 @@ public abstract class AbstractServerCall implements ServerCall, ServerStream.Lis autoRequestN = false; } - public boolean isAutoRequestN() { return autoRequestN; } - public void close(TriRpcStatus status, Map attachments) { doClose(status, attachments); } @@ -387,34 +393,34 @@ public abstract class AbstractServerCall implements ServerCall, ServerStream.Lis } closed = true; stream.complete(status, null, false, CommonConstants.TRI_EXCEPTION_CODE_NOT_EXISTS); - LOGGER.error(PROTOCOL_FAILED_REQUEST, "", "", "Triple request error: service=" + serviceName + " method" + methodName, - status.asException()); + LOGGER.error( + PROTOCOL_FAILED_REQUEST, + "", + "", + "Triple request error: service=" + serviceName + " method" + methodName, + status.asException()); } - protected ServerCall.Listener startInternalCall( - RpcInvocation invocation, - MethodDescriptor methodDescriptor, - Invoker invoker) { + RpcInvocation invocation, MethodDescriptor methodDescriptor, Invoker invoker) { this.cancellationContext = RpcContext.getCancellationContext(); ServerCallToObserverAdapter responseObserver = - new ServerCallToObserverAdapter<>(this, cancellationContext); + new ServerCallToObserverAdapter<>(this, cancellationContext); try { ServerCall.Listener listener; switch (methodDescriptor.getRpcType()) { case UNARY: - listener = new UnaryServerCallListener(invocation, invoker, responseObserver, packableMethod.needWrapper()); + listener = new UnaryServerCallListener( + invocation, invoker, responseObserver, packableMethod.needWrapper()); request(2); break; case SERVER_STREAM: - listener = new ServerStreamServerCallListener(invocation, invoker, - responseObserver); + listener = new ServerStreamServerCallListener(invocation, invoker, responseObserver); request(2); break; case BI_STREAM: case CLIENT_STREAM: - listener = new BiStreamServerCallListener(invocation, invoker, - responseObserver); + listener = new BiStreamServerCallListener(invocation, invoker, responseObserver); request(1); break; default: @@ -423,8 +429,9 @@ public abstract class AbstractServerCall implements ServerCall, ServerStream.Lis return listener; } catch (Exception e) { LOGGER.error(PROTOCOL_FAILED_CREATE_STREAM_TRIPLE, "", "", "Create triple stream failed", e); - responseErr(TriRpcStatus.INTERNAL.withDescription("Create stream failed") - .withCause(e)); + responseErr(TriRpcStatus.INTERNAL + .withDescription("Create stream failed") + .withCause(e)); } return null; } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/AbstractServerCallListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/AbstractServerCallListener.java index f645a80468..7fa838d8d7 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/AbstractServerCallListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/AbstractServerCallListener.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.call; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -30,19 +29,20 @@ import org.apache.dubbo.rpc.protocol.tri.observer.ServerCallToObserverAdapter; import java.net.InetSocketAddress; -import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_TIMEOUT_SERVER; import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY; +import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_TIMEOUT_SERVER; public abstract class AbstractServerCallListener implements AbstractServerCall.Listener { - private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(AbstractServerCallListener.class); + private static final ErrorTypeAwareLogger LOGGER = + LoggerFactory.getErrorTypeAwareLogger(AbstractServerCallListener.class); public final CancellationContext cancellationContext; final RpcInvocation invocation; final Invoker invoker; final ServerCallToObserverAdapter responseObserver; - public AbstractServerCallListener(RpcInvocation invocation, Invoker invoker, - ServerCallToObserverAdapter responseObserver) { + public AbstractServerCallListener( + RpcInvocation invocation, Invoker invoker, ServerCallToObserverAdapter responseObserver) { this.invocation = invocation; this.invoker = invoker; this.cancellationContext = responseObserver.cancellationContext; @@ -51,11 +51,10 @@ public abstract class AbstractServerCallListener implements AbstractServerCall.L public void invoke() { RpcContext.restoreCancellationContext(cancellationContext); - InetSocketAddress remoteAddress = (InetSocketAddress) invocation.getAttributes() - .remove(AbstractServerCall.REMOTE_ADDRESS_KEY); + InetSocketAddress remoteAddress = + (InetSocketAddress) invocation.getAttributes().remove(AbstractServerCall.REMOTE_ADDRESS_KEY); RpcContext.getServiceContext().setRemoteAddress(remoteAddress); - String remoteApp = (String) invocation.getAttributes() - .remove(TripleHeaderEnum.CONSUMER_APP_NAME_KEY); + String remoteApp = (String) invocation.getAttributes().remove(TripleHeaderEnum.CONSUMER_APP_NAME_KEY); if (null != remoteApp) { RpcContext.getServiceContext().setRemoteApplicationName(remoteApp); invocation.setAttachmentIfAbsent(REMOTE_APPLICATION_KEY, remoteApp); @@ -75,11 +74,13 @@ public abstract class AbstractServerCallListener implements AbstractServerCall.L } final long cost = System.currentTimeMillis() - stInMillis; if (responseObserver.isTimeout(cost)) { - LOGGER.error(PROTOCOL_TIMEOUT_SERVER, "", "", String.format( - "Invoke timeout at server side, ignored to send response. service=%s method=%s cost=%s", - invocation.getTargetServiceUniqueName(), - invocation.getMethodName(), - cost)); + LOGGER.error( + PROTOCOL_TIMEOUT_SERVER, + "", + "", + String.format( + "Invoke timeout at server side, ignored to send response. service=%s method=%s cost=%s", + invocation.getTargetServiceUniqueName(), invocation.getMethodName(), cost)); responseObserver.onCompleted(TriRpcStatus.DEADLINE_EXCEEDED); return; } @@ -93,7 +94,6 @@ public abstract class AbstractServerCallListener implements AbstractServerCall.L } } - protected void doOnResponseHasException(Throwable t) { responseObserver.onError(t); } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/BiStreamServerCallListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/BiStreamServerCallListener.java index 2d3346b5c6..e37ac9d006 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/BiStreamServerCallListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/BiStreamServerCallListener.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.call; import org.apache.dubbo.common.stream.StreamObserver; @@ -27,10 +26,10 @@ public class BiStreamServerCallListener extends AbstractServerCallListener { private StreamObserver requestObserver; - public BiStreamServerCallListener(RpcInvocation invocation, Invoker invoker, - ServerCallToObserverAdapter responseObserver) { + public BiStreamServerCallListener( + RpcInvocation invocation, Invoker invoker, ServerCallToObserverAdapter responseObserver) { super(invocation, invoker, responseObserver); - invocation.setArguments(new Object[]{responseObserver}); + invocation.setArguments(new Object[] {responseObserver}); invoke(); } @@ -55,7 +54,6 @@ public class BiStreamServerCallListener extends AbstractServerCallListener { requestObserver.onError(status.asException()); } - @Override public void onComplete() { requestObserver.onCompleted(); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCall.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCall.java index d99c8c3bf0..8b0e1be114 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCall.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCall.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.call; import org.apache.dubbo.common.stream.StreamObserver; @@ -83,8 +82,7 @@ public interface ClientCall { * @param responseListener the listener to receive response * @return the stream observer representing the request sink */ - StreamObserver start(RequestMetadata metadata, - Listener responseListener); + StreamObserver start(RequestMetadata metadata, Listener responseListener); /** * @return true if this call is auto request @@ -98,7 +96,6 @@ public interface ClientCall { */ void setAutoRequest(boolean autoRequest); - /** * No more data will be sent. */ @@ -110,5 +107,4 @@ public interface ClientCall { * @param compression compression algorithm */ void setCompression(String compression); - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ObserverToClientCallListenerAdapter.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ObserverToClientCallListenerAdapter.java index f52bf4e8d1..fce504e958 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ObserverToClientCallListenerAdapter.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ObserverToClientCallListenerAdapter.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.call; import org.apache.dubbo.common.stream.StreamObserver; @@ -27,7 +26,7 @@ public class ObserverToClientCallListenerAdapter implements ClientCall.Listener private final StreamObserver delegate; private ClientCall call; - private Consumer onStartConsumer = clientCall -> { }; + private Consumer onStartConsumer = clientCall -> {}; public ObserverToClientCallListenerAdapter(StreamObserver delegate) { this.delegate = delegate; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ReflectionAbstractServerCall.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ReflectionAbstractServerCall.java index 80e7c3cbc9..4be61a00df 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ReflectionAbstractServerCall.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ReflectionAbstractServerCall.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.call; import org.apache.dubbo.common.URL; @@ -37,14 +36,14 @@ import org.apache.dubbo.rpc.protocol.tri.TripleCustomerProtocolWapper; import org.apache.dubbo.rpc.protocol.tri.stream.ServerStream; import org.apache.dubbo.rpc.service.ServiceDescriptorInternalCache; -import io.netty.handler.codec.http.HttpHeaderNames; - import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; +import io.netty.handler.codec.http.HttpHeaderNames; + import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PACKABLE_METHOD_FACTORY; @@ -54,18 +53,24 @@ public class ReflectionAbstractServerCall extends AbstractServerCall { private final List headerFilters; private List methodDescriptors; - public ReflectionAbstractServerCall(Invoker invoker, - ServerStream serverStream, - FrameworkModel frameworkModel, - String acceptEncoding, - String serviceName, - String methodName, - List headerFilters, - Executor executor) { - super(invoker, serverStream, frameworkModel, - getServiceDescriptor(invoker.getUrl()), - acceptEncoding, serviceName, methodName, - executor); + public ReflectionAbstractServerCall( + Invoker invoker, + ServerStream serverStream, + FrameworkModel frameworkModel, + String acceptEncoding, + String serviceName, + String methodName, + List headerFilters, + Executor executor) { + super( + invoker, + serverStream, + frameworkModel, + getServiceDescriptor(invoker.getUrl()), + acceptEncoding, + serviceName, + methodName, + executor); this.headerFilters = headerFilters; } @@ -82,8 +87,7 @@ public class ReflectionAbstractServerCall extends AbstractServerCall { } private boolean isGeneric(String methodName) { - return CommonConstants.$INVOKE.equals(methodName) || CommonConstants.$INVOKE_ASYNC.equals( - methodName); + return CommonConstants.$INVOKE.equals(methodName) || CommonConstants.$INVOKE_ASYNC.equals(methodName); } @Override @@ -91,22 +95,23 @@ public class ReflectionAbstractServerCall extends AbstractServerCall { if (isGeneric(methodName)) { // There should be one and only one methodDescriptor = ServiceDescriptorInternalCache.genericService() - .getMethods(methodName).get(0); + .getMethods(methodName) + .get(0); } else if (isEcho(methodName)) { // There should be one and only one - methodDescriptor = ServiceDescriptorInternalCache.echoService().getMethods(methodName) - .get(0); + methodDescriptor = ServiceDescriptorInternalCache.echoService() + .getMethods(methodName) + .get(0); } else { methodDescriptors = serviceDescriptor.getMethods(methodName); // try lower-case method if (CollectionUtils.isEmpty(methodDescriptors)) { - final String lowerMethod = - Character.toLowerCase(methodName.charAt(0)) + methodName.substring(1); + final String lowerMethod = Character.toLowerCase(methodName.charAt(0)) + methodName.substring(1); methodDescriptors = serviceDescriptor.getMethods(lowerMethod); } if (CollectionUtils.isEmpty(methodDescriptors)) { responseErr(TriRpcStatus.UNIMPLEMENTED.withDescription( - "Method : " + methodName + " not found of service:" + serviceName)); + "Method : " + methodName + " not found of service:" + serviceName)); return; } // In most cases there is only one method @@ -152,8 +157,7 @@ public class ReflectionAbstractServerCall extends AbstractServerCall { if (isClosed()) { return; } - listener = ReflectionAbstractServerCall.this.startInternalCall(invocation, - methodDescriptor, invoker); + listener = ReflectionAbstractServerCall.this.startInternalCall(invocation, methodDescriptor, invoker); } @Override @@ -163,12 +167,10 @@ public class ReflectionAbstractServerCall extends AbstractServerCall { if (isClosed()) { return null; } - ClassLoadUtil.switchContextLoader( - invoker.getUrl().getServiceModel().getClassLoader()); + ClassLoadUtil.switchContextLoader(invoker.getUrl().getServiceModel().getClassLoader()); return packableMethod.getRequestUnpack().unpack(data); } - private void trySetMethodDescriptor(byte[] data) { if (methodDescriptor != null) { return; @@ -176,8 +178,8 @@ public class ReflectionAbstractServerCall extends AbstractServerCall { final TripleCustomerProtocolWapper.TripleRequestWrapper request; request = TripleCustomerProtocolWapper.TripleRequestWrapper.parseFrom(data); - final String[] paramTypes = request.getArgTypes() - .toArray(new String[request.getArgs().size()]); + final String[] paramTypes = + request.getArgTypes().toArray(new String[request.getArgs().size()]); // wrapper mode the method can overload so maybe list for (MethodDescriptor descriptor : methodDescriptors) { // params type is array @@ -187,10 +189,11 @@ public class ReflectionAbstractServerCall extends AbstractServerCall { } } if (methodDescriptor == null) { - ReflectionAbstractServerCall.this.close(TriRpcStatus.UNIMPLEMENTED.withDescription( - "Method :" + methodName + "[" + Arrays.toString( - paramTypes) + "] " + "not found of service:" - + serviceDescriptor.getInterfaceName()), null); + ReflectionAbstractServerCall.this.close( + TriRpcStatus.UNIMPLEMENTED.withDescription( + "Method :" + methodName + "[" + Arrays.toString(paramTypes) + "] " + "not found of service:" + + serviceDescriptor.getInterfaceName()), + null); return; } loadPackableMethod(invoker.getUrl()); @@ -199,13 +202,13 @@ public class ReflectionAbstractServerCall extends AbstractServerCall { @SuppressWarnings("unchecked") private void loadPackableMethod(URL url) { Map cacheMap = (Map) url.getServiceModel() - .getServiceMetadata() - .getAttributeMap() - .computeIfAbsent(PACKABLE_METHOD_CACHE, (k) -> new ConcurrentHashMap<>()); - packableMethod = cacheMap.computeIfAbsent(methodDescriptor, - (md) -> frameworkModel.getExtensionLoader(PackableMethodFactory.class) - .getExtension(ConfigurationUtils.getGlobalConfiguration(url.getApplicationModel()).getString(DUBBO_PACKABLE_METHOD_FACTORY, DEFAULT_KEY)) + .getServiceMetadata() + .getAttributeMap() + .computeIfAbsent(PACKABLE_METHOD_CACHE, (k) -> new ConcurrentHashMap<>()); + packableMethod = cacheMap.computeIfAbsent(methodDescriptor, (md) -> frameworkModel + .getExtensionLoader(PackableMethodFactory.class) + .getExtension(ConfigurationUtils.getGlobalConfiguration(url.getApplicationModel()) + .getString(DUBBO_PACKABLE_METHOD_FACTORY, DEFAULT_KEY)) .create(methodDescriptor, url, (String) requestMetadata.get(HttpHeaderNames.CONTENT_TYPE.toString()))); } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ServerCall.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ServerCall.java index 45742b9a80..e5bdb36513 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ServerCall.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ServerCall.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.call; import org.apache.dubbo.rpc.TriRpcStatus; @@ -73,5 +72,4 @@ public interface ServerCall { * @param responseAttrs response attachments */ void close(TriRpcStatus status, Map responseAttrs); - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ServerStreamServerCallListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ServerStreamServerCallListener.java index c6b42e50e2..8e5ea19caf 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ServerStreamServerCallListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/ServerStreamServerCallListener.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.call; import org.apache.dubbo.rpc.Invoker; @@ -24,21 +23,20 @@ import org.apache.dubbo.rpc.protocol.tri.observer.ServerCallToObserverAdapter; public class ServerStreamServerCallListener extends AbstractServerCallListener { - public ServerStreamServerCallListener(RpcInvocation invocation, Invoker invoker, - ServerCallToObserverAdapter responseObserver) { + public ServerStreamServerCallListener( + RpcInvocation invocation, Invoker invoker, ServerCallToObserverAdapter responseObserver) { super(invocation, invoker, responseObserver); } @Override - public void onReturn(Object value) { - } + public void onReturn(Object value) {} @Override public void onMessage(Object message, int actualContentLength) { if (message instanceof Object[]) { message = ((Object[]) message)[0]; } - invocation.setArguments(new Object[]{message, responseObserver}); + invocation.setArguments(new Object[] {message, responseObserver}); } @Override @@ -46,8 +44,6 @@ public class ServerStreamServerCallListener extends AbstractServerCallListener { responseObserver.onError(status.asException()); } - - @Override public void onComplete() { invoke(); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/StubAbstractServerCall.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/StubAbstractServerCall.java index 6f5027abfa..139c42c415 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/StubAbstractServerCall.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/StubAbstractServerCall.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.call; import org.apache.dubbo.common.URL; @@ -29,27 +28,31 @@ import java.util.concurrent.Executor; public class StubAbstractServerCall extends AbstractServerCall { - public StubAbstractServerCall(Invoker invoker, - ServerStream serverStream, - FrameworkModel frameworkModel, - String acceptEncoding, - String serviceName, - String methodName, - Executor executor) { - super(invoker, serverStream, frameworkModel, - getServiceDescriptor(invoker.getUrl(), serviceName), - acceptEncoding, serviceName, methodName, executor); - this.methodDescriptor = serviceDescriptor.getMethods(methodName) - .get(0); + public StubAbstractServerCall( + Invoker invoker, + ServerStream serverStream, + FrameworkModel frameworkModel, + String acceptEncoding, + String serviceName, + String methodName, + Executor executor) { + super( + invoker, + serverStream, + frameworkModel, + getServiceDescriptor(invoker.getUrl(), serviceName), + acceptEncoding, + serviceName, + methodName, + executor); + this.methodDescriptor = serviceDescriptor.getMethods(methodName).get(0); this.packableMethod = (StubMethodDescriptor) methodDescriptor; } private static ServiceDescriptor getServiceDescriptor(URL url, String serviceName) { ServiceDescriptor serviceDescriptor; if (url.getServiceModel() != null) { - serviceDescriptor = url - .getServiceModel() - .getServiceModel(); + serviceDescriptor = url.getServiceModel().getServiceModel(); } else { serviceDescriptor = StubSuppliers.getServiceDescriptor(serviceName); } @@ -60,5 +63,4 @@ public class StubAbstractServerCall extends AbstractServerCall { protected Object parseSingleMessage(byte[] data) throws Exception { return packableMethod.parseRequest(data); } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/TripleClientCall.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/TripleClientCall.java index 3673bd5e83..330deaa0bd 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/TripleClientCall.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/TripleClientCall.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.call; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -32,12 +31,12 @@ import org.apache.dubbo.rpc.protocol.tri.stream.StreamUtils; import org.apache.dubbo.rpc.protocol.tri.stream.TripleClientStream; import org.apache.dubbo.rpc.protocol.tri.transport.TripleWriteQueue; -import io.netty.channel.Channel; -import io.netty.handler.codec.http2.Http2Exception; - import java.util.Map; import java.util.concurrent.Executor; +import io.netty.channel.Channel; +import io.netty.handler.codec.http2.Http2Exception; + import static io.netty.handler.codec.http2.Http2Error.FLOW_CONTROL_ERROR; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_RESPONSE; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_SERIALIZE_TRIPLE; @@ -58,34 +57,47 @@ public class TripleClientCall implements ClientCall, ClientStream.Listener { private boolean done; private Http2Exception.StreamException streamException; - public TripleClientCall(AbstractConnectionClient connectionClient, Executor executor, - FrameworkModel frameworkModel, TripleWriteQueue writeQueue) { + public TripleClientCall( + AbstractConnectionClient connectionClient, + Executor executor, + FrameworkModel frameworkModel, + TripleWriteQueue writeQueue) { this.connectionClient = connectionClient; this.executor = executor; this.frameworkModel = frameworkModel; - this.writeQueue= writeQueue; + this.writeQueue = writeQueue; } // stream listener start @Override public void onMessage(byte[] message, boolean isReturnTriException) { if (done) { - LOGGER.warn(PROTOCOL_STREAM_LISTENER, "", "", - "Received message from closed stream,connection=" + connectionClient + " service=" - + requestMetadata.service + " method=" - + requestMetadata.method.getMethodName()); + LOGGER.warn( + PROTOCOL_STREAM_LISTENER, + "", + "", + "Received message from closed stream,connection=" + connectionClient + " service=" + + requestMetadata.service + " method=" + + requestMetadata.method.getMethodName()); return; } try { final Object unpacked = requestMetadata.packableMethod.parseResponse(message, isReturnTriException); listener.onMessage(unpacked, message.length); } catch (Throwable t) { - TriRpcStatus status = TriRpcStatus.INTERNAL.withDescription("Deserialize response failed") - .withCause(t); + TriRpcStatus status = TriRpcStatus.INTERNAL + .withDescription("Deserialize response failed") + .withCause(t); cancelByLocal(status.asException()); - listener.onClose(status,null, false); - LOGGER.error(PROTOCOL_FAILED_RESPONSE, "", "", String.format("Failed to deserialize triple response, service=%s, method=%s,connection=%s", - connectionClient, requestMetadata.service, requestMetadata.method.getMethodName()), t); + listener.onClose(status, null, false); + LOGGER.error( + PROTOCOL_FAILED_RESPONSE, + "", + "", + String.format( + "Failed to deserialize triple response, service=%s, method=%s,connection=%s", + connectionClient, requestMetadata.service, requestMetadata.method.getMethodName()), + t); } } @@ -102,8 +114,11 @@ public class TripleClientCall implements ClientCall, ClientStream.Listener { } @Override - public void onComplete(TriRpcStatus status, Map attachments, - Map excludeHeaders, boolean isReturnTriException) { + public void onComplete( + TriRpcStatus status, + Map attachments, + Map excludeHeaders, + boolean isReturnTriException) { if (done) { return; } @@ -111,8 +126,9 @@ public class TripleClientCall implements ClientCall, ClientStream.Listener { try { listener.onClose(status, StreamUtils.toAttachments(attachments), isReturnTriException); } catch (Throwable t) { - cancelByLocal( - TriRpcStatus.INTERNAL.withDescription("Close stream error").withCause(t) + cancelByLocal(TriRpcStatus.INTERNAL + .withDescription("Close stream error") + .withCause(t) .asException()); } if (requestMetadata.cancellationContext != null) { @@ -138,18 +154,18 @@ public class TripleClientCall implements ClientCall, ClientStream.Listener { if (stream == null) { return; } - if(t instanceof Http2Exception.StreamException && ((Http2Exception.StreamException) t).error().equals(FLOW_CONTROL_ERROR)){ - TriRpcStatus status = TriRpcStatus.CANCELLED.withCause(t) - .withDescription("Due flowcontrol over pendingbytes, Cancelled by client"); + if (t instanceof Http2Exception.StreamException + && ((Http2Exception.StreamException) t).error().equals(FLOW_CONTROL_ERROR)) { + TriRpcStatus status = TriRpcStatus.CANCELLED + .withCause(t) + .withDescription("Due flowcontrol over pendingbytes, Cancelled by client"); stream.cancelByLocal(status); streamException = (Http2Exception.StreamException) t; - }else{ - TriRpcStatus status = TriRpcStatus.CANCELLED.withCause(t) - .withDescription("Cancelled by client"); + } else { + TriRpcStatus status = TriRpcStatus.CANCELLED.withCause(t).withDescription("Cancelled by client"); stream.cancelByLocal(status); } - TriRpcStatus status = TriRpcStatus.CANCELLED.withCause(t) - .withDescription("Cancelled by client"); + TriRpcStatus status = TriRpcStatus.CANCELLED.withCause(t).withDescription("Cancelled by client"); stream.cancelByLocal(status); if (requestMetadata.cancellationContext != null) { requestMetadata.cancellationContext.cancel(t); @@ -165,7 +181,7 @@ public class TripleClientCall implements ClientCall, ClientStream.Listener { public void sendMessage(Object message) { if (canceled && null != streamException) { throw new IllegalStateException("Due flowcontrol over pendingbytes, Call already canceled"); - }else if (canceled) { + } else if (canceled) { throw new IllegalStateException("Call already canceled"); } if (!headerSent) { @@ -175,23 +191,29 @@ public class TripleClientCall implements ClientCall, ClientStream.Listener { final byte[] data; try { data = requestMetadata.packableMethod.packRequest(message); - int compressed = - Identity.MESSAGE_ENCODING.equals(requestMetadata.compressor.getMessageEncoding()) - ? 0 : 1; + int compressed = Identity.MESSAGE_ENCODING.equals(requestMetadata.compressor.getMessageEncoding()) ? 0 : 1; final byte[] compress = requestMetadata.compressor.compress(data); - stream.sendMessage(compress, compressed, false) - .addListener(f -> { - if (!f.isSuccess()) { - cancelByLocal(f.cause()); - } - }); + stream.sendMessage(compress, compressed, false).addListener(f -> { + if (!f.isSuccess()) { + cancelByLocal(f.cause()); + } + }); } catch (Throwable t) { - LOGGER.error(PROTOCOL_FAILED_SERIALIZE_TRIPLE, "", "", String.format("Serialize triple request failed, service=%s method=%s", - requestMetadata.service, - requestMetadata.method.getMethodName()), t); + LOGGER.error( + PROTOCOL_FAILED_SERIALIZE_TRIPLE, + "", + "", + String.format( + "Serialize triple request failed, service=%s method=%s", + requestMetadata.service, requestMetadata.method.getMethodName()), + t); cancelByLocal(t); - listener.onClose(TriRpcStatus.INTERNAL.withDescription("Serialize request failed") - .withCause(t), null, false); + listener.onClose( + TriRpcStatus.INTERNAL + .withDescription("Serialize request failed") + .withCause(t), + null, + false); } } // stream listener end @@ -204,12 +226,11 @@ public class TripleClientCall implements ClientCall, ClientStream.Listener { if (canceled) { return; } - stream.halfClose() - .addListener(f -> { - if (!f.isSuccess()) { - cancelByLocal(new IllegalStateException("Half close failed", f.cause())); - } - }); + stream.halfClose().addListener(f -> { + if (!f.isSuccess()) { + cancelByLocal(new IllegalStateException("Half close failed", f.cause())); + } + }); } @Override @@ -218,12 +239,11 @@ public class TripleClientCall implements ClientCall, ClientStream.Listener { } @Override - public StreamObserver start(RequestMetadata metadata, - ClientCall.Listener responseListener) { + public StreamObserver start(RequestMetadata metadata, ClientCall.Listener responseListener) { this.requestMetadata = metadata; this.listener = responseListener; - this.stream = new TripleClientStream(frameworkModel, executor, (Channel) connectionClient.getChannel(true), - this, writeQueue); + this.stream = new TripleClientStream( + frameworkModel, executor, (Channel) connectionClient.getChannel(true), this, writeQueue); return new ClientCallToObserverAdapter<>(this); } @@ -236,5 +256,4 @@ public class TripleClientCall implements ClientCall, ClientStream.Listener { public void setAutoRequest(boolean autoRequest) { this.autoRequest = autoRequest; } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/UnaryClientCallListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/UnaryClientCallListener.java index b08ee0618f..ca6e0d34bf 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/UnaryClientCallListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/UnaryClientCallListener.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.call; import org.apache.dubbo.remoting.Constants; @@ -50,7 +49,7 @@ public class UnaryClientCallListener implements ClientCall.Listener { } else { result.setValue(appResponse); } - } else { + } else { result.setException(status.asException()); } result.setAttribute(Constants.CONTENT_LENGTH_KEY, actualContentLength); @@ -59,8 +58,7 @@ public class UnaryClientCallListener implements ClientCall.Listener { @Override public void onStart(ClientCall call) { - future.addTimeoutListener( - () -> call.cancelByLocal(new IllegalStateException("client timeout"))); + future.addTimeoutListener(() -> call.cancelByLocal(new IllegalStateException("client timeout"))); call.request(2); } } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/UnaryServerCallListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/UnaryServerCallListener.java index e53b72079a..9e6da9158f 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/UnaryServerCallListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/call/UnaryServerCallListener.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.call; import org.apache.dubbo.remoting.Constants; @@ -28,8 +27,11 @@ public class UnaryServerCallListener extends AbstractServerCallListener { private final boolean needWrapper; - public UnaryServerCallListener(RpcInvocation invocation, Invoker invoker, - ServerCallToObserverAdapter responseObserver, boolean needWrapper) { + public UnaryServerCallListener( + RpcInvocation invocation, + Invoker invoker, + ServerCallToObserverAdapter responseObserver, + boolean needWrapper) { super(invocation, invoker, responseObserver); this.needWrapper = needWrapper; } @@ -45,7 +47,7 @@ public class UnaryServerCallListener extends AbstractServerCallListener { if (message instanceof Object[]) { invocation.setArguments((Object[]) message); } else { - invocation.setArguments(new Object[]{message}); + invocation.setArguments(new Object[] {message}); } invocation.put(Constants.CONTENT_LENGTH_KEY, actualContentLength); } @@ -64,7 +66,6 @@ public class UnaryServerCallListener extends AbstractServerCallListener { } } - private void onReturnException(Exception value) { TriRpcStatus status = TriRpcStatus.getStatus(value); int exceptionCode = status.code.code; @@ -80,5 +81,4 @@ public class UnaryServerCallListener extends AbstractServerCallListener { public void onComplete() { invoke(); } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/CancelQueueCommand.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/CancelQueueCommand.java index eb8b249fd0..1b988f3388 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/CancelQueueCommand.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/CancelQueueCommand.java @@ -14,14 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.command; +import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture; + import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.http2.DefaultHttp2ResetFrame; import io.netty.handler.codec.http2.Http2Error; -import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture; public class CancelQueueCommand extends StreamQueueCommand { private final Http2Error error; @@ -35,7 +35,6 @@ public class CancelQueueCommand extends StreamQueueCommand { return new CancelQueueCommand(streamChannelFuture, error); } - @Override public void doSend(ChannelHandlerContext ctx, ChannelPromise promise) { ctx.write(new DefaultHttp2ResetFrame(error), promise); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/CreateStreamQueueCommand.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/CreateStreamQueueCommand.java index 7044926bc1..7c53c58998 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/CreateStreamQueueCommand.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/CreateStreamQueueCommand.java @@ -16,13 +16,14 @@ */ package org.apache.dubbo.rpc.protocol.tri.command; +import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture; + import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.http2.Http2StreamChannel; import io.netty.handler.codec.http2.Http2StreamChannelBootstrap; import io.netty.util.concurrent.Future; -import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture; public class CreateStreamQueueCommand extends QueuedCommand { @@ -30,27 +31,27 @@ public class CreateStreamQueueCommand extends QueuedCommand { private final TripleStreamChannelFuture streamChannelFuture; - private CreateStreamQueueCommand(Http2StreamChannelBootstrap bootstrap, - TripleStreamChannelFuture streamChannelFuture) { + private CreateStreamQueueCommand( + Http2StreamChannelBootstrap bootstrap, TripleStreamChannelFuture streamChannelFuture) { this.bootstrap = bootstrap; this.streamChannelFuture = streamChannelFuture; this.promise(streamChannelFuture.getParentChannel().newPromise()); this.channel(streamChannelFuture.getParentChannel()); } - public static CreateStreamQueueCommand create(Http2StreamChannelBootstrap bootstrap, - TripleStreamChannelFuture streamChannelFuture) { + public static CreateStreamQueueCommand create( + Http2StreamChannelBootstrap bootstrap, TripleStreamChannelFuture streamChannelFuture) { return new CreateStreamQueueCommand(bootstrap, streamChannelFuture); } @Override public void doSend(ChannelHandlerContext ctx, ChannelPromise promise) { - //NOOP + // NOOP } @Override public void run(Channel channel) { - //work in I/O thread + // work in I/O thread Future future = bootstrap.open(); if (future.isSuccess()) { streamChannelFuture.complete(future.getNow()); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/DataQueueCommand.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/DataQueueCommand.java index cbd0a69ac2..a9ef447abb 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/DataQueueCommand.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/DataQueueCommand.java @@ -14,14 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.command; +import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture; + import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.http2.DefaultHttp2DataFrame; -import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture; public class DataQueueCommand extends StreamQueueCommand { @@ -31,15 +31,16 @@ public class DataQueueCommand extends StreamQueueCommand { private final boolean endStream; - private DataQueueCommand(TripleStreamChannelFuture streamChannelFuture, byte[] data, int compressFlag, boolean endStream) { + private DataQueueCommand( + TripleStreamChannelFuture streamChannelFuture, byte[] data, int compressFlag, boolean endStream) { super(streamChannelFuture); this.data = data; this.compressFlag = compressFlag; this.endStream = endStream; } - public static DataQueueCommand create(TripleStreamChannelFuture streamChannelFuture, byte[] data, boolean endStream, - int compressFlag) { + public static DataQueueCommand create( + TripleStreamChannelFuture streamChannelFuture, byte[] data, boolean endStream, int compressFlag) { return new DataQueueCommand(streamChannelFuture, data, compressFlag, endStream); } @@ -56,7 +57,6 @@ public class DataQueueCommand extends StreamQueueCommand { } } - // for test public byte[] getData() { return data; @@ -66,5 +66,4 @@ public class DataQueueCommand extends StreamQueueCommand { public boolean isEndStream() { return endStream; } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/EndStreamQueueCommand.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/EndStreamQueueCommand.java index 863230b43e..2164e02b63 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/EndStreamQueueCommand.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/EndStreamQueueCommand.java @@ -14,13 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.command; +import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture; + import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.http2.DefaultHttp2DataFrame; -import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture; public class EndStreamQueueCommand extends StreamQueueCommand { diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/HeaderQueueCommand.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/HeaderQueueCommand.java index 7ae2a1777c..e221b4370b 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/HeaderQueueCommand.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/HeaderQueueCommand.java @@ -14,14 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.command; +import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture; + import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame; import io.netty.handler.codec.http2.Http2Headers; -import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture; public class HeaderQueueCommand extends StreamQueueCommand { @@ -35,11 +35,13 @@ public class HeaderQueueCommand extends StreamQueueCommand { this.endStream = endStream; } - public static HeaderQueueCommand createHeaders(TripleStreamChannelFuture streamChannelFuture, Http2Headers headers) { + public static HeaderQueueCommand createHeaders( + TripleStreamChannelFuture streamChannelFuture, Http2Headers headers) { return new HeaderQueueCommand(streamChannelFuture, headers, false); } - public static HeaderQueueCommand createHeaders(TripleStreamChannelFuture streamChannelFuture, Http2Headers headers, boolean endStream) { + public static HeaderQueueCommand createHeaders( + TripleStreamChannelFuture streamChannelFuture, Http2Headers headers, boolean endStream) { return new HeaderQueueCommand(streamChannelFuture, headers, endStream); } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/QueuedCommand.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/QueuedCommand.java index fd140a9288..f3fe69a8eb 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/QueuedCommand.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/QueuedCommand.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.command; import io.netty.channel.Channel; @@ -70,4 +69,3 @@ public abstract class QueuedCommand { public abstract void doSend(ChannelHandlerContext ctx, ChannelPromise promise); } - diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/StreamQueueCommand.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/StreamQueueCommand.java index 2815bdabf7..548b25bc06 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/StreamQueueCommand.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/StreamQueueCommand.java @@ -14,13 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.command; -import io.netty.channel.Channel; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture; +import io.netty.channel.Channel; + public abstract class StreamQueueCommand extends QueuedCommand { protected final TripleStreamChannelFuture streamChannelFuture; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/TextDataQueueCommand.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/TextDataQueueCommand.java index ba35504973..c7da28d42d 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/TextDataQueueCommand.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/TextDataQueueCommand.java @@ -14,15 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.command; +import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture; + import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.http2.DefaultHttp2DataFrame; -import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture; public class TextDataQueueCommand extends StreamQueueCommand { @@ -36,7 +36,8 @@ public class TextDataQueueCommand extends StreamQueueCommand { this.endStream = endStream; } - public static TextDataQueueCommand createCommand(TripleStreamChannelFuture streamChannelFuture, String data, boolean endStream) { + public static TextDataQueueCommand createCommand( + TripleStreamChannelFuture streamChannelFuture, String data, boolean endStream) { return new TextDataQueueCommand(streamChannelFuture, data, endStream); } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Bzip2.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Bzip2.java index 5a53cb3f71..ab2c1bd3fe 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Bzip2.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Bzip2.java @@ -14,18 +14,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.compressor; -import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; -import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream; -import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.dubbo.rpc.RpcException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.OutputStream; +import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; +import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream; +import org.apache.commons.io.output.ByteArrayOutputStream; /** * bzip2 compressor, faster compression efficiency diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Compressor.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Compressor.java index 73a33f3fd9..4a67db5f6c 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Compressor.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Compressor.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.compressor; import org.apache.dubbo.common.extension.ExtensionScope; @@ -54,5 +53,4 @@ public interface Compressor extends MessageEncoding { byte[] compress(byte[] payloadByteArr); OutputStream decorate(OutputStream outputStream); - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/DeCompressor.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/DeCompressor.java index aa8c494040..c6ba092fb0 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/DeCompressor.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/DeCompressor.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.compressor; import org.apache.dubbo.common.extension.ExtensionScope; @@ -43,5 +42,4 @@ public interface DeCompressor extends MessageEncoding { * @return decompressed payload byte array */ byte[] decompress(byte[] payloadByteArr); - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Gzip.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Gzip.java index 168bc627aa..2623ded6b1 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Gzip.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Gzip.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.compressor; import org.apache.dubbo.rpc.RpcException; @@ -83,5 +82,4 @@ public class Gzip implements Compressor, DeCompressor { return byteOutStream.toByteArray(); } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Identity.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Identity.java index ee6d16a671..93fdd90521 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Identity.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Identity.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.compressor; import java.io.OutputStream; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/MessageEncoding.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/MessageEncoding.java index cdf2e0907c..9889be67a4 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/MessageEncoding.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/MessageEncoding.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.compressor; public interface MessageEncoding { diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Snappy.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Snappy.java index 2d1e9b08c2..26427bcc27 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Snappy.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Snappy.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.compressor; import org.apache.dubbo.rpc.RpcException; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/frame/Deframer.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/frame/Deframer.java index 66bb9e76e9..59083e9a24 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/frame/Deframer.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/frame/Deframer.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.frame; import io.netty.buffer.ByteBuf; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/frame/TriDecoder.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/frame/TriDecoder.java index 5fcfda427d..6970203cf8 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/frame/TriDecoder.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/frame/TriDecoder.java @@ -14,14 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.frame; +import org.apache.dubbo.rpc.RpcException; +import org.apache.dubbo.rpc.protocol.tri.compressor.DeCompressor; + import io.netty.buffer.ByteBuf; import io.netty.buffer.CompositeByteBuf; import io.netty.buffer.Unpooled; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.protocol.tri.compressor.DeCompressor; public class TriDecoder implements Deframer { @@ -155,7 +155,6 @@ public class TriDecoder implements Deframer { return data; } - private enum GrpcDecodeState { HEADER, PAYLOAD @@ -166,7 +165,5 @@ public class TriDecoder implements Deframer { void onRawMessage(byte[] data); void close(); - } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/AbstractServerCallListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/AbstractServerCallListener.java index 2ae592501c..689d9d03e3 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/AbstractServerCallListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/AbstractServerCallListener.java @@ -35,7 +35,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_TIM public abstract class AbstractServerCallListener implements ServerCallListener { - private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(AbstractServerCallListener.class); + private static final ErrorTypeAwareLogger LOGGER = + LoggerFactory.getErrorTypeAwareLogger(AbstractServerCallListener.class); protected final RpcInvocation invocation; @@ -43,9 +44,8 @@ public abstract class AbstractServerCallListener implements ServerCallListener { protected final StreamObserver responseObserver; - public AbstractServerCallListener(RpcInvocation invocation, - Invoker invoker, - StreamObserver responseObserver) { + public AbstractServerCallListener( + RpcInvocation invocation, Invoker invoker, StreamObserver responseObserver) { this.invocation = invocation; this.invoker = invoker; this.responseObserver = responseObserver; @@ -53,13 +53,13 @@ public abstract class AbstractServerCallListener implements ServerCallListener { public void invoke() { if (responseObserver instanceof Http2CancelableStreamObserver) { - RpcContext.restoreCancellationContext(((Http2CancelableStreamObserver) responseObserver).getCancellationContext()); + RpcContext.restoreCancellationContext( + ((Http2CancelableStreamObserver) responseObserver).getCancellationContext()); } - InetSocketAddress remoteAddress = (InetSocketAddress) invocation.getAttributes() - .remove(AbstractServerCall.REMOTE_ADDRESS_KEY); + InetSocketAddress remoteAddress = + (InetSocketAddress) invocation.getAttributes().remove(AbstractServerCall.REMOTE_ADDRESS_KEY); RpcContext.getServiceContext().setRemoteAddress(remoteAddress); - String remoteApp = (String) invocation.getAttributes() - .remove(TripleHeaderEnum.CONSUMER_APP_NAME_KEY); + String remoteApp = (String) invocation.getAttributes().remove(TripleHeaderEnum.CONSUMER_APP_NAME_KEY); if (null != remoteApp) { RpcContext.getServiceContext().setRemoteApplicationName(remoteApp); invocation.setAttachmentIfAbsent(REMOTE_APPLICATION_KEY, remoteApp); @@ -82,11 +82,13 @@ public abstract class AbstractServerCallListener implements ServerCallListener { final long cost = System.currentTimeMillis() - stInMillis; Long timeout = (Long) invocation.get("timeout"); if (timeout != null && timeout < cost) { - LOGGER.error(PROTOCOL_TIMEOUT_SERVER, "", "", String.format( - "Invoke timeout at server side, ignored to send response. service=%s method=%s cost=%s", - invocation.getTargetServiceUniqueName(), - invocation.getMethodName(), - cost)); + LOGGER.error( + PROTOCOL_TIMEOUT_SERVER, + "", + "", + String.format( + "Invoke timeout at server side, ignored to send response. service=%s method=%s cost=%s", + invocation.getTargetServiceUniqueName(), invocation.getMethodName(), cost)); HttpRequestTimeout serverSideTimeout = HttpRequestTimeout.serverSide(); responseObserver.onError(serverSideTimeout); return; @@ -106,5 +108,4 @@ public abstract class AbstractServerCallListener implements ServerCallListener { } public abstract void onReturn(Object value); - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/AbstractServerTransportListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/AbstractServerTransportListener.java index a80785ab13..4780dd008c 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/AbstractServerTransportListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/AbstractServerTransportListener.java @@ -66,9 +66,11 @@ import static org.apache.dubbo.common.constants.CommonConstants.HEADER_FILTER_KE import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_PARSE; -public abstract class AbstractServerTransportListener
    implements HttpTransportListener { +public abstract class AbstractServerTransportListener
    + implements HttpTransportListener { - private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(AbstractServerTransportListener.class); + private static final ErrorTypeAwareLogger LOGGER = + LoggerFactory.getErrorTypeAwareLogger(AbstractServerTransportListener.class); private final PathResolver pathResolver; @@ -104,12 +106,14 @@ public abstract class AbstractServerTransportListener
    getInvoker(HEADER metadata, String serviceName) { HttpHeaders headers = metadata.headers(); - final String version = - headers.containsKey(TripleHeaderEnum.SERVICE_VERSION.getHeader()) ? headers.get( - TripleHeaderEnum.SERVICE_VERSION.getHeader()).toString() : null; - final String group = - headers.containsKey(TripleHeaderEnum.SERVICE_GROUP.getHeader()) ? headers.get( - TripleHeaderEnum.SERVICE_GROUP.getHeader()).toString() : null; + final String version = headers.containsKey(TripleHeaderEnum.SERVICE_VERSION.getHeader()) + ? headers.get(TripleHeaderEnum.SERVICE_VERSION.getHeader()).toString() + : null; + final String group = headers.containsKey(TripleHeaderEnum.SERVICE_GROUP.getHeader()) + ? headers.get(TripleHeaderEnum.SERVICE_GROUP.getHeader()).toString() + : null; final String key = URL.buildKey(serviceName, group, version); Invoker invoker = pathResolver.resolve(key); if (invoker == null && TripleProtocol.RESOLVE_FALLBACK_TO_DEFAULT) { @@ -242,9 +247,9 @@ public abstract class AbstractServerTransportListener
    invoker, String serviceName, boolean hasStub) throws UnimplementedException { + private static ServiceDescriptor findServiceDescriptor(Invoker invoker, String serviceName, boolean hasStub) + throws UnimplementedException { ServiceDescriptor result; if (hasStub) { result = getStubServiceDescriptor(invoker.getUrl(), serviceName); @@ -265,7 +271,9 @@ public abstract class AbstractServerTransportListener
    invoker, - ServiceDescriptor serviceDescriptor, - MethodDescriptor methodDescriptor) { + protected RpcInvocation buildRpcInvocation( + Invoker invoker, ServiceDescriptor serviceDescriptor, MethodDescriptor methodDescriptor) { final URL url = invoker.getUrl(); - RpcInvocation inv = new RpcInvocation(url.getServiceModel(), - methodDescriptor.getMethodName(), - serviceDescriptor.getInterfaceName(), url.getProtocolServiceKey(), - methodDescriptor.getParameterClasses(), - new Object[0]); + RpcInvocation inv = new RpcInvocation( + url.getServiceModel(), + methodDescriptor.getMethodName(), + serviceDescriptor.getInterfaceName(), + url.getProtocolServiceKey(), + methodDescriptor.getParameterClasses(), + new Object[0]); inv.setTargetServiceUniqueName(url.getServiceKey()); inv.setReturnTypes(methodDescriptor.getReturnTypes()); Map headers = getHttpMetadata().headers().toSingleValueMap(); Map requestMetadata = headersToMap(headers, () -> { return Optional.ofNullable(headers.get(TripleHeaderEnum.TRI_HEADER_CONVERT.getHeader())) - .map(CharSequence::toString) - .orElse(null); + .map(CharSequence::toString) + .orElse(null); }); inv.setObjectAttachments(StreamUtils.toAttachments(requestMetadata)); inv.put("tri.remote.address", httpChannel.remoteAddress()); - //customizer RpcInvocation + // customizer RpcInvocation headerFilters.forEach(f -> f.invoke(invoker, inv)); return inv; } @@ -303,9 +312,7 @@ public abstract class AbstractServerTransportListener
    methodDescriptors = serviceDescriptor.getMethods(methodName); // try lower-case method if (CollectionUtils.isEmpty(methodDescriptors)) { - final String lowerMethod = - Character.toLowerCase(methodName.charAt(0)) + methodName.substring(1); + final String lowerMethod = Character.toLowerCase(methodName.charAt(0)) + methodName.substring(1); methodDescriptors = serviceDescriptor.getMethods(lowerMethod); } if (CollectionUtils.isEmpty(methodDescriptors)) { @@ -436,7 +444,8 @@ public abstract class AbstractServerTransportListener
    headersToMap(Map headers, Supplier convertUpperHeaderSupplier) { + protected Map headersToMap( + Map headers, Supplier convertUpperHeaderSupplier) { if (headers == null) { return Collections.emptyMap(); } @@ -444,10 +453,9 @@ public abstract class AbstractServerTransportListener
    header : headers.entrySet()) { String key = header.getKey(); if (key.endsWith(TripleConstant.HEADER_BIN_SUFFIX) - && key.length() > TripleConstant.HEADER_BIN_SUFFIX.length()) { + && key.length() > TripleConstant.HEADER_BIN_SUFFIX.length()) { try { - String realKey = key.substring(0, - key.length() - TripleConstant.HEADER_BIN_SUFFIX.length()); + String realKey = key.substring(0, key.length() - TripleConstant.HEADER_BIN_SUFFIX.length()); byte[] value = StreamUtils.decodeASCIIByte(header.getValue()); attachments.put(realKey, value); } catch (Exception e) { @@ -476,7 +484,11 @@ public abstract class AbstractServerTransportListener
    requestObserver; - public BiStreamServerCallListener(RpcInvocation invocation, - Invoker invoker, - FlowControlStreamObserver responseObserver) { + public BiStreamServerCallListener( + RpcInvocation invocation, Invoker invoker, FlowControlStreamObserver responseObserver) { super(invocation, invoker, responseObserver); - invocation.setArguments(new Object[]{responseObserver}); + invocation.setArguments(new Object[] {responseObserver}); invoke(); } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/DefaultHttpMessageListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/DefaultHttpMessageListener.java index 0ecab54e4f..d0e6cdb877 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/DefaultHttpMessageListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/DefaultHttpMessageListener.java @@ -24,9 +24,7 @@ public class DefaultHttpMessageListener implements HttpMessageListener { private ListeningDecoder listeningDecoder; - public DefaultHttpMessageListener() { - - } + public DefaultHttpMessageListener() {} public DefaultHttpMessageListener(ListeningDecoder listeningDecoder) { this.listeningDecoder = listeningDecoder; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/ServerCallToObserverAdapter.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/ServerCallToObserverAdapter.java index b463971087..7f9221182a 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/ServerCallToObserverAdapter.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/ServerCallToObserverAdapter.java @@ -21,5 +21,4 @@ import org.apache.dubbo.rpc.protocol.tri.ServerStreamObserver; public interface ServerCallToObserverAdapter extends ServerStreamObserver { void setExceptionCode(int exceptionCode); - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/ServerStreamServerCallListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/ServerStreamServerCallListener.java index 5a0e60969a..62fe3d7405 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/ServerStreamServerCallListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/ServerStreamServerCallListener.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.h12; import org.apache.dubbo.common.stream.StreamObserver; @@ -24,21 +23,20 @@ import org.apache.dubbo.rpc.RpcInvocation; public class ServerStreamServerCallListener extends AbstractServerCallListener { - public ServerStreamServerCallListener(RpcInvocation invocation, Invoker invoker, - StreamObserver responseObserver) { + public ServerStreamServerCallListener( + RpcInvocation invocation, Invoker invoker, StreamObserver responseObserver) { super(invocation, invoker, responseObserver); } @Override - public void onReturn(Object value) { - } + public void onReturn(Object value) {} @Override public void onMessage(Object message) { if (message instanceof Object[]) { message = ((Object[]) message)[0]; } - invocation.setArguments(new Object[]{message, responseObserver}); + invocation.setArguments(new Object[] {message, responseObserver}); } @Override diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/TripleProtocolDetector.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/TripleProtocolDetector.java index c6c7128ab1..9c7cd7138e 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/TripleProtocolDetector.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/TripleProtocolDetector.java @@ -16,12 +16,13 @@ */ package org.apache.dubbo.rpc.protocol.tri.h12; -import io.netty.handler.codec.http2.Http2CodecUtil; import org.apache.dubbo.remoting.api.ProtocolDetector; import org.apache.dubbo.remoting.buffer.ByteBufferBackedChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBuffers; +import io.netty.handler.codec.http2.Http2CodecUtil; + import static java.lang.Math.min; public class TripleProtocolDetector implements ProtocolDetector { @@ -29,11 +30,11 @@ public class TripleProtocolDetector implements ProtocolDetector { public static final String HTTP_VERSION = "HTTP_VERSION"; private final ChannelBuffer clientPrefaceString = new ByteBufferBackedChannelBuffer( - Http2CodecUtil.connectionPrefaceBuf().nioBuffer()); + Http2CodecUtil.connectionPrefaceBuf().nioBuffer()); @Override public Result detect(ChannelBuffer in) { - //http1 + // http1 if (in.readableBytes() < 2) { return Result.needMoreData(); } @@ -46,7 +47,7 @@ public class TripleProtocolDetector implements ProtocolDetector { } in.resetReaderIndex(); - //http2 + // http2 int prefaceLen = clientPrefaceString.readableBytes(); int bytesRead = min(in.readableBytes(), prefaceLen); if (bytesRead == 0 || !ChannelBuffers.prefixEquals(in, clientPrefaceString, bytesRead)) { diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/UnaryServerCallListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/UnaryServerCallListener.java index f933020ddd..8c32c30031 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/UnaryServerCallListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/UnaryServerCallListener.java @@ -26,9 +26,8 @@ public class UnaryServerCallListener extends AbstractServerCallListener { private boolean applyCustomizeException = false; - public UnaryServerCallListener(RpcInvocation invocation, - Invoker invoker, - StreamObserver responseObserver) { + public UnaryServerCallListener( + RpcInvocation invocation, Invoker invoker, StreamObserver responseObserver) { super(invocation, invoker, responseObserver); } @@ -47,7 +46,7 @@ public class UnaryServerCallListener extends AbstractServerCallListener { if (message instanceof Object[]) { invocation.setArguments((Object[]) message); } else { - invocation.setArguments(new Object[]{message}); + invocation.setArguments(new Object[] {message}); } } @@ -66,12 +65,11 @@ public class UnaryServerCallListener extends AbstractServerCallListener { } else { super.onResponseException(t); } - } @Override public void onCancel(long code) { - //ignore + // ignore } @Override diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcCompositeCodec.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcCompositeCodec.java index 48171cf234..2c5041d6c8 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcCompositeCodec.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcCompositeCodec.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.tri.h12.grpc; -import com.google.protobuf.Message; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.http12.exception.DecodeException; import org.apache.dubbo.remoting.http12.exception.EncodeException; @@ -27,6 +26,8 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import com.google.protobuf.Message; + import static org.apache.dubbo.common.constants.CommonConstants.PROTOBUF_MESSAGE_CLASS_NAME; /** @@ -44,8 +45,8 @@ public class GrpcCompositeCodec implements HttpMessageCodec { private final WrapperHttpMessageCodec wrapperHttpMessageCodec; - public GrpcCompositeCodec(ProtobufHttpMessageCodec protobufHttpMessageCodec, - WrapperHttpMessageCodec wrapperHttpMessageCodec) { + public GrpcCompositeCodec( + ProtobufHttpMessageCodec protobufHttpMessageCodec, WrapperHttpMessageCodec wrapperHttpMessageCodec) { this.protobufHttpMessageCodec = protobufHttpMessageCodec; this.wrapperHttpMessageCodec = wrapperHttpMessageCodec; } @@ -58,11 +59,11 @@ public class GrpcCompositeCodec implements HttpMessageCodec { this.wrapperHttpMessageCodec.setDecodeTypes(decodeTypes); } - @Override public void encode(OutputStream outputStream, Object data) throws EncodeException { - //protobuf - //TODO int compressed = Identity.MESSAGE_ENCODING.equals(requestMetadata.compressor.getMessageEncoding()) ? 0 : 1; + // protobuf + // TODO int compressed = Identity.MESSAGE_ENCODING.equals(requestMetadata.compressor.getMessageEncoding()) ? 0 : + // 1; try { int compressed = 0; outputStream.write(compressed); @@ -70,7 +71,7 @@ public class GrpcCompositeCodec implements HttpMessageCodec { ProtobufWriter.write(protobufHttpMessageCodec, outputStream, data); return; } - //wrapper + // wrapper wrapperHttpMessageCodec.encode(outputStream, data); } catch (IOException e) { throw new EncodeException(e); @@ -143,10 +144,9 @@ public class GrpcCompositeCodec implements HttpMessageCodec { private static void write(HttpMessageCodec codec, OutputStream outputStream, Object data) { int serializedSize = ((Message) data).getSerializedSize(); - //write length + // write length writeLength(outputStream, serializedSize); codec.encode(outputStream, data); } - } } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcHeaderNames.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcHeaderNames.java index 030cb53259..174a1756f4 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcHeaderNames.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcHeaderNames.java @@ -17,7 +17,6 @@ package org.apache.dubbo.rpc.protocol.tri.h12.grpc; public enum GrpcHeaderNames { - GRPC_STATUS("grpc-status"), GRPC_MESSAGE("grpc-message"), GRPC_ENCODING("grpc-encoding"), diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcHttp2ServerTransportListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcHttp2ServerTransportListener.java index 43ae3ec817..d8f7655e54 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcHttp2ServerTransportListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcHttp2ServerTransportListener.java @@ -51,7 +51,8 @@ import java.util.Objects; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_PARSE; -public class GrpcHttp2ServerTransportListener extends GenericHttp2ServerTransportListener implements Http2TransportListener { +public class GrpcHttp2ServerTransportListener extends GenericHttp2ServerTransportListener + implements Http2TransportListener { private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(AbstractServerCall.class); @@ -73,12 +74,13 @@ public class GrpcHttp2ServerTransportListener extends GenericHttp2ServerTranspor } private static String httpStatusToGrpcStatus(Throwable throwable) { - //http status code map to grpc status code + // http status code map to grpc status code return String.valueOf(TriRpcStatus.INTERNAL.code.code); } @Override - protected RpcInvocation buildRpcInvocation(Invoker invoker, ServiceDescriptor serviceDescriptor, MethodDescriptor methodDescriptor) { + protected RpcInvocation buildRpcInvocation( + Invoker invoker, ServiceDescriptor serviceDescriptor, MethodDescriptor methodDescriptor) { RpcInvocation rpcInvocation = super.buildRpcInvocation(invoker, serviceDescriptor, methodDescriptor); HttpHeaders headers = getHttpMetadata().headers(); String timeoutString = headers.getFirst(GrpcHeaderNames.GRPC_TIMEOUT.getName()); @@ -88,8 +90,15 @@ public class GrpcHttp2ServerTransportListener extends GenericHttp2ServerTranspor rpcInvocation.put("timeout", timeout); } } catch (Throwable t) { - LOGGER.warn(PROTOCOL_FAILED_PARSE, "", "", String.format("Failed to parse request timeout set from:%s, service=%s " - + "method=%s", timeoutString, serviceDescriptor.getInterfaceName(), getMethodDescriptor().getMethodName())); + LOGGER.warn( + PROTOCOL_FAILED_PARSE, + "", + "", + String.format( + "Failed to parse request timeout set from:%s, service=%s " + "method=%s", + timeoutString, + serviceDescriptor.getInterfaceName(), + getMethodDescriptor().getMethodName())); } return rpcInvocation; } @@ -119,10 +128,10 @@ public class GrpcHttp2ServerTransportListener extends GenericHttp2ServerTranspor String messageEncoding = metadata.headers().getFirst(GrpcHeaderNames.GRPC_ENCODING.getName()); if (null != messageEncoding) { if (!Identity.MESSAGE_ENCODING.equals(messageEncoding)) { - DeCompressor compressor = DeCompressor.getCompressor(getFrameworkModel(), - messageEncoding); + DeCompressor compressor = DeCompressor.getCompressor(getFrameworkModel(), messageEncoding); if (null == compressor) { - throw new UnimplementedException(GrpcHeaderNames.GRPC_ENCODING.getName() + " '" + messageEncoding + "'"); + throw new UnimplementedException( + GrpcHeaderNames.GRPC_ENCODING.getName() + " '" + messageEncoding + "'"); } getStreamingDecoder().setDeCompressor(compressor); } @@ -153,9 +162,7 @@ public class GrpcHttp2ServerTransportListener extends GenericHttp2ServerTranspor private class DetermineMethodDescriptorListener implements StreamingDecoder.FragmentListener { @Override - public void onFragmentMessage(InputStream rawMessage) { - - } + public void onFragmentMessage(InputStream rawMessage) {} @Override public void onClose() { @@ -165,7 +172,8 @@ public class GrpcHttp2ServerTransportListener extends GenericHttp2ServerTranspor @Override public void onFragmentMessage(InputStream dataHeader, InputStream rawMessage) { try { - ByteArrayOutputStream merge = new ByteArrayOutputStream(dataHeader.available() + rawMessage.available()); + ByteArrayOutputStream merge = + new ByteArrayOutputStream(dataHeader.available() + rawMessage.available()); transferToOutputStream(merge, dataHeader); ByteArrayOutputStream bos = new ByteArrayOutputStream(rawMessage.available()); transferToOutputStream(bos, rawMessage); @@ -178,11 +186,12 @@ public class GrpcHttp2ServerTransportListener extends GenericHttp2ServerTranspor String originalMethodName = parts[2]; methodDescriptor = findReflectionMethodDescriptor(getServiceDescriptor(), originalMethodName); if (methodDescriptor == null) { - List methodDescriptors = getServiceDescriptor().getMethods(originalMethodName); + List methodDescriptors = + getServiceDescriptor().getMethods(originalMethodName); final TripleCustomerProtocolWapper.TripleRequestWrapper request; request = TripleCustomerProtocolWapper.TripleRequestWrapper.parseFrom(data); final String[] paramTypes = request.getArgTypes() - .toArray(new String[request.getArgs().size()]); + .toArray(new String[request.getArgs().size()]); // wrapper mode the method can overload so maybe list for (MethodDescriptor descriptor : methodDescriptors) { // params type is array @@ -198,10 +207,12 @@ public class GrpcHttp2ServerTransportListener extends GenericHttp2ServerTranspor setMethodDescriptor(methodDescriptor); setMethodMetadata(MethodMetadata.fromMethodDescriptor(methodDescriptor)); setRpcInvocation(buildRpcInvocation(getInvoker(), getServiceDescriptor(), methodDescriptor)); - //replace decoder - HttpMessageListener httpMessageListener = GrpcHttp2ServerTransportListener.super.newHttpMessageListener(); + // replace decoder + HttpMessageListener httpMessageListener = + GrpcHttp2ServerTransportListener.super.newHttpMessageListener(); GrpcCompositeCodec grpcCompositeCodec = (GrpcCompositeCodec) getHttpMessageCodec(); - grpcCompositeCodec.setEncodeTypes(new Class[]{getMethodMetadata().getActualResponseType()}); + grpcCompositeCodec.setEncodeTypes( + new Class[] {getMethodMetadata().getActualResponseType()}); grpcCompositeCodec.setDecodeTypes(getMethodMetadata().getActualRequestTypes()); setHttpMessageListener(httpMessageListener); } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcUtils.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcUtils.java index 2689824a6f..889b387071 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcUtils.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/GrpcUtils.java @@ -22,9 +22,7 @@ import java.util.concurrent.TimeUnit; public class GrpcUtils { - private GrpcUtils() { - - } + private GrpcUtils() {} public static Long parseTimeoutToMills(String timeoutVal) { if (StringUtils.isEmpty(timeoutVal) || StringUtils.isContains(timeoutVal, "null")) { @@ -50,5 +48,4 @@ public class GrpcUtils { return null; } } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/StreamingHttpMessageListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/StreamingHttpMessageListener.java index bbcac87d43..77b860fca2 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/StreamingHttpMessageListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/StreamingHttpMessageListener.java @@ -25,8 +25,7 @@ public class StreamingHttpMessageListener implements HttpMessageListener { private StreamingDecoder streamingDecoder; - public StreamingHttpMessageListener() { - } + public StreamingHttpMessageListener() {} public StreamingHttpMessageListener(StreamingDecoder streamingDecoder) { this.streamingDecoder = streamingDecoder; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/WrapperHttpMessageCodec.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/WrapperHttpMessageCodec.java index 21a7a428f6..ea68580736 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/WrapperHttpMessageCodec.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/grpc/WrapperHttpMessageCodec.java @@ -52,9 +52,8 @@ public class WrapperHttpMessageCodec implements HttpMessageCodec { public WrapperHttpMessageCodec(URL url, FrameworkModel frameworkModel) { this.url = url; this.serialization = frameworkModel - .getExtensionLoader(MultipleSerialization.class) - .getExtension(url.getParameter(Constants.MULTI_SERIALIZATION_KEY, - CommonConstants.DEFAULT_KEY)); + .getExtensionLoader(MultipleSerialization.class) + .getExtension(url.getParameter(Constants.MULTI_SERIALIZATION_KEY, CommonConstants.DEFAULT_KEY)); } public void setSerializeType(String serializeType) { @@ -75,11 +74,11 @@ public class WrapperHttpMessageCodec implements HttpMessageCodec { ByteArrayOutputStream bos = new ByteArrayOutputStream(); serialization.serialize(url, serializeType, encodeTypes[0], data, bos); byte[] encoded = TripleCustomerProtocolWapper.TripleResponseWrapper.Builder.newBuilder() - .setSerializeType(serializeType) - .setType(encodeTypes[0].getName()) - .setData(bos.toByteArray()) - .build() - .toByteArray(); + .setSerializeType(serializeType) + .setType(encodeTypes[0].getName()) + .setData(bos.toByteArray()) + .build() + .toByteArray(); writeLength(outputStream, encoded.length); outputStream.write(encoded); } catch (IOException e) { @@ -89,12 +88,12 @@ public class WrapperHttpMessageCodec implements HttpMessageCodec { @Override public void encode(OutputStream outputStream, Object[] data) throws EncodeException { - //TODO + // TODO } @Override public Object decode(InputStream inputStream, Class targetType) throws DecodeException { - Object[] decode = this.decode(inputStream, new Class[]{targetType}); + Object[] decode = this.decode(inputStream, new Class[] {targetType}); if (decode == null || decode.length == 0) { return null; } @@ -110,13 +109,13 @@ public class WrapperHttpMessageCodec implements HttpMessageCodec { while ((len = inputStream.read(data)) != -1) { bos.write(data, 0, len); } - TripleCustomerProtocolWapper.TripleRequestWrapper wrapper = TripleCustomerProtocolWapper.TripleRequestWrapper.parseFrom( - bos.toByteArray()); + TripleCustomerProtocolWapper.TripleRequestWrapper wrapper = + TripleCustomerProtocolWapper.TripleRequestWrapper.parseFrom(bos.toByteArray()); setSerializeType(wrapper.getSerializeType()); Object[] ret = new Object[wrapper.getArgs().size()]; for (int i = 0; i < wrapper.getArgs().size(); i++) { - ByteArrayInputStream in = new ByteArrayInputStream( - wrapper.getArgs().get(i)); + ByteArrayInputStream in = + new ByteArrayInputStream(wrapper.getArgs().get(i)); try { ret[i] = this.serialization.deserialize(url, wrapper.getSerializeType(), targetTypes[i], in); } catch (ClassNotFoundException e) { diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http1/DefaultHttp11ServerTransportListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http1/DefaultHttp11ServerTransportListener.java index c7d34b1a87..2253fb6e22 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http1/DefaultHttp11ServerTransportListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http1/DefaultHttp11ServerTransportListener.java @@ -41,7 +41,9 @@ import org.apache.dubbo.rpc.protocol.tri.h12.ServerCallListener; import org.apache.dubbo.rpc.protocol.tri.h12.ServerStreamServerCallListener; import org.apache.dubbo.rpc.protocol.tri.h12.UnaryServerCallListener; -public class DefaultHttp11ServerTransportListener extends AbstractServerTransportListener implements Http1ServerTransportListener { +public class DefaultHttp11ServerTransportListener + extends AbstractServerTransportListener + implements Http1ServerTransportListener { private final HttpChannel httpChannel; @@ -53,18 +55,19 @@ public class DefaultHttp11ServerTransportListener extends AbstractServerTranspor this.httpChannel = httpChannel; } - private ServerCallListener startListener(RpcInvocation invocation, - MethodDescriptor methodDescriptor, - Invoker invoker) { + private ServerCallListener startListener( + RpcInvocation invocation, MethodDescriptor methodDescriptor, Invoker invoker) { switch (methodDescriptor.getRpcType()) { case UNARY: Http1ServerChannelObserver http1ChannelObserver = new Http1ServerChannelObserver(httpChannel); http1ChannelObserver.setHttpMessageCodec(getHttpMessageCodec()); return new AutoCompleteUnaryServerCallListener(invocation, invoker, http1ChannelObserver); case SERVER_STREAM: - Http1ServerChannelObserver serverStreamChannelObserver = new Http1ServerStreamChannelObserver(httpChannel); + Http1ServerChannelObserver serverStreamChannelObserver = + new Http1ServerStreamChannelObserver(httpChannel); serverStreamChannelObserver.setHttpMessageCodec(getHttpMessageCodec()); - serverStreamChannelObserver.setHeadersCustomizer((headers) -> headers.set(HttpHeaderNames.CONTENT_TYPE.getName(), MediaType.TEXT_EVENT_STREAM_VALUE.getName())); + serverStreamChannelObserver.setHeadersCustomizer((headers) -> headers.set( + HttpHeaderNames.CONTENT_TYPE.getName(), MediaType.TEXT_EVENT_STREAM_VALUE.getName())); return new AutoCompleteServerStreamServerCallListener(invocation, invoker, serverStreamChannelObserver); default: throw new UnsupportedOperationException("HTTP1.x only support unary and server-stream"); @@ -85,7 +88,8 @@ public class DefaultHttp11ServerTransportListener extends AbstractServerTranspor setMethodMetadata(methodMetadata); setRpcInvocation(rpcInvocation); HttpMessageCodec httpMessageCodec = getHttpMessageCodec(); - ListeningDecoder listeningDecoder = newListeningDecoder(httpMessageCodec, methodMetadata.getActualRequestTypes()); + ListeningDecoder listeningDecoder = + newListeningDecoder(httpMessageCodec, methodMetadata.getActualRequestTypes()); return new DefaultHttpMessageListener(listeningDecoder); } @@ -98,7 +102,8 @@ public class DefaultHttp11ServerTransportListener extends AbstractServerTranspor private static class AutoCompleteUnaryServerCallListener extends UnaryServerCallListener { - public AutoCompleteUnaryServerCallListener(RpcInvocation invocation, Invoker invoker, StreamObserver responseObserver) { + public AutoCompleteUnaryServerCallListener( + RpcInvocation invocation, Invoker invoker, StreamObserver responseObserver) { super(invocation, invoker, responseObserver); } @@ -111,7 +116,8 @@ public class DefaultHttp11ServerTransportListener extends AbstractServerTranspor private static class AutoCompleteServerStreamServerCallListener extends ServerStreamServerCallListener { - public AutoCompleteServerStreamServerCallListener(RpcInvocation invocation, Invoker invoker, StreamObserver responseObserver) { + public AutoCompleteServerStreamServerCallListener( + RpcInvocation invocation, Invoker invoker, StreamObserver responseObserver) { super(invocation, invoker, responseObserver); } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http1/DefaultHttp11ServerTransportListenerFactory.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http1/DefaultHttp11ServerTransportListenerFactory.java index cddeb4182e..042a7af719 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http1/DefaultHttp11ServerTransportListenerFactory.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http1/DefaultHttp11ServerTransportListenerFactory.java @@ -24,7 +24,8 @@ import org.apache.dubbo.rpc.model.FrameworkModel; public class DefaultHttp11ServerTransportListenerFactory implements Http1ServerTransportListenerFactory { - public static final Http1ServerTransportListenerFactory INSTANCE = new DefaultHttp11ServerTransportListenerFactory(); + public static final Http1ServerTransportListenerFactory INSTANCE = + new DefaultHttp11ServerTransportListenerFactory(); @Override public Http1ServerTransportListener newInstance(HttpChannel httpChannel, URL url, FrameworkModel frameworkModel) { diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/GenericHttp2ServerTransportListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/GenericHttp2ServerTransportListener.java index bb09853da2..c4b4f46007 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/GenericHttp2ServerTransportListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/GenericHttp2ServerTransportListener.java @@ -50,7 +50,8 @@ import org.apache.dubbo.rpc.protocol.tri.h12.grpc.StreamingHttpMessageListener; import java.util.concurrent.Executor; -public class GenericHttp2ServerTransportListener extends AbstractServerTransportListener implements Http2TransportListener { +public class GenericHttp2ServerTransportListener extends AbstractServerTransportListener + implements Http2TransportListener { private final Http2ServerChannelObserver serverChannelObserver; @@ -62,10 +63,12 @@ public class GenericHttp2ServerTransportListener extends AbstractServerTransport private ServerCallListener serverCallListener; - public GenericHttp2ServerTransportListener(H2StreamChannel h2StreamChannel, URL url, FrameworkModel frameworkModel) { + public GenericHttp2ServerTransportListener( + H2StreamChannel h2StreamChannel, URL url, FrameworkModel frameworkModel) { super(frameworkModel, url, h2StreamChannel); this.h2StreamChannel = h2StreamChannel; - this.executorSupport = ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()).getExecutorSupport(url); + this.executorSupport = ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()) + .getExecutorSupport(url); this.streamingDecoder = newStreamingDecoder(); this.serverChannelObserver = new Http2ServerCallToObserverAdapter(frameworkModel, h2StreamChannel); this.serverChannelObserver.setHttpMessageCodec(JsonCodec.INSTANCE); @@ -78,9 +81,8 @@ public class GenericHttp2ServerTransportListener extends AbstractServerTransport return new SerializingExecutor(executor); } - private ServerCallListener startListener(RpcInvocation invocation, - MethodDescriptor methodDescriptor, - Invoker invoker) { + private ServerCallListener startListener( + RpcInvocation invocation, MethodDescriptor methodDescriptor, Invoker invoker) { Http2ServerChannelObserver responseObserver = getServerChannelObserver(); CancellationContext cancellationContext = RpcContext.getCancellationContext(); responseObserver.setCancellationContext(cancellationContext); @@ -90,7 +92,10 @@ public class GenericHttp2ServerTransportListener extends AbstractServerTransport boolean hasStub = getPathResolver().hasNativeStub(httpMetadata.path()); boolean applyCustomizeException = false; if (!hasStub) { - applyCustomizeException = ReflectionPackableMethod.needWrap(methodDescriptor, getMethodMetadata().getActualRequestTypes(), getMethodMetadata().getActualResponseType()); + applyCustomizeException = ReflectionPackableMethod.needWrap( + methodDescriptor, + getMethodMetadata().getActualRequestTypes(), + getMethodMetadata().getActualResponseType()); } UnaryServerCallListener unaryServerCallListener = startUnary(invocation, invoker, responseObserver); unaryServerCallListener.setApplyCustomizeException(applyCustomizeException); @@ -116,7 +121,7 @@ public class GenericHttp2ServerTransportListener extends AbstractServerTransport } protected StreamingDecoder newStreamingDecoder() { - //default no op + // default no op return new NoOpStreamingDecoder(); } @@ -148,7 +153,8 @@ public class GenericHttp2ServerTransportListener extends AbstractServerTransport setRpcInvocation(buildRpcInvocation(getInvoker(), getServiceDescriptor(), methodDescriptor)); } initializeServerCallListener(); - DefaultListeningDecoder defaultListeningDecoder = new DefaultListeningDecoder(getHttpMessageCodec(), getMethodMetadata().getActualRequestTypes()); + DefaultListeningDecoder defaultListeningDecoder = new DefaultListeningDecoder( + getHttpMessageCodec(), getMethodMetadata().getActualRequestTypes()); defaultListeningDecoder.setListener(new Http2StreamingDecodeListener(serverCallListener)); streamingDecoder.setFragmentListener(new StreamingDecoder.DefaultFragmentListener(defaultListeningDecoder)); getServerChannelObserver().setStreamingDecoder(streamingDecoder); @@ -203,17 +209,18 @@ public class GenericHttp2ServerTransportListener extends AbstractServerTransport } } - private UnaryServerCallListener startUnary(RpcInvocation invocation, - Invoker invoker, - Http2ServerChannelObserver responseObserver) { + private UnaryServerCallListener startUnary( + RpcInvocation invocation, Invoker invoker, Http2ServerChannelObserver responseObserver) { return new UnaryServerCallListener(invocation, invoker, responseObserver); } - private ServerStreamServerCallListener startServerStreaming(RpcInvocation invocation, Invoker invoker, Http2ServerChannelObserver responseObserver) { + private ServerStreamServerCallListener startServerStreaming( + RpcInvocation invocation, Invoker invoker, Http2ServerChannelObserver responseObserver) { return new ServerStreamServerCallListener(invocation, invoker, responseObserver); } - private BiStreamServerCallListener startBiStreaming(RpcInvocation invocation, Invoker invoker, Http2ServerChannelObserver responseObserver) { + private BiStreamServerCallListener startBiStreaming( + RpcInvocation invocation, Invoker invoker, Http2ServerChannelObserver responseObserver) { return new BiStreamServerCallListener(invocation, invoker, responseObserver); } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/GenericHttp2ServerTransportListenerFactory.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/GenericHttp2ServerTransportListenerFactory.java index f6e6841311..5faa17595d 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/GenericHttp2ServerTransportListenerFactory.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/GenericHttp2ServerTransportListenerFactory.java @@ -27,9 +27,7 @@ public class GenericHttp2ServerTransportListenerFactory implements Http2ServerTr public static final Http2ServerTransportListenerFactory INSTANCE = new GenericHttp2ServerTransportListenerFactory(); @Override - public Http2TransportListener newInstance(H2StreamChannel streamChannel, - URL url, - FrameworkModel frameworkModel) { + public Http2TransportListener newInstance(H2StreamChannel streamChannel, URL url, FrameworkModel frameworkModel) { return new GenericHttp2ServerTransportListener(streamChannel, url, frameworkModel); } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/Http2ServerCallToObserverAdapter.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/Http2ServerCallToObserverAdapter.java index 932f94563b..62ae0ad1a0 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/Http2ServerCallToObserverAdapter.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/Http2ServerCallToObserverAdapter.java @@ -20,7 +20,8 @@ import org.apache.dubbo.remoting.http12.h2.H2StreamChannel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.tri.h12.ServerCallToObserverAdapter; -public class Http2ServerCallToObserverAdapter extends Http2ServerStreamObserver implements ServerCallToObserverAdapter { +public class Http2ServerCallToObserverAdapter extends Http2ServerStreamObserver + implements ServerCallToObserverAdapter { private int exceptionCode; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/Http2ServerStreamObserver.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/Http2ServerStreamObserver.java index 03dab446f3..8460ee3df1 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/Http2ServerStreamObserver.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http2/Http2ServerStreamObserver.java @@ -31,7 +31,8 @@ import org.apache.dubbo.rpc.protocol.tri.stream.StreamUtils; import java.util.Map; -public class Http2ServerStreamObserver extends Http2ServerChannelObserver implements ServerStreamObserver, AttachmentHolder { +public class Http2ServerStreamObserver extends Http2ServerChannelObserver + implements ServerStreamObserver, AttachmentHolder { private final FrameworkModel frameworkModel; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/CallStreamObserver.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/CallStreamObserver.java index 362ab9ed4b..d7d74dfb88 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/CallStreamObserver.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/CallStreamObserver.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.observer; import org.apache.dubbo.common.stream.StreamObserver; @@ -22,7 +21,6 @@ import org.apache.dubbo.rpc.protocol.tri.compressor.Compressor; public interface CallStreamObserver extends StreamObserver { - /** * Requests the peer to produce {@code count} more messages to be delivered to the 'inbound' * {@link StreamObserver}. @@ -50,5 +48,4 @@ public interface CallStreamObserver extends StreamObserver { * specified. */ void disableAutoFlowControl(); - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/ClientCallToObserverAdapter.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/ClientCallToObserverAdapter.java index 37f17694c3..9f9b054029 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/ClientCallToObserverAdapter.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/ClientCallToObserverAdapter.java @@ -14,15 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.observer; import org.apache.dubbo.rpc.protocol.tri.CancelableStreamObserver; import org.apache.dubbo.rpc.protocol.tri.ClientStreamObserver; import org.apache.dubbo.rpc.protocol.tri.call.ClientCall; -public class ClientCallToObserverAdapter extends CancelableStreamObserver implements - ClientStreamObserver { +public class ClientCallToObserverAdapter extends CancelableStreamObserver implements ClientStreamObserver { private final ClientCall call; private boolean terminated; @@ -38,8 +36,7 @@ public class ClientCallToObserverAdapter extends CancelableStreamObserver @Override public void onNext(Object data) { if (terminated) { - throw new IllegalStateException( - "Stream observer has been terminated, no more data is allowed"); + throw new IllegalStateException("Stream observer has been terminated, no more data is allowed"); } call.sendMessage(data); } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/ServerCallToObserverAdapter.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/ServerCallToObserverAdapter.java index f2ae04ac8c..f0d84f1939 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/ServerCallToObserverAdapter.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/observer/ServerCallToObserverAdapter.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.observer; import org.apache.dubbo.common.constants.CommonConstants; @@ -28,8 +27,7 @@ import org.apache.dubbo.rpc.protocol.tri.call.AbstractServerCall; import java.util.Map; -public class ServerCallToObserverAdapter extends CancelableStreamObserver implements - ServerStreamObserver { +public class ServerCallToObserverAdapter extends CancelableStreamObserver implements ServerStreamObserver { private static final Logger LOGGER = LoggerFactory.getLogger(CancelableStreamObserver.class); public final CancellationContext cancellationContext; @@ -57,8 +55,7 @@ public class ServerCallToObserverAdapter extends CancelableStreamObserver isNeedReturnException = needReturnException; } - public ServerCallToObserverAdapter(AbstractServerCall call, - CancellationContext cancellationContext) { + public ServerCallToObserverAdapter(AbstractServerCall call, CancellationContext cancellationContext) { this.call = call; this.cancellationContext = cancellationContext; } @@ -67,7 +64,6 @@ public class ServerCallToObserverAdapter extends CancelableStreamObserver return call.isAutoRequestN(); } - public boolean isTerminated() { return terminated; } @@ -79,8 +75,7 @@ public class ServerCallToObserverAdapter extends CancelableStreamObserver @Override public void onNext(Object data) { if (isTerminated()) { - throw new IllegalStateException( - "Stream observer has been terminated, no more data is allowed"); + throw new IllegalStateException("Stream observer has been terminated, no more data is allowed"); } call.setExceptionCode(exceptionCode); call.setNeedReturnException(isNeedReturnException); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/HealthStatusManager.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/HealthStatusManager.java index be4fbc8301..9b8e970803 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/HealthStatusManager.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/HealthStatusManager.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.service; import io.grpc.health.v1.Health; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/ReflectionV1AlphaService.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/ReflectionV1AlphaService.java index b1a2659eb6..9217d4ff2d 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/ReflectionV1AlphaService.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/ReflectionV1AlphaService.java @@ -14,12 +14,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.service; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.rpc.TriRpcStatus; +import java.util.ArrayDeque; +import java.util.HashSet; +import java.util.Queue; +import java.util.Set; + import com.google.protobuf.Descriptors.FileDescriptor; import io.grpc.reflection.v1alpha.DubboServerReflectionTriple; import io.grpc.reflection.v1alpha.ErrorResponse; @@ -31,11 +35,6 @@ import io.grpc.reflection.v1alpha.ServerReflectionRequest; import io.grpc.reflection.v1alpha.ServerReflectionResponse; import io.grpc.reflection.v1alpha.ServiceResponse; -import java.util.ArrayDeque; -import java.util.HashSet; -import java.util.Queue; -import java.util.Set; - /** * Provides a reflection service for Protobuf service for service test and dynamic gateway. * @@ -43,10 +42,9 @@ import java.util.Set; */ public class ReflectionV1AlphaService extends DubboServerReflectionTriple.ServerReflectionImplBase { - @Override public StreamObserver serverReflectionInfo( - StreamObserver responseObserver) { + StreamObserver responseObserver) { return new StreamObserver() { @Override public void onNext(ServerReflectionRequest request) { @@ -68,9 +66,10 @@ public class ReflectionV1AlphaService extends DubboServerReflectionTriple.Server break; default: sendErrorResponse( - request, - TriRpcStatus.Code.UNIMPLEMENTED, - "not implemented " + request.getMessageRequestCase(), responseObserver); + request, + TriRpcStatus.Code.UNIMPLEMENTED, + "not implemented " + request.getMessageRequestCase(), + responseObserver); } } @@ -86,75 +85,66 @@ public class ReflectionV1AlphaService extends DubboServerReflectionTriple.Server }; } - private void getFileByName(ServerReflectionRequest request, - StreamObserver responseObserver) { + private void getFileByName( + ServerReflectionRequest request, StreamObserver responseObserver) { String name = request.getFileByFilename(); FileDescriptor fd = SchemaDescriptorRegistry.getSchemaDescriptor(name); if (fd != null) { responseObserver.onNext(createServerReflectionResponse(request, fd)); } else { - sendErrorResponse(request, TriRpcStatus.Code.NOT_FOUND, "File not found.", - responseObserver); + sendErrorResponse(request, TriRpcStatus.Code.NOT_FOUND, "File not found.", responseObserver); } } - private void getFileContainingSymbol(ServerReflectionRequest request, - StreamObserver responseObserver) { + private void getFileContainingSymbol( + ServerReflectionRequest request, StreamObserver responseObserver) { String symbol = request.getFileContainingSymbol(); FileDescriptor fd = SchemaDescriptorRegistry.getSchemaDescriptor(symbol); if (fd != null) { responseObserver.onNext(createServerReflectionResponse(request, fd)); } else { - sendErrorResponse(request, TriRpcStatus.Code.NOT_FOUND, "Symbol not found.", - responseObserver); + sendErrorResponse(request, TriRpcStatus.Code.NOT_FOUND, "Symbol not found.", responseObserver); } } - private void getFileByExtension(ServerReflectionRequest request, - StreamObserver responseObserver) { + private void getFileByExtension( + ServerReflectionRequest request, StreamObserver responseObserver) { ExtensionRequest extensionRequest = request.getFileContainingExtension(); String type = extensionRequest.getContainingType(); int extension = extensionRequest.getExtensionNumber(); - FileDescriptor fd = - SchemaDescriptorRegistry.getFileDescriptorByExtensionAndNumber(type, extension); + FileDescriptor fd = SchemaDescriptorRegistry.getFileDescriptorByExtensionAndNumber(type, extension); if (fd != null) { responseObserver.onNext(createServerReflectionResponse(request, fd)); } else { - sendErrorResponse(request, TriRpcStatus.Code.NOT_FOUND, "Extension not found.", - responseObserver); + sendErrorResponse(request, TriRpcStatus.Code.NOT_FOUND, "Extension not found.", responseObserver); } } - private void getAllExtensions(ServerReflectionRequest request, - StreamObserver responseObserver) { + private void getAllExtensions( + ServerReflectionRequest request, StreamObserver responseObserver) { String type = request.getAllExtensionNumbersOfType(); Set extensions = SchemaDescriptorRegistry.getExtensionNumbers(type); if (extensions != null) { ExtensionNumberResponse.Builder builder = - ExtensionNumberResponse.newBuilder() - .setBaseTypeName(type) - .addAllExtensionNumber(extensions); - responseObserver.onNext( - ServerReflectionResponse.newBuilder() + ExtensionNumberResponse.newBuilder().setBaseTypeName(type).addAllExtensionNumber(extensions); + responseObserver.onNext(ServerReflectionResponse.newBuilder() .setValidHost(request.getHost()) .setOriginalRequest(request) .setAllExtensionNumbersResponse(builder) .build()); } else { - sendErrorResponse(request, TriRpcStatus.Code.NOT_FOUND, "Type not found.", - responseObserver); + sendErrorResponse(request, TriRpcStatus.Code.NOT_FOUND, "Type not found.", responseObserver); } } - private void listServices(ServerReflectionRequest request, - StreamObserver responseObserver) { + private void listServices( + ServerReflectionRequest request, StreamObserver responseObserver) { ListServiceResponse.Builder builder = ListServiceResponse.newBuilder(); for (String serviceName : SchemaDescriptorRegistry.listServiceNames()) { builder.addService(ServiceResponse.newBuilder().setName(serviceName)); } - responseObserver.onNext( - ServerReflectionResponse.newBuilder() + responseObserver.onNext(ServerReflectionResponse.newBuilder() .setValidHost(request.getHost()) .setOriginalRequest(request) .setListServicesResponse(builder) @@ -162,22 +152,21 @@ public class ReflectionV1AlphaService extends DubboServerReflectionTriple.Server } private void sendErrorResponse( - ServerReflectionRequest request, TriRpcStatus.Code code, String message, - StreamObserver responseObserver) { - ServerReflectionResponse response = - ServerReflectionResponse.newBuilder() + ServerReflectionRequest request, + TriRpcStatus.Code code, + String message, + StreamObserver responseObserver) { + ServerReflectionResponse response = ServerReflectionResponse.newBuilder() .setValidHost(request.getHost()) .setOriginalRequest(request) .setErrorResponse( - ErrorResponse.newBuilder() - .setErrorCode(code.code) - .setErrorMessage(message)) + ErrorResponse.newBuilder().setErrorCode(code.code).setErrorMessage(message)) .build(); responseObserver.onNext(response); } private ServerReflectionResponse createServerReflectionResponse( - ServerReflectionRequest request, FileDescriptor fd) { + ServerReflectionRequest request, FileDescriptor fd) { FileDescriptorResponse.Builder fdRBuilder = FileDescriptorResponse.newBuilder(); Set seenFiles = new HashSet<>(); Queue frontier = new ArrayDeque<>(); @@ -194,9 +183,9 @@ public class ReflectionV1AlphaService extends DubboServerReflectionTriple.Server } } return ServerReflectionResponse.newBuilder() - .setValidHost(request.getHost()) - .setOriginalRequest(request) - .setFileDescriptorResponse(fdRBuilder) - .build(); + .setValidHost(request.getHost()) + .setOriginalRequest(request) + .setFileDescriptorResponse(fdRBuilder) + .build(); } } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/SchemaDescriptorRegistry.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/SchemaDescriptorRegistry.java index 3d37505ae1..0eb6fc6825 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/SchemaDescriptorRegistry.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/SchemaDescriptorRegistry.java @@ -14,13 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.service; -import com.google.protobuf.Descriptors.Descriptor; -import com.google.protobuf.Descriptors.FieldDescriptor; -import com.google.protobuf.Descriptors.FileDescriptor; - import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -30,6 +25,10 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Descriptors.FileDescriptor; + public class SchemaDescriptorRegistry { private static final Map DESCRIPTORS_BY_SYMBOL = new ConcurrentHashMap<>(); @@ -66,8 +65,7 @@ public class SchemaDescriptorRegistry { fdMap.put(number, fd); } - public static FileDescriptor getFileDescriptorByExtensionAndNumber(String extension, - int number) { + public static FileDescriptor getFileDescriptorByExtensionAndNumber(String extension, int number) { return EXTENSIONS.getOrDefault(extension, Collections.emptyMap()).get(number); } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/TriBuiltinService.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/TriBuiltinService.java index 8abfd9de40..b45a40ef06 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/TriBuiltinService.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/TriBuiltinService.java @@ -28,11 +28,11 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; +import java.util.concurrent.atomic.AtomicBoolean; + import io.grpc.health.v1.DubboHealthTriple; import io.grpc.health.v1.Health; -import java.util.concurrent.atomic.AtomicBoolean; - import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.rpc.Constants.PROXY_KEY; import static org.apache.dubbo.rpc.Constants.TRI_BUILTIN_SERVICE_INIT; @@ -52,8 +52,7 @@ public class TriBuiltinService { private ReflectionV1AlphaService reflectionServiceV1Alpha; private HealthStatusManager healthStatusManager; - private Configuration config = ConfigurationUtils.getGlobalConfiguration( - ApplicationModel.defaultModel()); + private Configuration config = ConfigurationUtils.getGlobalConfiguration(ApplicationModel.defaultModel()); private final AtomicBoolean init = new AtomicBoolean(); @@ -72,22 +71,20 @@ public class TriBuiltinService { proxyFactory = frameworkModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); pathResolver = frameworkModel.getExtensionLoader(PathResolver.class).getDefaultExtension(); addSingleBuiltinService(DubboHealthTriple.SERVICE_NAME, healthService, Health.class); - addSingleBuiltinService(ReflectionV1AlphaService.SERVICE_NAME, reflectionServiceV1Alpha, - ReflectionV1AlphaService.class); + addSingleBuiltinService( + ReflectionV1AlphaService.SERVICE_NAME, reflectionServiceV1Alpha, ReflectionV1AlphaService.class); } } - public boolean enable(){ + public boolean enable() { return config.getBoolean(TRI_BUILTIN_SERVICE_INIT, false); } - private void addSingleBuiltinService(String serviceName, T impl, Class interfaceClass) { ModuleModel internalModule = ApplicationModel.defaultModel().getInternalModule(); - URL url = new ServiceConfigURL(CommonConstants.TRIPLE, null, null, ANYHOST_VALUE, 0, - serviceName) - .addParameter(PROXY_KEY, CommonConstants.NATIVE_STUB) - .setScopeModel(internalModule); + URL url = new ServiceConfigURL(CommonConstants.TRIPLE, null, null, ANYHOST_VALUE, 0, serviceName) + .addParameter(PROXY_KEY, CommonConstants.NATIVE_STUB) + .setScopeModel(internalModule); Invoker invoker = proxyFactory.getInvoker(impl, interfaceClass, url); pathResolver.add(serviceName, invoker); internalModule.addDestroyListener(scopeModel -> pathResolver.remove(serviceName)); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/TriHealthImpl.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/TriHealthImpl.java index c21e78e1af..72ebda45bd 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/TriHealthImpl.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/service/TriHealthImpl.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.service; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -23,15 +22,15 @@ import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.TriRpcStatus; -import io.grpc.health.v1.DubboHealthTriple; -import io.grpc.health.v1.HealthCheckRequest; -import io.grpc.health.v1.HealthCheckResponse; - import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import io.grpc.health.v1.DubboHealthTriple; +import io.grpc.health.v1.HealthCheckRequest; +import io.grpc.health.v1.HealthCheckResponse; + import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_CLOSED_SERVER; public class TriHealthImpl extends DubboHealthTriple.HealthImplBase { @@ -48,22 +47,20 @@ public class TriHealthImpl extends DubboHealthTriple.HealthImplBase { // user-defined equals() doesn't confuse our book-keeping of the StreamObservers. Constructing // such Multimap would require extra lines and the end result is not significantly simpler, thus I // would rather not have the Guava collections dependency. - private final HashMap, Boolean>> watchers = new HashMap<>(); + private final HashMap, Boolean>> watchers = + new HashMap<>(); // Indicates if future status changes should be ignored. private boolean terminal; public TriHealthImpl() { // Copy of what Go and C++ do. - statusMap.put(HealthStatusManager.SERVICE_NAME_ALL_SERVICES, - HealthCheckResponse.ServingStatus.SERVING); + statusMap.put(HealthStatusManager.SERVICE_NAME_ALL_SERVICES, HealthCheckResponse.ServingStatus.SERVING); } - private static HealthCheckResponse getResponseForWatch( - HealthCheckResponse.ServingStatus recordedStatus) { + private static HealthCheckResponse getResponseForWatch(HealthCheckResponse.ServingStatus recordedStatus) { return HealthCheckResponse.newBuilder() - .setStatus(recordedStatus == null ? HealthCheckResponse.ServingStatus.SERVICE_UNKNOWN - : recordedStatus) - .build(); + .setStatus(recordedStatus == null ? HealthCheckResponse.ServingStatus.SERVICE_UNKNOWN : recordedStatus) + .build(); } @Override @@ -72,19 +69,18 @@ public class TriHealthImpl extends DubboHealthTriple.HealthImplBase { if (status != null) { return HealthCheckResponse.newBuilder().setStatus(status).build(); } - throw TriRpcStatus.NOT_FOUND.withDescription("unknown service " + request.getService()) - .asException(); + throw TriRpcStatus.NOT_FOUND + .withDescription("unknown service " + request.getService()) + .asException(); } @Override - public void watch(HealthCheckRequest request, - StreamObserver responseObserver) { + public void watch(HealthCheckRequest request, StreamObserver responseObserver) { final String service = request.getService(); synchronized (watchLock) { HealthCheckResponse.ServingStatus status = statusMap.get(service); responseObserver.onNext(getResponseForWatch(status)); - IdentityHashMap, Boolean> serviceWatchers = watchers.get( - service); + IdentityHashMap, Boolean> serviceWatchers = watchers.get(service); if (serviceWatchers == null) { serviceWatchers = new IdentityHashMap<>(); watchers.put(service, serviceWatchers); @@ -93,8 +89,7 @@ public class TriHealthImpl extends DubboHealthTriple.HealthImplBase { } RpcContext.getCancellationContext().addListener(context -> { synchronized (watchLock) { - IdentityHashMap, Boolean> serviceWatchers = watchers.get( - service); + IdentityHashMap, Boolean> serviceWatchers = watchers.get(service); if (serviceWatchers != null) { serviceWatchers.remove(responseObserver); if (serviceWatchers.isEmpty()) { @@ -150,8 +145,7 @@ public class TriHealthImpl extends DubboHealthTriple.HealthImplBase { private void notifyWatchers(String service, HealthCheckResponse.ServingStatus status) { HealthCheckResponse response = getResponseForWatch(status); - IdentityHashMap, Boolean> serviceWatchers = watchers.get( - service); + IdentityHashMap, Boolean> serviceWatchers = watchers.get(service); if (serviceWatchers != null) { for (StreamObserver responseObserver : serviceWatchers.keySet()) { responseObserver.onNext(response); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/AbstractStream.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/AbstractStream.java index e85620703c..f2f69bb344 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/AbstractStream.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/AbstractStream.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.stream; import org.apache.dubbo.common.threadpool.serial.SerializingExecutor; @@ -31,7 +30,6 @@ public abstract class AbstractStream implements Stream { protected Executor executor; protected final FrameworkModel frameworkModel; - private static final boolean HAS_PROTOBUF = hasProtobuf(); public AbstractStream(Executor executor, FrameworkModel frameworkModel) { diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ClientStream.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ClientStream.java index 42842c5fe3..304d3c4653 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ClientStream.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ClientStream.java @@ -14,15 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.stream; import org.apache.dubbo.rpc.TriRpcStatus; -import io.netty.util.concurrent.Future; - import java.util.Map; +import io.netty.util.concurrent.Future; + /** * ClientStream is used to send request to server and receive response from server. Response is * received by {@link ClientStream.Listener} Requests are sent by {@link ClientStream} directly. @@ -41,8 +40,7 @@ public interface ClientStream extends Stream { * * @param attachments received from remote peer */ - default void onComplete(TriRpcStatus status, Map attachments) { - } + default void onComplete(TriRpcStatus status, Map attachments) {} /** * Callback when request completed. @@ -51,11 +49,13 @@ public interface ClientStream extends Stream { * @param attachments attachments received from remote peer * @param reserved triple protocol reserved data */ - default void onComplete(TriRpcStatus status, Map attachments, - Map reserved, boolean isReturnTriException) { + default void onComplete( + TriRpcStatus status, + Map attachments, + Map reserved, + boolean isReturnTriException) { onComplete(status, attachments); } - } /** @@ -73,5 +73,4 @@ public interface ClientStream extends Stream { * @return a future of send result */ Future halfClose(); - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ServerStream.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ServerStream.java index 0b815253d0..88f45284d4 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ServerStream.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ServerStream.java @@ -14,15 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.stream; import org.apache.dubbo.rpc.TriRpcStatus; -import io.netty.util.concurrent.Future; - import java.util.Map; +import io.netty.util.concurrent.Future; + /** * ServerStream is used to send response to client and receive requests from client. {@link * Listener} is used to receive requests from client. @@ -51,7 +50,8 @@ public interface ServerStream extends Stream { * @param attachments response attachments * @return a future that indicates the completion of send trailers */ - Future complete(TriRpcStatus status, Map attachments, boolean isNeedReturnException, int exceptionCode); + Future complete( + TriRpcStatus status, Map attachments, boolean isNeedReturnException, int exceptionCode); /** * Send message to client @@ -61,5 +61,4 @@ public interface ServerStream extends Stream { * @return a future that indicates the completion of send message */ Future sendMessage(byte[] message, int compressFlag); - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/Stream.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/Stream.java index 72b7aec844..05b55e5224 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/Stream.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/Stream.java @@ -14,17 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.stream; - import org.apache.dubbo.rpc.TriRpcStatus; +import java.net.SocketAddress; + import io.netty.handler.codec.http2.Http2Headers; import io.netty.util.concurrent.Future; -import java.net.SocketAddress; - /** * Stream is a bi-directional channel that manipulates the data flow between peers. Inbound data * from remote peer is acquired by {@link Listener}. Outbound data to remote peer is sent directly @@ -51,7 +49,6 @@ public interface Stream { * @param status the cancel status */ void onCancelByRemote(TriRpcStatus status); - } /** @@ -83,5 +80,4 @@ public interface Stream { * @param n number of message */ void request(int n); - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/StreamUtils.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/StreamUtils.java index 8df63eab78..b1ec7306a0 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/StreamUtils.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/StreamUtils.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.stream; -import io.netty.handler.codec.http2.DefaultHttp2Headers; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.JsonUtils; @@ -34,6 +32,8 @@ import java.util.HashMap; import java.util.Locale; import java.util.Map; +import io.netty.handler.codec.http2.DefaultHttp2Headers; + import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_UNSUPPORTED; public class StreamUtils { @@ -43,7 +43,6 @@ public class StreamUtils { private static final Base64.Decoder BASE64_DECODER = Base64.getDecoder(); private static final Base64.Encoder BASE64_ENCODER = Base64.getEncoder().withoutPadding(); - private static final int MAX_LRU_HEADER_MAP_SIZE = 10000; private static final Map lruHeaderMap = new LRU2Cache<>(MAX_LRU_HEADER_MAP_SIZE); @@ -83,9 +82,8 @@ public class StreamUtils { * @param attachments KV pairs * @param needConvertHeaderKey convert flag */ - public static void convertAttachment(DefaultHttp2Headers headers, - Map attachments, - boolean needConvertHeaderKey) { + public static void convertAttachment( + DefaultHttp2Headers headers, Map attachments, boolean needConvertHeaderKey) { if (attachments == null) { return; } @@ -115,9 +113,8 @@ public class StreamUtils { } } - public static void convertAttachment(HttpHeaders headers, - Map attachments, - boolean needConvertHeaderKey) { + public static void convertAttachment( + HttpHeaders headers, Map attachments, boolean needConvertHeaderKey) { if (attachments == null) { return; } @@ -147,9 +144,7 @@ public class StreamUtils { } } - - public static void convertAttachment(DefaultHttp2Headers headers, - Map attachments) { + public static void convertAttachment(DefaultHttp2Headers headers, Map attachments) { convertAttachment(headers, attachments, false); } @@ -169,11 +164,20 @@ public class StreamUtils { String str = encodeBase64ASCII((byte[]) v); headers.set(key + TripleConstant.HEADER_BIN_SUFFIX, str); } else { - LOGGER.warn(PROTOCOL_UNSUPPORTED, "", "", "Unsupported attachment k: " + key + " class: " + v.getClass().getName()); + LOGGER.warn( + PROTOCOL_UNSUPPORTED, + "", + "", + "Unsupported attachment k: " + key + " class: " + + v.getClass().getName()); } } catch (Throwable t) { - LOGGER.warn(PROTOCOL_UNSUPPORTED, "", "", "Meet exception when convert single attachment key:" + key + " value=" + v, - t); + LOGGER.warn( + PROTOCOL_UNSUPPORTED, + "", + "", + "Meet exception when convert single attachment key:" + key + " value=" + v, + t); } } @@ -186,13 +190,20 @@ public class StreamUtils { String str = encodeBase64ASCII((byte[]) v); headers.set(key + TripleConstant.HEADER_BIN_SUFFIX, str); } else { - LOGGER.warn(PROTOCOL_UNSUPPORTED, "", "", "Unsupported attachment k: " + key + " class: " + v.getClass().getName()); + LOGGER.warn( + PROTOCOL_UNSUPPORTED, + "", + "", + "Unsupported attachment k: " + key + " class: " + + v.getClass().getName()); } } catch (Throwable t) { - LOGGER.warn(PROTOCOL_UNSUPPORTED, "", "", "Meet exception when convert single attachment key:" + key + " value=" + v, - t); + LOGGER.warn( + PROTOCOL_UNSUPPORTED, + "", + "", + "Meet exception when convert single attachment key:" + key + " value=" + v, + t); } } - - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleClientStream.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleClientStream.java index da7ddc4543..8b060ae82d 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleClientStream.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleClientStream.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.stream; import org.apache.dubbo.common.constants.CommonConstants; @@ -41,6 +40,14 @@ import org.apache.dubbo.rpc.protocol.tri.transport.TripleHttp2ClientResponseHand import org.apache.dubbo.rpc.protocol.tri.transport.TripleWriteQueue; import org.apache.dubbo.rpc.protocol.tri.transport.WriteQueue; +import java.io.IOException; +import java.net.SocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Executor; + import com.google.protobuf.Any; import com.google.rpc.DebugInfo; import com.google.rpc.ErrorInfo; @@ -56,17 +63,8 @@ import io.netty.handler.codec.http2.Http2StreamChannel; import io.netty.handler.codec.http2.Http2StreamChannelBootstrap; import io.netty.util.ReferenceCountUtil; -import java.io.IOException; -import java.net.SocketAddress; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Executor; - import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_RESPONSE; - /** * ClientStream is an abstraction for bi-directional messaging. It maintains a {@link WriteQueue} to * write Http2Frame to remote. A {@link H2TransportListener} receives Http2Frame from remote. @@ -87,11 +85,12 @@ public class TripleClientStream extends AbstractStream implements ClientStream { private boolean isReturnTriException = false; // for test - TripleClientStream(FrameworkModel frameworkModel, - Executor executor, - TripleWriteQueue writeQueue, - ClientStream.Listener listener, - Http2StreamChannel http2StreamChannel) { + TripleClientStream( + FrameworkModel frameworkModel, + Executor executor, + TripleWriteQueue writeQueue, + ClientStream.Listener listener, + Http2StreamChannel http2StreamChannel) { super(executor, frameworkModel); this.parent = http2StreamChannel.parent(); this.listener = listener; @@ -99,11 +98,12 @@ public class TripleClientStream extends AbstractStream implements ClientStream { this.streamChannelFuture = initHttp2StreamChannel(http2StreamChannel); } - public TripleClientStream(FrameworkModel frameworkModel, - Executor executor, - Channel parent, - ClientStream.Listener listener, - TripleWriteQueue writeQueue) { + public TripleClientStream( + FrameworkModel frameworkModel, + Executor executor, + Channel parent, + ClientStream.Listener listener, + TripleWriteQueue writeQueue) { super(executor, frameworkModel); this.parent = parent; this.listener = listener; @@ -115,19 +115,18 @@ public class TripleClientStream extends AbstractStream implements ClientStream { TripleStreamChannelFuture streamChannelFuture = new TripleStreamChannelFuture(parent); Http2StreamChannelBootstrap bootstrap = new Http2StreamChannelBootstrap(parent); bootstrap.handler(new ChannelInboundHandlerAdapter() { - @Override - public void handlerAdded(ChannelHandlerContext ctx) throws Exception { - Channel channel = ctx.channel(); - channel.pipeline().addLast(new TripleCommandOutBoundHandler()); - channel.pipeline().addLast(new TripleHttp2ClientResponseHandler(createTransportListener())); - } - }); + @Override + public void handlerAdded(ChannelHandlerContext ctx) throws Exception { + Channel channel = ctx.channel(); + channel.pipeline().addLast(new TripleCommandOutBoundHandler()); + channel.pipeline().addLast(new TripleHttp2ClientResponseHandler(createTransportListener())); + } + }); CreateStreamQueueCommand cmd = CreateStreamQueueCommand.create(bootstrap, streamChannelFuture); this.writeQueue.enqueue(cmd); return streamChannelFuture; } - public ChannelFuture sendHeader(Http2Headers headers) { if (this.writeQueue == null) { // already processed at createStream() @@ -146,8 +145,8 @@ public class TripleClientStream extends AbstractStream implements ClientStream { } private void transportException(Throwable cause) { - final TriRpcStatus status = TriRpcStatus.INTERNAL.withDescription("Http2 exception") - .withCause(cause); + final TriRpcStatus status = + TriRpcStatus.INTERNAL.withDescription("Http2 exception").withCause(cause); listener.onComplete(status, null, null, false); } @@ -167,25 +166,21 @@ public class TripleClientStream extends AbstractStream implements ClientStream { return parent.remoteAddress(); } - @Override public ChannelFuture sendMessage(byte[] message, int compressFlag, boolean eos) { ChannelFuture checkResult = preCheck(); if (!checkResult.isSuccess()) { return checkResult; } - final DataQueueCommand cmd = DataQueueCommand.create(streamChannelFuture, message, false, - compressFlag); + final DataQueueCommand cmd = DataQueueCommand.create(streamChannelFuture, message, false, compressFlag); return this.writeQueue.enqueueFuture(cmd, parent.eventLoop()).addListener(future -> { - if (!future.isSuccess()) { - cancelByLocal( - TriRpcStatus.INTERNAL.withDescription("Client write message failed") - .withCause(future.cause()) - ); - transportException(future.cause()); - } - } - ); + if (!future.isSuccess()) { + cancelByLocal(TriRpcStatus.INTERNAL + .withDescription("Client write message failed") + .withCause(future.cause())); + transportException(future.cause()); + } + }); } @Override @@ -221,8 +216,7 @@ public class TripleClientStream extends AbstractStream implements ClientStream { return new ClientTransportListener(); } - class ClientTransportListener extends AbstractH2TransportListener implements - H2TransportListener { + class ClientTransportListener extends AbstractH2TransportListener implements H2TransportListener { private TriRpcStatus transportError; private DeCompressor decompressor; @@ -237,7 +231,8 @@ public class TripleClientStream extends AbstractStream implements ClientStream { void finishProcess(TriRpcStatus status, Http2Headers trailers, boolean isReturnTriException) { final Map reserved = filterReservedHeaders(trailers); - final Map attachments = headersToMap(trailers, () -> reserved.get(TripleHeaderEnum.TRI_HEADER_CONVERT.getHeader())); + final Map attachments = + headersToMap(trailers, () -> reserved.get(TripleHeaderEnum.TRI_HEADER_CONVERT.getHeader())); final TriRpcStatus detailStatus; final TriRpcStatus statusFromTrailers = getStatusFromTrailers(reserved); if (statusFromTrailers != null) { @@ -249,17 +244,17 @@ public class TripleClientStream extends AbstractStream implements ClientStream { } private TriRpcStatus validateHeaderStatus(Http2Headers headers) { - Integer httpStatus = - headers.status() == null ? null : Integer.parseInt(headers.status().toString()); + Integer httpStatus = headers.status() == null + ? null + : Integer.parseInt(headers.status().toString()); if (httpStatus == null) { return TriRpcStatus.INTERNAL.withDescription("Missing HTTP status code"); } - final CharSequence contentType = headers.get( - TripleHeaderEnum.CONTENT_TYPE_KEY.getHeader()); - if (contentType == null || !contentType.toString() - .startsWith(TripleHeaderEnum.APPLICATION_GRPC.getHeader())) { + final CharSequence contentType = headers.get(TripleHeaderEnum.CONTENT_TYPE_KEY.getHeader()); + if (contentType == null + || !contentType.toString().startsWith(TripleHeaderEnum.APPLICATION_GRPC.getHeader())) { return TriRpcStatus.fromCode(TriRpcStatus.httpStatusToGrpcCode(httpStatus)) - .withDescription("invalid content-type: " + contentType); + .withDescription("invalid content-type: " + contentType); } return null; } @@ -273,11 +268,11 @@ public class TripleClientStream extends AbstractStream implements ClientStream { transportError = TriRpcStatus.INTERNAL.withDescription("Received headers twice"); return; } - Integer httpStatus = - headers.status() == null ? null : Integer.parseInt(headers.status().toString()); + Integer httpStatus = headers.status() == null + ? null + : Integer.parseInt(headers.status().toString()); - if (httpStatus != null && Integer.parseInt(httpStatus.toString()) > 100 - && httpStatus < 200) { + if (httpStatus != null && Integer.parseInt(httpStatus.toString()) > 100 && httpStatus < 200) { // ignored return; } @@ -296,12 +291,11 @@ public class TripleClientStream extends AbstractStream implements ClientStream { if (null != messageEncoding) { String compressorStr = messageEncoding.toString(); if (!Identity.IDENTITY.getMessageEncoding().equals(compressorStr)) { - DeCompressor compressor = DeCompressor.getCompressor(frameworkModel, - compressorStr); + DeCompressor compressor = DeCompressor.getCompressor(frameworkModel, compressorStr); if (null == compressor) { - throw TriRpcStatus.UNIMPLEMENTED.withDescription(String.format( - "Grpc-encoding '%s' is not supported", - compressorStr)).asException(); + throw TriRpcStatus.UNIMPLEMENTED + .withDescription(String.format("Grpc-encoding '%s' is not supported", compressorStr)) + .asException(); } else { decompressor = compressor; } @@ -357,23 +351,22 @@ public class TripleClientStream extends AbstractStream implements ClientStream { if (headerReceived) { return TriRpcStatus.UNKNOWN.withDescription("missing GRPC status in response"); } - Integer httpStatus = - trailers.status() == null ? null : Integer.parseInt(trailers.status().toString()); + Integer httpStatus = trailers.status() == null + ? null + : Integer.parseInt(trailers.status().toString()); if (httpStatus != null) { status = TriRpcStatus.fromCode(TriRpcStatus.httpStatusToGrpcCode(httpStatus)); } else { status = TriRpcStatus.INTERNAL.withDescription("missing HTTP status code"); } - return status.appendDescription( - "missing GRPC status, inferred error from HTTP status code"); + return status.appendDescription("missing GRPC status, inferred error from HTTP status code"); } - private TriRpcStatus getStatusFromTrailers(Map metadata) { if (null == metadata) { return null; } - if (!getGrpcStatusDetailEnabled()){ + if (!getGrpcStatusDetailEnabled()) { return null; } // second get status detail @@ -390,11 +383,10 @@ public class TripleClientStream extends AbstractStream implements ClientStream { // get common exception from DebugInfo TriRpcStatus status = TriRpcStatus.fromCode(statusDetail.getCode()) - .withDescription(TriRpcStatus.decodeMessage(statusDetail.getMessage())); + .withDescription(TriRpcStatus.decodeMessage(statusDetail.getMessage())); DebugInfo debugInfo = (DebugInfo) classObjectMap.get(DebugInfo.class); if (debugInfo != null) { - String msg = ExceptionUtils.getStackFrameString( - debugInfo.getStackEntriesList()); + String msg = ExceptionUtils.getStackFrameString(debugInfo.getStackEntriesList()); status = status.appendDescription(msg); } return status; @@ -403,10 +395,8 @@ public class TripleClientStream extends AbstractStream implements ClientStream { } finally { ClassLoadUtil.switchContextLoader(tccl); } - } - private Map, Object> tranFromStatusDetails(List detailList) { Map, Object> map = new HashMap<>(detailList.size()); try { @@ -433,7 +423,8 @@ public class TripleClientStream extends AbstractStream implements ClientStream { if (!halfClosed) { Http2StreamChannel channel = streamChannelFuture.getNow(); if (channel.isActive() && !rst) { - writeQueue.enqueue(CancelQueueCommand.createCommand(streamChannelFuture, Http2Error.CANCEL)); + writeQueue.enqueue( + CancelQueueCommand.createCommand(streamChannelFuture, Http2Error.CANCEL)); rst = true; } } @@ -442,7 +433,6 @@ public class TripleClientStream extends AbstractStream implements ClientStream { onHeaderReceived(headers); } }); - } @Override @@ -460,8 +450,7 @@ public class TripleClientStream extends AbstractStream implements ClientStream { private void doOnData(ByteBuf data, boolean endStream) { if (transportError != null) { - transportError.appendDescription( - "Data:" + data.toString(StandardCharsets.UTF_8)); + transportError.appendDescription("Data:" + data.toString(StandardCharsets.UTF_8)); ReferenceCountUtil.release(data); if (transportError.description.length() > 512 || endStream) { handleH2TransportError(transportError); @@ -469,8 +458,7 @@ public class TripleClientStream extends AbstractStream implements ClientStream { return; } if (!headerReceived) { - handleH2TransportError(TriRpcStatus.INTERNAL.withDescription( - "headers not received before payload")); + handleH2TransportError(TriRpcStatus.INTERNAL.withDescription("headers not received before payload")); return; } deframer.deframe(data); @@ -479,8 +467,8 @@ public class TripleClientStream extends AbstractStream implements ClientStream { @Override public void cancelByRemote(long errorCode) { executor.execute(() -> { - transportError = TriRpcStatus.CANCELLED - .withDescription("Canceled by remote peer, errorCode=" + errorCode); + transportError = + TriRpcStatus.CANCELLED.withDescription("Canceled by remote peer, errorCode=" + errorCode); finishProcess(transportError, null, false); }); } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleServerStream.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleServerStream.java index 88e5cd0b3d..0aaca48491 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleServerStream.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleServerStream.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.stream; -import io.netty.util.ReferenceCountUtil; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -46,6 +44,14 @@ import org.apache.dubbo.rpc.protocol.tri.transport.AbstractH2TransportListener; import org.apache.dubbo.rpc.protocol.tri.transport.H2TransportListener; import org.apache.dubbo.rpc.protocol.tri.transport.TripleWriteQueue; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.Executor; + import com.google.protobuf.Any; import com.google.rpc.DebugInfo; import com.google.rpc.Status; @@ -59,16 +65,9 @@ import io.netty.handler.codec.http2.DefaultHttp2Headers; import io.netty.handler.codec.http2.Http2Error; import io.netty.handler.codec.http2.Http2Headers; import io.netty.handler.codec.http2.Http2StreamChannel; +import io.netty.util.ReferenceCountUtil; import io.netty.util.concurrent.Future; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.Executor; - import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REQUEST; @@ -90,13 +89,14 @@ public class TripleServerStream extends AbstractStream implements ServerStream { private final Http2StreamChannel http2StreamChannel; private final TripleStreamChannelFuture tripleStreamChannelFuture; - public TripleServerStream(Http2StreamChannel channel, - FrameworkModel frameworkModel, - Executor executor, - PathResolver pathResolver, - String acceptEncoding, - List filters, - TripleWriteQueue writeQueue) { + public TripleServerStream( + Http2StreamChannel channel, + FrameworkModel frameworkModel, + Executor executor, + PathResolver pathResolver, + String acceptEncoding, + List filters, + TripleWriteQueue writeQueue) { super(executor, frameworkModel); this.pathResolver = pathResolver; this.acceptEncoding = acceptEncoding; @@ -129,7 +129,8 @@ public class TripleServerStream extends AbstractStream implements ServerStream { @Override public ChannelFuture sendHeader(Http2Headers headers) { if (reset) { - return http2StreamChannel.newFailedFuture(new IllegalStateException("Stream already reset, no more headers allowed")); + return http2StreamChannel.newFailedFuture( + new IllegalStateException("Stream already reset, no more headers allowed")); } if (headerSent) { return http2StreamChannel.newFailedFuture(new IllegalStateException("Header already sent")); @@ -142,12 +143,13 @@ public class TripleServerStream extends AbstractStream implements ServerStream { return checkResult; } headerSent = true; - return writeQueue.enqueue(HeaderQueueCommand.createHeaders(tripleStreamChannelFuture, headers, false)) - .addListener(f -> { - if (!f.isSuccess()) { - reset(Http2Error.INTERNAL_ERROR); - } - }); + return writeQueue + .enqueue(HeaderQueueCommand.createHeaders(tripleStreamChannelFuture, headers, false)) + .addListener(f -> { + if (!f.isSuccess()) { + reset(Http2Error.INTERNAL_ERROR); + } + }); } @Override @@ -158,16 +160,18 @@ public class TripleServerStream extends AbstractStream implements ServerStream { return reset(Http2Error.CANCEL); } - @Override - public ChannelFuture complete(TriRpcStatus status, Map attachments, boolean isNeedReturnException, int exceptionCode) { - Http2Headers trailers = getTrailers(status, attachments, isNeedReturnException, CommonConstants.TRI_EXCEPTION_CODE_NOT_EXISTS); + public ChannelFuture complete( + TriRpcStatus status, Map attachments, boolean isNeedReturnException, int exceptionCode) { + Http2Headers trailers = + getTrailers(status, attachments, isNeedReturnException, CommonConstants.TRI_EXCEPTION_CODE_NOT_EXISTS); return sendTrailers(trailers); } private ChannelFuture sendTrailers(Http2Headers trailers) { if (reset) { - return http2StreamChannel.newFailedFuture(new IllegalStateException("Stream already reset, no more trailers allowed")); + return http2StreamChannel.newFailedFuture( + new IllegalStateException("Stream already reset, no more trailers allowed")); } if (trailersSent) { return http2StreamChannel.newFailedFuture(new IllegalStateException("Trailers already sent")); @@ -178,15 +182,17 @@ public class TripleServerStream extends AbstractStream implements ServerStream { } headerSent = true; trailersSent = true; - return writeQueue.enqueue(HeaderQueueCommand.createHeaders(tripleStreamChannelFuture, trailers, true)) - .addListener(f -> { - if (!f.isSuccess()) { - reset(Http2Error.INTERNAL_ERROR); - } - }); + return writeQueue + .enqueue(HeaderQueueCommand.createHeaders(tripleStreamChannelFuture, trailers, true)) + .addListener(f -> { + if (!f.isSuccess()) { + reset(Http2Error.INTERNAL_ERROR); + } + }); } - private Http2Headers getTrailers(TriRpcStatus rpcStatus, Map attachments, boolean isNeedReturnException, int exceptionCode) { + private Http2Headers getTrailers( + TriRpcStatus rpcStatus, Map attachments, boolean isNeedReturnException, int exceptionCode) { DefaultHttp2Headers headers = new DefaultHttp2Headers(); if (!headerSent) { headers.status(HttpResponseStatus.OK.codeAsText()); @@ -203,24 +209,25 @@ public class TripleServerStream extends AbstractStream implements ServerStream { if (!getGrpcStatusDetailEnabled()) { return headers; } - Status.Builder builder = Status.newBuilder().setCode(rpcStatus.code.code) - .setMessage(grpcMessage); + Status.Builder builder = + Status.newBuilder().setCode(rpcStatus.code.code).setMessage(grpcMessage); Throwable throwable = rpcStatus.cause; if (throwable == null) { Status status = builder.build(); - headers.set(TripleHeaderEnum.STATUS_DETAIL_KEY.getHeader(), - StreamUtils.encodeBase64ASCII(status.toByteArray())); + headers.set( + TripleHeaderEnum.STATUS_DETAIL_KEY.getHeader(), + StreamUtils.encodeBase64ASCII(status.toByteArray())); return headers; } DebugInfo debugInfo = DebugInfo.newBuilder() - .addAllStackEntries(ExceptionUtils.getStackFrameList(throwable, 6)) - // can not use now - // .setDetail(throwable.getMessage()) - .build(); + .addAllStackEntries(ExceptionUtils.getStackFrameList(throwable, 6)) + // can not use now + // .setDetail(throwable.getMessage()) + .build(); builder.addDetails(Any.pack(debugInfo)); Status status = builder.build(); - headers.set(TripleHeaderEnum.STATUS_DETAIL_KEY.getHeader(), - StreamUtils.encodeBase64ASCII(status.toByteArray())); + headers.set( + TripleHeaderEnum.STATUS_DETAIL_KEY.getHeader(), StreamUtils.encodeBase64ASCII(status.toByteArray())); return headers; } @@ -231,20 +238,19 @@ public class TripleServerStream extends AbstractStream implements ServerStream { return Optional.ofNullable(status.cause).map(Throwable::getMessage).orElse("unknown"); } - @Override public ChannelFuture sendMessage(byte[] message, int compressFlag) { if (reset) { return http2StreamChannel.newFailedFuture( - new IllegalStateException("Stream already reset, no more body allowed")); + new IllegalStateException("Stream already reset, no more body allowed")); } if (!headerSent) { return http2StreamChannel.newFailedFuture( - new IllegalStateException("Headers did not sent before send body")); + new IllegalStateException("Headers did not sent before send body")); } if (trailersSent) { return http2StreamChannel.newFailedFuture( - new IllegalStateException("Trailers already sent, no more body allowed")); + new IllegalStateException("Trailers already sent, no more body allowed")); } ChannelFuture checkResult = preCheck(); if (!checkResult.isSuccess()) { @@ -264,10 +270,11 @@ public class TripleServerStream extends AbstractStream implements ServerStream { if (!checkResult.isSuccess()) { return; } - Http2Headers headers = new DefaultHttp2Headers(true).status(String.valueOf(code)) - .setInt(TripleHeaderEnum.STATUS_KEY.getHeader(), status.code.code) - .set(TripleHeaderEnum.MESSAGE_KEY.getHeader(), status.description) - .set(TripleHeaderEnum.CONTENT_TYPE_KEY.getHeader(), TripleConstant.TEXT_PLAIN_UTF8); + Http2Headers headers = new DefaultHttp2Headers(true) + .status(String.valueOf(code)) + .setInt(TripleHeaderEnum.STATUS_KEY.getHeader(), status.code.code) + .set(TripleHeaderEnum.MESSAGE_KEY.getHeader(), status.description) + .set(TripleHeaderEnum.CONTENT_TYPE_KEY.getHeader(), TripleConstant.TEXT_PLAIN_UTF8); writeQueue.enqueue(HeaderQueueCommand.createHeaders(tripleStreamChannelFuture, headers, false)); writeQueue.enqueue(TextDataQueueCommand.createCommand(tripleStreamChannelFuture, status.description, true)); } @@ -279,21 +286,21 @@ public class TripleServerStream extends AbstractStream implements ServerStream { * @param status status of error */ private void responseErr(TriRpcStatus status) { - Http2Headers trailers = new DefaultHttp2Headers().status(OK.codeAsText()) - .set(HttpHeaderNames.CONTENT_TYPE, TripleConstant.CONTENT_PROTO) - .setInt(TripleHeaderEnum.STATUS_KEY.getHeader(), status.code.code) - .set(TripleHeaderEnum.MESSAGE_KEY.getHeader(), status.toEncodedMessage()); + Http2Headers trailers = new DefaultHttp2Headers() + .status(OK.codeAsText()) + .set(HttpHeaderNames.CONTENT_TYPE, TripleConstant.CONTENT_PROTO) + .setInt(TripleHeaderEnum.STATUS_KEY.getHeader(), status.code.code) + .set(TripleHeaderEnum.MESSAGE_KEY.getHeader(), status.toEncodedMessage()); sendTrailers(trailers); } - private Invoker getInvoker(Http2Headers headers, String serviceName) { - final String version = - headers.contains(TripleHeaderEnum.SERVICE_VERSION.getHeader()) ? headers.get( - TripleHeaderEnum.SERVICE_VERSION.getHeader()).toString() : null; - final String group = - headers.contains(TripleHeaderEnum.SERVICE_GROUP.getHeader()) ? headers.get( - TripleHeaderEnum.SERVICE_GROUP.getHeader()).toString() : null; + final String version = headers.contains(TripleHeaderEnum.SERVICE_VERSION.getHeader()) + ? headers.get(TripleHeaderEnum.SERVICE_VERSION.getHeader()).toString() + : null; + final String group = headers.contains(TripleHeaderEnum.SERVICE_GROUP.getHeader()) + ? headers.get(TripleHeaderEnum.SERVICE_GROUP.getHeader()).toString() + : null; final String key = URL.buildKey(serviceName, group, version); Invoker invoker = pathResolver.resolve(key); if (invoker == null && TripleProtocol.RESOLVE_FALLBACK_TO_DEFAULT) { @@ -315,8 +322,7 @@ public class TripleServerStream extends AbstractStream implements ServerStream { return http2StreamChannel.newSucceededFuture(); } - public class ServerTransportObserver extends AbstractH2TransportListener implements - H2TransportListener { + public class ServerTransportObserver extends AbstractH2TransportListener implements H2TransportListener { /** * must starts from application/grpc @@ -335,42 +341,45 @@ public class TripleServerStream extends AbstractStream implements ServerStream { private void processHeader(Http2Headers headers, boolean endStream) { if (!HttpMethod.POST.asciiName().contentEquals(headers.method())) { - responsePlainTextError(HttpResponseStatus.METHOD_NOT_ALLOWED.code(), - TriRpcStatus.INTERNAL.withDescription( - String.format("Method '%s' is not supported", headers.method()))); + responsePlainTextError( + HttpResponseStatus.METHOD_NOT_ALLOWED.code(), + TriRpcStatus.INTERNAL.withDescription( + String.format("Method '%s' is not supported", headers.method()))); return; } if (headers.path() == null) { - responsePlainTextError(HttpResponseStatus.NOT_FOUND.code(), - TriRpcStatus.fromCode(TriRpcStatus.Code.UNIMPLEMENTED.code) - .withDescription("Expected path but is missing")); + responsePlainTextError( + HttpResponseStatus.NOT_FOUND.code(), + TriRpcStatus.fromCode(TriRpcStatus.Code.UNIMPLEMENTED.code) + .withDescription("Expected path but is missing")); return; } final String path = headers.path().toString(); if (path.charAt(0) != '/') { - responsePlainTextError(HttpResponseStatus.NOT_FOUND.code(), - TriRpcStatus.fromCode(TriRpcStatus.Code.UNIMPLEMENTED.code) - .withDescription(String.format("Expected path to start with /: %s", path))); + responsePlainTextError( + HttpResponseStatus.NOT_FOUND.code(), + TriRpcStatus.fromCode(TriRpcStatus.Code.UNIMPLEMENTED.code) + .withDescription(String.format("Expected path to start with /: %s", path))); return; } - final CharSequence contentType = HttpUtil.getMimeType( - headers.get(HttpHeaderNames.CONTENT_TYPE)); + final CharSequence contentType = HttpUtil.getMimeType(headers.get(HttpHeaderNames.CONTENT_TYPE)); if (contentType == null) { - responsePlainTextError(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE.code(), - TriRpcStatus.fromCode(TriRpcStatus.Code.INTERNAL.code) - .withDescription("Content-Type is missing from the request")); + responsePlainTextError( + HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE.code(), + TriRpcStatus.fromCode(TriRpcStatus.Code.INTERNAL.code) + .withDescription("Content-Type is missing from the request")); return; } final String contentString = contentType.toString(); if (!supportContentType(contentString)) { - responsePlainTextError(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE.code(), - TriRpcStatus.fromCode(TriRpcStatus.Code.INTERNAL.code) - .withDescription( - String.format("Content-Type '%s' is not supported", contentString))); + responsePlainTextError( + HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE.code(), + TriRpcStatus.fromCode(TriRpcStatus.Code.INTERNAL.code) + .withDescription(String.format("Content-Type '%s' is not supported", contentString))); return; } @@ -384,8 +393,7 @@ public class TripleServerStream extends AbstractStream implements ServerStream { Invoker invoker = getInvoker(headers, serviceName); if (invoker == null) { - responseErr( - TriRpcStatus.UNIMPLEMENTED.withDescription("Service not found:" + serviceName)); + responseErr(TriRpcStatus.UNIMPLEMENTED.withDescription("Service not found:" + serviceName)); return; } @@ -398,38 +406,46 @@ public class TripleServerStream extends AbstractStream implements ServerStream { if (null != messageEncoding) { String compressorStr = messageEncoding.toString(); if (!Identity.MESSAGE_ENCODING.equals(compressorStr)) { - DeCompressor compressor = DeCompressor.getCompressor(frameworkModel, - compressorStr); + DeCompressor compressor = DeCompressor.getCompressor(frameworkModel, compressorStr); if (null == compressor) { responseErr(TriRpcStatus.fromCode(TriRpcStatus.Code.UNIMPLEMENTED.code) - .withDescription(String.format("Grpc-encoding '%s' is not supported", - compressorStr))); + .withDescription(String.format("Grpc-encoding '%s' is not supported", compressorStr))); return; } deCompressor = compressor; } } - Map requestMetadata = headersToMap(headers, () -> - Optional.ofNullable(headers.get(TripleHeaderEnum.TRI_HEADER_CONVERT.getHeader())) - .map(CharSequence::toString) - .orElse(null)); + Map requestMetadata = headersToMap( + headers, () -> Optional.ofNullable(headers.get(TripleHeaderEnum.TRI_HEADER_CONVERT.getHeader())) + .map(CharSequence::toString) + .orElse(null)); boolean hasStub = pathResolver.hasNativeStub(path); if (hasStub) { - listener = new StubAbstractServerCall(invoker, TripleServerStream.this, - frameworkModel, - acceptEncoding, serviceName, originalMethodName, executor); + listener = new StubAbstractServerCall( + invoker, + TripleServerStream.this, + frameworkModel, + acceptEncoding, + serviceName, + originalMethodName, + executor); } else { - listener = new ReflectionAbstractServerCall(invoker, TripleServerStream.this, - frameworkModel, acceptEncoding, serviceName, originalMethodName, filters, - executor); + listener = new ReflectionAbstractServerCall( + invoker, + TripleServerStream.this, + frameworkModel, + acceptEncoding, + serviceName, + originalMethodName, + filters, + executor); } // must before onHeader deframer = new TriDecoder(deCompressor, new ServerDecoderListener(listener)); listener.onHeader(requestMetadata); } - @Override public void onData(ByteBuf data, boolean endStream) { try { @@ -463,12 +479,11 @@ public class TripleServerStream extends AbstractStream implements ServerStream { if (listener == null) { return; } - executor.execute(() -> listener.onCancelByRemote(TriRpcStatus.CANCELLED - .withDescription("Canceled by client ,errorCode=" + errorCode))); + executor.execute(() -> listener.onCancelByRemote( + TriRpcStatus.CANCELLED.withDescription("Canceled by client ,errorCode=" + errorCode))); } } - private static class ServerDecoderListener implements TriDecoder.Listener { private final ServerStream.Listener listener; @@ -487,6 +502,4 @@ public class TripleServerStream extends AbstractStream implements ServerStream { listener.onComplete(); } } - - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleStreamChannelFuture.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleStreamChannelFuture.java index fc3e152aab..6c47761cbe 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleStreamChannelFuture.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleStreamChannelFuture.java @@ -14,15 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.stream; -import io.netty.channel.Channel; -import io.netty.handler.codec.http2.Http2StreamChannel; import org.apache.dubbo.common.utils.Assert; import java.util.concurrent.CompletableFuture; +import io.netty.channel.Channel; +import io.netty.handler.codec.http2.Http2StreamChannel; + public class TripleStreamChannelFuture extends CompletableFuture { private final Channel parentChannel; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/AbstractH2TransportListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/AbstractH2TransportListener.java index 5bcec31fde..fe5c341b20 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/AbstractH2TransportListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/AbstractH2TransportListener.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.transport; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -25,19 +24,20 @@ import org.apache.dubbo.rpc.protocol.tri.TripleConstant; import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum; import org.apache.dubbo.rpc.protocol.tri.stream.StreamUtils; -import io.netty.handler.codec.http2.Http2Headers; - import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.function.Supplier; +import io.netty.handler.codec.http2.Http2Headers; + import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_PARSE; public abstract class AbstractH2TransportListener implements H2TransportListener { - private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(AbstractH2TransportListener.class); + private static final ErrorTypeAwareLogger LOGGER = + LoggerFactory.getErrorTypeAwareLogger(AbstractH2TransportListener.class); /** * Parse metadata to a KV pairs map. @@ -53,10 +53,9 @@ public abstract class AbstractH2TransportListener implements H2TransportListener for (Map.Entry header : trailers) { String key = header.getKey().toString(); if (key.endsWith(TripleConstant.HEADER_BIN_SUFFIX) - && key.length() > TripleConstant.HEADER_BIN_SUFFIX.length()) { + && key.length() > TripleConstant.HEADER_BIN_SUFFIX.length()) { try { - String realKey = key.substring(0, - key.length() - TripleConstant.HEADER_BIN_SUFFIX.length()); + String realKey = key.substring(0, key.length() - TripleConstant.HEADER_BIN_SUFFIX.length()); byte[] value = StreamUtils.decodeASCIIByte(header.getValue()); attachments.put(realKey, value); } catch (Exception e) { @@ -85,12 +84,15 @@ public abstract class AbstractH2TransportListener implements H2TransportListener // If convertUpperHeaderSupplier does not return String, just fail... // Internal invocation, use INTERNAL_ERROR instead. - LOGGER.error(INTERNAL_ERROR, "wrong internal invocation", "", "Triple convertNoLowerCaseHeader error, obj is not String"); + LOGGER.error( + INTERNAL_ERROR, + "wrong internal invocation", + "", + "Triple convertNoLowerCaseHeader error, obj is not String"); } return attachments; } - protected Map filterReservedHeaders(Http2Headers trailers) { if (trailers == null) { return Collections.emptyMap(); @@ -104,5 +106,4 @@ public abstract class AbstractH2TransportListener implements H2TransportListener } return excludeHeaders; } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/GracefulShutdown.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/GracefulShutdown.java index 5e7090c6c8..29c0b6f44f 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/GracefulShutdown.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/GracefulShutdown.java @@ -14,9 +14,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.transport; +import java.util.concurrent.TimeUnit; + import io.netty.buffer.ByteBufUtil; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; @@ -27,8 +28,6 @@ import io.netty.handler.codec.http2.Http2GoAwayFrame; import io.netty.handler.codec.http2.Http2PingFrame; import io.netty.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - public class GracefulShutdown { static final long GRACEFUL_SHUTDOWN_PING = 0x97ACEF001L; private static final long GRACEFUL_SHUTDOWN_PING_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(10); @@ -45,14 +44,12 @@ public class GracefulShutdown { } public void gracefulShutdown() { - Http2GoAwayFrame goAwayFrame = new DefaultHttp2GoAwayFrame(Http2Error.NO_ERROR, ByteBufUtil - .writeAscii(ctx.alloc(), goAwayMessage)); + Http2GoAwayFrame goAwayFrame = + new DefaultHttp2GoAwayFrame(Http2Error.NO_ERROR, ByteBufUtil.writeAscii(ctx.alloc(), goAwayMessage)); goAwayFrame.setExtraStreamIds(Integer.MAX_VALUE); ctx.writeAndFlush(goAwayFrame); - pingFuture = ctx.executor().schedule( - () -> secondGoAwayAndClose(ctx), - GRACEFUL_SHUTDOWN_PING_TIMEOUT_NANOS, - TimeUnit.NANOSECONDS); + pingFuture = ctx.executor() + .schedule(() -> secondGoAwayAndClose(ctx), GRACEFUL_SHUTDOWN_PING_TIMEOUT_NANOS, TimeUnit.NANOSECONDS); Http2PingFrame pingFrame = new DefaultHttp2PingFrame(GRACEFUL_SHUTDOWN_PING, false); ctx.writeAndFlush(pingFrame); @@ -67,10 +64,10 @@ public class GracefulShutdown { pingFuture.cancel(false); try { - Http2GoAwayFrame goAwayFrame = new DefaultHttp2GoAwayFrame(Http2Error.NO_ERROR, - ByteBufUtil.writeAscii(this.ctx.alloc(), this.goAwayMessage)); + Http2GoAwayFrame goAwayFrame = new DefaultHttp2GoAwayFrame( + Http2Error.NO_ERROR, ByteBufUtil.writeAscii(this.ctx.alloc(), this.goAwayMessage)); ctx.writeAndFlush(goAwayFrame); - //TODO support customize graceful shutdown timeout mills + // TODO support customize graceful shutdown timeout mills ctx.close(originPromise); } catch (Exception e) { ctx.fireExceptionCaught(e); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/H2TransportListener.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/H2TransportListener.java index 3f85317850..2d6c62e0be 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/H2TransportListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/H2TransportListener.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.transport; import io.netty.buffer.ByteBuf; @@ -42,7 +41,5 @@ public interface H2TransportListener { */ void onData(ByteBuf data, boolean endStream); - void cancelByRemote(long errorCode); - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleCommandOutBoundHandler.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleCommandOutBoundHandler.java index 741b3dbfe8..0cfb8bbfd2 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleCommandOutBoundHandler.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleCommandOutBoundHandler.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.transport; import org.apache.dubbo.rpc.protocol.tri.command.QueuedCommand; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleGoAwayHandler.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleGoAwayHandler.java index 14e652adf4..3da48c1d6f 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleGoAwayHandler.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleGoAwayHandler.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.transport; import org.apache.dubbo.common.logger.Logger; @@ -31,15 +30,16 @@ public class TripleGoAwayHandler extends ChannelDuplexHandler { private static final Logger logger = LoggerFactory.getLogger(TripleGoAwayHandler.class); - public TripleGoAwayHandler() { - } + public TripleGoAwayHandler() {} @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof Http2GoAwayFrame) { - final ConnectionHandler connectionHandler = (ConnectionHandler) ctx.pipeline().get(Constants.CONNECTION_HANDLER_NAME); + final ConnectionHandler connectionHandler = + (ConnectionHandler) ctx.pipeline().get(Constants.CONNECTION_HANDLER_NAME); if (logger.isInfoEnabled()) { - logger.info("Receive go away frame of " + ctx.channel().localAddress() + " -> " + ctx.channel().remoteAddress() + " and will reconnect later."); + logger.info("Receive go away frame of " + ctx.channel().localAddress() + " -> " + + ctx.channel().remoteAddress() + " and will reconnect later."); } connectionHandler.onGoAway(ctx.channel()); } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2ClientResponseHandler.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2ClientResponseHandler.java index c53e04d6c5..b8e9230eb5 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2ClientResponseHandler.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2ClientResponseHandler.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.transport; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; @@ -32,11 +31,10 @@ import io.netty.handler.codec.http2.Http2StreamFrame; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_SERIALIZE_TRIPLE; -public final class TripleHttp2ClientResponseHandler extends - SimpleChannelInboundHandler { +public final class TripleHttp2ClientResponseHandler extends SimpleChannelInboundHandler { - private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger( - TripleHttp2ClientResponseHandler.class); + private static final ErrorTypeAwareLogger LOGGER = + LoggerFactory.getErrorTypeAwareLogger(TripleHttp2ClientResponseHandler.class); private final H2TransportListener transportListener; public TripleHttp2ClientResponseHandler(H2TransportListener listener) { @@ -51,8 +49,7 @@ public final class TripleHttp2ClientResponseHandler extends Http2GoAwayFrame event = (Http2GoAwayFrame) evt; ctx.close(); LOGGER.debug( - "Event triggered, event name is: " + event.name() + ", last stream id is: " - + event.lastStreamId()); + "Event triggered, event name is: " + event.name() + ", last stream id is: " + event.lastStreamId()); } else if (evt instanceof Http2ResetFrame) { onResetRead(ctx, (Http2ResetFrame) evt); } @@ -72,7 +69,11 @@ public final class TripleHttp2ClientResponseHandler extends } private void onResetRead(ChannelHandlerContext ctx, Http2ResetFrame resetFrame) { - LOGGER.warn(PROTOCOL_FAILED_SERIALIZE_TRIPLE, "", "", "Triple Client received remote reset errorCode=" + resetFrame.errorCode()); + LOGGER.warn( + PROTOCOL_FAILED_SERIALIZE_TRIPLE, + "", + "", + "Triple Client received remote reset errorCode=" + resetFrame.errorCode()); transportListener.cancelByRemote(resetFrame.errorCode()); ctx.close(); } @@ -84,12 +85,14 @@ public final class TripleHttp2ClientResponseHandler extends @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { - final TriRpcStatus status = TriRpcStatus.INTERNAL - .withCause(cause); - LOGGER.warn(PROTOCOL_FAILED_SERIALIZE_TRIPLE, "", "", "Meet Exception on ClientResponseHandler, status code is: " + status.code, - cause); + final TriRpcStatus status = TriRpcStatus.INTERNAL.withCause(cause); + LOGGER.warn( + PROTOCOL_FAILED_SERIALIZE_TRIPLE, + "", + "", + "Meet Exception on ClientResponseHandler, status code is: " + status.code, + cause); transportListener.cancelByRemote(Http2Error.INTERNAL_ERROR.code()); ctx.close(); } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2FrameServerHandler.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2FrameServerHandler.java index 4b17e82b29..daebefc339 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2FrameServerHandler.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2FrameServerHandler.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.transport; -import io.netty.handler.codec.http2.Http2StreamChannel; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.HeaderFilter; @@ -28,42 +26,43 @@ import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.tri.compressor.DeCompressor; import org.apache.dubbo.rpc.protocol.tri.stream.TripleServerStream; +import java.util.List; +import java.util.concurrent.Executor; + import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http2.Http2DataFrame; import io.netty.handler.codec.http2.Http2HeadersFrame; import io.netty.handler.codec.http2.Http2ResetFrame; +import io.netty.handler.codec.http2.Http2StreamChannel; import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCounted; -import java.util.List; -import java.util.concurrent.Executor; - import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_RESPONSE; public class TripleHttp2FrameServerHandler extends ChannelDuplexHandler { - - private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger( - TripleHttp2FrameServerHandler.class); + private static final ErrorTypeAwareLogger LOGGER = + LoggerFactory.getErrorTypeAwareLogger(TripleHttp2FrameServerHandler.class); private final PathResolver pathResolver; private final ExecutorSupport executorSupport; private final String acceptEncoding; private final TripleServerStream tripleServerStream; public TripleHttp2FrameServerHandler( - FrameworkModel frameworkModel, - ExecutorSupport executorSupport, - List filters, - Http2StreamChannel channel, - TripleWriteQueue writeQueue) { + FrameworkModel frameworkModel, + ExecutorSupport executorSupport, + List filters, + Http2StreamChannel channel, + TripleWriteQueue writeQueue) { this.executorSupport = executorSupport; - this.acceptEncoding = String.join(",", - frameworkModel.getExtensionLoader(DeCompressor.class).getSupportedExtensions()); - this.pathResolver = frameworkModel.getExtensionLoader(PathResolver.class) - .getDefaultExtension(); + this.acceptEncoding = String.join( + ",", frameworkModel.getExtensionLoader(DeCompressor.class).getSupportedExtensions()); + this.pathResolver = + frameworkModel.getExtensionLoader(PathResolver.class).getDefaultExtension(); // The executor will be assigned in onHeadersRead method - tripleServerStream = new TripleServerStream(channel, frameworkModel, null, pathResolver, acceptEncoding, filters, writeQueue); + tripleServerStream = new TripleServerStream( + channel, frameworkModel, null, pathResolver, acceptEncoding, filters, writeQueue); } @Override @@ -88,7 +87,8 @@ public class TripleHttp2FrameServerHandler extends ChannelDuplexHandler { } public void onResetRead(ChannelHandlerContext ctx, Http2ResetFrame frame) { - LOGGER.warn(PROTOCOL_FAILED_RESPONSE, "", "", "Triple Server received remote reset errorCode=" + frame.errorCode()); + LOGGER.warn( + PROTOCOL_FAILED_RESPONSE, "", "", "Triple Server received remote reset errorCode=" + frame.errorCode()); if (tripleServerStream != null) { tripleServerStream.transportObserver.cancelByRemote(frame.errorCode()); } @@ -99,8 +99,7 @@ public class TripleHttp2FrameServerHandler extends ChannelDuplexHandler { if (LOGGER.isWarnEnabled()) { LOGGER.warn(PROTOCOL_FAILED_RESPONSE, "", "", "Exception in processing triple message", cause); } - TriRpcStatus status = TriRpcStatus.getStatus(cause, - "Provider's error:\n" + cause.getMessage()); + TriRpcStatus status = TriRpcStatus.getStatus(cause, "Provider's error:\n" + cause.getMessage()); tripleServerStream.cancelByLocal(status); } @@ -113,5 +112,4 @@ public class TripleHttp2FrameServerHandler extends ChannelDuplexHandler { tripleServerStream.setExecutor(executor); tripleServerStream.transportObserver.onHeader(msg.headers(), msg.isEndStream()); } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleIsolationExecutorSupport.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleIsolationExecutorSupport.java index a00de30f5a..cd70a2a3b5 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleIsolationExecutorSupport.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleIsolationExecutorSupport.java @@ -25,9 +25,9 @@ import org.apache.dubbo.remoting.http12.h2.Http2Header; import org.apache.dubbo.rpc.executor.AbstractIsolationExecutorSupport; import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum; - public class TripleIsolationExecutorSupport extends AbstractIsolationExecutorSupport { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(TripleIsolationExecutorSupport.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(TripleIsolationExecutorSupport.class); public TripleIsolationExecutorSupport(URL url) { super(url); @@ -44,12 +44,12 @@ public class TripleIsolationExecutorSupport extends AbstractIsolationExecutorSup String path = http2Metadata.path(); String[] parts = path.split("/"); // path like /{interfaceName}/{methodName} String interfaceName = parts[1]; - String version = headers.containsKey(TripleHeaderEnum.SERVICE_VERSION.getHeader()) ? - headers.getFirst(TripleHeaderEnum.SERVICE_VERSION.getHeader()) : null; - String group = headers.containsKey(TripleHeaderEnum.SERVICE_GROUP.getHeader()) ? - headers.getFirst(TripleHeaderEnum.SERVICE_GROUP.getHeader()) : null; + String version = headers.containsKey(TripleHeaderEnum.SERVICE_VERSION.getHeader()) + ? headers.getFirst(TripleHeaderEnum.SERVICE_VERSION.getHeader()) + : null; + String group = headers.containsKey(TripleHeaderEnum.SERVICE_GROUP.getHeader()) + ? headers.getFirst(TripleHeaderEnum.SERVICE_GROUP.getHeader()) + : null; return new ServiceKey(interfaceName, version, group); } - - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleServerConnectionHandler.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleServerConnectionHandler.java index 5750470384..06c517208e 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleServerConnectionHandler.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleServerConnectionHandler.java @@ -14,9 +14,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.transport; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; +import org.apache.dubbo.common.logger.LoggerFactory; + +import java.io.IOException; +import java.net.SocketException; +import java.util.HashSet; +import java.util.Set; + import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.http2.DefaultHttp2ResetFrame; @@ -25,19 +32,13 @@ import io.netty.handler.codec.http2.Http2Error; import io.netty.handler.codec.http2.Http2GoAwayFrame; import io.netty.handler.codec.http2.Http2PingFrame; import io.netty.util.ReferenceCountUtil; -import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; -import org.apache.dubbo.common.logger.LoggerFactory; - -import java.io.IOException; -import java.net.SocketException; -import java.util.HashSet; -import java.util.Set; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_RESPONSE; import static org.apache.dubbo.rpc.protocol.tri.transport.GracefulShutdown.GRACEFUL_SHUTDOWN_PING; public class TripleServerConnectionHandler extends Http2ChannelDuplexHandler { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(TripleServerConnectionHandler.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(TripleServerConnectionHandler.class); // Some exceptions are not very useful and add too much noise to the log private static final Set QUIET_EXCEPTIONS = new HashSet<>(); private static final Set> QUIET_EXCEPTIONS_CLASS = new HashSet<>(); @@ -56,7 +57,11 @@ public class TripleServerConnectionHandler extends Http2ChannelDuplexHandler { if (((Http2PingFrame) msg).content() == GRACEFUL_SHUTDOWN_PING) { if (gracefulShutdown == null) { // this should never happen - logger.warn(PROTOCOL_FAILED_RESPONSE, "", "", "Received GRACEFUL_SHUTDOWN_PING Ack but gracefulShutdown is null"); + logger.warn( + PROTOCOL_FAILED_RESPONSE, + "", + "", + "Received GRACEFUL_SHUTDOWN_PING Ack but gracefulShutdown is null"); } else { gracefulShutdown.secondGoAwayAndClose(ctx); } @@ -71,9 +76,9 @@ public class TripleServerConnectionHandler extends Http2ChannelDuplexHandler { @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); - //reset all active stream on connection close + // reset all active stream on connection close forEachActiveStream(stream -> { - //ignore remote side close + // ignore remote side close if (!stream.state().remoteSideOpen()) { return true; } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleTailHandler.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleTailHandler.java index b7d1410d50..7e0742648e 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleTailHandler.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleTailHandler.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.transport; import io.netty.channel.ChannelHandlerContext; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleWriteQueue.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleWriteQueue.java index c659e9e708..7585e9a484 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleWriteQueue.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleWriteQueue.java @@ -14,22 +14,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.transport; -import io.netty.channel.Channel; -import io.netty.channel.ChannelFuture; -import io.netty.channel.ChannelPromise; import org.apache.dubbo.common.BatchExecutorQueue; import org.apache.dubbo.rpc.protocol.tri.command.QueuedCommand; import java.util.concurrent.CompletionException; import java.util.concurrent.Executor; +import io.netty.channel.Channel; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelPromise; + public class TripleWriteQueue extends BatchExecutorQueue { - public TripleWriteQueue() { - } + public TripleWriteQueue() {} public TripleWriteQueue(int chunkSize) { super(chunkSize); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/WriteQueue.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/WriteQueue.java index b0125681b8..ff839473b7 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/WriteQueue.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/WriteQueue.java @@ -14,19 +14,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.transport; import org.apache.dubbo.rpc.protocol.tri.command.QueuedCommand; -import io.netty.channel.Channel; -import io.netty.channel.ChannelFuture; -import io.netty.channel.ChannelPromise; - import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; +import io.netty.channel.Channel; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelPromise; + @Deprecated public class WriteQueue { @@ -87,5 +86,4 @@ public class WriteQueue { } } } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/stub/StubInvocationUtil.java b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/stub/StubInvocationUtil.java index 123cbbfd27..39bc3d0aba 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/stub/StubInvocationUtil.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/stub/StubInvocationUtil.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.stub; import org.apache.dubbo.common.stream.StreamObserver; @@ -26,13 +25,12 @@ import org.apache.dubbo.rpc.proxy.InvocationUtil; public class StubInvocationUtil { - public static R unaryCall(Invoker invoker, MethodDescriptor methodDescriptor, - T request) { - return (R) call(invoker, methodDescriptor, new Object[]{request}); + public static R unaryCall(Invoker invoker, MethodDescriptor methodDescriptor, T request) { + return (R) call(invoker, methodDescriptor, new Object[] {request}); } - public static void unaryCall(Invoker invoker, MethodDescriptor method, T request, - StreamObserver responseObserver) { + public static void unaryCall( + Invoker invoker, MethodDescriptor method, T request, StreamObserver responseObserver) { try { Object res = unaryCall(invoker, method, request); responseObserver.onNext((R) res); @@ -42,23 +40,25 @@ public class StubInvocationUtil { responseObserver.onCompleted(); } - public static StreamObserver biOrClientStreamCall(Invoker invoker, - MethodDescriptor method, StreamObserver responseObserver) { - return (StreamObserver) call(invoker, method, new Object[]{responseObserver}); + public static StreamObserver biOrClientStreamCall( + Invoker invoker, MethodDescriptor method, StreamObserver responseObserver) { + return (StreamObserver) call(invoker, method, new Object[] {responseObserver}); } - public static void serverStreamCall(Invoker invoker, MethodDescriptor method, - T request, StreamObserver responseObserver) { - call(invoker, method, new Object[]{request, responseObserver}); + public static void serverStreamCall( + Invoker invoker, MethodDescriptor method, T request, StreamObserver responseObserver) { + call(invoker, method, new Object[] {request, responseObserver}); } - private static Object call(Invoker invoker, MethodDescriptor methodDescriptor, - Object[] arguments) { - RpcInvocation rpcInvocation = new RpcInvocation(invoker.getUrl().getServiceModel(), - methodDescriptor.getMethodName(), invoker.getInterface().getName(), - invoker.getUrl().getProtocolServiceKey(), methodDescriptor.getParameterClasses(), - arguments); - //When there are multiple MethodDescriptors with the same method name, the return type will be wrong + private static Object call(Invoker invoker, MethodDescriptor methodDescriptor, Object[] arguments) { + RpcInvocation rpcInvocation = new RpcInvocation( + invoker.getUrl().getServiceModel(), + methodDescriptor.getMethodName(), + invoker.getInterface().getName(), + invoker.getUrl().getProtocolServiceKey(), + methodDescriptor.getParameterClasses(), + arguments); + // When there are multiple MethodDescriptors with the same method name, the return type will be wrong rpcInvocation.setReturnType(methodDescriptor.getReturnClass()); try { return InvocationUtil.invoke(invoker, rpcInvocation); @@ -66,9 +66,7 @@ public class StubInvocationUtil { if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { - throw TriRpcStatus.INTERNAL - .withCause(e) - .asException(); + throw TriRpcStatus.INTERNAL.withCause(e).asException(); } } } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/StatusRpcExceptionTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/StatusRpcExceptionTest.java index 67ad0b36c9..712c60d3e8 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/StatusRpcExceptionTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/StatusRpcExceptionTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc; import org.junit.jupiter.api.Assertions; @@ -24,7 +23,7 @@ class StatusRpcExceptionTest { @Test void getStatus() { - Assertions.assertEquals(TriRpcStatus.INTERNAL, - ((StatusRpcException) TriRpcStatus.INTERNAL.asException()).getStatus()); + Assertions.assertEquals( + TriRpcStatus.INTERNAL, ((StatusRpcException) TriRpcStatus.INTERNAL.asException()).getStatus()); } } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/TriRpcStatusTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/TriRpcStatusTest.java index 92bad1446d..0bbc325861 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/TriRpcStatusTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/TriRpcStatusTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc; import org.apache.dubbo.remoting.TimeoutException; @@ -39,7 +38,7 @@ class TriRpcStatusTest { TriRpcStatus.fromCode(1000); fail(); } catch (Throwable t) { - //pass + // pass } } @@ -51,21 +50,21 @@ class TriRpcStatusTest { @Test void getStatus() { StatusRpcException rpcException = new StatusRpcException(TriRpcStatus.INTERNAL); - Assertions.assertEquals(TriRpcStatus.INTERNAL.code, - TriRpcStatus.getStatus(rpcException).code); + Assertions.assertEquals(TriRpcStatus.INTERNAL.code, TriRpcStatus.getStatus(rpcException).code); } @Test void testGetStatus() { StatusRpcException rpcException = new StatusRpcException(TriRpcStatus.INTERNAL); - Assertions.assertEquals(TriRpcStatus.INTERNAL.code, - TriRpcStatus.getStatus(rpcException, null).code); + Assertions.assertEquals(TriRpcStatus.INTERNAL.code, TriRpcStatus.getStatus(rpcException, null).code); - Assertions.assertEquals(TriRpcStatus.DEADLINE_EXCEEDED.code, - TriRpcStatus.getStatus(new RpcException(RpcException.TIMEOUT_EXCEPTION), null).code); + Assertions.assertEquals( + TriRpcStatus.DEADLINE_EXCEEDED.code, + TriRpcStatus.getStatus(new RpcException(RpcException.TIMEOUT_EXCEPTION), null).code); - Assertions.assertEquals(TriRpcStatus.DEADLINE_EXCEEDED.code, - TriRpcStatus.getStatus(new TimeoutException(true, null, null), null).code); + Assertions.assertEquals( + TriRpcStatus.DEADLINE_EXCEEDED.code, + TriRpcStatus.getStatus(new TimeoutException(true, null, null), null).code); } @Test @@ -86,8 +85,7 @@ class TriRpcStatusTest { @Test void decodeMessage() { String message = "😯"; - Assertions.assertEquals(message, - TriRpcStatus.decodeMessage(TriRpcStatus.encodeMessage(message))); + Assertions.assertEquals(message, TriRpcStatus.decodeMessage(TriRpcStatus.encodeMessage(message))); Assertions.assertTrue(TriRpcStatus.decodeMessage("").isEmpty()); Assertions.assertTrue(TriRpcStatus.decodeMessage(null).isEmpty()); @@ -96,26 +94,23 @@ class TriRpcStatusTest { @Test void httpStatusToGrpcCode() { Assertions.assertEquals(Code.UNIMPLEMENTED, TriRpcStatus.httpStatusToGrpcCode(404)); - Assertions.assertEquals(Code.UNAVAILABLE, - TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.BAD_GATEWAY.code())); - Assertions.assertEquals(Code.UNAVAILABLE, - TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.TOO_MANY_REQUESTS.code())); - Assertions.assertEquals(Code.UNAVAILABLE, - TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.SERVICE_UNAVAILABLE.code())); - Assertions.assertEquals(Code.UNAVAILABLE, - TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.GATEWAY_TIMEOUT.code())); - Assertions.assertEquals(Code.INTERNAL, - TriRpcStatus.httpStatusToGrpcCode( - HttpResponseStatus.CONTINUE.code())); - Assertions.assertEquals(Code.INTERNAL, - TriRpcStatus.httpStatusToGrpcCode( - HttpResponseStatus.REQUEST_HEADER_FIELDS_TOO_LARGE.code())); - Assertions.assertEquals(Code.UNKNOWN, - TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.ACCEPTED.code())); - Assertions.assertEquals(Code.PERMISSION_DENIED, - TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.FORBIDDEN.code())); - Assertions.assertEquals(Code.UNIMPLEMENTED, - TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.NOT_FOUND.code())); + Assertions.assertEquals( + Code.UNAVAILABLE, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.BAD_GATEWAY.code())); + Assertions.assertEquals( + Code.UNAVAILABLE, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.TOO_MANY_REQUESTS.code())); + Assertions.assertEquals( + Code.UNAVAILABLE, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.SERVICE_UNAVAILABLE.code())); + Assertions.assertEquals( + Code.UNAVAILABLE, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.GATEWAY_TIMEOUT.code())); + Assertions.assertEquals(Code.INTERNAL, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.CONTINUE.code())); + Assertions.assertEquals( + Code.INTERNAL, + TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.REQUEST_HEADER_FIELDS_TOO_LARGE.code())); + Assertions.assertEquals(Code.UNKNOWN, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.ACCEPTED.code())); + Assertions.assertEquals( + Code.PERMISSION_DENIED, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.FORBIDDEN.code())); + Assertions.assertEquals( + Code.UNIMPLEMENTED, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.NOT_FOUND.code())); } @Test @@ -154,17 +149,18 @@ class TriRpcStatusTest { @Test void asException() { StatusRpcException exception = TriRpcStatus.NOT_FOUND - .withDescription("desc") - .withCause(new IllegalStateException("test")).asException(); + .withDescription("desc") + .withCause(new IllegalStateException("test")) + .asException(); Assertions.assertEquals(Code.NOT_FOUND, exception.getStatus().code); } @Test void toEncodedMessage() { String message = TriRpcStatus.NOT_FOUND - .withDescription("desc") - .withCause(new IllegalStateException("test")) - .toEncodedMessage(); + .withDescription("desc") + .withCause(new IllegalStateException("test")) + .toEncodedMessage(); Assertions.assertTrue(message.contains("desc")); Assertions.assertTrue(message.contains("test")); } @@ -172,9 +168,9 @@ class TriRpcStatusTest { @Test void toMessageWithoutCause() { String message = TriRpcStatus.NOT_FOUND - .withDescription("desc") - .withCause(new IllegalStateException("test")) - .toMessageWithoutCause(); + .withDescription("desc") + .withCause(new IllegalStateException("test")) + .toMessageWithoutCause(); Assertions.assertTrue(message.contains("desc")); Assertions.assertFalse(message.contains("test")); } @@ -182,9 +178,9 @@ class TriRpcStatusTest { @Test void toMessage() { String message = TriRpcStatus.NOT_FOUND - .withDescription("desc") - .withCause(new IllegalStateException("test")) - .toMessage(); + .withDescription("desc") + .withCause(new IllegalStateException("test")) + .toMessage(); Assertions.assertTrue(message.contains("desc")); Assertions.assertTrue(message.contains("test")); } @@ -207,19 +203,15 @@ class TriRpcStatusTest { @Test void toMessage2() { String content = "\t\ntest with whitespace\r\nand Unicode BMP ☺ and non-BMP 😈\t\n"; - final TriRpcStatus status = TriRpcStatus.INTERNAL - .withDescription(content); + final TriRpcStatus status = TriRpcStatus.INTERNAL.withDescription(content); Assertions.assertEquals(content, status.toMessage()); } @Test void triCodeToDubboCode() { - Assertions.assertEquals(TIMEOUT_EXCEPTION, - TriRpcStatus.triCodeToDubboCode(Code.DEADLINE_EXCEEDED)); - Assertions.assertEquals(FORBIDDEN_EXCEPTION, - TriRpcStatus.triCodeToDubboCode(Code.PERMISSION_DENIED)); - Assertions.assertEquals(METHOD_NOT_FOUND, - TriRpcStatus.triCodeToDubboCode(Code.UNIMPLEMENTED)); + Assertions.assertEquals(TIMEOUT_EXCEPTION, TriRpcStatus.triCodeToDubboCode(Code.DEADLINE_EXCEEDED)); + Assertions.assertEquals(FORBIDDEN_EXCEPTION, TriRpcStatus.triCodeToDubboCode(Code.PERMISSION_DENIED)); + Assertions.assertEquals(METHOD_NOT_FOUND, TriRpcStatus.triCodeToDubboCode(Code.UNIMPLEMENTED)); Assertions.assertEquals(UNKNOWN_EXCEPTION, TriRpcStatus.triCodeToDubboCode(Code.UNKNOWN)); } } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/CancelableStreamObserverTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/CancelableStreamObserverTest.java index 1de8acf020..06c6fabfc7 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/CancelableStreamObserverTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/CancelableStreamObserverTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.rpc.CancellationContext; @@ -28,19 +27,13 @@ class CancelableStreamObserverTest { void setCancellationContext() { CancelableStreamObserver observer = new CancelableStreamObserver() { @Override - public void onNext(Object data) { - - } + public void onNext(Object data) {} @Override - public void onError(Throwable throwable) { - - } + public void onError(Throwable throwable) {} @Override - public void onCompleted() { - - } + public void onCompleted() {} }; CancellationContext cancellationContext = new CancellationContext(); observer.setCancellationContext(cancellationContext); @@ -49,6 +42,5 @@ class CancelableStreamObserverTest { } @Test - void cancel() { - } + void cancel() {} } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/ClassLoadUtilTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/ClassLoadUtilTest.java index 81875ccdc3..28d4f84fd0 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/ClassLoadUtilTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/ClassLoadUtilTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import org.junit.jupiter.api.Test; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/DeadlineFutureTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/DeadlineFutureTest.java index 09d03513eb..7de864f349 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/DeadlineFutureTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/DeadlineFutureTest.java @@ -14,20 +14,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.StatusRpcException; import org.apache.dubbo.rpc.TriRpcStatus; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; + import io.netty.util.concurrent.ImmediateEventExecutor; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; - class DeadlineFutureTest { @Test @@ -35,15 +34,14 @@ class DeadlineFutureTest { String service = "service"; String method = "method"; String address = "localhost:12201"; - DeadlineFuture timeout = DeadlineFuture.newFuture(service, method, address, 10, - ImmediateEventExecutor.INSTANCE); + DeadlineFuture timeout = + DeadlineFuture.newFuture(service, method, address, 10, ImmediateEventExecutor.INSTANCE); TimeUnit.MILLISECONDS.sleep(20); AppResponse timeoutResponse = timeout.get(); Assertions.assertTrue(timeoutResponse.getException() instanceof StatusRpcException); - - DeadlineFuture success = DeadlineFuture.newFuture(service, method, address, 1000, - ImmediateEventExecutor.INSTANCE); + DeadlineFuture success = + DeadlineFuture.newFuture(service, method, address, 1000, ImmediateEventExecutor.INSTANCE); AppResponse response = new AppResponse(); success.received(TriRpcStatus.OK, response); AppResponse response1 = success.get(); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/DescriptorService.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/DescriptorService.java index 51f4d1000e..7d93565c33 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/DescriptorService.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/DescriptorService.java @@ -22,7 +22,6 @@ import java.util.concurrent.CompletableFuture; public interface DescriptorService { - CompletableFuture unaryFuture(); void noParameterMethod(); @@ -41,7 +40,6 @@ public interface DescriptorService { */ String noParameterAndReturnJavaClassMethod(); - /** * bi stream need wrapper * @@ -71,7 +69,6 @@ public interface DescriptorService { void sayHelloServerStream2(Object request, StreamObserver reply); /***********************grpc******************************/ - java.util.Iterator iteratorServerStream(HelloReply request); reactor.core.publisher.Mono reactorMethod(HelloReply reactorRequest); @@ -102,6 +99,4 @@ public interface DescriptorService { StreamObserver testErrorBiStream3(StreamObserver observer); StreamObserver testErrorBiStream4(StreamObserver observer, String str); - - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/ExceptionUtilsTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/ExceptionUtilsTest.java index 598da917f2..3454548670 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/ExceptionUtilsTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/ExceptionUtilsTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.common.URL; @@ -29,16 +28,18 @@ import org.apache.dubbo.rpc.model.*; import org.apache.dubbo.rpc.protocol.tri.support.IGreeter2; import org.apache.dubbo.rpc.protocol.tri.support.IGreeter2Impl; import org.apache.dubbo.rpc.protocol.tri.support.IGreeterException; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class ExceptionUtilsTest { private IllegalStateException exception = new IllegalStateException("Exception0"); + @Test void getStackTrace() { Assertions.assertTrue(ExceptionUtils.getStackTrace(exception).contains("Exception0")); @@ -46,8 +47,7 @@ class ExceptionUtilsTest { @Test void getStackFrameString() { - String str = ExceptionUtils.getStackFrameString( - Arrays.stream(exception.getStackTrace()) + String str = ExceptionUtils.getStackFrameString(Arrays.stream(exception.getStackTrace()) .map(StackTraceElement::toString) .collect(Collectors.toList())); Assertions.assertTrue(str.contains("ExceptionUtilsTest")); @@ -56,67 +56,67 @@ class ExceptionUtilsTest { @Test void getStackFrames() { StackTraceElement[] traces = exception.getStackTrace(); - List frames = Arrays.stream(traces) - .map(StackTraceElement::toString) - .collect(Collectors.toList()); + List frames = + Arrays.stream(traces).map(StackTraceElement::toString).collect(Collectors.toList()); String str = ExceptionUtils.getStackFrameString(frames); - List stackFrames = Arrays.stream(ExceptionUtils.getStackFrames(str)) - .collect(Collectors.toList()); - Assertions.assertEquals(frames,stackFrames); + List stackFrames = + Arrays.stream(ExceptionUtils.getStackFrames(str)).collect(Collectors.toList()); + Assertions.assertEquals(frames, stackFrames); } @Test void testGetStackFrames() { String[] stackFrames = ExceptionUtils.getStackFrames(exception); - Assertions.assertNotEquals(0,stackFrames.length); + Assertions.assertNotEquals(0, stackFrames.length); } @Test void getStackFrameList() { List stackFrameList = ExceptionUtils.getStackFrameList(exception, 10); - Assertions.assertEquals(10,stackFrameList.size()); + Assertions.assertEquals(10, stackFrameList.size()); } @Test void testGetStackFrameList() { List stackFrameList = ExceptionUtils.getStackFrameList(exception); - Assertions.assertNotEquals(10,stackFrameList.size()); + Assertions.assertNotEquals(10, stackFrameList.size()); } @Test - void testSelfDefineException() throws Exception{ + void testSelfDefineException() throws Exception { IGreeter2 serviceImpl = new IGreeter2Impl(); int availablePort = NetUtils.getAvailablePort(); ApplicationModel applicationModel = ApplicationModel.defaultModel(); - URL providerUrl = URL.valueOf( - "tri://127.0.0.1:" + availablePort + "/" + IGreeter2.class.getName()).addParameter(CommonConstants.TIMEOUT_KEY, 10000);; + URL providerUrl = URL.valueOf("tri://127.0.0.1:" + availablePort + "/" + IGreeter2.class.getName()) + .addParameter(CommonConstants.TIMEOUT_KEY, 10000); + ; - ModuleServiceRepository serviceRepository = applicationModel.getDefaultModule() - .getServiceRepository(); + ModuleServiceRepository serviceRepository = + applicationModel.getDefaultModule().getServiceRepository(); ServiceDescriptor serviceDescriptor = serviceRepository.registerService(IGreeter2.class); ProviderModel providerModel = new ProviderModel( - providerUrl.getServiceKey(), - serviceImpl, - serviceDescriptor, - new ServiceMetadata(), ClassUtils.getClassLoader(IGreeter2.class)); + providerUrl.getServiceKey(), + serviceImpl, + serviceDescriptor, + new ServiceMetadata(), + ClassUtils.getClassLoader(IGreeter2.class)); serviceRepository.registerProvider(providerModel); providerUrl = providerUrl.setServiceModel(providerModel); Protocol protocol = new TripleProtocol(providerUrl.getOrDefaultFrameworkModel()); - ProxyFactory proxy = applicationModel.getExtensionLoader(ProxyFactory.class) - .getAdaptiveExtension(); + ProxyFactory proxy = + applicationModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Invoker invoker = proxy.getInvoker(serviceImpl, IGreeter2.class, providerUrl); Exporter export = protocol.export(invoker); - URL consumerUrl = URL.valueOf( - "tri://127.0.0.1:" + availablePort + "/" + IGreeter2.class.getName()).addParameter(CommonConstants.TIMEOUT_KEY, 10000); + URL consumerUrl = URL.valueOf("tri://127.0.0.1:" + availablePort + "/" + IGreeter2.class.getName()) + .addParameter(CommonConstants.TIMEOUT_KEY, 10000); - ConsumerModel consumerModel = new ConsumerModel(consumerUrl.getServiceKey(), null, - serviceDescriptor, null, - null, null); + ConsumerModel consumerModel = + new ConsumerModel(consumerUrl.getServiceKey(), null, serviceDescriptor, null, null, null); consumerUrl = consumerUrl.setServiceModel(consumerModel); IGreeter2 greeterProxy = proxy.getProxy(protocol.refer(IGreeter2.class, consumerUrl)); Thread.sleep(1000); @@ -138,6 +138,5 @@ class ExceptionUtilsTest { // resource recycle. serviceRepository.destroy(); System.out.println("serviceRepository destroyed"); - } } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/HelloReply.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/HelloReply.java index fa03322dc0..73df537e85 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/HelloReply.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/HelloReply.java @@ -14,8 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - - package org.apache.dubbo.rpc.protocol.tri; import com.google.protobuf.Message; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/Http2ProtocolDetectorTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/Http2ProtocolDetectorTest.java index 313396fc47..f9832a12d7 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/Http2ProtocolDetectorTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/Http2ProtocolDetectorTest.java @@ -42,16 +42,18 @@ class Http2ProtocolDetectorTest { ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(); ChannelBuffer in = new ByteBufferBackedChannelBuffer(byteBuf.nioBuffer()); ProtocolDetector.Result result = detector.detect(in); - Assertions.assertEquals(result.flag(), ProtocolDetector.Result.unrecognized().flag()); + Assertions.assertEquals( + result.flag(), ProtocolDetector.Result.unrecognized().flag()); byteBuf.writeBytes(connectionPrefaceBuf); result = detector.detect(new ByteBufferBackedChannelBuffer(byteBuf.nioBuffer())); - Assertions.assertEquals(result.flag(), ProtocolDetector.Result.recognized().flag()); + Assertions.assertEquals( + result.flag(), ProtocolDetector.Result.recognized().flag()); byteBuf.clear(); byteBuf.writeBytes(connectionPrefaceBuf, 0, 1); result = detector.detect(new ByteBufferBackedChannelBuffer(byteBuf.nioBuffer())); - Assertions.assertEquals(result.flag(), ProtocolDetector.Result.needMoreData().flag()); - + Assertions.assertEquals( + result.flag(), ProtocolDetector.Result.needMoreData().flag()); } } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/PbUnpackTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/PbUnpackTest.java index 919cfae3a1..4a3f6a8e06 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/PbUnpackTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/PbUnpackTest.java @@ -14,22 +14,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; +import java.io.IOException; + import io.grpc.health.v1.HealthCheckRequest; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.io.IOException; - class PbUnpackTest { @Test void unpack() throws IOException { - HealthCheckRequest req = HealthCheckRequest.newBuilder() - .setService("service") - .build(); + HealthCheckRequest req = + HealthCheckRequest.newBuilder().setService("service").build(); PbUnpack unpack = new PbUnpack<>(HealthCheckRequest.class); HealthCheckRequest obj = (HealthCheckRequest) unpack.unpack(req.toByteArray()); Assertions.assertEquals("service", obj.getService()); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/ReflectionPackableMethodTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/ReflectionPackableMethodTest.java index 1eadb5305e..46c79a9ae8 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/ReflectionPackableMethodTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/ReflectionPackableMethodTest.java @@ -20,15 +20,15 @@ import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.rpc.model.MethodDescriptor; import org.apache.dubbo.rpc.model.ReflectionMethodDescriptor; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.util.concurrent.CompletableFuture; + import io.reactivex.Single; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.util.concurrent.CompletableFuture; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertSame; @@ -37,7 +37,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; class ReflectionPackableMethodTest { - @Test void testUnaryFuture() throws Exception { Method method = DescriptorService.class.getMethod("unaryFuture"); @@ -115,8 +114,8 @@ class ReflectionPackableMethodTest { @Test void testIsServerStream() throws NoSuchMethodException { - Method method = DescriptorService.class.getMethod("sayHelloServerStream", HelloReply.class, - StreamObserver.class); + Method method = + DescriptorService.class.getMethod("sayHelloServerStream", HelloReply.class, StreamObserver.class); ReflectionMethodDescriptor descriptor = new ReflectionMethodDescriptor(method); Assertions.assertFalse(needWrap(descriptor)); @@ -150,17 +149,15 @@ class ReflectionPackableMethodTest { MethodDescriptor descriptor3 = new ReflectionMethodDescriptor(method3); Assertions.assertFalse(needWrap(descriptor3)); - Method method4 = DescriptorService.class.getMethod("rxJavaMethod", Single.class); MethodDescriptor descriptor4 = new ReflectionMethodDescriptor(method4); Assertions.assertFalse(needWrap(descriptor4)); } - @Test void testMultiProtoParameter() throws Exception { - Method method = DescriptorService.class.getMethod("testMultiProtobufParameters", HelloReply.class, - HelloReply.class); + Method method = + DescriptorService.class.getMethod("testMultiProtobufParameters", HelloReply.class, HelloReply.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); needWrap(descriptor); @@ -184,29 +181,29 @@ class ReflectionPackableMethodTest { @Test void testErrorServerStream() throws Exception { - Method method = DescriptorService.class.getMethod("testErrorServerStream", StreamObserver.class, - HelloReply.class); + Method method = + DescriptorService.class.getMethod("testErrorServerStream", StreamObserver.class, HelloReply.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); needWrap(descriptor); }); - Method method2 = DescriptorService.class.getMethod("testErrorServerStream2", HelloReply.class, HelloReply.class, - StreamObserver.class); + Method method2 = DescriptorService.class.getMethod( + "testErrorServerStream2", HelloReply.class, HelloReply.class, StreamObserver.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method2); needWrap(descriptor); }); - Method method3 = DescriptorService.class.getMethod("testErrorServerStream3", String.class, - StreamObserver.class); + Method method3 = + DescriptorService.class.getMethod("testErrorServerStream3", String.class, StreamObserver.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method3); needWrap(descriptor); }); - Method method4 = DescriptorService.class.getMethod("testErrorServerStream4", String.class, String.class, - StreamObserver.class); + Method method4 = DescriptorService.class.getMethod( + "testErrorServerStream4", String.class, String.class, StreamObserver.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method4); needWrap(descriptor); @@ -247,15 +244,19 @@ class ReflectionPackableMethodTest { switch (method.getRpcType()) { case CLIENT_STREAM: case BI_STREAM: - actualRequestTypes = new Class[]{(Class) ((ParameterizedType) method.getMethod() - .getGenericReturnType()).getActualTypeArguments()[0]}; - actualResponseType = (Class) ((ParameterizedType) method.getMethod() - .getGenericParameterTypes()[0]).getActualTypeArguments()[0]; + actualRequestTypes = new Class[] { + (Class) + ((ParameterizedType) method.getMethod().getGenericReturnType()).getActualTypeArguments()[0] + }; + actualResponseType = + (Class) ((ParameterizedType) method.getMethod().getGenericParameterTypes()[0]) + .getActualTypeArguments()[0]; break; case SERVER_STREAM: actualRequestTypes = method.getMethod().getParameterTypes(); - actualResponseType = (Class) ((ParameterizedType) method.getMethod() - .getGenericParameterTypes()[1]).getActualTypeArguments()[0]; + actualResponseType = + (Class) ((ParameterizedType) method.getMethod().getGenericParameterTypes()[1]) + .getActualTypeArguments()[0]; break; case UNARY: actualRequestTypes = method.getParameterClasses(); @@ -267,5 +268,4 @@ class ReflectionPackableMethodTest { return ReflectionPackableMethod.needWrap(method, actualRequestTypes, actualResponseType); } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/SingleProtobufUtilsTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/SingleProtobufUtilsTest.java index d8fcd939c1..2cbbfbe724 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/SingleProtobufUtilsTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/SingleProtobufUtilsTest.java @@ -18,6 +18,10 @@ package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.triple.TripleWrapper; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + import com.google.protobuf.BoolValue; import com.google.protobuf.BytesValue; import com.google.protobuf.DoubleValue; @@ -35,10 +39,6 @@ import io.grpc.health.v1.HealthCheckResponse; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - /** * {@link SingleProtobufUtils} */ @@ -67,12 +67,14 @@ class SingleProtobufUtilsTest { Assertions.assertNotNull(parser); TripleWrapper.TripleRequestWrapper requestWrapper = TripleWrapper.TripleRequestWrapper.newBuilder() - .setSerializeType("hessian4").build(); + .setSerializeType("hessian4") + .build(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); SingleProtobufUtils.serialize(requestWrapper, bos); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - TripleWrapper.TripleRequestWrapper tripleRequestWrapper = SingleProtobufUtils.deserialize(bis, TripleWrapper.TripleRequestWrapper.class); + TripleWrapper.TripleRequestWrapper tripleRequestWrapper = + SingleProtobufUtils.deserialize(bis, TripleWrapper.TripleRequestWrapper.class); Assertions.assertEquals(tripleRequestWrapper.getSerializeType(), "hessian4"); } } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TripleCustomerProtocolWapperTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TripleCustomerProtocolWapperTest.java index 227a3cc84c..f15b69368a 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TripleCustomerProtocolWapperTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TripleCustomerProtocolWapperTest.java @@ -16,14 +16,15 @@ */ package org.apache.dubbo.rpc.protocol.tri; -import com.google.protobuf.ByteString; import org.apache.dubbo.triple.TripleWrapper; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import com.google.protobuf.ByteString; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + public class TripleCustomerProtocolWapperTest { @Test @@ -51,11 +52,14 @@ public class TripleCustomerProtocolWapperTest { @Test void testTripleRequestWrapperWithOnlySerializeType() { String serialize = "hession"; - TripleCustomerProtocolWapper.TripleRequestWrapper.Builder builder = TripleCustomerProtocolWapper.TripleRequestWrapper.Builder.newBuilder(); - TripleCustomerProtocolWapper.TripleRequestWrapper tripleRequestWrapper = builder.setSerializeType(serialize).build(); - final TripleWrapper.TripleRequestWrapper.Builder pbbuilder = TripleWrapper.TripleRequestWrapper.newBuilder() - .setSerializeType(serialize); - Assertions.assertArrayEquals(tripleRequestWrapper.toByteArray(), pbbuilder.build().toByteArray()); + TripleCustomerProtocolWapper.TripleRequestWrapper.Builder builder = + TripleCustomerProtocolWapper.TripleRequestWrapper.Builder.newBuilder(); + TripleCustomerProtocolWapper.TripleRequestWrapper tripleRequestWrapper = + builder.setSerializeType(serialize).build(); + final TripleWrapper.TripleRequestWrapper.Builder pbbuilder = + TripleWrapper.TripleRequestWrapper.newBuilder().setSerializeType(serialize); + Assertions.assertArrayEquals( + tripleRequestWrapper.toByteArray(), pbbuilder.build().toByteArray()); } @Test @@ -65,23 +69,24 @@ public class TripleCustomerProtocolWapperTest { byte[] secondArg = "i am second arg".getBytes(StandardCharsets.UTF_8); String serialize = "hession"; - TripleCustomerProtocolWapper.TripleRequestWrapper.Builder builder = TripleCustomerProtocolWapper.TripleRequestWrapper.Builder.newBuilder(); - TripleCustomerProtocolWapper.TripleRequestWrapper tripleRequestWrapper = builder - .setSerializeType(serialize) - .addArgTypes("com.google.protobuf.ByteString") - .addArgTypes("org.apache.dubbo.common.URL") - .addArgs(firstArg) - .addArgs(secondArg) - .build(); + TripleCustomerProtocolWapper.TripleRequestWrapper.Builder builder = + TripleCustomerProtocolWapper.TripleRequestWrapper.Builder.newBuilder(); + TripleCustomerProtocolWapper.TripleRequestWrapper tripleRequestWrapper = builder.setSerializeType(serialize) + .addArgTypes("com.google.protobuf.ByteString") + .addArgTypes("org.apache.dubbo.common.URL") + .addArgs(firstArg) + .addArgs(secondArg) + .build(); final TripleWrapper.TripleRequestWrapper.Builder pbbuilder = TripleWrapper.TripleRequestWrapper.newBuilder() - .setSerializeType(serialize) - .addArgTypes("com.google.protobuf.ByteString") - .addArgTypes("org.apache.dubbo.common.URL") - .addArgs(ByteString.copyFrom(firstArg)) - .addArgs(ByteString.copyFrom(secondArg)); + .setSerializeType(serialize) + .addArgTypes("com.google.protobuf.ByteString") + .addArgTypes("org.apache.dubbo.common.URL") + .addArgs(ByteString.copyFrom(firstArg)) + .addArgs(ByteString.copyFrom(secondArg)); - Assertions.assertArrayEquals(tripleRequestWrapper.toByteArray(), pbbuilder.build().toByteArray()); + Assertions.assertArrayEquals( + tripleRequestWrapper.toByteArray(), pbbuilder.build().toByteArray()); } @Test @@ -90,39 +95,42 @@ public class TripleCustomerProtocolWapperTest { byte[] secondArg = "i am second arg".getBytes(StandardCharsets.UTF_8); String serialize = "hession4"; - TripleCustomerProtocolWapper.TripleRequestWrapper.Builder builder = TripleCustomerProtocolWapper.TripleRequestWrapper.Builder.newBuilder(); - TripleCustomerProtocolWapper.TripleRequestWrapper tripleRequestWrapper = builder - .setSerializeType(serialize) - .addArgTypes("com.google.protobuf.ByteString") - .addArgTypes("org.apache.dubbo.common.URL") - .addArgs(firstArg) - .addArgs(secondArg) - .build(); + TripleCustomerProtocolWapper.TripleRequestWrapper.Builder builder = + TripleCustomerProtocolWapper.TripleRequestWrapper.Builder.newBuilder(); + TripleCustomerProtocolWapper.TripleRequestWrapper tripleRequestWrapper = builder.setSerializeType(serialize) + .addArgTypes("com.google.protobuf.ByteString") + .addArgTypes("org.apache.dubbo.common.URL") + .addArgs(firstArg) + .addArgs(secondArg) + .build(); final TripleWrapper.TripleRequestWrapper.Builder pbbuilder = TripleWrapper.TripleRequestWrapper.newBuilder() - .setSerializeType(serialize) - .addArgTypes("com.google.protobuf.ByteString") - .addArgTypes("org.apache.dubbo.common.URL") - .addArgs(ByteString.copyFrom(firstArg)) - .addArgs(ByteString.copyFrom(secondArg)); + .setSerializeType(serialize) + .addArgTypes("com.google.protobuf.ByteString") + .addArgTypes("org.apache.dubbo.common.URL") + .addArgs(ByteString.copyFrom(firstArg)) + .addArgs(ByteString.copyFrom(secondArg)); - TripleCustomerProtocolWapper.TripleRequestWrapper parseFrom = TripleCustomerProtocolWapper.TripleRequestWrapper.parseFrom(pbbuilder.build().toByteArray()); + TripleCustomerProtocolWapper.TripleRequestWrapper parseFrom = + TripleCustomerProtocolWapper.TripleRequestWrapper.parseFrom( + pbbuilder.build().toByteArray()); Assertions.assertEquals(parseFrom.getSerializeType(), tripleRequestWrapper.getSerializeType()); - Assertions.assertArrayEquals(parseFrom.getArgs().toArray(), tripleRequestWrapper.getArgs().toArray()); - Assertions.assertArrayEquals(parseFrom.getArgTypes().toArray(), tripleRequestWrapper.getArgTypes().toArray()); + Assertions.assertArrayEquals( + parseFrom.getArgs().toArray(), tripleRequestWrapper.getArgs().toArray()); + Assertions.assertArrayEquals( + parseFrom.getArgTypes().toArray(), + tripleRequestWrapper.getArgTypes().toArray()); } @Test void testTripleResponseWrapperWithNullData() { String serializeType = "hession4"; String type = "String"; - TripleCustomerProtocolWapper.TripleResponseWrapper.Builder builder = TripleCustomerProtocolWapper.TripleResponseWrapper.Builder.newBuilder(); - TripleCustomerProtocolWapper.TripleResponseWrapper tripleResponseWrapper = builder - .setSerializeType(serializeType) - .setType(type) - .build(); - TripleWrapper.TripleResponseWrapper.Builder pbBuilder = TripleWrapper.TripleResponseWrapper.newBuilder() - .setType(type) - .setSerializeType(serializeType); + TripleCustomerProtocolWapper.TripleResponseWrapper.Builder builder = + TripleCustomerProtocolWapper.TripleResponseWrapper.Builder.newBuilder(); + TripleCustomerProtocolWapper.TripleResponseWrapper tripleResponseWrapper = + builder.setSerializeType(serializeType).setType(type).build(); + TripleWrapper.TripleResponseWrapper.Builder pbBuilder = + TripleWrapper.TripleResponseWrapper.newBuilder().setType(type).setSerializeType(serializeType); Assertions.assertArrayEquals(pbBuilder.build().toByteArray(), tripleResponseWrapper.toByteArray()); } @@ -130,34 +138,34 @@ public class TripleCustomerProtocolWapperTest { void testTripleResponseWrapper() { String serializeType = "hession4"; String type = "String"; - String data = "/*\n" + - " * Licensed to the Apache Software Foundation (ASF) under one or more\n" + - " * contributor license agreements. See the NOTICE file distributed with\n" + - " * this work for additional information regarding copyright ownership.\n" + - " * The ASF licenses this file to You under the Apache License, Version 2.0\n" + - " * (the \"License\"); you may not use this file except in compliance with\n" + - " * the License. You may obtain a copy of the License at\n" + - " *\n" + - " * http://www.apache.org/licenses/LICENSE-2.0\n" + - " *\n" + - " * Unless required by applicable law or agreed to in writing, software\n" + - " * distributed under the License is distributed on an \"AS IS\" BASIS,\n" + - " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + - " * See the License for the specific language governing permissions and\n" + - " * limitations under the License.\n" + - " */"; + String data = "/*\n" + " * Licensed to the Apache Software Foundation (ASF) under one or more\n" + + " * contributor license agreements. See the NOTICE file distributed with\n" + + " * this work for additional information regarding copyright ownership.\n" + + " * The ASF licenses this file to You under the Apache License, Version 2.0\n" + + " * (the \"License\"); you may not use this file except in compliance with\n" + + " * the License. You may obtain a copy of the License at\n" + + " *\n" + + " * http://www.apache.org/licenses/LICENSE-2.0\n" + + " *\n" + + " * Unless required by applicable law or agreed to in writing, software\n" + + " * distributed under the License is distributed on an \"AS IS\" BASIS,\n" + + " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + + " * See the License for the specific language governing permissions and\n" + + " * limitations under the License.\n" + + " */"; byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8); - TripleCustomerProtocolWapper.TripleResponseWrapper.Builder builder = TripleCustomerProtocolWapper.TripleResponseWrapper.Builder.newBuilder(); - TripleCustomerProtocolWapper.TripleResponseWrapper tripleResponseWrapper = builder - .setSerializeType(serializeType) - .setType(type) - .setData(dataBytes) - .build(); + TripleCustomerProtocolWapper.TripleResponseWrapper.Builder builder = + TripleCustomerProtocolWapper.TripleResponseWrapper.Builder.newBuilder(); + TripleCustomerProtocolWapper.TripleResponseWrapper tripleResponseWrapper = builder.setSerializeType( + serializeType) + .setType(type) + .setData(dataBytes) + .build(); TripleWrapper.TripleResponseWrapper.Builder pbBuilder = TripleWrapper.TripleResponseWrapper.newBuilder() - .setType(type) - .setData(ByteString.copyFrom(dataBytes)) - .setSerializeType(serializeType); + .setType(type) + .setData(ByteString.copyFrom(dataBytes)) + .setSerializeType(serializeType); Assertions.assertArrayEquals(pbBuilder.build().toByteArray(), tripleResponseWrapper.toByteArray()); } @@ -165,33 +173,32 @@ public class TripleCustomerProtocolWapperTest { void testTripleResponseParseFrom() { String serializeType = "hession4"; String type = "String"; - String data = "/*\n" + - " * Licensed to the Apache Software Foundation (ASF) under one or more\n" + - " * contributor license agreements. See the NOTICE file distributed with\n" + - " * this work for additional information regarding copyright ownership.\n" + - " * The ASF licenses this file to You under the Apache License, Version 2.0\n" + - " * (the \"License\"); you may not use this file except in compliance with\n" + - " * the License. You may obtain a copy of the License at\n" + - " *\n" + - " * http://www.apache.org/licenses/LICENSE-2.0\n" + - " *\n" + - " * Unless required by applicable law or agreed to in writing, software\n" + - " * distributed under the License is distributed on an \"AS IS\" BASIS,\n" + - " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + - " * See the License for the specific language governing permissions and\n" + - " * limitations under the License.\n" + - " */"; + String data = "/*\n" + " * Licensed to the Apache Software Foundation (ASF) under one or more\n" + + " * contributor license agreements. See the NOTICE file distributed with\n" + + " * this work for additional information regarding copyright ownership.\n" + + " * The ASF licenses this file to You under the Apache License, Version 2.0\n" + + " * (the \"License\"); you may not use this file except in compliance with\n" + + " * the License. You may obtain a copy of the License at\n" + + " *\n" + + " * http://www.apache.org/licenses/LICENSE-2.0\n" + + " *\n" + + " * Unless required by applicable law or agreed to in writing, software\n" + + " * distributed under the License is distributed on an \"AS IS\" BASIS,\n" + + " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + + " * See the License for the specific language governing permissions and\n" + + " * limitations under the License.\n" + + " */"; byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8); TripleWrapper.TripleResponseWrapper.Builder pbBuilder = TripleWrapper.TripleResponseWrapper.newBuilder() - .setType(type) - .setData(ByteString.copyFrom(dataBytes)) - .setSerializeType(serializeType); + .setType(type) + .setData(ByteString.copyFrom(dataBytes)) + .setSerializeType(serializeType); byte[] pbRawBytes = pbBuilder.build().toByteArray(); - TripleCustomerProtocolWapper.TripleResponseWrapper tripleResponseWrapper = TripleCustomerProtocolWapper.TripleResponseWrapper.parseFrom(pbRawBytes); + TripleCustomerProtocolWapper.TripleResponseWrapper tripleResponseWrapper = + TripleCustomerProtocolWapper.TripleResponseWrapper.parseFrom(pbRawBytes); Assertions.assertArrayEquals(pbRawBytes, tripleResponseWrapper.toByteArray()); Assertions.assertArrayEquals(dataBytes, tripleResponseWrapper.getData()); Assertions.assertEquals(serializeType, tripleResponseWrapper.getSerializeType()); Assertions.assertEquals(type, tripleResponseWrapper.getType()); } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TripleInvokerTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TripleInvokerTest.java index 101941423a..a468d9d815 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TripleInvokerTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TripleInvokerTest.java @@ -31,14 +31,14 @@ import org.apache.dubbo.rpc.protocol.tri.call.TripleClientCall; import org.apache.dubbo.rpc.protocol.tri.compressor.Identity; import org.apache.dubbo.rpc.protocol.tri.support.IGreeter; +import java.util.HashSet; +import java.util.concurrent.ExecutorService; + import io.netty.channel.Channel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.HashSet; -import java.util.concurrent.ExecutorService; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @@ -52,8 +52,7 @@ class TripleInvokerTest { ConnectionManager connectionManager = Mockito.mock(ConnectionManager.class); when(connectionManager.connect(any(URL.class), any(ChannelHandler.class))) .thenReturn(connectionClient); - when(connectionClient.getChannel(true)) - .thenReturn(channel); + when(connectionClient.getChannel(true)).thenReturn(channel); when(connectionClient.isConnected()).thenReturn(true); ExecutorService executorService = ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()) @@ -64,15 +63,14 @@ class TripleInvokerTest { .thenReturn(streamObserver); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("test"); - invocation.setArguments(new Object[]{streamObserver, streamObserver}); - TripleInvoker invoker = new TripleInvoker<>(IGreeter.class, url, - Identity.MESSAGE_ENCODING, connectionClient, new HashSet<>(), executorService); - MethodDescriptor echoMethod = new ReflectionMethodDescriptor( - IGreeter.class.getDeclaredMethod("echo", String.class)); + invocation.setArguments(new Object[] {streamObserver, streamObserver}); + TripleInvoker invoker = new TripleInvoker<>( + IGreeter.class, url, Identity.MESSAGE_ENCODING, connectionClient, new HashSet<>(), executorService); + MethodDescriptor echoMethod = + new ReflectionMethodDescriptor(IGreeter.class.getDeclaredMethod("echo", String.class)); Assertions.assertTrue(invoker.isAvailable()); invoker.invokeUnary(echoMethod, invocation, call, new ThreadlessExecutor()); invoker.destroy(); Assertions.assertFalse(invoker.isAvailable()); } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TriplePathResolverTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TriplePathResolverTest.java index fc223b1165..5e9d212bf0 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TriplePathResolverTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TriplePathResolverTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.common.URL; @@ -32,9 +31,8 @@ import org.junit.jupiter.api.Test; class TriplePathResolverTest { - private static final PathResolver PATH_RESOLVER = ExtensionLoader.getExtensionLoader( - PathResolver.class) - .getDefaultExtension(); + private static final PathResolver PATH_RESOLVER = + ExtensionLoader.getExtensionLoader(PathResolver.class).getDefaultExtension(); private static final Invoker INVOKER = new Invoker() { @Override @@ -48,9 +46,7 @@ class TriplePathResolverTest { } @Override - public void destroy() { - - } + public void destroy() {} @Override public Class getInterface() { diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TripleProtocolTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TripleProtocolTest.java index 483897d971..0887afce9d 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TripleProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TripleProtocolTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri; import org.apache.dubbo.common.URL; @@ -35,14 +34,13 @@ import org.apache.dubbo.rpc.protocol.tri.support.IGreeter; import org.apache.dubbo.rpc.protocol.tri.support.IGreeterImpl; import org.apache.dubbo.rpc.protocol.tri.support.MockStreamObserver; +import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.concurrent.TimeUnit; - import static org.apache.dubbo.rpc.protocol.tri.support.IGreeter.SERVER_MSG; - class TripleProtocolTest { @Test @@ -52,33 +50,31 @@ class TripleProtocolTest { int availablePort = NetUtils.getAvailablePort(); ApplicationModel applicationModel = ApplicationModel.defaultModel(); - URL providerUrl = URL.valueOf( - "tri://127.0.0.1:" + availablePort + "/" + IGreeter.class.getName()); + URL providerUrl = URL.valueOf("tri://127.0.0.1:" + availablePort + "/" + IGreeter.class.getName()); - ModuleServiceRepository serviceRepository = applicationModel.getDefaultModule() - .getServiceRepository(); + ModuleServiceRepository serviceRepository = + applicationModel.getDefaultModule().getServiceRepository(); ServiceDescriptor serviceDescriptor = serviceRepository.registerService(IGreeter.class); ProviderModel providerModel = new ProviderModel( - providerUrl.getServiceKey(), - serviceImpl, - serviceDescriptor, - new ServiceMetadata(), ClassUtils.getClassLoader(IGreeter.class)); + providerUrl.getServiceKey(), + serviceImpl, + serviceDescriptor, + new ServiceMetadata(), + ClassUtils.getClassLoader(IGreeter.class)); serviceRepository.registerProvider(providerModel); providerUrl = providerUrl.setServiceModel(providerModel); Protocol protocol = new TripleProtocol(providerUrl.getOrDefaultFrameworkModel()); - ProxyFactory proxy = applicationModel.getExtensionLoader(ProxyFactory.class) - .getAdaptiveExtension(); + ProxyFactory proxy = + applicationModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Invoker invoker = proxy.getInvoker(serviceImpl, IGreeter.class, providerUrl); Exporter export = protocol.export(invoker); - URL consumerUrl = URL.valueOf( - "tri://127.0.0.1:" + availablePort + "/" + IGreeter.class.getName()); + URL consumerUrl = URL.valueOf("tri://127.0.0.1:" + availablePort + "/" + IGreeter.class.getName()); - ConsumerModel consumerModel = new ConsumerModel(consumerUrl.getServiceKey(), null, - serviceDescriptor, null, - null, null); + ConsumerModel consumerModel = + new ConsumerModel(consumerUrl.getServiceKey(), null, serviceDescriptor, null, null, null); consumerUrl = consumerUrl.setServiceModel(consumerModel); IGreeter greeterProxy = proxy.getProxy(protocol.refer(IGreeter.class, consumerUrl)); Thread.sleep(1000); @@ -97,8 +93,7 @@ class TripleProtocolTest { // 3. test bidirectionalStream MockStreamObserver outboundMessageSubscriber2 = new MockStreamObserver(); - StreamObserver inboundMessageObserver = greeterProxy.bidirectionalStream( - outboundMessageSubscriber2); + StreamObserver inboundMessageObserver = greeterProxy.bidirectionalStream(outboundMessageSubscriber2); inboundMessageObserver.onNext(REQUEST_MSG); inboundMessageObserver.onCompleted(); outboundMessageSubscriber2.getLatch().await(3000, TimeUnit.MILLISECONDS); @@ -106,7 +101,8 @@ class TripleProtocolTest { Assertions.assertEquals(outboundMessageSubscriber2.getOnNextData(), SERVER_MSG); Assertions.assertTrue(outboundMessageSubscriber2.isOnCompleted()); // verify server - MockStreamObserver serverOutboundMessageSubscriber = (MockStreamObserver) ((IGreeterImpl) serviceImpl).getMockStreamObserver(); + MockStreamObserver serverOutboundMessageSubscriber = + (MockStreamObserver) ((IGreeterImpl) serviceImpl).getMockStreamObserver(); serverOutboundMessageSubscriber.getLatch().await(1000, TimeUnit.MILLISECONDS); Assertions.assertEquals(REQUEST_MSG, serverOutboundMessageSubscriber.getOnNextData()); Assertions.assertTrue(serverOutboundMessageSubscriber.isOnCompleted()); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCallTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCallTest.java index 501b55f398..9a5f9b48d5 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCallTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCallTest.java @@ -14,10 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.call; -class ClientCallTest { - - -} +class ClientCallTest {} diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/call/ReflectionServerCallTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/call/ReflectionServerCallTest.java index 7b379dbcdd..c598305ce6 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/call/ReflectionServerCallTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/call/ReflectionServerCallTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.call; import org.apache.dubbo.common.URL; @@ -29,13 +28,13 @@ import org.apache.dubbo.rpc.protocol.tri.DescriptorService; import org.apache.dubbo.rpc.protocol.tri.HelloReply; import org.apache.dubbo.rpc.protocol.tri.stream.TripleServerStream; +import java.lang.reflect.Method; +import java.util.Collections; + import io.netty.util.concurrent.ImmediateEventExecutor; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.lang.reflect.Method; -import java.util.Collections; - import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; @@ -51,38 +50,41 @@ class ReflectionServerCallTest { Method method = DescriptorService.class.getMethod("sayHello", HelloReply.class); MethodDescriptor methodDescriptor = new ReflectionMethodDescriptor(method); URL url = Mockito.mock(URL.class); - when(invoker.getUrl()) - .thenReturn(url); - when(url.getServiceModel()) - .thenReturn(providerModel); - when(providerModel.getServiceMetadata()) - .thenReturn(serviceMetadata); + when(invoker.getUrl()).thenReturn(url); + when(url.getServiceModel()).thenReturn(providerModel); + when(providerModel.getServiceMetadata()).thenReturn(serviceMetadata); String service = "testService"; String methodName = "method"; try { - ReflectionAbstractServerCall call = new ReflectionAbstractServerCall(invoker, serverStream, - new FrameworkModel(), "", - service, methodName, - Collections.emptyList(), - ImmediateEventExecutor.INSTANCE); + ReflectionAbstractServerCall call = new ReflectionAbstractServerCall( + invoker, + serverStream, + new FrameworkModel(), + "", + service, + methodName, + Collections.emptyList(), + ImmediateEventExecutor.INSTANCE); fail(); } catch (Exception e) { // pass } ServiceDescriptor serviceDescriptor = Mockito.mock(ServiceDescriptor.class); - when(serviceDescriptor.getMethods(anyString())) - .thenReturn(Collections.singletonList(methodDescriptor)); + when(serviceDescriptor.getMethods(anyString())).thenReturn(Collections.singletonList(methodDescriptor)); - when(providerModel.getServiceModel()) - .thenReturn(serviceDescriptor); + when(providerModel.getServiceModel()).thenReturn(serviceDescriptor); - ReflectionAbstractServerCall call2 = new ReflectionAbstractServerCall(invoker, serverStream, - new FrameworkModel(), "", - service, methodName, - Collections.emptyList(), - ImmediateEventExecutor.INSTANCE); + ReflectionAbstractServerCall call2 = new ReflectionAbstractServerCall( + invoker, + serverStream, + new FrameworkModel(), + "", + service, + methodName, + Collections.emptyList(), + ImmediateEventExecutor.INSTANCE); call2.onHeader(Collections.emptyMap()); call2.onMessage(new byte[0], false); call2.onComplete(); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/call/StubServerCallTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/call/StubServerCallTest.java index e957092140..b500e91bbc 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/call/StubServerCallTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/call/StubServerCallTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.call; import org.apache.dubbo.common.URL; @@ -26,12 +25,12 @@ import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.model.StubMethodDescriptor; import org.apache.dubbo.rpc.protocol.tri.stream.TripleServerStream; +import java.util.Collections; + import io.netty.util.concurrent.ImmediateEventExecutor; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.Collections; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; @@ -46,24 +45,22 @@ class StubServerCallTest { ServiceDescriptor serviceDescriptor = Mockito.mock(ServiceDescriptor.class); StubMethodDescriptor methodDescriptor = Mockito.mock(StubMethodDescriptor.class); URL url = Mockito.mock(URL.class); - when(invoker.getUrl()) - .thenReturn(url); - when(url.getServiceModel()) - .thenReturn(providerModel); - when(providerModel.getServiceModel()) - .thenReturn(serviceDescriptor); - when(serviceDescriptor.getMethods(anyString())) - .thenReturn(Collections.singletonList(methodDescriptor)); - when(methodDescriptor.getRpcType()) - .thenReturn(RpcType.UNARY); - when(methodDescriptor.parseRequest(any(byte[].class))) - .thenReturn("test"); + when(invoker.getUrl()).thenReturn(url); + when(url.getServiceModel()).thenReturn(providerModel); + when(providerModel.getServiceModel()).thenReturn(serviceDescriptor); + when(serviceDescriptor.getMethods(anyString())).thenReturn(Collections.singletonList(methodDescriptor)); + when(methodDescriptor.getRpcType()).thenReturn(RpcType.UNARY); + when(methodDescriptor.parseRequest(any(byte[].class))).thenReturn("test"); String service = "testService"; String method = "method"; - StubAbstractServerCall call = new StubAbstractServerCall(invoker, tripleServerStream, - new FrameworkModel(), "", - service, method, - ImmediateEventExecutor.INSTANCE); + StubAbstractServerCall call = new StubAbstractServerCall( + invoker, + tripleServerStream, + new FrameworkModel(), + "", + service, + method, + ImmediateEventExecutor.INSTANCE); call.onHeader(Collections.emptyMap()); call.onMessage(new byte[0], false); call.onComplete(); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/Bzip2Test.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/Bzip2Test.java index 723c4b123c..99490cae73 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/Bzip2Test.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/Bzip2Test.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.compressor; import org.apache.dubbo.rpc.model.ApplicationModel; @@ -44,18 +43,20 @@ class Bzip2Test { @ValueSource(strings = {"bzip2"}) @ParameterizedTest void compression(String compressorName) { - Compressor compressor = ApplicationModel.defaultModel().getDefaultModule() - .getExtensionLoader(Compressor.class) - .getExtension(compressorName); - String loadByStatic = Compressor.getCompressor(new FrameworkModel(), compressorName) - .getMessageEncoding(); + Compressor compressor = ApplicationModel.defaultModel() + .getDefaultModule() + .getExtensionLoader(Compressor.class) + .getExtension(compressorName); + String loadByStatic = + Compressor.getCompressor(new FrameworkModel(), compressorName).getMessageEncoding(); Assertions.assertEquals(loadByStatic, compressor.getMessageEncoding()); byte[] compressedByteArr = compressor.compress(TEST_STR.getBytes()); - DeCompressor deCompressor = ApplicationModel.defaultModel().getDefaultModule() - .getExtensionLoader(DeCompressor.class) - .getExtension(compressorName); + DeCompressor deCompressor = ApplicationModel.defaultModel() + .getDefaultModule() + .getExtensionLoader(DeCompressor.class) + .getExtension(compressorName); byte[] decompressedByteArr = deCompressor.decompress(compressedByteArr); Assertions.assertEquals(new String(decompressedByteArr), TEST_STR); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/GzipTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/GzipTest.java index 43bb0c701b..9c10938a5e 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/GzipTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/GzipTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.compressor; import org.apache.dubbo.rpc.model.ApplicationModel; @@ -41,18 +40,20 @@ class GzipTest { @ValueSource(strings = {"gzip"}) @ParameterizedTest void compression(String compressorName) { - Compressor compressor = ApplicationModel.defaultModel().getDefaultModule() - .getExtensionLoader(Compressor.class) - .getExtension(compressorName); - String loadByStatic = Compressor.getCompressor(new FrameworkModel(), compressorName) - .getMessageEncoding(); + Compressor compressor = ApplicationModel.defaultModel() + .getDefaultModule() + .getExtensionLoader(Compressor.class) + .getExtension(compressorName); + String loadByStatic = + Compressor.getCompressor(new FrameworkModel(), compressorName).getMessageEncoding(); Assertions.assertEquals(loadByStatic, compressor.getMessageEncoding()); byte[] compressedByteArr = compressor.compress(TEST_STR.getBytes()); - DeCompressor deCompressor = ApplicationModel.defaultModel().getDefaultModule() - .getExtensionLoader(DeCompressor.class) - .getExtension(compressorName); + DeCompressor deCompressor = ApplicationModel.defaultModel() + .getDefaultModule() + .getExtensionLoader(DeCompressor.class) + .getExtension(compressorName); byte[] decompressedByteArr = deCompressor.decompress(compressedByteArr); Assertions.assertEquals(new String(decompressedByteArr), TEST_STR); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/IdentityTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/IdentityTest.java index dc77255a0d..9c996f3a7e 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/IdentityTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/IdentityTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.compressor; import org.junit.jupiter.api.Assertions; @@ -29,14 +28,14 @@ class IdentityTest { @Test void compress() { - byte[] input = new byte[]{1, 2, 3, 4, 5}; + byte[] input = new byte[] {1, 2, 3, 4, 5}; final byte[] compressed = Identity.IDENTITY.compress(input); Assertions.assertEquals(input, compressed); } @Test void decompress() { - byte[] input = new byte[]{1, 2, 3, 4, 5}; + byte[] input = new byte[] {1, 2, 3, 4, 5}; final byte[] decompressed = Identity.IDENTITY.decompress(input); Assertions.assertEquals(input, decompressed); } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/SnappyTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/SnappyTest.java index 7371f06c62..b611b12664 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/SnappyTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/SnappyTest.java @@ -43,18 +43,20 @@ class SnappyTest { @ValueSource(strings = {"snappy"}) @ParameterizedTest void compression(String compressorName) { - Compressor compressor = ApplicationModel.defaultModel().getDefaultModule() - .getExtensionLoader(Compressor.class) - .getExtension(compressorName); - String loadByStatic = Compressor.getCompressor(new FrameworkModel(), compressorName) - .getMessageEncoding(); + Compressor compressor = ApplicationModel.defaultModel() + .getDefaultModule() + .getExtensionLoader(Compressor.class) + .getExtension(compressorName); + String loadByStatic = + Compressor.getCompressor(new FrameworkModel(), compressorName).getMessageEncoding(); Assertions.assertEquals(loadByStatic, compressor.getMessageEncoding()); byte[] compressedByteArr = compressor.compress(TEST_STR.getBytes()); - DeCompressor deCompressor = ApplicationModel.defaultModel().getDefaultModule() - .getExtensionLoader(DeCompressor.class) - .getExtension(compressorName); + DeCompressor deCompressor = ApplicationModel.defaultModel() + .getDefaultModule() + .getExtensionLoader(DeCompressor.class) + .getExtension(compressorName); byte[] decompressedByteArr = deCompressor.decompress(compressedByteArr); Assertions.assertEquals(new String(decompressedByteArr), TEST_STR); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/frame/RecordListener.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/frame/RecordListener.java index 355d407861..c9ec2776d2 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/frame/RecordListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/frame/RecordListener.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.frame; public class RecordListener implements TriDecoder.Listener { diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/frame/TriDecoderTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/frame/TriDecoderTest.java index f0f2564b7b..40e793fcb3 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/frame/TriDecoderTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/frame/TriDecoderTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.frame; import org.apache.dubbo.rpc.protocol.tri.compressor.DeCompressor; @@ -50,5 +49,4 @@ class TriDecoderTest { Assertions.assertEquals(2, listener.lastData.length); decoder.close(); } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/service/HealthStatusManagerTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/service/HealthStatusManagerTest.java index 0665881ba1..4dfdc3e45b 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/service/HealthStatusManagerTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/service/HealthStatusManagerTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.service; import org.apache.dubbo.rpc.StatusRpcException; @@ -41,9 +40,9 @@ class HealthStatusManagerTest { void setStatus() { String service = "serv0"; manager.setStatus(service, ServingStatus.SERVING); - ServingStatus stored = manager.getHealthService().check(HealthCheckRequest.newBuilder() - .setService(service) - .build()).getStatus(); + ServingStatus stored = manager.getHealthService() + .check(HealthCheckRequest.newBuilder().setService(service).build()) + .getStatus(); Assertions.assertEquals(ServingStatus.SERVING, stored); } @@ -51,15 +50,14 @@ class HealthStatusManagerTest { void clearStatus() { String service = "serv1"; manager.setStatus(service, ServingStatus.SERVING); - ServingStatus stored = manager.getHealthService().check(HealthCheckRequest.newBuilder() - .setService(service) - .build()).getStatus(); + ServingStatus stored = manager.getHealthService() + .check(HealthCheckRequest.newBuilder().setService(service).build()) + .getStatus(); Assertions.assertEquals(ServingStatus.SERVING, stored); manager.clearStatus(service); try { - manager.getHealthService().check(HealthCheckRequest.newBuilder() - .setService(service) - .build()); + manager.getHealthService() + .check(HealthCheckRequest.newBuilder().setService(service).build()); fail(); } catch (StatusRpcException e) { Assertions.assertEquals(Code.NOT_FOUND, e.getStatus().code); @@ -70,14 +68,14 @@ class HealthStatusManagerTest { void enterTerminalState() { String service = "serv2"; manager.setStatus(service, ServingStatus.SERVING); - ServingStatus stored = manager.getHealthService().check(HealthCheckRequest.newBuilder() - .setService(service) - .build()).getStatus(); + ServingStatus stored = manager.getHealthService() + .check(HealthCheckRequest.newBuilder().setService(service).build()) + .getStatus(); Assertions.assertEquals(ServingStatus.SERVING, stored); manager.enterTerminalState(); - ServingStatus stored2 = manager.getHealthService().check(HealthCheckRequest.newBuilder() - .setService(service) - .build()).getStatus(); + ServingStatus stored2 = manager.getHealthService() + .check(HealthCheckRequest.newBuilder().setService(service).build()) + .getStatus(); Assertions.assertEquals(ServingStatus.NOT_SERVING, stored2); } } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/service/TriBuiltinServiceTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/service/TriBuiltinServiceTest.java index 6710fdc142..d4d45a8e4a 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/service/TriBuiltinServiceTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/service/TriBuiltinServiceTest.java @@ -39,17 +39,17 @@ class TriBuiltinServiceTest { } @Test - void testForceEnable(){ + void testForceEnable() { FrameworkModel frameworkModel = new FrameworkModel(); TriBuiltinService triBuiltinService = new TriBuiltinService(frameworkModel); triBuiltinService.init(); String serviceName = DubboHealthTriple.SERVICE_NAME; Assertions.assertNotNull(triBuiltinService.getHealthStatusManager()); - PathResolver pathResolver = frameworkModel.getExtensionLoader(PathResolver.class) - .getDefaultExtension(); + PathResolver pathResolver = + frameworkModel.getExtensionLoader(PathResolver.class).getDefaultExtension(); Assertions.assertNotNull(pathResolver.resolve(serviceName)); - ModuleServiceRepository repository = frameworkModel.getInternalApplicationModel() - .getInternalModule().getServiceRepository(); + ModuleServiceRepository repository = + frameworkModel.getInternalApplicationModel().getInternalModule().getServiceRepository(); Assertions.assertFalse(repository.getAllServices().isEmpty()); Assertions.assertNotNull(StubSuppliers.getServiceDescriptor(serviceName)); } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/service/TriHealthImplTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/service/TriHealthImplTest.java index faa4b0ace3..11101168e9 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/service/TriHealthImplTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/service/TriHealthImplTest.java @@ -20,16 +20,16 @@ import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.IdentityHashMap; + import io.grpc.health.v1.HealthCheckRequest; import io.grpc.health.v1.HealthCheckResponse; import io.grpc.health.v1.HealthCheckResponse.ServingStatus; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.lang.reflect.Field; -import java.util.HashMap; -import java.util.IdentityHashMap; - /** * {@link TriHealthImpl} */ @@ -43,7 +43,8 @@ class TriHealthImplTest { HealthCheckResponse response = triHealth.check(request); Assertions.assertEquals(response.getStatus(), HealthCheckResponse.ServingStatus.SERVING); - HealthCheckRequest badRequest = HealthCheckRequest.newBuilder().setService("test").build(); + HealthCheckRequest badRequest = + HealthCheckRequest.newBuilder().setService("test").build(); Assertions.assertThrows(RpcException.class, () -> triHealth.check(badRequest)); } @@ -51,9 +52,8 @@ class TriHealthImplTest { void testWatch() throws Exception { TriHealthImpl triHealth = new TriHealthImpl(); - HealthCheckRequest request = HealthCheckRequest.newBuilder() - .setService("testWatch") - .build(); + HealthCheckRequest request = + HealthCheckRequest.newBuilder().setService("testWatch").build(); triHealth.setStatus(request.getService(), ServingStatus.SERVING); StreamObserver streamObserver = new MockStreamObserver(); @@ -61,54 +61,51 @@ class TriHealthImplTest { // test watch triHealth.watch(request, streamObserver); Assertions.assertNotNull(RpcContext.getCancellationContext().getListeners()); - HashMap, Boolean>> watches = getWatches( - triHealth); + HashMap, Boolean>> watches = getWatches(triHealth); Assertions.assertTrue(watches.containsKey(request.getService())); Assertions.assertTrue(watches.get(request.getService()).containsKey(streamObserver)); Assertions.assertTrue(watches.get(request.getService()).get(streamObserver)); MockStreamObserver mockStreamObserver = (MockStreamObserver) streamObserver; Assertions.assertEquals(mockStreamObserver.getCount(), 1); - Assertions.assertEquals(mockStreamObserver.getResponse().getStatus(), - HealthCheckResponse.ServingStatus.SERVING); + Assertions.assertEquals( + mockStreamObserver.getResponse().getStatus(), HealthCheckResponse.ServingStatus.SERVING); // test setStatus - triHealth.setStatus(request.getService(), - HealthCheckResponse.ServingStatus.SERVICE_UNKNOWN); + triHealth.setStatus(request.getService(), HealthCheckResponse.ServingStatus.SERVICE_UNKNOWN); Assertions.assertEquals(mockStreamObserver.getCount(), 2); - Assertions.assertEquals(mockStreamObserver.getResponse().getStatus(), - HealthCheckResponse.ServingStatus.SERVICE_UNKNOWN); + Assertions.assertEquals( + mockStreamObserver.getResponse().getStatus(), HealthCheckResponse.ServingStatus.SERVICE_UNKNOWN); triHealth.enterTerminalState(); Assertions.assertEquals(mockStreamObserver.getCount(), 3); - Assertions.assertEquals(mockStreamObserver.getResponse().getStatus(), - HealthCheckResponse.ServingStatus.NOT_SERVING); + Assertions.assertEquals( + mockStreamObserver.getResponse().getStatus(), HealthCheckResponse.ServingStatus.NOT_SERVING); // test clearStatus turnOffTerminal(triHealth); triHealth.clearStatus(request.getService()); Assertions.assertEquals(mockStreamObserver.getCount(), 4); - Assertions.assertEquals(mockStreamObserver.getResponse().getStatus(), - HealthCheckResponse.ServingStatus.SERVICE_UNKNOWN); + Assertions.assertEquals( + mockStreamObserver.getResponse().getStatus(), HealthCheckResponse.ServingStatus.SERVICE_UNKNOWN); // test listener RpcContext.getCancellationContext().close(); Assertions.assertTrue(watches.isEmpty()); } - private void turnOffTerminal(TriHealthImpl triHealth) - throws NoSuchFieldException, IllegalAccessException { + private void turnOffTerminal(TriHealthImpl triHealth) throws NoSuchFieldException, IllegalAccessException { Field terminalField = triHealth.getClass().getDeclaredField("terminal"); terminalField.setAccessible(true); terminalField.set(triHealth, false); } private HashMap, Boolean>> getWatches( - TriHealthImpl triHealth) throws Exception { + TriHealthImpl triHealth) throws Exception { Field watchersField = triHealth.getClass().getDeclaredField("watchers"); watchersField.setAccessible(true); HashMap, Boolean>> watches = - (HashMap, Boolean>>) watchersField.get( - triHealth); + (HashMap, Boolean>>) + watchersField.get(triHealth); return watches; } @@ -124,14 +121,10 @@ class TriHealthImplTest { } @Override - public void onError(Throwable throwable) { - - } + public void onError(Throwable throwable) {} @Override - public void onCompleted() { - - } + public void onCompleted() {} public int getCount() { return count; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/stream/MockClientStreamListener.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/stream/MockClientStreamListener.java index ac135cf0cd..4daeea8137 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/stream/MockClientStreamListener.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/stream/MockClientStreamListener.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.stream; import org.apache.dubbo.rpc.TriRpcStatus; @@ -33,8 +32,7 @@ public class MockClientStreamListener implements ClientStream.Listener { } @Override - public void onComplete(TriRpcStatus status, - Map attachments) { + public void onComplete(TriRpcStatus status, Map attachments) { this.status = status; } @@ -44,7 +42,5 @@ public class MockClientStreamListener implements ClientStream.Listener { } @Override - public void onCancelByRemote(TriRpcStatus status) { - - } + public void onCancelByRemote(TriRpcStatus status) {} } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/stream/StreamUtilsTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/stream/StreamUtilsTest.java index 544332b22d..07d08513e0 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/stream/StreamUtilsTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/stream/StreamUtilsTest.java @@ -14,17 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.stream; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.rpc.TriRpcStatus; import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum; -import io.netty.handler.codec.http2.DefaultHttp2Headers; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; @@ -33,15 +28,18 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -class StreamUtilsTest { +import io.netty.handler.codec.http2.DefaultHttp2Headers; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +class StreamUtilsTest { @Test void encodeBase64ASCII() { String content = "😯"; - Assertions.assertArrayEquals(content.getBytes(StandardCharsets.UTF_8), - StreamUtils.decodeASCIIByte(StreamUtils.encodeBase64ASCII(content.getBytes( - StandardCharsets.UTF_8)))); + Assertions.assertArrayEquals( + content.getBytes(StandardCharsets.UTF_8), + StreamUtils.decodeASCIIByte(StreamUtils.encodeBase64ASCII(content.getBytes(StandardCharsets.UTF_8)))); } @Test @@ -69,11 +67,13 @@ class StreamUtilsTest { Assertions.assertNull(headers.get(TripleHeaderEnum.PATH_KEY.getHeader())); Assertions.assertNull(headers.get("Upper")); Assertions.assertNull(headers.get("obj")); - String jsonRaw = headers.get(TripleHeaderEnum.TRI_HEADER_CONVERT.getHeader()).toString(); + String jsonRaw = + headers.get(TripleHeaderEnum.TRI_HEADER_CONVERT.getHeader()).toString(); String json = TriRpcStatus.decodeMessage(jsonRaw); System.out.println(jsonRaw + "---" + json); Map upperMap = JsonUtils.toJavaObject(json, Map.class); - Assertions.assertArrayEquals("Upper".getBytes(StandardCharsets.UTF_8), upperMap.get("upper").getBytes(StandardCharsets.UTF_8)); + Assertions.assertArrayEquals( + "Upper".getBytes(StandardCharsets.UTF_8), upperMap.get("upper").getBytes(StandardCharsets.UTF_8)); int count = 10000; CountDownLatch latch = new CountDownLatch(count); @@ -110,6 +110,4 @@ class StreamUtilsTest { Assertions.assertEquals(0, latch.getCount()); executorService.shutdown(); } - - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleClientStreamTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleClientStreamTest.java index 0ab866e6cc..4e6b6f25c9 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleClientStreamTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleClientStreamTest.java @@ -14,18 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.stream; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; -import io.netty.channel.embedded.EmbeddedChannel; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.handler.codec.http.HttpResponseStatus; -import io.netty.handler.codec.http.HttpScheme; -import io.netty.handler.codec.http2.DefaultHttp2Headers; -import io.netty.handler.codec.http2.Http2StreamChannel; -import io.netty.util.concurrent.ImmediateEventExecutor; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.TriRpcStatus; import org.apache.dubbo.rpc.model.ApplicationModel; @@ -45,11 +35,21 @@ import org.apache.dubbo.rpc.protocol.tri.compressor.Compressor; import org.apache.dubbo.rpc.protocol.tri.support.IGreeter; import org.apache.dubbo.rpc.protocol.tri.transport.H2TransportListener; import org.apache.dubbo.rpc.protocol.tri.transport.TripleWriteQueue; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; import java.util.concurrent.Executor; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.embedded.EmbeddedChannel; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.handler.codec.http.HttpResponseStatus; +import io.netty.handler.codec.http.HttpScheme; +import io.netty.handler.codec.http2.DefaultHttp2Headers; +import io.netty.handler.codec.http2.Http2StreamChannel; +import io.netty.util.concurrent.ImmediateEventExecutor; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -61,25 +61,29 @@ class TripleClientStreamTest { @Test void progress() { final URL url = URL.valueOf("tri://127.0.0.1:8080/foo.bar.service"); - final ModuleServiceRepository repo = ApplicationModel.defaultModel().getDefaultModule() - .getServiceRepository(); + final ModuleServiceRepository repo = + ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); repo.registerService(IGreeter.class); final ServiceDescriptor serviceDescriptor = repo.getService(IGreeter.class.getName()); - final MethodDescriptor methodDescriptor = serviceDescriptor.getMethod("echo", - new Class[]{String.class}); + final MethodDescriptor methodDescriptor = serviceDescriptor.getMethod("echo", new Class[] {String.class}); MockClientStreamListener listener = new MockClientStreamListener(); TripleWriteQueue writeQueue = mock(TripleWriteQueue.class); final EmbeddedChannel channel = new EmbeddedChannel(); - when(writeQueue.enqueueFuture(any(QueuedCommand.class), any(Executor.class))).thenReturn(channel.newPromise()); + when(writeQueue.enqueueFuture(any(QueuedCommand.class), any(Executor.class))) + .thenReturn(channel.newPromise()); Http2StreamChannel http2StreamChannel = mock(Http2StreamChannel.class); when(http2StreamChannel.isActive()).thenReturn(true); when(http2StreamChannel.newSucceededFuture()).thenReturn(channel.newSucceededFuture()); when(http2StreamChannel.eventLoop()).thenReturn(new NioEventLoopGroup().next()); when(http2StreamChannel.newPromise()).thenReturn(channel.newPromise()); when(http2StreamChannel.parent()).thenReturn(channel); - TripleClientStream stream = new TripleClientStream(url.getOrDefaultFrameworkModel(), - ImmediateEventExecutor.INSTANCE, writeQueue, listener, http2StreamChannel); + TripleClientStream stream = new TripleClientStream( + url.getOrDefaultFrameworkModel(), + ImmediateEventExecutor.INSTANCE, + writeQueue, + listener, + http2StreamChannel); verify(writeQueue).enqueue(any(CreateStreamQueueCommand.class)); final RequestMetadata requestMetadata = new RequestMetadata(); @@ -108,15 +112,13 @@ class TripleClientStreamTest { H2TransportListener transportListener = stream.createTransportListener(); DefaultHttp2Headers headers = new DefaultHttp2Headers(); - headers.scheme(HttpScheme.HTTP.name()) - .status(HttpResponseStatus.OK.codeAsText()); + headers.scheme(HttpScheme.HTTP.name()).status(HttpResponseStatus.OK.codeAsText()); headers.set(TripleHeaderEnum.STATUS_KEY.getHeader(), TriRpcStatus.OK.code.code + ""); - headers.set(TripleHeaderEnum.CONTENT_TYPE_KEY.getHeader(), - TripleHeaderEnum.CONTENT_PROTO.getHeader()); + headers.set(TripleHeaderEnum.CONTENT_TYPE_KEY.getHeader(), TripleHeaderEnum.CONTENT_PROTO.getHeader()); transportListener.onHeader(headers, false); Assertions.assertTrue(listener.started); stream.request(2); - byte[] data = new byte[]{0, 0, 0, 0, 1, 1}; + byte[] data = new byte[] {0, 0, 0, 0, 1, 1}; final ByteBuf buf = Unpooled.wrappedBuffer(data); transportListener.onData(buf, false); Assertions.assertEquals(1, listener.message.length); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeter.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeter.java index 42a89af743..85b0865bdf 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeter.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeter.java @@ -1,20 +1,19 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * 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. + * 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 org.apache.dubbo.rpc.protocol.tri.support; import org.apache.dubbo.common.stream.StreamObserver; @@ -37,5 +36,4 @@ public interface IGreeter { void serverStream(String str, StreamObserver observer); StreamObserver bidirectionalStream(StreamObserver observer); - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeter2Impl.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeter2Impl.java index 10f35d27b1..d180a422bb 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeter2Impl.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeter2Impl.java @@ -16,9 +16,9 @@ */ package org.apache.dubbo.rpc.protocol.tri.support; -public class IGreeter2Impl implements IGreeter2{ +public class IGreeter2Impl implements IGreeter2 { @Override - public String echo(String request) throws IGreeterException { + public String echo(String request) throws IGreeterException { throw new IGreeterException("I am self define exception"); } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeterException.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeterException.java index a76748fb0a..3e781fe16b 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeterException.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeterException.java @@ -19,7 +19,7 @@ package org.apache.dubbo.rpc.protocol.tri.support; public class IGreeterException extends Exception { private String message; - public IGreeterException(String message){ + public IGreeterException(String message) { super(message); this.message = message; } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeterImpl.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeterImpl.java index f0b54fa1c6..ad844c329e 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeterImpl.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeterImpl.java @@ -1,20 +1,19 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * 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. + * 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 org.apache.dubbo.rpc.protocol.tri.support; import org.apache.dubbo.common.stream.StreamObserver; @@ -52,7 +51,7 @@ public class IGreeterImpl implements IGreeter { observer.onCompleted(); } }; - return mockStreamObserver;// This will serve as the server's outboundMessageSubscriber + return mockStreamObserver; // This will serve as the server's outboundMessageSubscriber } public StreamObserver getMockStreamObserver() { diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/MockStreamObserver.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/MockStreamObserver.java index f21686dbe0..64aeb265d4 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/MockStreamObserver.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/MockStreamObserver.java @@ -1,18 +1,18 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * 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. + * 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 org.apache.dubbo.rpc.protocol.tri.support; diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/transport/AbstractH2TransportListenerTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/transport/AbstractH2TransportListenerTest.java index ba936e6084..92d5b3c65c 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/transport/AbstractH2TransportListenerTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/transport/AbstractH2TransportListenerTest.java @@ -14,9 +14,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.protocol.tri.transport; +import java.util.Map; + import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http2.DefaultHttp2Headers; @@ -24,8 +25,6 @@ import io.netty.handler.codec.http2.Http2Headers; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.Map; - import static io.netty.handler.codec.http.HttpScheme.HTTPS; class AbstractH2TransportListenerTest { @@ -34,30 +33,21 @@ class AbstractH2TransportListenerTest { void headersToMap() { AbstractH2TransportListener listener = new AbstractH2TransportListener() { @Override - public void onHeader(Http2Headers headers, boolean endStream) { - - } + public void onHeader(Http2Headers headers, boolean endStream) {} @Override - public void onData(ByteBuf data, boolean endStream) { - - } + public void onData(ByteBuf data, boolean endStream) {} @Override - public void cancelByRemote(long errorCode) { - - } + public void cancelByRemote(long errorCode) {} }; DefaultHttp2Headers headers = new DefaultHttp2Headers(); - headers.scheme(HTTPS.name()) - .path("/foo.bar") - .method(HttpMethod.POST.asciiName()); + headers.scheme(HTTPS.name()).path("/foo.bar").method(HttpMethod.POST.asciiName()); headers.set("foo", "bar"); final Map map = listener.headersToMap(headers, () -> null); Assertions.assertEquals(4, map.size()); } @Test - void filterReservedHeaders() { - } + void filterReservedHeaders() {} } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2ClientResponseHandlerTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2ClientResponseHandlerTest.java index 466066383c..16f838466f 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2ClientResponseHandlerTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2ClientResponseHandlerTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.tri.transport; - import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.ByteBufUtil; import io.netty.channel.Channel; @@ -40,7 +39,6 @@ class TripleHttp2ClientResponseHandlerTest { private ChannelHandlerContext ctx; private AbstractH2TransportListener transportListener; - @BeforeEach public void init() { transportListener = Mockito.mock(AbstractH2TransportListener.class); @@ -53,8 +51,8 @@ class TripleHttp2ClientResponseHandlerTest { @Test void testUserEventTriggered() throws Exception { // test Http2GoAwayFrame - Http2GoAwayFrame goAwayFrame = new DefaultHttp2GoAwayFrame(Http2Error.NO_ERROR, ByteBufUtil - .writeAscii(ByteBufAllocator.DEFAULT, "app_requested")); + Http2GoAwayFrame goAwayFrame = new DefaultHttp2GoAwayFrame( + Http2Error.NO_ERROR, ByteBufUtil.writeAscii(ByteBufAllocator.DEFAULT, "app_requested")); handler.userEventTriggered(ctx, goAwayFrame); Mockito.verify(ctx, Mockito.times(1)).close(); diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/transport/WriteQueueTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/transport/WriteQueueTest.java index 40e5c1d84d..22e8452463 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/transport/WriteQueueTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/transport/WriteQueueTest.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.protocol.tri.transport; -import io.netty.channel.embedded.EmbeddedChannel; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.TriRpcStatus; import org.apache.dubbo.rpc.protocol.tri.command.CancelQueueCommand; @@ -24,14 +23,18 @@ import org.apache.dubbo.rpc.protocol.tri.command.DataQueueCommand; import org.apache.dubbo.rpc.protocol.tri.command.HeaderQueueCommand; import org.apache.dubbo.rpc.protocol.tri.command.QueuedCommand; import org.apache.dubbo.rpc.protocol.tri.command.TextDataQueueCommand; +import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; import io.netty.channel.Channel; import io.netty.channel.ChannelPromise; import io.netty.channel.DefaultEventLoop; import io.netty.channel.EventLoop; +import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.http2.DefaultHttp2Headers; import io.netty.handler.codec.http2.Http2Error; -import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; @@ -40,12 +43,8 @@ import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.mockito.stubbing.Answer; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; - import static org.apache.dubbo.rpc.protocol.tri.transport.WriteQueue.DEQUE_CHUNK_SIZE; - /** * {@link WriteQueue} */ @@ -65,8 +64,8 @@ class WriteQueueTest { Mockito.when(channel.eventLoop()).thenReturn(eventLoop); Mockito.when(channel.isActive()).thenReturn(true); Mockito.when(channel.newPromise()).thenReturn(promise); - Mockito.when(channel.write(Mockito.any(), Mockito.any())).thenAnswer( - (Answer) invocationOnMock -> { + Mockito.when(channel.write(Mockito.any(), Mockito.any())) + .thenAnswer((Answer) invocationOnMock -> { writeMethodCalledTimes.incrementAndGet(); return promise; }); @@ -81,13 +80,16 @@ class WriteQueueTest { WriteQueue writeQueue = new WriteQueue(); EmbeddedChannel embeddedChannel = new EmbeddedChannel(); TripleStreamChannelFuture tripleStreamChannelFuture = new TripleStreamChannelFuture(embeddedChannel); - writeQueue.enqueue(HeaderQueueCommand.createHeaders(tripleStreamChannelFuture, new DefaultHttp2Headers()).channel(channel)); - writeQueue.enqueue(DataQueueCommand.create(tripleStreamChannelFuture, new byte[0], false, 0).channel(channel)); - TriRpcStatus status = TriRpcStatus.UNKNOWN - .withCause(new RpcException()) - .withDescription("Encode Response data error"); - writeQueue.enqueue(CancelQueueCommand.createCommand(tripleStreamChannelFuture, Http2Error.CANCEL).channel(channel)); - writeQueue.enqueue(TextDataQueueCommand.createCommand(tripleStreamChannelFuture, status.description, true).channel(channel)); + writeQueue.enqueue(HeaderQueueCommand.createHeaders(tripleStreamChannelFuture, new DefaultHttp2Headers()) + .channel(channel)); + writeQueue.enqueue(DataQueueCommand.create(tripleStreamChannelFuture, new byte[0], false, 0) + .channel(channel)); + TriRpcStatus status = + TriRpcStatus.UNKNOWN.withCause(new RpcException()).withDescription("Encode Response data error"); + writeQueue.enqueue(CancelQueueCommand.createCommand(tripleStreamChannelFuture, Http2Error.CANCEL) + .channel(channel)); + writeQueue.enqueue(TextDataQueueCommand.createCommand(tripleStreamChannelFuture, status.description, true) + .channel(channel)); while (writeMethodCalledTimes.get() != 4) { Thread.sleep(50); @@ -95,7 +97,8 @@ class WriteQueueTest { ArgumentCaptor commandArgumentCaptor = ArgumentCaptor.forClass(QueuedCommand.class); ArgumentCaptor promiseArgumentCaptor = ArgumentCaptor.forClass(ChannelPromise.class); - Mockito.verify(channel, Mockito.times(4)).write(commandArgumentCaptor.capture(), promiseArgumentCaptor.capture()); + Mockito.verify(channel, Mockito.times(4)) + .write(commandArgumentCaptor.capture(), promiseArgumentCaptor.capture()); List queuedCommands = commandArgumentCaptor.getAllValues(); Assertions.assertEquals(queuedCommands.size(), 4); Assertions.assertTrue(queuedCommands.get(0) instanceof HeaderQueueCommand); @@ -113,13 +116,14 @@ class WriteQueueTest { TripleStreamChannelFuture tripleStreamChannelFuture = new TripleStreamChannelFuture(embeddedChannel); writeMethodCalledTimes.set(0); for (int i = 0; i < DEQUE_CHUNK_SIZE; i++) { - writeQueue.enqueue(HeaderQueueCommand.createHeaders(tripleStreamChannelFuture, new DefaultHttp2Headers()).channel(channel)); + writeQueue.enqueue(HeaderQueueCommand.createHeaders(tripleStreamChannelFuture, new DefaultHttp2Headers()) + .channel(channel)); } - writeQueue.enqueue(HeaderQueueCommand.createHeaders(tripleStreamChannelFuture, new DefaultHttp2Headers()).channel(channel)); + writeQueue.enqueue(HeaderQueueCommand.createHeaders(tripleStreamChannelFuture, new DefaultHttp2Headers()) + .channel(channel)); while (writeMethodCalledTimes.get() != (DEQUE_CHUNK_SIZE + 1)) { Thread.sleep(50); } Mockito.verify(channel, Mockito.times(DEQUE_CHUNK_SIZE + 1)).write(Mockito.any(), Mockito.any()); } - } diff --git a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/stub/StubInvocationUtilTest.java b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/stub/StubInvocationUtilTest.java index 9db612a3ef..c3d92ff237 100644 --- a/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/stub/StubInvocationUtilTest.java +++ b/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/stub/StubInvocationUtilTest.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.stub; import org.apache.dubbo.common.URL; @@ -27,15 +26,15 @@ import org.apache.dubbo.rpc.model.MethodDescriptor; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.protocol.tri.support.IGreeter; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; - import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @@ -76,7 +75,7 @@ class StubInvocationUtilTest { private MethodDescriptor createMockMethodDescriptor() { MethodDescriptor method = Mockito.mock(MethodDescriptor.class); - when(method.getParameterClasses()).thenReturn(new Class[]{String.class}); + when(method.getParameterClasses()).thenReturn(new Class[] {String.class}); when(method.getMethodName()).thenReturn("sayHello"); return method; } @@ -99,8 +98,10 @@ class StubInvocationUtilTest { } @Test - void unaryCall2(){ - when(invoker.invoke(any(Invocation.class))).thenThrow(new RuntimeException("a")).thenThrow(new Error("b")); + void unaryCall2() { + when(invoker.invoke(any(Invocation.class))) + .thenThrow(new RuntimeException("a")) + .thenThrow(new Error("b")); try { StubInvocationUtil.unaryCall(invoker, method, request); fail(); @@ -127,8 +128,7 @@ class StubInvocationUtilTest { } @Override - public void onError(Throwable throwable) { - } + public void onError(Throwable throwable) {} @Override public void onCompleted() { @@ -144,7 +144,8 @@ class StubInvocationUtilTest { void biOrClientStreamCall() throws InterruptedException { when(invoker.invoke(any(Invocation.class))).then(invocationOnMock -> { Invocation invocation = (Invocation) invocationOnMock.getArguments()[0]; - StreamObserver observer = (StreamObserver) invocation.getArguments()[0]; + StreamObserver observer = + (StreamObserver) invocation.getArguments()[0]; observer.onNext(response); observer.onCompleted(); when(result.recreate()).then(invocationOnMock1 -> new StreamObserver() { @@ -154,9 +155,7 @@ class StubInvocationUtilTest { } @Override - public void onError(Throwable throwable) { - - } + public void onError(Throwable throwable) {} @Override public void onCompleted() { @@ -173,8 +172,7 @@ class StubInvocationUtilTest { } @Override - public void onError(Throwable throwable) { - } + public void onError(Throwable throwable) {} @Override public void onCompleted() { @@ -193,7 +191,8 @@ class StubInvocationUtilTest { void serverStreamCall() throws InterruptedException { when(invoker.invoke(any(Invocation.class))).then(invocationOnMock -> { Invocation invocation = (Invocation) invocationOnMock.getArguments()[0]; - StreamObserver observer = (StreamObserver) invocation.getArguments()[1]; + StreamObserver observer = + (StreamObserver) invocation.getArguments()[1]; for (int i = 0; i < 10; i++) { observer.onNext(response); } @@ -208,8 +207,7 @@ class StubInvocationUtilTest { } @Override - public void onError(Throwable throwable) { - } + public void onError(Throwable throwable) {} @Override public void onCompleted() { @@ -219,5 +217,4 @@ class StubInvocationUtilTest { StubInvocationUtil.serverStreamCall(invoker, method, request, responseObserver); Assertions.assertTrue(latch.await(1, TimeUnit.SECONDS)); } - } diff --git a/dubbo-rpc/pom.xml b/dubbo-rpc/pom.xml index 752b6c560c..14fe501020 100644 --- a/dubbo-rpc/pom.xml +++ b/dubbo-rpc/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-parent - ${revision} - ../pom.xml - - dubbo-rpc - pom - ${project.artifactId} - The rpc module of dubbo project - - false - - - dubbo-rpc-api - dubbo-rpc-dubbo - dubbo-rpc-injvm - dubbo-rpc-rest - dubbo-rpc-triple - + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + + dubbo-rpc + pom + ${project.artifactId} + The rpc module of dubbo project + + dubbo-rpc-api + dubbo-rpc-dubbo + dubbo-rpc-injvm + dubbo-rpc-rest + dubbo-rpc-triple + + + false + - - - org.apache.dubbo - dubbo-test-check - ${project.parent.version} - test - - + + + org.apache.dubbo + dubbo-test-check + ${project.parent.version} + test + + diff --git a/dubbo-serialization/dubbo-serialization-api/pom.xml b/dubbo-serialization/dubbo-serialization-api/pom.xml index f76044ced2..dca58b1feb 100644 --- a/dubbo-serialization/dubbo-serialization-api/pom.xml +++ b/dubbo-serialization/dubbo-serialization-api/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - org.apache.dubbo - dubbo-serialization - ${revision} - ../pom.xml - - dubbo-serialization-api - jar - ${project.artifactId} - The serialization interface module of dubbo project - - false - - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - \ No newline at end of file + 4.0.0 + + org.apache.dubbo + dubbo-serialization + ${revision} + ../pom.xml + + dubbo-serialization-api + jar + ${project.artifactId} + The serialization interface module of dubbo project + + false + + + + org.apache.dubbo + dubbo-common + ${project.parent.version} + + + diff --git a/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/Constants.java b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/Constants.java index 9dda745b0d..00bb5f8486 100644 --- a/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/Constants.java +++ b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/Constants.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.serialize; public interface Constants { diff --git a/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/DefaultMultipleSerialization.java b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/DefaultMultipleSerialization.java index bff9842444..b0ccb0fd04 100644 --- a/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/DefaultMultipleSerialization.java +++ b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/DefaultMultipleSerialization.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.serialize; import org.apache.dubbo.common.URL; @@ -28,16 +27,21 @@ public class DefaultMultipleSerialization implements MultipleSerialization { @Override public void serialize(URL url, String serializeType, Class clz, Object obj, OutputStream os) throws IOException { serializeType = convertHessian(serializeType); - final Serialization serialization = url.getOrDefaultFrameworkModel().getExtensionLoader(Serialization.class).getExtension(serializeType); + final Serialization serialization = url.getOrDefaultFrameworkModel() + .getExtensionLoader(Serialization.class) + .getExtension(serializeType); final ObjectOutput serialize = serialization.serialize(null, os); serialize.writeObject(obj); serialize.flushBuffer(); } @Override - public Object deserialize(URL url, String serializeType, Class clz, InputStream os) throws IOException, ClassNotFoundException { + public Object deserialize(URL url, String serializeType, Class clz, InputStream os) + throws IOException, ClassNotFoundException { serializeType = convertHessian(serializeType); - final Serialization serialization = url.getOrDefaultFrameworkModel().getExtensionLoader(Serialization.class).getExtension(serializeType); + final Serialization serialization = url.getOrDefaultFrameworkModel() + .getExtensionLoader(Serialization.class) + .getExtension(serializeType); final ObjectInput in = serialization.deserialize(null, os); return in.readObject(clz); } diff --git a/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/DefaultSerializationExceptionWrapper.java b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/DefaultSerializationExceptionWrapper.java index 6d7f4fabe8..6e29085068 100644 --- a/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/DefaultSerializationExceptionWrapper.java +++ b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/DefaultSerializationExceptionWrapper.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.serialize; import org.apache.dubbo.common.URL; @@ -81,7 +80,6 @@ public class DefaultSerializationExceptionWrapper implements Serialization { return target.readByte(); } catch (Exception e) { throw handleToIOException(e); - } } @@ -91,7 +89,6 @@ public class DefaultSerializationExceptionWrapper implements Serialization { return target.readShort(); } catch (Exception e) { throw handleToIOException(e); - } } @@ -101,7 +98,6 @@ public class DefaultSerializationExceptionWrapper implements Serialization { return target.readInt(); } catch (Exception e) { throw handleToIOException(e); - } } @@ -111,7 +107,6 @@ public class DefaultSerializationExceptionWrapper implements Serialization { return target.readLong(); } catch (Exception e) { throw handleToIOException(e); - } } @@ -359,5 +354,4 @@ public class DefaultSerializationExceptionWrapper implements Serialization { } return (IOException) e; } - } diff --git a/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/MultipleSerialization.java b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/MultipleSerialization.java index 55b67fcad6..3bafedfbca 100644 --- a/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/MultipleSerialization.java +++ b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/MultipleSerialization.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.serialize; import org.apache.dubbo.common.URL; @@ -30,6 +29,6 @@ public interface MultipleSerialization { void serialize(URL url, String serializeType, Class clz, Object obj, OutputStream os) throws IOException; - Object deserialize(URL url, String serializeType, Class clz, InputStream os) throws IOException, ClassNotFoundException; - + Object deserialize(URL url, String serializeType, Class clz, InputStream os) + throws IOException, ClassNotFoundException; } diff --git a/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/ObjectInput.java b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/ObjectInput.java index 853334f925..34a54dc784 100644 --- a/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/ObjectInput.java +++ b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/ObjectInput.java @@ -55,7 +55,6 @@ public interface ObjectInput extends DataInput { */ T readObject(Class cls, Type type) throws IOException, ClassNotFoundException; - /** * The following methods are customized for the requirement of Dubbo's RPC protocol implementation. Legacy protocol * implementation will try to write Map, Throwable and Null value directly to the stream, which does not meet the diff --git a/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/ObjectOutput.java b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/ObjectOutput.java index 20b189fd5d..3681c811e5 100644 --- a/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/ObjectOutput.java +++ b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/ObjectOutput.java @@ -56,5 +56,4 @@ public interface ObjectOutput extends DataOutput { default void writeAttachments(Map attachments) throws IOException { writeObject(attachments); } - } diff --git a/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/Serialization.java b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/Serialization.java index d0314c576d..6ecca8d441 100644 --- a/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/Serialization.java +++ b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/Serialization.java @@ -38,7 +38,7 @@ public interface Serialization { /** * Get content type unique id, recommended that custom implementations use values different with - * any value of {@link Constants} and don't greater than ExchangeCodec.SERIALIZATION_MASK (31) + * any value of {@link Constants} and don't greater than ExchangeCodec.SERIALIZATION_MASK (31) * because dubbo protocol use 5 bits to record serialization ID in header. * * @return content type id @@ -73,5 +73,4 @@ public interface Serialization { */ @Adaptive ObjectInput deserialize(URL url, InputStream input) throws IOException; - } diff --git a/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/SerializationException.java b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/SerializationException.java index ed0c445562..9ad234f967 100644 --- a/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/SerializationException.java +++ b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/SerializationException.java @@ -31,5 +31,4 @@ public class SerializationException extends Exception { public SerializationException(Throwable cause) { super(cause); } - } diff --git a/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/support/DefaultSerializationSelector.java b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/support/DefaultSerializationSelector.java index 86c08257ea..d7cb4a6e84 100644 --- a/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/support/DefaultSerializationSelector.java +++ b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/support/DefaultSerializationSelector.java @@ -16,14 +16,13 @@ */ package org.apache.dubbo.common.serialize.support; - public class DefaultSerializationSelector { - private final static String DEFAULT_REMOTING_SERIALIZATION_PROPERTY_KEY = "DUBBO_DEFAULT_SERIALIZATION"; + private static final String DEFAULT_REMOTING_SERIALIZATION_PROPERTY_KEY = "DUBBO_DEFAULT_SERIALIZATION"; - private final static String DEFAULT_REMOTING_SERIALIZATION_PROPERTY = "hessian2"; + private static final String DEFAULT_REMOTING_SERIALIZATION_PROPERTY = "hessian2"; - private final static String DEFAULT_REMOTING_SERIALIZATION; + private static final String DEFAULT_REMOTING_SERIALIZATION; static { String fromProperty = System.getProperty(DEFAULT_REMOTING_SERIALIZATION_PROPERTY_KEY); diff --git a/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/support/SerializableClassRegistry.java b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/support/SerializableClassRegistry.java index 591ba0e1b0..47cab4996b 100644 --- a/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/support/SerializableClassRegistry.java +++ b/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/support/SerializableClassRegistry.java @@ -25,7 +25,6 @@ import java.util.Map; */ public abstract class SerializableClassRegistry { - private static final Map, Object> REGISTRATIONS = new HashMap<>(); /** diff --git a/dubbo-serialization/dubbo-serialization-fastjson2/pom.xml b/dubbo-serialization/dubbo-serialization-fastjson2/pom.xml index 736bd1fc2c..432de6f89d 100644 --- a/dubbo-serialization/dubbo-serialization-fastjson2/pom.xml +++ b/dubbo-serialization/dubbo-serialization-fastjson2/pom.xml @@ -15,34 +15,31 @@ 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. --> + + 4.0.0 + + org.apache.dubbo + dubbo-serialization + ${revision} + ../pom.xml + - - 4.0.0 - - org.apache.dubbo - dubbo-serialization - ${revision} - ../pom.xml - - - dubbo-serialization-fastjson2 - jar - ${project.artifactId} - The fastjson2 serialization module of dubbo project - - false - - - - org.apache.dubbo - dubbo-serialization-api - ${project.parent.version} - - - com.alibaba.fastjson2 - fastjson2 - - + dubbo-serialization-fastjson2 + jar + ${project.artifactId} + The fastjson2 serialization module of dubbo project + + false + + + + org.apache.dubbo + dubbo-serialization-api + ${project.parent.version} + + + com.alibaba.fastjson2 + fastjson2 + + diff --git a/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2ObjectInput.java b/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2ObjectInput.java index 6b19a110ee..a167ea3983 100644 --- a/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2ObjectInput.java +++ b/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2ObjectInput.java @@ -19,13 +19,13 @@ package org.apache.dubbo.common.serialize.fastjson2; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.utils.ClassUtils; -import com.alibaba.fastjson2.JSONB; -import com.alibaba.fastjson2.JSONReader; - import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; +import com.alibaba.fastjson2.JSONB; +import com.alibaba.fastjson2.JSONReader; + /** * FastJson object input implementation */ @@ -38,8 +38,10 @@ public class FastJson2ObjectInput implements ObjectInput { private volatile ClassLoader classLoader; private final InputStream is; - public FastJson2ObjectInput(Fastjson2CreatorManager fastjson2CreatorManager, - Fastjson2SecurityManager fastjson2SecurityManager, InputStream in) { + public FastJson2ObjectInput( + Fastjson2CreatorManager fastjson2CreatorManager, + Fastjson2SecurityManager fastjson2SecurityManager, + InputStream in) { this.fastjson2CreatorManager = fastjson2CreatorManager; this.fastjson2SecurityManager = fastjson2SecurityManager; this.classLoader = Thread.currentThread().getContextClassLoader(); @@ -93,7 +95,8 @@ public class FastJson2ObjectInput implements ObjectInput { byte[] bytes = new byte[length]; int read = is.read(bytes, 0, length); if (read != length) { - throw new IllegalArgumentException("deserialize failed. expected read length: " + length + " but actual read: " + read); + throw new IllegalArgumentException( + "deserialize failed. expected read length: " + length + " but actual read: " + read); } return bytes; } @@ -110,26 +113,34 @@ public class FastJson2ObjectInput implements ObjectInput { byte[] bytes = new byte[length]; int read = is.read(bytes, 0, length); if (read != length) { - throw new IllegalArgumentException("deserialize failed. expected read length: " + length + " but actual read: " + read); + throw new IllegalArgumentException( + "deserialize failed. expected read length: " + length + " but actual read: " + read); } Fastjson2SecurityManager.Handler securityFilter = fastjson2SecurityManager.getSecurityFilter(); T result; if (securityFilter.isCheckSerializable()) { - result = JSONB.parseObject(bytes, cls, securityFilter, - JSONReader.Feature.UseDefaultConstructorAsPossible, - JSONReader.Feature.ErrorOnNoneSerializable, - JSONReader.Feature.IgnoreAutoTypeNotMatch, - JSONReader.Feature.UseNativeObject, - JSONReader.Feature.FieldBased); + result = JSONB.parseObject( + bytes, + cls, + securityFilter, + JSONReader.Feature.UseDefaultConstructorAsPossible, + JSONReader.Feature.ErrorOnNoneSerializable, + JSONReader.Feature.IgnoreAutoTypeNotMatch, + JSONReader.Feature.UseNativeObject, + JSONReader.Feature.FieldBased); } else { - result = JSONB.parseObject(bytes, cls, securityFilter, - JSONReader.Feature.UseDefaultConstructorAsPossible, - JSONReader.Feature.UseNativeObject, - JSONReader.Feature.IgnoreAutoTypeNotMatch, - JSONReader.Feature.FieldBased); + result = JSONB.parseObject( + bytes, + cls, + securityFilter, + JSONReader.Feature.UseDefaultConstructorAsPossible, + JSONReader.Feature.UseNativeObject, + JSONReader.Feature.IgnoreAutoTypeNotMatch, + JSONReader.Feature.FieldBased); } if (result != null && cls != null && !ClassUtils.isMatch(result.getClass(), cls)) { - throw new IllegalArgumentException("deserialize failed. expected class: " + cls + " but actual class: " + result.getClass()); + throw new IllegalArgumentException( + "deserialize failed. expected class: " + cls + " but actual class: " + result.getClass()); } return result; } @@ -141,26 +152,34 @@ public class FastJson2ObjectInput implements ObjectInput { byte[] bytes = new byte[length]; int read = is.read(bytes, 0, length); if (read != length) { - throw new IllegalArgumentException("deserialize failed. expected read length: " + length + " but actual read: " + read); + throw new IllegalArgumentException( + "deserialize failed. expected read length: " + length + " but actual read: " + read); } Fastjson2SecurityManager.Handler securityFilter = fastjson2SecurityManager.getSecurityFilter(); T result; if (securityFilter.isCheckSerializable()) { - result = JSONB.parseObject(bytes, cls, securityFilter, - JSONReader.Feature.UseDefaultConstructorAsPossible, - JSONReader.Feature.ErrorOnNoneSerializable, - JSONReader.Feature.IgnoreAutoTypeNotMatch, - JSONReader.Feature.UseNativeObject, - JSONReader.Feature.FieldBased); + result = JSONB.parseObject( + bytes, + cls, + securityFilter, + JSONReader.Feature.UseDefaultConstructorAsPossible, + JSONReader.Feature.ErrorOnNoneSerializable, + JSONReader.Feature.IgnoreAutoTypeNotMatch, + JSONReader.Feature.UseNativeObject, + JSONReader.Feature.FieldBased); } else { - result = JSONB.parseObject(bytes, cls, securityFilter, - JSONReader.Feature.UseDefaultConstructorAsPossible, - JSONReader.Feature.UseNativeObject, - JSONReader.Feature.IgnoreAutoTypeNotMatch, - JSONReader.Feature.FieldBased); + result = JSONB.parseObject( + bytes, + cls, + securityFilter, + JSONReader.Feature.UseDefaultConstructorAsPossible, + JSONReader.Feature.UseNativeObject, + JSONReader.Feature.IgnoreAutoTypeNotMatch, + JSONReader.Feature.FieldBased); } if (result != null && cls != null && !ClassUtils.isMatch(result.getClass(), cls)) { - throw new IllegalArgumentException("deserialize failed. expected class: " + cls + " but actual class: " + result.getClass()); + throw new IllegalArgumentException( + "deserialize failed. expected class: " + cls + " but actual class: " + result.getClass()); } return result; } @@ -177,7 +196,8 @@ public class FastJson2ObjectInput implements ObjectInput { byte[] bytes = new byte[Integer.BYTES]; int read = is.read(bytes, 0, Integer.BYTES); if (read != Integer.BYTES) { - throw new IllegalArgumentException("deserialize failed. expected read length: " + Integer.BYTES + " but actual read: " + read); + throw new IllegalArgumentException( + "deserialize failed. expected read length: " + Integer.BYTES + " but actual read: " + read); } int value = 0; for (byte b : bytes) { diff --git a/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2ObjectOutput.java b/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2ObjectOutput.java index 025e7a603f..f596b8db4a 100644 --- a/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2ObjectOutput.java +++ b/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2ObjectOutput.java @@ -16,11 +16,11 @@ */ package org.apache.dubbo.common.serialize.fastjson2; +import org.apache.dubbo.common.serialize.ObjectOutput; + import java.io.IOException; import java.io.OutputStream; -import org.apache.dubbo.common.serialize.ObjectOutput; - import com.alibaba.fastjson2.JSONB; import com.alibaba.fastjson2.JSONWriter; @@ -36,9 +36,10 @@ public class FastJson2ObjectOutput implements ObjectOutput { private volatile ClassLoader classLoader; private final OutputStream os; - public FastJson2ObjectOutput(Fastjson2CreatorManager fastjson2CreatorManager, - Fastjson2SecurityManager fastjson2SecurityManager, - OutputStream out) { + public FastJson2ObjectOutput( + Fastjson2CreatorManager fastjson2CreatorManager, + Fastjson2SecurityManager fastjson2SecurityManager, + OutputStream out) { this.fastjson2CreatorManager = fastjson2CreatorManager; this.fastjson2SecurityManager = fastjson2SecurityManager; this.classLoader = Thread.currentThread().getContextClassLoader(); @@ -103,22 +104,26 @@ public class FastJson2ObjectOutput implements ObjectOutput { updateClassLoaderIfNeed(); byte[] bytes; if (fastjson2SecurityManager.getSecurityFilter().isCheckSerializable()) { - bytes = JSONB.toBytes(obj, JSONWriter.Feature.WriteClassName, - JSONWriter.Feature.FieldBased, - JSONWriter.Feature.ErrorOnNoneSerializable, - JSONWriter.Feature.ReferenceDetection, - JSONWriter.Feature.WriteNulls, - JSONWriter.Feature.NotWriteDefaultValue, - JSONWriter.Feature.NotWriteHashMapArrayListClassName, - JSONWriter.Feature.WriteNameAsSymbol); + bytes = JSONB.toBytes( + obj, + JSONWriter.Feature.WriteClassName, + JSONWriter.Feature.FieldBased, + JSONWriter.Feature.ErrorOnNoneSerializable, + JSONWriter.Feature.ReferenceDetection, + JSONWriter.Feature.WriteNulls, + JSONWriter.Feature.NotWriteDefaultValue, + JSONWriter.Feature.NotWriteHashMapArrayListClassName, + JSONWriter.Feature.WriteNameAsSymbol); } else { - bytes = JSONB.toBytes(obj, JSONWriter.Feature.WriteClassName, - JSONWriter.Feature.FieldBased, - JSONWriter.Feature.ReferenceDetection, - JSONWriter.Feature.WriteNulls, - JSONWriter.Feature.NotWriteDefaultValue, - JSONWriter.Feature.NotWriteHashMapArrayListClassName, - JSONWriter.Feature.WriteNameAsSymbol); + bytes = JSONB.toBytes( + obj, + JSONWriter.Feature.WriteClassName, + JSONWriter.Feature.FieldBased, + JSONWriter.Feature.ReferenceDetection, + JSONWriter.Feature.WriteNulls, + JSONWriter.Feature.NotWriteDefaultValue, + JSONWriter.Feature.NotWriteHashMapArrayListClassName, + JSONWriter.Feature.WriteNameAsSymbol); } writeLength(bytes.length); os.write(bytes); @@ -147,5 +152,4 @@ public class FastJson2ObjectOutput implements ObjectOutput { public void flushBuffer() throws IOException { os.flush(); } - } diff --git a/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2Serialization.java b/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2Serialization.java index 47ce0e1708..39ee568f42 100644 --- a/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2Serialization.java +++ b/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2Serialization.java @@ -51,13 +51,15 @@ public class FastJson2Serialization implements Serialization { @Override public ObjectOutput serialize(URL url, OutputStream output) throws IOException { Fastjson2CreatorManager fastjson2CreatorManager = Optional.ofNullable(url) - .map(URL::getOrDefaultFrameworkModel) - .orElseGet(FrameworkModel::defaultModel) - .getBeanFactory().getBean(Fastjson2CreatorManager.class); + .map(URL::getOrDefaultFrameworkModel) + .orElseGet(FrameworkModel::defaultModel) + .getBeanFactory() + .getBean(Fastjson2CreatorManager.class); Fastjson2SecurityManager fastjson2SecurityManager = Optional.ofNullable(url) - .map(URL::getOrDefaultFrameworkModel) - .orElseGet(FrameworkModel::defaultModel) - .getBeanFactory().getBean(Fastjson2SecurityManager.class); + .map(URL::getOrDefaultFrameworkModel) + .orElseGet(FrameworkModel::defaultModel) + .getBeanFactory() + .getBean(Fastjson2SecurityManager.class); return new FastJson2ObjectOutput(fastjson2CreatorManager, fastjson2SecurityManager, output); } @@ -65,15 +67,16 @@ public class FastJson2Serialization implements Serialization { @Override public ObjectInput deserialize(URL url, InputStream input) throws IOException { Fastjson2CreatorManager fastjson2CreatorManager = Optional.ofNullable(url) - .map(URL::getOrDefaultFrameworkModel) - .orElseGet(FrameworkModel::defaultModel) - .getBeanFactory().getBean(Fastjson2CreatorManager.class); + .map(URL::getOrDefaultFrameworkModel) + .orElseGet(FrameworkModel::defaultModel) + .getBeanFactory() + .getBean(Fastjson2CreatorManager.class); Fastjson2SecurityManager fastjson2SecurityManager = Optional.ofNullable(url) - .map(URL::getOrDefaultFrameworkModel) - .orElseGet(FrameworkModel::defaultModel) - .getBeanFactory().getBean(Fastjson2SecurityManager.class); + .map(URL::getOrDefaultFrameworkModel) + .orElseGet(FrameworkModel::defaultModel) + .getBeanFactory() + .getBean(Fastjson2SecurityManager.class); return new FastJson2ObjectInput(fastjson2CreatorManager, fastjson2SecurityManager, input); } - } diff --git a/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/Fastjson2CreatorManager.java b/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/Fastjson2CreatorManager.java index e112f89226..4120dc3943 100644 --- a/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/Fastjson2CreatorManager.java +++ b/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/Fastjson2CreatorManager.java @@ -16,26 +16,25 @@ */ package org.apache.dubbo.common.serialize.fastjson2; -import com.alibaba.fastjson2.reader.ObjectReaderCreator; -import com.alibaba.fastjson2.writer.ObjectWriterCreator; import org.apache.dubbo.common.aot.NativeDetector; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ScopeClassLoaderListener; -import com.alibaba.fastjson2.JSONFactory; -import com.alibaba.fastjson2.reader.ObjectReaderCreatorASM; -import com.alibaba.fastjson2.writer.ObjectWriterCreatorASM; - import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import com.alibaba.fastjson2.JSONFactory; +import com.alibaba.fastjson2.reader.ObjectReaderCreator; +import com.alibaba.fastjson2.reader.ObjectReaderCreatorASM; +import com.alibaba.fastjson2.writer.ObjectWriterCreator; +import com.alibaba.fastjson2.writer.ObjectWriterCreatorASM; + public class Fastjson2CreatorManager implements ScopeClassLoaderListener { /** * An empty classLoader used when classLoader is system classLoader. Prevent the NPE. */ - private static final ClassLoader SYSTEM_CLASSLOADER_KEY = new ClassLoader() { - }; + private static final ClassLoader SYSTEM_CLASSLOADER_KEY = new ClassLoader() {}; private final Map readerMap = new ConcurrentHashMap<>(); private final Map writerMap = new ConcurrentHashMap<>(); diff --git a/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/Fastjson2ScopeModelInitializer.java b/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/Fastjson2ScopeModelInitializer.java index db256cce38..520d9465be 100644 --- a/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/Fastjson2ScopeModelInitializer.java +++ b/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/Fastjson2ScopeModelInitializer.java @@ -32,12 +32,8 @@ public class Fastjson2ScopeModelInitializer implements ScopeModelInitializer { } @Override - public void initializeApplicationModel(ApplicationModel applicationModel) { - - } + public void initializeApplicationModel(ApplicationModel applicationModel) {} @Override - public void initializeModuleModel(ModuleModel moduleModel) { - - } + public void initializeModuleModel(ModuleModel moduleModel) {} } diff --git a/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/Fastjson2SecurityManager.java b/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/Fastjson2SecurityManager.java index 1c1258af55..d155fabe1b 100644 --- a/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/Fastjson2SecurityManager.java +++ b/dubbo-serialization/dubbo-serialization-fastjson2/src/main/java/org/apache/dubbo/common/serialize/fastjson2/Fastjson2SecurityManager.java @@ -24,13 +24,13 @@ import org.apache.dubbo.common.utils.SerializeCheckStatus; import org.apache.dubbo.common.utils.SerializeSecurityManager; import org.apache.dubbo.rpc.model.FrameworkModel; -import com.alibaba.fastjson2.filter.ContextAutoTypeBeforeHandler; -import com.alibaba.fastjson2.util.TypeUtils; - import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import com.alibaba.fastjson2.filter.ContextAutoTypeBeforeHandler; +import com.alibaba.fastjson2.util.TypeUtils; + import static com.alibaba.fastjson2.util.TypeUtils.loadClass; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_UNTRUSTED_SERIALIZE_CLASS; import static org.apache.dubbo.common.utils.SerializeCheckStatus.STRICT; @@ -38,7 +38,8 @@ import static org.apache.dubbo.common.utils.SerializeCheckStatus.STRICT; public class Fastjson2SecurityManager implements AllowClassNotifyListener { private volatile Handler securityFilter; - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(Fastjson2SecurityManager.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(Fastjson2SecurityManager.class); private final SerializeSecurityManager securityManager; @@ -53,27 +54,46 @@ public class Fastjson2SecurityManager implements AllowClassNotifyListener { public Fastjson2SecurityManager(FrameworkModel frameworkModel) { securityManager = frameworkModel.getBeanFactory().getOrRegisterBean(SerializeSecurityManager.class); securityManager.registerListener(this); - securityFilter = new Handler(AllowClassNotifyListener.DEFAULT_STATUS, securityManager, true, new String[0], new ConcurrentHashSet<>()); + securityFilter = new Handler( + AllowClassNotifyListener.DEFAULT_STATUS, + securityManager, + true, + new String[0], + new ConcurrentHashSet<>()); } @Override public synchronized void notifyPrefix(Set allowedList, Set disAllowedList) { this.allowedList = allowedList; this.disAllowedList = disAllowedList; - this.securityFilter = new Handler(this.status, this.securityManager, this.checkSerializable, this.allowedList.toArray(new String[0]), this.disAllowedList); + this.securityFilter = new Handler( + this.status, + this.securityManager, + this.checkSerializable, + this.allowedList.toArray(new String[0]), + this.disAllowedList); } @Override public synchronized void notifyCheckStatus(SerializeCheckStatus status) { this.status = status; - this.securityFilter = new Handler(this.status, this.securityManager, this.checkSerializable, this.allowedList.toArray(new String[0]), this.disAllowedList); + this.securityFilter = new Handler( + this.status, + this.securityManager, + this.checkSerializable, + this.allowedList.toArray(new String[0]), + this.disAllowedList); } @Override public synchronized void notifyCheckSerializable(boolean checkSerializable) { this.checkSerializable = checkSerializable; - this.securityFilter = new Handler(this.status, this.securityManager, this.checkSerializable, this.allowedList.toArray(new String[0]), this.disAllowedList); - + this.securityFilter = new Handler( + this.status, + this.securityManager, + this.checkSerializable, + this.allowedList.toArray(new String[0]), + this.disAllowedList); } public Handler getSecurityFilter() { @@ -89,7 +109,12 @@ public class Fastjson2SecurityManager implements AllowClassNotifyListener { final boolean checkSerializable; - public Handler(SerializeCheckStatus status, SerializeSecurityManager serializeSecurityManager, boolean checkSerializable, String[] acceptNames, Set disAllowedList) { + public Handler( + SerializeCheckStatus status, + SerializeSecurityManager serializeSecurityManager, + boolean checkSerializable, + String[] acceptNames, + Set disAllowedList) { super(true, acceptNames); this.status = status; this.serializeSecurityManager = serializeSecurityManager; @@ -108,9 +133,9 @@ public class Fastjson2SecurityManager implements AllowClassNotifyListener { // 2. check if in strict mode if (status == STRICT) { - String msg = "[Serialization Security] Serialized class " + typeName + " is not in allow list. " + - "Current mode is `STRICT`, will disallow to deserialize it by default. " + - "Please add it into security/serialize.allowlist or follow FAQ to configure it."; + String msg = "[Serialization Security] Serialized class " + typeName + " is not in allow list. " + + "Current mode is `STRICT`, will disallow to deserialize it by default. " + + "Please add it into security/serialize.allowlist or follow FAQ to configure it."; if (serializeSecurityManager.getWarnedClasses().add(typeName)) { logger.error(PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, "", "", msg); } @@ -121,12 +146,17 @@ public class Fastjson2SecurityManager implements AllowClassNotifyListener { // 3. try load Class localClass = loadClassDirectly(typeName); if (localClass != null) { - if (status == SerializeCheckStatus.WARN && serializeSecurityManager.getWarnedClasses().add(typeName)) { - logger.warn(PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, "", "", - "[Serialization Security] Serialized class " + localClass.getName() + " is not in allow list. " + - "Current mode is `WARN`, will allow to deserialize it by default. " + - "Dubbo will set to `STRICT` mode by default in the future. " + - "Please add it into security/serialize.allowlist or follow FAQ to configure it."); + if (status == SerializeCheckStatus.WARN + && serializeSecurityManager.getWarnedClasses().add(typeName)) { + logger.warn( + PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, + "", + "", + "[Serialization Security] Serialized class " + localClass.getName() + + " is not in allow list. " + + "Current mode is `WARN`, will allow to deserialize it by default. " + + "Dubbo will set to `STRICT` mode by default in the future. " + + "Please add it into security/serialize.allowlist or follow FAQ to configure it."); } return localClass; } @@ -148,9 +178,9 @@ public class Fastjson2SecurityManager implements AllowClassNotifyListener { if (clazz == null && checkIfDisAllow(typeName)) { clazz = DenyClass.class; - String msg = "[Serialization Security] Serialized class " + typeName + " is in disAllow list. " + - "Current mode is `WARN`, will disallow to deserialize it by default. " + - "Please add it into security/serialize.allowlist or follow FAQ to configure it."; + String msg = "[Serialization Security] Serialized class " + typeName + " is in disAllow list. " + + "Current mode is `WARN`, will disallow to deserialize it by default. " + + "Please add it into security/serialize.allowlist or follow FAQ to configure it."; if (serializeSecurityManager.getWarnedClasses().add(typeName)) { logger.warn(PROTOCOL_UNTRUSTED_SERIALIZE_CLASS, "", "", msg); } @@ -177,7 +207,6 @@ public class Fastjson2SecurityManager implements AllowClassNotifyListener { return clazz; } - } private static class DenyClass { diff --git a/dubbo-serialization/dubbo-serialization-fastjson2/src/test/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2SerializationTest.java b/dubbo-serialization/dubbo-serialization-fastjson2/src/test/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2SerializationTest.java index 4a9dc6eb0a..5c64491b95 100644 --- a/dubbo-serialization/dubbo-serialization-fastjson2/src/test/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2SerializationTest.java +++ b/dubbo-serialization/dubbo-serialization-fastjson2/src/test/java/org/apache/dubbo/common/serialize/fastjson2/FastJson2SerializationTest.java @@ -24,10 +24,6 @@ import org.apache.dubbo.common.utils.SerializeCheckStatus; import org.apache.dubbo.common.utils.SerializeSecurityManager; import org.apache.dubbo.rpc.model.FrameworkModel; -import com.example.test.TestPojo; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -38,12 +34,17 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; +import com.example.test.TestPojo; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + public class FastJson2SerializationTest { @Test void testReadString() throws IOException { FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write string, read string @@ -130,7 +131,8 @@ public class FastJson2SerializationTest { @Test void testReadEvent() throws IOException, ClassNotFoundException { FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write string, read event @@ -204,7 +206,8 @@ public class FastJson2SerializationTest { @Test void testReadByte() throws IOException { FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write byte, read byte @@ -278,14 +281,16 @@ public class FastJson2SerializationTest { @Test void testReadObject() throws IOException, ClassNotFoundException { FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write pojo, read pojo { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); @@ -299,7 +304,8 @@ public class FastJson2SerializationTest { { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); LinkedList pojos = new LinkedList<>(); pojos.add(trustedPojo); @@ -316,7 +322,8 @@ public class FastJson2SerializationTest { { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); @@ -330,7 +337,8 @@ public class FastJson2SerializationTest { { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); LinkedList pojos = new LinkedList<>(); pojos.add(trustedPojo); @@ -347,7 +355,8 @@ public class FastJson2SerializationTest { { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); LinkedList pojos = new LinkedList<>(); pojos.add(trustedPojo); @@ -366,15 +375,20 @@ public class FastJson2SerializationTest { @Test void testReadObjectNotMatched() throws IOException, ClassNotFoundException { FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); - frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class).setCheckStatus(SerializeCheckStatus.STRICT); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); + frameworkModel + .getBeanFactory() + .getBean(SerializeSecurityManager.class) + .setCheckStatus(SerializeCheckStatus.STRICT); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write pojo, read list failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); @@ -388,7 +402,8 @@ public class FastJson2SerializationTest { { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); @@ -402,7 +417,8 @@ public class FastJson2SerializationTest { { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); @@ -416,7 +432,8 @@ public class FastJson2SerializationTest { { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); @@ -430,7 +447,8 @@ public class FastJson2SerializationTest { { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); @@ -444,7 +462,8 @@ public class FastJson2SerializationTest { { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); @@ -458,7 +477,8 @@ public class FastJson2SerializationTest { { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); LinkedList pojos = new LinkedList<>(); pojos.add(trustedPojo); @@ -475,7 +495,8 @@ public class FastJson2SerializationTest { { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); LinkedList pojos = new LinkedList<>(); pojos.add(trustedPojo); @@ -494,7 +515,8 @@ public class FastJson2SerializationTest { @Test void testLimit1() throws IOException, ClassNotFoundException { FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write trusted, read trusted @@ -520,12 +542,16 @@ public class FastJson2SerializationTest { { FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); TestPojo trustedPojo = new TestPojo("12345"); - frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class).addToAllowed(trustedPojo.getClass().getName()); + frameworkModel + .getBeanFactory() + .getBean(SerializeSecurityManager.class) + .addToAllowed(trustedPojo.getClass().getName()); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); @@ -535,11 +561,15 @@ public class FastJson2SerializationTest { { FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); byte[] bytes = outputStream.toByteArray(); - frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class).setCheckStatus(SerializeCheckStatus.STRICT); + frameworkModel + .getBeanFactory() + .getBean(SerializeSecurityManager.class) + .setCheckStatus(SerializeCheckStatus.STRICT); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readObject); @@ -554,12 +584,17 @@ public class FastJson2SerializationTest { { FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); - TrustedNotSerializable trustedPojo = new TrustedNotSerializable(ThreadLocalRandom.current().nextDouble()); + TrustedNotSerializable trustedPojo = + new TrustedNotSerializable(ThreadLocalRandom.current().nextDouble()); - frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class).setCheckSerializable(false); + frameworkModel + .getBeanFactory() + .getBean(SerializeSecurityManager.class) + .setCheckSerializable(false); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); @@ -569,11 +604,15 @@ public class FastJson2SerializationTest { { FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); byte[] bytes = outputStream.toByteArray(); - frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class).setCheckStatus(SerializeCheckStatus.STRICT); + frameworkModel + .getBeanFactory() + .getBean(SerializeSecurityManager.class) + .setCheckStatus(SerializeCheckStatus.STRICT); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertThrows(IOException.class, objectInput::readObject); diff --git a/dubbo-serialization/dubbo-serialization-fastjson2/src/test/java/org/apache/dubbo/common/serialize/fastjson2/TypeMatchTest.java b/dubbo-serialization/dubbo-serialization-fastjson2/src/test/java/org/apache/dubbo/common/serialize/fastjson2/TypeMatchTest.java index 974f685a2a..21f4622f39 100644 --- a/dubbo-serialization/dubbo-serialization-fastjson2/src/test/java/org/apache/dubbo/common/serialize/fastjson2/TypeMatchTest.java +++ b/dubbo-serialization/dubbo-serialization-fastjson2/src/test/java/org/apache/dubbo/common/serialize/fastjson2/TypeMatchTest.java @@ -24,13 +24,6 @@ import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.extension.ExtensionContext; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.ArgumentsProvider; -import org.junit.jupiter.params.provider.ArgumentsSource; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.lang.reflect.Method; @@ -40,6 +33,13 @@ import java.util.List; import java.util.Map; import java.util.stream.Stream; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.ArgumentsProvider; +import org.junit.jupiter.params.provider.ArgumentsSource; + class TypeMatchTest { static class DataProvider implements ArgumentsProvider { @Override @@ -68,24 +68,32 @@ class TypeMatchTest { datas.add("world".getBytes()); for (Method method : ObjectInput.class.getMethods()) { - if (method.getName().startsWith("read") && method.getParameterTypes().length == 0 && !method.getReturnType().equals(Object.class)) { + if (method.getName().startsWith("read") + && method.getParameterTypes().length == 0 + && !method.getReturnType().equals(Object.class)) { readMethods.add(method); } } for (Method method : DataInput.class.getMethods()) { - if (method.getName().startsWith("read") && method.getParameterTypes().length == 0 && !method.getReturnType().equals(Object.class)) { + if (method.getName().startsWith("read") + && method.getParameterTypes().length == 0 + && !method.getReturnType().equals(Object.class)) { readMethods.add(method); } } for (Method method : ObjectOutput.class.getMethods()) { - if (method.getName().startsWith("write") && method.getParameterTypes().length == 1 && !method.getParameterTypes()[0].equals(Object.class)) { + if (method.getName().startsWith("write") + && method.getParameterTypes().length == 1 + && !method.getParameterTypes()[0].equals(Object.class)) { writeMethods.add(method); } } for (Method method : DataOutput.class.getMethods()) { - if (method.getName().startsWith("write") && method.getParameterTypes().length == 1 && !method.getParameterTypes()[0].equals(Object.class)) { + if (method.getName().startsWith("write") + && method.getParameterTypes().length == 1 + && !method.getParameterTypes()[0].equals(Object.class)) { writeMethods.add(method); } } @@ -108,8 +116,9 @@ class TypeMatchTest { if (output.getParameterTypes()[0].isAssignableFrom(data.getClass())) { argumentsList.add(Arguments.arguments(data, input, output)); } - if (primitiveWrapperTypeMap.containsKey(data.getClass()) && - output.getParameterTypes()[0].isAssignableFrom(primitiveWrapperTypeMap.get(data.getClass()))) { + if (primitiveWrapperTypeMap.containsKey(data.getClass()) + && output.getParameterTypes()[0].isAssignableFrom( + primitiveWrapperTypeMap.get(data.getClass()))) { argumentsList.add(Arguments.arguments(data, input, output)); } } @@ -124,7 +133,8 @@ class TypeMatchTest { @ArgumentsSource(DataProvider.class) void test(Object data, Method input, Method output) throws Exception { FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("fastjson2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); diff --git a/dubbo-serialization/dubbo-serialization-hessian2/pom.xml b/dubbo-serialization/dubbo-serialization-hessian2/pom.xml index 99a966ca6c..49728e18f4 100644 --- a/dubbo-serialization/dubbo-serialization-hessian2/pom.xml +++ b/dubbo-serialization/dubbo-serialization-hessian2/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - org.apache.dubbo - dubbo-serialization - ${revision} - ../pom.xml - - dubbo-serialization-hessian2 - jar - ${project.artifactId} - The hessian2 serialization module of dubbo project - - false - - - - org.apache.dubbo - dubbo-serialization-api - ${project.parent.version} - - - com.alibaba - hessian-lite - - - \ No newline at end of file + 4.0.0 + + org.apache.dubbo + dubbo-serialization + ${revision} + ../pom.xml + + dubbo-serialization-hessian2 + jar + ${project.artifactId} + The hessian2 serialization module of dubbo project + + false + + + + org.apache.dubbo + dubbo-serialization-api + ${project.parent.version} + + + com.alibaba + hessian-lite + + + diff --git a/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ClassLoaderListener.java b/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ClassLoaderListener.java index 13b0b2462d..5387607d96 100644 --- a/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ClassLoaderListener.java +++ b/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ClassLoaderListener.java @@ -27,7 +27,8 @@ public class Hessian2ClassLoaderListener implements ScopeClassLoaderListener T readObject(Class cls) throws IOException, - ClassNotFoundException { - if (!mH2i.getSerializerFactory().getClassLoader().equals(Thread.currentThread().getContextClassLoader())) { - mH2i.setSerializerFactory(hessian2FactoryManager.getSerializerFactory(Thread.currentThread().getContextClassLoader())); + public T readObject(Class cls) throws IOException, ClassNotFoundException { + if (!mH2i.getSerializerFactory() + .getClassLoader() + .equals(Thread.currentThread().getContextClassLoader())) { + mH2i.setSerializerFactory(hessian2FactoryManager.getSerializerFactory( + Thread.currentThread().getContextClassLoader())); } return (T) mH2i.readObject(cls); } @Override public T readObject(Class cls, Type type) throws IOException, ClassNotFoundException { - if (!mH2i.getSerializerFactory().getClassLoader().equals(Thread.currentThread().getContextClassLoader())) { - mH2i.setSerializerFactory(hessian2FactoryManager.getSerializerFactory(Thread.currentThread().getContextClassLoader())); + if (!mH2i.getSerializerFactory() + .getClassLoader() + .equals(Thread.currentThread().getContextClassLoader())) { + mH2i.setSerializerFactory(hessian2FactoryManager.getSerializerFactory( + Thread.currentThread().getContextClassLoader())); } return readObject(cls); } @@ -123,7 +134,7 @@ public class Hessian2ObjectInput implements ObjectInput, Cleanable { @Override public void cleanup() { - if(mH2i != null) { + if (mH2i != null) { mH2i.reset(); } } diff --git a/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ObjectOutput.java b/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ObjectOutput.java index 27c1ebd91d..7468b095f7 100644 --- a/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ObjectOutput.java +++ b/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ObjectOutput.java @@ -20,11 +20,11 @@ import org.apache.dubbo.common.serialize.Cleanable; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.rpc.model.FrameworkModel; -import com.alibaba.com.caucho.hessian.io.Hessian2Output; - import java.io.IOException; import java.io.OutputStream; +import com.alibaba.com.caucho.hessian.io.Hessian2Output; + /** * Hessian2 object output implementation */ @@ -35,13 +35,16 @@ public class Hessian2ObjectOutput implements ObjectOutput, Cleanable { @Deprecated public Hessian2ObjectOutput(OutputStream os) { mH2o = new Hessian2Output(os); - Hessian2FactoryManager hessian2FactoryManager = FrameworkModel.defaultModel().getBeanFactory().getOrRegisterBean(Hessian2FactoryManager.class); - mH2o.setSerializerFactory(hessian2FactoryManager.getSerializerFactory(Thread.currentThread().getContextClassLoader())); + Hessian2FactoryManager hessian2FactoryManager = + FrameworkModel.defaultModel().getBeanFactory().getOrRegisterBean(Hessian2FactoryManager.class); + mH2o.setSerializerFactory(hessian2FactoryManager.getSerializerFactory( + Thread.currentThread().getContextClassLoader())); } public Hessian2ObjectOutput(OutputStream os, Hessian2FactoryManager hessian2FactoryManager) { mH2o = new Hessian2Output(os); - mH2o.setSerializerFactory(hessian2FactoryManager.getSerializerFactory(Thread.currentThread().getContextClassLoader())); + mH2o.setSerializerFactory(hessian2FactoryManager.getSerializerFactory( + Thread.currentThread().getContextClassLoader())); } @Override @@ -110,7 +113,7 @@ public class Hessian2ObjectOutput implements ObjectOutput, Cleanable { @Override public void cleanup() { - if(mH2o != null) { + if (mH2o != null) { mH2o.reset(); } } diff --git a/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ScopeModelInitializer.java b/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ScopeModelInitializer.java index a86b39bdb8..41ee9b5fa9 100644 --- a/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ScopeModelInitializer.java +++ b/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2ScopeModelInitializer.java @@ -32,12 +32,8 @@ public class Hessian2ScopeModelInitializer implements ScopeModelInitializer { } @Override - public void initializeApplicationModel(ApplicationModel applicationModel) { - - } + public void initializeApplicationModel(ApplicationModel applicationModel) {} @Override - public void initializeModuleModel(ModuleModel moduleModel) { - - } + public void initializeModuleModel(ModuleModel moduleModel) {} } diff --git a/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2Serialization.java b/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2Serialization.java index 1156c15513..4263d3de0e 100644 --- a/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2Serialization.java +++ b/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2Serialization.java @@ -51,19 +51,20 @@ public class Hessian2Serialization implements Serialization { @Override public ObjectOutput serialize(URL url, OutputStream out) throws IOException { Hessian2FactoryManager hessian2FactoryManager = Optional.ofNullable(url) - .map(URL::getOrDefaultFrameworkModel) - .orElseGet(FrameworkModel::defaultModel) - .getBeanFactory().getBean(Hessian2FactoryManager.class); + .map(URL::getOrDefaultFrameworkModel) + .orElseGet(FrameworkModel::defaultModel) + .getBeanFactory() + .getBean(Hessian2FactoryManager.class); return new Hessian2ObjectOutput(out, hessian2FactoryManager); } @Override public ObjectInput deserialize(URL url, InputStream is) throws IOException { Hessian2FactoryManager hessian2FactoryManager = Optional.ofNullable(url) - .map(URL::getOrDefaultFrameworkModel) - .orElseGet(FrameworkModel::defaultModel) - .getBeanFactory().getBean(Hessian2FactoryManager.class); + .map(URL::getOrDefaultFrameworkModel) + .orElseGet(FrameworkModel::defaultModel) + .getBeanFactory() + .getBean(Hessian2FactoryManager.class); return new Hessian2ObjectInput(is, hessian2FactoryManager); } - } diff --git a/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2SerializerFactory.java b/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2SerializerFactory.java index b6bf38fbe0..e813894292 100644 --- a/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2SerializerFactory.java +++ b/dubbo-serialization/dubbo-serialization-hessian2/src/main/java/org/apache/dubbo/common/serialize/hessian2/Hessian2SerializerFactory.java @@ -18,20 +18,20 @@ package org.apache.dubbo.common.serialize.hessian2; import org.apache.dubbo.common.utils.DefaultSerializeClassChecker; +import java.io.Serializable; + import com.alibaba.com.caucho.hessian.io.Deserializer; import com.alibaba.com.caucho.hessian.io.JavaDeserializer; import com.alibaba.com.caucho.hessian.io.JavaSerializer; import com.alibaba.com.caucho.hessian.io.Serializer; import com.alibaba.com.caucho.hessian.io.SerializerFactory; -import java.io.Serializable; - public class Hessian2SerializerFactory extends SerializerFactory { private final DefaultSerializeClassChecker defaultSerializeClassChecker; - - public Hessian2SerializerFactory(ClassLoader classLoader, DefaultSerializeClassChecker defaultSerializeClassChecker) { + public Hessian2SerializerFactory( + ClassLoader classLoader, DefaultSerializeClassChecker defaultSerializeClassChecker) { super(classLoader); this.defaultSerializeClassChecker = defaultSerializeClassChecker; } @@ -43,8 +43,7 @@ public class Hessian2SerializerFactory extends SerializerFactory { @Override protected Serializer getDefaultSerializer(Class cl) { - if (_defaultSerializer != null) - return _defaultSerializer; + if (_defaultSerializer != null) return _defaultSerializer; try { // pre-check if class is allow @@ -79,8 +78,9 @@ public class Hessian2SerializerFactory extends SerializerFactory { // If dubbo class checker check serializable => fail // If both hessian and dubbo class checker allow non-serializable => ok if (!Serializable.class.isAssignableFrom(cl) - && (!isAllowNonSerializable() || defaultSerializeClassChecker.isCheckSerializable())) { - throw new IllegalStateException("Serialized class " + cl.getName() + " must implement java.io.Serializable"); + && (!isAllowNonSerializable() || defaultSerializeClassChecker.isCheckSerializable())) { + throw new IllegalStateException( + "Serialized class " + cl.getName() + " must implement java.io.Serializable"); } } } diff --git a/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/serialize/hessian2/Hessian2SerializationTest.java b/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/serialize/hessian2/Hessian2SerializationTest.java index e94f41b350..93dc9d1185 100644 --- a/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/serialize/hessian2/Hessian2SerializationTest.java +++ b/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/serialize/hessian2/Hessian2SerializationTest.java @@ -24,10 +24,6 @@ import org.apache.dubbo.common.utils.SerializeCheckStatus; import org.apache.dubbo.common.utils.SerializeSecurityManager; import org.apache.dubbo.rpc.model.FrameworkModel; -import com.example.test.TestPojo; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -38,11 +34,16 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; +import com.example.test.TestPojo; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class Hessian2SerializationTest { @Test void testReadString() throws IOException { FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write string, read string @@ -129,7 +130,8 @@ class Hessian2SerializationTest { @Test void testReadEvent() throws IOException, ClassNotFoundException { FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write string, read event @@ -203,7 +205,8 @@ class Hessian2SerializationTest { @Test void testReadByte() throws IOException { FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write byte, read byte @@ -277,14 +280,16 @@ class Hessian2SerializationTest { @Test void testReadObject() throws IOException, ClassNotFoundException { FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write pojo, read pojo { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); @@ -298,7 +303,8 @@ class Hessian2SerializationTest { { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); LinkedList pojos = new LinkedList<>(); pojos.add(trustedPojo); @@ -315,7 +321,8 @@ class Hessian2SerializationTest { { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); @@ -329,7 +336,8 @@ class Hessian2SerializationTest { { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); LinkedList pojos = new LinkedList<>(); pojos.add(trustedPojo); @@ -346,7 +354,8 @@ class Hessian2SerializationTest { { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); LinkedList pojos = new LinkedList<>(); pojos.add(trustedPojo); @@ -365,14 +374,16 @@ class Hessian2SerializationTest { @Test void testReadObjectNotMatched() throws IOException, ClassNotFoundException { FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write pojo, read list failed { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); @@ -386,7 +397,8 @@ class Hessian2SerializationTest { { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); @@ -400,7 +412,8 @@ class Hessian2SerializationTest { { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); @@ -414,7 +427,8 @@ class Hessian2SerializationTest { { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); @@ -428,7 +442,8 @@ class Hessian2SerializationTest { { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); @@ -442,7 +457,8 @@ class Hessian2SerializationTest { { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); @@ -456,7 +472,8 @@ class Hessian2SerializationTest { { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); LinkedList pojos = new LinkedList<>(); pojos.add(trustedPojo); @@ -473,7 +490,8 @@ class Hessian2SerializationTest { { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); - TrustedPojo trustedPojo = new TrustedPojo(ThreadLocalRandom.current().nextDouble()); + TrustedPojo trustedPojo = + new TrustedPojo(ThreadLocalRandom.current().nextDouble()); LinkedList pojos = new LinkedList<>(); pojos.add(trustedPojo); @@ -492,7 +510,8 @@ class Hessian2SerializationTest { @Test void testLimit1() throws IOException, ClassNotFoundException { FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write trusted, read trusted @@ -514,8 +533,12 @@ class Hessian2SerializationTest { @Test void testLimit2() throws IOException, ClassNotFoundException { FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); - frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class).setCheckStatus(SerializeCheckStatus.STRICT); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); + frameworkModel + .getBeanFactory() + .getBean(SerializeSecurityManager.class) + .setCheckStatus(SerializeCheckStatus.STRICT); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write untrusted failed @@ -531,11 +554,13 @@ class Hessian2SerializationTest { @Test void testLimit3() throws IOException, ClassNotFoundException { FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); // write un-serializable failed - TrustedNotSerializable trustedPojo = new TrustedNotSerializable(ThreadLocalRandom.current().nextDouble()); + TrustedNotSerializable trustedPojo = + new TrustedNotSerializable(ThreadLocalRandom.current().nextDouble()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput objectOutput = serialization.serialize(url, outputStream); @@ -551,12 +576,16 @@ class Hessian2SerializationTest { { FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); TestPojo trustedPojo = new TestPojo("12345"); - frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class).addToAllowed(trustedPojo.getClass().getName()); + frameworkModel + .getBeanFactory() + .getBean(SerializeSecurityManager.class) + .addToAllowed(trustedPojo.getClass().getName()); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); @@ -566,11 +595,15 @@ class Hessian2SerializationTest { { FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); byte[] bytes = outputStream.toByteArray(); - frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class).setCheckStatus(SerializeCheckStatus.STRICT); + frameworkModel + .getBeanFactory() + .getBean(SerializeSecurityManager.class) + .setCheckStatus(SerializeCheckStatus.STRICT); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); ObjectInput objectInput = serialization.deserialize(url, inputStream); Assertions.assertInstanceOf(Map.class, objectInput.readObject()); @@ -586,12 +619,17 @@ class Hessian2SerializationTest { { System.setProperty("dubbo.hessian.allowNonSerializable", "true"); FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); - TrustedNotSerializable trustedPojo = new TrustedNotSerializable(ThreadLocalRandom.current().nextDouble()); + TrustedNotSerializable trustedPojo = + new TrustedNotSerializable(ThreadLocalRandom.current().nextDouble()); - frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class).setCheckSerializable(false); + frameworkModel + .getBeanFactory() + .getBean(SerializeSecurityManager.class) + .setCheckSerializable(false); ObjectOutput objectOutput = serialization.serialize(url, outputStream); objectOutput.writeObject(trustedPojo); objectOutput.flushBuffer(); @@ -602,7 +640,8 @@ class Hessian2SerializationTest { { FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); byte[] bytes = outputStream.toByteArray(); diff --git a/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/serialize/hessian2/TypeMatchTest.java b/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/serialize/hessian2/TypeMatchTest.java index b155981be7..6fcf10e6da 100644 --- a/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/serialize/hessian2/TypeMatchTest.java +++ b/dubbo-serialization/dubbo-serialization-hessian2/src/test/java/org/apache/dubbo/common/serialize/hessian2/TypeMatchTest.java @@ -22,26 +22,23 @@ import org.apache.dubbo.common.serialize.DataOutput; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.Serialization; -import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.rpc.model.FrameworkModel; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import org.junit.jupiter.params.provider.ArgumentsSource; -import org.junit.jupiter.params.provider.ArgumentsSources; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.stream.Stream; class TypeMatchTest { static class DataProvider implements ArgumentsProvider { @@ -71,24 +68,32 @@ class TypeMatchTest { datas.add("world".getBytes()); for (Method method : ObjectInput.class.getMethods()) { - if (method.getName().startsWith("read") && method.getParameterTypes().length == 0 && !method.getReturnType().equals(Object.class)) { + if (method.getName().startsWith("read") + && method.getParameterTypes().length == 0 + && !method.getReturnType().equals(Object.class)) { readMethods.add(method); } } for (Method method : DataInput.class.getMethods()) { - if (method.getName().startsWith("read") && method.getParameterTypes().length == 0 && !method.getReturnType().equals(Object.class)) { + if (method.getName().startsWith("read") + && method.getParameterTypes().length == 0 + && !method.getReturnType().equals(Object.class)) { readMethods.add(method); } } for (Method method : ObjectOutput.class.getMethods()) { - if (method.getName().startsWith("write") && method.getParameterTypes().length == 1 && !method.getParameterTypes()[0].equals(Object.class)) { + if (method.getName().startsWith("write") + && method.getParameterTypes().length == 1 + && !method.getParameterTypes()[0].equals(Object.class)) { writeMethods.add(method); } } for (Method method : DataOutput.class.getMethods()) { - if (method.getName().startsWith("write") && method.getParameterTypes().length == 1 && !method.getParameterTypes()[0].equals(Object.class)) { + if (method.getName().startsWith("write") + && method.getParameterTypes().length == 1 + && !method.getParameterTypes()[0].equals(Object.class)) { writeMethods.add(method); } } @@ -111,8 +116,9 @@ class TypeMatchTest { if (output.getParameterTypes()[0].isAssignableFrom(data.getClass())) { argumentsList.add(Arguments.arguments(data, input, output)); } - if (primitiveWrapperTypeMap.containsKey(data.getClass()) && - output.getParameterTypes()[0].isAssignableFrom(primitiveWrapperTypeMap.get(data.getClass()))) { + if (primitiveWrapperTypeMap.containsKey(data.getClass()) + && output.getParameterTypes()[0].isAssignableFrom( + primitiveWrapperTypeMap.get(data.getClass()))) { argumentsList.add(Arguments.arguments(data, input, output)); } } @@ -127,7 +133,8 @@ class TypeMatchTest { @ArgumentsSource(DataProvider.class) void test(Object data, Method input, Method output) throws Exception { FrameworkModel frameworkModel = new FrameworkModel(); - Serialization serialization = frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); + Serialization serialization = + frameworkModel.getExtensionLoader(Serialization.class).getExtension("hessian2"); URL url = URL.valueOf("").setScopeModel(frameworkModel); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); diff --git a/dubbo-serialization/dubbo-serialization-jdk/pom.xml b/dubbo-serialization/dubbo-serialization-jdk/pom.xml index 7058dbde4a..3c9fe679dc 100644 --- a/dubbo-serialization/dubbo-serialization-jdk/pom.xml +++ b/dubbo-serialization/dubbo-serialization-jdk/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - org.apache.dubbo - dubbo-serialization - ${revision} - ../pom.xml - - dubbo-serialization-jdk - jar - ${project.artifactId} - The jdk serialization module of dubbo project - - false - - - - org.apache.dubbo - dubbo-serialization-api - ${project.parent.version} - - - com.alibaba - hessian-lite - - - \ No newline at end of file + 4.0.0 + + org.apache.dubbo + dubbo-serialization + ${revision} + ../pom.xml + + dubbo-serialization-jdk + jar + ${project.artifactId} + The jdk serialization module of dubbo project + + false + + + + org.apache.dubbo + dubbo-serialization-api + ${project.parent.version} + + + com.alibaba + hessian-lite + + + diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/CompactedJavaSerialization.java b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/CompactedJavaSerialization.java index 2df9db1aa2..b87e75c006 100644 --- a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/CompactedJavaSerialization.java +++ b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/CompactedJavaSerialization.java @@ -55,5 +55,4 @@ public class CompactedJavaSerialization implements Serialization { public ObjectInput deserialize(URL url, InputStream is) throws IOException { return new JavaObjectInput(is, true); } - } diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/CompactedObjectInputStream.java b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/CompactedObjectInputStream.java index 2eaf7af6ab..045fec3b14 100644 --- a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/CompactedObjectInputStream.java +++ b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/CompactedObjectInputStream.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.common.serialize.java; - import org.apache.dubbo.common.utils.ClassUtils; import java.io.EOFException; diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaObjectInput.java b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaObjectInput.java index b7a32942c7..bbdd02ffaf 100644 --- a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaObjectInput.java +++ b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaObjectInput.java @@ -77,8 +77,7 @@ public class JavaObjectInput extends NativeJavaObjectInput { @Override @SuppressWarnings("unchecked") - public T readObject(Class cls) throws IOException, - ClassNotFoundException { + public T readObject(Class cls) throws IOException, ClassNotFoundException { return (T) readObject(); } @@ -87,5 +86,4 @@ public class JavaObjectInput extends NativeJavaObjectInput { public T readObject(Class cls, Type type) throws IOException, ClassNotFoundException { return (T) readObject(); } - } diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaSerialization.java b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaSerialization.java index 4626ece767..1962ab4123 100644 --- a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaSerialization.java +++ b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/java/JavaSerialization.java @@ -55,9 +55,13 @@ public class JavaSerialization implements Serialization { @Override public ObjectOutput serialize(URL url, OutputStream out) throws IOException { if (warn.compareAndSet(false, true)) { - logger.error(PROTOCOL_UNSAFE_SERIALIZATION, "", "", "Java serialization is unsafe. Dubbo Team do not recommend anyone to use it." + - "If you still want to use it, please follow [JEP 290](https://openjdk.java.net/jeps/290)" + - "to set serialization filter to prevent deserialization leak."); + logger.error( + PROTOCOL_UNSAFE_SERIALIZATION, + "", + "", + "Java serialization is unsafe. Dubbo Team do not recommend anyone to use it." + + "If you still want to use it, please follow [JEP 290](https://openjdk.java.net/jeps/290)" + + "to set serialization filter to prevent deserialization leak."); } return new JavaObjectOutput(out); } @@ -65,11 +69,14 @@ public class JavaSerialization implements Serialization { @Override public ObjectInput deserialize(URL url, InputStream is) throws IOException { if (warn.compareAndSet(false, true)) { - logger.error(PROTOCOL_UNSAFE_SERIALIZATION, "", "", "Java serialization is unsafe. Dubbo Team do not recommend anyone to use it." + - "If you still want to use it, please follow [JEP 290](https://openjdk.java.net/jeps/290)" + - "to set serialization filter to prevent deserialization leak."); + logger.error( + PROTOCOL_UNSAFE_SERIALIZATION, + "", + "", + "Java serialization is unsafe. Dubbo Team do not recommend anyone to use it." + + "If you still want to use it, please follow [JEP 290](https://openjdk.java.net/jeps/290)" + + "to set serialization filter to prevent deserialization leak."); } return new JavaObjectInput(is); } - } diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaObjectInput.java b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaObjectInput.java index c791250f7a..74431832ff 100644 --- a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaObjectInput.java +++ b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaObjectInput.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.serialize.nativejava; import org.apache.dubbo.common.serialize.ObjectInput; @@ -108,7 +107,7 @@ public class NativeJavaObjectInput implements ObjectInput { if (len < 0) { return null; } else if (len == 0) { - return new byte[]{}; + return new byte[] {}; } else { byte[] result = new byte[len]; inputStream.readFully(result); diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaObjectOutput.java b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaObjectOutput.java index 2ff82f76c3..a3274094db 100644 --- a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaObjectOutput.java +++ b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaObjectOutput.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.serialize.nativejava; import org.apache.dubbo.common.serialize.ObjectOutput; diff --git a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaSerialization.java b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaSerialization.java index 2e6e493b91..ea37e998a8 100644 --- a/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaSerialization.java +++ b/dubbo-serialization/dubbo-serialization-jdk/src/main/java/org/apache/dubbo/common/serialize/nativejava/NativeJavaSerialization.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.common.serialize.nativejava; import org.apache.dubbo.common.URL; @@ -57,9 +56,13 @@ public class NativeJavaSerialization implements Serialization { @Override public ObjectOutput serialize(URL url, OutputStream output) throws IOException { if (warn.compareAndSet(false, true)) { - logger.error(PROTOCOL_UNSAFE_SERIALIZATION, "", "", "Java serialization is unsafe. Dubbo Team do not recommend anyone to use it." + - "If you still want to use it, please follow [JEP 290](https://openjdk.java.net/jeps/290)" + - "to set serialization filter to prevent deserialization leak."); + logger.error( + PROTOCOL_UNSAFE_SERIALIZATION, + "", + "", + "Java serialization is unsafe. Dubbo Team do not recommend anyone to use it." + + "If you still want to use it, please follow [JEP 290](https://openjdk.java.net/jeps/290)" + + "to set serialization filter to prevent deserialization leak."); } return new NativeJavaObjectOutput(output); } @@ -67,9 +70,13 @@ public class NativeJavaSerialization implements Serialization { @Override public ObjectInput deserialize(URL url, InputStream input) throws IOException { if (warn.compareAndSet(false, true)) { - logger.error(PROTOCOL_UNSAFE_SERIALIZATION, "", "", "Java serialization is unsafe. Dubbo Team do not recommend anyone to use it." + - "If you still want to use it, please follow [JEP 290](https://openjdk.java.net/jeps/290)" + - "to set serialization filter to prevent deserialization leak."); + logger.error( + PROTOCOL_UNSAFE_SERIALIZATION, + "", + "", + "Java serialization is unsafe. Dubbo Team do not recommend anyone to use it." + + "If you still want to use it, please follow [JEP 290](https://openjdk.java.net/jeps/290)" + + "to set serialization filter to prevent deserialization leak."); } return new NativeJavaObjectInput(input); } diff --git a/dubbo-serialization/pom.xml b/dubbo-serialization/pom.xml index dbfa18c288..0fed5f14fc 100644 --- a/dubbo-serialization/pom.xml +++ b/dubbo-serialization/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - - org.apache.dubbo - dubbo-parent - ${revision} - ../pom.xml - - dubbo-serialization - pom - ${project.artifactId} - The serialization module of dubbo project - - false - - - dubbo-serialization-api - dubbo-serialization-hessian2 - dubbo-serialization-jdk - dubbo-serialization-fastjson2 - + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + + dubbo-serialization + pom + ${project.artifactId} + The serialization module of dubbo project + + dubbo-serialization-api + dubbo-serialization-hessian2 + dubbo-serialization-jdk + dubbo-serialization-fastjson2 + + + false + - - - org.apache.dubbo - dubbo-test-check - ${project.parent.version} - test - - + + + org.apache.dubbo + dubbo-test-check + ${project.parent.version} + test + + diff --git a/dubbo-spring-boot/dubbo-spring-boot-actuator/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-actuator/pom.xml index c9ce0c7c71..b91b00c525 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-actuator/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-actuator/pom.xml @@ -15,122 +15,120 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - org.apache.dubbo - dubbo-spring-boot - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-spring-boot + ${revision} + ../pom.xml + - dubbo-spring-boot-actuator - jar - Apache Dubbo Spring Boot Actuator + dubbo-spring-boot-actuator + jar + Apache Dubbo Spring Boot Actuator - + - - org.apache.dubbo - dubbo-spring-boot-actuator-compatible - ${project.version} - + + org.apache.dubbo + dubbo-spring-boot-actuator-compatible + ${project.version} + - - - org.springframework.boot - spring-boot-starter-web - true - + + + org.springframework.boot + spring-boot-starter-web + true + - - org.springframework.boot - spring-boot-starter-actuator - true - + + org.springframework.boot + spring-boot-starter-actuator + true + - - org.springframework.boot - spring-boot-autoconfigure - true - + + org.springframework.boot + spring-boot-autoconfigure + true + - - - org.apache.dubbo - dubbo-spring-boot-autoconfigure - ${project.version} - + + + org.apache.dubbo + dubbo-spring-boot-autoconfigure + ${project.version} + - - - org.apache.dubbo - dubbo - ${project.version} - + + + org.apache.dubbo + dubbo + ${project.version} + - - org.apache.dubbo - dubbo-common - ${project.version} - true - + + org.apache.dubbo + dubbo-common + ${project.version} + true + - - org.apache.dubbo - dubbo-config-spring - ${project.version} - true - + + org.apache.dubbo + dubbo-config-spring + ${project.version} + true + - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - true - + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + true + - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - true - + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.version} + true + - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${revision} - true - + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${revision} + true + - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - true - + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + true + - - - org.springframework.boot - spring-boot-starter-test - test - + + + org.springframework.boot + spring-boot-starter-test + test + - - org.junit.platform - junit-platform-runner - test - - - org.apache.dubbo - dubbo-metrics-default - ${project.version} - + + org.junit.platform + junit-platform-runner + test + + + org.apache.dubbo + dubbo-metrics-default + ${project.version} + - + diff --git a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAnnotationAutoConfiguration.java b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAnnotationAutoConfiguration.java index c1e66cd654..bad49280ba 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAnnotationAutoConfiguration.java +++ b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAnnotationAutoConfiguration.java @@ -91,5 +91,4 @@ public class DubboEndpointAnnotationAutoConfiguration { public DubboShutdownEndpoint dubboShutdownEndpoint() { return new DubboShutdownEndpoint(); } - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboMetricsAutoConfiguration.java b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboMetricsAutoConfiguration.java index 0543547cd6..88b05d4ef0 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboMetricsAutoConfiguration.java +++ b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboMetricsAutoConfiguration.java @@ -14,11 +14,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.spring.boot.actuate.autoconfigure; -import io.micrometer.core.instrument.MeterRegistry; import org.apache.dubbo.spring.boot.actuate.mertics.DubboMetricsBinder; + +import io.micrometer.core.instrument.MeterRegistry; import org.springframework.boot.actuate.autoconfigure.metrics.CompositeMeterRegistryAutoConfiguration; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; @@ -27,10 +27,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplicat import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; - -@Configuration( - proxyBeanMethods = false -) +@Configuration(proxyBeanMethods = false) @ConditionalOnWebApplication @AutoConfigureAfter(CompositeMeterRegistryAutoConfiguration.class) public class DubboMetricsAutoConfiguration { diff --git a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboConfigsMetadataEndpoint.java b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboConfigsMetadataEndpoint.java index 77b1e2080c..70fff635dc 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboConfigsMetadataEndpoint.java +++ b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboConfigsMetadataEndpoint.java @@ -19,12 +19,12 @@ package org.apache.dubbo.spring.boot.actuate.endpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.AbstractDubboMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboConfigsMetadata; +import java.util.Map; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; -import java.util.Map; - /** * Dubbo Configs Metadata {@link Endpoint} * diff --git a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboMetadataEndpoint.java b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboMetadataEndpoint.java index fb35b7f08f..3eb816d17a 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboMetadataEndpoint.java +++ b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboMetadataEndpoint.java @@ -18,12 +18,12 @@ package org.apache.dubbo.spring.boot.actuate.endpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboMetadata; +import java.util.Map; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; -import java.util.Map; - /** * Actuator {@link Endpoint} to expose Dubbo Meta Data * @@ -40,5 +40,4 @@ public class DubboMetadataEndpoint { public Map invoke() { return dubboMetadata.invoke(); } - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboPropertiesMetadataEndpoint.java b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboPropertiesMetadataEndpoint.java index 8105e33011..d14207c174 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboPropertiesMetadataEndpoint.java +++ b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboPropertiesMetadataEndpoint.java @@ -19,12 +19,12 @@ package org.apache.dubbo.spring.boot.actuate.endpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.AbstractDubboMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboPropertiesMetadata; +import java.util.SortedMap; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; -import java.util.SortedMap; - /** * Dubbo Properties {@link Endpoint} * diff --git a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboReferencesMetadataEndpoint.java b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboReferencesMetadataEndpoint.java index f2497da3f3..77abd35f46 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboReferencesMetadataEndpoint.java +++ b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboReferencesMetadataEndpoint.java @@ -20,12 +20,12 @@ import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.AbstractDubboMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboReferencesMetadata; +import java.util.Map; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; -import java.util.Map; - /** * {@link DubboReference} Metadata {@link Endpoint} * diff --git a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboServicesMetadataEndpoint.java b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboServicesMetadataEndpoint.java index 845dbc1f3f..5ee1b41d22 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboServicesMetadataEndpoint.java +++ b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboServicesMetadataEndpoint.java @@ -20,12 +20,12 @@ import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.AbstractDubboMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboServicesMetadata; +import java.util.Map; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; -import java.util.Map; - /** * {@link DubboService} Metadata {@link Endpoint} * diff --git a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboShutdownEndpoint.java b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboShutdownEndpoint.java index 9565e84979..4b1a8f5ed5 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboShutdownEndpoint.java +++ b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboShutdownEndpoint.java @@ -19,12 +19,12 @@ package org.apache.dubbo.spring.boot.actuate.endpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.AbstractDubboMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboShutdownMetadata; +import java.util.Map; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.WriteOperation; -import java.util.Map; - /** * Dubbo Shutdown * @@ -40,5 +40,4 @@ public class DubboShutdownEndpoint extends AbstractDubboMetadata { public Map shutdown() throws Exception { return dubboShutdownMetadata.shutdown(); } - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/condition/CompatibleConditionalOnEnabledEndpoint.java b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/condition/CompatibleConditionalOnEnabledEndpoint.java index 3c1bc1e1cb..5d8078fa32 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/condition/CompatibleConditionalOnEnabledEndpoint.java +++ b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/condition/CompatibleConditionalOnEnabledEndpoint.java @@ -16,16 +16,16 @@ */ package org.apache.dubbo.spring.boot.actuate.endpoint.condition; -import org.springframework.boot.actuate.endpoint.annotation.Endpoint; -import org.springframework.boot.actuate.endpoint.annotation.EndpointExtension; -import org.springframework.context.annotation.Conditional; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.springframework.boot.actuate.endpoint.annotation.Endpoint; +import org.springframework.boot.actuate.endpoint.annotation.EndpointExtension; +import org.springframework.context.annotation.Conditional; + /** * {@link Conditional} that checks whether or not an endpoint is enabled, which is compatible with * org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint ([2.0.x, 2.2.x]) diff --git a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/condition/CompatibleOnEnabledEndpointCondition.java b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/condition/CompatibleOnEnabledEndpointCondition.java index 0c76ea7605..d5308c5680 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/condition/CompatibleOnEnabledEndpointCondition.java +++ b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/condition/CompatibleOnEnabledEndpointCondition.java @@ -38,16 +38,16 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_CLASS */ class CompatibleOnEnabledEndpointCondition implements Condition { - private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(CompatibleOnEnabledEndpointCondition.class); + private static final ErrorTypeAwareLogger LOGGER = + LoggerFactory.getErrorTypeAwareLogger(CompatibleOnEnabledEndpointCondition.class); // Spring Boot [2.0.0 , 2.2.x] static String CONDITION_CLASS_NAME_OLD = - "org.springframework.boot.actuate.autoconfigure.endpoint.condition.OnEnabledEndpointCondition"; + "org.springframework.boot.actuate.autoconfigure.endpoint.condition.OnEnabledEndpointCondition"; // Spring Boot 2.2.0 + static String CONDITION_CLASS_NAME_NEW = - "org.springframework.boot.actuate.autoconfigure.endpoint.condition.OnAvailableEndpointCondition"; - + "org.springframework.boot.actuate.autoconfigure.endpoint.condition.OnAvailableEndpointCondition"; @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { @@ -64,7 +64,11 @@ class CompatibleOnEnabledEndpointCondition implements Condition { return true; } // No condition class found - LOGGER.warn(COMMON_CLASS_NOT_FOUND, "No condition class found", "", String.format("No condition class found, Dubbo Health Endpoint [%s] will not expose", metadata)); + LOGGER.warn( + COMMON_CLASS_NOT_FOUND, + "No condition class found", + "", + String.format("No condition class found, Dubbo Health Endpoint [%s] will not expose", metadata)); return false; } } diff --git a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/mertics/DubboMetricsBinder.java b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/mertics/DubboMetricsBinder.java index dbb8ce349c..85f5c27ce4 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/mertics/DubboMetricsBinder.java +++ b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/mertics/DubboMetricsBinder.java @@ -14,33 +14,32 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.spring.boot.actuate.mertics; +import org.apache.dubbo.metrics.MetricsGlobalRegistry; + import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.composite.CompositeMeterRegistry; -import org.apache.dubbo.metrics.MetricsGlobalRegistry; import org.springframework.beans.factory.DisposableBean; import org.springframework.boot.context.event.ApplicationStartedEvent; import org.springframework.context.ApplicationListener; - public class DubboMetricsBinder implements ApplicationListener, DisposableBean { private final MeterRegistry meterRegistry; + public DubboMetricsBinder(MeterRegistry meterRegistry) { this.meterRegistry = meterRegistry; } + @Override public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) { if (meterRegistry instanceof CompositeMeterRegistry) { MetricsGlobalRegistry.setCompositeRegistry((CompositeMeterRegistry) meterRegistry); - }else{ + } else { MetricsGlobalRegistry.getCompositeRegistry().add(meterRegistry); } } @Override - public void destroy() { - - } + public void destroy() {} } diff --git a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/test/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAnnotationAutoConfigurationTest.java b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/test/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAnnotationAutoConfigurationTest.java index e90122fbe8..1999808e7b 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/test/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAnnotationAutoConfigurationTest.java +++ b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/test/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAnnotationAutoConfigurationTest.java @@ -27,6 +27,10 @@ import org.apache.dubbo.spring.boot.actuate.endpoint.DubboReferencesMetadataEndp import org.apache.dubbo.spring.boot.actuate.endpoint.DubboServicesMetadataEndpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.DubboShutdownEndpoint; +import java.util.Map; +import java.util.SortedMap; +import java.util.function.Supplier; + import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Assert; @@ -43,10 +47,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.web.client.RestTemplate; -import java.util.Map; -import java.util.SortedMap; -import java.util.function.Supplier; - /** * {@link DubboEndpointAnnotationAutoConfiguration} Test * @@ -55,31 +55,31 @@ import java.util.function.Supplier; @ExtendWith(SpringExtension.class) @SpringBootTest( classes = { - DubboEndpointAnnotationAutoConfigurationTest.class, - DubboEndpointAnnotationAutoConfigurationTest.ConsumerConfiguration.class + DubboEndpointAnnotationAutoConfigurationTest.class, + DubboEndpointAnnotationAutoConfigurationTest.ConsumerConfiguration.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { - "dubbo.service.version = 1.0.0", - "dubbo.application.id = my-application", - "dubbo.application.name = dubbo-demo-application", - "dubbo.module.id = my-module", - "dubbo.module.name = dubbo-demo-module", - "dubbo.registry.id = my-registry", - "dubbo.registry.address = N/A", - "dubbo.protocol.id=my-protocol", - "dubbo.protocol.name=dubbo", - "dubbo.protocol.port=20880", - "dubbo.provider.id=my-provider", - "dubbo.provider.host=127.0.0.1", - "dubbo.scan.basePackages = org.apache.dubbo.spring.boot.actuate.autoconfigure", - "management.endpoint.dubbo.enabled = true", - "management.endpoint.dubboshutdown.enabled = true", - "management.endpoint.dubboconfigs.enabled = true", - "management.endpoint.dubboservices.enabled = true", - "management.endpoint.dubboreferences.enabled = true", - "management.endpoint.dubboproperties.enabled = true", - "management.endpoints.web.exposure.include = *", + "dubbo.service.version = 1.0.0", + "dubbo.application.id = my-application", + "dubbo.application.name = dubbo-demo-application", + "dubbo.module.id = my-module", + "dubbo.module.name = dubbo-demo-module", + "dubbo.registry.id = my-registry", + "dubbo.registry.address = N/A", + "dubbo.protocol.id=my-protocol", + "dubbo.protocol.name=dubbo", + "dubbo.protocol.port=20880", + "dubbo.provider.id=my-provider", + "dubbo.provider.host=127.0.0.1", + "dubbo.scan.basePackages = org.apache.dubbo.spring.boot.actuate.autoconfigure", + "management.endpoint.dubbo.enabled = true", + "management.endpoint.dubboshutdown.enabled = true", + "management.endpoint.dubboconfigs.enabled = true", + "management.endpoint.dubboservices.enabled = true", + "management.endpoint.dubboreferences.enabled = true", + "management.endpoint.dubboproperties.enabled = true", + "management.endpoints.web.exposure.include = *", }) @EnableAutoConfiguration @Disabled @@ -132,7 +132,6 @@ class DubboEndpointAnnotationAutoConfigurationTest { Assert.assertEquals(1, shutdownCounts.get("protocols")); Assert.assertEquals(1, shutdownCounts.get("services")); Assert.assertEquals(0, shutdownCounts.get("references")); - } @Test @@ -141,7 +140,8 @@ class DubboEndpointAnnotationAutoConfigurationTest { Map>> configsMap = dubboConfigsMetadataEndpoint.configs(); Map> beansMetadata = configsMap.get("ApplicationConfig"); - Assert.assertEquals("dubbo-demo-application", beansMetadata.get("my-application").get("name")); + Assert.assertEquals( + "dubbo-demo-application", beansMetadata.get("my-application").get("name")); beansMetadata = configsMap.get("ConsumerConfig"); Assert.assertTrue(beansMetadata.isEmpty()); @@ -169,7 +169,6 @@ class DubboEndpointAnnotationAutoConfigurationTest { beansMetadata = configsMap.get("ServiceConfig"); Assert.assertFalse(beansMetadata.isEmpty()); - } @Test @@ -179,10 +178,10 @@ class DubboEndpointAnnotationAutoConfigurationTest { Assert.assertEquals(1, services.size()); - Map demoServiceMeta = services.get("ServiceBean:org.apache.dubbo.spring.boot.actuate.autoconfigure.DubboEndpointAnnotationAutoConfigurationTest$DemoService:1.0.0:"); + Map demoServiceMeta = services.get( + "ServiceBean:org.apache.dubbo.spring.boot.actuate.autoconfigure.DubboEndpointAnnotationAutoConfigurationTest$DemoService:1.0.0:"); Assert.assertEquals("1.0.0", demoServiceMeta.get("version")); - } @Test @@ -191,11 +190,16 @@ class DubboEndpointAnnotationAutoConfigurationTest { Map> references = dubboReferencesMetadataEndpoint.references(); Assert.assertTrue(!references.isEmpty()); - String injectedField = "private " + DemoService.class.getName() + " " + ConsumerConfiguration.class.getName() + ".demoService"; + String injectedField = + "private " + DemoService.class.getName() + " " + ConsumerConfiguration.class.getName() + ".demoService"; Map referenceMap = references.get(injectedField); Assert.assertNotNull(referenceMap); Assert.assertEquals(DemoService.class, referenceMap.get("interfaceClass")); - Assert.assertEquals(BaseServiceMetadata.buildServiceKey(DemoService.class.getName(),ConsumerConfiguration.DEMO_GROUP,ConsumerConfiguration.DEMO_VERSION), + Assert.assertEquals( + BaseServiceMetadata.buildServiceKey( + DemoService.class.getName(), + ConsumerConfiguration.DEMO_GROUP, + ConsumerConfiguration.DEMO_VERSION), referenceMap.get("uniqueServiceName")); } @@ -215,12 +219,13 @@ class DubboEndpointAnnotationAutoConfigurationTest { Assert.assertEquals("20880", properties.get("dubbo.protocol.port")); Assert.assertEquals("my-provider", properties.get("dubbo.provider.id")); Assert.assertEquals("127.0.0.1", properties.get("dubbo.provider.host")); - Assert.assertEquals("org.apache.dubbo.spring.boot.actuate.autoconfigure", properties.get("dubbo.scan.basePackages")); + Assert.assertEquals( + "org.apache.dubbo.spring.boot.actuate.autoconfigure", properties.get("dubbo.scan.basePackages")); } @Test void testHttpEndpoints() throws JsonProcessingException { -// testHttpEndpoint("/dubbo", dubboEndpoint::invoke); + // testHttpEndpoint("/dubbo", dubboEndpoint::invoke); testHttpEndpoint("/dubbo/configs", dubboConfigsMetadataEndpoint::configs); testHttpEndpoint("/dubbo/services", dubboServicesMetadataEndpoint::services); testHttpEndpoint("/dubbo/references", dubboReferencesMetadataEndpoint::references); @@ -233,7 +238,6 @@ class DubboEndpointAnnotationAutoConfigurationTest { Assert.assertEquals(objectMapper.writeValueAsString(resultsSupplier.get()), response); } - interface DemoService { String sayHello(String name); } @@ -242,14 +246,12 @@ class DubboEndpointAnnotationAutoConfigurationTest { version = "${dubbo.service.version}", application = "${dubbo.application.id}", protocol = "${dubbo.protocol.id}", - registry = "${dubbo.registry.id}" - ) + registry = "${dubbo.registry.id}") static class DefaultDemoService implements DemoService { public String sayHello(String name) { return "Hello, " + name + " (from Spring Boot)"; } - } @Configuration @@ -259,6 +261,5 @@ class DubboEndpointAnnotationAutoConfigurationTest { @DubboReference(group = DEMO_GROUP, version = DEMO_VERSION) private DemoService demoService; - } -} \ No newline at end of file +} diff --git a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/test/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboEndpointTest.java b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/test/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboEndpointTest.java index 87dfb6333b..0aea4fc7a8 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-actuator/src/test/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboEndpointTest.java +++ b/dubbo-spring-boot/dubbo-spring-boot-actuator/src/test/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboEndpointTest.java @@ -19,6 +19,8 @@ package org.apache.dubbo.spring.boot.actuate.endpoint; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.spring.boot.util.DubboUtils; +import java.util.Map; + import org.junit.Assert; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -29,8 +31,6 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.util.Map; - import static org.apache.dubbo.common.Version.getVersion; /** @@ -41,17 +41,11 @@ import static org.apache.dubbo.common.Version.getVersion; */ @ExtendWith(SpringExtension.class) @SpringBootTest( - classes = { - DubboMetadataEndpoint.class - }, - properties = { - "dubbo.application.name = dubbo-demo-application" - } -) + classes = {DubboMetadataEndpoint.class}, + properties = {"dubbo.application.name = dubbo-demo-application"}) @EnableAutoConfiguration class DubboEndpointTest { - @Autowired private DubboMetadataEndpoint dubboEndpoint; @@ -86,8 +80,5 @@ class DubboEndpointTest { Assert.assertEquals("https://github.com/apache/dubbo-spring-boot-project", urls.get("github")); Assert.assertEquals("https://github.com/apache/dubbo-spring-boot-project/issues", urls.get("issues")); Assert.assertEquals("https://github.com/apache/dubbo-spring-boot-project.git", urls.get("git")); - } - - -} \ No newline at end of file +} diff --git a/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/pom.xml index 741a05be1d..50d0c17537 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/pom.xml @@ -15,70 +15,68 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - org.apache.dubbo - dubbo-spring-boot - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-spring-boot + ${revision} + ../pom.xml + - dubbo-spring-boot-autoconfigure - jar - Apache Dubbo Spring Boot Auto-Configure + dubbo-spring-boot-autoconfigure + jar + Apache Dubbo Spring Boot Auto-Configure - + - - - org.apache.dubbo - dubbo-spring-boot-autoconfigure-compatible - ${project.version} - + + + org.apache.dubbo + dubbo-spring-boot-autoconfigure-compatible + ${project.version} + - - - org.springframework.boot - spring-boot-autoconfigure - true - + + + org.springframework.boot + spring-boot-autoconfigure + true + - - org.springframework.boot - spring-boot-starter-logging - true - + + org.springframework.boot + spring-boot-starter-logging + true + - - - org.apache.dubbo - dubbo - ${project.version} - + + + org.apache.dubbo + dubbo + ${project.version} + - - org.apache.dubbo - dubbo-common - ${project.version} - true - + + org.apache.dubbo + dubbo-common + ${project.version} + true + - - org.apache.dubbo - dubbo-config-spring - ${project.version} - true - + + org.apache.dubbo + dubbo-config-spring + ${project.version} + true + - - - org.springframework.boot - spring-boot-starter-test - test - + + + org.springframework.boot + spring-boot-starter-test + test + - + diff --git a/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/BinderDubboConfigBinder.java b/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/BinderDubboConfigBinder.java index 3da5f0b410..361c549935 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/BinderDubboConfigBinder.java +++ b/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/BinderDubboConfigBinder.java @@ -18,6 +18,8 @@ package org.apache.dubbo.spring.boot.autoconfigure; import org.apache.dubbo.config.spring.context.properties.DubboConfigBinder; +import java.util.Map; + import com.alibaba.spring.context.config.ConfigurationBeanBinder; import org.springframework.boot.context.properties.bind.BindHandler; import org.springframework.boot.context.properties.bind.Bindable; @@ -30,8 +32,6 @@ import org.springframework.boot.context.properties.source.UnboundElementsSourceF import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.PropertySource; -import java.util.Map; - import static java.util.Arrays.asList; import static org.springframework.boot.context.properties.source.ConfigurationPropertySources.from; @@ -44,10 +44,14 @@ import static org.springframework.boot.context.properties.source.ConfigurationPr class BinderDubboConfigBinder implements ConfigurationBeanBinder { @Override - public void bind(Map configurationProperties, boolean ignoreUnknownFields, - boolean ignoreInvalidFields, Object configurationBean) { + public void bind( + Map configurationProperties, + boolean ignoreUnknownFields, + boolean ignoreInvalidFields, + Object configurationBean) { - Iterable> propertySources = asList(new MapPropertySource("internal", configurationProperties)); + Iterable> propertySources = + asList(new MapPropertySource("internal", configurationProperties)); // Converts ConfigurationPropertySources Iterable configurationPropertySources = from(propertySources); @@ -55,7 +59,8 @@ class BinderDubboConfigBinder implements ConfigurationBeanBinder { // Wrap Bindable from DubboConfig instance Bindable bindable = Bindable.ofInstance(configurationBean); - Binder binder = new Binder(configurationPropertySources, new PropertySourcesPlaceholdersResolver(propertySources)); + Binder binder = + new Binder(configurationPropertySources, new PropertySourcesPlaceholdersResolver(propertySources)); // Get BindHandler BindHandler bindHandler = getBindHandler(ignoreUnknownFields, ignoreInvalidFields); @@ -64,8 +69,7 @@ class BinderDubboConfigBinder implements ConfigurationBeanBinder { binder.bind("", bindable, bindHandler); } - private BindHandler getBindHandler(boolean ignoreUnknownFields, - boolean ignoreInvalidFields) { + private BindHandler getBindHandler(boolean ignoreUnknownFields, boolean ignoreInvalidFields) { BindHandler handler = BindHandler.DEFAULT; if (ignoreInvalidFields) { handler = new IgnoreErrorsBindHandler(handler); diff --git a/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboRelaxedBinding2AutoConfiguration.java b/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboRelaxedBinding2AutoConfiguration.java index 8e3454937f..8883a94464 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboRelaxedBinding2AutoConfiguration.java +++ b/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboRelaxedBinding2AutoConfiguration.java @@ -18,6 +18,9 @@ package org.apache.dubbo.spring.boot.autoconfigure; import org.apache.dubbo.config.spring.util.PropertySourcesUtils; +import java.util.Map; +import java.util.Set; + import com.alibaba.spring.context.config.ConfigurationBeanBinder; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -34,9 +37,6 @@ import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertyResolver; -import java.util.Map; -import java.util.Set; - import static java.util.Collections.emptySet; import static org.apache.dubbo.spring.boot.util.DubboUtils.BASE_PACKAGES_BEAN_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.BASE_PACKAGES_PROPERTY_NAME; @@ -61,7 +61,8 @@ public class DubboRelaxedBinding2AutoConfiguration { ConfigurableEnvironment propertyResolver = new AbstractEnvironment() { @Override protected void customizePropertySources(MutablePropertySources propertySources) { - Map dubboScanProperties = PropertySourcesUtils.getSubProperties(environment.getPropertySources(), DUBBO_SCAN_PREFIX); + Map dubboScanProperties = + PropertySourcesUtils.getSubProperties(environment.getPropertySources(), DUBBO_SCAN_PREFIX); propertySources.addLast(new MapPropertySource("dubboScanProperties", dubboScanProperties)); } }; @@ -89,5 +90,4 @@ public class DubboRelaxedBinding2AutoConfiguration { public ConfigurationBeanBinder relaxedDubboConfigBinder() { return new BinderDubboConfigBinder(); } - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/BinderDubboConfigBinderTest.java b/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/BinderDubboConfigBinderTest.java index 807a0c4906..f9132ef689 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/BinderDubboConfigBinderTest.java +++ b/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/BinderDubboConfigBinderTest.java @@ -20,6 +20,8 @@ import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.RegistryConfig; +import java.util.Map; + import com.alibaba.spring.context.config.ConfigurationBeanBinder; import org.junit.Assert; import org.junit.Test; @@ -30,8 +32,6 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; -import java.util.Map; - import static com.alibaba.spring.util.PropertySourcesUtils.getSubProperties; /** @@ -69,4 +69,4 @@ class BinderDubboConfigBinderTest { dubboConfigBinder.bind(properties, true, true, protocolConfig); Assert.assertEquals(Integer.valueOf(20881), protocolConfig.getPort()); } -} \ No newline at end of file +} diff --git a/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/DubboRelaxedBinding2AutoConfigurationTest.java b/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/DubboRelaxedBinding2AutoConfigurationTest.java index df418da731..15995be3ad 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/DubboRelaxedBinding2AutoConfigurationTest.java +++ b/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/DubboRelaxedBinding2AutoConfigurationTest.java @@ -20,6 +20,9 @@ import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotati import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor; import org.apache.dubbo.config.spring.util.DubboBeanUtils; +import java.util.Map; +import java.util.Set; + import com.alibaba.spring.context.config.ConfigurationBeanBinder; import org.junit.Test; import org.junit.runner.RunWith; @@ -34,9 +37,6 @@ import org.springframework.core.env.Environment; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.ClassUtils; -import java.util.Map; -import java.util.Set; - import static org.apache.dubbo.spring.boot.util.DubboUtils.BASE_PACKAGES_BEAN_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME; import static org.junit.Assert.assertEquals; @@ -47,9 +47,9 @@ import static org.junit.Assert.assertTrue; * {@link DubboRelaxedBinding2AutoConfiguration} Test */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = DubboRelaxedBinding2AutoConfigurationTest.class, properties = { - "dubbo.scan.basePackages = org.apache.dubbo.spring.boot.autoconfigure" -}) +@SpringBootTest( + classes = DubboRelaxedBinding2AutoConfigurationTest.class, + properties = {"dubbo.scan.basePackages = org.apache.dubbo.spring.boot.autoconfigure"}) @EnableAutoConfiguration @PropertySource(value = "classpath:/dubbo.properties") class DubboRelaxedBinding2AutoConfigurationTest { @@ -77,22 +77,20 @@ class DubboRelaxedBinding2AutoConfigurationTest { @Test void testBeans() { - assertTrue(ClassUtils.isAssignableValue(BinderDubboConfigBinder.class, dubboConfigBinder)); assertNotNull(serviceAnnotationPostProcessor); assertNotNull(serviceAnnotationPostProcessor.getIfAvailable()); - ReferenceAnnotationBeanPostProcessor referenceAnnotationBeanPostProcessor = DubboBeanUtils.getReferenceAnnotationBeanPostProcessor(applicationContext); + ReferenceAnnotationBeanPostProcessor referenceAnnotationBeanPostProcessor = + DubboBeanUtils.getReferenceAnnotationBeanPostProcessor(applicationContext); assertNotNull(referenceAnnotationBeanPostProcessor); assertNotNull(environment); assertNotNull(environments); - assertEquals(1, environments.size()); assertTrue(environments.containsValue(environment)); } - -} \ No newline at end of file +} diff --git a/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/env/DubboDefaultPropertiesEnvironmentPostProcessorTest.java b/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/env/DubboDefaultPropertiesEnvironmentPostProcessorTest.java index 3adb6f17e3..cb9963777d 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/env/DubboDefaultPropertiesEnvironmentPostProcessorTest.java +++ b/dubbo-spring-boot/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/env/DubboDefaultPropertiesEnvironmentPostProcessorTest.java @@ -16,6 +16,8 @@ */ package org.apache.dubbo.spring.boot.env; +import java.util.HashMap; + import org.junit.Assert; import org.junit.Test; import org.springframework.boot.SpringApplication; @@ -25,8 +27,6 @@ import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource; import org.springframework.mock.env.MockEnvironment; -import java.util.HashMap; - /** * {@link DubboDefaultPropertiesEnvironmentPostProcessor} Test */ @@ -94,4 +94,4 @@ class DubboDefaultPropertiesEnvironmentPostProcessorTest { Assert.assertEquals("false", environment.getProperty("dubbo.config.multiple")); Assert.assertEquals("false", environment.getProperty("dubbo.application.qos-enable")); } -} \ No newline at end of file +} diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/pom.xml index 31748f6283..5261f51979 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/pom.xml @@ -15,93 +15,91 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - org.apache.dubbo - dubbo-spring-boot-compatible - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-spring-boot-compatible + ${revision} + ../pom.xml + - dubbo-spring-boot-actuator-compatible - Apache Dubbo Spring Boot Compatible for Spring Boot 1.x Actuator + dubbo-spring-boot-actuator-compatible + Apache Dubbo Spring Boot Compatible for Spring Boot 1.x Actuator - + - - org.springframework.boot - spring-boot-starter-web - true - + + org.springframework.boot + spring-boot-starter-web + true + - - org.apache.tomcat.embed - tomcat-embed-core - true - + + org.apache.tomcat.embed + tomcat-embed-core + true + - - org.springframework.boot - spring-boot-starter-actuator - true - + + org.springframework.boot + spring-boot-starter-actuator + true + - - org.springframework.boot - spring-boot-autoconfigure - true - + + org.springframework.boot + spring-boot-autoconfigure + true + - - - org.springframework.boot - spring-boot-configuration-processor - true - + + + org.springframework.boot + spring-boot-configuration-processor + true + - - - org.apache.dubbo - dubbo-spring-boot-autoconfigure-compatible - ${project.version} - + + + org.apache.dubbo + dubbo-spring-boot-autoconfigure-compatible + ${project.version} + - - org.apache.dubbo - dubbo - ${project.version} - + + org.apache.dubbo + dubbo + ${project.version} + - - org.apache.dubbo - dubbo-common - ${project.version} - true - + + org.apache.dubbo + dubbo-common + ${project.version} + true + - - org.apache.dubbo - dubbo-config-spring - ${project.version} - true - + + org.apache.dubbo + dubbo-config-spring + ${project.version} + true + - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - test - + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + test + - - - org.springframework.boot - spring-boot-starter-test - test - + + + org.springframework.boot + spring-boot-starter-test + test + - + diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAutoConfiguration.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAutoConfiguration.java index 92a9ba0aa9..0357b000bb 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAutoConfiguration.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAutoConfiguration.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.spring.boot.actuate.autoconfigure; - import org.apache.dubbo.spring.boot.actuate.endpoint.DubboEndpoint; import org.apache.dubbo.spring.boot.autoconfigure.DubboAutoConfiguration; import org.apache.dubbo.spring.boot.autoconfigure.DubboRelaxedBindingAutoConfiguration; @@ -36,13 +35,10 @@ import org.springframework.context.annotation.Configuration; * @since 2.7.0 */ @Configuration -@ConditionalOnClass(name = { - "org.springframework.boot.actuate.endpoint.Endpoint" // Spring Boot 1.x -}) -@AutoConfigureAfter(value = { - DubboAutoConfiguration.class, - DubboRelaxedBindingAutoConfiguration.class -}) +@ConditionalOnClass( + name = {"org.springframework.boot.actuate.endpoint.Endpoint" // Spring Boot 1.x + }) +@AutoConfigureAfter(value = {DubboAutoConfiguration.class, DubboRelaxedBindingAutoConfiguration.class}) @EnableConfigurationProperties(DubboEndpoint.class) public class DubboEndpointAutoConfiguration { diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointMetadataAutoConfiguration.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointMetadataAutoConfiguration.java index fa754d6a32..32c0bd003d 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointMetadataAutoConfiguration.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointMetadataAutoConfiguration.java @@ -26,14 +26,14 @@ import org.springframework.context.annotation.Configuration; /** * Dubbo Endpoints Metadata Auto-{@link Configuration} */ -@ConditionalOnClass(name = { - "org.springframework.boot.actuate.health.Health" // If spring-boot-actuator is present -}) +@ConditionalOnClass( + name = {"org.springframework.boot.actuate.health.Health" // If spring-boot-actuator is present + }) @Configuration -@AutoConfigureAfter(name = { - "org.apache.dubbo.spring.boot.autoconfigure.DubboAutoConfiguration", - "org.apache.dubbo.spring.boot.autoconfigure.DubboRelaxedBindingAutoConfiguration" -}) +@AutoConfigureAfter( + name = { + "org.apache.dubbo.spring.boot.autoconfigure.DubboAutoConfiguration", + "org.apache.dubbo.spring.boot.autoconfigure.DubboRelaxedBindingAutoConfiguration" + }) @ComponentScan(basePackageClasses = AbstractDubboMetadata.class) -public class DubboEndpointMetadataAutoConfiguration { -} +public class DubboEndpointMetadataAutoConfiguration {} diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboHealthIndicatorAutoConfiguration.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboHealthIndicatorAutoConfiguration.java index c5bcd792c9..ed02987552 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboHealthIndicatorAutoConfiguration.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboHealthIndicatorAutoConfiguration.java @@ -34,9 +34,7 @@ import org.springframework.context.annotation.Configuration; * @since 2.7.0 */ @Configuration -@ConditionalOnClass(name = { - "org.springframework.boot.actuate.health.Health" -}) +@ConditionalOnClass(name = {"org.springframework.boot.actuate.health.Health"}) @ConditionalOnProperty(name = "management.health.dubbo.enabled", matchIfMissing = true, havingValue = "true") @EnableConfigurationProperties(DubboHealthIndicatorProperties.class) public class DubboHealthIndicatorAutoConfiguration { @@ -46,5 +44,4 @@ public class DubboHealthIndicatorAutoConfiguration { public DubboHealthIndicator dubboHealthIndicator() { return new DubboHealthIndicator(); } - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboMvcEndpointManagementContextConfiguration.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboMvcEndpointManagementContextConfiguration.java index b3cdabdc43..e879d09a3c 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboMvcEndpointManagementContextConfiguration.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboMvcEndpointManagementContextConfiguration.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.spring.boot.actuate.autoconfigure; - import org.apache.dubbo.spring.boot.actuate.endpoint.DubboEndpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.mvc.DubboMvcEndpoint; @@ -34,9 +33,7 @@ import org.springframework.context.annotation.Bean; * @since 2.7.0 */ @ManagementContextConfiguration -@ConditionalOnClass(name = { - "org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter" -}) +@ConditionalOnClass(name = {"org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter"}) @ConditionalOnWebApplication public class DubboMvcEndpointManagementContextConfiguration { diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboEndpoint.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboEndpoint.java index 375902d5ff..5d9f0267bb 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboEndpoint.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboEndpoint.java @@ -16,16 +16,15 @@ */ package org.apache.dubbo.spring.boot.actuate.endpoint; - import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboMetadata; +import java.util.Map; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.AbstractEndpoint; import org.springframework.boot.actuate.endpoint.Endpoint; import org.springframework.boot.context.properties.ConfigurationProperties; -import java.util.Map; - /** * Actuator {@link Endpoint} to expose Dubbo Meta Data * diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/AbstractDubboMetadata.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/AbstractDubboMetadata.java index 5154d27c42..5a3f332dd6 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/AbstractDubboMetadata.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/AbstractDubboMetadata.java @@ -21,13 +21,6 @@ import org.apache.dubbo.config.spring.ServiceBean; import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor; import org.apache.dubbo.config.spring.util.DubboBeanUtils; -import org.springframework.beans.BeansException; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.context.EnvironmentAware; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.Environment; - import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; @@ -39,6 +32,13 @@ import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.EnvironmentAware; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.Environment; + import static org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors; import static org.springframework.util.ClassUtils.isPrimitiveOrWrapper; @@ -60,8 +60,7 @@ public abstract class AbstractDubboMetadata implements ApplicationContextAware, || type == BigInteger.class || type == Date.class || type == URL.class - || type == Class.class - ; + || type == Class.class; } @Override @@ -97,7 +96,6 @@ public abstract class AbstractDubboMetadata implements ApplicationContextAware, beanMetadata.put(name, value); } } - } } catch (Exception e) { @@ -105,7 +103,6 @@ public abstract class AbstractDubboMetadata implements ApplicationContextAware, } return beanMetadata; - } protected Map getServiceBeansMap() { @@ -119,6 +116,4 @@ public abstract class AbstractDubboMetadata implements ApplicationContextAware, protected Map getProtocolConfigsBeanMap() { return beansOfTypeIncludingAncestors(applicationContext, ProtocolConfig.class); } - - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboConfigsMetadata.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboConfigsMetadata.java index 5df03b403e..5ddf340978 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboConfigsMetadata.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboConfigsMetadata.java @@ -28,12 +28,12 @@ import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.ServiceConfig; -import org.springframework.stereotype.Component; - import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; +import org.springframework.stereotype.Component; + import static org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors; /** @@ -60,13 +60,14 @@ public class DubboConfigsMetadata extends AbstractDubboMetadata { addDubboConfigBeans(ServiceConfig.class, configsMap); return configsMap; - } - private void addDubboConfigBeans(Class dubboConfigClass, - Map>> configsMap) { + private void addDubboConfigBeans( + Class dubboConfigClass, + Map>> configsMap) { - Map dubboConfigBeans = beansOfTypeIncludingAncestors(applicationContext, dubboConfigClass); + Map dubboConfigBeans = + beansOfTypeIncludingAncestors(applicationContext, dubboConfigClass); String name = dubboConfigClass.getSimpleName(); @@ -78,10 +79,8 @@ public class DubboConfigsMetadata extends AbstractDubboMetadata { AbstractConfig configBean = entry.getValue(); Map configBeanMeta = resolveBeanMetadata(configBean); beansMetadata.put(beanName, configBeanMeta); - } configsMap.put(name, beansMetadata); - } } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboMetadata.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboMetadata.java index 77093478a7..f14e1e7033 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboMetadata.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboMetadata.java @@ -19,11 +19,11 @@ package org.apache.dubbo.spring.boot.actuate.endpoint.metadata; import org.apache.dubbo.common.Version; import org.apache.dubbo.spring.boot.util.DubboUtils; -import org.springframework.stereotype.Component; - import java.util.LinkedHashMap; import java.util.Map; +import org.springframework.stereotype.Component; + import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_GITHUB_URL; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_MAILING_LIST; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_SPRING_BOOT_GITHUB_URL; diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboPropertiesMetadata.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboPropertiesMetadata.java index 5e3d4c4385..de9f146e3c 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboPropertiesMetadata.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboPropertiesMetadata.java @@ -16,10 +16,10 @@ */ package org.apache.dubbo.spring.boot.actuate.endpoint.metadata; -import org.springframework.stereotype.Component; - import java.util.SortedMap; +import org.springframework.stereotype.Component; + import static org.apache.dubbo.config.spring.util.EnvironmentUtils.filterDubboProperties; /** diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboReferencesMetadata.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboReferencesMetadata.java index 7c51ccf2a7..d7130664d1 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboReferencesMetadata.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboReferencesMetadata.java @@ -21,13 +21,13 @@ import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.spring.ReferenceBean; import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor; -import org.springframework.beans.factory.annotation.InjectionMetadata; -import org.springframework.stereotype.Component; - import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; +import org.springframework.beans.factory.annotation.InjectionMetadata; +import org.springframework.stereotype.Component; + /** * {@link DubboReference} Metadata * @@ -46,7 +46,6 @@ public class DubboReferencesMetadata extends AbstractDubboMetadata { referencesMetadata.putAll(buildReferencesMetadata(beanPostProcessor.getInjectedMethodReferenceBeanMap())); return referencesMetadata; - } private Map> buildReferencesMetadata( @@ -64,17 +63,15 @@ public class DubboReferencesMetadata extends AbstractDubboMetadata { Map beanMetadata = null; if (referenceConfig != null) { beanMetadata = resolveBeanMetadata(referenceConfig); - //beanMetadata.put("invoker", resolveBeanMetadata(referenceBean.get())); + // beanMetadata.put("invoker", resolveBeanMetadata(referenceBean.get())); } else { // referenceBean is not initialized beanMetadata = new LinkedHashMap<>(); } referencesMetadata.put(String.valueOf(injectedElement.getMember()), beanMetadata); - } return referencesMetadata; } - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboServicesMetadata.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboServicesMetadata.java index 11ce4d567a..44b63794d1 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboServicesMetadata.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboServicesMetadata.java @@ -19,11 +19,11 @@ package org.apache.dubbo.spring.boot.actuate.endpoint.metadata; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.config.spring.ServiceBean; -import org.springframework.stereotype.Component; - import java.util.LinkedHashMap; import java.util.Map; +import org.springframework.stereotype.Component; + /** * {@link DubboService} Metadata * @@ -54,11 +54,9 @@ public class DubboServicesMetadata extends AbstractDubboMetadata { } servicesMetadata.put(serviceBeanName, serviceBeanMetadata); - } return servicesMetadata; - } private Object resolveServiceBean(String serviceBeanName, ServiceBean serviceBean) { @@ -74,11 +72,8 @@ public class DubboServicesMetadata extends AbstractDubboMetadata { if (applicationContext.containsBean(serviceName)) { return applicationContext.getBean(serviceName, interfaceClass); } - } return null; - } - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboShutdownMetadata.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboShutdownMetadata.java index bdbd12590c..8430108abd 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboShutdownMetadata.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboShutdownMetadata.java @@ -21,14 +21,14 @@ import org.apache.dubbo.config.spring.ServiceBean; import org.apache.dubbo.registry.support.RegistryManager; import org.apache.dubbo.rpc.model.ApplicationModel; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + /** * Dubbo Shutdown * @@ -65,7 +65,8 @@ public class DubboShutdownMetadata extends AbstractDubboMetadata { shutdownCountData.put("services", serviceBeansMap.size()); // Reference Beans - Collection> references = applicationModel.getDefaultModule().getConfigManager().getReferences(); + Collection> references = + applicationModel.getDefaultModule().getConfigManager().getReferences(); for (ReferenceConfigBase reference : references) { reference.destroy(); } @@ -75,8 +76,6 @@ public class DubboShutdownMetadata extends AbstractDubboMetadata { Map shutdownData = new TreeMap<>(); shutdownData.put("shutdown.count", shutdownCountData); - return shutdownData; } - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/mvc/DubboMvcEndpoint.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/mvc/DubboMvcEndpoint.java index 965de4d255..6af9051418 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/mvc/DubboMvcEndpoint.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/mvc/DubboMvcEndpoint.java @@ -23,6 +23,9 @@ import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboReferencesMet import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboServicesMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboShutdownMetadata; +import java.util.Map; +import java.util.SortedMap; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -34,9 +37,6 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.context.request.async.DeferredResult; -import java.util.Map; -import java.util.SortedMap; - /** * {@link MvcEndpoint} to expose Dubbo Metadata * @@ -76,37 +76,49 @@ public class DubboMvcEndpoint extends EndpointMvcAdapter { super(dubboEndpoint); } - - @RequestMapping(value = DUBBO_SHUTDOWN_ENDPOINT_URI, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) + @RequestMapping( + value = DUBBO_SHUTDOWN_ENDPOINT_URI, + method = RequestMethod.POST, + produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public DeferredResult shutdown() throws Exception { Map shutdownCountData = dubboShutdownMetadata.shutdown(); return new DeferredResult(null, shutdownCountData); } - @RequestMapping(value = DUBBO_CONFIGS_ENDPOINT_URI, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + @RequestMapping( + value = DUBBO_CONFIGS_ENDPOINT_URI, + method = RequestMethod.GET, + produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Map>> configs() { return dubboConfigsMetadata.configs(); } - - @RequestMapping(value = DUBBO_SERVICES_ENDPOINT_URI, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + @RequestMapping( + value = DUBBO_SERVICES_ENDPOINT_URI, + method = RequestMethod.GET, + produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Map> services() { return dubboServicesMetadata.services(); } - @RequestMapping(value = DUBBO_REFERENCES_ENDPOINT_URI, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + @RequestMapping( + value = DUBBO_REFERENCES_ENDPOINT_URI, + method = RequestMethod.GET, + produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Map> references() { return dubboReferencesMetadata.references(); } - @RequestMapping(value = DUBBO_PROPERTIES_ENDPOINT_URI, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + @RequestMapping( + value = DUBBO_PROPERTIES_ENDPOINT_URI, + method = RequestMethod.GET, + produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public SortedMap properties() { return dubboPropertiesMetadata.properties(); - } } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/health/DubboHealthIndicator.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/health/DubboHealthIndicator.java index 135ef96f8f..14d5ba1096 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/health/DubboHealthIndicator.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/health/DubboHealthIndicator.java @@ -24,17 +24,17 @@ import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.health.AbstractHealthIndicator; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.util.StringUtils; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; - /** * Dubbo {@link HealthIndicator} * @@ -46,10 +46,10 @@ public class DubboHealthIndicator extends AbstractHealthIndicator { @Autowired private DubboHealthIndicatorProperties dubboHealthIndicatorProperties; - //@Autowired(required = false) + // @Autowired(required = false) private Map protocolConfigs = Collections.emptyMap(); - //@Autowired(required = false) + // @Autowired(required = false) private Map providerConfigs = Collections.emptyMap(); @Autowired @@ -100,10 +100,7 @@ public class DubboHealthIndicator extends AbstractHealthIndicator { detail.put("status", status); builder.withDetail(statusCheckerName, detail); - } - - } /** @@ -122,33 +119,27 @@ public class DubboHealthIndicator extends AbstractHealthIndicator { statusCheckerNamesMap.putAll(resolveStatusCheckerNamesMapFromProviderConfig()); return statusCheckerNamesMap; - } private Map resolveStatusCheckerNamesMapFromDubboHealthIndicatorProperties() { - DubboHealthIndicatorProperties.Status status = - dubboHealthIndicatorProperties.getStatus(); + DubboHealthIndicatorProperties.Status status = dubboHealthIndicatorProperties.getStatus(); Map statusCheckerNamesMap = new LinkedHashMap<>(); for (String statusName : status.getDefaults()) { statusCheckerNamesMap.put(statusName, DubboHealthIndicatorProperties.PREFIX + ".status.defaults"); - } for (String statusName : status.getExtras()) { statusCheckerNamesMap.put(statusName, DubboHealthIndicatorProperties.PREFIX + ".status.extras"); - } return statusCheckerNamesMap; - } - private Map resolveStatusCheckerNamesMapFromProtocolConfigs() { if (protocolConfigs.isEmpty()) { @@ -170,13 +161,10 @@ public class DubboHealthIndicator extends AbstractHealthIndicator { String source = buildSource(beanName, protocolConfig); statusCheckerNamesMap.put(statusCheckerName, source); - } - } return statusCheckerNamesMap; - } private Map resolveStatusCheckerNamesMapFromProviderConfig() { @@ -203,13 +191,10 @@ public class DubboHealthIndicator extends AbstractHealthIndicator { String source = buildSource(beanName, providerConfig); statusCheckerNamesMap.put(statusCheckerName, source); - } - } return statusCheckerNamesMap; - } private Set getStatusCheckerNames(ProtocolConfig protocolConfig) { @@ -225,5 +210,4 @@ public class DubboHealthIndicator extends AbstractHealthIndicator { private String buildSource(String beanName, Object bean) { return beanName + "@" + bean.getClass().getSimpleName() + ".getStatus()"; } - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/health/DubboHealthIndicatorProperties.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/health/DubboHealthIndicatorProperties.java index 0bc1082ed7..b0ba917dd3 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/health/DubboHealthIndicatorProperties.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/health/DubboHealthIndicatorProperties.java @@ -18,13 +18,13 @@ package org.apache.dubbo.spring.boot.actuate.health; import org.apache.dubbo.common.status.StatusChecker; -import org.springframework.boot.actuate.health.HealthIndicator; -import org.springframework.boot.context.properties.ConfigurationProperties; - import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.boot.context.properties.ConfigurationProperties; + import static org.apache.dubbo.spring.boot.actuate.health.DubboHealthIndicatorProperties.PREFIX; /** @@ -95,5 +95,4 @@ public class DubboHealthIndicatorProperties { this.extras = extras; } } - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/test/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAutoConfigurationTest.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/test/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAutoConfigurationTest.java index e22741b872..925b582c5a 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/test/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAutoConfigurationTest.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/test/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAutoConfigurationTest.java @@ -24,6 +24,10 @@ import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboReferencesMet import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboServicesMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboShutdownMetadata; +import java.util.Map; +import java.util.SortedMap; +import java.util.function.Supplier; + import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Assert; @@ -37,10 +41,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; -import java.util.Map; -import java.util.SortedMap; -import java.util.function.Supplier; - /** * {@link DubboEndpointAutoConfiguration} Test * @@ -48,35 +48,32 @@ import java.util.function.Supplier; */ @RunWith(SpringRunner.class) @SpringBootTest( - classes = { - DubboEndpointAutoConfiguration.class, - DubboEndpointAutoConfigurationTest.class - }, + classes = {DubboEndpointAutoConfiguration.class, DubboEndpointAutoConfigurationTest.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { - "dubbo.service.version = 1.0.0", - "dubbo.application.id = my-application", - "dubbo.application.name = dubbo-demo-application", - "dubbo.module.id = my-module", - "dubbo.module.name = dubbo-demo-module", - "dubbo.registry.id = my-registry", - "dubbo.registry.address = N/A", - "dubbo.protocol.id=my-protocol", - "dubbo.protocol.name=dubbo", - "dubbo.protocol.port=20880", - "dubbo.provider.id=my-provider", - "dubbo.provider.host=127.0.0.1", - "dubbo.scan.basePackages=org.apache.dubbo.spring.boot.actuate.autoconfigure", - "endpoints.enabled = true", - "management.security.enabled = false", - "management.contextPath = /actuator", - "endpoints.dubbo.enabled = true", - "endpoints.dubbo.sensitive = false", - "endpoints.dubboshutdown.enabled = true", - "endpoints.dubboconfigs.enabled = true", - "endpoints.dubboservices.enabled = true", - "endpoints.dubboreferences.enabled = true", - "endpoints.dubboproperties.enabled = true", + "dubbo.service.version = 1.0.0", + "dubbo.application.id = my-application", + "dubbo.application.name = dubbo-demo-application", + "dubbo.module.id = my-module", + "dubbo.module.name = dubbo-demo-module", + "dubbo.registry.id = my-registry", + "dubbo.registry.address = N/A", + "dubbo.protocol.id=my-protocol", + "dubbo.protocol.name=dubbo", + "dubbo.protocol.port=20880", + "dubbo.provider.id=my-provider", + "dubbo.provider.host=127.0.0.1", + "dubbo.scan.basePackages=org.apache.dubbo.spring.boot.actuate.autoconfigure", + "endpoints.enabled = true", + "management.security.enabled = false", + "management.contextPath = /actuator", + "endpoints.dubbo.enabled = true", + "endpoints.dubbo.sensitive = false", + "endpoints.dubboshutdown.enabled = true", + "endpoints.dubboconfigs.enabled = true", + "endpoints.dubboservices.enabled = true", + "endpoints.dubboreferences.enabled = true", + "endpoints.dubboproperties.enabled = true", }) @EnableAutoConfiguration @Ignore @@ -119,7 +116,6 @@ public class DubboEndpointAutoConfigurationTest { Assert.assertEquals(1, shutdownCounts.get("protocols")); Assert.assertEquals(1, shutdownCounts.get("services")); Assert.assertEquals(0, shutdownCounts.get("references")); - } @Test @@ -128,7 +124,8 @@ public class DubboEndpointAutoConfigurationTest { Map>> configsMap = dubboConfigsMetadata.configs(); Map> beansMetadata = configsMap.get("ApplicationConfig"); - Assert.assertEquals("dubbo-demo-application", beansMetadata.get("my-application").get("name")); + Assert.assertEquals( + "dubbo-demo-application", beansMetadata.get("my-application").get("name")); beansMetadata = configsMap.get("ConsumerConfig"); Assert.assertTrue(beansMetadata.isEmpty()); @@ -156,7 +153,6 @@ public class DubboEndpointAutoConfigurationTest { beansMetadata = configsMap.get("ServiceConfig"); Assert.assertFalse(beansMetadata.isEmpty()); - } @Test @@ -166,10 +162,10 @@ public class DubboEndpointAutoConfigurationTest { Assert.assertEquals(1, services.size()); - Map demoServiceMeta = services.get("ServiceBean:org.apache.dubbo.spring.boot.actuate.autoconfigure.DubboEndpointAutoConfigurationTest$DemoService:1.0.0:"); + Map demoServiceMeta = services.get( + "ServiceBean:org.apache.dubbo.spring.boot.actuate.autoconfigure.DubboEndpointAutoConfigurationTest$DemoService:1.0.0:"); Assert.assertEquals("1.0.0", demoServiceMeta.get("version")); - } @Test @@ -178,7 +174,6 @@ public class DubboEndpointAutoConfigurationTest { Map> references = dubboReferencesMetadata.references(); Assert.assertTrue(references.isEmpty()); - } @Test @@ -197,12 +192,13 @@ public class DubboEndpointAutoConfigurationTest { Assert.assertEquals("20880", properties.get("dubbo.protocol.port")); Assert.assertEquals("my-provider", properties.get("dubbo.provider.id")); Assert.assertEquals("127.0.0.1", properties.get("dubbo.provider.host")); - Assert.assertEquals("org.apache.dubbo.spring.boot.actuate.autoconfigure", properties.get("dubbo.scan.basePackages")); + Assert.assertEquals( + "org.apache.dubbo.spring.boot.actuate.autoconfigure", properties.get("dubbo.scan.basePackages")); } @Test public void testHttpEndpoints() throws JsonProcessingException { -// testHttpEndpoint("/dubbo", dubboEndpoint::invoke); + // testHttpEndpoint("/dubbo", dubboEndpoint::invoke); testHttpEndpoint("/dubbo/configs", dubboConfigsMetadata::configs); testHttpEndpoint("/dubbo/services", dubboServicesMetadata::services); testHttpEndpoint("/dubbo/references", dubboReferencesMetadata::references); @@ -215,7 +211,6 @@ public class DubboEndpointAutoConfigurationTest { Assert.assertEquals(objectMapper.writeValueAsString(resultsSupplier.get()), response); } - interface DemoService { String sayHello(String name); } @@ -224,15 +219,11 @@ public class DubboEndpointAutoConfigurationTest { version = "${dubbo.service.version}", application = "${dubbo.application.id}", protocol = "${dubbo.protocol.id}", - registry = "${dubbo.registry.id}" - ) + registry = "${dubbo.registry.id}") static class DefaultDemoService implements DemoService { public String sayHello(String name) { return "Hello, " + name + " (from Spring Boot)"; } - } - - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/test/java/org/apache/dubbo/spring/boot/actuate/health/DubboHealthIndicatorTest.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/test/java/org/apache/dubbo/spring/boot/actuate/health/DubboHealthIndicatorTest.java index 130e21e8d8..c785cf8ac4 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/test/java/org/apache/dubbo/spring/boot/actuate/health/DubboHealthIndicatorTest.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/test/java/org/apache/dubbo/spring/boot/actuate/health/DubboHealthIndicatorTest.java @@ -18,6 +18,8 @@ package org.apache.dubbo.spring.boot.actuate.health; import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig; +import java.util.Map; + import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -29,8 +31,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; -import java.util.Map; - /** * {@link DubboHealthIndicator} Test * @@ -38,24 +38,20 @@ import java.util.Map; * @since 2.7.0 */ @RunWith(SpringRunner.class) -@TestPropertySource(properties = { - "dubbo.application.id = my-application-1", - "dubbo.application.name = dubbo-demo-application-1", - "dubbo.protocol.id = dubbo-protocol", - "dubbo.protocol.name = dubbo", - "dubbo.protocol.port = 12345", - "dubbo.protocol.status = registry", - "dubbo.provider.id = dubbo-provider", - "dubbo.provider.status = server", - "management.health.dubbo.status.defaults = memory", - "management.health.dubbo.status.extras = load,threadpool" -}) -@SpringBootTest( - classes = { - DubboHealthIndicator.class, - DubboHealthIndicatorTest.class - } -) +@TestPropertySource( + properties = { + "dubbo.application.id = my-application-1", + "dubbo.application.name = dubbo-demo-application-1", + "dubbo.protocol.id = dubbo-protocol", + "dubbo.protocol.name = dubbo", + "dubbo.protocol.port = 12345", + "dubbo.protocol.status = registry", + "dubbo.provider.id = dubbo-provider", + "dubbo.provider.status = server", + "management.health.dubbo.status.defaults = memory", + "management.health.dubbo.status.extras = load,threadpool" + }) +@SpringBootTest(classes = {DubboHealthIndicator.class, DubboHealthIndicatorTest.class}) @EnableConfigurationProperties(DubboHealthIndicatorProperties.class) @EnableDubboConfig public class DubboHealthIndicatorTest { @@ -75,7 +71,6 @@ public class DubboHealthIndicatorTest { Assert.assertEquals("management.health.dubbo.status.defaults", statusCheckerNamesMap.get("memory")); Assert.assertEquals("management.health.dubbo.status.extras", statusCheckerNamesMap.get("load")); Assert.assertEquals("management.health.dubbo.status.extras", statusCheckerNamesMap.get("threadpool")); - } @Test @@ -84,6 +79,5 @@ public class DubboHealthIndicatorTest { Health health = dubboHealthIndicator.health(); Assert.assertEquals(Status.UNKNOWN, health.getStatus()); - } } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/pom.xml index 98c6f80fc3..4a5705905c 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/pom.xml @@ -15,87 +15,85 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - org.apache.dubbo - dubbo-spring-boot-compatible - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-spring-boot-compatible + ${revision} + ../pom.xml + - dubbo-spring-boot-autoconfigure-compatible - Apache Dubbo Spring Boot Compatible for Spring Boot 1.x Auto-Configure + dubbo-spring-boot-autoconfigure-compatible + Apache Dubbo Spring Boot Compatible for Spring Boot 1.x Auto-Configure - - - - org.springframework.boot - spring-boot-autoconfigure - true - + + + + org.springframework.boot + spring-boot-autoconfigure + true + - - org.springframework.boot - spring-boot - true - + + org.springframework.boot + spring-boot + true + - - org.springframework.boot - spring-boot-starter-logging - true - + + org.springframework.boot + spring-boot-starter-logging + true + - - org.apache.dubbo - dubbo-common - ${project.version} - true - + + org.apache.dubbo + dubbo-common + ${project.version} + true + - - org.apache.dubbo - dubbo-config-spring - ${project.version} - true - + + org.apache.dubbo + dubbo-config-spring + ${project.version} + true + - - org.apache.dubbo - dubbo - ${project.version} - + + org.apache.dubbo + dubbo + ${project.version} + - - org.apache.dubbo - dubbo-spring-boot-configuration-metadata-compatible - ${project.version} - provided - + + org.apache.dubbo + dubbo-spring-boot-configuration-metadata-compatible + ${project.version} + provided + - - - org.springframework.boot - spring-boot-starter-test - test - - + + + org.springframework.boot + spring-boot-starter-test + test + + - - - - src/main/resources - - - META-INF - ../metadata/target/classes/META-INF - - spring-configuration-metadata.json - - - - + + + + src/main/resources + + + META-INF + ../metadata/target/classes/META-INF + + spring-configuration-metadata.json + + + + diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboAutoConfiguration.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboAutoConfiguration.java index 18e76e07ff..acf60f04df 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboAutoConfiguration.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboAutoConfiguration.java @@ -22,6 +22,10 @@ import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotati import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor; import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig; import org.apache.dubbo.config.spring.util.SpringCompatUtils; + +import java.util.Collection; +import java.util.Set; + import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; @@ -29,9 +33,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import java.util.Collection; -import java.util.Set; - import static org.apache.dubbo.spring.boot.util.DubboUtils.BASE_PACKAGES_BEAN_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.BASE_PACKAGES_PROPERTY_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; @@ -61,14 +62,17 @@ public class DubboAutoConfiguration { @ConditionalOnProperty(prefix = DUBBO_SCAN_PREFIX, name = BASE_PACKAGES_PROPERTY_NAME) @ConditionalOnBean(name = BASE_PACKAGES_BEAN_NAME) @Bean - public ServiceAnnotationPostProcessor serviceAnnotationBeanProcessor(@Qualifier(BASE_PACKAGES_BEAN_NAME) Set packagesToScan) { + public ServiceAnnotationPostProcessor serviceAnnotationBeanProcessor( + @Qualifier(BASE_PACKAGES_BEAN_NAME) Set packagesToScan) { ServiceAnnotationPostProcessor serviceAnnotationPostProcessor; try { - serviceAnnotationPostProcessor = (ServiceAnnotationPostProcessor) SpringCompatUtils.serviceAnnotationPostProcessor().getDeclaredConstructor(Collection.class).newInstance(packagesToScan); + serviceAnnotationPostProcessor = + (ServiceAnnotationPostProcessor) SpringCompatUtils.serviceAnnotationPostProcessor() + .getDeclaredConstructor(Collection.class) + .newInstance(packagesToScan); } catch (Exception e) { throw new RuntimeException(e); } return serviceAnnotationPostProcessor; } - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboConfigurationProperties.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboConfigurationProperties.java index efdcf9bc65..959cee4a77 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboConfigurationProperties.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboConfigurationProperties.java @@ -30,12 +30,13 @@ import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.SslConfig; import org.apache.dubbo.config.TracingConfig; import org.apache.dubbo.config.TripleConfig; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.NestedConfigurationProperty; import java.util.LinkedHashMap; import java.util.Map; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.NestedConfigurationProperty; + /** * Dubbo {@link ConfigurationProperties Config Properties} only used to generate JSON metadata (non-public class) * diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboRelaxedBindingAutoConfiguration.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboRelaxedBindingAutoConfiguration.java index fdd3209362..560ae96f47 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboRelaxedBindingAutoConfiguration.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboRelaxedBindingAutoConfiguration.java @@ -16,6 +16,8 @@ */ package org.apache.dubbo.spring.boot.autoconfigure; +import java.util.Set; + import com.alibaba.spring.context.config.ConfigurationBeanBinder; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; @@ -27,8 +29,6 @@ import org.springframework.context.annotation.Scope; import org.springframework.core.env.Environment; import org.springframework.core.env.PropertyResolver; -import java.util.Set; - import static java.util.Collections.emptySet; import static org.apache.dubbo.spring.boot.util.DubboUtils.BASE_PACKAGES_BEAN_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.BASE_PACKAGES_PROPERTY_NAME; @@ -69,5 +69,4 @@ public class DubboRelaxedBindingAutoConfiguration { public ConfigurationBeanBinder relaxedDubboConfigBinder() { return new RelaxedDubboConfigBinder(); } - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/RelaxedDubboConfigBinder.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/RelaxedDubboConfigBinder.java index 40bc227047..cecfc1dcde 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/RelaxedDubboConfigBinder.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/RelaxedDubboConfigBinder.java @@ -18,13 +18,12 @@ package org.apache.dubbo.spring.boot.autoconfigure; import org.apache.dubbo.config.spring.context.properties.DubboConfigBinder; +import java.util.Map; + import com.alibaba.spring.context.config.ConfigurationBeanBinder; import org.springframework.beans.MutablePropertyValues; import org.springframework.boot.bind.RelaxedDataBinder; -import java.util.Map; - - /** * Spring Boot Relaxed {@link DubboConfigBinder} implementation * @@ -33,8 +32,11 @@ import java.util.Map; class RelaxedDubboConfigBinder implements ConfigurationBeanBinder { @Override - public void bind(Map configurationProperties, boolean ignoreUnknownFields, - boolean ignoreInvalidFields, Object configurationBean) { + public void bind( + Map configurationProperties, + boolean ignoreUnknownFields, + boolean ignoreInvalidFields, + Object configurationBean) { RelaxedDataBinder relaxedDataBinder = new RelaxedDataBinder(configurationBean); // Set ignored* relaxedDataBinder.setIgnoreInvalidFields(ignoreInvalidFields); diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/beans/factory/config/ServiceBeanIdConflictProcessor.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/beans/factory/config/ServiceBeanIdConflictProcessor.java index 94592a9ee3..dee05c07cc 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/beans/factory/config/ServiceBeanIdConflictProcessor.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/beans/factory/config/ServiceBeanIdConflictProcessor.java @@ -20,6 +20,12 @@ import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.spring.ServiceBean; import org.apache.dubbo.config.spring.reference.ReferenceAttributes; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + import org.springframework.beans.BeansException; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor; @@ -28,12 +34,6 @@ import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor; import org.springframework.core.Ordered; import org.springframework.core.PriorityOrdered; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - import static org.apache.dubbo.config.spring.util.SpringCompatUtils.getPropertyValue; import static org.springframework.util.ClassUtils.getUserClass; import static org.springframework.util.ClassUtils.isAssignable; @@ -48,7 +48,8 @@ import static org.springframework.util.ClassUtils.isAssignable; * @since 2.7.7 * @deprecated */ -public class ServiceBeanIdConflictProcessor implements MergedBeanDefinitionPostProcessor, DisposableBean, PriorityOrdered { +public class ServiceBeanIdConflictProcessor + implements MergedBeanDefinitionPostProcessor, DisposableBean, PriorityOrdered { /** * The key is the class names of interfaces that were exported by {@link ServiceBean} @@ -85,7 +86,6 @@ public class ServiceBeanIdConflictProcessor implements MergedBeanDefinitionPostP // Set id as the bean name serviceConfig.setId(beanName); } - } return bean; } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/context/DubboApplicationContextInitializer.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/context/DubboApplicationContextInitializer.java index 56f78b9970..805b423a3c 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/context/DubboApplicationContextInitializer.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/context/DubboApplicationContextInitializer.java @@ -46,5 +46,4 @@ public class DubboApplicationContextInitializer implements ApplicationContextIni public int getOrder() { return HIGHEST_PRECEDENCE; } - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/context/event/AwaitingNonWebApplicationListener.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/context/event/AwaitingNonWebApplicationListener.java index 3f2fd415db..bd3a7e5de6 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/context/event/AwaitingNonWebApplicationListener.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/context/event/AwaitingNonWebApplicationListener.java @@ -20,6 +20,13 @@ import org.apache.dubbo.common.lang.ShutdownHookCallbacks; import org.apache.dubbo.config.spring.util.DubboBeanUtils; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.context.event.ApplicationFailedEvent; @@ -32,13 +39,6 @@ import org.springframework.context.event.ContextClosedEvent; import org.springframework.context.event.SmartApplicationListener; import org.springframework.util.ClassUtils; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - import static java.util.concurrent.Executors.newSingleThreadExecutor; import static org.springframework.util.ObjectUtils.containsElement; @@ -49,7 +49,7 @@ import static org.springframework.util.ObjectUtils.containsElement; */ public class AwaitingNonWebApplicationListener implements SmartApplicationListener { - private static final String[] WEB_APPLICATION_CONTEXT_CLASSES = new String[]{ + private static final String[] WEB_APPLICATION_CONTEXT_CLASSES = new String[] { "org.springframework.web.context.WebApplicationContext", "org.springframework.boot.web.reactive.context.ReactiveWebApplicationContext" }; @@ -57,7 +57,7 @@ public class AwaitingNonWebApplicationListener implements SmartApplicationListen private static final Logger logger = LoggerFactory.getLogger(AwaitingNonWebApplicationListener.class); private static final Class[] SUPPORTED_APPLICATION_EVENTS = - of(ApplicationReadyEvent.class, ContextClosedEvent.class); + of(ApplicationReadyEvent.class, ContextClosedEvent.class); private final AtomicBoolean awaited = new AtomicBoolean(false); @@ -135,7 +135,8 @@ public class AwaitingNonWebApplicationListener implements SmartApplicationListen if (applicationModel == null) { return; } - ShutdownHookCallbacks shutdownHookCallbacks = applicationModel.getBeanFactory().getBean(ShutdownHookCallbacks.class); + ShutdownHookCallbacks shutdownHookCallbacks = + applicationModel.getBeanFactory().getBean(ShutdownHookCallbacks.class); if (shutdownHookCallbacks != null) { shutdownHookCallbacks.addCallback(this::release); } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/context/event/DubboConfigBeanDefinitionConflictApplicationListener.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/context/event/DubboConfigBeanDefinitionConflictApplicationListener.java index d9c7d4cf5c..2e5c4fe9ff 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/context/event/DubboConfigBeanDefinitionConflictApplicationListener.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/context/event/DubboConfigBeanDefinitionConflictApplicationListener.java @@ -19,6 +19,10 @@ package org.apache.dubbo.spring.boot.context.event; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig; +import java.util.Objects; +import java.util.stream.Collectors; +import java.util.stream.Stream; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.BeanFactoryUtils; @@ -33,10 +37,6 @@ import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.core.Ordered; import org.springframework.core.env.Environment; -import java.util.Objects; -import java.util.stream.Collectors; -import java.util.stream.Stream; - import static org.springframework.beans.factory.BeanFactoryUtils.beanNamesForTypeIncludingAncestors; import static org.springframework.context.ConfigurableApplicationContext.ENVIRONMENT_BEAN_NAME; @@ -47,8 +47,8 @@ import static org.springframework.context.ConfigurableApplicationContext.ENVIRON * @see ApplicationListener * @since 2.7.5 */ -public class DubboConfigBeanDefinitionConflictApplicationListener implements ApplicationListener, - Ordered { +public class DubboConfigBeanDefinitionConflictApplicationListener + implements ApplicationListener, Ordered { private final Logger logger = LoggerFactory.getLogger(getClass()); @@ -64,7 +64,8 @@ public class DubboConfigBeanDefinitionConflictApplicationListener implements App if (beanFactory instanceof BeanDefinitionRegistry) { return (BeanDefinitionRegistry) beanFactory; } - throw new IllegalStateException("The BeanFactory in the ApplicationContext must bea subclass of BeanDefinitionRegistry"); + throw new IllegalStateException( + "The BeanFactory in the ApplicationContext must bea subclass of BeanDefinitionRegistry"); } /** @@ -86,34 +87,32 @@ public class DubboConfigBeanDefinitionConflictApplicationListener implements App // Remove ApplicationConfig Beans that are configured by "dubbo.application.*" Stream.of(beansNames) - .filter(beansName -> isConfiguredApplicationConfigBeanName(environment, beansName)) - .forEach(registry::removeBeanDefinition); + .filter(beansName -> isConfiguredApplicationConfigBeanName(environment, beansName)) + .forEach(registry::removeBeanDefinition); beansNames = beanNamesForTypeIncludingAncestors(beanFactory, ApplicationConfig.class); if (beansNames.length > 1) { - throw new IllegalStateException(String.format("There are more than one instances of %s, whose bean definitions : %s", - ApplicationConfig.class.getSimpleName(), - Stream.of(beansNames) - .map(registry::getBeanDefinition) - .collect(Collectors.toList())) - ); + throw new IllegalStateException(String.format( + "There are more than one instances of %s, whose bean definitions : %s", + ApplicationConfig.class.getSimpleName(), + Stream.of(beansNames).map(registry::getBeanDefinition).collect(Collectors.toList()))); } } private boolean isConfiguredApplicationConfigBeanName(Environment environment, String beanName) { boolean removed = BeanFactoryUtils.isGeneratedBeanName(beanName) - // Dubbo ApplicationConfig id as bean name - || Objects.equals(beanName, environment.getProperty("dubbo.application.id")); + // Dubbo ApplicationConfig id as bean name + || Objects.equals(beanName, environment.getProperty("dubbo.application.id")); if (removed && logger.isDebugEnabled()) { - logger.debug("The {} bean [ name : {} ] has been removed!", ApplicationConfig.class.getSimpleName(), beanName); + logger.debug( + "The {} bean [ name : {} ] has been removed!", ApplicationConfig.class.getSimpleName(), beanName); } return removed; } - @Override public int getOrder() { return LOWEST_PRECEDENCE; diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/context/event/WelcomeLogoApplicationListener.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/context/event/WelcomeLogoApplicationListener.java index 4ff84fc44b..4d511307d4 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/context/event/WelcomeLogoApplicationListener.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/context/event/WelcomeLogoApplicationListener.java @@ -17,18 +17,16 @@ package org.apache.dubbo.spring.boot.context.event; import org.apache.dubbo.common.Version; - - import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; + +import java.util.concurrent.atomic.AtomicBoolean; + import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; -import org.springframework.boot.logging.LoggingApplicationListener; import org.springframework.context.ApplicationListener; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; -import java.util.concurrent.atomic.AtomicBoolean; - import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_GITHUB_URL; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_MAILING_LIST; import static org.apache.dubbo.spring.boot.util.DubboUtils.LINE_SEPARATOR; @@ -39,7 +37,7 @@ import static org.apache.dubbo.spring.boot.util.DubboUtils.LINE_SEPARATOR; * @see ApplicationListener * @since 2.7.0 */ -@Order(Ordered.HIGHEST_PRECEDENCE + 20 + 1) // After LoggingApplicationListener#DEFAULT_ORDER +@Order(Ordered.HIGHEST_PRECEDENCE + 20 + 1) // After LoggingApplicationListener#DEFAULT_ORDER public class WelcomeLogoApplicationListener implements ApplicationListener { private static AtomicBoolean processed = new AtomicBoolean(false); @@ -77,16 +75,15 @@ public class WelcomeLogoApplicationListener implements ApplicationListenertrue as default. @@ -107,14 +106,13 @@ public class DubboDefaultPropertiesEnvironmentPostProcessor implements Environme * @param propertySources {@link MutablePropertySources} * @param map Default Dubbo Properties */ - private void addOrReplace(MutablePropertySources propertySources, - Map map) { + private void addOrReplace(MutablePropertySources propertySources, Map map) { MapPropertySource target = null; if (propertySources.contains(PROPERTY_SOURCE_NAME)) { PropertySource source = propertySources.get(PROPERTY_SOURCE_NAME); if (source instanceof MapPropertySource) { target = (MapPropertySource) source; - for (Map.Entry entry : map.entrySet()) { + for (Map.Entry entry : map.entrySet()) { String key = entry.getKey(); if (!target.containsProperty(key)) { target.getSource().put(key, entry.getValue()); diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/util/DubboUtils.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/util/DubboUtils.java index 46d7291b9d..dc7f6f9b91 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/util/DubboUtils.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/util/DubboUtils.java @@ -21,11 +21,11 @@ import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotation import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig; import org.apache.dubbo.config.spring.context.properties.DubboConfigBinder; +import java.util.Set; + import org.springframework.boot.context.ContextIdApplicationContextInitializer; import org.springframework.core.env.PropertyResolver; -import java.util.Set; - /** * The utilities class for Dubbo * @@ -38,7 +38,6 @@ public abstract class DubboUtils { */ public static final String LINE_SEPARATOR = System.getProperty("line.separator"); - /** * The separator of property name */ @@ -52,12 +51,14 @@ public abstract class DubboUtils { /** * The prefix of property name for Dubbo scan */ - public static final String DUBBO_SCAN_PREFIX = DUBBO_PREFIX + PROPERTY_NAME_SEPARATOR + "scan" + PROPERTY_NAME_SEPARATOR; + public static final String DUBBO_SCAN_PREFIX = + DUBBO_PREFIX + PROPERTY_NAME_SEPARATOR + "scan" + PROPERTY_NAME_SEPARATOR; /** * The prefix of property name for Dubbo Config */ - public static final String DUBBO_CONFIG_PREFIX = DUBBO_PREFIX + PROPERTY_NAME_SEPARATOR + "config" + PROPERTY_NAME_SEPARATOR; + public static final String DUBBO_CONFIG_PREFIX = + DUBBO_PREFIX + PROPERTY_NAME_SEPARATOR + "config" + PROPERTY_NAME_SEPARATOR; /** * The property name of base packages to scan @@ -96,11 +97,11 @@ public abstract class DubboUtils { */ public static final boolean DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE = true; - /** * The github URL of Dubbo Spring Boot */ - public static final String DUBBO_SPRING_BOOT_GITHUB_URL = "https://github.com/apache/dubbo/tree/3.0/dubbo-spring-boot"; + public static final String DUBBO_SPRING_BOOT_GITHUB_URL = + "https://github.com/apache/dubbo/tree/3.0/dubbo-spring-boot"; /** * The git URL of Dubbo Spring Boot @@ -179,6 +180,4 @@ public abstract class DubboUtils { * @since 2.7.1 */ public static final String DUBBO_CONFIG_MULTIPLE_PROPERTY = "dubbo.config.multiple"; - - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/TestSuite.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/TestSuite.java index e01131891f..bde1d9c014 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/TestSuite.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/TestSuite.java @@ -32,16 +32,15 @@ import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ - CompatibleDubboAutoConfigurationTest.class, - CompatibleDubboAutoConfigurationTestWithoutProperties.class, - DubboAutoConfigurationOnMultipleConfigTest.class, - DubboAutoConfigurationOnSingleConfigTest.class, - RelaxedDubboConfigBinderTest.class, - AwaitingNonWebApplicationListenerTest.class, - DubboConfigBeanDefinitionConflictApplicationListenerTest.class, - WelcomeLogoApplicationListenerTest.class, - DubboDefaultPropertiesEnvironmentPostProcessorTest.class, - DubboUtilsTest.class, + CompatibleDubboAutoConfigurationTest.class, + CompatibleDubboAutoConfigurationTestWithoutProperties.class, + DubboAutoConfigurationOnMultipleConfigTest.class, + DubboAutoConfigurationOnSingleConfigTest.class, + RelaxedDubboConfigBinderTest.class, + AwaitingNonWebApplicationListenerTest.class, + DubboConfigBeanDefinitionConflictApplicationListenerTest.class, + WelcomeLogoApplicationListenerTest.class, + DubboDefaultPropertiesEnvironmentPostProcessorTest.class, + DubboUtilsTest.class, }) -public class TestSuite { -} +public class TestSuite {} diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/CompatibleDubboAutoConfigurationTest.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/CompatibleDubboAutoConfigurationTest.java index 6d1330c7b5..ced20cf117 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/CompatibleDubboAutoConfigurationTest.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/CompatibleDubboAutoConfigurationTest.java @@ -19,6 +19,7 @@ package org.apache.dubbo.spring.boot.autoconfigure; import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor; import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor; import org.apache.dubbo.config.spring.util.DubboBeanUtils; + import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -35,11 +36,9 @@ import org.springframework.test.context.junit4.SpringRunner; * @see DubboAutoConfiguration */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = { - CompatibleDubboAutoConfigurationTest.class -}, properties = { - "dubbo.scan.base-packages = org.apache.dubbo.spring.boot.autoconfigure" -}) +@SpringBootTest( + classes = {CompatibleDubboAutoConfigurationTest.class}, + properties = {"dubbo.scan.base-packages = org.apache.dubbo.spring.boot.autoconfigure"}) @EnableAutoConfiguration @PropertySource(value = "classpath:/META-INF/dubbo.properties") public class CompatibleDubboAutoConfigurationTest { @@ -55,7 +54,8 @@ public class CompatibleDubboAutoConfigurationTest { Assert.assertNotNull(serviceAnnotationPostProcessor); Assert.assertNotNull(serviceAnnotationPostProcessor.getIfAvailable()); - ReferenceAnnotationBeanPostProcessor referenceAnnotationBeanPostProcessor = DubboBeanUtils.getReferenceAnnotationBeanPostProcessor(applicationContext); + ReferenceAnnotationBeanPostProcessor referenceAnnotationBeanPostProcessor = + DubboBeanUtils.getReferenceAnnotationBeanPostProcessor(applicationContext); Assert.assertNotNull(referenceAnnotationBeanPostProcessor); } } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/CompatibleDubboAutoConfigurationTestWithoutProperties.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/CompatibleDubboAutoConfigurationTestWithoutProperties.java index 15ead545ec..746b759c7c 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/CompatibleDubboAutoConfigurationTestWithoutProperties.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/CompatibleDubboAutoConfigurationTestWithoutProperties.java @@ -20,6 +20,7 @@ import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor; import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor; import org.apache.dubbo.config.spring.util.DubboBeanUtils; + import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -37,9 +38,9 @@ import org.springframework.test.context.junit4.SpringRunner; * @see DubboAutoConfiguration */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = CompatibleDubboAutoConfigurationTestWithoutProperties.class, properties = { - "dubbo.application.name=demo" -}) +@SpringBootTest( + classes = CompatibleDubboAutoConfigurationTestWithoutProperties.class, + properties = {"dubbo.application.name=demo"}) @EnableAutoConfiguration public class CompatibleDubboAutoConfigurationTestWithoutProperties { @@ -63,7 +64,8 @@ public class CompatibleDubboAutoConfigurationTestWithoutProperties { public void testBeans() { Assert.assertNull(serviceAnnotationPostProcessor); - ReferenceAnnotationBeanPostProcessor referenceAnnotationBeanPostProcessor = DubboBeanUtils.getReferenceAnnotationBeanPostProcessor(applicationContext); + ReferenceAnnotationBeanPostProcessor referenceAnnotationBeanPostProcessor = + DubboBeanUtils.getReferenceAnnotationBeanPostProcessor(applicationContext); Assert.assertNotNull(referenceAnnotationBeanPostProcessor); } } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/DubboAutoConfigurationOnMultipleConfigTest.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/DubboAutoConfigurationOnMultipleConfigTest.java index b0fc8accf2..147e2576ae 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/DubboAutoConfigurationOnMultipleConfigTest.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/DubboAutoConfigurationOnMultipleConfigTest.java @@ -25,6 +25,9 @@ import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; +import java.util.LinkedHashMap; +import java.util.Map; + import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -40,9 +43,6 @@ import org.springframework.core.env.Environment; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; -import java.util.LinkedHashMap; -import java.util.Map; - import static org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors; /** @@ -54,23 +54,18 @@ import static org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncl @RunWith(SpringRunner.class) @TestPropertySource( properties = { - "dubbo.applications.application1.NAME = dubbo-demo-application", - "dubbo.modules.module1.name = dubbo-demo-module", - "dubbo.registries.registry1.address = zookeeper://192.168.99.100:32770", - "dubbo.protocols.protocol1.name=dubbo", - "dubbo.protocols.protocol1.pORt=20880", - "dubbo.monitors.monitor1.Address=zookeeper://127.0.0.1:32770", - "dubbo.providers.provider1.host=127.0.0.1", - "dubbo.consumers.consumer1.client=netty", - "dubbo.config.multiple=true", - "dubbo.scan.basePackages=org.apache.dubbo.spring.boot.dubbo, org.apache.dubbo.spring.boot.condition" - } -) -@SpringBootTest( - classes = { - DubboAutoConfigurationOnMultipleConfigTest.class - } -) + "dubbo.applications.application1.NAME = dubbo-demo-application", + "dubbo.modules.module1.name = dubbo-demo-module", + "dubbo.registries.registry1.address = zookeeper://192.168.99.100:32770", + "dubbo.protocols.protocol1.name=dubbo", + "dubbo.protocols.protocol1.pORt=20880", + "dubbo.monitors.monitor1.Address=zookeeper://127.0.0.1:32770", + "dubbo.providers.provider1.host=127.0.0.1", + "dubbo.consumers.consumer1.client=netty", + "dubbo.config.multiple=true", + "dubbo.scan.basePackages=org.apache.dubbo.spring.boot.dubbo, org.apache.dubbo.spring.boot.condition" + }) +@SpringBootTest(classes = {DubboAutoConfigurationOnMultipleConfigTest.class}) @EnableAutoConfiguration public class DubboAutoConfigurationOnMultipleConfigTest { @@ -163,7 +158,6 @@ public class DubboAutoConfigurationOnMultipleConfigTest { @Test public void testMultipleDubboConfigBindingProperties() { - Assert.assertEquals(1, applications.size()); Assert.assertEquals(1, modules.size()); @@ -177,7 +171,6 @@ public class DubboAutoConfigurationOnMultipleConfigTest { Assert.assertEquals(1, providers.size()); Assert.assertEquals(1, consumers.size()); - } @Test @@ -186,7 +179,8 @@ public class DubboAutoConfigurationOnMultipleConfigTest { /** * Multiple {@link ApplicationConfig} */ - Map applications = beansOfTypeIncludingAncestors(applicationContext, ApplicationConfig.class); + Map applications = + beansOfTypeIncludingAncestors(applicationContext, ApplicationConfig.class); Assert.assertEquals(1, applications.size()); @@ -200,7 +194,8 @@ public class DubboAutoConfigurationOnMultipleConfigTest { /** * Multiple {@link RegistryConfig} */ - Map registries = beansOfTypeIncludingAncestors(applicationContext, RegistryConfig.class); + Map registries = + beansOfTypeIncludingAncestors(applicationContext, RegistryConfig.class); Assert.assertEquals(1, registries.size()); @@ -231,35 +226,30 @@ public class DubboAutoConfigurationOnMultipleConfigTest { Map consumers = beansOfTypeIncludingAncestors(applicationContext, ConsumerConfig.class); Assert.assertEquals(1, consumers.size()); - } @Test public void testApplicationConfig() { Assert.assertEquals("dubbo-demo-application", application.getName()); - } @Test public void testModuleConfig() { Assert.assertEquals("dubbo-demo-module", module.getName()); - } @Test public void testRegistryConfig() { Assert.assertEquals("zookeeper://192.168.99.100:32770", registry.getAddress()); - } @Test public void testMonitorConfig() { Assert.assertEquals("zookeeper://127.0.0.1:32770", monitor.getAddress()); - } @Test @@ -267,13 +257,11 @@ public class DubboAutoConfigurationOnMultipleConfigTest { Assert.assertEquals("dubbo", protocol.getName()); Assert.assertEquals(Integer.valueOf(20880), protocol.getPort()); - } @Test public void testConsumerConfig() { Assert.assertEquals("netty", consumer.getClient()); - } } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/DubboAutoConfigurationOnSingleConfigTest.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/DubboAutoConfigurationOnSingleConfigTest.java index db6d5a98c2..2cfc203543 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/DubboAutoConfigurationOnSingleConfigTest.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/DubboAutoConfigurationOnSingleConfigTest.java @@ -48,19 +48,16 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @TestPropertySource( properties = { - "dubbo.application.name = dubbo-demo-application", - "dubbo.module.name = dubbo-demo-module", - "dubbo.registry.address = zookeeper://192.168.99.100:32770", - "dubbo.protocol.name=dubbo", - "dubbo.protocol.port=20880", - "dubbo.monitor.address=zookeeper://127.0.0.1:32770", - "dubbo.provider.host=127.0.0.1", - "dubbo.consumer.client=netty" - } -) -@SpringBootTest( - classes = {DubboAutoConfigurationOnSingleConfigTest.class} -) + "dubbo.application.name = dubbo-demo-application", + "dubbo.module.name = dubbo-demo-module", + "dubbo.registry.address = zookeeper://192.168.99.100:32770", + "dubbo.protocol.name=dubbo", + "dubbo.protocol.port=20880", + "dubbo.monitor.address=zookeeper://127.0.0.1:32770", + "dubbo.provider.host=127.0.0.1", + "dubbo.consumer.client=netty" + }) +@SpringBootTest(classes = {DubboAutoConfigurationOnSingleConfigTest.class}) @EnableAutoConfiguration public class DubboAutoConfigurationOnSingleConfigTest { @@ -105,28 +102,24 @@ public class DubboAutoConfigurationOnSingleConfigTest { public void testApplicationConfig() { Assert.assertEquals("dubbo-demo-application", applicationConfig.getName()); - } @Test public void testModuleConfig() { Assert.assertEquals("dubbo-demo-module", moduleConfig.getName()); - } @Test public void testRegistryConfig() { Assert.assertEquals("zookeeper://192.168.99.100:32770", registryConfig.getAddress()); - } @Test public void testMonitorConfig() { Assert.assertEquals("zookeeper://127.0.0.1:32770", monitorConfig.getAddress()); - } @Test @@ -134,20 +127,17 @@ public class DubboAutoConfigurationOnSingleConfigTest { Assert.assertEquals("dubbo", protocolConfig.getName()); Assert.assertEquals(Integer.valueOf(20880), protocolConfig.getPort()); - } @Test public void testProviderConfig() { Assert.assertEquals("127.0.0.1", providerConfig.getHost()); - } @Test public void testConsumerConfig() { Assert.assertEquals("netty", consumerConfig.getClient()); - } } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/RelaxedDubboConfigBinderTest.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/RelaxedDubboConfigBinderTest.java index aebfb95deb..d79c3b27c5 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/RelaxedDubboConfigBinderTest.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/RelaxedDubboConfigBinderTest.java @@ -21,6 +21,8 @@ import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; +import java.util.Map; + import com.alibaba.spring.context.config.ConfigurationBeanBinder; import org.junit.After; import org.junit.Assert; @@ -33,21 +35,20 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; -import java.util.Map; - import static com.alibaba.spring.util.PropertySourcesUtils.getSubProperties; /** * {@link RelaxedDubboConfigBinder} Test */ @RunWith(SpringRunner.class) -@TestPropertySource(properties = { - "dubbo.application.NAME=hello", - "dubbo.application.owneR=world", - "dubbo.registry.Address=10.20.153.17", - "dubbo.protocol.pORt=20881", - "dubbo.service.invoke.timeout=2000", -}) +@TestPropertySource( + properties = { + "dubbo.application.NAME=hello", + "dubbo.application.owneR=world", + "dubbo.registry.Address=10.20.153.17", + "dubbo.protocol.pORt=20881", + "dubbo.service.invoke.timeout=2000", + }) @ContextConfiguration(classes = RelaxedDubboConfigBinder.class) public class RelaxedDubboConfigBinderTest { @@ -78,13 +79,12 @@ public class RelaxedDubboConfigBinderTest { RegistryConfig registryConfig = new RegistryConfig(); properties = getSubProperties(environment.getPropertySources(), "dubbo.registry"); - dubboConfigBinder.bind(properties, true, true, registryConfig); + dubboConfigBinder.bind(properties, true, true, registryConfig); Assert.assertEquals("10.20.153.17", registryConfig.getAddress()); ProtocolConfig protocolConfig = new ProtocolConfig(); properties = getSubProperties(environment.getPropertySources(), "dubbo.protocol"); - dubboConfigBinder.bind(properties, true, true, protocolConfig); + dubboConfigBinder.bind(properties, true, true, protocolConfig); Assert.assertEquals(Integer.valueOf(20881), protocolConfig.getPort()); - } } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/context/event/AwaitingNonWebApplicationListenerTest.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/context/event/AwaitingNonWebApplicationListenerTest.java index 7975d4787b..6e4823ce1c 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/context/event/AwaitingNonWebApplicationListenerTest.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/context/event/AwaitingNonWebApplicationListenerTest.java @@ -36,34 +36,34 @@ public class AwaitingNonWebApplicationListenerTest { DubboBootstrap.reset(); } -// @Test -// public void init() { -// AtomicBoolean awaited = AwaitingNonWebApplicationListener.getAwaited(); -// awaited.set(false); -// } -// -// @Test -// public void testSingleContextNonWebApplication() { -// new SpringApplicationBuilder(Object.class) -// .web(false) -// .run() -// .close(); -// -// ShutdownHookCallbacks.INSTANCE.addCallback(() -> { -// AtomicBoolean awaited = AwaitingNonWebApplicationListener.getAwaited(); -// Assert.assertTrue(awaited.get()); -// System.out.println("Callback..."); -// }); -// } -// -// @Test -// public void testMultipleContextNonWebApplication() { -// new SpringApplicationBuilder(Object.class) -// .parent(Object.class) -// .web(false) -// .run().close(); -// AtomicBoolean awaited = AwaitingNonWebApplicationListener.getAwaited(); -// Assert.assertFalse(awaited.get()); -// } + // @Test + // public void init() { + // AtomicBoolean awaited = AwaitingNonWebApplicationListener.getAwaited(); + // awaited.set(false); + // } + // + // @Test + // public void testSingleContextNonWebApplication() { + // new SpringApplicationBuilder(Object.class) + // .web(false) + // .run() + // .close(); + // + // ShutdownHookCallbacks.INSTANCE.addCallback(() -> { + // AtomicBoolean awaited = AwaitingNonWebApplicationListener.getAwaited(); + // Assert.assertTrue(awaited.get()); + // System.out.println("Callback..."); + // }); + // } + // + // @Test + // public void testMultipleContextNonWebApplication() { + // new SpringApplicationBuilder(Object.class) + // .parent(Object.class) + // .web(false) + // .run().close(); + // AtomicBoolean awaited = AwaitingNonWebApplicationListener.getAwaited(); + // Assert.assertFalse(awaited.get()); + // } } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/context/event/DubboConfigBeanDefinitionConflictApplicationListenerTest.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/context/event/DubboConfigBeanDefinitionConflictApplicationListenerTest.java index 70f5e573d3..635b9f2b52 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/context/event/DubboConfigBeanDefinitionConflictApplicationListenerTest.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/context/event/DubboConfigBeanDefinitionConflictApplicationListenerTest.java @@ -20,6 +20,8 @@ import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig; +import java.util.Map; + import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -28,9 +30,6 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.PropertySource; -import java.util.Map; - - /** * {@link DubboConfigBeanDefinitionConflictApplicationListener} Test * @@ -41,16 +40,15 @@ public class DubboConfigBeanDefinitionConflictApplicationListenerTest { @Before public void init() { DubboBootstrap.reset(); - //context.addApplicationListener(new DubboConfigBeanDefinitionConflictApplicationListener()); + // context.addApplicationListener(new DubboConfigBeanDefinitionConflictApplicationListener()); } @After public void destroy() { DubboBootstrap.reset(); - } - //@Test + // @Test public void testNormalCase() { System.setProperty("dubbo.application.name", "test-dubbo-application"); @@ -71,7 +69,8 @@ public class DubboConfigBeanDefinitionConflictApplicationListenerTest { @Test public void testDuplicatedConfigsCase() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PropertySourceConfig.class, DubboConfig.class, XmlConfig.class); + AnnotationConfigApplicationContext context = + new AnnotationConfigApplicationContext(PropertySourceConfig.class, DubboConfig.class, XmlConfig.class); try { context.start(); @@ -89,16 +88,11 @@ public class DubboConfigBeanDefinitionConflictApplicationListenerTest { } @EnableDubboConfig - static class DubboConfig { - - } + static class DubboConfig {} @PropertySource("classpath:/META-INF/dubbo.properties") - static class PropertySourceConfig { - - } + static class PropertySourceConfig {} @ImportResource("classpath:/META-INF/spring/dubbo-context.xml") - static class XmlConfig { - } + static class XmlConfig {} } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/context/event/WelcomeLogoApplicationListenerTest.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/context/event/WelcomeLogoApplicationListenerTest.java index c006a7553e..893ed17e0e 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/context/event/WelcomeLogoApplicationListenerTest.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/context/event/WelcomeLogoApplicationListenerTest.java @@ -30,9 +30,7 @@ import org.springframework.test.context.junit4.SpringRunner; * @since 2.7.0 */ @RunWith(SpringRunner.class) -@SpringBootTest( - classes = {WelcomeLogoApplicationListener.class} -) +@SpringBootTest(classes = {WelcomeLogoApplicationListener.class}) public class WelcomeLogoApplicationListenerTest { @Autowired @@ -42,7 +40,5 @@ public class WelcomeLogoApplicationListenerTest { public void testOnApplicationEvent() { Assert.assertNotNull(welcomeLogoApplicationListener.buildBannerText()); - } - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/env/DubboDefaultPropertiesEnvironmentPostProcessorTest.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/env/DubboDefaultPropertiesEnvironmentPostProcessorTest.java index 56642875d2..b17c1af634 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/env/DubboDefaultPropertiesEnvironmentPostProcessorTest.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/env/DubboDefaultPropertiesEnvironmentPostProcessorTest.java @@ -16,6 +16,8 @@ */ package org.apache.dubbo.spring.boot.env; +import java.util.HashMap; + import org.junit.Assert; import org.junit.Test; import org.springframework.boot.SpringApplication; @@ -25,8 +27,6 @@ import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource; import org.springframework.mock.env.MockEnvironment; -import java.util.HashMap; - /** * {@link DubboDefaultPropertiesEnvironmentPostProcessor} Test */ diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/util/DubboUtilsTest.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/util/DubboUtilsTest.java index bbcb245081..b7598d0313 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/util/DubboUtilsTest.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/util/DubboUtilsTest.java @@ -78,8 +78,5 @@ public class DubboUtilsTest { Assert.assertTrue(DEFAULT_MULTIPLE_CONFIG_PROPERTY_VALUE); Assert.assertTrue(DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE); - - } - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/metadata/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-compatible/metadata/pom.xml index ff56b943b4..d27b64c9a0 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/metadata/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/metadata/pom.xml @@ -15,173 +15,171 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - org.apache.dubbo - dubbo-spring-boot-compatible - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-spring-boot-compatible + ${revision} + ../pom.xml + - dubbo-spring-boot-configuration-metadata-compatible + dubbo-spring-boot-configuration-metadata-compatible - - true - ${project.build.directory}/generated-sources/java - + + true + ${project.build.directory}/generated-sources/java + - - - org.slf4j - slf4j-api - true - - - log4j - log4j - true - - - org.apache.logging.log4j - log4j-api - true - - - org.apache.logging.log4j - log4j-core - true - - - org.springframework.boot - spring-boot-autoconfigure - true - - - org.apache.dubbo - dubbo-common - ${project.version} - true - + + + org.slf4j + slf4j-api + true + + + log4j + log4j + true + + + org.apache.logging.log4j + log4j-api + true + + + org.apache.logging.log4j + log4j-core + true + + + org.springframework.boot + spring-boot-autoconfigure + true + + + org.apache.dubbo + dubbo-common + ${project.version} + true + - - org.springframework.boot - spring-boot-configuration-processor - true - - + + org.springframework.boot + spring-boot-configuration-processor + true + + - - - - org.apache.maven.plugins - maven-antrun-plugin - - - get-version-infos - none - - - copy-sources - process-sources - - run - - - - - - - - - - - - - - - - - - - - - - - - clean-sources - compile - - run - - - - - - - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - add-source - generate-sources - - add-source - - - - ${sources_directory} - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - only - - - - maven-surefire-plugin - - true - - - - maven-javadoc-plugin - - true - - - - maven-jar-plugin - - - default-jar - none - - - - - maven-install-plugin - - true - - - - maven-source-plugin - - true - - - - + + + + org.apache.maven.plugins + maven-antrun-plugin + + + get-version-infos + none + + + copy-sources + + run + + process-sources + + + + + + + + + + + + + + + + + + + + + + + clean-sources + + run + + compile + + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add-source + + add-source + + generate-sources + + + ${sources_directory} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + only + + + + maven-surefire-plugin + + true + + + + maven-javadoc-plugin + + true + + + + maven-jar-plugin + + + default-jar + none + + + + + maven-install-plugin + + true + + + + maven-source-plugin + + true + + + + diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/metadata/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboMetadataGenerateAutoConfiguration.java b/dubbo-spring-boot/dubbo-spring-boot-compatible/metadata/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboMetadataGenerateAutoConfiguration.java index 2b4f208a00..8f61844e8e 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/metadata/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboMetadataGenerateAutoConfiguration.java +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/metadata/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/DubboMetadataGenerateAutoConfiguration.java @@ -21,5 +21,4 @@ import org.springframework.context.annotation.Configuration; @Configuration @EnableConfigurationProperties(DubboConfigurationProperties.class) -public class DubboMetadataGenerateAutoConfiguration { -} +public class DubboMetadataGenerateAutoConfiguration {} diff --git a/dubbo-spring-boot/dubbo-spring-boot-compatible/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-compatible/pom.xml index 926e7b27b0..1285023d5b 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-compatible/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-compatible/pom.xml @@ -15,68 +15,65 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - org.apache.dubbo - dubbo-spring-boot - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-spring-boot + ${revision} + ../pom.xml + - dubbo-spring-boot-compatible - pom - Apache Dubbo Spring Boot Compatible for Spring Boot 1.x + dubbo-spring-boot-compatible + pom + Apache Dubbo Spring Boot Compatible for Spring Boot 1.x - - 1.5.22.RELEASE - + + autoconfigure + actuator + metadata + - - autoconfigure - actuator - metadata - + + 1.5.22.RELEASE + - + - - - spring-boot-1.4 - - 1.4.7.RELEASE - - - - jdk15ge-simple - - [15, - - - - - org.apache.maven.plugins - maven-surefire-plugin - - true - 1 - false - ${argline} ${jacocoArgLine} + + + spring-boot-1.4 + + 1.4.7.RELEASE + + + + jdk15ge-simple + + [15, + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + 1 + false + ${argline} ${jacocoArgLine} --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.math=ALL-UNNAMED - --add-opens java.base/java.util=ALL-UNNAMED - - - - - - - - - - - - + --add-opens java.base/java.util=ALL-UNNAMED + + + + + + + + + + + diff --git a/dubbo-spring-boot/dubbo-spring-boot-interceptor/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-interceptor/pom.xml index f173ad97be..6585f611e4 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-interceptor/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-interceptor/pom.xml @@ -15,38 +15,37 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - org.apache.dubbo - dubbo-spring-boot - ${revision} - ../pom.xml - - jar - 4.0.0 - dubbo-spring-boot-interceptor - Apache Dubbo Spring Boot Interceptor + + 4.0.0 + + org.apache.dubbo + dubbo-spring-boot + ${revision} + ../pom.xml + + dubbo-spring-boot-interceptor + jar + Apache Dubbo Spring Boot Interceptor - - - - org.apache.dubbo - dubbo - ${project.version} - - - org.apache.dubbo - dubbo-common - ${project.version} - true - - - - org.springframework.boot - spring-boot-starter-web - true - - + + + + org.apache.dubbo + dubbo + ${project.version} + + + org.apache.dubbo + dubbo-common + ${project.version} + true + + + + org.springframework.boot + spring-boot-starter-web + true + + diff --git a/dubbo-spring-boot/dubbo-spring-boot-interceptor/src/main/java/org/apache/dubbo/spring/boot/interceptor/DubboTagCookieInterceptor.java b/dubbo-spring-boot/dubbo-spring-boot-interceptor/src/main/java/org/apache/dubbo/spring/boot/interceptor/DubboTagCookieInterceptor.java index ad91025c5f..ec76e3c8b0 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-interceptor/src/main/java/org/apache/dubbo/spring/boot/interceptor/DubboTagCookieInterceptor.java +++ b/dubbo-spring-boot/dubbo-spring-boot-interceptor/src/main/java/org/apache/dubbo/spring/boot/interceptor/DubboTagCookieInterceptor.java @@ -18,36 +18,38 @@ package org.apache.dubbo.spring.boot.interceptor; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.rpc.RpcContext; -import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.springframework.web.servlet.HandlerInterceptor; + public class DubboTagCookieInterceptor implements HandlerInterceptor { @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { String tag = getSingleCookieValue(request.getCookies(), CommonConstants.TAG_KEY); - RpcContext.getClientAttachment().setAttachment(CommonConstants.TAG_KEY,tag); + RpcContext.getClientAttachment().setAttachment(CommonConstants.TAG_KEY, tag); return true; } @Override - public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) + throws Exception { RpcContext.getClientAttachment().removeAttachment(CommonConstants.TAG_KEY); } - private static String getSingleCookieValue(Cookie[] cookies, String name){ + private static String getSingleCookieValue(Cookie[] cookies, String name) { if (cookies == null || cookies.length == 0) { return null; } - for (Cookie cookie: cookies) { + for (Cookie cookie : cookies) { if (name.equals(cookie.getName())) { return cookie.getValue(); } } return null; } - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-interceptor/src/main/java/org/apache/dubbo/spring/boot/interceptor/DubboTagHeaderOrParameterInterceptor.java b/dubbo-spring-boot/dubbo-spring-boot-interceptor/src/main/java/org/apache/dubbo/spring/boot/interceptor/DubboTagHeaderOrParameterInterceptor.java index df6a614f4e..298c563b3e 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-interceptor/src/main/java/org/apache/dubbo/spring/boot/interceptor/DubboTagHeaderOrParameterInterceptor.java +++ b/dubbo-spring-boot/dubbo-spring-boot-interceptor/src/main/java/org/apache/dubbo/spring/boot/interceptor/DubboTagHeaderOrParameterInterceptor.java @@ -18,15 +18,17 @@ package org.apache.dubbo.spring.boot.interceptor; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.rpc.RpcContext; -import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.springframework.web.servlet.HandlerInterceptor; + public class DubboTagHeaderOrParameterInterceptor implements HandlerInterceptor { @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { String tag = request.getHeader(CommonConstants.DUBBO_TAG_HEADER); if (tag == null) { tag = request.getParameter(CommonConstants.TAG_KEY); @@ -38,8 +40,8 @@ public class DubboTagHeaderOrParameterInterceptor implements HandlerInterceptor } @Override - public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) + throws Exception { RpcContext.getClientAttachment().removeAttachment(CommonConstants.TAG_KEY); } - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-starter/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-starter/pom.xml index 64b5b20766..7abb4ce74f 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starter/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starter/pom.xml @@ -15,34 +15,32 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - org.apache.dubbo - dubbo-spring-boot - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-spring-boot + ${revision} + ../pom.xml + - dubbo-spring-boot-starter - jar - Apache Dubbo Spring Boot Starter + dubbo-spring-boot-starter + jar + Apache Dubbo Spring Boot Starter - - - - org.springframework.boot - spring-boot-starter - true - + + + + org.springframework.boot + spring-boot-starter + true + - - org.apache.dubbo - dubbo-spring-boot-autoconfigure - ${project.version} - + + org.apache.dubbo + dubbo-spring-boot-autoconfigure + ${project.version} + - + diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-nacos-spring-boot-starter/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-nacos-spring-boot-starter/pom.xml index 7f4df2957a..49ea3b67be 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-nacos-spring-boot-starter/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-nacos-spring-boot-starter/pom.xml @@ -15,30 +15,27 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - - - org.apache.dubbo - dubbo-spring-boot-starters - ${revision} - ../pom.xml - - 4.0.0 - - dubbo-nacos-spring-boot-starter + + 4.0.0 + + org.apache.dubbo + dubbo-spring-boot-starters ${revision} - jar - Apache Dubbo Nacos Spring Boot Starter + ../pom.xml + - - + dubbo-nacos-spring-boot-starter + ${revision} + jar + Apache Dubbo Nacos Spring Boot Starter - - - com.alibaba.nacos - nacos-client - - + - \ No newline at end of file + + + com.alibaba.nacos + nacos-client + + + + diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-seata-spring-boot-starter/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-seata-spring-boot-starter/pom.xml index c5b089d42b..c1c7645329 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-seata-spring-boot-starter/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-seata-spring-boot-starter/pom.xml @@ -15,42 +15,39 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - - 4.0.0 - - org.apache.dubbo - dubbo-spring-boot-starters - ${revision} - ../pom.xml - - - dubbo-seata-spring-boot-starter + + 4.0.0 + + org.apache.dubbo + dubbo-spring-boot-starters ${revision} - jar - Apache Dubbo Seata Spring Boot Starter + ../pom.xml + - - + dubbo-seata-spring-boot-starter + ${revision} + jar + Apache Dubbo Seata Spring Boot Starter - - - - io.seata - seata-spring-boot-starter - - - io.seata - seata-core - - - + - - io.seata - seata-core - - + + + + io.seata + seata-spring-boot-starter + + + io.seata + seata-core + + + - \ No newline at end of file + + io.seata + seata-core + + + + diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-sentinel-spring-boot-starter/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-sentinel-spring-boot-starter/pom.xml index 0e6dfd5c9d..95fda16704 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-sentinel-spring-boot-starter/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-sentinel-spring-boot-starter/pom.xml @@ -15,34 +15,31 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - - 4.0.0 - - org.apache.dubbo - dubbo-spring-boot-starters - ${revision} - ../pom.xml - - - dubbo-sentinel-spring-boot-starter + + 4.0.0 + + org.apache.dubbo + dubbo-spring-boot-starters ${revision} - jar - Apache Dubbo Sentinel Spring Boot Starter + ../pom.xml + - - + dubbo-sentinel-spring-boot-starter + ${revision} + jar + Apache Dubbo Sentinel Spring Boot Starter - - - com.alibaba.csp - sentinel-apache-dubbo3-adapter - - - com.alibaba.csp - sentinel-transport-simple-http - - + - \ No newline at end of file + + + com.alibaba.csp + sentinel-apache-dubbo3-adapter + + + com.alibaba.csp + sentinel-transport-simple-http + + + + diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-zookeeper-curator5-spring-boot-starter/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-zookeeper-curator5-spring-boot-starter/pom.xml index 3c933c8a81..ee3b69fe9a 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-zookeeper-curator5-spring-boot-starter/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-zookeeper-curator5-spring-boot-starter/pom.xml @@ -15,49 +15,47 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - - - org.apache.dubbo - dubbo-spring-boot-starters - ${revision} - ../pom.xml - - 4.0.0 - - dubbo-zookeeper-curator5-spring-boot-starter + + 4.0.0 + + org.apache.dubbo + dubbo-spring-boot-starters ${revision} - jar - Apache Dubbo Zookeeper Curator5 Spring Boot Starter + ../pom.xml + - - 5.1.0 - 3.8.3 - + dubbo-zookeeper-curator5-spring-boot-starter + ${revision} + jar + Apache Dubbo Zookeeper Curator5 Spring Boot Starter - - - - org.apache.zookeeper - parent - ${zookeeper_version} - pom - import - - - + + 5.1.0 + 3.8.3 + + - - org.apache.curator - curator-x-discovery - ${curator5_version} - - - org.apache.zookeeper - zookeeper - ${zookeeper_version} - + + org.apache.zookeeper + parent + ${zookeeper_version} + pom + import + + + + + + org.apache.curator + curator-x-discovery + ${curator5_version} + + + org.apache.zookeeper + zookeeper + ${zookeeper_version} + + diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-zookeeper-spring-boot-starter/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-zookeeper-spring-boot-starter/pom.xml index 31cf4d47e0..ca4350360f 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-zookeeper-spring-boot-starter/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/dubbo-zookeeper-spring-boot-starter/pom.xml @@ -15,36 +15,34 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - - 4.0.0 - - org.apache.dubbo - dubbo-spring-boot-starters - ${revision} - ../pom.xml - - - dubbo-zookeeper-spring-boot-starter + + 4.0.0 + + org.apache.dubbo + dubbo-spring-boot-starters ${revision} - jar - Apache Dubbo Zookeeper Spring Boot Starter + ../pom.xml + - - 3.8.3 - + dubbo-zookeeper-spring-boot-starter + ${revision} + jar + Apache Dubbo Zookeeper Spring Boot Starter - - - org.apache.curator - curator-x-discovery - - - org.apache.zookeeper - zookeeper - ${zookeeper_version} - - + + 3.8.3 + + + + + org.apache.curator + curator-x-discovery + + + org.apache.zookeeper + zookeeper + ${zookeeper_version} + + diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/pom.xml index dcbf52ba40..860e286be1 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/pom.xml @@ -15,144 +15,142 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - dubbo-observability-spring-boot-starters - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-observability-spring-boot-starters + ${revision} + ../pom.xml + - dubbo-observability-spring-boot-autoconfigure + dubbo-observability-spring-boot-autoconfigure - - - - io.micrometer - micrometer-tracing - - - io.micrometer - micrometer-observation - - - io.micrometer - micrometer-core - - - io.micrometer - micrometer-registry-prometheus - - - com.tdunning - t-digest - + + + + io.micrometer + micrometer-tracing + + + io.micrometer + micrometer-observation + + + io.micrometer + micrometer-core + + + io.micrometer + micrometer-registry-prometheus + + + com.tdunning + t-digest + - - - org.springframework.boot - spring-boot-autoconfigure - true - - - org.springframework.boot - spring-boot-configuration-processor - true - - - org.springframework - spring-webmvc - true - - - org.springframework - spring-webflux - true - - - org.springframework.boot - spring-boot-test - test - - - org.assertj - assertj-core - test - + + + org.springframework.boot + spring-boot-autoconfigure + true + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.springframework + spring-webmvc + true + + + org.springframework + spring-webflux + true + + + org.springframework.boot + spring-boot-test + test + + + org.assertj + assertj-core + test + - - - io.micrometer - micrometer-tracing-bridge-otel - true - - - io.micrometer - micrometer-tracing-bridge-brave - true - + + + io.micrometer + micrometer-tracing-bridge-otel + true + + + io.micrometer + micrometer-tracing-bridge-brave + true + - - - io.opentelemetry - opentelemetry-exporter-zipkin - true - - - io.opentelemetry - opentelemetry-exporter-otlp - true - - - io.zipkin.reporter2 - zipkin-reporter-brave - true - + + + io.opentelemetry + opentelemetry-exporter-zipkin + true + + + io.opentelemetry + opentelemetry-exporter-otlp + true + + + io.zipkin.reporter2 + zipkin-reporter-brave + true + - - - io.zipkin.reporter2 - zipkin-sender-urlconnection - true - + + + io.zipkin.reporter2 + zipkin-sender-urlconnection + true + - - - org.apache.dubbo - dubbo-common - ${project.version} - true - - - org.apache.dubbo - dubbo-spring-boot-starter - ${project.version} - - - org.apache.dubbo - dubbo-qos - ${project.version} - true - - - org.apache.dubbo - dubbo-config-spring - ${project.version} - true - + + + org.apache.dubbo + dubbo-common + ${project.version} + true + + + org.apache.dubbo + dubbo-spring-boot-starter + ${project.version} + + + org.apache.dubbo + dubbo-qos + ${project.version} + true + + + org.apache.dubbo + dubbo-config-spring + ${project.version} + true + - - - io.prometheus - simpleclient - - - io.prometheus - simpleclient_pushgateway - - + + + io.prometheus + simpleclient + + + io.prometheus + simpleclient_pushgateway + + - \ No newline at end of file + diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/DubboMicrometerTracingAutoConfiguration.java b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/DubboMicrometerTracingAutoConfiguration.java index 4c8adef1e3..f864906d31 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/DubboMicrometerTracingAutoConfiguration.java +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/DubboMicrometerTracingAutoConfiguration.java @@ -30,7 +30,12 @@ import org.springframework.core.annotation.Order; * this class is available starting from Boot 3.0. It's not available if you're using Boot < 3.0 */ @ConditionalOnDubboTracingEnable -@ConditionalOnClass(name = {"io.micrometer.observation.Observation", "io.micrometer.tracing.Tracer", "io.micrometer.tracing.propagation.Propagator"}) +@ConditionalOnClass( + name = { + "io.micrometer.observation.Observation", + "io.micrometer.tracing.Tracer", + "io.micrometer.tracing.propagation.Propagator" + }) @AutoConfigureAfter(name = "org.springframework.boot.actuate.autoconfigure.tracing.MicrometerTracingAutoConfiguration") public class DubboMicrometerTracingAutoConfiguration { @@ -49,7 +54,8 @@ public class DubboMicrometerTracingAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnBean(io.micrometer.tracing.Tracer.class) - public io.micrometer.tracing.handler.DefaultTracingObservationHandler defaultTracingObservationHandler(io.micrometer.tracing.Tracer tracer) { + public io.micrometer.tracing.handler.DefaultTracingObservationHandler defaultTracingObservationHandler( + io.micrometer.tracing.Tracer tracer) { return new io.micrometer.tracing.handler.DefaultTracingObservationHandler(tracer); } @@ -57,8 +63,9 @@ public class DubboMicrometerTracingAutoConfiguration { @ConditionalOnMissingBean @ConditionalOnBean({io.micrometer.tracing.Tracer.class, io.micrometer.tracing.propagation.Propagator.class}) @Order(SENDER_TRACING_OBSERVATION_HANDLER_ORDER) - public io.micrometer.tracing.handler.PropagatingSenderTracingObservationHandler propagatingSenderTracingObservationHandler(io.micrometer.tracing.Tracer tracer, - io.micrometer.tracing.propagation.Propagator propagator) { + public io.micrometer.tracing.handler.PropagatingSenderTracingObservationHandler + propagatingSenderTracingObservationHandler( + io.micrometer.tracing.Tracer tracer, io.micrometer.tracing.propagation.Propagator propagator) { return new io.micrometer.tracing.handler.PropagatingSenderTracingObservationHandler<>(tracer, propagator); } @@ -66,9 +73,9 @@ public class DubboMicrometerTracingAutoConfiguration { @ConditionalOnMissingBean @ConditionalOnBean({io.micrometer.tracing.Tracer.class, io.micrometer.tracing.propagation.Propagator.class}) @Order(RECEIVER_TRACING_OBSERVATION_HANDLER_ORDER) - public io.micrometer.tracing.handler.PropagatingReceiverTracingObservationHandler propagatingReceiverTracingObservationHandler(io.micrometer.tracing.Tracer tracer, - io.micrometer.tracing.propagation.Propagator propagator) { + public io.micrometer.tracing.handler.PropagatingReceiverTracingObservationHandler + propagatingReceiverTracingObservationHandler( + io.micrometer.tracing.Tracer tracer, io.micrometer.tracing.propagation.Propagator propagator) { return new io.micrometer.tracing.handler.PropagatingReceiverTracingObservationHandler<>(tracer, propagator); } - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/DubboObservationAutoConfiguration.java b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/DubboObservationAutoConfiguration.java index 10ffaa9be1..a2524e9e01 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/DubboObservationAutoConfiguration.java +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/DubboObservationAutoConfiguration.java @@ -23,6 +23,8 @@ import org.apache.dubbo.qos.protocol.QosProtocolWrapper; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.spring.boot.observability.autoconfigure.annotation.ConditionalOnDubboTracingEnable; +import java.util.Arrays; + import io.micrometer.core.instrument.MeterRegistry; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; @@ -39,19 +41,19 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; -import java.util.Arrays; - /** * Register observationRegistry to ApplicationModel. * Create observationRegistry when you are using Boot <3.0 or you are not using spring-boot-starter-actuator */ -@AutoConfiguration(after = DubboMicrometerTracingAutoConfiguration.class, afterName = "org.springframework.boot.actuate.autoconfigure.observation.ObservationAutoConfiguration") +@AutoConfiguration( + after = DubboMicrometerTracingAutoConfiguration.class, + afterName = "org.springframework.boot.actuate.autoconfigure.observation.ObservationAutoConfiguration") @ConditionalOnDubboTracingEnable @ConditionalOnClass(name = {"io.micrometer.observation.Observation", "io.micrometer.tracing.Tracer"}) -public class DubboObservationAutoConfiguration implements BeanFactoryAware, ApplicationListener, Ordered { +public class DubboObservationAutoConfiguration + implements BeanFactoryAware, ApplicationListener, Ordered { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(QosProtocolWrapper.class); - public DubboObservationAutoConfiguration(ApplicationModel applicationModel) { this.applicationModel = applicationModel; } @@ -68,10 +70,12 @@ public class DubboObservationAutoConfiguration implements BeanFactoryAware, Appl } @Bean - @ConditionalOnMissingBean(type = "org.springframework.boot.actuate.autoconfigure.observation.ObservationRegistryPostProcessor") + @ConditionalOnMissingBean( + type = "org.springframework.boot.actuate.autoconfigure.observation.ObservationRegistryPostProcessor") @ConditionalOnClass(name = "io.micrometer.observation.ObservationHandler") - public ObservationRegistryPostProcessor dubboObservationRegistryPostProcessor(ObjectProvider observationHandlerGrouping, - ObjectProvider> observationHandlers) { + public ObservationRegistryPostProcessor dubboObservationRegistryPostProcessor( + ObjectProvider observationHandlerGrouping, + ObjectProvider> observationHandlers) { return new ObservationRegistryPostProcessor(observationHandlerGrouping, observationHandlers); } @@ -83,9 +87,13 @@ public class DubboObservationAutoConfiguration implements BeanFactoryAware, Appl @Override public void onApplicationEvent(DubboConfigInitEvent event) { try { - applicationModel.getBeanFactory().registerBean(beanFactory.getBean(io.micrometer.observation.ObservationRegistry.class)); + applicationModel + .getBeanFactory() + .registerBean(beanFactory.getBean(io.micrometer.observation.ObservationRegistry.class)); applicationModel.getBeanFactory().registerBean(beanFactory.getBean(io.micrometer.tracing.Tracer.class)); - applicationModel.getBeanFactory().registerBean(beanFactory.getBean(io.micrometer.tracing.propagation.Propagator.class)); + applicationModel + .getBeanFactory() + .registerBean(beanFactory.getBean(io.micrometer.tracing.propagation.Propagator.class)); } catch (NoSuchBeanDefinitionException e) { logger.info("Please use a version of micrometer higher than 1.10.0: " + e.getMessage()); } @@ -99,21 +107,23 @@ public class DubboObservationAutoConfiguration implements BeanFactoryAware, Appl @Configuration(proxyBeanMethods = false) @ConditionalOnClass(MeterRegistry.class) @ConditionalOnMissingClass("io.micrometer.tracing.Tracer") - @ConditionalOnMissingBean(type = "org.springframework.boot.actuate.autoconfigure.observation.ObservationRegistryPostProcessor") + @ConditionalOnMissingBean( + type = "org.springframework.boot.actuate.autoconfigure.observation.ObservationRegistryPostProcessor") static class OnlyMetricsConfiguration { @Bean @ConditionalOnClass(name = "io.micrometer.core.instrument.observation.MeterObservationHandler") ObservationHandlerGrouping metricsObservationHandlerGrouping() { - return new ObservationHandlerGrouping(io.micrometer.core.instrument.observation.MeterObservationHandler.class); + return new ObservationHandlerGrouping( + io.micrometer.core.instrument.observation.MeterObservationHandler.class); } - } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(io.micrometer.tracing.Tracer.class) @ConditionalOnMissingClass("io.micrometer.core.instrument.MeterRegistry") - @ConditionalOnMissingBean(type = "org.springframework.boot.actuate.autoconfigure.observation.ObservationRegistryPostProcessor") + @ConditionalOnMissingBean( + type = "org.springframework.boot.actuate.autoconfigure.observation.ObservationRegistryPostProcessor") static class OnlyTracingConfiguration { @Bean @@ -121,21 +131,25 @@ public class DubboObservationAutoConfiguration implements BeanFactoryAware, Appl ObservationHandlerGrouping tracingObservationHandlerGrouping() { return new ObservationHandlerGrouping(io.micrometer.tracing.handler.TracingObservationHandler.class); } - } @Configuration(proxyBeanMethods = false) @ConditionalOnClass({MeterRegistry.class, io.micrometer.tracing.Tracer.class}) - @ConditionalOnMissingBean(type = "org.springframework.boot.actuate.autoconfigure.observation.ObservationRegistryPostProcessor") + @ConditionalOnMissingBean( + type = "org.springframework.boot.actuate.autoconfigure.observation.ObservationRegistryPostProcessor") static class MetricsWithTracingConfiguration { @Bean - @ConditionalOnClass(name = {"io.micrometer.tracing.handler.TracingObservationHandler", "io.micrometer.core.instrument.observation.MeterObservationHandler"}) + @ConditionalOnClass( + name = { + "io.micrometer.tracing.handler.TracingObservationHandler", + "io.micrometer.core.instrument.observation.MeterObservationHandler" + }) ObservationHandlerGrouping metricsAndTracingObservationHandlerGrouping() { - return new ObservationHandlerGrouping( - Arrays.asList(io.micrometer.tracing.handler.TracingObservationHandler.class, io.micrometer.core.instrument.observation.MeterObservationHandler.class)); + return new ObservationHandlerGrouping(Arrays.asList( + io.micrometer.tracing.handler.TracingObservationHandler.class, + io.micrometer.core.instrument.observation.MeterObservationHandler.class)); } - } @Configuration(proxyBeanMethods = false) @@ -149,10 +163,10 @@ public class DubboObservationAutoConfiguration implements BeanFactoryAware, Appl @Bean @ConditionalOnClass(name = {"io.micrometer.core.instrument.observation.DefaultMeterObservationHandler"}) - io.micrometer.core.instrument.observation.DefaultMeterObservationHandler defaultMeterObservationHandler(MeterRegistry meterRegistry) { + io.micrometer.core.instrument.observation.DefaultMeterObservationHandler defaultMeterObservationHandler( + MeterRegistry meterRegistry) { return new io.micrometer.core.instrument.observation.DefaultMeterObservationHandler(meterRegistry); } - } @ConditionalOnBean(io.micrometer.tracing.Tracer.class) @@ -160,14 +174,19 @@ public class DubboObservationAutoConfiguration implements BeanFactoryAware, Appl static class TracingAndMetricsObservationHandlerConfiguration { @Bean - @ConditionalOnClass(name = {"io.micrometer.tracing.handler.TracingAwareMeterObservationHandler", "io.micrometer.tracing.Tracer"}) - io.micrometer.tracing.handler.TracingAwareMeterObservationHandler tracingAwareMeterObservationHandler( - MeterRegistry meterRegistry, io.micrometer.tracing.Tracer tracer) { - io.micrometer.core.instrument.observation.DefaultMeterObservationHandler delegate = new io.micrometer.core.instrument.observation.DefaultMeterObservationHandler(meterRegistry); + @ConditionalOnClass( + name = { + "io.micrometer.tracing.handler.TracingAwareMeterObservationHandler", + "io.micrometer.tracing.Tracer" + }) + io.micrometer.tracing.handler.TracingAwareMeterObservationHandler< + io.micrometer.observation.Observation.Context> + tracingAwareMeterObservationHandler( + MeterRegistry meterRegistry, io.micrometer.tracing.Tracer tracer) { + io.micrometer.core.instrument.observation.DefaultMeterObservationHandler delegate = + new io.micrometer.core.instrument.observation.DefaultMeterObservationHandler(meterRegistry); return new io.micrometer.tracing.handler.TracingAwareMeterObservationHandler<>(delegate, tracer); } - } - } } diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/ObservabilityUtils.java b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/ObservabilityUtils.java index 0c774d700a..c4298d879d 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/ObservabilityUtils.java +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/ObservabilityUtils.java @@ -28,15 +28,20 @@ public class ObservabilityUtils { public static final String DUBBO_TRACING_PREFIX = DUBBO_PREFIX + PROPERTY_NAME_SEPARATOR + "tracing"; - public static final String DUBBO_TRACING_PROPAGATION = DUBBO_TRACING_PREFIX + PROPERTY_NAME_SEPARATOR + "propagation"; + public static final String DUBBO_TRACING_PROPAGATION = + DUBBO_TRACING_PREFIX + PROPERTY_NAME_SEPARATOR + "propagation"; public static final String DUBBO_TRACING_BAGGAGE = DUBBO_TRACING_PREFIX + PROPERTY_NAME_SEPARATOR + "baggage"; - public static final String DUBBO_TRACING_BAGGAGE_CORRELATION = DUBBO_TRACING_BAGGAGE + PROPERTY_NAME_SEPARATOR + "correlation"; + public static final String DUBBO_TRACING_BAGGAGE_CORRELATION = + DUBBO_TRACING_BAGGAGE + PROPERTY_NAME_SEPARATOR + "correlation"; - public static final String DUBBO_TRACING_BAGGAGE_ENABLED = DUBBO_TRACING_BAGGAGE + PROPERTY_NAME_SEPARATOR + "enabled"; + public static final String DUBBO_TRACING_BAGGAGE_ENABLED = + DUBBO_TRACING_BAGGAGE + PROPERTY_NAME_SEPARATOR + "enabled"; - public static final String DUBBO_TRACING_ZIPKIN_CONFIG_PREFIX = DUBBO_TRACING_PREFIX + PROPERTY_NAME_SEPARATOR + "tracing-exporter.zipkin-config"; + public static final String DUBBO_TRACING_ZIPKIN_CONFIG_PREFIX = + DUBBO_TRACING_PREFIX + PROPERTY_NAME_SEPARATOR + "tracing-exporter.zipkin-config"; - public static final String DUBBO_TRACING_OTLP_CONFIG_PREFIX = DUBBO_TRACING_PREFIX + PROPERTY_NAME_SEPARATOR + "tracing-exporter.otlp-config"; + public static final String DUBBO_TRACING_OTLP_CONFIG_PREFIX = + DUBBO_TRACING_PREFIX + PROPERTY_NAME_SEPARATOR + "tracing-exporter.otlp-config"; } diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/ObservationHandlerGrouping.java b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/ObservationHandlerGrouping.java index 1c3df96886..d2d1820352 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/ObservationHandlerGrouping.java +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/ObservationHandlerGrouping.java @@ -16,15 +16,15 @@ */ package org.apache.dubbo.spring.boot.observability.autoconfigure; +import java.util.Collections; +import java.util.List; + import io.micrometer.observation.ObservationHandler; import io.micrometer.observation.ObservationRegistry; import org.springframework.util.CollectionUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import java.util.Collections; -import java.util.List; - /** * Groups {@link ObservationHandler ObservationHandlers} by type. * copy from {@link org.springframework.boot.actuate.autoconfigure.observation.ObservationHandlerGrouping} @@ -45,7 +45,8 @@ class ObservationHandlerGrouping { } void apply(List> handlers, ObservationRegistry.ObservationConfig config) { - MultiValueMap, ObservationHandler> groupings = new LinkedMultiValueMap<>(); + MultiValueMap, ObservationHandler> groupings = + new LinkedMultiValueMap<>(); for (ObservationHandler handler : handlers) { Class category = findCategory(handler); if (category != null) { @@ -57,7 +58,8 @@ class ObservationHandlerGrouping { for (Class category : this.categories) { List> handlerGroup = groupings.get(category); if (!CollectionUtils.isEmpty(handlerGroup)) { - config.observationHandler(new ObservationHandler.FirstMatchingCompositeObservationHandler(handlerGroup)); + config.observationHandler( + new ObservationHandler.FirstMatchingCompositeObservationHandler(handlerGroup)); } } } @@ -70,5 +72,4 @@ class ObservationHandlerGrouping { } return null; } - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/ObservationRegistryPostProcessor.java b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/ObservationRegistryPostProcessor.java index 1d315c2b9a..1330827601 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/ObservationRegistryPostProcessor.java +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/ObservationRegistryPostProcessor.java @@ -16,15 +16,15 @@ */ package org.apache.dubbo.spring.boot.observability.autoconfigure; +import java.util.List; +import java.util.stream.Collectors; + import io.micrometer.observation.ObservationHandler; import io.micrometer.observation.ObservationRegistry; import org.springframework.beans.BeansException; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.config.BeanPostProcessor; -import java.util.List; -import java.util.stream.Collectors; - /** * registry observationHandlers to observationConfig */ @@ -32,11 +32,11 @@ public class ObservationRegistryPostProcessor implements BeanPostProcessor { private final ObjectProvider observationHandlerGrouping; private final ObjectProvider> observationHandlers; - public ObservationRegistryPostProcessor(ObjectProvider observationHandlerGrouping, - ObjectProvider> observationHandlers) { + public ObservationRegistryPostProcessor( + ObjectProvider observationHandlerGrouping, + ObjectProvider> observationHandlers) { this.observationHandlerGrouping = observationHandlerGrouping; this.observationHandlers = observationHandlers; - } @Override @@ -46,8 +46,7 @@ public class ObservationRegistryPostProcessor implements BeanPostProcessor { List> observationHandlerList = observationHandlers.orderedStream().collect(Collectors.toList()); observationHandlerGrouping.ifAvailable(grouping -> { - grouping.apply(observationHandlerList, - observationRegistry.observationConfig()); + grouping.apply(observationHandlerList, observationRegistry.observationConfig()); }); } return bean; diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/annotation/ConditionalOnDubboTracingEnable.java b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/annotation/ConditionalOnDubboTracingEnable.java index 1404b62908..b389de1abd 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/annotation/ConditionalOnDubboTracingEnable.java +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/annotation/ConditionalOnDubboTracingEnable.java @@ -18,8 +18,6 @@ package org.apache.dubbo.spring.boot.observability.autoconfigure.annotation; import org.apache.dubbo.spring.boot.observability.autoconfigure.ObservabilityUtils; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; @@ -27,6 +25,8 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; + /** * Checks whether tracing is enabled. * It matches if the value of the {@code dubbo.tracing.enabled} property is {@code true} or if it @@ -39,5 +39,4 @@ import java.lang.annotation.Target; @Inherited @Documented @ConditionalOnProperty(prefix = ObservabilityUtils.DUBBO_TRACING_PREFIX, name = "enabled") -public @interface ConditionalOnDubboTracingEnable { -} +public @interface ConditionalOnDubboTracingEnable {} diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/brave/BraveAutoConfiguration.java b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/brave/BraveAutoConfiguration.java index 8894b890cb..a2083b7679 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/brave/BraveAutoConfiguration.java +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/brave/BraveAutoConfiguration.java @@ -22,6 +22,10 @@ import org.apache.dubbo.spring.boot.observability.autoconfigure.DubboMicrometerT import org.apache.dubbo.spring.boot.observability.autoconfigure.ObservabilityUtils; import org.apache.dubbo.spring.boot.observability.autoconfigure.annotation.ConditionalOnDubboTracingEnable; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -33,21 +37,25 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - - /** * provider Brave when you are using Boot <3.0 or you are not using spring-boot-starter-actuator */ -@AutoConfiguration(before = DubboMicrometerTracingAutoConfiguration.class, afterName = "org.springframework.boot.actuate.autoconfigure.tracing.BraveAutoConfiguration") -@ConditionalOnClass(name = {"io.micrometer.tracing.Tracer", "io.micrometer.tracing.brave.bridge.BraveTracer", "io.micrometer.tracing.brave.bridge.BraveBaggageManager", "brave.Tracing"}) +@AutoConfiguration( + before = DubboMicrometerTracingAutoConfiguration.class, + afterName = "org.springframework.boot.actuate.autoconfigure.tracing.BraveAutoConfiguration") +@ConditionalOnClass( + name = { + "io.micrometer.tracing.Tracer", + "io.micrometer.tracing.brave.bridge.BraveTracer", + "io.micrometer.tracing.brave.bridge.BraveBaggageManager", + "brave.Tracing" + }) @EnableConfigurationProperties(DubboConfigurationProperties.class) @ConditionalOnDubboTracingEnable public class BraveAutoConfiguration { - private static final io.micrometer.tracing.brave.bridge.BraveBaggageManager BRAVE_BAGGAGE_MANAGER = new io.micrometer.tracing.brave.bridge.BraveBaggageManager(); + private static final io.micrometer.tracing.brave.bridge.BraveBaggageManager BRAVE_BAGGAGE_MANAGER = + new io.micrometer.tracing.brave.bridge.BraveBaggageManager(); /** * Default value for application name if {@code spring.application.name} is not set. @@ -63,24 +71,34 @@ public class BraveAutoConfiguration { @Bean @ConditionalOnMissingBean @Order(Ordered.HIGHEST_PRECEDENCE) - io.micrometer.tracing.brave.bridge.CompositeSpanHandler compositeSpanHandler(ObjectProvider predicates, - ObjectProvider reporters, ObjectProvider filters) { - return new io.micrometer.tracing.brave.bridge.CompositeSpanHandler(predicates.orderedStream().collect(Collectors.toList()), + io.micrometer.tracing.brave.bridge.CompositeSpanHandler compositeSpanHandler( + ObjectProvider predicates, + ObjectProvider reporters, + ObjectProvider filters) { + return new io.micrometer.tracing.brave.bridge.CompositeSpanHandler( + predicates.orderedStream().collect(Collectors.toList()), reporters.orderedStream().collect(Collectors.toList()), filters.orderedStream().collect(Collectors.toList())); } @Bean @ConditionalOnMissingBean - public brave.Tracing braveTracing(List spanHandlers, - List tracingCustomizers, brave.propagation.CurrentTraceContext currentTraceContext, - brave.propagation.Propagation.Factory propagationFactory, brave.sampler.Sampler sampler) { + public brave.Tracing braveTracing( + List spanHandlers, + List tracingCustomizers, + brave.propagation.CurrentTraceContext currentTraceContext, + brave.propagation.Propagation.Factory propagationFactory, + brave.sampler.Sampler sampler) { String applicationName = dubboConfigProperties.getApplication().getName(); if (StringUtils.isEmpty(applicationName)) { applicationName = DEFAULT_APPLICATION_NAME; } - brave.Tracing.Builder builder = brave.Tracing.newBuilder().currentTraceContext(currentTraceContext).traceId128Bit(true) - .supportsJoin(false).propagationFactory(propagationFactory).sampler(sampler) + brave.Tracing.Builder builder = brave.Tracing.newBuilder() + .currentTraceContext(currentTraceContext) + .traceId128Bit(true) + .supportsJoin(false) + .propagationFactory(propagationFactory) + .sampler(sampler) .localServiceName(applicationName); spanHandlers.forEach(builder::addSpanHandler); for (brave.TracingCustomizer tracingCustomizer : tracingCustomizers) { @@ -97,11 +115,14 @@ public class BraveAutoConfiguration { @Bean @ConditionalOnMissingBean - public brave.propagation.CurrentTraceContext braveCurrentTraceContext(List scopeDecorators, - List currentTraceContextCustomizers) { - brave.propagation.ThreadLocalCurrentTraceContext.Builder builder = brave.propagation.ThreadLocalCurrentTraceContext.newBuilder(); + public brave.propagation.CurrentTraceContext braveCurrentTraceContext( + List scopeDecorators, + List currentTraceContextCustomizers) { + brave.propagation.ThreadLocalCurrentTraceContext.Builder builder = + brave.propagation.ThreadLocalCurrentTraceContext.newBuilder(); scopeDecorators.forEach(builder::addScopeDecorator); - for (brave.propagation.CurrentTraceContextCustomizer currentTraceContextCustomizer : currentTraceContextCustomizers) { + for (brave.propagation.CurrentTraceContextCustomizer currentTraceContextCustomizer : + currentTraceContextCustomizers) { currentTraceContextCustomizer.customize(builder); } return builder.build(); @@ -110,13 +131,18 @@ public class BraveAutoConfiguration { @Bean @ConditionalOnMissingBean public brave.sampler.Sampler braveSampler(DubboConfigurationProperties properties) { - return brave.sampler.Sampler.create(properties.getTracing().getSampling().getProbability()); + return brave.sampler.Sampler.create( + properties.getTracing().getSampling().getProbability()); } @Bean @ConditionalOnMissingBean(io.micrometer.tracing.Tracer.class) - io.micrometer.tracing.brave.bridge.BraveTracer braveTracerBridge(brave.Tracer tracer, brave.propagation.CurrentTraceContext currentTraceContext) { - return new io.micrometer.tracing.brave.bridge.BraveTracer(tracer, new io.micrometer.tracing.brave.bridge.BraveCurrentTraceContext(currentTraceContext), BRAVE_BAGGAGE_MANAGER); + io.micrometer.tracing.brave.bridge.BraveTracer braveTracerBridge( + brave.Tracer tracer, brave.propagation.CurrentTraceContext currentTraceContext) { + return new io.micrometer.tracing.brave.bridge.BraveTracer( + tracer, + new io.micrometer.tracing.brave.bridge.BraveCurrentTraceContext(currentTraceContext), + BRAVE_BAGGAGE_MANAGER); } @Bean @@ -147,14 +173,15 @@ public class BraveAutoConfiguration { String type = tracing.getTracing().getPropagation().getType(); switch (type) { case org.apache.dubbo.config.nested.PropagationConfig.B3: - return brave.propagation.B3Propagation.newFactoryBuilder().injectFormat(brave.propagation.B3Propagation.Format.SINGLE_NO_PARENT).build(); + return brave.propagation.B3Propagation.newFactoryBuilder() + .injectFormat(brave.propagation.B3Propagation.Format.SINGLE_NO_PARENT) + .build(); case org.apache.dubbo.config.nested.PropagationConfig.W3C: return new io.micrometer.tracing.brave.bridge.W3CPropagation(); default: throw new IllegalArgumentException("UnSupport propagation type"); } } - } @ConditionalOnProperty(value = ObservabilityUtils.DUBBO_TRACING_BAGGAGE_ENABLED, matchIfMissing = true) @@ -168,25 +195,36 @@ public class BraveAutoConfiguration { @Bean @ConditionalOnMissingBean - @ConditionalOnProperty(prefix = ObservabilityUtils.DUBBO_TRACING_PROPAGATION, value = "type", havingValue = "B3") + @ConditionalOnProperty( + prefix = ObservabilityUtils.DUBBO_TRACING_PROPAGATION, + value = "type", + havingValue = "B3") brave.baggage.BaggagePropagation.FactoryBuilder b3PropagationFactoryBuilder( ObjectProvider baggagePropagationCustomizers) { - brave.propagation.Propagation.Factory delegate = - brave.propagation.B3Propagation.newFactoryBuilder().injectFormat(brave.propagation.B3Propagation.Format.SINGLE_NO_PARENT).build(); + brave.propagation.Propagation.Factory delegate = brave.propagation.B3Propagation.newFactoryBuilder() + .injectFormat(brave.propagation.B3Propagation.Format.SINGLE_NO_PARENT) + .build(); - brave.baggage.BaggagePropagation.FactoryBuilder builder = brave.baggage.BaggagePropagation.newFactoryBuilder(delegate); + brave.baggage.BaggagePropagation.FactoryBuilder builder = + brave.baggage.BaggagePropagation.newFactoryBuilder(delegate); baggagePropagationCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); return builder; } @Bean @ConditionalOnMissingBean - @ConditionalOnProperty(prefix = ObservabilityUtils.DUBBO_TRACING_PROPAGATION, value = "type", havingValue = "W3C", matchIfMissing = true) + @ConditionalOnProperty( + prefix = ObservabilityUtils.DUBBO_TRACING_PROPAGATION, + value = "type", + havingValue = "W3C", + matchIfMissing = true) brave.baggage.BaggagePropagation.FactoryBuilder w3cPropagationFactoryBuilder( ObjectProvider baggagePropagationCustomizers) { - brave.propagation.Propagation.Factory delegate = new io.micrometer.tracing.brave.bridge.W3CPropagation(BRAVE_BAGGAGE_MANAGER, Collections.emptyList()); + brave.propagation.Propagation.Factory delegate = new io.micrometer.tracing.brave.bridge.W3CPropagation( + BRAVE_BAGGAGE_MANAGER, Collections.emptyList()); - brave.baggage.BaggagePropagation.FactoryBuilder builder = brave.baggage.BaggagePropagation.newFactoryBuilder(delegate); + brave.baggage.BaggagePropagation.FactoryBuilder builder = + brave.baggage.BaggagePropagation.newFactoryBuilder(delegate); baggagePropagationCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); return builder; } @@ -196,16 +234,19 @@ public class BraveAutoConfiguration { @Order(0) brave.baggage.BaggagePropagationCustomizer remoteFieldsBaggagePropagationCustomizer() { return (builder) -> { - List remoteFields = dubboConfigProperties.getTracing().getBaggage().getRemoteFields(); + List remoteFields = + dubboConfigProperties.getTracing().getBaggage().getRemoteFields(); for (String fieldName : remoteFields) { - builder.add(brave.baggage.BaggagePropagationConfig.SingleBaggageField.remote(brave.baggage.BaggageField.create(fieldName))); + builder.add(brave.baggage.BaggagePropagationConfig.SingleBaggageField.remote( + brave.baggage.BaggageField.create(fieldName))); } }; } @Bean @ConditionalOnMissingBean - brave.propagation.Propagation.Factory propagationFactory(brave.baggage.BaggagePropagation.FactoryBuilder factoryBuilder) { + brave.propagation.Propagation.Factory propagationFactory( + brave.baggage.BaggagePropagation.FactoryBuilder factoryBuilder) { return factoryBuilder.build(); } @@ -213,31 +254,39 @@ public class BraveAutoConfiguration { @ConditionalOnMissingBean brave.baggage.CorrelationScopeDecorator.Builder mdcCorrelationScopeDecoratorBuilder( ObjectProvider correlationScopeCustomizers) { - brave.baggage.CorrelationScopeDecorator.Builder builder = brave.context.slf4j.MDCScopeDecorator.newBuilder(); + brave.baggage.CorrelationScopeDecorator.Builder builder = + brave.context.slf4j.MDCScopeDecorator.newBuilder(); correlationScopeCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); return builder; } @Bean @Order(0) - @ConditionalOnProperty(prefix = ObservabilityUtils.DUBBO_TRACING_BAGGAGE_CORRELATION, name = "enabled", + @ConditionalOnProperty( + prefix = ObservabilityUtils.DUBBO_TRACING_BAGGAGE_CORRELATION, + name = "enabled", matchIfMissing = true) brave.baggage.CorrelationScopeCustomizer correlationFieldsCorrelationScopeCustomizer() { return (builder) -> { - List correlationFields = this.dubboConfigProperties.getTracing().getBaggage().getCorrelation().getFields(); + List correlationFields = this.dubboConfigProperties + .getTracing() + .getBaggage() + .getCorrelation() + .getFields(); for (String field : correlationFields) { - builder.add(brave.baggage.CorrelationScopeConfig.SingleCorrelationField.newBuilder(brave.baggage.BaggageField.create(field)) - .flushOnUpdate().build()); + builder.add(brave.baggage.CorrelationScopeConfig.SingleCorrelationField.newBuilder( + brave.baggage.BaggageField.create(field)) + .flushOnUpdate() + .build()); } }; } @Bean @ConditionalOnMissingBean(brave.propagation.CurrentTraceContext.ScopeDecorator.class) - brave.propagation.CurrentTraceContext.ScopeDecorator correlationScopeDecorator(brave.baggage.CorrelationScopeDecorator.Builder builder) { + brave.propagation.CurrentTraceContext.ScopeDecorator correlationScopeDecorator( + brave.baggage.CorrelationScopeDecorator.Builder builder) { return builder.build(); } - } - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/otlp/OtlpAutoConfiguration.java b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/otlp/OtlpAutoConfiguration.java index f26a851f37..dd55dbe2f4 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/otlp/OtlpAutoConfiguration.java +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/otlp/OtlpAutoConfiguration.java @@ -14,13 +14,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.otlp; import org.apache.dubbo.config.nested.ExporterConfig.OtlpConfig; import org.apache.dubbo.spring.boot.autoconfigure.DubboConfigurationProperties; import org.apache.dubbo.spring.boot.observability.autoconfigure.annotation.ConditionalOnDubboTracingEnable; +import java.util.Map; + import io.micrometer.tracing.otel.bridge.OtelTracer; import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter; @@ -33,8 +34,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; -import java.util.Map; - import static org.apache.dubbo.spring.boot.observability.autoconfigure.ObservabilityUtils.DUBBO_TRACING_OTLP_CONFIG_PREFIX; /** @@ -48,7 +47,8 @@ public class OtlpAutoConfiguration { @Bean @ConditionalOnProperty(prefix = DUBBO_TRACING_OTLP_CONFIG_PREFIX, name = "endpoint") - @ConditionalOnMissingBean(value = OtlpGrpcSpanExporter.class, + @ConditionalOnMissingBean( + value = OtlpGrpcSpanExporter.class, type = "io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter") OtlpGrpcSpanExporter otlpGrpcSpanExporter(DubboConfigurationProperties properties) { OtlpConfig cfg = properties.getTracing().getTracingExporter().getOtlpConfig(); diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/HttpSender.java b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/HttpSender.java index 0bc815031f..8b4fe1261f 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/HttpSender.java +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/HttpSender.java @@ -14,9 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.zipkin; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.Collections; +import java.util.List; +import java.util.zip.GZIPOutputStream; + import org.springframework.http.HttpHeaders; import org.springframework.util.unit.DataSize; import zipkin2.Call; @@ -26,13 +32,6 @@ import zipkin2.reporter.BytesMessageEncoder; import zipkin2.reporter.ClosedSenderException; import zipkin2.reporter.Sender; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.util.Collections; -import java.util.List; -import java.util.zip.GZIPOutputStream; - /** * A Zipkin {@link Sender} that uses an HTTP client to send JSON spans. Supports automatic compression with gzip. */ @@ -140,6 +139,5 @@ abstract class HttpSender extends Sender { } return result.toByteArray(); } - } } diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/ZipkinAutoConfiguration.java b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/ZipkinAutoConfiguration.java index 8e16503b4f..7e37ade6b3 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/ZipkinAutoConfiguration.java +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/ZipkinAutoConfiguration.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.zipkin; import org.apache.dubbo.spring.boot.observability.autoconfigure.annotation.ConditionalOnDubboTracingEnable; @@ -38,7 +37,6 @@ import zipkin2.reporter.Sender; import static org.apache.dubbo.spring.boot.observability.autoconfigure.ObservabilityUtils.DUBBO_TRACING_ZIPKIN_CONFIG_PREFIX; - /** * {@link EnableAutoConfiguration Auto-configuration} for Zipkin. *

    @@ -48,11 +46,16 @@ import static org.apache.dubbo.spring.boot.observability.autoconfigure.Observabi * * @since 3.2.1 */ -@AutoConfiguration(after = RestTemplateAutoConfiguration.class, afterName = "org.springframework.boot.actuate.autoconfigure.tracing.zipkin") +@AutoConfiguration( + after = RestTemplateAutoConfiguration.class, + afterName = "org.springframework.boot.actuate.autoconfigure.tracing.zipkin") @ConditionalOnClass(Sender.class) -@Import({SenderConfiguration.class, - ReporterConfiguration.class, BraveConfiguration.class, - OpenTelemetryConfiguration.class}) +@Import({ + SenderConfiguration.class, + ReporterConfiguration.class, + BraveConfiguration.class, + OpenTelemetryConfiguration.class +}) @ConditionalOnDubboTracingEnable public class ZipkinAutoConfiguration { @@ -62,5 +65,4 @@ public class ZipkinAutoConfiguration { public BytesEncoder spanBytesEncoder() { return SpanBytesEncoder.JSON_V2; } - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/ZipkinConfigurations.java b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/ZipkinConfigurations.java index 3fc32ff2f4..cb5e3701a0 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/ZipkinConfigurations.java +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/ZipkinConfigurations.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.zipkin; import org.apache.dubbo.config.nested.ExporterConfig; @@ -22,6 +21,8 @@ import org.apache.dubbo.spring.boot.autoconfigure.DubboConfigurationProperties; import org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.zipkin.customizer.ZipkinRestTemplateBuilderCustomizer; import org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.zipkin.customizer.ZipkinWebClientBuilderCustomizer; +import java.util.concurrent.atomic.AtomicReference; + import io.opentelemetry.exporter.zipkin.ZipkinSpanExporter; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; @@ -43,8 +44,6 @@ import zipkin2.reporter.Sender; import zipkin2.reporter.brave.ZipkinSpanHandler; import zipkin2.reporter.urlconnection.URLConnectionSender; -import java.util.concurrent.atomic.AtomicReference; - import static org.apache.dubbo.spring.boot.observability.autoconfigure.ObservabilityUtils.DUBBO_TRACING_ZIPKIN_CONFIG_PREFIX; /** @@ -54,10 +53,12 @@ class ZipkinConfigurations { @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(prefix = DUBBO_TRACING_ZIPKIN_CONFIG_PREFIX, name = "endpoint") - @Import({UrlConnectionSenderConfiguration.class, WebClientSenderConfiguration.class, - RestTemplateSenderConfiguration.class}) - static class SenderConfiguration { - } + @Import({ + UrlConnectionSenderConfiguration.class, + WebClientSenderConfiguration.class, + RestTemplateSenderConfiguration.class + }) + static class SenderConfiguration {} @Configuration(proxyBeanMethods = false) @ConditionalOnClass(URLConnectionSender.class) @@ -68,13 +69,13 @@ class ZipkinConfigurations { @ConditionalOnMissingBean(Sender.class) URLConnectionSender urlConnectionSender(DubboConfigurationProperties properties) { URLConnectionSender.Builder builder = URLConnectionSender.newBuilder(); - ExporterConfig.ZipkinConfig zipkinConfig = properties.getTracing().getTracingExporter().getZipkinConfig(); + ExporterConfig.ZipkinConfig zipkinConfig = + properties.getTracing().getTracingExporter().getZipkinConfig(); builder.connectTimeout((int) zipkinConfig.getConnectTimeout().toMillis()); builder.readTimeout((int) zipkinConfig.getReadTimeout().toMillis()); builder.endpoint(zipkinConfig.getEndpoint()); return builder.build(); } - } @Configuration(proxyBeanMethods = false) @@ -84,9 +85,11 @@ class ZipkinConfigurations { @Bean @ConditionalOnMissingBean(Sender.class) - ZipkinRestTemplateSender restTemplateSender(DubboConfigurationProperties properties, - ObjectProvider customizers) { - ExporterConfig.ZipkinConfig zipkinConfig = properties.getTracing().getTracingExporter().getZipkinConfig(); + ZipkinRestTemplateSender restTemplateSender( + DubboConfigurationProperties properties, + ObjectProvider customizers) { + ExporterConfig.ZipkinConfig zipkinConfig = + properties.getTracing().getTracingExporter().getZipkinConfig(); RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder() .setConnectTimeout(zipkinConfig.getConnectTimeout()) .setReadTimeout(zipkinConfig.getReadTimeout()); @@ -94,17 +97,17 @@ class ZipkinConfigurations { return new ZipkinRestTemplateSender(zipkinConfig.getEndpoint(), restTemplateBuilder.build()); } - private RestTemplateBuilder applyCustomizers(RestTemplateBuilder restTemplateBuilder, - ObjectProvider customizers) { - Iterable orderedCustomizers = () -> customizers.orderedStream() - .iterator(); + private RestTemplateBuilder applyCustomizers( + RestTemplateBuilder restTemplateBuilder, + ObjectProvider customizers) { + Iterable orderedCustomizers = + () -> customizers.orderedStream().iterator(); RestTemplateBuilder currentBuilder = restTemplateBuilder; for (ZipkinRestTemplateBuilderCustomizer customizer : orderedCustomizers) { currentBuilder = customizer.customize(currentBuilder); } return currentBuilder; } - } @Configuration(proxyBeanMethods = false) @@ -114,14 +117,14 @@ class ZipkinConfigurations { @Bean @ConditionalOnMissingBean(Sender.class) - ZipkinWebClientSender webClientSender(DubboConfigurationProperties properties, - ObjectProvider customizers) { - ExporterConfig.ZipkinConfig zipkinConfig = properties.getTracing().getTracingExporter().getZipkinConfig(); + ZipkinWebClientSender webClientSender( + DubboConfigurationProperties properties, ObjectProvider customizers) { + ExporterConfig.ZipkinConfig zipkinConfig = + properties.getTracing().getTracingExporter().getZipkinConfig(); WebClient.Builder builder = WebClient.builder(); customizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); return new ZipkinWebClientSender(zipkinConfig.getEndpoint(), builder.build()); } - } @Configuration(proxyBeanMethods = false) @@ -133,7 +136,6 @@ class ZipkinConfigurations { AsyncReporter spanReporter(Sender sender, BytesEncoder encoder) { return AsyncReporter.builder(sender).build(encoder); } - } @Configuration(proxyBeanMethods = false) @@ -144,9 +146,9 @@ class ZipkinConfigurations { @ConditionalOnMissingBean @ConditionalOnBean(Reporter.class) ZipkinSpanHandler zipkinSpanHandler(Reporter spanReporter) { - return (ZipkinSpanHandler) ZipkinSpanHandler.newBuilder(spanReporter).build(); + return (ZipkinSpanHandler) + ZipkinSpanHandler.newBuilder(spanReporter).build(); } - } @Configuration(proxyBeanMethods = false) @@ -157,20 +159,24 @@ class ZipkinConfigurations { @Bean @ConditionalOnMissingBean - ZipkinSpanExporter zipkinSpanExporter(DubboConfigurationProperties properties, BytesEncoder encoder, ObjectProvider senders) { + ZipkinSpanExporter zipkinSpanExporter( + DubboConfigurationProperties properties, BytesEncoder encoder, ObjectProvider senders) { AtomicReference senderRef = new AtomicReference<>(); senders.orderedStream().findFirst().ifPresent(senderRef::set); Sender sender = senderRef.get(); if (sender == null) { - ExporterConfig.ZipkinConfig zipkinConfig = properties.getTracing().getTracingExporter().getZipkinConfig(); + ExporterConfig.ZipkinConfig zipkinConfig = + properties.getTracing().getTracingExporter().getZipkinConfig(); return ZipkinSpanExporter.builder() .setEncoder(encoder) .setEndpoint(zipkinConfig.getEndpoint()) .setReadTimeout(zipkinConfig.getReadTimeout()) .build(); } - return ZipkinSpanExporter.builder().setEncoder(encoder).setSender(sender).build(); + return ZipkinSpanExporter.builder() + .setEncoder(encoder) + .setSender(sender) + .build(); } - } } diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/ZipkinRestTemplateSender.java b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/ZipkinRestTemplateSender.java index 45eff7f6fb..acd3b5b733 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/ZipkinRestTemplateSender.java +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/ZipkinRestTemplateSender.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.zipkin; import org.springframework.http.HttpEntity; @@ -71,6 +70,5 @@ class ZipkinRestTemplateSender extends HttpSender { callback.onError(ex); } } - } } diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/ZipkinWebClientSender.java b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/ZipkinWebClientSender.java index 128f04431a..637d1c5016 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/ZipkinWebClientSender.java +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/ZipkinWebClientSender.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.zipkin; import org.springframework.http.HttpHeaders; @@ -68,7 +67,8 @@ class ZipkinWebClientSender extends HttpSender { } private Mono> sendRequest() { - return this.webClient.post() + return this.webClient + .post() .uri(this.endpoint) .headers(this::addDefaultHeaders) .bodyValue(getBody()) @@ -79,6 +79,5 @@ class ZipkinWebClientSender extends HttpSender { private void addDefaultHeaders(HttpHeaders headers) { headers.addAll(getDefaultHeaders()); } - } } diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/customizer/ZipkinRestTemplateBuilderCustomizer.java b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/customizer/ZipkinRestTemplateBuilderCustomizer.java index db7209e46a..52db70e551 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/customizer/ZipkinRestTemplateBuilderCustomizer.java +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/customizer/ZipkinRestTemplateBuilderCustomizer.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.zipkin.customizer; import org.springframework.boot.web.client.RestTemplateBuilder; diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/customizer/ZipkinWebClientBuilderCustomizer.java b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/customizer/ZipkinWebClientBuilderCustomizer.java index d890280529..243242d128 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/customizer/ZipkinWebClientBuilderCustomizer.java +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/exporter/zipkin/customizer/ZipkinWebClientBuilderCustomizer.java @@ -14,10 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.spring.boot.observability.autoconfigure.exporter.zipkin.customizer; - import org.springframework.web.reactive.function.client.WebClient; /** @@ -35,5 +33,4 @@ public interface ZipkinWebClientBuilderCustomizer { * @param webClientBuilder the {@code WebClient.Builder} to customize */ void customize(WebClient.Builder webClientBuilder); - } diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/otel/OpenTelemetryAutoConfiguration.java b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/otel/OpenTelemetryAutoConfiguration.java index 6b4e38f7c9..25e80abf26 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/otel/OpenTelemetryAutoConfiguration.java +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/observability/autoconfigure/otel/OpenTelemetryAutoConfiguration.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.spring.boot.observability.autoconfigure.otel; - import org.apache.dubbo.common.Version; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.spring.boot.autoconfigure.DubboConfigurationProperties; @@ -24,6 +23,10 @@ import org.apache.dubbo.spring.boot.observability.autoconfigure.DubboMicrometerT import org.apache.dubbo.spring.boot.observability.autoconfigure.ObservabilityUtils; import org.apache.dubbo.spring.boot.observability.autoconfigure.annotation.ConditionalOnDubboTracingEnable; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -33,18 +36,20 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - /** * provider OpenTelemetry when you are using Boot <3.0 or you are not using spring-boot-starter-actuator */ -@AutoConfiguration(before = DubboMicrometerTracingAutoConfiguration.class, afterName = "org.springframework.boot.actuate.autoconfigure.tracing.OpenTelemetryAutoConfiguration") +@AutoConfiguration( + before = DubboMicrometerTracingAutoConfiguration.class, + afterName = "org.springframework.boot.actuate.autoconfigure.tracing.OpenTelemetryAutoConfiguration") @ConditionalOnDubboTracingEnable -@ConditionalOnClass(name = {"io.micrometer.tracing.otel.bridge.OtelTracer", - "io.opentelemetry.sdk.trace.SdkTracerProvider", "io.opentelemetry.api.OpenTelemetry" - , "io.micrometer.tracing.SpanCustomizer"}) +@ConditionalOnClass( + name = { + "io.micrometer.tracing.otel.bridge.OtelTracer", + "io.opentelemetry.sdk.trace.SdkTracerProvider", + "io.opentelemetry.api.OpenTelemetry", + "io.micrometer.tracing.SpanCustomizer" + }) @EnableConfigurationProperties(DubboConfigurationProperties.class) public class OpenTelemetryAutoConfiguration { @@ -61,46 +66,67 @@ public class OpenTelemetryAutoConfiguration { @Bean @ConditionalOnMissingBean - io.opentelemetry.api.OpenTelemetry openTelemetry(io.opentelemetry.sdk.trace.SdkTracerProvider sdkTracerProvider, io.opentelemetry.context.propagation.ContextPropagators contextPropagators) { - return io.opentelemetry.sdk.OpenTelemetrySdk.builder().setTracerProvider(sdkTracerProvider).setPropagators(contextPropagators) + io.opentelemetry.api.OpenTelemetry openTelemetry( + io.opentelemetry.sdk.trace.SdkTracerProvider sdkTracerProvider, + io.opentelemetry.context.propagation.ContextPropagators contextPropagators) { + return io.opentelemetry.sdk.OpenTelemetrySdk.builder() + .setTracerProvider(sdkTracerProvider) + .setPropagators(contextPropagators) .build(); } @Bean @ConditionalOnMissingBean - io.opentelemetry.sdk.trace.SdkTracerProvider otelSdkTracerProvider(ObjectProvider spanProcessors, - io.opentelemetry.sdk.trace.samplers.Sampler sampler) { + io.opentelemetry.sdk.trace.SdkTracerProvider otelSdkTracerProvider( + ObjectProvider spanProcessors, + io.opentelemetry.sdk.trace.samplers.Sampler sampler) { String applicationName = dubboConfigProperties.getApplication().getName(); if (StringUtils.isEmpty(applicationName)) { applicationName = DEFAULT_APPLICATION_NAME; } - io.opentelemetry.sdk.trace.SdkTracerProviderBuilder builder = io.opentelemetry.sdk.trace.SdkTracerProvider.builder().setSampler(sampler) - .setResource(io.opentelemetry.sdk.resources.Resource.create(io.opentelemetry.api.common.Attributes.of(io.opentelemetry.semconv.resource.attributes.ResourceAttributes.SERVICE_NAME, applicationName))); + io.opentelemetry.sdk.trace.SdkTracerProviderBuilder builder = + io.opentelemetry.sdk.trace.SdkTracerProvider.builder() + .setSampler(sampler) + .setResource(io.opentelemetry.sdk.resources.Resource.create( + io.opentelemetry.api.common.Attributes.of( + io.opentelemetry.semconv.resource.attributes.ResourceAttributes.SERVICE_NAME, + applicationName))); spanProcessors.orderedStream().forEach(builder::addSpanProcessor); return builder.build(); } @Bean @ConditionalOnMissingBean - io.opentelemetry.context.propagation.ContextPropagators otelContextPropagators(ObjectProvider textMapPropagators) { - return io.opentelemetry.context.propagation.ContextPropagators.create(io.opentelemetry.context.propagation.TextMapPropagator.composite(textMapPropagators.orderedStream().collect(Collectors.toList()))); + io.opentelemetry.context.propagation.ContextPropagators otelContextPropagators( + ObjectProvider textMapPropagators) { + return io.opentelemetry.context.propagation.ContextPropagators.create( + io.opentelemetry.context.propagation.TextMapPropagator.composite( + textMapPropagators.orderedStream().collect(Collectors.toList()))); } @Bean @ConditionalOnMissingBean io.opentelemetry.sdk.trace.samplers.Sampler otelSampler() { - io.opentelemetry.sdk.trace.samplers.Sampler rootSampler = io.opentelemetry.sdk.trace.samplers.Sampler.traceIdRatioBased(this.dubboConfigProperties.getTracing().getSampling().getProbability()); + io.opentelemetry.sdk.trace.samplers.Sampler rootSampler = + io.opentelemetry.sdk.trace.samplers.Sampler.traceIdRatioBased( + this.dubboConfigProperties.getTracing().getSampling().getProbability()); return io.opentelemetry.sdk.trace.samplers.Sampler.parentBased(rootSampler); } @Bean @ConditionalOnMissingBean - io.opentelemetry.sdk.trace.SpanProcessor otelSpanProcessor(ObjectProvider spanExporters, - ObjectProvider spanExportingPredicates, ObjectProvider spanReporters, - ObjectProvider spanFilters) { - return io.opentelemetry.sdk.trace.export.BatchSpanProcessor.builder(new io.micrometer.tracing.otel.bridge.CompositeSpanExporter(spanExporters.orderedStream().collect(Collectors.toList()), - spanExportingPredicates.orderedStream().collect(Collectors.toList()), spanReporters.orderedStream().collect(Collectors.toList()), - spanFilters.orderedStream().collect(Collectors.toList()))).build(); + io.opentelemetry.sdk.trace.SpanProcessor otelSpanProcessor( + ObjectProvider spanExporters, + ObjectProvider spanExportingPredicates, + ObjectProvider spanReporters, + ObjectProvider spanFilters) { + return io.opentelemetry.sdk.trace.export.BatchSpanProcessor.builder( + new io.micrometer.tracing.otel.bridge.CompositeSpanExporter( + spanExporters.orderedStream().collect(Collectors.toList()), + spanExportingPredicates.orderedStream().collect(Collectors.toList()), + spanReporters.orderedStream().collect(Collectors.toList()), + spanFilters.orderedStream().collect(Collectors.toList()))) + .build(); } @Bean @@ -111,29 +137,41 @@ public class OpenTelemetryAutoConfiguration { @Bean @ConditionalOnMissingBean(io.micrometer.tracing.Tracer.class) - io.micrometer.tracing.otel.bridge.OtelTracer micrometerOtelTracer(io.opentelemetry.api.trace.Tracer tracer, io.micrometer.tracing.otel.bridge.OtelTracer.EventPublisher eventPublisher, - io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext otelCurrentTraceContext) { - return new io.micrometer.tracing.otel.bridge.OtelTracer(tracer, otelCurrentTraceContext, eventPublisher, - new io.micrometer.tracing.otel.bridge.OtelBaggageManager(otelCurrentTraceContext, this.dubboConfigProperties.getTracing().getBaggage().getRemoteFields(), + io.micrometer.tracing.otel.bridge.OtelTracer micrometerOtelTracer( + io.opentelemetry.api.trace.Tracer tracer, + io.micrometer.tracing.otel.bridge.OtelTracer.EventPublisher eventPublisher, + io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext otelCurrentTraceContext) { + return new io.micrometer.tracing.otel.bridge.OtelTracer( + tracer, + otelCurrentTraceContext, + eventPublisher, + new io.micrometer.tracing.otel.bridge.OtelBaggageManager( + otelCurrentTraceContext, + this.dubboConfigProperties.getTracing().getBaggage().getRemoteFields(), Collections.emptyList())); } @Bean @ConditionalOnMissingBean - io.micrometer.tracing.otel.bridge.OtelPropagator otelPropagator(io.opentelemetry.context.propagation.ContextPropagators contextPropagators, io.opentelemetry.api.trace.Tracer tracer) { + io.micrometer.tracing.otel.bridge.OtelPropagator otelPropagator( + io.opentelemetry.context.propagation.ContextPropagators contextPropagators, + io.opentelemetry.api.trace.Tracer tracer) { return new io.micrometer.tracing.otel.bridge.OtelPropagator(contextPropagators, tracer); } @Bean @ConditionalOnMissingBean - io.micrometer.tracing.otel.bridge.OtelTracer.EventPublisher otelTracerEventPublisher(List eventListeners) { + io.micrometer.tracing.otel.bridge.OtelTracer.EventPublisher otelTracerEventPublisher( + List eventListeners) { return new OTelEventPublisher(eventListeners); } @Bean @ConditionalOnMissingBean - io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext otelCurrentTraceContext(io.micrometer.tracing.otel.bridge.OtelTracer.EventPublisher publisher) { - io.opentelemetry.context.ContextStorage.addWrapper(new io.micrometer.tracing.otel.bridge.EventPublishingContextWrapper(publisher)); + io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext otelCurrentTraceContext( + io.micrometer.tracing.otel.bridge.OtelTracer.EventPublisher publisher) { + io.opentelemetry.context.ContextStorage.addWrapper( + new io.micrometer.tracing.otel.bridge.EventPublishingContextWrapper(publisher)); return new io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext(); } @@ -161,33 +199,52 @@ public class OpenTelemetryAutoConfiguration { @Bean @ConditionalOnMissingBean - @ConditionalOnProperty(prefix = ObservabilityUtils.DUBBO_TRACING_PROPAGATION, name = "type", havingValue = "W3C", + @ConditionalOnProperty( + prefix = ObservabilityUtils.DUBBO_TRACING_PROPAGATION, + name = "type", + havingValue = "W3C", matchIfMissing = true) - io.opentelemetry.context.propagation.TextMapPropagator w3cTextMapPropagatorWithBaggage(io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext otelCurrentTraceContext) { - List remoteFields = this.dubboConfigProperties.getTracing().getBaggage().getRemoteFields(); - return io.opentelemetry.context.propagation.TextMapPropagator.composite(io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator.getInstance(), - io.opentelemetry.api.baggage.propagation.W3CBaggagePropagator.getInstance(), new io.micrometer.tracing.otel.propagation.BaggageTextMapPropagator(remoteFields, - new io.micrometer.tracing.otel.bridge.OtelBaggageManager(otelCurrentTraceContext, remoteFields, Collections.emptyList()))); + io.opentelemetry.context.propagation.TextMapPropagator w3cTextMapPropagatorWithBaggage( + io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext otelCurrentTraceContext) { + List remoteFields = + this.dubboConfigProperties.getTracing().getBaggage().getRemoteFields(); + return io.opentelemetry.context.propagation.TextMapPropagator.composite( + io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator.getInstance(), + io.opentelemetry.api.baggage.propagation.W3CBaggagePropagator.getInstance(), + new io.micrometer.tracing.otel.propagation.BaggageTextMapPropagator( + remoteFields, + new io.micrometer.tracing.otel.bridge.OtelBaggageManager( + otelCurrentTraceContext, remoteFields, Collections.emptyList()))); } @Bean @ConditionalOnMissingBean @ConditionalOnProperty(prefix = ObservabilityUtils.DUBBO_TRACING_PROPAGATION, name = "type", havingValue = "B3") - io.opentelemetry.context.propagation.TextMapPropagator b3BaggageTextMapPropagator(io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext otelCurrentTraceContext) { - List remoteFields = this.dubboConfigProperties.getTracing().getBaggage().getRemoteFields(); - return io.opentelemetry.context.propagation.TextMapPropagator.composite(io.opentelemetry.extension.trace.propagation.B3Propagator.injectingSingleHeader(), - new io.micrometer.tracing.otel.propagation.BaggageTextMapPropagator(remoteFields, - new io.micrometer.tracing.otel.bridge.OtelBaggageManager(otelCurrentTraceContext, remoteFields, Collections.emptyList()))); + io.opentelemetry.context.propagation.TextMapPropagator b3BaggageTextMapPropagator( + io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext otelCurrentTraceContext) { + List remoteFields = + this.dubboConfigProperties.getTracing().getBaggage().getRemoteFields(); + return io.opentelemetry.context.propagation.TextMapPropagator.composite( + io.opentelemetry.extension.trace.propagation.B3Propagator.injectingSingleHeader(), + new io.micrometer.tracing.otel.propagation.BaggageTextMapPropagator( + remoteFields, + new io.micrometer.tracing.otel.bridge.OtelBaggageManager( + otelCurrentTraceContext, remoteFields, Collections.emptyList()))); } @Bean @ConditionalOnMissingBean - @ConditionalOnProperty(prefix = ObservabilityUtils.DUBBO_TRACING_BAGGAGE_CORRELATION, name = "enabled", + @ConditionalOnProperty( + prefix = ObservabilityUtils.DUBBO_TRACING_BAGGAGE_CORRELATION, + name = "enabled", matchIfMissing = true) io.micrometer.tracing.otel.bridge.Slf4JBaggageEventListener otelSlf4JBaggageEventListener() { - return new io.micrometer.tracing.otel.bridge.Slf4JBaggageEventListener(this.dubboConfigProperties.getTracing().getBaggage().getCorrelation().getFields()); + return new io.micrometer.tracing.otel.bridge.Slf4JBaggageEventListener(this.dubboConfigProperties + .getTracing() + .getBaggage() + .getCorrelation() + .getFields()); } - } @Configuration(proxyBeanMethods = false) @@ -203,12 +260,14 @@ public class OpenTelemetryAutoConfiguration { @Bean @ConditionalOnMissingBean - @ConditionalOnProperty(prefix = ObservabilityUtils.DUBBO_TRACING_PROPAGATION, name = "type", havingValue = "W3C", + @ConditionalOnProperty( + prefix = ObservabilityUtils.DUBBO_TRACING_PROPAGATION, + name = "type", + havingValue = "W3C", matchIfMissing = true) io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator w3cTextMapPropagatorWithoutBaggage() { return io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator.getInstance(); } - } static class OTelEventPublisher implements io.micrometer.tracing.otel.bridge.OtelTracer.EventPublisher { @@ -225,8 +284,5 @@ public class OpenTelemetryAutoConfiguration { listener.onEvent(event); } } - } - } - diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/observability/autoconfigure/observability/DubboMicrometerTracingAutoConfigurationTests.java b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/observability/autoconfigure/observability/DubboMicrometerTracingAutoConfigurationTests.java index 0e4734a992..4b2f9e4868 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/observability/autoconfigure/observability/DubboMicrometerTracingAutoConfigurationTests.java +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/observability/autoconfigure/observability/DubboMicrometerTracingAutoConfigurationTests.java @@ -14,11 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.spring.boot.observability.autoconfigure.observability; import org.apache.dubbo.spring.boot.observability.autoconfigure.DubboMicrometerTracingAutoConfiguration; +import java.util.List; +import java.util.stream.Collectors; + import io.micrometer.tracing.Tracer; import io.micrometer.tracing.handler.DefaultTracingObservationHandler; import io.micrometer.tracing.handler.PropagatingReceiverTracingObservationHandler; @@ -32,9 +34,6 @@ import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import java.util.List; -import java.util.stream.Collectors; - import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -49,7 +48,8 @@ class DubboMicrometerTracingAutoConfigurationTests { @Test void shouldSupplyBeans() { - this.contextRunner.withUserConfiguration(TracerConfiguration.class, PropagatorConfiguration.class) + this.contextRunner + .withUserConfiguration(TracerConfiguration.class, PropagatorConfiguration.class) .run((context) -> { assertThat(context).hasSingleBean(DefaultTracingObservationHandler.class); assertThat(context).hasSingleBean(PropagatingReceiverTracingObservationHandler.class); @@ -60,10 +60,11 @@ class DubboMicrometerTracingAutoConfigurationTests { @Test @SuppressWarnings("rawtypes") void shouldSupplyBeansInCorrectOrder() { - this.contextRunner.withUserConfiguration(TracerConfiguration.class, PropagatorConfiguration.class) + this.contextRunner + .withUserConfiguration(TracerConfiguration.class, PropagatorConfiguration.class) .run((context) -> { - List tracingObservationHandlers = context - .getBeanProvider(TracingObservationHandler.class) + List tracingObservationHandlers = context.getBeanProvider( + TracingObservationHandler.class) .orderedStream() .collect(Collectors.toList()); assertThat(tracingObservationHandlers).hasSize(3); @@ -89,11 +90,13 @@ class DubboMicrometerTracingAutoConfigurationTests { @Test void shouldNotSupplyBeansIfMicrometerIsMissing() { - this.contextRunner.withClassLoader(new FilteredClassLoader("io.micrometer")).run((context) -> { - assertThat(context).doesNotHaveBean(DefaultTracingObservationHandler.class); - assertThat(context).doesNotHaveBean(PropagatingReceiverTracingObservationHandler.class); - assertThat(context).doesNotHaveBean(PropagatingSenderTracingObservationHandler.class); - }); + this.contextRunner + .withClassLoader(new FilteredClassLoader("io.micrometer")) + .run((context) -> { + assertThat(context).doesNotHaveBean(DefaultTracingObservationHandler.class); + assertThat(context).doesNotHaveBean(PropagatingReceiverTracingObservationHandler.class); + assertThat(context).doesNotHaveBean(PropagatingSenderTracingObservationHandler.class); + }); } @Test @@ -115,7 +118,8 @@ class DubboMicrometerTracingAutoConfigurationTests { @Test void shouldNotSupplyBeansIfTracingIsDisabled() { - this.contextRunner.withUserConfiguration(TracerConfiguration.class, PropagatorConfiguration.class) + this.contextRunner + .withUserConfiguration(TracerConfiguration.class, PropagatorConfiguration.class) .withPropertyValues("dubbo.tracing.enabled=false") .run((context) -> { assertThat(context).doesNotHaveBean(DefaultTracingObservationHandler.class); @@ -131,7 +135,6 @@ class DubboMicrometerTracingAutoConfigurationTests { Tracer tracer() { return mock(Tracer.class); } - } @Configuration(proxyBeanMethods = false) @@ -141,7 +144,6 @@ class DubboMicrometerTracingAutoConfigurationTests { Propagator propagator() { return mock(Propagator.class); } - } @Configuration(proxyBeanMethods = false) @@ -161,6 +163,5 @@ class DubboMicrometerTracingAutoConfigurationTests { PropagatingSenderTracingObservationHandler customPropagatingSenderTracingObservationHandler() { return mock(PropagatingSenderTracingObservationHandler.class); } - } } diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-observability-spring-boot-starter/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-observability-spring-boot-starter/pom.xml index ce94cf3ddc..1f3de6df5c 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-observability-spring-boot-starter/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-observability-spring-boot-starter/pom.xml @@ -15,31 +15,29 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - dubbo-observability-spring-boot-starters - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-observability-spring-boot-starters + ${revision} + ../pom.xml + - dubbo-observability-spring-boot-starter - jar - Apache Dubbo Spring Boot Observability Starter + dubbo-observability-spring-boot-starter + jar + Apache Dubbo Spring Boot Observability Starter - - - org.apache.dubbo - dubbo-observability-spring-boot-autoconfigure - ${project.version} - - - org.apache.dubbo - dubbo-spring-boot-actuator - ${project.version} - - + + + org.apache.dubbo + dubbo-observability-spring-boot-autoconfigure + ${project.version} + + + org.apache.dubbo + dubbo-spring-boot-actuator + ${project.version} + + diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-tracing-brave-zipkin-spring-boot-starter/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-tracing-brave-zipkin-spring-boot-starter/pom.xml index 2567edc06a..4dd4b17963 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-tracing-brave-zipkin-spring-boot-starter/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-tracing-brave-zipkin-spring-boot-starter/pom.xml @@ -15,35 +15,33 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - dubbo-observability-spring-boot-starters - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-observability-spring-boot-starters + ${revision} + ../pom.xml + - dubbo-tracing-brave-zipkin-spring-boot-starter - jar - Apache Dubbo Spring Boot Tracing Brave Zipkin Starter + dubbo-tracing-brave-zipkin-spring-boot-starter + jar + Apache Dubbo Spring Boot Tracing Brave Zipkin Starter - - - org.apache.dubbo - dubbo-observability-spring-boot-autoconfigure - ${project.version} - - - io.micrometer - micrometer-tracing-bridge-brave - - - io.zipkin.reporter2 - zipkin-reporter-brave - - + + + org.apache.dubbo + dubbo-observability-spring-boot-autoconfigure + ${project.version} + + + io.micrometer + micrometer-tracing-bridge-brave + + + io.zipkin.reporter2 + zipkin-reporter-brave + + - \ No newline at end of file + diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-tracing-otel-otlp-spring-boot-starter/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-tracing-otel-otlp-spring-boot-starter/pom.xml index da4909ab61..8d10b3a96d 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-tracing-otel-otlp-spring-boot-starter/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-tracing-otel-otlp-spring-boot-starter/pom.xml @@ -15,35 +15,33 @@ See the License for the specific language governing permissions and limitations under the License. --> - - 4.0.0 - - dubbo-observability-spring-boot-starters - org.apache.dubbo - ${revision} - ../pom.xml - + + 4.0.0 + + org.apache.dubbo + dubbo-observability-spring-boot-starters + ${revision} + ../pom.xml + - dubbo-tracing-otel-otlp-spring-boot-starter - jar - Apache Dubbo Spring Boot Tracing Otel OTLP Starter + dubbo-tracing-otel-otlp-spring-boot-starter + jar + Apache Dubbo Spring Boot Tracing Otel OTLP Starter - - - org.apache.dubbo - dubbo-observability-spring-boot-autoconfigure - ${project.version} - - - io.micrometer - micrometer-tracing-bridge-otel - - - io.opentelemetry - opentelemetry-exporter-otlp - - + + + org.apache.dubbo + dubbo-observability-spring-boot-autoconfigure + ${project.version} + + + io.micrometer + micrometer-tracing-bridge-otel + + + io.opentelemetry + opentelemetry-exporter-otlp + + - \ No newline at end of file + diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-tracing-otel-zipkin-spring-boot-starter/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-tracing-otel-zipkin-spring-boot-starter/pom.xml index bbe734c042..a2fc86c411 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-tracing-otel-zipkin-spring-boot-starter/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/dubbo-tracing-otel-zipkin-spring-boot-starter/pom.xml @@ -15,35 +15,33 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - dubbo-observability-spring-boot-starters - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-observability-spring-boot-starters + ${revision} + ../pom.xml + - dubbo-tracing-otel-zipkin-spring-boot-starter - jar - Apache Dubbo Spring Boot Tracing Otel Zipkin Starter + dubbo-tracing-otel-zipkin-spring-boot-starter + jar + Apache Dubbo Spring Boot Tracing Otel Zipkin Starter - - - org.apache.dubbo - dubbo-observability-spring-boot-autoconfigure - ${project.version} - - - io.micrometer - micrometer-tracing-bridge-otel - - - io.opentelemetry - opentelemetry-exporter-zipkin - - + + + org.apache.dubbo + dubbo-observability-spring-boot-autoconfigure + ${project.version} + + + io.micrometer + micrometer-tracing-bridge-otel + + + io.opentelemetry + opentelemetry-exporter-zipkin + + - \ No newline at end of file + diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/pom.xml index 4181729134..6fb61862f5 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/observability/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/observability/pom.xml @@ -15,74 +15,72 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - org.apache.dubbo - dubbo-spring-boot-starters - ${revision} - ../pom.xml - - 4.0.0 - pom + + 4.0.0 + + org.apache.dubbo + dubbo-spring-boot-starters + ${revision} + ../pom.xml + - dubbo-observability-spring-boot-starters + dubbo-observability-spring-boot-starters + pom - - autoconfigure - dubbo-tracing-otel-zipkin-spring-boot-starter - dubbo-tracing-brave-zipkin-spring-boot-starter - dubbo-observability-spring-boot-starter - dubbo-tracing-otel-otlp-spring-boot-starter - + + autoconfigure + dubbo-tracing-otel-zipkin-spring-boot-starter + dubbo-tracing-brave-zipkin-spring-boot-starter + dubbo-observability-spring-boot-starter + dubbo-tracing-otel-otlp-spring-boot-starter + - - 1.11.5 - 1.1.6 - 1.31.0 - 2.16.4 - 0.16.0 - + + 1.11.5 + 1.1.6 + 1.31.0 + 2.16.4 + 0.16.0 + - - - - io.micrometer - micrometer-bom - ${micrometer.version} - pom - import - - - io.micrometer - micrometer-tracing-bom - ${micrometer-tracing.version} - pom - import - - - io.opentelemetry - opentelemetry-bom - ${opentelemetry.version} - pom - import - - - io.zipkin.reporter2 - zipkin-reporter-bom - ${zipkin-reporter.version} - pom - import - - - io.prometheus - simpleclient_bom - ${prometheus-client.version} - pom - import - - - + + + + io.micrometer + micrometer-bom + ${micrometer.version} + pom + import + + + io.micrometer + micrometer-tracing-bom + ${micrometer-tracing.version} + pom + import + + + io.opentelemetry + opentelemetry-bom + ${opentelemetry.version} + pom + import + + + io.zipkin.reporter2 + zipkin-reporter-bom + ${zipkin-reporter.version} + pom + import + + + io.prometheus + simpleclient_bom + ${prometheus-client.version} + pom + import + + + diff --git a/dubbo-spring-boot/dubbo-spring-boot-starters/pom.xml b/dubbo-spring-boot/dubbo-spring-boot-starters/pom.xml index 0049d17307..897a01556a 100644 --- a/dubbo-spring-boot/dubbo-spring-boot-starters/pom.xml +++ b/dubbo-spring-boot/dubbo-spring-boot-starters/pom.xml @@ -15,29 +15,27 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - + + 4.0.0 - - org.apache.dubbo - dubbo-spring-boot - ${revision} - ../pom.xml - - 4.0.0 + + org.apache.dubbo + dubbo-spring-boot + ${revision} + ../pom.xml + - dubbo-spring-boot-starters - pom - Apache Dubbo Spring Boot Starters + dubbo-spring-boot-starters + pom + Apache Dubbo Spring Boot Starters - - observability - dubbo-nacos-spring-boot-starter - dubbo-zookeeper-spring-boot-starter - dubbo-zookeeper-curator5-spring-boot-starter - dubbo-sentinel-spring-boot-starter - dubbo-seata-spring-boot-starter - + + observability + dubbo-nacos-spring-boot-starter + dubbo-zookeeper-spring-boot-starter + dubbo-zookeeper-curator5-spring-boot-starter + dubbo-sentinel-spring-boot-starter + dubbo-seata-spring-boot-starter + - \ No newline at end of file + diff --git a/dubbo-spring-boot/pom.xml b/dubbo-spring-boot/pom.xml index 3e4344ec2e..1d072e958e 100644 --- a/dubbo-spring-boot/pom.xml +++ b/dubbo-spring-boot/pom.xml @@ -15,184 +15,182 @@ See the License for the specific language governing permissions and limitations under the License. --> - - 4.0.0 - - org.apache.dubbo - dubbo-parent - ${revision} - ../pom.xml - + + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + - dubbo-spring-boot + dubbo-spring-boot - pom - Apache Dubbo Spring Boot Parent + pom + Apache Dubbo Spring Boot Parent - - dubbo-spring-boot-actuator - dubbo-spring-boot-autoconfigure - dubbo-spring-boot-compatible - dubbo-spring-boot-starter - dubbo-spring-boot-starters - dubbo-spring-boot-interceptor - + + dubbo-spring-boot-actuator + dubbo-spring-boot-autoconfigure + dubbo-spring-boot-compatible + dubbo-spring-boot-starter + dubbo-spring-boot-starters + dubbo-spring-boot-interceptor + - - 2.7.17 - - 1.14.9 - 1.7.33 - 4.11.0 - - - - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - org.springframework.boot - spring-boot-starter-logging - ${spring-boot.version} - - - logback-classic - ch.qos.logback - - - log4j-to-slf4j - org.apache.logging.log4j - - - log4j-over-slf4j - org.slf4j - - - - - org.slf4j - slf4j-log4j12 - ${slf4j-log4j12_version} - - - org.mockito - mockito-core - ${mockito_version} - test - - - org.mockito - mockito-inline - ${mockito_version} - test - - - + + 2.7.17 + + 1.14.9 + 1.7.33 + 4.11.0 + + - - - org.junit.vintage - junit-vintage-engine - test - - - net.bytebuddy - byte-buddy - ${byte-buddy.version} - test - - - net.bytebuddy - byte-buddy-agent - ${byte-buddy.version} - test - - - org.apache.dubbo - dubbo-test-check - ${project.parent.version} - test - - + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + org.springframework.boot + spring-boot-starter-logging + ${spring-boot.version} + + + ch.qos.logback + logback-classic + + + org.apache.logging.log4j + log4j-to-slf4j + + org.slf4j - slf4j-log4j12 - ${slf4j-log4j12_version} - test - + log4j-over-slf4j + + + + + org.slf4j + slf4j-log4j12 + ${slf4j-log4j12_version} + + + org.mockito + mockito-core + ${mockito_version} + test + + + org.mockito + mockito-inline + ${mockito_version} + test + + - - - - spring-boot-2.0 - - 2.0.9.RELEASE - - + + + + org.junit.vintage + junit-vintage-engine + test + + + net.bytebuddy + byte-buddy + ${byte-buddy.version} + test + + + net.bytebuddy + byte-buddy-agent + ${byte-buddy.version} + test + + + org.apache.dubbo + dubbo-test-check + ${project.parent.version} + test + + + org.slf4j + slf4j-log4j12 + ${slf4j-log4j12_version} + test + + - - - spring-boot-2.1 - - 2.1.15.RELEASE - - + + + + + false + src/main/resources/ + + + META-INF/ + false + ../ + + NOTICE + LICENSE + + + + + + org.apache.maven.plugins + maven-jar-plugin + ${maven_jar_version} + + + true + true + + true + true + + + ${project.version} + ${project.version} + + + + + + - - - spring-boot-2.2 - - 2.2.8.RELEASE - - - + + + + spring-boot-2.0 + + 2.0.9.RELEASE + + - - - - - src/main/resources/ - false - - - ../ - META-INF/ - false - - NOTICE - LICENSE - - - - - - org.apache.maven.plugins - maven-jar-plugin - ${maven_jar_version} - - - true - true - - true - true - - - ${project.version} - ${project.version} - - - - - - + + + spring-boot-2.1 + + 2.1.15.RELEASE + + + + + + spring-boot-2.2 + + 2.2.8.RELEASE + + + diff --git a/dubbo-test/dubbo-dependencies-all/pom.xml b/dubbo-test/dubbo-dependencies-all/pom.xml index a9834cd0ed..306f3e1e03 100644 --- a/dubbo-test/dubbo-dependencies-all/pom.xml +++ b/dubbo-test/dubbo-dependencies-all/pom.xml @@ -15,617 +15,616 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - dubbo-test - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-test + ${revision} + ../pom.xml + - dubbo-dependencies-all - Aggregate jacoco report + dubbo-dependencies-all + Aggregate jacoco report - - true - + + true + - - - - org.apache.dubbo - dubbo-cluster - ${project.version} - + + + + org.apache.dubbo + dubbo-cluster + ${project.version} + - - - org.apache.dubbo - dubbo-common - ${project.version} - + + + org.apache.dubbo + dubbo-common + ${project.version} + - - - org.apache.dubbo - dubbo-compatible - ${project.version} - + + + org.apache.dubbo + dubbo-compatible + ${project.version} + - - - org.apache.dubbo - dubbo-compiler - ${project.version} - + + + org.apache.dubbo + dubbo-compiler + ${project.version} + - - - org.apache.dubbo - dubbo-config-api - ${project.version} - - - org.apache.dubbo - dubbo-config-spring - ${project.version} - - - - - - + + + org.apache.dubbo + dubbo-config-api + ${project.version} + + + org.apache.dubbo + dubbo-config-spring + ${project.version} + + + + + + - - - org.apache.dubbo - dubbo-configcenter-file - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-apollo - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-nacos - ${project.version} - + + + org.apache.dubbo + dubbo-configcenter-file + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-apollo + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-nacos + ${project.version} + - - - org.apache.dubbo - dubbo-container-api - ${project.version} - - - org.apache.dubbo - dubbo-container-spring - ${project.version} - + + + org.apache.dubbo + dubbo-container-api + ${project.version} + + + org.apache.dubbo + dubbo-container-spring + ${project.version} + - - - org.apache.dubbo - dubbo - ${project.version} - + + + org.apache.dubbo + dubbo + ${project.version} + - - - org.apache.dubbo - dubbo-filter-cache - ${project.version} - - - org.apache.dubbo - dubbo-filter-validation - ${project.version} - + + + org.apache.dubbo + dubbo-filter-cache + ${project.version} + + + org.apache.dubbo + dubbo-filter-validation + ${project.version} + - - - org.apache.dubbo - dubbo-kubernetes - ${project.version} - + + + org.apache.dubbo + dubbo-kubernetes + ${project.version} + - - - org.apache.dubbo - dubbo-metadata-api - ${project.version} - - - org.apache.dubbo - dubbo-metadata-rest - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-nacos - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-redis - ${project.version} - - - org.apache.dubbo - dubbo-metadata-processor - ${project.version} - - - org.apache.dubbo - dubbo-metadata-definition-protobuf - ${project.version} - + + + org.apache.dubbo + dubbo-metadata-api + ${project.version} + + + org.apache.dubbo + dubbo-metadata-rest + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-nacos + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-redis + ${project.version} + + + org.apache.dubbo + dubbo-metadata-processor + ${project.version} + + + org.apache.dubbo + dubbo-metadata-definition-protobuf + ${project.version} + - - - org.apache.dubbo - dubbo-metrics-api - ${project.version} - - - org.apache.dubbo - dubbo-metrics-event - ${project.version} - - - org.apache.dubbo - dubbo-metrics-default - ${project.version} - - - org.apache.dubbo - dubbo-metrics-registry - ${project.version} - + + + org.apache.dubbo + dubbo-metrics-api + ${project.version} + + + org.apache.dubbo + dubbo-metrics-event + ${project.version} + + + org.apache.dubbo + dubbo-metrics-default + ${project.version} + + + org.apache.dubbo + dubbo-metrics-registry + ${project.version} + - - org.apache.dubbo - dubbo-metrics-metadata - ${project.version} - + + org.apache.dubbo + dubbo-metrics-metadata + ${project.version} + - - org.apache.dubbo - dubbo-metrics-config-center - ${project.version} - + + org.apache.dubbo + dubbo-metrics-config-center + ${project.version} + - - org.apache.dubbo - dubbo-metrics-netty - ${project.version} - + + org.apache.dubbo + dubbo-metrics-netty + ${project.version} + - - org.apache.dubbo - dubbo-metrics-prometheus - ${project.version} - - - org.apache.dubbo - dubbo-tracing - ${project.version} - + + org.apache.dubbo + dubbo-metrics-prometheus + ${project.version} + + + org.apache.dubbo + dubbo-tracing + ${project.version} + - - - org.apache.dubbo - dubbo-monitor-api - ${project.version} - - - org.apache.dubbo - dubbo-monitor-common - ${project.version} - - - org.apache.dubbo - dubbo-monitor-default - ${project.version} - - - - org.apache.dubbo - dubbo-native - ${project.version} - + + + org.apache.dubbo + dubbo-monitor-api + ${project.version} + + + org.apache.dubbo + dubbo-monitor-common + ${project.version} + + + org.apache.dubbo + dubbo-monitor-default + ${project.version} + + + + org.apache.dubbo + dubbo-native + ${project.version} + - - org.apache.dubbo - dubbo-maven-plugin - ${project.version} - + + org.apache.dubbo + dubbo-maven-plugin + ${project.version} + - - - org.apache.dubbo - dubbo-auth - ${project.version} - - - org.apache.dubbo - dubbo-security - ${project.version} - - - org.apache.dubbo - dubbo-qos-api - ${project.version} - - - org.apache.dubbo - dubbo-qos - ${project.version} - - - org.apache.dubbo - dubbo-spring-security - ${project.version} - - - org.apache.dubbo - dubbo-reactive - ${project.version} - + + + org.apache.dubbo + dubbo-auth + ${project.version} + + + org.apache.dubbo + dubbo-security + ${project.version} + + + org.apache.dubbo + dubbo-qos-api + ${project.version} + + + org.apache.dubbo + dubbo-qos + ${project.version} + + + org.apache.dubbo + dubbo-spring-security + ${project.version} + + + org.apache.dubbo + dubbo-reactive + ${project.version} + - - org.apache.dubbo - dubbo-plugin-cluster-mergeable - ${project.version} - + + org.apache.dubbo + dubbo-plugin-cluster-mergeable + ${project.version} + - - org.apache.dubbo - dubbo-plugin-mock - ${project.version} - + + org.apache.dubbo + dubbo-plugin-mock + ${project.version} + - - org.apache.dubbo - dubbo-plugin-router-script - ${project.version} - + + org.apache.dubbo + dubbo-plugin-router-script + ${project.version} + - - org.apache.dubbo - dubbo-plugin-router-mesh - ${project.version} - + + org.apache.dubbo + dubbo-plugin-router-mesh + ${project.version} + - - org.apache.dubbo - dubbo-plugin-router-condition - ${project.version} - + + org.apache.dubbo + dubbo-plugin-router-condition + ${project.version} + - - org.apache.dubbo - dubbo-plugin-router-tag - ${project.version} - + + org.apache.dubbo + dubbo-plugin-router-tag + ${project.version} + - - org.apache.dubbo - dubbo-plugin-loadbalance-adaptive - ${project.version} - + + org.apache.dubbo + dubbo-plugin-loadbalance-adaptive + ${project.version} + - - org.apache.dubbo - dubbo-plugin-access-log - ${project.version} - + + org.apache.dubbo + dubbo-plugin-access-log + ${project.version} + - - org.apache.dubbo - dubbo-plugin-tps - ${project.version} - + + org.apache.dubbo + dubbo-plugin-tps + ${project.version} + - - org.apache.dubbo - dubbo-plugin-token - ${project.version} - + + org.apache.dubbo + dubbo-plugin-token + ${project.version} + - - org.apache.dubbo - dubbo-plugin-generic-invoke - ${project.version} - + + org.apache.dubbo + dubbo-plugin-generic-invoke + ${project.version} + - - org.apache.dubbo - dubbo-plugin-context - ${project.version} - + + org.apache.dubbo + dubbo-plugin-context + ${project.version} + - - org.apache.dubbo - dubbo-plugin-classloader-filter - ${project.version} - + + org.apache.dubbo + dubbo-plugin-classloader-filter + ${project.version} + - - org.apache.dubbo - dubbo-plugin-proxy-bytebuddy - ${project.version} - + + org.apache.dubbo + dubbo-plugin-proxy-bytebuddy + ${project.version} + - - org.apache.dubbo - dubbo-plugin-qos-trace - ${project.version} - + + org.apache.dubbo + dubbo-plugin-qos-trace + ${project.version} + - - - org.apache.dubbo - dubbo-registry-api - ${project.version} - - - org.apache.dubbo - dubbo-registry-multicast - ${project.version} - - - org.apache.dubbo - dubbo-registry-multiple - ${project.version} - - - org.apache.dubbo - dubbo-registry-nacos - ${project.version} - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - + + + org.apache.dubbo + dubbo-registry-api + ${project.version} + + + org.apache.dubbo + dubbo-registry-multicast + ${project.version} + + + org.apache.dubbo + dubbo-registry-multiple + ${project.version} + + + org.apache.dubbo + dubbo-registry-nacos + ${project.version} + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.version} + - - - org.apache.dubbo - dubbo-remoting-api - ${project.version} - - - org.apache.dubbo - dubbo-remoting-http - ${project.version} - - - org.apache.dubbo - dubbo-remoting-http12 - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - - - org.apache.dubbo - dubbo-remoting-zookeeper-api - ${project.version} - - - org.apache.dubbo - dubbo-remoting-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-remoting-zookeeper-curator5 - ${project.version} - + + + org.apache.dubbo + dubbo-remoting-api + ${project.version} + + + org.apache.dubbo + dubbo-remoting-http + ${project.version} + + + org.apache.dubbo + dubbo-remoting-http12 + ${project.version} + + + org.apache.dubbo + dubbo-remoting-netty + ${project.version} + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + + + org.apache.dubbo + dubbo-remoting-zookeeper-api + ${project.version} + + + org.apache.dubbo + dubbo-remoting-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-remoting-zookeeper-curator5 + ${project.version} + - - - org.apache.dubbo - dubbo-rpc-api - ${project.version} - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - - - org.apache.dubbo - dubbo-rpc-injvm - ${project.version} - - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - + + + org.apache.dubbo + dubbo-rpc-api + ${project.version} + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + + + org.apache.dubbo + dubbo-rpc-injvm + ${project.version} + + + org.apache.dubbo + dubbo-rpc-rest + ${project.version} + - - org.apache.dubbo - dubbo-rpc-triple - ${project.version} - + + org.apache.dubbo + dubbo-rpc-triple + ${project.version} + - - - org.apache.dubbo - dubbo-serialization-api - ${project.version} - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-jdk - ${project.version} - + + + org.apache.dubbo + dubbo-serialization-api + ${project.version} + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-jdk + ${project.version} + - - - org.apache.dubbo - dubbo-spring-boot-actuator - ${project.version} - - - org.apache.dubbo - dubbo-spring-boot-autoconfigure - ${project.version} - - - org.apache.dubbo - dubbo-spring-boot-actuator-compatible - ${project.version} - - - org.apache.dubbo - dubbo-spring-boot-autoconfigure-compatible - ${project.version} - - - org.apache.dubbo - dubbo-spring-boot-configuration-metadata-compatible - ${project.version} - - - org.apache.dubbo - dubbo-spring-boot-starter - ${project.version} - - - org.apache.dubbo - dubbo-spring-boot-interceptor - ${project.version} - + + + org.apache.dubbo + dubbo-spring-boot-actuator + ${project.version} + + + org.apache.dubbo + dubbo-spring-boot-autoconfigure + ${project.version} + + + org.apache.dubbo + dubbo-spring-boot-actuator-compatible + ${project.version} + + + org.apache.dubbo + dubbo-spring-boot-autoconfigure-compatible + ${project.version} + + + org.apache.dubbo + dubbo-spring-boot-configuration-metadata-compatible + ${project.version} + + + org.apache.dubbo + dubbo-spring-boot-starter + ${project.version} + + + org.apache.dubbo + dubbo-spring-boot-interceptor + ${project.version} + - - org.apache.dubbo - dubbo-observability-spring-boot-autoconfigure - ${project.version} - - - org.apache.dubbo - dubbo-tracing-otel-zipkin-spring-boot-starter - ${project.version} - - - org.apache.dubbo - dubbo-tracing-otel-otlp-spring-boot-starter - ${project.version} - - - org.apache.dubbo - dubbo-tracing-brave-zipkin-spring-boot-starter - ${project.version} - - - org.apache.dubbo - dubbo-observability-spring-boot-starter - ${project.version} - - - org.apache.dubbo - dubbo-nacos-spring-boot-starter - ${project.version} - - - org.apache.dubbo - dubbo-zookeeper-spring-boot-starter - ${project.version} - - - org.apache.dubbo - dubbo-zookeeper-curator5-spring-boot-starter - ${project.version} - - - org.apache.dubbo - dubbo-sentinel-spring-boot-starter - ${project.version} - - - org.apache.dubbo - dubbo-seata-spring-boot-starter - ${project.version} - + + org.apache.dubbo + dubbo-observability-spring-boot-autoconfigure + ${project.version} + + + org.apache.dubbo + dubbo-tracing-otel-zipkin-spring-boot-starter + ${project.version} + + + org.apache.dubbo + dubbo-tracing-otel-otlp-spring-boot-starter + ${project.version} + + + org.apache.dubbo + dubbo-tracing-brave-zipkin-spring-boot-starter + ${project.version} + + + org.apache.dubbo + dubbo-observability-spring-boot-starter + ${project.version} + + + org.apache.dubbo + dubbo-nacos-spring-boot-starter + ${project.version} + + + org.apache.dubbo + dubbo-zookeeper-spring-boot-starter + ${project.version} + + + org.apache.dubbo + dubbo-zookeeper-curator5-spring-boot-starter + ${project.version} + + + org.apache.dubbo + dubbo-sentinel-spring-boot-starter + ${project.version} + + + org.apache.dubbo + dubbo-seata-spring-boot-starter + ${project.version} + - - - org.apache.dubbo - dubbo-test-check - ${project.version} - - - org.apache.dubbo - dubbo-test-common - ${project.version} - - - org.apache.dubbo - dubbo-test-modules - ${project.version} - - - org.apache.dubbo - dubbo-test-spring - ${project.version} - - - org.apache.dubbo - dubbo-test-spring3.2 - ${project.version} - - - org.apache.dubbo - dubbo-test-spring4.1 - ${project.version} - - - org.apache.dubbo - dubbo-test-spring4.2 - ${project.version} - + + + org.apache.dubbo + dubbo-test-check + ${project.version} + + + org.apache.dubbo + dubbo-test-common + ${project.version} + + + org.apache.dubbo + dubbo-test-modules + ${project.version} + + + org.apache.dubbo + dubbo-test-spring + ${project.version} + + + org.apache.dubbo + dubbo-test-spring3.2 + ${project.version} + + + org.apache.dubbo + dubbo-test-spring4.1 + ${project.version} + + + org.apache.dubbo + dubbo-test-spring4.2 + ${project.version} + - - - org.apache.dubbo - dubbo-xds - ${project.version} - - + + + org.apache.dubbo + dubbo-xds + ${project.version} + + diff --git a/dubbo-test/dubbo-test-check/pom.xml b/dubbo-test/dubbo-test-check/pom.xml index 7b6a8b037f..caaa651243 100644 --- a/dubbo-test/dubbo-test-check/pom.xml +++ b/dubbo-test/dubbo-test-check/pom.xml @@ -15,86 +15,84 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - dubbo-test - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-test + ${revision} + ../pom.xml + - dubbo-test-check + dubbo-test-check - - true - 4.2.0 - 3.7.2 - 4.2.0 - 1.24.0 - 1.9.3 - 1.3 - 2.12.3 - + + true + 4.2.0 + 3.7.2 + 4.2.0 + 1.24.0 + 1.9.3 + 1.3 + 2.12.3 + - - - org.apache.dubbo - dubbo-common - ${project.version} - - - org.junit.platform - junit-platform-launcher - ${junit.platform.launcher.version} - - - org.apache.commons - commons-lang3 - - - org.apache.zookeeper - zookeeper - ${zookeeper.version} - - - org.apache.curator - curator-framework - ${curator5.version} - - - - org.apache.commons - commons-compress - ${commons.compress.version} - compile - - - org.apache.commons - commons-exec - ${commons.exec.version} - - - - org.asynchttpclient - async-http-client - ${async.http.client.version} - - + + + org.apache.dubbo + dubbo-common + ${project.version} + + + org.junit.platform + junit-platform-launcher + ${junit.platform.launcher.version} + + + org.apache.commons + commons-lang3 + + + org.apache.zookeeper + zookeeper + ${zookeeper.version} + + + org.apache.curator + curator-framework + ${curator5.version} + + + + org.apache.commons + commons-compress + ${commons.compress.version} + compile + + + org.apache.commons + commons-exec + ${commons.exec.version} + + + + org.asynchttpclient + async-http-client + ${async.http.client.version} + + - - - curator5 - - [17, - - - 5.1.0 - 3.6.0 - 5.1.0 - - - + + + curator5 + + [17, + + + 5.1.0 + 3.6.0 + 5.1.0 + + + diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/AbstractRegistryCenterTestExecutionListener.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/AbstractRegistryCenterTestExecutionListener.java index c5c607c88f..6c29169eb0 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/AbstractRegistryCenterTestExecutionListener.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/AbstractRegistryCenterTestExecutionListener.java @@ -16,15 +16,15 @@ */ package org.apache.dubbo.test.check; +import java.util.HashSet; +import java.util.Set; + import org.junit.platform.engine.TestSource; import org.junit.platform.engine.support.descriptor.ClassSource; import org.junit.platform.launcher.TestExecutionListener; import org.junit.platform.launcher.TestIdentifier; import org.junit.platform.launcher.TestPlan; -import java.util.HashSet; -import java.util.Set; - /** * The abstract implementation provides the basic methods.

    * {@link #needRegistryCenter(TestPlan)}: checks if current {@link TestPlan} need registry center. @@ -67,10 +67,11 @@ public abstract class AbstractRegistryCenterTestExecutionListener implements Tes */ public boolean needRegistryCenter(TestPlan testPlan) { return testPlan.getRoots().stream() - .flatMap(testIdentifier -> testPlan.getChildren(testIdentifier).stream()) - .filter(testIdentifier -> testIdentifier.getSource().isPresent()) - .filter(testIdentifier -> supportEmbeddedZookeeper(testIdentifier)) - .count() > 0; + .flatMap(testIdentifier -> testPlan.getChildren(testIdentifier).stream()) + .filter(testIdentifier -> testIdentifier.getSource().isPresent()) + .filter(testIdentifier -> supportEmbeddedZookeeper(testIdentifier)) + .count() + > 0; } /** @@ -89,7 +90,8 @@ public abstract class AbstractRegistryCenterTestExecutionListener implements Tes } TestSource testSource = testIdentifier.getSource().orElse(null); if (testSource instanceof ClassSource) { - String packageName = ((ClassSource) testSource).getJavaClass().getPackage().getName(); + String packageName = + ((ClassSource) testSource).getJavaClass().getPackage().getName(); for (String pkgName : PACKAGE_NAME) { if (packageName.contains(pkgName)) { return true; diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/DubboTestChecker.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/DubboTestChecker.java index 846d01a8ad..6eb150aeab 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/DubboTestChecker.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/DubboTestChecker.java @@ -20,15 +20,6 @@ import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.model.FrameworkModel; -import org.apache.commons.lang3.StringUtils; -import org.junit.platform.engine.TestExecutionResult; -import org.junit.platform.engine.TestSource; -import org.junit.platform.engine.support.descriptor.ClassSource; -import org.junit.platform.engine.support.descriptor.MethodSource; -import org.junit.platform.launcher.TestExecutionListener; -import org.junit.platform.launcher.TestIdentifier; -import org.junit.platform.launcher.TestPlan; - import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -41,6 +32,15 @@ import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; +import org.apache.commons.lang3.StringUtils; +import org.junit.platform.engine.TestExecutionResult; +import org.junit.platform.engine.TestSource; +import org.junit.platform.engine.support.descriptor.ClassSource; +import org.junit.platform.engine.support.descriptor.MethodSource; +import org.junit.platform.launcher.TestExecutionListener; +import org.junit.platform.launcher.TestIdentifier; +import org.junit.platform.launcher.TestPlan; + /** * A test listener to check unclosed threads of test. * @@ -136,7 +136,8 @@ public class DubboTestChecker implements TestExecutionListener { String defaultReportDir = "target/"; String defaultReportFileName = "test-check-report.txt"; if (checkThreads) { - String reportFilePath = properties.getProperty(CONFIG_REPORT_FILE, defaultReportDir + defaultReportFileName); + String reportFilePath = + properties.getProperty(CONFIG_REPORT_FILE, defaultReportDir + defaultReportFileName); this.reportFile = new File(reportFilePath); if (reportFile.isDirectory()) { reportFile.mkdirs(); @@ -148,8 +149,9 @@ public class DubboTestChecker implements TestExecutionListener { } log("Project dir: " + projectDir); - log(String.format("Dubbo test checker configs: checkMode=%s, checkThreads=%s, threadDumpWaitTimeMs=%s, forceDestroy=%s, reportFile=%s", - checkMode, checkThreads, threadDumpWaitTimeMs, forceDestroyDubboAfterClass, reportFileCanonicalPath)); + log(String.format( + "Dubbo test checker configs: checkMode=%s, checkThreads=%s, threadDumpWaitTimeMs=%s, forceDestroy=%s, reportFile=%s", + checkMode, checkThreads, threadDumpWaitTimeMs, forceDestroyDubboAfterClass, reportFileCanonicalPath)); flushReportFile(); } @@ -170,7 +172,8 @@ public class DubboTestChecker implements TestExecutionListener { private void printThreadCheckingSummaryReport() { log("===== Thread Checking Summary Report ======"); log("Project dir: " + projectDir); - log("Total found " + unclosedThreadMap.size() + " unclosed threads in " + unclosedThreadsOfTestMap.size() + " tests."); + log("Total found " + unclosedThreadMap.size() + " unclosed threads in " + unclosedThreadsOfTestMap.size() + + " tests."); log(""); unclosedThreadsOfTestMap.forEach((testClassName, threads) -> { printUnclosedThreads(threads, testClassName); @@ -199,8 +202,8 @@ public class DubboTestChecker implements TestExecutionListener { public void executionStarted(TestIdentifier testIdentifier) { TestSource testSource = testIdentifier.getSource().orElse(null); if (testSource instanceof ClassSource) { -// ClassSource source = (ClassSource) testSource; -// log("Run test class: " + source.getClassName()); + // ClassSource source = (ClassSource) testSource; + // log("Run test class: " + source.getClassName()); } else if (testSource instanceof MethodSource) { MethodSource source = (MethodSource) testSource; log("Run test method: " + source.getClassName() + "#" + source.getMethodName()); @@ -218,7 +221,7 @@ public class DubboTestChecker implements TestExecutionListener { } MethodSource methodSource = (MethodSource) testSource; testClassName = methodSource.getClassName(); - //log("Finish test method: " + methodSource.getClassName() + "#" + methodSource.getMethodName()); + // log("Finish test method: " + methodSource.getClassName() + "#" + methodSource.getMethodName()); } else if (testSource instanceof ClassSource) { if (forceDestroyDubboAfterClass) { // make sure destroy dubbo engine @@ -231,7 +234,7 @@ public class DubboTestChecker implements TestExecutionListener { ClassSource source = (ClassSource) testSource; testClassName = source.getClassName(); - //log("Finish test class: " + source.getClassName()); + // log("Finish test class: " + source.getClassName()); } else { return; } @@ -251,12 +254,19 @@ public class DubboTestChecker implements TestExecutionListener { Map threadStacks = Thread.getAllStackTraces(); List unclosedThreads = threadStacks.keySet().stream() - .filter(thread -> !StringUtils.startsWithAny(thread.getName(), - "Reference Handler", "Finalizer", "Signal Dispatcher", "Attach Listener", "process reaper", "main" // jvm - , "surefire-forkedjvm-" // surefire plugin - )) - .filter(thread -> !unclosedThreadMap.containsKey(thread)) - .collect(Collectors.toList()); + .filter(thread -> !StringUtils.startsWithAny( + thread.getName(), + "Reference Handler", + "Finalizer", + "Signal Dispatcher", + "Attach Listener", + "process reaper", + "main" // jvm + , + "surefire-forkedjvm-" // surefire plugin + )) + .filter(thread -> !unclosedThreadMap.containsKey(thread)) + .collect(Collectors.toList()); unclosedThreads.sort(Comparator.comparing(Thread::getName)); if (unclosedThreads.size() > 0) { for (Thread thread : unclosedThreads) { @@ -295,8 +305,7 @@ public class DubboTestChecker implements TestExecutionListener { } public static String getFullStacktrace(Thread thread, StackTraceElement[] stackTrace) { - StringBuilder sb = new StringBuilder("Thread: \"" + thread.getName() + "\"" + " Id=" - + thread.getId()); + StringBuilder sb = new StringBuilder("Thread: \"" + thread.getName() + "\"" + " Id=" + thread.getId()); sb.append(' ').append(thread.getState()); sb.append('\n'); if (stackTrace == null) { @@ -308,5 +317,4 @@ public class DubboTestChecker implements TestExecutionListener { } return sb.toString(); } - } diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/RegistryCenterFinished.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/RegistryCenterFinished.java index b3f56f3dd9..35d151791e 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/RegistryCenterFinished.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/RegistryCenterFinished.java @@ -29,12 +29,11 @@ public class RegistryCenterFinished extends AbstractRegistryCenterTestExecutionL public void testPlanExecutionFinished(TestPlan testPlan) { super.testPlanExecutionFinished(testPlan); try { - if(needRegistryCenter(testPlan)){ + if (needRegistryCenter(testPlan)) { GlobalRegistryCenter.shutdown(); } } catch (Throwable cause) { - throw new IllegalStateException("Failed to terminate zookeeper instance in unit test",cause); + throw new IllegalStateException("Failed to terminate zookeeper instance in unit test", cause); } } - } diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/exception/DubboTestException.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/exception/DubboTestException.java index 6c3f1062a6..87ca7345fd 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/exception/DubboTestException.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/exception/DubboTestException.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.test.check.exception; /** * Define a specified exception when test. diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/Config.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/Config.java index 0cda9b5684..814acf2ce3 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/Config.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/Config.java @@ -24,7 +24,7 @@ public interface Config { /** * Returns the default connection address in single registry center. */ - default String getConnectionAddress(){ + default String getConnectionAddress() { return getConnectionAddress1(); } diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/Context.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/Context.java index 76b15fcdbb..b6fb61694d 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/Context.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/Context.java @@ -19,5 +19,4 @@ package org.apache.dubbo.test.check.registrycenter; /** * The global context to store all initialized variables. */ -public interface Context { -} +public interface Context {} diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/ZookeeperRegistryCenter.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/ZookeeperRegistryCenter.java index cff1431aff..e9aa0459fa 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/ZookeeperRegistryCenter.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/ZookeeperRegistryCenter.java @@ -27,9 +27,9 @@ import org.apache.dubbo.test.check.registrycenter.initializer.ConfigZookeeperIni import org.apache.dubbo.test.check.registrycenter.initializer.DownloadZookeeperInitializer; import org.apache.dubbo.test.check.registrycenter.initializer.UnpackZookeeperInitializer; import org.apache.dubbo.test.check.registrycenter.initializer.ZookeeperInitializer; +import org.apache.dubbo.test.check.registrycenter.processor.ResetZookeeperProcessor; import org.apache.dubbo.test.check.registrycenter.processor.StartZookeeperUnixProcessor; import org.apache.dubbo.test.check.registrycenter.processor.StartZookeeperWindowsProcessor; -import org.apache.dubbo.test.check.registrycenter.processor.ResetZookeeperProcessor; import org.apache.dubbo.test.check.registrycenter.processor.StopZookeeperUnixProcessor; import org.apache.dubbo.test.check.registrycenter.processor.StopZookeeperWindowsProcessor; @@ -37,9 +37,9 @@ import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.HashMap; import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; @@ -136,22 +136,21 @@ class ZookeeperRegistryCenter implements RegistryCenter { String directory; // Use System.getProperty({@link #CONFIG_EMBEDDED_ZOOKEEPER_DIRECTORY}) directory = System.getProperty(CONFIG_EMBEDDED_ZOOKEEPER_DIRECTORY); - logger.info(String.format("The customized directory is %s to store zookeeper binary archive.",directory)); + logger.info(String.format("The customized directory is %s to store zookeeper binary archive.", directory)); if (StringUtils.isNotEmpty(directory)) { return directory; } // Use System.getProperty(user.home) - logger.info(String.format("The user home is %s to store zookeeper binary archive.",directory)); + logger.info(String.format("The user home is %s to store zookeeper binary archive.", directory)); directory = System.getProperty("user.home"); - logger.info(String.format("user.home is %s",directory)); + logger.info(String.format("user.home is %s", directory)); if (StringUtils.isEmpty(directory)) { // Use default temporary directory directory = System.getProperty("java.io.tmpdir"); - logger.info(String.format("The temporary directory is %s to store zookeeper binary archive.",directory)); + logger.info(String.format("The temporary directory is %s to store zookeeper binary archive.", directory)); } Assert.notEmptyString(directory, "The directory to store zookeeper binary archive cannot be null or empty."); return directory + File.separator + ".tmp" + File.separator + "zookeeper"; - } /** diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/config/ZookeeperConfig.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/config/ZookeeperConfig.java index da12656acb..487da08c1c 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/config/ZookeeperConfig.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/config/ZookeeperConfig.java @@ -71,7 +71,7 @@ public class ZookeeperConfig implements Config { /** * The default admin server ports of zookeeper. */ - private static final int[] DEFAULT_ADMIN_SERVER_PORTS = new int[]{18081, 18082}; + private static final int[] DEFAULT_ADMIN_SERVER_PORTS = new int[] {18081, 18082}; /** * The default version of zookeeper. @@ -91,7 +91,8 @@ public class ZookeeperConfig implements Config { // with the key of {@link #ZOOKEEPER_PORT_1_KEY} first, and then {@link #ZOOKEEPER_PORT_KEY}, // finally use {@link #DEFAULT_CLIENT_PORT_1} as default port - // The priority of the other is that get it from system properties config with the key of {@link #ZOOKEEPER_PORT_2_KEY} first, + // The priority of the other is that get it from system properties config with the key of {@link + // #ZOOKEEPER_PORT_2_KEY} first, // and then use {@link #DEFAULT_CLIENT_PORT_2} as default port int port1 = DEFAULT_CLIENT_PORT_1; @@ -115,7 +116,8 @@ public class ZookeeperConfig implements Config { } if (port1 == port2) { - throw new IllegalArgumentException(String.format("The client ports %d and %d of zookeeper cannot be same!", port1, port2)); + throw new IllegalArgumentException( + String.format("The client ports %d and %d of zookeeper cannot be same!", port1, port2)); } CLIENT_PORTS[0] = port1; @@ -123,8 +125,10 @@ public class ZookeeperConfig implements Config { // set system properties config System.setProperty(ZOOKEEPER_CONNECTION_ADDRESS_KEY, String.format(CONNECTION_ADDRESS_FORMAT, CLIENT_PORTS[0])); - System.setProperty(ZOOKEEPER_CONNECTION_ADDRESS_1_KEY, String.format(CONNECTION_ADDRESS_FORMAT, CLIENT_PORTS[0])); - System.setProperty(ZOOKEEPER_CONNECTION_ADDRESS_2_KEY, String.format(CONNECTION_ADDRESS_FORMAT, CLIENT_PORTS[1])); + System.setProperty( + ZOOKEEPER_CONNECTION_ADDRESS_1_KEY, String.format(CONNECTION_ADDRESS_FORMAT, CLIENT_PORTS[0])); + System.setProperty( + ZOOKEEPER_CONNECTION_ADDRESS_2_KEY, String.format(CONNECTION_ADDRESS_FORMAT, CLIENT_PORTS[1])); } @Override diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/context/ZookeeperWindowsContext.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/context/ZookeeperWindowsContext.java index 2698d1a606..7277ec1d33 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/context/ZookeeperWindowsContext.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/context/ZookeeperWindowsContext.java @@ -18,8 +18,6 @@ package org.apache.dubbo.test.check.registrycenter.context; import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory; -import org.apache.commons.exec.ExecuteWatchdog; - import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; @@ -27,6 +25,8 @@ import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import org.apache.commons.exec.ExecuteWatchdog; + /** * The global context for zookeeper on Windows OS. */ @@ -35,9 +35,14 @@ public class ZookeeperWindowsContext extends ZookeeperContext { /** * The default executor service to manage the lifecycle of zookeeper. */ - private final ExecutorService DEFAULT_EXECUTOR_SERVICE = new ThreadPoolExecutor(2, 2, 0, TimeUnit.MILLISECONDS, - new SynchronousQueue<>(), - new NamedInternalThreadFactory("mocked-zookeeper", true), new ThreadPoolExecutor.AbortPolicy()); + private final ExecutorService DEFAULT_EXECUTOR_SERVICE = new ThreadPoolExecutor( + 2, + 2, + 0, + TimeUnit.MILLISECONDS, + new SynchronousQueue<>(), + new NamedInternalThreadFactory("mocked-zookeeper", true), + new ThreadPoolExecutor.AbortPolicy()); /** * Define the default {@link ExecuteWatchdog} for terminating all registered zookeeper processes. @@ -73,7 +78,7 @@ public class ZookeeperWindowsContext extends ZookeeperContext { * Remove the registered pid with the given client port. * @param clientPort the client port of zookeeper instance. */ - public void removePid(int clientPort){ + public void removePid(int clientPort) { this.processIds.remove(clientPort); } diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/ConfigZookeeperInitializer.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/ConfigZookeeperInitializer.java index f703f1e780..67b4f98f79 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/ConfigZookeeperInitializer.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/ConfigZookeeperInitializer.java @@ -45,7 +45,8 @@ public class ConfigZookeeperInitializer extends ZookeeperInitializer { * @throws DubboTestException when an exception occurred */ private void updateConfig(ZookeeperContext context, int clientPort, int adminServerPort) throws DubboTestException { - Path zookeeperConf = Paths.get(context.getSourceFile().getParent().toString(), + Path zookeeperConf = Paths.get( + context.getSourceFile().getParent().toString(), String.valueOf(clientPort), context.getUnpackedDirectory(), "conf"); @@ -63,13 +64,18 @@ public class ConfigZookeeperInitializer extends ZookeeperInitializer { logger.info("It is creating the data directory..."); Files.createDirectories(dataDir); } catch (IOException e) { - throw new RuntimeException(String.format("Failed to create the data directory to save zookeeper binary file, file path:%s", context.getSourceFile()), e); + throw new RuntimeException( + String.format( + "Failed to create the data directory to save zookeeper binary file, file path:%s", + context.getSourceFile()), + e); } } properties.setProperty("dataDir", dataDir.toString()); FileOutputStream oFile = null; try { - oFile = new FileOutputStream(Paths.get(zookeeperConf.toString(), "zoo.cfg").toFile()); + oFile = new FileOutputStream( + Paths.get(zookeeperConf.toString(), "zoo.cfg").toFile()); properties.store(oFile, ""); } finally { try { @@ -78,9 +84,8 @@ public class ConfigZookeeperInitializer extends ZookeeperInitializer { throw new DubboTestException("Failed to close file", e); } } - logger.info("The configuration information of zoo.cfg are as below,\n" + - "which located in " + zooSample.getAbsolutePath() + "\n" + - propertiesToString(properties)); + logger.info("The configuration information of zoo.cfg are as below,\n" + "which located in " + + zooSample.getAbsolutePath() + "\n" + propertiesToString(properties)); } catch (IOException e) { throw new DubboTestException(String.format("Failed to update %s file", zooSample), e); } @@ -95,13 +100,18 @@ public class ConfigZookeeperInitializer extends ZookeeperInitializer { logger.info("It is creating the log directory..."); Files.createDirectories(logDir); } catch (IOException e) { - throw new RuntimeException(String.format("Failed to create the log directory to save zookeeper binary file, file path:%s", context.getSourceFile()), e); + throw new RuntimeException( + String.format( + "Failed to create the log directory to save zookeeper binary file, file path:%s", + context.getSourceFile()), + e); } } properties.setProperty("zookeeper.log.dir", logDir.toString()); FileOutputStream oFile = null; try { - oFile = new FileOutputStream(Paths.get(zookeeperConf.toString(), "log4j.properties").toFile()); + oFile = new FileOutputStream( + Paths.get(zookeeperConf.toString(), "log4j.properties").toFile()); properties.store(oFile, ""); } finally { try { @@ -110,9 +120,8 @@ public class ConfigZookeeperInitializer extends ZookeeperInitializer { throw new DubboTestException("Failed to close file", e); } } - logger.info("The configuration information of log4j.properties are as below,\n" + - "which located in " + log4j.getAbsolutePath() + "\n" + - propertiesToString(properties)); + logger.info("The configuration information of log4j.properties are as below,\n" + "which located in " + + log4j.getAbsolutePath() + "\n" + propertiesToString(properties)); } catch (IOException e) { throw new DubboTestException(String.format("Failed to update %s file", zooSample), e); } diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/DownloadZookeeperInitializer.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/DownloadZookeeperInitializer.java index d961e42bfb..fa53136f62 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/DownloadZookeeperInitializer.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/DownloadZookeeperInitializer.java @@ -21,12 +21,6 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.test.check.exception.DubboTestException; import org.apache.dubbo.test.check.registrycenter.context.ZookeeperContext; -import org.asynchttpclient.AsyncCompletionHandler; -import org.asynchttpclient.AsyncHttpClient; -import org.asynchttpclient.DefaultAsyncHttpClient; -import org.asynchttpclient.DefaultAsyncHttpClientConfig; -import org.asynchttpclient.Response; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -37,6 +31,12 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import org.asynchttpclient.AsyncCompletionHandler; +import org.asynchttpclient.AsyncHttpClient; +import org.asynchttpclient.DefaultAsyncHttpClient; +import org.asynchttpclient.DefaultAsyncHttpClientConfig; +import org.asynchttpclient.Response; + import static org.apache.dubbo.common.constants.LoggerCodeConstants.TESTING_REGISTRY_FAILED_TO_DOWNLOAD_ZK_FILE; /** @@ -44,7 +44,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.TESTING_REGI */ public class DownloadZookeeperInitializer extends ZookeeperInitializer { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DownloadZookeeperInitializer.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(DownloadZookeeperInitializer.class); /** * The zookeeper binary file name format. @@ -54,7 +55,8 @@ public class DownloadZookeeperInitializer extends ZookeeperInitializer { /** * The url format for zookeeper binary file. */ - private static final String ZOOKEEPER_BINARY_URL_FORMAT = "https://archive.apache.org/dist/zookeeper/zookeeper-%s/" + ZOOKEEPER_FILE_NAME_FORMAT; + private static final String ZOOKEEPER_BINARY_URL_FORMAT = + "https://archive.apache.org/dist/zookeeper/zookeeper-%s/" + ZOOKEEPER_FILE_NAME_FORMAT; /** * The temporary directory. @@ -89,40 +91,52 @@ public class DownloadZookeeperInitializer extends ZookeeperInitializer { String zookeeperFileName = String.format(ZOOKEEPER_FILE_NAME_FORMAT, context.getVersion()); Path temporaryFilePath; try { - temporaryFilePath = Paths.get(Files.createTempDirectory("").getParent().toString(), - TEMPORARY_DIRECTORY, - zookeeperFileName); + temporaryFilePath = Paths.get( + Files.createTempDirectory("").getParent().toString(), TEMPORARY_DIRECTORY, zookeeperFileName); } catch (IOException e) { - throw new RuntimeException(String.format("Cannot create the temporary directory, file path: %s", TEMPORARY_DIRECTORY), e); + throw new RuntimeException( + String.format("Cannot create the temporary directory, file path: %s", TEMPORARY_DIRECTORY), e); } // create the temporary directory path. try { Files.createDirectories(temporaryFilePath.getParent()); } catch (IOException e) { - throw new RuntimeException(String.format("Failed to create the temporary directory to save zookeeper binary file, file path:%s", temporaryFilePath.getParent()), e); + throw new RuntimeException( + String.format( + "Failed to create the temporary directory to save zookeeper binary file, file path:%s", + temporaryFilePath.getParent()), + e); } // download zookeeper binary file in temporary directory. - String zookeeperBinaryUrl = String.format(ZOOKEEPER_BINARY_URL_FORMAT, context.getVersion(), context.getVersion()); + String zookeeperBinaryUrl = + String.format(ZOOKEEPER_BINARY_URL_FORMAT, context.getVersion(), context.getVersion()); try { - logger.info("It is beginning to download the zookeeper binary archive, it will take several minutes..." + - "\nThe zookeeper binary archive file will be download from " + zookeeperBinaryUrl + "," + - "\nwhich will be saved in " + temporaryFilePath.toString() + "," + - "\nalso it will be renamed to 'apache-zookeeper-bin.tar.gz' and moved into " + context.getSourceFile() + ".\n"); + logger.info("It is beginning to download the zookeeper binary archive, it will take several minutes..." + + "\nThe zookeeper binary archive file will be download from " + + zookeeperBinaryUrl + "," + "\nwhich will be saved in " + + temporaryFilePath.toString() + "," + + "\nalso it will be renamed to 'apache-zookeeper-bin.tar.gz' and moved into " + + context.getSourceFile() + ".\n"); this.download(zookeeperBinaryUrl, temporaryFilePath); } catch (Exception e) { - throw new RuntimeException(String.format("Download zookeeper binary archive failed, download url:%s, file path:%s." + - "\nOr you can do something to avoid this problem as below:" + - "\n1. Download zookeeper binary archive manually regardless of the version" + - "\n2. Rename the downloaded file named 'apache-zookeeper-{version}-bin.tar.gz' to 'apache-zookeeper-bin.tar.gz'" + - "\n3. Put the renamed file in %s, you maybe need to create the directory if necessary.\n", - zookeeperBinaryUrl, temporaryFilePath, context.getSourceFile()), e); + throw new RuntimeException( + String.format( + "Download zookeeper binary archive failed, download url:%s, file path:%s." + + "\nOr you can do something to avoid this problem as below:" + + "\n1. Download zookeeper binary archive manually regardless of the version" + + "\n2. Rename the downloaded file named 'apache-zookeeper-{version}-bin.tar.gz' to 'apache-zookeeper-bin.tar.gz'" + + "\n3. Put the renamed file in %s, you maybe need to create the directory if necessary.\n", + zookeeperBinaryUrl, temporaryFilePath, context.getSourceFile()), + e); } // check downloaded zookeeper binary file in temporary directory. if (!checkFile(temporaryFilePath)) { - throw new IllegalArgumentException(String.format("There are some unknown problem occurred when downloaded the zookeeper binary archive file, file path:%s", temporaryFilePath)); + throw new IllegalArgumentException(String.format( + "There are some unknown problem occurred when downloaded the zookeeper binary archive file, file path:%s", + temporaryFilePath)); } // create target directory if necessary @@ -130,7 +144,11 @@ public class DownloadZookeeperInitializer extends ZookeeperInitializer { try { Files.createDirectories(context.getSourceFile().getParent()); } catch (IOException e) { - throw new IllegalArgumentException(String.format("Failed to create target directory, the directory path: %s", context.getSourceFile().getParent()), e); + throw new IllegalArgumentException( + String.format( + "Failed to create target directory, the directory path: %s", + context.getSourceFile().getParent()), + e); } } @@ -138,12 +156,17 @@ public class DownloadZookeeperInitializer extends ZookeeperInitializer { try { Files.copy(temporaryFilePath, context.getSourceFile(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { - throw new IllegalArgumentException(String.format("Failed to copy file, the source file path: %s, the target file path: %s", temporaryFilePath, context.getSourceFile()), e); + throw new IllegalArgumentException( + String.format( + "Failed to copy file, the source file path: %s, the target file path: %s", + temporaryFilePath, context.getSourceFile()), + e); } // checks the zookeeper binary file exists or not again if (!checkFile(context.getSourceFile())) { - throw new IllegalArgumentException(String.format("The zookeeper binary archive file doesn't exist, file path:%s", context.getSourceFile())); + throw new IllegalArgumentException(String.format( + "The zookeeper binary archive file doesn't exist, file path:%s", context.getSourceFile())); } } @@ -153,26 +176,32 @@ public class DownloadZookeeperInitializer extends ZookeeperInitializer { * @param url the url to download. * @param targetPath the target path to save the downloaded file. */ - private void download(String url, Path targetPath) throws ExecutionException, InterruptedException, IOException, TimeoutException { - AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient( - new DefaultAsyncHttpClientConfig.Builder() + private void download(String url, Path targetPath) + throws ExecutionException, InterruptedException, IOException, TimeoutException { + AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient(new DefaultAsyncHttpClientConfig.Builder() .setConnectTimeout(CONNECT_TIMEOUT) .setRequestTimeout(REQUEST_TIMEOUT) .setMaxRequestRetry(1) .build()); - Future responseFuture = asyncHttpClient.prepareGet(url).execute(new AsyncCompletionHandler() { - @Override - public Response onCompleted(Response response) { - logger.info("Download zookeeper binary archive file successfully! download url: " + url); - return response; - } + Future responseFuture = asyncHttpClient + .prepareGet(url) + .execute(new AsyncCompletionHandler() { + @Override + public Response onCompleted(Response response) { + logger.info("Download zookeeper binary archive file successfully! download url: " + url); + return response; + } - @Override - public void onThrowable(Throwable t) { - logger.warn(TESTING_REGISTRY_FAILED_TO_DOWNLOAD_ZK_FILE, "", "", "Failed to download the file, download url: " + url); - super.onThrowable(t); - } - }); + @Override + public void onThrowable(Throwable t) { + logger.warn( + TESTING_REGISTRY_FAILED_TO_DOWNLOAD_ZK_FILE, + "", + "", + "Failed to download the file, download url: " + url); + super.onThrowable(t); + } + }); // Future timeout should 2 times as equal as REQUEST_TIMEOUT, because it will retry 1 time. Response response = responseFuture.get(REQUEST_TIMEOUT * 2, TimeUnit.MILLISECONDS); Files.copy(response.getResponseBodyAsStream(), targetPath, StandardCopyOption.REPLACE_EXISTING); diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/UnpackZookeeperInitializer.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/UnpackZookeeperInitializer.java index d720c9494b..209d0593bd 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/UnpackZookeeperInitializer.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/UnpackZookeeperInitializer.java @@ -21,11 +21,6 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.test.check.exception.DubboTestException; import org.apache.dubbo.test.check.registrycenter.context.ZookeeperContext; -import org.apache.commons.compress.archivers.tar.TarArchiveEntry; -import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; -import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; -import org.apache.commons.compress.utils.IOUtils; - import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -34,6 +29,11 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; +import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; +import org.apache.commons.compress.utils.IOUtils; + /** * Unpack the downloaded zookeeper binary archive. */ @@ -50,16 +50,16 @@ public class UnpackZookeeperInitializer extends ZookeeperInitializer { */ private void unpack(ZookeeperContext context, int clientPort) throws DubboTestException { File sourceFile = context.getSourceFile().toFile(); - Path targetPath = Paths.get(context.getSourceFile().getParent().toString(), - String.valueOf(clientPort)); + Path targetPath = Paths.get(context.getSourceFile().getParent().toString(), String.valueOf(clientPort)); // check if it's unpacked. if (targetPath.toFile() != null && targetPath.toFile().isDirectory()) { logger.info(String.format("The file has been unpacked, target path:%s", targetPath.toString())); return; } try (FileInputStream fileInputStream = new FileInputStream(sourceFile); - GzipCompressorInputStream gzipCompressorInputStream = new GzipCompressorInputStream(fileInputStream); - TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(gzipCompressorInputStream, "UTF-8")) { + GzipCompressorInputStream gzipCompressorInputStream = new GzipCompressorInputStream(fileInputStream); + TarArchiveInputStream tarArchiveInputStream = + new TarArchiveInputStream(gzipCompressorInputStream, "UTF-8")) { File targetFile = targetPath.toFile(); TarArchiveEntry entry; while ((entry = tarArchiveInputStream.getNextTarEntry()) != null) { @@ -86,21 +86,21 @@ public class UnpackZookeeperInitializer extends ZookeeperInitializer { this.unpack(context, clientPort); // get the file name, just like apache-zookeeper-{version}-bin // the version we maybe unknown if the zookeeper archive binary file is copied by user self. - Path parentPath = Paths.get(context.getSourceFile().getParent().toString(), - String.valueOf(clientPort)); - if (!Files.exists(parentPath) || - !parentPath.toFile().isDirectory() || - parentPath.toFile().listFiles().length != 1) { + Path parentPath = Paths.get(context.getSourceFile().getParent().toString(), String.valueOf(clientPort)); + if (!Files.exists(parentPath) + || !parentPath.toFile().isDirectory() + || parentPath.toFile().listFiles().length != 1) { throw new IllegalStateException("There is something wrong in unpacked file!"); } // rename directory File sourceFile = parentPath.toFile().listFiles()[0]; - File targetFile = Paths.get(parentPath.toString(), context.getUnpackedDirectory()).toFile(); + File targetFile = Paths.get(parentPath.toString(), context.getUnpackedDirectory()) + .toFile(); sourceFile.renameTo(targetFile); if (!Files.exists(targetFile.toPath()) || !targetFile.isDirectory()) { - throw new IllegalStateException(String.format("Failed to rename the directory. source directory: %s, target directory: %s", - sourceFile.toPath().toString(), - targetFile.toPath().toString())); + throw new IllegalStateException(String.format( + "Failed to rename the directory. source directory: %s, target directory: %s", + sourceFile.toPath().toString(), targetFile.toPath().toString())); } // get the bin path Path zookeeperBin = Paths.get(targetFile.toString(), "bin"); diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/FindPidWindowsProcessor.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/FindPidWindowsProcessor.java index 8be66db880..e672bef408 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/FindPidWindowsProcessor.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/FindPidWindowsProcessor.java @@ -22,11 +22,6 @@ import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.test.check.exception.DubboTestException; import org.apache.dubbo.test.check.registrycenter.context.ZookeeperWindowsContext; -import org.apache.commons.exec.CommandLine; -import org.apache.commons.exec.DefaultExecutor; -import org.apache.commons.exec.Executor; -import org.apache.commons.exec.PumpStreamHandler; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -34,6 +29,10 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; +import org.apache.commons.exec.CommandLine; +import org.apache.commons.exec.DefaultExecutor; +import org.apache.commons.exec.Executor; +import org.apache.commons.exec.PumpStreamHandler; /** * Create a {@link org.apache.dubbo.test.check.registrycenter.Processor} to find pid on Windows OS. @@ -82,8 +81,8 @@ public class FindPidWindowsProcessor extends ZookeeperWindowsProcessor { if (values != null && values.length > 0) { for (int i = 0; i < values.length; i++) { List segments = Arrays.stream(values[i].trim().split(" ")) - .filter(str -> !"".equals(str)) - .collect(Collectors.toList()); + .filter(str -> !"".equals(str)) + .collect(Collectors.toList()); // segments sample: // TCP // 127.0.0.1:2182 @@ -92,7 +91,8 @@ public class FindPidWindowsProcessor extends ZookeeperWindowsProcessor { // 4020 if (segments != null && segments.size() == 5) { if (this.check(segments.get(1), clientPort)) { - int pid = Integer.valueOf(segments.get(segments.size() - 1).trim()); + int pid = Integer.valueOf( + segments.get(segments.size() - 1).trim()); context.register(clientPort, pid); return; } @@ -101,7 +101,8 @@ public class FindPidWindowsProcessor extends ZookeeperWindowsProcessor { } } } catch (IOException e) { - throw new DubboTestException(String.format("Failed to find the PID of zookeeper with port %d", clientPort), e); + throw new DubboTestException( + String.format("Failed to find the PID of zookeeper with port %d", clientPort), e); } } @@ -114,7 +115,7 @@ public class FindPidWindowsProcessor extends ZookeeperWindowsProcessor { */ private boolean check(String segment, int clientPort) { return ("[::]:" + clientPort).equalsIgnoreCase(segment) - || ("0.0.0.0:" + clientPort).equalsIgnoreCase(segment) - || ("127.0.0.1:" + clientPort).equalsIgnoreCase(segment); + || ("0.0.0.0:" + clientPort).equalsIgnoreCase(segment) + || ("127.0.0.1:" + clientPort).equalsIgnoreCase(segment); } } diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/KillProcessWindowsProcessor.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/KillProcessWindowsProcessor.java index d83c67814d..96e0e07b85 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/KillProcessWindowsProcessor.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/KillProcessWindowsProcessor.java @@ -21,13 +21,13 @@ import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.test.check.exception.DubboTestException; import org.apache.dubbo.test.check.registrycenter.context.ZookeeperWindowsContext; +import java.io.IOException; + import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.Executor; import org.apache.commons.exec.PumpStreamHandler; -import java.io.IOException; - /** * Create a {@link org.apache.dubbo.test.check.registrycenter.Processor} to kill pid on Windows OS. */ @@ -55,7 +55,8 @@ public class KillProcessWindowsProcessor extends ZookeeperWindowsProcessor { // clear pid context.removePid(clientPort); } catch (IOException e) { - throw new DubboTestException(String.format("Failed to kill the pid %d of zookeeper with port %d", pid, clientPort), e); + throw new DubboTestException( + String.format("Failed to kill the pid %d of zookeeper with port %d", pid, clientPort), e); } } } diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/ResetZookeeperProcessor.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/ResetZookeeperProcessor.java index b9cb8685f2..012954e18f 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/ResetZookeeperProcessor.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/ResetZookeeperProcessor.java @@ -21,12 +21,12 @@ import org.apache.dubbo.test.check.registrycenter.Context; import org.apache.dubbo.test.check.registrycenter.Processor; import org.apache.dubbo.test.check.registrycenter.context.ZookeeperContext; +import java.util.concurrent.TimeUnit; + import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryNTimes; -import java.util.concurrent.TimeUnit; - /** * Create {@link Process} to reset zookeeper. */ @@ -34,13 +34,13 @@ public class ResetZookeeperProcessor implements Processor { @Override public void process(Context context) throws DubboTestException { - ZookeeperContext zookeeperContext = (ZookeeperContext)context; + ZookeeperContext zookeeperContext = (ZookeeperContext) context; for (int clientPort : zookeeperContext.getClientPorts()) { CuratorFramework client; try { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder() - .connectString("127.0.0.1:" + clientPort) - .retryPolicy(new RetryNTimes(1, 1000)); + .connectString("127.0.0.1:" + clientPort) + .retryPolicy(new RetryNTimes(1, 1000)); client = builder.build(); client.start(); boolean connected = client.blockUntilConnected(1000, TimeUnit.MILLISECONDS); diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/StartZookeeperUnixProcessor.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/StartZookeeperUnixProcessor.java index 3cb4587926..ec65a96456 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/StartZookeeperUnixProcessor.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/StartZookeeperUnixProcessor.java @@ -43,19 +43,25 @@ public class StartZookeeperUnixProcessor extends ZookeeperUnixProcessor { protected Process doProcess(ZookeeperContext context, int clientPort) throws DubboTestException { logger.info(String.format("The zookeeper-%d is starting...", clientPort)); List commands = new ArrayList<>(); - Path zookeeperBin = Paths.get(context.getSourceFile().getParent().toString(), + Path zookeeperBin = Paths.get( + context.getSourceFile().getParent().toString(), String.valueOf(clientPort), context.getUnpackedDirectory(), "bin"); commands.add(Paths.get(zookeeperBin.toString(), "zkServer.sh") - .toAbsolutePath().toString()); + .toAbsolutePath() + .toString()); commands.add("start"); - commands.add(Paths.get(zookeeperBin.getParent().toString(), - "conf", - "zoo.cfg").toAbsolutePath().toString()); + commands.add(Paths.get(zookeeperBin.getParent().toString(), "conf", "zoo.cfg") + .toAbsolutePath() + .toString()); try { - return new ProcessBuilder().directory(zookeeperBin.getParent().toFile()) - .command(commands).inheritIO().redirectOutput(ProcessBuilder.Redirect.PIPE).start(); + return new ProcessBuilder() + .directory(zookeeperBin.getParent().toFile()) + .command(commands) + .inheritIO() + .redirectOutput(ProcessBuilder.Redirect.PIPE) + .start(); } catch (IOException e) { throw new DubboTestException(String.format("Failed to start zookeeper-%d", clientPort), e); } diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/StartZookeeperWindowsProcessor.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/StartZookeeperWindowsProcessor.java index 7e40e65765..f384ede4ed 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/StartZookeeperWindowsProcessor.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/StartZookeeperWindowsProcessor.java @@ -22,14 +22,14 @@ import org.apache.dubbo.test.check.exception.DubboTestException; import org.apache.dubbo.test.check.registrycenter.Processor; import org.apache.dubbo.test.check.registrycenter.context.ZookeeperWindowsContext; -import org.apache.commons.exec.CommandLine; -import org.apache.commons.exec.DefaultExecutor; -import org.apache.commons.exec.Executor; - import java.nio.file.Path; import java.nio.file.Paths; import java.util.concurrent.TimeUnit; +import org.apache.commons.exec.CommandLine; +import org.apache.commons.exec.DefaultExecutor; +import org.apache.commons.exec.Executor; + /** * Create {@link Process} to start zookeeper on Windows OS. */ @@ -55,17 +55,19 @@ public class StartZookeeperWindowsProcessor extends ZookeeperWindowsProcessor { this.killPidProcessor.process(context); for (int clientPort : context.getClientPorts()) { logger.info(String.format("The zookeeper-%d is starting...", clientPort)); - Path zookeeperBin = Paths.get(context.getSourceFile().getParent().toString(), - String.valueOf(clientPort), - context.getUnpackedDirectory(), - "bin"); + Path zookeeperBin = Paths.get( + context.getSourceFile().getParent().toString(), + String.valueOf(clientPort), + context.getUnpackedDirectory(), + "bin"); Executor executor = new DefaultExecutor(); executor.setExitValues(null); executor.setWatchdog(context.getWatchdog()); CommandLine cmdLine = new CommandLine("cmd.exe"); cmdLine.addArgument("/c"); cmdLine.addArgument(Paths.get(zookeeperBin.toString(), "zkServer.cmd") - .toAbsolutePath().toString()); + .toAbsolutePath() + .toString()); context.getExecutorService().submit(() -> executor.execute(cmdLine)); } try { diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/StopZookeeperUnixProcessor.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/StopZookeeperUnixProcessor.java index 452fbed216..f7a2f0ae9a 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/StopZookeeperUnixProcessor.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/StopZookeeperUnixProcessor.java @@ -44,16 +44,22 @@ public class StopZookeeperUnixProcessor extends ZookeeperUnixProcessor { protected Process doProcess(ZookeeperContext context, int clientPort) throws DubboTestException { logger.info(String.format("The zookeeper-%d is stopping...", clientPort)); List commands = new ArrayList<>(); - Path zookeeperBin = Paths.get(context.getSourceFile().getParent().toString(), - String.valueOf(clientPort), - context.getUnpackedDirectory(), - "bin"); + Path zookeeperBin = Paths.get( + context.getSourceFile().getParent().toString(), + String.valueOf(clientPort), + context.getUnpackedDirectory(), + "bin"); commands.add(Paths.get(zookeeperBin.toString(), "zkServer.sh") - .toAbsolutePath().toString()); + .toAbsolutePath() + .toString()); commands.add("stop"); try { - return new ProcessBuilder().directory(zookeeperBin.getParent().toFile()) - .command(commands).inheritIO().redirectOutput(ProcessBuilder.Redirect.PIPE).start(); + return new ProcessBuilder() + .directory(zookeeperBin.getParent().toFile()) + .command(commands) + .inheritIO() + .redirectOutput(ProcessBuilder.Redirect.PIPE) + .start(); } catch (IOException e) { throw new DubboTestException(String.format("Failed to stop zookeeper-%d", clientPort), e); } diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/ZookeeperUnixProcessor.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/ZookeeperUnixProcessor.java index c5b25c8e33..100f00b54e 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/ZookeeperUnixProcessor.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/ZookeeperUnixProcessor.java @@ -37,7 +37,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.TESTING_REGI */ public abstract class ZookeeperUnixProcessor implements Processor { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ZookeeperUnixProcessor.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(ZookeeperUnixProcessor.class); @Override public void process(Context context) throws DubboTestException { @@ -50,7 +51,12 @@ public abstract class ZookeeperUnixProcessor implements Processor { try { process.destroy(); } catch (Throwable cause) { - logger.warn(TESTING_REGISTRY_FAILED_TO_STOP_ZOOKEEPER, "", "", String.format("Failed to kill the process, with client port %s !", clientPort), cause); + logger.warn( + TESTING_REGISTRY_FAILED_TO_STOP_ZOOKEEPER, + "", + "", + String.format("Failed to kill the process, with client port %s !", clientPort), + cause); } } } @@ -64,7 +70,7 @@ public abstract class ZookeeperUnixProcessor implements Processor { try (final BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream))) { String line; while ((line = reader.readLine()) != null) { - logger.error(TESTING_REGISTRY_FAILED_TO_START_ZOOKEEPER,"","",line); + logger.error(TESTING_REGISTRY_FAILED_TO_START_ZOOKEEPER, "", "", line); } } catch (IOException e) { /* eat quietly */ diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/ZookeeperWindowsProcessor.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/ZookeeperWindowsProcessor.java index d364bd63ac..340b3441d9 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/ZookeeperWindowsProcessor.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/ZookeeperWindowsProcessor.java @@ -20,6 +20,7 @@ import org.apache.dubbo.test.check.exception.DubboTestException; import org.apache.dubbo.test.check.registrycenter.Context; import org.apache.dubbo.test.check.registrycenter.Processor; import org.apache.dubbo.test.check.registrycenter.context.ZookeeperWindowsContext; + /** * The abstract implementation of {@link Processor} is to provide some common methods on Windows OS. */ diff --git a/dubbo-test/dubbo-test-common/pom.xml b/dubbo-test/dubbo-test-common/pom.xml index be6a987ad8..9f82b3b271 100644 --- a/dubbo-test/dubbo-test-common/pom.xml +++ b/dubbo-test/dubbo-test-common/pom.xml @@ -1,3 +1,4 @@ + - - - dubbo-test - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-test + ${revision} + ../pom.xml + - dubbo-test-common + dubbo-test-common - - true - + + true + - - - org.apache.zookeeper - zookeeper - + + + org.apache.zookeeper + zookeeper + - - org.apache.dubbo - dubbo-common - ${project.version} - - - org.apache.dubbo - dubbo-rpc-api - ${project.version} - - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - - - org.apache.dubbo - dubbo-test-check - ${project.version} - - + + org.apache.dubbo + dubbo-common + ${project.version} + + + org.apache.dubbo + dubbo-rpc-api + ${project.version} + + + org.apache.dubbo + dubbo-rpc-rest + ${project.version} + + + org.apache.dubbo + dubbo-test-check + ${project.version} + + diff --git a/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/ErrorHandler.java b/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/ErrorHandler.java index b44ff13298..ba8e965691 100644 --- a/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/ErrorHandler.java +++ b/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/ErrorHandler.java @@ -23,5 +23,4 @@ public interface ErrorHandler { * Handle the given error, possibly rethrowing it as a fatal exception. */ void handleError(Throwable t); - } diff --git a/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/SysProps.java b/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/SysProps.java index dac5edd9f9..dcfafc37f8 100644 --- a/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/SysProps.java +++ b/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/SysProps.java @@ -41,5 +41,4 @@ public class SysProps { } reset(); } - } diff --git a/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/api/DemoService.java b/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/api/DemoService.java index 9a5dfc155a..f90031bd1e 100644 --- a/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/api/DemoService.java +++ b/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/api/DemoService.java @@ -23,5 +23,4 @@ public interface DemoService { String sayHello(String name); CompletableFuture sayHelloAsync(String name); - } diff --git a/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/api/RestDemoService.java b/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/api/RestDemoService.java index 809cd94d73..07b0667469 100644 --- a/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/api/RestDemoService.java +++ b/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/api/RestDemoService.java @@ -23,7 +23,6 @@ import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; - @Path("/demoService") public interface RestDemoService { @GET diff --git a/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/impl/DemoServiceImpl.java b/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/impl/DemoServiceImpl.java index 4b80d8b8b2..0ab09bdc55 100644 --- a/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/impl/DemoServiceImpl.java +++ b/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/impl/DemoServiceImpl.java @@ -31,11 +31,11 @@ public class DemoServiceImpl implements DemoService { @Override public CompletableFuture sayHelloAsync(String name) { CompletableFuture cf = CompletableFuture.supplyAsync(() -> { -// try { -// Thread.sleep(1000); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } + // try { + // Thread.sleep(1000); + // } catch (InterruptedException e) { + // e.printStackTrace(); + // } return "async result:" + name; }); return cf; diff --git a/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/impl/GreetingServiceImpl.java b/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/impl/GreetingServiceImpl.java index 0ad249abf6..cd205bcc7b 100644 --- a/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/impl/GreetingServiceImpl.java +++ b/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/impl/GreetingServiceImpl.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.test.common.impl; - import org.apache.dubbo.test.common.api.GreetingService; /** diff --git a/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/impl/RestDemoServiceImpl.java b/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/impl/RestDemoServiceImpl.java index c8633145ff..a2fd54edaf 100644 --- a/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/impl/RestDemoServiceImpl.java +++ b/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/impl/RestDemoServiceImpl.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.test.common.impl; - import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.test.common.api.RestDemoService; @@ -31,7 +30,6 @@ public class RestDemoServiceImpl implements RestDemoService { return "Hello, " + name; } - public boolean isCalled() { return called; } diff --git a/dubbo-test/dubbo-test-modules/pom.xml b/dubbo-test/dubbo-test-modules/pom.xml index bcd2a99a9a..f2ade3d077 100644 --- a/dubbo-test/dubbo-test-modules/pom.xml +++ b/dubbo-test/dubbo-test-modules/pom.xml @@ -15,36 +15,34 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - dubbo-test - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-test + ${revision} + ../pom.xml + - dubbo-test-modules - Check if dependencies configured properly + dubbo-test-modules + Check if dependencies configured properly - - true - 2.1.4 - + + true + 2.1.4 + - - - org.dom4j - dom4j - ${dom4j_version} - test - - - org.apache.dubbo - dubbo-common - ${project.version} - - + + + org.dom4j + dom4j + ${dom4j_version} + test + + + org.apache.dubbo + dubbo-common + ${project.version} + + diff --git a/dubbo-test/dubbo-test-modules/src/test/java/org/apache/dubbo/dependency/FileTest.java b/dubbo-test/dubbo-test-modules/src/test/java/org/apache/dubbo/dependency/FileTest.java index b971b22908..5f9f02e3cc 100644 --- a/dubbo-test/dubbo-test-modules/src/test/java/org/apache/dubbo/dependency/FileTest.java +++ b/dubbo-test/dubbo-test-modules/src/test/java/org/apache/dubbo/dependency/FileTest.java @@ -16,15 +16,6 @@ */ package org.apache.dubbo.dependency; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.Element; -import org.dom4j.io.SAXReader; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -38,10 +29,19 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.Element; +import org.dom4j.io.SAXReader; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + class FileTest { - private final static List ignoredModules = new LinkedList<>(); - private final static List ignoredArtifacts = new LinkedList<>(); - private final static List ignoredModulesInDubboAll = new LinkedList<>(); + private static final List ignoredModules = new LinkedList<>(); + private static final List ignoredArtifacts = new LinkedList<>(); + private static final List ignoredModulesInDubboAll = new LinkedList<>(); static { ignoredModules.add(Pattern.compile("dubbo-apache-release")); @@ -81,33 +81,37 @@ class FileTest { SAXReader reader = new SAXReader(); List artifactIds = poms.stream() - .map(f -> { - try { - return reader.read(f); - } catch (DocumentException e) { - throw new RuntimeException(e); - } - }) - .map(Document::getRootElement) - .map(doc -> doc.elementText("artifactId")) - .sorted() - .collect(Collectors.toList()); + .map(f -> { + try { + return reader.read(f); + } catch (DocumentException e) { + throw new RuntimeException(e); + } + }) + .map(Document::getRootElement) + .map(doc -> doc.elementText("artifactId")) + .sorted() + .collect(Collectors.toList()); String dubboBomPath = "dubbo-distribution" + File.separator + "dubbo-bom" + File.separator + "pom.xml"; Document dubboBom = reader.read(new File(getBaseFile(), dubboBomPath)); - List artifactIdsInDubboBom = dubboBom.getRootElement() - .element("dependencyManagement") - .element("dependencies") - .elements("dependency") - .stream() - .map(ele -> ele.elementText("artifactId")) - .collect(Collectors.toList()); + List artifactIdsInDubboBom = dubboBom + .getRootElement() + .element("dependencyManagement") + .element("dependencies") + .elements("dependency") + .stream() + .map(ele -> ele.elementText("artifactId")) + .collect(Collectors.toList()); List expectedArtifactIds = new LinkedList<>(artifactIds); expectedArtifactIds.removeAll(artifactIdsInDubboBom); - expectedArtifactIds.removeIf(artifactId -> ignoredModules.stream().anyMatch(pattern -> pattern.matcher(artifactId).matches())); + expectedArtifactIds.removeIf(artifactId -> ignoredModules.stream() + .anyMatch(pattern -> pattern.matcher(artifactId).matches())); - Assertions.assertTrue(expectedArtifactIds.isEmpty(), "Newly created modules must be added to dubbo-bom. Found modules: " + expectedArtifactIds); + Assertions.assertTrue( + expectedArtifactIds.isEmpty(), + "Newly created modules must be added to dubbo-bom. Found modules: " + expectedArtifactIds); } @Test @@ -120,28 +124,35 @@ class FileTest { SAXReader reader = new SAXReader(); List artifactIds = poms.stream() - .map(f -> { - try { - return reader.read(f); - } catch (DocumentException e) { - throw new RuntimeException(e); - } - }) - .map(Document::getRootElement) - .map(doc -> doc.elementText("artifactId")) - .sorted() - .collect(Collectors.toList()); + .map(f -> { + try { + return reader.read(f); + } catch (DocumentException e) { + throw new RuntimeException(e); + } + }) + .map(Document::getRootElement) + .map(doc -> doc.elementText("artifactId")) + .sorted() + .collect(Collectors.toList()); List artifactIdsInRoot = IOUtils.readLines( - this.getClass().getClassLoader().getResource("META-INF/versions/.artifacts").openStream(), + this.getClass() + .getClassLoader() + .getResource("META-INF/versions/.artifacts") + .openStream(), StandardCharsets.UTF_8); artifactIdsInRoot.removeIf(s -> s.startsWith("#")); List expectedArtifactIds = new LinkedList<>(artifactIds); expectedArtifactIds.removeAll(artifactIdsInRoot); - expectedArtifactIds.removeIf(artifactId -> ignoredArtifacts.stream().anyMatch(pattern -> pattern.matcher(artifactId).matches())); + expectedArtifactIds.removeIf(artifactId -> ignoredArtifacts.stream() + .anyMatch(pattern -> pattern.matcher(artifactId).matches())); - Assertions.assertTrue(expectedArtifactIds.isEmpty(), "Newly created modules must be added to .artifacts (in project root). Found modules: " + expectedArtifactIds); + Assertions.assertTrue( + expectedArtifactIds.isEmpty(), + "Newly created modules must be added to .artifacts (in project root). Found modules: " + + expectedArtifactIds); } @Test @@ -154,33 +165,35 @@ class FileTest { SAXReader reader = new SAXReader(); List artifactIds = poms.stream() - .map(f -> { - try { - return reader.read(f); - } catch (DocumentException e) { - throw new RuntimeException(e); - } - }) - .map(Document::getRootElement) - .filter(doc -> !Objects.equals("pom", doc.elementText("packaging"))) - .map(doc -> doc.elementText("artifactId")) - .sorted() - .collect(Collectors.toList()); + .map(f -> { + try { + return reader.read(f); + } catch (DocumentException e) { + throw new RuntimeException(e); + } + }) + .map(Document::getRootElement) + .filter(doc -> !Objects.equals("pom", doc.elementText("packaging"))) + .map(doc -> doc.elementText("artifactId")) + .sorted() + .collect(Collectors.toList()); - String dubboDependenciesAllPath = "dubbo-test" + File.separator + "dubbo-dependencies-all" + File.separator + "pom.xml"; + String dubboDependenciesAllPath = + "dubbo-test" + File.separator + "dubbo-dependencies-all" + File.separator + "pom.xml"; Document dubboDependenciesAll = reader.read(new File(getBaseFile(), dubboDependenciesAllPath)); - List artifactIdsInDubboDependenciesAll = dubboDependenciesAll.getRootElement() - .element("dependencies") - .elements("dependency") - .stream() - .map(ele -> ele.elementText("artifactId")) - .collect(Collectors.toList()); + List artifactIdsInDubboDependenciesAll = + dubboDependenciesAll.getRootElement().element("dependencies").elements("dependency").stream() + .map(ele -> ele.elementText("artifactId")) + .collect(Collectors.toList()); List expectedArtifactIds = new LinkedList<>(artifactIds); expectedArtifactIds.removeAll(artifactIdsInDubboDependenciesAll); - expectedArtifactIds.removeIf(artifactId -> ignoredModules.stream().anyMatch(pattern -> pattern.matcher(artifactId).matches())); + expectedArtifactIds.removeIf(artifactId -> ignoredModules.stream() + .anyMatch(pattern -> pattern.matcher(artifactId).matches())); - Assertions.assertTrue(expectedArtifactIds.isEmpty(), "Newly created modules must be added to dubbo-dependencies-all. Found modules: " + expectedArtifactIds); + Assertions.assertTrue( + expectedArtifactIds.isEmpty(), + "Newly created modules must be added to dubbo-dependencies-all. Found modules: " + expectedArtifactIds); } @Test @@ -193,71 +206,83 @@ class FileTest { SAXReader reader = new SAXReader(); List artifactIds = poms.stream() - .map(f -> { - try { - return reader.read(f); - } catch (DocumentException e) { - throw new RuntimeException(e); - } - }) - .map(Document::getRootElement) - .map(doc -> doc.elementText("artifactId")) - .sorted() - .collect(Collectors.toList()); + .map(f -> { + try { + return reader.read(f); + } catch (DocumentException e) { + throw new RuntimeException(e); + } + }) + .map(Document::getRootElement) + .map(doc -> doc.elementText("artifactId")) + .sorted() + .collect(Collectors.toList()); Assertions.assertEquals(poms.size(), artifactIds.size()); List deployedArtifactIds = poms.stream() - .map(f -> { - try { - return reader.read(f); - } catch (DocumentException e) { - throw new RuntimeException(e); - } - }) - .map(Document::getRootElement) - .filter(doc -> !Objects.equals("pom", doc.elementText("packaging"))) - .filter(doc -> Objects.isNull(doc.element("properties")) || - (!Objects.equals("true", doc.element("properties").elementText("skip_maven_deploy")) && - !Objects.equals("true", doc.element("properties").elementText("maven.deploy.skip")))) - .map(doc -> doc.elementText("artifactId")) - .sorted() - .collect(Collectors.toList()); + .map(f -> { + try { + return reader.read(f); + } catch (DocumentException e) { + throw new RuntimeException(e); + } + }) + .map(Document::getRootElement) + .filter(doc -> !Objects.equals("pom", doc.elementText("packaging"))) + .filter(doc -> Objects.isNull(doc.element("properties")) + || (!Objects.equals("true", doc.element("properties").elementText("skip_maven_deploy")) + && !Objects.equals( + "true", doc.element("properties").elementText("maven.deploy.skip")))) + .map(doc -> doc.elementText("artifactId")) + .sorted() + .collect(Collectors.toList()); String dubboAllPath = "dubbo-distribution" + File.separator + "dubbo-all" + File.separator + "pom.xml"; Document dubboAll = reader.read(new File(getBaseFile(), dubboAllPath)); - List artifactIdsInDubboAll = dubboAll.getRootElement() - .element("dependencies") - .elements("dependency") - .stream() - .map(ele -> ele.elementText("artifactId")) - .collect(Collectors.toList()); + List artifactIdsInDubboAll = + dubboAll.getRootElement().element("dependencies").elements("dependency").stream() + .map(ele -> ele.elementText("artifactId")) + .collect(Collectors.toList()); List expectedArtifactIds = new LinkedList<>(deployedArtifactIds); expectedArtifactIds.removeAll(artifactIdsInDubboAll); - expectedArtifactIds.removeIf(artifactId -> ignoredModules.stream().anyMatch(pattern -> pattern.matcher(artifactId).matches())); - expectedArtifactIds.removeIf(artifactId -> ignoredModulesInDubboAll.stream().anyMatch(pattern -> pattern.matcher(artifactId).matches())); + expectedArtifactIds.removeIf(artifactId -> ignoredModules.stream() + .anyMatch(pattern -> pattern.matcher(artifactId).matches())); + expectedArtifactIds.removeIf(artifactId -> ignoredModulesInDubboAll.stream() + .anyMatch(pattern -> pattern.matcher(artifactId).matches())); - Assertions.assertTrue(expectedArtifactIds.isEmpty(), "Newly created modules must be added to dubbo-all(dubbo-distribution" + File.separator + "dubbo-all" + File.separator + "pom.xml). Found modules: " + expectedArtifactIds); + Assertions.assertTrue( + expectedArtifactIds.isEmpty(), + "Newly created modules must be added to dubbo-all(dubbo-distribution" + File.separator + "dubbo-all" + + File.separator + "pom.xml). Found modules: " + expectedArtifactIds); List unexpectedArtifactIds = new LinkedList<>(artifactIdsInDubboAll); unexpectedArtifactIds.removeIf(artifactId -> !artifactIds.contains(artifactId)); unexpectedArtifactIds.removeAll(deployedArtifactIds); - Assertions.assertTrue(unexpectedArtifactIds.isEmpty(), "Undeploy dependencies should not be added to dubbo-all(dubbo-distribution" + File.separator + "dubbo-all" + File.separator + "pom.xml). Found modules: " + unexpectedArtifactIds); + Assertions.assertTrue( + unexpectedArtifactIds.isEmpty(), + "Undeploy dependencies should not be added to dubbo-all(dubbo-distribution" + File.separator + + "dubbo-all" + File.separator + "pom.xml). Found modules: " + unexpectedArtifactIds); unexpectedArtifactIds = new LinkedList<>(); for (String artifactId : artifactIdsInDubboAll) { if (!artifactIds.contains(artifactId)) { continue; } - if (ignoredModules.stream().anyMatch(pattern -> pattern.matcher(artifactId).matches())) { + if (ignoredModules.stream() + .anyMatch(pattern -> pattern.matcher(artifactId).matches())) { unexpectedArtifactIds.add(artifactId); } - if (ignoredModulesInDubboAll.stream().anyMatch(pattern -> pattern.matcher(artifactId).matches())) { + if (ignoredModulesInDubboAll.stream() + .anyMatch(pattern -> pattern.matcher(artifactId).matches())) { unexpectedArtifactIds.add(artifactId); } } - Assertions.assertTrue(unexpectedArtifactIds.isEmpty(), "Unexpected dependencies should not be added to dubbo-all(dubbo-distribution" + File.separator + "dubbo-all" + File.separator + "pom.xml). Found modules: " + unexpectedArtifactIds); + Assertions.assertTrue( + unexpectedArtifactIds.isEmpty(), + "Unexpected dependencies should not be added to dubbo-all(dubbo-distribution" + File.separator + + "dubbo-all" + File.separator + "pom.xml). Found modules: " + unexpectedArtifactIds); } @Test @@ -270,84 +295,97 @@ class FileTest { SAXReader reader = new SAXReader(); List artifactIds = poms.stream() - .map(f -> { - try { - return reader.read(f); - } catch (DocumentException e) { - throw new RuntimeException(e); - } - }) - .map(Document::getRootElement) - .map(doc -> doc.elementText("artifactId")) - .sorted() - .collect(Collectors.toList()); + .map(f -> { + try { + return reader.read(f); + } catch (DocumentException e) { + throw new RuntimeException(e); + } + }) + .map(Document::getRootElement) + .map(doc -> doc.elementText("artifactId")) + .sorted() + .collect(Collectors.toList()); Assertions.assertEquals(poms.size(), artifactIds.size()); List deployedArtifactIds = poms.stream() - .map(f -> { - try { - return reader.read(f); - } catch (DocumentException e) { - throw new RuntimeException(e); - } - }) - .map(Document::getRootElement) - .filter(doc -> Objects.isNull(doc.element("properties")) || - (!Objects.equals("true", doc.element("properties").elementText("skip_maven_deploy")) && - !Objects.equals("true", doc.element("properties").elementText("maven.deploy.skip")))) - .filter(doc -> !Objects.equals("pom", doc.elementText("packaging"))) - .map(doc -> doc.elementText("artifactId")) - .sorted() - .collect(Collectors.toList()); + .map(f -> { + try { + return reader.read(f); + } catch (DocumentException e) { + throw new RuntimeException(e); + } + }) + .map(Document::getRootElement) + .filter(doc -> Objects.isNull(doc.element("properties")) + || (!Objects.equals("true", doc.element("properties").elementText("skip_maven_deploy")) + && !Objects.equals( + "true", doc.element("properties").elementText("maven.deploy.skip")))) + .filter(doc -> !Objects.equals("pom", doc.elementText("packaging"))) + .map(doc -> doc.elementText("artifactId")) + .sorted() + .collect(Collectors.toList()); String dubboAllPath = "dubbo-distribution" + File.separator + "dubbo-all" + File.separator + "pom.xml"; Document dubboAll = reader.read(new File(getBaseFile(), dubboAllPath)); - List artifactIdsInDubboAll = dubboAll.getRootElement() - .element("build") - .element("plugins") - .elements("plugin") - .stream() - .filter(ele -> ele.elementText("artifactId").equals("maven-shade-plugin")) - .map(ele -> ele.element("executions")) - .map(ele -> ele.elements("execution")) - .flatMap(Collection::stream) - .filter(ele -> ele.elementText("phase").equals("package")) - .map(ele -> ele.element("configuration")) - .map(ele -> ele.element("artifactSet")) - .map(ele -> ele.element("includes")) - .map(ele -> ele.elements("include")) - .flatMap(Collection::stream) - .map(Element::getText) - .filter(artifactId -> artifactId.startsWith("org.apache.dubbo:")) - .map(artifactId -> artifactId.substring("org.apache.dubbo:".length())) - .collect(Collectors.toList()); + List artifactIdsInDubboAll = + dubboAll.getRootElement().element("build").element("plugins").elements("plugin").stream() + .filter(ele -> ele.elementText("artifactId").equals("maven-shade-plugin")) + .map(ele -> ele.element("executions")) + .map(ele -> ele.elements("execution")) + .flatMap(Collection::stream) + .filter(ele -> ele.elementText("phase").equals("package")) + .map(ele -> ele.element("configuration")) + .map(ele -> ele.element("artifactSet")) + .map(ele -> ele.element("includes")) + .map(ele -> ele.elements("include")) + .flatMap(Collection::stream) + .map(Element::getText) + .filter(artifactId -> artifactId.startsWith("org.apache.dubbo:")) + .map(artifactId -> artifactId.substring("org.apache.dubbo:".length())) + .collect(Collectors.toList()); List expectedArtifactIds = new LinkedList<>(deployedArtifactIds); expectedArtifactIds.removeAll(artifactIdsInDubboAll); - expectedArtifactIds.removeIf(artifactId -> ignoredModules.stream().anyMatch(pattern -> pattern.matcher(artifactId).matches())); - expectedArtifactIds.removeIf(artifactId -> ignoredModulesInDubboAll.stream().anyMatch(pattern -> pattern.matcher(artifactId).matches())); + expectedArtifactIds.removeIf(artifactId -> ignoredModules.stream() + .anyMatch(pattern -> pattern.matcher(artifactId).matches())); + expectedArtifactIds.removeIf(artifactId -> ignoredModulesInDubboAll.stream() + .anyMatch(pattern -> pattern.matcher(artifactId).matches())); - Assertions.assertTrue(expectedArtifactIds.isEmpty(), "Newly created modules must be added to dubbo-all (dubbo-distribution" + File.separator + "dubbo-all" + File.separator + "pom.xml in shade plugin). Found modules: " + expectedArtifactIds); + Assertions.assertTrue( + expectedArtifactIds.isEmpty(), + "Newly created modules must be added to dubbo-all (dubbo-distribution" + File.separator + "dubbo-all" + + File.separator + "pom.xml in shade plugin). Found modules: " + expectedArtifactIds); List unexpectedArtifactIds = new LinkedList<>(artifactIdsInDubboAll); unexpectedArtifactIds.removeIf(artifactId -> !artifactIds.contains(artifactId)); unexpectedArtifactIds.removeAll(deployedArtifactIds); - Assertions.assertTrue(unexpectedArtifactIds.isEmpty(), "Undeploy dependencies should not be added to dubbo-all (dubbo-distribution" + File.separator + "dubbo-all" + File.separator + "pom.xml in shade plugin). Found modules: " + unexpectedArtifactIds); + Assertions.assertTrue( + unexpectedArtifactIds.isEmpty(), + "Undeploy dependencies should not be added to dubbo-all (dubbo-distribution" + File.separator + + "dubbo-all" + File.separator + "pom.xml in shade plugin). Found modules: " + + unexpectedArtifactIds); unexpectedArtifactIds = new LinkedList<>(); for (String artifactId : artifactIdsInDubboAll) { if (!artifactIds.contains(artifactId)) { continue; } - if (ignoredModules.stream().anyMatch(pattern -> pattern.matcher(artifactId).matches())) { + if (ignoredModules.stream() + .anyMatch(pattern -> pattern.matcher(artifactId).matches())) { unexpectedArtifactIds.add(artifactId); } - if (ignoredModulesInDubboAll.stream().anyMatch(pattern -> pattern.matcher(artifactId).matches())) { + if (ignoredModulesInDubboAll.stream() + .anyMatch(pattern -> pattern.matcher(artifactId).matches())) { unexpectedArtifactIds.add(artifactId); } } - Assertions.assertTrue(unexpectedArtifactIds.isEmpty(), "Unexpected dependencies should not be added to dubbo-all (dubbo-distribution" + File.separator + "dubbo-all" + File.separator + "pom.xml in shade plugin). Found modules: " + unexpectedArtifactIds); + Assertions.assertTrue( + unexpectedArtifactIds.isEmpty(), + "Unexpected dependencies should not be added to dubbo-all (dubbo-distribution" + File.separator + + "dubbo-all" + File.separator + "pom.xml in shade plugin). Found modules: " + + unexpectedArtifactIds); } @Test @@ -361,32 +399,37 @@ class FileTest { SAXReader reader = new SAXReader(); Document dubboAll = reader.read(new File(baseFile, dubboAllPath)); - List transformsInDubboAll = dubboAll.getRootElement() - .element("build") - .element("plugins") - .elements("plugin") - .stream() - .filter(ele -> ele.elementText("artifactId").equals("maven-shade-plugin")) - .map(ele -> ele.element("executions")) - .map(ele -> ele.elements("execution")) - .flatMap(Collection::stream) - .filter(ele -> ele.elementText("phase").equals("package")) - .map(ele -> ele.element("configuration")) - .map(ele -> ele.element("transformers")) - .map(ele -> ele.elements("transformer")) - .flatMap(Collection::stream) - .map(ele -> ele.elementText("resource")) - .map(String::trim) - .map(resource -> resource.substring(resource.lastIndexOf("/") + 1)) - .collect(Collectors.toList()); + List transformsInDubboAll = + dubboAll.getRootElement().element("build").element("plugins").elements("plugin").stream() + .filter(ele -> ele.elementText("artifactId").equals("maven-shade-plugin")) + .map(ele -> ele.element("executions")) + .map(ele -> ele.elements("execution")) + .flatMap(Collection::stream) + .filter(ele -> ele.elementText("phase").equals("package")) + .map(ele -> ele.element("configuration")) + .map(ele -> ele.element("transformers")) + .map(ele -> ele.elements("transformer")) + .flatMap(Collection::stream) + .map(ele -> ele.elementText("resource")) + .map(String::trim) + .map(resource -> resource.substring(resource.lastIndexOf("/") + 1)) + .collect(Collectors.toList()); List expectedSpis = new LinkedList<>(spis); expectedSpis.removeAll(transformsInDubboAll); - Assertions.assertTrue(expectedSpis.isEmpty(), "Newly created SPI interface must be added to dubbo-all(dubbo-distribution" + File.separator + "dubbo-all" + File.separator + "pom.xml in shade plugin) to being transformed. Found spis: " + expectedSpis); + Assertions.assertTrue( + expectedSpis.isEmpty(), + "Newly created SPI interface must be added to dubbo-all(dubbo-distribution" + File.separator + + "dubbo-all" + File.separator + "pom.xml in shade plugin) to being transformed. Found spis: " + + expectedSpis); List unexpectedSpis = new LinkedList<>(transformsInDubboAll); unexpectedSpis.removeAll(spis); - Assertions.assertTrue(unexpectedSpis.isEmpty(), "Class without `@SPI` declaration should not be added to dubbo-all(dubbo-distribution" + File.separator + "dubbo-all" + File.separator + "pom.xml in shade plugin) to being transformed. Found spis: " + unexpectedSpis); + Assertions.assertTrue( + unexpectedSpis.isEmpty(), + "Class without `@SPI` declaration should not be added to dubbo-all(dubbo-distribution" + File.separator + + "dubbo-all" + File.separator + "pom.xml in shade plugin) to being transformed. Found spis: " + + unexpectedSpis); } @Test @@ -399,12 +442,21 @@ class FileTest { readSPIResource(baseFile, spiResources); Map copyOfSpis = new HashMap<>(spiResources); copyOfSpis.entrySet().removeIf(entry -> spis.contains(entry.getValue())); - Assertions.assertTrue(copyOfSpis.isEmpty(), "Newly created spi profiles must have a valid class declared with `@SPI`. Found spi profiles: " + copyOfSpis.keySet()); + Assertions.assertTrue( + copyOfSpis.isEmpty(), + "Newly created spi profiles must have a valid class declared with `@SPI`. Found spi profiles: " + + copyOfSpis.keySet()); List unexpectedSpis = new LinkedList<>(); readSPIUnexpectedResource(baseFile, unexpectedSpis); - unexpectedSpis.removeIf(file -> file.getAbsolutePath().contains("dubbo-common" + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "META-INF" + File.separator + "services" + File.separator + "org.apache.dubbo.common.extension.LoadingStrategy")); - Assertions.assertTrue(unexpectedSpis.isEmpty(), "Dubbo native provided spi profiles must filed in `META-INF" + File.separator + "dubbo" + File.separator + "internal`. Please move to proper folder . Found spis: " + unexpectedSpis); + unexpectedSpis.removeIf(file -> file.getAbsolutePath() + .contains("dubbo-common" + File.separator + "src" + File.separator + "main" + File.separator + + "resources" + File.separator + "META-INF" + File.separator + "services" + File.separator + + "org.apache.dubbo.common.extension.LoadingStrategy")); + Assertions.assertTrue( + unexpectedSpis.isEmpty(), + "Dubbo native provided spi profiles must filed in `META-INF" + File.separator + "dubbo" + File.separator + + "internal`. Please move to proper folder . Found spis: " + unexpectedSpis); } private static File getBaseFile() { @@ -460,8 +512,9 @@ class FileTest { } if (content != null && content.contains("@SPI")) { String absolutePath = path.getAbsolutePath(); - absolutePath = absolutePath.substring(absolutePath.lastIndexOf("src" + File.separator + "main" + File.separator + "java" + File.separator) - + ("src" + File.separator + "main" + File.separator + "java" + File.separator).length()); + absolutePath = absolutePath.substring(absolutePath.lastIndexOf( + "src" + File.separator + "main" + File.separator + "java" + File.separator) + + ("src" + File.separator + "main" + File.separator + "java" + File.separator).length()); absolutePath = absolutePath.substring(0, absolutePath.lastIndexOf(".java")); absolutePath = absolutePath.replaceAll(Matcher.quoteReplacement(File.separator), "."); spis.add(absolutePath); @@ -482,10 +535,16 @@ class FileTest { if (path.getAbsolutePath().contains("target")) { return; } - if (path.getAbsolutePath().contains("src" + File.separator + "main" + File.separator + "resources" + File.separator + "META-INF" + File.separator + "dubbo" + File.separator + "internal" + File.separator)) { + if (path.getAbsolutePath() + .contains("src" + File.separator + "main" + File.separator + "resources" + File.separator + + "META-INF" + File.separator + "dubbo" + File.separator + "internal" + File.separator)) { String absolutePath = path.getAbsolutePath(); - absolutePath = absolutePath.substring(absolutePath.lastIndexOf("src" + File.separator + "main" + File.separator + "resources" + File.separator + "META-INF" + File.separator + "dubbo" + File.separator + "internal" + File.separator) - + ("src" + File.separator + "main" + File.separator + "resources" + File.separator + "META-INF" + File.separator + "dubbo" + File.separator + "internal" + File.separator).length()); + absolutePath = absolutePath.substring(absolutePath.lastIndexOf("src" + File.separator + "main" + + File.separator + "resources" + File.separator + "META-INF" + File.separator + "dubbo" + + File.separator + "internal" + File.separator) + + ("src" + File.separator + "main" + File.separator + "resources" + File.separator + "META-INF" + + File.separator + "dubbo" + File.separator + "internal" + File.separator) + .length()); absolutePath = absolutePath.replaceAll(Matcher.quoteReplacement(File.separator), "."); spis.put(path, absolutePath); } @@ -504,35 +563,55 @@ class FileTest { if (path.getAbsolutePath().contains("target")) { return; } - if (path.getAbsolutePath().contains("src" + File.separator + "main" + File.separator + "resources" + File.separator + "META-INF" + File.separator + "dubbo" + File.separator + "org.apache.dubbo")) { + if (path.getAbsolutePath() + .contains("src" + File.separator + "main" + File.separator + "resources" + File.separator + + "META-INF" + File.separator + "dubbo" + File.separator + "org.apache.dubbo")) { spis.add(path); } - if (path.getAbsolutePath().contains("src" + File.separator + "main" + File.separator + "resources" + File.separator + "META-INF" + File.separator + "dubbo" + File.separator + "com.alibaba.dubbo")) { + if (path.getAbsolutePath() + .contains("src" + File.separator + "main" + File.separator + "resources" + File.separator + + "META-INF" + File.separator + "dubbo" + File.separator + "com.alibaba.dubbo")) { spis.add(path); } - if (path.getAbsolutePath().contains("src" + File.separator + "main" + File.separator + "resources" + File.separator + "META-INF" + File.separator + "services" + File.separator + "org.apache.dubbo")) { + if (path.getAbsolutePath() + .contains("src" + File.separator + "main" + File.separator + "resources" + File.separator + + "META-INF" + File.separator + "services" + File.separator + "org.apache.dubbo")) { spis.add(path); } - if (path.getAbsolutePath().contains("src" + File.separator + "main" + File.separator + "resources" + File.separator + "META-INF" + File.separator + "services" + File.separator + "com.alibaba.dubbo")) { + if (path.getAbsolutePath() + .contains("src" + File.separator + "main" + File.separator + "resources" + File.separator + + "META-INF" + File.separator + "services" + File.separator + "com.alibaba.dubbo")) { spis.add(path); } - if (path.getAbsolutePath().contains("src" + File.separator + "main" + File.separator + "resources" + File.separator + "META-INF.dubbo" + File.separator + "org.apache.dubbo")) { + if (path.getAbsolutePath() + .contains("src" + File.separator + "main" + File.separator + "resources" + File.separator + + "META-INF.dubbo" + File.separator + "org.apache.dubbo")) { spis.add(path); } - if (path.getAbsolutePath().contains("src" + File.separator + "main" + File.separator + "resources" + File.separator + "META-INF.dubbo" + File.separator + "com.alibaba.dubbo")) { + if (path.getAbsolutePath() + .contains("src" + File.separator + "main" + File.separator + "resources" + File.separator + + "META-INF.dubbo" + File.separator + "com.alibaba.dubbo")) { spis.add(path); } - if (path.getAbsolutePath().contains("src" + File.separator + "main" + File.separator + "resources" + File.separator + "META-INF.services" + File.separator + "org.apache.dubbo")) { + if (path.getAbsolutePath() + .contains("src" + File.separator + "main" + File.separator + "resources" + File.separator + + "META-INF.services" + File.separator + "org.apache.dubbo")) { spis.add(path); } - if (path.getAbsolutePath().contains("src" + File.separator + "main" + File.separator + "resources" + File.separator + "META-INF.services" + File.separator + "com.alibaba.dubbo")) { + if (path.getAbsolutePath() + .contains("src" + File.separator + "main" + File.separator + "resources" + File.separator + + "META-INF.services" + File.separator + "com.alibaba.dubbo")) { spis.add(path); } - if (path.getAbsolutePath().contains("src" + File.separator + "main" + File.separator + "resources" + File.separator + "META-INF.dubbo.internal" + File.separator + "org.apache.dubbo")) { + if (path.getAbsolutePath() + .contains("src" + File.separator + "main" + File.separator + "resources" + File.separator + + "META-INF.dubbo.internal" + File.separator + "org.apache.dubbo")) { spis.add(path); } - if (path.getAbsolutePath().contains("src" + File.separator + "main" + File.separator + "resources" + File.separator + "META-INF.dubbo.internal" + File.separator + "com.alibaba.dubbo")) { + if (path.getAbsolutePath() + .contains("src" + File.separator + "main" + File.separator + "resources" + File.separator + + "META-INF.dubbo.internal" + File.separator + "com.alibaba.dubbo")) { spis.add(path); } } diff --git a/dubbo-test/dubbo-test-spring/pom.xml b/dubbo-test/dubbo-test-spring/pom.xml index 834bb2c476..a0b4bf91cc 100644 --- a/dubbo-test/dubbo-test-spring/pom.xml +++ b/dubbo-test/dubbo-test-spring/pom.xml @@ -1,3 +1,4 @@ + - - - dubbo-test - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-test + ${revision} + ../pom.xml + - dubbo-test-spring + dubbo-test-spring - - true - 3.2.18.RELEASE - - - - - - - - - org.springframework - spring-framework-bom - ${spring_version} - pom - import - - - + + true + 3.2.18.RELEASE + + + + + - - - org.apache.dubbo - dubbo-test-common - ${project.version} - - - - - org.apache.dubbo - dubbo-registry-multicast - ${project.version} - - - org.apache.dubbo - dubbo-registry-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-registry-nacos - ${project.version} - - - com.alibaba.nacos - nacos-client - - - org.apache.dubbo - dubbo-configcenter-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-configcenter-nacos - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-zookeeper - ${project.version} - - - org.apache.dubbo - dubbo-metadata-report-nacos - ${project.version} - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - - - org.apache.dubbo - dubbo-rpc-rest - ${project.version} - - - org.apache.dubbo - dubbo-config-spring - ${project.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-fastjson2 - ${project.version} - - - org.apache.dubbo - dubbo-serialization-jdk - ${project.version} - - - org.slf4j - slf4j-log4j12 - - - - - org.junit.jupiter - junit-jupiter-engine - compile - - - org.junit.jupiter - junit-jupiter-params - compile - - - org.hamcrest - hamcrest - compile - - - org.junit.jupiter - junit-jupiter-api - compile - - - org.mockito - mockito-core - compile - - - org.mockito - mockito-inline - compile - - - - org.apache.curator - curator-framework - compile - - - org.apache.curator - curator-recipes - compile - - - org.apache.zookeeper - zookeeper - compile - + + org.springframework + spring-framework-bom + ${spring_version} + pom + import + + + + + + + org.apache.dubbo + dubbo-test-common + ${project.version} + + + + + org.apache.dubbo + dubbo-registry-multicast + ${project.version} + + + org.apache.dubbo + dubbo-registry-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-registry-nacos + ${project.version} + + + com.alibaba.nacos + nacos-client + + + org.apache.dubbo + dubbo-configcenter-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-configcenter-nacos + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-zookeeper + ${project.version} + + + org.apache.dubbo + dubbo-metadata-report-nacos + ${project.version} + + + org.apache.dubbo + dubbo-rpc-dubbo + ${project.version} + + + org.apache.dubbo + dubbo-rpc-rest + ${project.version} + + + org.apache.dubbo + dubbo-config-spring + ${project.version} + + + org.apache.dubbo + dubbo-remoting-netty4 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-hessian2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-fastjson2 + ${project.version} + + + org.apache.dubbo + dubbo-serialization-jdk + ${project.version} + + + org.slf4j + slf4j-log4j12 + + + + + org.junit.jupiter + junit-jupiter-engine + compile + + + org.junit.jupiter + junit-jupiter-params + compile + + + org.hamcrest + hamcrest + compile + + + org.junit.jupiter + junit-jupiter-api + compile + + + org.mockito + mockito-core + compile + + + org.mockito + mockito-inline + compile + + + + org.apache.curator + curator-framework + compile + + + org.apache.curator + curator-recipes + compile + + + org.apache.zookeeper + zookeeper + compile + + diff --git a/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/SpringAnnotationBeanTest.java b/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/SpringAnnotationBeanTest.java index f51f19a054..b8e1446148 100644 --- a/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/SpringAnnotationBeanTest.java +++ b/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/SpringAnnotationBeanTest.java @@ -39,13 +39,14 @@ public class SpringAnnotationBeanTest { } @AfterAll - public static void afterAll(){ + public static void afterAll() { DubboBootstrap.reset(); } @Test public void test() { - AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(TestConfiguration.class); + AnnotationConfigApplicationContext applicationContext = + new AnnotationConfigApplicationContext(TestConfiguration.class); TestService testService = applicationContext.getBean(TestService.class); testService.test(); diff --git a/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/SpringJavaConfigBeanTest.java b/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/SpringJavaConfigBeanTest.java index 472132ca52..8f4bb91efa 100644 --- a/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/SpringJavaConfigBeanTest.java +++ b/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/SpringJavaConfigBeanTest.java @@ -36,6 +36,9 @@ import org.apache.dubbo.test.common.api.DemoService; import org.apache.dubbo.test.common.impl.DemoServiceImpl; import org.apache.dubbo.test.spring.context.MockSpringInitCustomizer; +import java.util.Collection; +import java.util.Map; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; @@ -46,9 +49,6 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import java.util.Collection; -import java.util.Map; - public class SpringJavaConfigBeanTest { private static final String MY_PROTOCOL_ID = "myProtocol"; @@ -60,7 +60,7 @@ public class SpringJavaConfigBeanTest { } @AfterAll - public static void afterAll(){ + public static void afterAll() { DubboBootstrap.reset(); } @@ -106,8 +106,10 @@ public class SpringJavaConfigBeanTest { Assertions.assertEquals(2346, protocolConfig.getPort()); Assertions.assertEquals(MY_PROTOCOL_ID, protocolConfig.getId()); - ModuleConfigManager moduleConfigManager = applicationModel.getDefaultModule().getConfigManager(); - ConsumerConfig consumerConfig = moduleConfigManager.getDefaultConsumer().get(); + ModuleConfigManager moduleConfigManager = + applicationModel.getDefaultModule().getConfigManager(); + ConsumerConfig consumerConfig = + moduleConfigManager.getDefaultConsumer().get(); Assertions.assertEquals(1000, consumerConfig.getTimeout()); Assertions.assertEquals("demo", consumerConfig.getGroup()); Assertions.assertEquals(false, consumerConfig.isCheck()); @@ -125,7 +127,7 @@ public class SpringJavaConfigBeanTest { Assertions.assertEquals(5, referenceConfig.getRetries()); DemoService referProxy = (DemoService) referenceConfig.get(); - Assertions.assertTrue( referProxy instanceof DemoService); + Assertions.assertTrue(referProxy instanceof DemoService); String result = referProxy.sayHello("dubbo"); Assertions.assertEquals("Hello dubbo", result); @@ -134,10 +136,8 @@ public class SpringJavaConfigBeanTest { } finally { consumerContext.close(); } - } - @EnableDubbo(scanBasePackages = "") @Configuration static class TestConfiguration { @@ -183,7 +183,6 @@ public class SpringJavaConfigBeanTest { public ReferenceBean demoService() { return new ReferenceBean<>(); } - } @Configuration diff --git a/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/SpringXmlConfigTest.java b/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/SpringXmlConfigTest.java index 8df53b1cfd..d3a75091e9 100644 --- a/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/SpringXmlConfigTest.java +++ b/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/SpringXmlConfigTest.java @@ -44,7 +44,7 @@ public class SpringXmlConfigTest { } @AfterAll - public static void afterAll(){ + public static void afterAll() { DubboBootstrap.reset(); providerContext.close(); } @@ -83,6 +83,5 @@ public class SpringXmlConfigTest { applicationContext.close(); } } - } } diff --git a/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/context/MockSpringInitCustomizer.java b/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/context/MockSpringInitCustomizer.java index e2ec79e800..c794fcf985 100644 --- a/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/context/MockSpringInitCustomizer.java +++ b/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/context/MockSpringInitCustomizer.java @@ -20,6 +20,10 @@ import org.apache.dubbo.config.spring.context.DubboSpringInitContext; import org.apache.dubbo.config.spring.context.DubboSpringInitCustomizer; import org.apache.dubbo.rpc.model.FrameworkModel; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + import org.junit.jupiter.api.Assertions; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; @@ -28,10 +32,6 @@ import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.context.ConfigurableApplicationContext; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - public class MockSpringInitCustomizer implements DubboSpringInitCustomizer { private List contexts = new ArrayList<>(); @@ -41,9 +41,9 @@ public class MockSpringInitCustomizer implements DubboSpringInitCustomizer { this.contexts.add(context); // register post-processor bean, expecting the bean is loaded and invoked by spring container - AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder - .rootBeanDefinition(CustomBeanFactoryPostProcessor.class) - .getBeanDefinition(); + AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition( + CustomBeanFactoryPostProcessor.class) + .getBeanDefinition(); context.getRegistry().registerBeanDefinition(CustomBeanFactoryPostProcessor.class.getName(), beanDefinition); } @@ -62,8 +62,8 @@ public class MockSpringInitCustomizer implements DubboSpringInitCustomizer { public static void checkCustomizer(ConfigurableApplicationContext applicationContext) { Set customizers = FrameworkModel.defaultModel() - .getExtensionLoader(DubboSpringInitCustomizer.class) - .getSupportedExtensionInstances(); + .getExtensionLoader(DubboSpringInitCustomizer.class) + .getSupportedExtensionInstances(); MockSpringInitCustomizer mockCustomizer = null; for (DubboSpringInitCustomizer customizer : customizers) { @@ -86,7 +86,8 @@ public class MockSpringInitCustomizer implements DubboSpringInitCustomizer { Assertions.assertEquals(true, foundInitContext); // expect CustomBeanFactoryPostProcessor is loaded and invoked - CustomBeanFactoryPostProcessor customBeanFactoryPostProcessor = applicationContext.getBean(CustomBeanFactoryPostProcessor.class); + CustomBeanFactoryPostProcessor customBeanFactoryPostProcessor = + applicationContext.getBean(CustomBeanFactoryPostProcessor.class); Assertions.assertEquals(applicationContext.getBeanFactory(), customBeanFactoryPostProcessor.beanFactory); } } diff --git a/dubbo-test/dubbo-test-spring3.2/pom.xml b/dubbo-test/dubbo-test-spring3.2/pom.xml index 78f8c9d2ff..fc5afbdd49 100644 --- a/dubbo-test/dubbo-test-spring3.2/pom.xml +++ b/dubbo-test/dubbo-test-spring3.2/pom.xml @@ -1,3 +1,4 @@ + - - - dubbo-test - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-test + ${revision} + ../pom.xml + - dubbo-test-spring3.2 + dubbo-test-spring3.2 - - true - 3.2.18.RELEASE - - - - - - org.springframework - spring-framework-bom - ${spring_version} - pom - import - - - + + true + 3.2.18.RELEASE + + - - - org.apache.dubbo - dubbo-test-spring - ${project.version} - test - - - org.apache.curator - curator-framework - - - - org.apache.curator - curator-recipes - - - - org.apache.zookeeper - zookeeper - - - + + org.springframework + spring-framework-bom + ${spring_version} + pom + import + + - + + + + org.apache.dubbo + dubbo-test-spring + ${project.version} + test + + + org.apache.curator + curator-framework + + + + org.apache.curator + curator-recipes + + + + org.apache.zookeeper + zookeeper + + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + org.apache.dubbo:dubbo-test-spring + + + + + + + + + jdk15ge-simple + + [15, + + - - org.apache.maven.plugins - maven-surefire-plugin - - - org.apache.dubbo:dubbo-test-spring - - - - - - - - - jdk15ge-simple - - [15, - - - - - org.apache.maven.plugins - maven-surefire-plugin - - true - 1 - false - ${argline} ${jacocoArgLine} + + org.apache.maven.plugins + maven-surefire-plugin + + true + 1 + false + ${argline} ${jacocoArgLine} --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.math=ALL-UNNAMED - --add-opens java.base/java.util=ALL-UNNAMED - - - - - - - - - - - - + --add-opens java.base/java.util=ALL-UNNAMED + + + + + + + + + + + diff --git a/dubbo-test/dubbo-test-spring4.1/pom.xml b/dubbo-test/dubbo-test-spring4.1/pom.xml index 64c9b36511..5dd84f31e4 100644 --- a/dubbo-test/dubbo-test-spring4.1/pom.xml +++ b/dubbo-test/dubbo-test-spring4.1/pom.xml @@ -1,3 +1,4 @@ + - - - dubbo-test - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-test + ${revision} + ../pom.xml + - dubbo-test-spring4.1 + dubbo-test-spring4.1 - - true - 4.1.9.RELEASE - - - - - - org.springframework - spring-framework-bom - ${spring_version} - pom - import - - - + + true + 4.1.9.RELEASE + + - - - org.apache.dubbo - dubbo-test-spring - ${project.version} - test - - - org.apache.curator - curator-framework - - - - org.apache.curator - curator-recipes - - - - org.apache.zookeeper - zookeeper - - - + + org.springframework + spring-framework-bom + ${spring_version} + pom + import + + - + + + + org.apache.dubbo + dubbo-test-spring + ${project.version} + test + + + org.apache.curator + curator-framework + + + + org.apache.curator + curator-recipes + + + + org.apache.zookeeper + zookeeper + + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + org.apache.dubbo:dubbo-test-spring + + + + + + + + + jdk15ge-simple + + [15, + + - - org.apache.maven.plugins - maven-surefire-plugin - - - org.apache.dubbo:dubbo-test-spring - - - - - - - - - jdk15ge-simple - - [15, - - - - - org.apache.maven.plugins - maven-surefire-plugin - - true - 1 - false - ${argline} ${jacocoArgLine} + + org.apache.maven.plugins + maven-surefire-plugin + + true + 1 + false + ${argline} ${jacocoArgLine} --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.math=ALL-UNNAMED - --add-opens java.base/java.util=ALL-UNNAMED - - - - - - - - - - - - + --add-opens java.base/java.util=ALL-UNNAMED + + + + + + + + + + + diff --git a/dubbo-test/dubbo-test-spring4.2/pom.xml b/dubbo-test/dubbo-test-spring4.2/pom.xml index d4c0ac2555..6030243cd5 100644 --- a/dubbo-test/dubbo-test-spring4.2/pom.xml +++ b/dubbo-test/dubbo-test-spring4.2/pom.xml @@ -1,3 +1,4 @@ + - - - dubbo-test - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 + + 4.0.0 + + org.apache.dubbo + dubbo-test + ${revision} + ../pom.xml + - dubbo-test-spring4.2 + dubbo-test-spring4.2 - - true - 4.2.4.RELEASE - - - - - - org.springframework - spring-framework-bom - ${spring_version} - pom - import - - - + + true + 4.2.4.RELEASE + + - - - org.apache.dubbo - dubbo-test-spring - ${project.version} - test - - - org.apache.curator - curator-framework - - - - org.apache.curator - curator-recipes - - - - org.apache.zookeeper - zookeeper - - - + + org.springframework + spring-framework-bom + ${spring_version} + pom + import + + - + + + + org.apache.dubbo + dubbo-test-spring + ${project.version} + test + + + org.apache.curator + curator-framework + + + + org.apache.curator + curator-recipes + + + + org.apache.zookeeper + zookeeper + + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + org.apache.dubbo:dubbo-test-spring + + + + + + + + + jdk15ge-simple + + [15, + + - - org.apache.maven.plugins - maven-surefire-plugin - - - org.apache.dubbo:dubbo-test-spring - - - - - - - - - jdk15ge-simple - - [15, - - - - - org.apache.maven.plugins - maven-surefire-plugin - - true - 1 - false - ${argline} ${jacocoArgLine} + + org.apache.maven.plugins + maven-surefire-plugin + + true + 1 + false + ${argline} ${jacocoArgLine} --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.math=ALL-UNNAMED - --add-opens java.base/java.util=ALL-UNNAMED - - - - - - - - - - - - + --add-opens java.base/java.util=ALL-UNNAMED + + + + + + + + + + + diff --git a/dubbo-test/pom.xml b/dubbo-test/pom.xml index 180d478462..80807b77ad 100644 --- a/dubbo-test/pom.xml +++ b/dubbo-test/pom.xml @@ -1,3 +1,4 @@ + - - - org.apache.dubbo - dubbo-parent - ${revision} - ../pom.xml - - 4.0.0 - dubbo-test - pom + + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + + dubbo-test + pom - - dubbo-test-check - dubbo-test-common - dubbo-test-spring - dubbo-test-spring3.2 - dubbo-test-spring4.1 - dubbo-test-spring4.2 - dubbo-dependencies-all - dubbo-test-modules - + + dubbo-test-check + dubbo-test-common + dubbo-test-spring + dubbo-test-spring3.2 + dubbo-test-spring4.1 + dubbo-test-spring4.2 + dubbo-dependencies-all + dubbo-test-modules + - - true - + + true + diff --git a/dubbo-xds/pom.xml b/dubbo-xds/pom.xml index 21b287adef..d44a6abd86 100644 --- a/dubbo-xds/pom.xml +++ b/dubbo-xds/pom.xml @@ -15,119 +15,117 @@ See the License for the specific language governing permissions and limitations under the License. --> - - 4.0.0 - - org.apache.dubbo - dubbo-parent - ${revision} - ../pom.xml - + + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../pom.xml + - dubbo-xds - ${project.artifactId} - The xDS Integration - - false - + dubbo-xds + ${project.artifactId} + The xDS Integration + + false + - + - - org.apache.dubbo - dubbo-registry-api - ${project.version} - + + org.apache.dubbo + dubbo-registry-api + ${project.version} + - - org.apache.dubbo - dubbo-common - ${project.version} - + + org.apache.dubbo + dubbo-common + ${project.version} + - - io.grpc - grpc-protobuf - + + io.grpc + grpc-protobuf + - - io.grpc - grpc-stub - + + io.grpc + grpc-stub + - - io.grpc - grpc-netty-shaded - + + io.grpc + grpc-netty-shaded + - - io.envoyproxy.controlplane - api - + + io.envoyproxy.controlplane + api + - - com.google.protobuf - protobuf-java - + + com.google.protobuf + protobuf-java + - - com.google.protobuf - protobuf-java-util - + + com.google.protobuf + protobuf-java-util + - - org.bouncycastle - bcprov-jdk15on - - - org.bouncycastle - bcpkix-jdk15on - - - org.bouncycastle - bcprov-ext-jdk15on - + + org.bouncycastle + bcprov-jdk15on + + + org.bouncycastle + bcpkix-jdk15on + + + org.bouncycastle + bcprov-ext-jdk15on + - + - - - - kr.motd.maven - os-maven-plugin - ${maven_os_plugin_version} - - - - - org.xolstice.maven.plugins - protobuf-maven-plugin - ${maven_protobuf_plugin_version} - - com.google.protobuf:protoc:${protobuf-protoc_version}:exe:${os.detected.classifier} - grpc-java - io.grpc:protoc-gen-grpc-java:${grpc_version}:exe:${os.detected.classifier} - - - - - compile - compile-custom - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - true - - - - + + + + org.xolstice.maven.plugins + protobuf-maven-plugin + ${maven_protobuf_plugin_version} + + com.google.protobuf:protoc:${protobuf-protoc_version}:exe:${os.detected.classifier} + grpc-java + io.grpc:protoc-gen-grpc-java:${grpc_version}:exe:${os.detected.classifier} + + + + + compile + compile-custom + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + + true + + + + + + kr.motd.maven + os-maven-plugin + ${maven_os_plugin_version} + + + diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsInitializationException.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsInitializationException.java index b79f55c717..9a9b9a35ca 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsInitializationException.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsInitializationException.java @@ -18,11 +18,11 @@ package org.apache.dubbo.registry.xds; public final class XdsInitializationException extends Exception { - public XdsInitializationException(String message) { - super(message); - } + public XdsInitializationException(String message) { + super(message); + } - public XdsInitializationException(String message, Throwable cause) { - super(message, cause); - } + public XdsInitializationException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsRegistry.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsRegistry.java index a4bd51e6b1..30e005ffe7 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsRegistry.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsRegistry.java @@ -37,22 +37,14 @@ public class XdsRegistry extends FailbackRegistry { } @Override - public void doRegister(URL url) { - - } + public void doRegister(URL url) {} @Override - public void doUnregister(URL url) { - - } + public void doUnregister(URL url) {} @Override - public void doSubscribe(URL url, NotifyListener listener) { - - } + public void doSubscribe(URL url, NotifyListener listener) {} @Override - public void doUnsubscribe(URL url, NotifyListener listener) { - - } + public void doUnsubscribe(URL url, NotifyListener listener) {} } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsServiceDiscovery.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsServiceDiscovery.java index b40b68650b..3385ff97a0 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsServiceDiscovery.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsServiceDiscovery.java @@ -16,12 +16,6 @@ */ package org.apache.dubbo.registry.xds; -import java.util.Collection; -import java.util.Comparator; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -34,6 +28,12 @@ import org.apache.dubbo.registry.xds.util.protocol.message.Endpoint; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ScopeModelUtil; +import java.util.Collection; +import java.util.Comparator; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_INITIALIZE_XDS; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_PARSING_XDS; @@ -80,22 +80,35 @@ public class XdsServiceDiscovery extends ReflectionBasedServiceDiscovery { } @Override - public void addServiceInstancesChangedListener(ServiceInstancesChangedListener listener) throws NullPointerException, IllegalArgumentException { - listener.getServiceNames().forEach(serviceName -> exchanger.observeEndpoints(serviceName, - (endpoints -> notifyListener(serviceName, listener, changedToInstances(serviceName, endpoints))))); + public void addServiceInstancesChangedListener(ServiceInstancesChangedListener listener) + throws NullPointerException, IllegalArgumentException { + listener.getServiceNames() + .forEach(serviceName -> exchanger.observeEndpoints( + serviceName, + (endpoints -> + notifyListener(serviceName, listener, changedToInstances(serviceName, endpoints))))); } private List changedToInstances(String serviceName, Collection endpoints) { List instances = new LinkedList<>(); endpoints.forEach(endpoint -> { try { - DefaultServiceInstance serviceInstance = new DefaultServiceInstance(serviceName, endpoint.getAddress(), endpoint.getPortValue(), ScopeModelUtil.getApplicationModel(getUrl().getScopeModel())); + DefaultServiceInstance serviceInstance = new DefaultServiceInstance( + serviceName, + endpoint.getAddress(), + endpoint.getPortValue(), + ScopeModelUtil.getApplicationModel(getUrl().getScopeModel())); // fill metadata by SelfHostMetaServiceDiscovery, will be fetched by RPC request serviceInstance.putExtendParam("clusterName", endpoint.getClusterName()); fillServiceInstance(serviceInstance); instances.add(serviceInstance); } catch (Throwable t) { - logger.error(REGISTRY_ERROR_PARSING_XDS, "", "", "Error occurred when parsing endpoints. Endpoints List:" + endpoints, t); + logger.error( + REGISTRY_ERROR_PARSING_XDS, + "", + "", + "Error occurred when parsing endpoints. Endpoints List:" + endpoints, + t); } }); instances.sort(Comparator.comparingInt(ServiceInstance::hashCode)); diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsServiceDiscoveryFactory.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsServiceDiscoveryFactory.java index 706e230c51..0f763c59c9 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsServiceDiscoveryFactory.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/XdsServiceDiscoveryFactory.java @@ -27,7 +27,8 @@ import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERR public class XdsServiceDiscoveryFactory extends AbstractServiceDiscoveryFactory { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(XdsServiceDiscoveryFactory.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(XdsServiceDiscoveryFactory.class); @Override protected ServiceDiscovery createDiscovery(URL registryURL) { @@ -35,7 +36,12 @@ public class XdsServiceDiscoveryFactory extends AbstractServiceDiscoveryFactory try { xdsServiceDiscovery.doInitialize(registryURL); } catch (Exception e) { - logger.error(REGISTRY_ERROR_INITIALIZE_XDS, "", "", "Error occurred when initialize xDS service discovery impl.", e); + logger.error( + REGISTRY_ERROR_INITIALIZE_XDS, + "", + "", + "Error occurred when initialize xDS service discovery impl.", + e); } return xdsServiceDiscovery; } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/istio/IstioCitadelCertificateSigner.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/istio/IstioCitadelCertificateSigner.java index 99225b0316..db54ea5628 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/istio/IstioCitadelCertificateSigner.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/istio/IstioCitadelCertificateSigner.java @@ -23,6 +23,24 @@ import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.registry.xds.XdsCertificateSigner; import org.apache.dubbo.rpc.RpcException; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.StringWriter; +import java.nio.charset.StandardCharsets; +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.spec.ECGenParameterSpec; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + import io.grpc.ManagedChannel; import io.grpc.Metadata; import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; @@ -47,31 +65,14 @@ import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder; import org.bouncycastle.util.io.pem.PemObject; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.StringWriter; -import java.nio.charset.StandardCharsets; -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.spec.ECGenParameterSpec; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_GENERATE_CERT_ISTIO; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_GENERATE_KEY_ISTIO; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_RECEIVE_ERROR_MSG_ISTIO; public class IstioCitadelCertificateSigner implements XdsCertificateSigner { - private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(IstioCitadelCertificateSigner.class); + private static final ErrorTypeAwareLogger logger = + LoggerFactory.getErrorTypeAwareLogger(IstioCitadelCertificateSigner.class); private final org.apache.dubbo.registry.xds.istio.IstioEnv istioEnv; @@ -129,8 +130,13 @@ public class IstioCitadelCertificateSigner implements XdsCertificateSigner { privateKey = keypair.getPrivate(); signer = new JcaContentSignerBuilder("SHA256withECDSA").build(keypair.getPrivate()); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | OperatorCreationException e) { - logger.error(REGISTRY_FAILED_GENERATE_KEY_ISTIO, "", "", "Generate Key with secp256r1 algorithm failed. Please check if your system support. " - + "Will attempt to generate with RSA2048.", e); + logger.error( + REGISTRY_FAILED_GENERATE_KEY_ISTIO, + "", + "", + "Generate Key with secp256r1 algorithm failed. Please check if your system support. " + + "Will attempt to generate with RSA2048.", + e); } } @@ -143,7 +149,12 @@ public class IstioCitadelCertificateSigner implements XdsCertificateSigner { privateKey = keypair.getPrivate(); signer = new JcaContentSignerBuilder("SHA256WithRSA").build(keypair.getPrivate()); } catch (NoSuchAlgorithmException | OperatorCreationException e) { - logger.error(REGISTRY_FAILED_GENERATE_KEY_ISTIO, "", "", "Generate Key with SHA256WithRSA algorithm failed. Please check if your system support.", e); + logger.error( + REGISTRY_FAILED_GENERATE_KEY_ISTIO, + "", + "", + "Generate Key with SHA256WithRSA algorithm failed. Please check if your system support.", + e); throw new RpcException(e); } } @@ -153,17 +164,16 @@ public class IstioCitadelCertificateSigner implements XdsCertificateSigner { ManagedChannel channel; if (StringUtils.isNotEmpty(caCert)) { channel = NettyChannelBuilder.forTarget(istioEnv.getCaAddr()) - .sslContext( - GrpcSslContexts.forClient() - .trustManager(new ByteArrayInputStream(caCert.getBytes(StandardCharsets.UTF_8))) - .build()) - .build(); + .sslContext(GrpcSslContexts.forClient() + .trustManager(new ByteArrayInputStream(caCert.getBytes(StandardCharsets.UTF_8))) + .build()) + .build(); } else { channel = NettyChannelBuilder.forTarget(istioEnv.getCaAddr()) - .sslContext(GrpcSslContexts.forClient() - .trustManager(InsecureTrustManagerFactory.INSTANCE) - .build()) - .build(); + .sslContext(GrpcSslContexts.forClient() + .trustManager(InsecureTrustManagerFactory.INSTANCE) + .build()) + .build(); } Metadata header = new Metadata(); @@ -180,9 +190,11 @@ public class IstioCitadelCertificateSigner implements XdsCertificateSigner { CountDownLatch countDownLatch = new CountDownLatch(1); StringBuffer publicKeyBuilder = new StringBuffer(); AtomicBoolean failed = new AtomicBoolean(false); - stub.createCertificate(generateRequest(csr), generateResponseObserver(countDownLatch, publicKeyBuilder, failed)); + stub.createCertificate( + generateRequest(csr), generateResponseObserver(countDownLatch, publicKeyBuilder, failed)); - long expireTime = System.currentTimeMillis() + (long) (istioEnv.getSecretTTL() * istioEnv.getSecretGracePeriodRatio()); + long expireTime = + System.currentTimeMillis() + (long) (istioEnv.getSecretTTL() * istioEnv.getSecretGracePeriodRatio()); try { countDownLatch.await(); @@ -195,24 +207,28 @@ public class IstioCitadelCertificateSigner implements XdsCertificateSigner { } String privateKeyPem = generatePrivatePemKey(privateKey); - CertPair certPair = new CertPair(privateKeyPem, publicKeyBuilder.toString(), System.currentTimeMillis(), expireTime); + CertPair certPair = + new CertPair(privateKeyPem, publicKeyBuilder.toString(), System.currentTimeMillis(), expireTime); channel.shutdown(); return certPair; } private IstioCertificateRequest generateRequest(String csr) { - return IstioCertificateRequest.newBuilder().setCsr(csr).setValidityDuration(istioEnv.getSecretTTL()).build(); + return IstioCertificateRequest.newBuilder() + .setCsr(csr) + .setValidityDuration(istioEnv.getSecretTTL()) + .build(); } - private StreamObserver generateResponseObserver(CountDownLatch countDownLatch, - StringBuffer publicKeyBuilder, - AtomicBoolean failed) { + private StreamObserver generateResponseObserver( + CountDownLatch countDownLatch, StringBuffer publicKeyBuilder, AtomicBoolean failed) { return new StreamObserver() { @Override public void onNext(IstioCertificateResponse istioCertificateResponse) { for (int i = 0; i < istioCertificateResponse.getCertChainCount(); i++) { - publicKeyBuilder.append(istioCertificateResponse.getCertChainBytes(i).toStringUtf8()); + publicKeyBuilder.append( + istioCertificateResponse.getCertChainBytes(i).toStringUtf8()); } if (logger.isDebugEnabled()) { logger.debug("Receive Cert chain from Istio Citadel. \n" + publicKeyBuilder); @@ -223,7 +239,12 @@ public class IstioCitadelCertificateSigner implements XdsCertificateSigner { @Override public void onError(Throwable throwable) { failed.set(true); - logger.error(REGISTRY_RECEIVE_ERROR_MSG_ISTIO, "", "", "Receive error message from Istio Citadel grpc stub.", throwable); + logger.error( + REGISTRY_RECEIVE_ERROR_MSG_ISTIO, + "", + "", + "Receive error message from Istio Citadel grpc stub.", + throwable); countDownLatch.countDown(); } @@ -253,14 +274,15 @@ public class IstioCitadelCertificateSigner implements XdsCertificateSigner { } private String generateCsr(PublicKey publicKey, ContentSigner signer) throws IOException { - GeneralNames subjectAltNames = new GeneralNames(new GeneralName[]{new GeneralName(6, istioEnv.getCsrHost())}); + GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] {new GeneralName(6, istioEnv.getCsrHost())}); ExtensionsGenerator extGen = new ExtensionsGenerator(); extGen.addExtension(Extension.subjectAlternativeName, true, subjectAltNames); PKCS10CertificationRequest request = new JcaPKCS10CertificationRequestBuilder( - new X500Name("O=" + istioEnv.getTrustDomain()), publicKey).addAttribute( - PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate()).build(signer); + new X500Name("O=" + istioEnv.getTrustDomain()), publicKey) + .addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate()) + .build(signer); String csr = generatePemKey("CERTIFICATE REQUEST", request.getEncoded()); diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/istio/IstioConstant.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/istio/IstioConstant.java index 9787643674..018fa3a0fa 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/istio/IstioConstant.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/istio/IstioConstant.java @@ -20,91 +20,90 @@ public class IstioConstant { /** * Address of the spiffe certificate provider. Defaults to discoveryAddress */ - public final static String CA_ADDR_KEY = "CA_ADDR"; + public static final String CA_ADDR_KEY = "CA_ADDR"; /** * CA and xDS services */ - public final static String DEFAULT_CA_ADDR = "istiod.istio-system.svc:15012"; + public static final String DEFAULT_CA_ADDR = "istiod.istio-system.svc:15012"; /** * The trust domain for spiffe certificates */ - public final static String TRUST_DOMAIN_KEY = "TRUST_DOMAIN"; + public static final String TRUST_DOMAIN_KEY = "TRUST_DOMAIN"; /** * The trust domain for spiffe certificates default value */ - public final static String DEFAULT_TRUST_DOMAIN = "cluster.local"; + public static final String DEFAULT_TRUST_DOMAIN = "cluster.local"; - public final static String WORKLOAD_NAMESPACE_KEY = "WORKLOAD_NAMESPACE"; + public static final String WORKLOAD_NAMESPACE_KEY = "WORKLOAD_NAMESPACE"; - public final static String DEFAULT_WORKLOAD_NAMESPACE = "default"; + public static final String DEFAULT_WORKLOAD_NAMESPACE = "default"; /** * k8s jwt token */ - public final static String KUBERNETES_SA_PATH = "/var/run/secrets/kubernetes.io/serviceaccount/token"; + public static final String KUBERNETES_SA_PATH = "/var/run/secrets/kubernetes.io/serviceaccount/token"; - public final static String KUBERNETES_CA_PATH = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt"; + public static final String KUBERNETES_CA_PATH = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt"; - public final static String ISTIO_SA_PATH = "/var/run/secrets/tokens/istio-token"; + public static final String ISTIO_SA_PATH = "/var/run/secrets/tokens/istio-token"; - public final static String ISTIO_CA_PATH = "/var/run/secrets/istio/root-cert.pem"; + public static final String ISTIO_CA_PATH = "/var/run/secrets/istio/root-cert.pem"; - public final static String KUBERNETES_NAMESPACE_PATH = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"; + public static final String KUBERNETES_NAMESPACE_PATH = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"; - public final static String RSA_KEY_SIZE_KEY = "RSA_KEY_SIZE"; + public static final String RSA_KEY_SIZE_KEY = "RSA_KEY_SIZE"; - public final static String DEFAULT_RSA_KEY_SIZE = "2048"; + public static final String DEFAULT_RSA_KEY_SIZE = "2048"; /** * The type of ECC signature algorithm to use when generating private keys */ - public final static String ECC_SIG_ALG_KEY = "ECC_SIGNATURE_ALGORITHM"; + public static final String ECC_SIG_ALG_KEY = "ECC_SIGNATURE_ALGORITHM"; - public final static String DEFAULT_ECC_SIG_ALG = "ECDSA"; + public static final String DEFAULT_ECC_SIG_ALG = "ECDSA"; /** * The cert lifetime requested by istio agent */ - public final static String SECRET_TTL_KEY = "SECRET_TTL"; + public static final String SECRET_TTL_KEY = "SECRET_TTL"; /** * The cert lifetime default value 24h0m0s */ - public final static String DEFAULT_SECRET_TTL = "86400"; //24 * 60 * 60 + public static final String DEFAULT_SECRET_TTL = "86400"; // 24 * 60 * 60 /** * The grace period ratio for the cert rotation */ - public final static String SECRET_GRACE_PERIOD_RATIO_KEY = "SECRET_GRACE_PERIOD_RATIO"; + public static final String SECRET_GRACE_PERIOD_RATIO_KEY = "SECRET_GRACE_PERIOD_RATIO"; /** * The grace period ratio for the cert rotation, by default 0.5 */ - public final static String DEFAULT_SECRET_GRACE_PERIOD_RATIO = "0.5"; + public static final String DEFAULT_SECRET_GRACE_PERIOD_RATIO = "0.5"; - public final static String ISTIO_META_CLUSTER_ID_KEY = "ISTIO_META_CLUSTER_ID"; + public static final String ISTIO_META_CLUSTER_ID_KEY = "ISTIO_META_CLUSTER_ID"; - public final static String PILOT_CERT_PROVIDER_KEY = "PILOT_CERT_PROVIDER"; + public static final String PILOT_CERT_PROVIDER_KEY = "PILOT_CERT_PROVIDER"; - public final static String ISTIO_PILOT_CERT_PROVIDER = "istiod"; + public static final String ISTIO_PILOT_CERT_PROVIDER = "istiod"; - public final static String DEFAULT_ISTIO_META_CLUSTER_ID = "Kubernetes"; + public static final String DEFAULT_ISTIO_META_CLUSTER_ID = "Kubernetes"; - public final static String SPIFFE = "spiffe://"; + public static final String SPIFFE = "spiffe://"; - public final static String NS = "/ns/"; + public static final String NS = "/ns/"; - public final static String SA = "/sa/"; + public static final String SA = "/sa/"; - public final static String JWT_POLICY = "JWT_POLICY"; + public static final String JWT_POLICY = "JWT_POLICY"; - public final static String DEFAULT_JWT_POLICY = "first-party-jwt"; + public static final String DEFAULT_JWT_POLICY = "first-party-jwt"; - public final static String FIRST_PARTY_JWT = "first-party-jwt"; - - public final static String THIRD_PARTY_JWT = "third-party-jwt"; + public static final String FIRST_PARTY_JWT = "first-party-jwt"; + public static final String THIRD_PARTY_JWT = "third-party-jwt"; } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/istio/IstioEnv.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/istio/IstioEnv.java index 3ff1d1dfe5..e508e7cc29 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/istio/IstioEnv.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/istio/IstioEnv.java @@ -21,13 +21,13 @@ import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.registry.xds.XdsEnv; -import org.apache.commons.io.FileUtils; - import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Optional; +import org.apache.commons.io.FileUtils; + import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_READ_FILE_ISTIO; import static org.apache.dubbo.registry.xds.istio.IstioConstant.NS; import static org.apache.dubbo.registry.xds.istio.IstioConstant.SA; @@ -61,32 +61,41 @@ public class IstioEnv implements XdsEnv { private String pilotCertProvider; private IstioEnv() { - jwtPolicy = Optional.ofNullable(System.getenv(IstioConstant.JWT_POLICY)).orElse(IstioConstant.DEFAULT_JWT_POLICY); + jwtPolicy = + Optional.ofNullable(System.getenv(IstioConstant.JWT_POLICY)).orElse(IstioConstant.DEFAULT_JWT_POLICY); podName = Optional.ofNullable(System.getenv("POD_NAME")).orElse(System.getenv("HOSTNAME")); - trustDomain = Optional.ofNullable(System.getenv(IstioConstant.TRUST_DOMAIN_KEY)).orElse(IstioConstant.DEFAULT_TRUST_DOMAIN); + trustDomain = Optional.ofNullable(System.getenv(IstioConstant.TRUST_DOMAIN_KEY)) + .orElse(IstioConstant.DEFAULT_TRUST_DOMAIN); workloadNameSpace = Optional.ofNullable(System.getenv(IstioConstant.WORKLOAD_NAMESPACE_KEY)) - .orElseGet(()->{ - File namespaceFile = new File(IstioConstant.KUBERNETES_NAMESPACE_PATH); - if (namespaceFile.canRead()) { - try { - return FileUtils.readFileToString(namespaceFile, StandardCharsets.UTF_8); - } catch (IOException e) { - logger.error(REGISTRY_ERROR_READ_FILE_ISTIO, "", "", "read namespace file error", e); + .orElseGet(() -> { + File namespaceFile = new File(IstioConstant.KUBERNETES_NAMESPACE_PATH); + if (namespaceFile.canRead()) { + try { + return FileUtils.readFileToString(namespaceFile, StandardCharsets.UTF_8); + } catch (IOException e) { + logger.error(REGISTRY_ERROR_READ_FILE_ISTIO, "", "", "read namespace file error", e); + } } - } - return IstioConstant.DEFAULT_WORKLOAD_NAMESPACE; - }); + return IstioConstant.DEFAULT_WORKLOAD_NAMESPACE; + }); caAddr = Optional.ofNullable(System.getenv(IstioConstant.CA_ADDR_KEY)).orElse(IstioConstant.DEFAULT_CA_ADDR); - rasKeySize = Integer.parseInt(Optional.ofNullable(System.getenv(IstioConstant.RSA_KEY_SIZE_KEY)).orElse(IstioConstant.DEFAULT_RSA_KEY_SIZE)); - eccSigAlg = Optional.ofNullable(System.getenv(IstioConstant.ECC_SIG_ALG_KEY)).orElse(IstioConstant.DEFAULT_ECC_SIG_ALG); - secretTTL = Integer.parseInt(Optional.ofNullable(System.getenv(IstioConstant.SECRET_TTL_KEY)).orElse(IstioConstant.DEFAULT_SECRET_TTL)); - secretGracePeriodRatio = Float.parseFloat(Optional.ofNullable(System.getenv(IstioConstant.SECRET_GRACE_PERIOD_RATIO_KEY)).orElse(IstioConstant.DEFAULT_SECRET_GRACE_PERIOD_RATIO)); - istioMetaClusterId = Optional.ofNullable(System.getenv(IstioConstant.ISTIO_META_CLUSTER_ID_KEY)).orElse(IstioConstant.DEFAULT_ISTIO_META_CLUSTER_ID); - pilotCertProvider = Optional.ofNullable(System.getenv(IstioConstant.PILOT_CERT_PROVIDER_KEY)).orElse(""); + rasKeySize = Integer.parseInt(Optional.ofNullable(System.getenv(IstioConstant.RSA_KEY_SIZE_KEY)) + .orElse(IstioConstant.DEFAULT_RSA_KEY_SIZE)); + eccSigAlg = Optional.ofNullable(System.getenv(IstioConstant.ECC_SIG_ALG_KEY)) + .orElse(IstioConstant.DEFAULT_ECC_SIG_ALG); + secretTTL = Integer.parseInt(Optional.ofNullable(System.getenv(IstioConstant.SECRET_TTL_KEY)) + .orElse(IstioConstant.DEFAULT_SECRET_TTL)); + secretGracePeriodRatio = + Float.parseFloat(Optional.ofNullable(System.getenv(IstioConstant.SECRET_GRACE_PERIOD_RATIO_KEY)) + .orElse(IstioConstant.DEFAULT_SECRET_GRACE_PERIOD_RATIO)); + istioMetaClusterId = Optional.ofNullable(System.getenv(IstioConstant.ISTIO_META_CLUSTER_ID_KEY)) + .orElse(IstioConstant.DEFAULT_ISTIO_META_CLUSTER_ID); + pilotCertProvider = Optional.ofNullable(System.getenv(IstioConstant.PILOT_CERT_PROVIDER_KEY)) + .orElse(""); if (getServiceAccount() == null) { - throw new UnsupportedOperationException("Unable to found kubernetes service account token file. " + - "Please check if work in Kubernetes and mount service account token file correctly."); + throw new UnsupportedOperationException("Unable to found kubernetes service account token file. " + + "Please check if work in Kubernetes and mount service account token file correctly."); } } @@ -116,7 +125,12 @@ public class IstioEnv implements XdsEnv { try { return FileUtils.readFileToString(saFile, StandardCharsets.UTF_8); } catch (IOException e) { - logger.error(LoggerCodeConstants.REGISTRY_ISTIO_EXCEPTION, "File Read Failed", "", "Unable to read token file.", e); + logger.error( + LoggerCodeConstants.REGISTRY_ISTIO_EXCEPTION, + "File Read Failed", + "", + "Unable to read token file.", + e); } } @@ -172,7 +186,8 @@ public class IstioEnv implements XdsEnv { try { return FileUtils.readFileToString(caFile, StandardCharsets.UTF_8); } catch (IOException e) { - logger.error(LoggerCodeConstants.REGISTRY_ISTIO_EXCEPTION, "File Read Failed", "", "read ca file error", e); + logger.error( + LoggerCodeConstants.REGISTRY_ISTIO_EXCEPTION, "File Read Failed", "", "read ca file error", e); } } return null; diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/AdsObserver.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/AdsObserver.java index 9727dd67c1..5e1734806d 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/AdsObserver.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/AdsObserver.java @@ -16,11 +16,6 @@ */ package org.apache.dubbo.registry.xds.util; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; @@ -29,6 +24,11 @@ import org.apache.dubbo.registry.xds.util.protocol.AbstractProtocol; import org.apache.dubbo.registry.xds.util.protocol.DeltaResource; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + import io.envoyproxy.envoy.config.core.v3.Node; import io.envoyproxy.envoy.service.discovery.v3.DiscoveryRequest; import io.envoyproxy.envoy.service.discovery.v3.DiscoveryResponse; @@ -85,12 +85,15 @@ public class AdsObserver { protected DiscoveryRequest buildAck(DiscoveryResponse response) { // for ACK return DiscoveryRequest.newBuilder() - .setNode(adsObserver.node) - .setTypeUrl(response.getTypeUrl()) - .setVersionInfo(response.getVersionInfo()) - .setResponseNonce(response.getNonce()) - .addAllResourceNames(adsObserver.observedResources.get(response.getTypeUrl()).getResourceNamesList()) - .build(); + .setNode(adsObserver.node) + .setTypeUrl(response.getTypeUrl()) + .setVersionInfo(response.getVersionInfo()) + .setResponseNonce(response.getNonce()) + .addAllResourceNames(adsObserver + .observedResources + .get(response.getTypeUrl()) + .getResourceNamesList()) + .build(); } @Override @@ -107,8 +110,11 @@ public class AdsObserver { } private void triggerReConnectTask() { - ScheduledExecutorService scheduledFuture = applicationModel.getFrameworkModel().getBeanFactory() - .getBean(FrameworkExecutorRepository.class).getSharedScheduledExecutor(); + ScheduledExecutorService scheduledFuture = applicationModel + .getFrameworkModel() + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class) + .getSharedScheduledExecutor(); scheduledFuture.schedule(this::recover, 3, TimeUnit.SECONDS); } @@ -120,7 +126,11 @@ public class AdsObserver { observedResources.values().forEach(requestObserver::onNext); return; } else { - logger.error(REGISTRY_ERROR_REQUEST_XDS, "", "", "Recover failed for xDS connection. Will retry. Create channel failed."); + logger.error( + REGISTRY_ERROR_REQUEST_XDS, + "", + "", + "Recover failed for xDS connection. Will retry. Create channel failed."); } } catch (Exception e) { logger.error(REGISTRY_ERROR_REQUEST_XDS, "", "", "Recover failed for xDS connection. Will retry.", e); diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/NodeBuilder.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/NodeBuilder.java index e353bec85e..eaa88f3904 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/NodeBuilder.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/NodeBuilder.java @@ -23,11 +23,11 @@ import io.envoyproxy.envoy.config.core.v3.Node; public class NodeBuilder { - private final static String SVC_CLUSTER_LOCAL = ".svc.cluster.local"; + private static final String SVC_CLUSTER_LOCAL = ".svc.cluster.local"; public static Node build() { -// String podName = System.getenv("metadata.name"); -// String podNamespace = System.getenv("metadata.namespace"); + // String podName = System.getenv("metadata.name"); + // String podNamespace = System.getenv("metadata.namespace"); String podName = IstioEnv.getInstance().getPodName(); String podNamespace = IstioEnv.getInstance().getWorkloadNameSpace(); @@ -36,8 +36,8 @@ public class NodeBuilder { // id -> sidecar~ip~{POD_NAME}~{NAMESPACE_NAME}.svc.cluster.local // cluster -> {SVC_NAME} return Node.newBuilder() - .setId("sidecar~" + NetUtils.getLocalHost() + "~" +podName + "~" + podNamespace + SVC_CLUSTER_LOCAL) - .setCluster(svcName) - .build(); + .setId("sidecar~" + NetUtils.getLocalHost() + "~" + podName + "~" + podNamespace + SVC_CLUSTER_LOCAL) + .setCluster(svcName) + .build(); } } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/PilotExchanger.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/PilotExchanger.java index d85965a7df..87fa81083a 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/PilotExchanger.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/PilotExchanger.java @@ -16,18 +16,6 @@ */ package org.apache.dubbo.registry.xds.util; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Consumer; -import java.util.stream.Collectors; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; import org.apache.dubbo.common.utils.CollectionUtils; @@ -43,6 +31,18 @@ import org.apache.dubbo.registry.xds.util.protocol.message.RouteResult; import org.apache.dubbo.rpc.cluster.router.xds.RdsVirtualHostListener; import org.apache.dubbo.rpc.model.ApplicationModel; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; +import java.util.stream.Collectors; + public class PilotExchanger { protected final XdsChannel xdsChannel; @@ -78,7 +78,8 @@ public class PilotExchanger { this.edsProtocol = new EdsProtocol(adsObserver, NodeBuilder.build(), pollingTimeout); this.listenerResult = ldsProtocol.getListeners(); - this.routeResult = rdsProtocol.getResource(listenerResult.values().iterator().next().getRouteConfigNames()); + this.routeResult = rdsProtocol.getResource( + listenerResult.values().iterator().next().getRouteConfigNames()); Set ldsResourcesName = new HashSet<>(); ldsResourcesName.add(AbstractProtocol.emptyResourceName); // Observer RDS update @@ -87,42 +88,52 @@ public class PilotExchanger { isRdsObserve.set(true); } // Observe LDS updated - ldsProtocol.observeResource(ldsResourcesName, (newListener) -> { - // update local cache - if (!newListener.equals(listenerResult)) { - this.listenerResult = newListener; - // update RDS observation - if (isRdsObserve.get()) { - createRouteObserve(); - } - } - }, false); + ldsProtocol.observeResource( + ldsResourcesName, + (newListener) -> { + // update local cache + if (!newListener.equals(listenerResult)) { + this.listenerResult = newListener; + // update RDS observation + if (isRdsObserve.get()) { + createRouteObserve(); + } + } + }, + false); } private void createRouteObserve() { - rdsProtocol.observeResource(listenerResult.values().iterator().next().getRouteConfigNames(), (newResult) -> { - // check if observed domain update ( will update endpoint observation ) - List domainsToUpdate = new LinkedList<>(); - domainObserveConsumer.forEach((domain, consumer) -> { - newResult.values().forEach(o -> { - Set newRoute = o.searchDomain(domain); - for (Map.Entry entry : routeResult.entrySet()) { - if (!entry.getValue().searchDomain(domain).equals(newRoute)) { - // routers in observed domain has been updated -// Long domainRequest = domainObserveRequest.get(domain); - // router list is empty when observeEndpoints() called and domainRequest has not been created yet - // create new observation - domainsToUpdate.add(domain); -// doObserveEndpoints(domain); - } - } - }); - }); - routeResult = newResult; - ExecutorService executorService = applicationModel.getFrameworkModel().getBeanFactory() - .getBean(FrameworkExecutorRepository.class).getSharedExecutor(); - executorService.submit(() -> domainsToUpdate.forEach(this::doObserveEndpoints)); - }, false); + rdsProtocol.observeResource( + listenerResult.values().iterator().next().getRouteConfigNames(), + (newResult) -> { + // check if observed domain update ( will update endpoint observation ) + List domainsToUpdate = new LinkedList<>(); + domainObserveConsumer.forEach((domain, consumer) -> { + newResult.values().forEach(o -> { + Set newRoute = o.searchDomain(domain); + for (Map.Entry entry : routeResult.entrySet()) { + if (!entry.getValue().searchDomain(domain).equals(newRoute)) { + // routers in observed domain has been updated + // Long domainRequest = domainObserveRequest.get(domain); + // router list is empty when observeEndpoints() called and domainRequest has not + // been created yet + // create new observation + domainsToUpdate.add(domain); + // doObserveEndpoints(domain); + } + } + }); + }); + routeResult = newResult; + ExecutorService executorService = applicationModel + .getFrameworkModel() + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class) + .getSharedExecutor(); + executorService.submit(() -> domainsToUpdate.forEach(this::doObserveEndpoints)); + }, + false); } public static PilotExchanger initialize(URL url) { @@ -144,7 +155,6 @@ public class PilotExchanger { return GLOBAL_PILOT_EXCHANGER != null; } - public void destroy() { xdsChannel.destroy(); } @@ -193,20 +203,20 @@ public class PilotExchanger { // observation will be created when RDS updates if (CollectionUtils.isNotEmpty(router)) { edsProtocol.observeResource( - router, - (endpointResultMap) -> { - Set endpoints = endpointResultMap.values().stream() - .map(EndpointResult::getEndpoints) - .flatMap(Set::stream) - .collect(Collectors.toSet()); - for (Consumer> consumer : domainObserveConsumer.get(domain)) { - consumer.accept(endpoints); - } - }, false); + router, + (endpointResultMap) -> { + Set endpoints = endpointResultMap.values().stream() + .map(EndpointResult::getEndpoints) + .flatMap(Set::stream) + .collect(Collectors.toSet()); + for (Consumer> consumer : domainObserveConsumer.get(domain)) { + consumer.accept(endpoints); + } + }, + false); domainObserveRequest.add(domain); } } - } public void unObserveEndpoints(String domain, Consumer> consumer) { @@ -237,5 +247,4 @@ public class PilotExchanger { public void unObserveLds(Consumer> consumer) { ldsProtocol.unobserveResource(Collections.singleton(AbstractProtocol.emptyResourceName), consumer); } - } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/XdsChannel.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/XdsChannel.java index d4e069a364..a6f7dffde1 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/XdsChannel.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/XdsChannel.java @@ -16,31 +16,32 @@ */ package org.apache.dubbo.registry.xds.util; -import io.grpc.ManagedChannel; -import io.grpc.netty.shaded.io.netty.channel.epoll.EpollDomainSocketChannel; -import io.grpc.netty.shaded.io.netty.channel.epoll.EpollEventLoopGroup; -import io.grpc.netty.shaded.io.netty.channel.unix.DomainSocketAddress; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.url.component.URLAddress; import org.apache.dubbo.registry.xds.XdsCertificateSigner; -import io.envoyproxy.envoy.service.discovery.v3.AggregatedDiscoveryServiceGrpc; -import io.envoyproxy.envoy.service.discovery.v3.DeltaDiscoveryRequest; -import io.envoyproxy.envoy.service.discovery.v3.DeltaDiscoveryResponse; -import io.envoyproxy.envoy.service.discovery.v3.DiscoveryRequest; -import io.envoyproxy.envoy.service.discovery.v3.DiscoveryResponse; -import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; -import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; -import io.grpc.netty.shaded.io.netty.handler.ssl.SslContext; -import io.grpc.netty.shaded.io.netty.handler.ssl.util.InsecureTrustManagerFactory; -import io.grpc.stub.StreamObserver; import org.apache.dubbo.registry.xds.util.bootstrap.Bootstrapper; import org.apache.dubbo.registry.xds.util.bootstrap.BootstrapperImpl; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; +import io.envoyproxy.envoy.service.discovery.v3.AggregatedDiscoveryServiceGrpc; +import io.envoyproxy.envoy.service.discovery.v3.DeltaDiscoveryRequest; +import io.envoyproxy.envoy.service.discovery.v3.DeltaDiscoveryResponse; +import io.envoyproxy.envoy.service.discovery.v3.DiscoveryRequest; +import io.envoyproxy.envoy.service.discovery.v3.DiscoveryResponse; +import io.grpc.ManagedChannel; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.netty.channel.epoll.EpollDomainSocketChannel; +import io.grpc.netty.shaded.io.netty.channel.epoll.EpollEventLoopGroup; +import io.grpc.netty.shaded.io.netty.channel.unix.DomainSocketAddress; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContext; +import io.grpc.netty.shaded.io.netty.handler.ssl.util.InsecureTrustManagerFactory; +import io.grpc.stub.StreamObserver; + import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_CREATE_CHANNEL_XDS; public class XdsChannel { @@ -70,39 +71,52 @@ public class XdsChannel { this.url = url; try { if (!url.getParameter(USE_AGENT, false)) { - if(PLAINTEXT.equals(url.getParameter(SECURE))){ - managedChannel = NettyChannelBuilder.forAddress(url.getHost(), url.getPort()).usePlaintext() - .build(); - }else{ - XdsCertificateSigner signer = url.getOrDefaultApplicationModel().getExtensionLoader(XdsCertificateSigner.class) - .getExtension(url.getParameter("signer", "istio")); + if (PLAINTEXT.equals(url.getParameter(SECURE))) { + managedChannel = NettyChannelBuilder.forAddress(url.getHost(), url.getPort()) + .usePlaintext() + .build(); + } else { + XdsCertificateSigner signer = url.getOrDefaultApplicationModel() + .getExtensionLoader(XdsCertificateSigner.class) + .getExtension(url.getParameter("signer", "istio")); XdsCertificateSigner.CertPair certPair = signer.GenerateCert(url); SslContext context = GrpcSslContexts.forClient() - .trustManager(InsecureTrustManagerFactory.INSTANCE) - .keyManager(new ByteArrayInputStream(certPair.getPublicKey().getBytes(StandardCharsets.UTF_8)), - new ByteArrayInputStream(certPair.getPrivateKey().getBytes(StandardCharsets.UTF_8))) - .build(); - managedChannel = NettyChannelBuilder.forAddress(url.getHost(), url.getPort()).sslContext(context) - .build(); + .trustManager(InsecureTrustManagerFactory.INSTANCE) + .keyManager( + new ByteArrayInputStream( + certPair.getPublicKey().getBytes(StandardCharsets.UTF_8)), + new ByteArrayInputStream( + certPair.getPrivateKey().getBytes(StandardCharsets.UTF_8))) + .build(); + managedChannel = NettyChannelBuilder.forAddress(url.getHost(), url.getPort()) + .sslContext(context) + .build(); } } else { BootstrapperImpl bootstrapper = new BootstrapperImpl(); Bootstrapper.BootstrapInfo bootstrapInfo = bootstrapper.bootstrap(); - URLAddress address = URLAddress.parse(bootstrapInfo.servers().get(0).target(), null, false); + URLAddress address = + URLAddress.parse(bootstrapInfo.servers().get(0).target(), null, false); EpollEventLoopGroup elg = new EpollEventLoopGroup(); managedChannel = NettyChannelBuilder.forAddress(new DomainSocketAddress("/" + address.getPath())) - .eventLoopGroup(elg) - .channelType(EpollDomainSocketChannel.class) - .usePlaintext() - .build(); + .eventLoopGroup(elg) + .channelType(EpollDomainSocketChannel.class) + .usePlaintext() + .build(); } } catch (Exception e) { - logger.error(REGISTRY_ERROR_CREATE_CHANNEL_XDS, "", "", "Error occurred when creating gRPC channel to control panel.", e); + logger.error( + REGISTRY_ERROR_CREATE_CHANNEL_XDS, + "", + "", + "Error occurred when creating gRPC channel to control panel.", + e); } channel = managedChannel; } - public StreamObserver observeDeltaDiscoveryRequest(StreamObserver observer) { + public StreamObserver observeDeltaDiscoveryRequest( + StreamObserver observer) { return AggregatedDiscoveryServiceGrpc.newStub(channel).deltaAggregatedResources(observer); } @@ -110,12 +124,16 @@ public class XdsChannel { return AggregatedDiscoveryServiceGrpc.newStub(channel).streamAggregatedResources(observer); } - public StreamObserver observeDeltaDiscoveryRequestV2(StreamObserver observer) { - return io.envoyproxy.envoy.service.discovery.v2.AggregatedDiscoveryServiceGrpc.newStub(channel).deltaAggregatedResources(observer); + public StreamObserver observeDeltaDiscoveryRequestV2( + StreamObserver observer) { + return io.envoyproxy.envoy.service.discovery.v2.AggregatedDiscoveryServiceGrpc.newStub(channel) + .deltaAggregatedResources(observer); } - public StreamObserver createDeltaDiscoveryRequestV2(StreamObserver observer) { - return io.envoyproxy.envoy.service.discovery.v2.AggregatedDiscoveryServiceGrpc.newStub(channel).streamAggregatedResources(observer); + public StreamObserver createDeltaDiscoveryRequestV2( + StreamObserver observer) { + return io.envoyproxy.envoy.service.discovery.v2.AggregatedDiscoveryServiceGrpc.newStub(channel) + .streamAggregatedResources(observer); } public void destroy() { diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/BootstrapInfoImpl.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/BootstrapInfoImpl.java index a4e4451891..3570b20e32 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/BootstrapInfoImpl.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/BootstrapInfoImpl.java @@ -16,13 +16,14 @@ */ package org.apache.dubbo.registry.xds.util.bootstrap; -import io.envoyproxy.envoy.config.core.v3.Node; - import javax.annotation.Nullable; + import java.util.LinkedList; import java.util.List; import java.util.Map; +import io.envoyproxy.envoy.config.core.v3.Node; + public final class BootstrapInfoImpl extends Bootstrapper.BootstrapInfo { private final List servers; @@ -33,7 +34,11 @@ public final class BootstrapInfoImpl extends Bootstrapper.BootstrapInfo { private final Node node; - BootstrapInfoImpl(List servers, String serverListenerResourceNameTemplate, Map certProviders, Node node) { + BootstrapInfoImpl( + List servers, + String serverListenerResourceNameTemplate, + Map certProviders, + Node node) { this.servers = servers; this.serverListenerResourceNameTemplate = serverListenerResourceNameTemplate; this.certProviders = certProviders; @@ -62,10 +67,10 @@ public final class BootstrapInfoImpl extends Bootstrapper.BootstrapInfo { @Override public String toString() { return "BootstrapInfo{" - + "servers=" + servers + ", " - + "serverListenerResourceNameTemplate=" + serverListenerResourceNameTemplate + ", " - + "node=" + node + ", " - + "}"; + + "servers=" + servers + ", " + + "serverListenerResourceNameTemplate=" + serverListenerResourceNameTemplate + ", " + + "node=" + node + ", " + + "}"; } public static final class Builder extends Bootstrapper.BootstrapInfo.Builder { @@ -75,8 +80,9 @@ public final class BootstrapInfoImpl extends Bootstrapper.BootstrapInfo { private Map certProviders; private String serverListenerResourceNameTemplate; - Builder() { - } + + Builder() {} + @Override Bootstrapper.BootstrapInfo.Builder servers(List servers) { this.servers = new LinkedList<>(servers); @@ -93,21 +99,22 @@ public final class BootstrapInfoImpl extends Bootstrapper.BootstrapInfo { } @Override - Bootstrapper.BootstrapInfo.Builder certProviders(@Nullable Map certProviders) { + Bootstrapper.BootstrapInfo.Builder certProviders( + @Nullable Map certProviders) { this.certProviders = certProviders; return this; } @Override - Bootstrapper.BootstrapInfo.Builder serverListenerResourceNameTemplate(@Nullable String serverListenerResourceNameTemplate) { + Bootstrapper.BootstrapInfo.Builder serverListenerResourceNameTemplate( + @Nullable String serverListenerResourceNameTemplate) { this.serverListenerResourceNameTemplate = serverListenerResourceNameTemplate; return this; } @Override Bootstrapper.BootstrapInfo build() { - if (this.servers == null - || this.node == null) { + if (this.servers == null || this.node == null) { StringBuilder missing = new StringBuilder(); if (this.servers == null) { missing.append(" servers"); @@ -118,12 +125,7 @@ public final class BootstrapInfoImpl extends Bootstrapper.BootstrapInfo { throw new IllegalStateException("Missing required properties:" + missing); } return new BootstrapInfoImpl( - this.servers, - this.serverListenerResourceNameTemplate, - this.certProviders, - this.node); + this.servers, this.serverListenerResourceNameTemplate, this.certProviders, this.node); } } - } - diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/Bootstrapper.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/Bootstrapper.java index 5e018c45a6..69a7ee89a5 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/Bootstrapper.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/Bootstrapper.java @@ -16,14 +16,16 @@ */ package org.apache.dubbo.registry.xds.util.bootstrap; -import io.envoyproxy.envoy.config.core.v3.Node; -import io.grpc.ChannelCredentials; import org.apache.dubbo.registry.xds.XdsInitializationException; import javax.annotation.Nullable; + import java.util.List; import java.util.Map; +import io.envoyproxy.envoy.config.core.v3.Node; +import io.grpc.ChannelCredentials; + public abstract class Bootstrapper { public abstract BootstrapInfo bootstrap() throws XdsInitializationException; @@ -40,7 +42,6 @@ public abstract class Bootstrapper { abstract boolean useProtocolV3(); abstract boolean ignoreResourceDeletion(); - } public abstract static class CertificateProviderInfo { @@ -66,8 +67,7 @@ public abstract class Bootstrapper { abstract Builder certProviders(@Nullable Map certProviders); - abstract Builder serverListenerResourceNameTemplate( - @Nullable String serverListenerResourceNameTemplate); + abstract Builder serverListenerResourceNameTemplate(@Nullable String serverListenerResourceNameTemplate); abstract BootstrapInfo build(); } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/BootstrapperImpl.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/BootstrapperImpl.java index d9e299763f..66c7a62397 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/BootstrapperImpl.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/BootstrapperImpl.java @@ -16,15 +16,12 @@ */ package org.apache.dubbo.registry.xds.util.bootstrap; -import io.envoyproxy.envoy.config.core.v3.Node; -import io.grpc.ChannelCredentials; -import io.grpc.internal.JsonParser; -import io.grpc.internal.JsonUtil; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.registry.xds.XdsInitializationException; import javax.annotation.Nullable; + import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -34,6 +31,11 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; +import io.envoyproxy.envoy.config.core.v3.Node; +import io.grpc.ChannelCredentials; +import io.grpc.internal.JsonParser; +import io.grpc.internal.JsonUtil; + public class BootstrapperImpl extends Bootstrapper { static final String BOOTSTRAP_PATH_SYS_ENV_VAR = "GRPC_XDS_BOOTSTRAP"; @@ -98,11 +100,10 @@ public class BootstrapperImpl extends Bootstrapper { Map certProviders = new HashMap<>(certProvidersBlob.size()); for (String name : certProvidersBlob.keySet()) { Map valueMap = JsonUtil.getObject(certProvidersBlob, name); - String pluginName = - checkForNull(JsonUtil.getString(valueMap, "plugin_name"), "plugin_name"); + String pluginName = checkForNull(JsonUtil.getString(valueMap, "plugin_name"), "plugin_name"); Map config = checkForNull(JsonUtil.getObject(valueMap, "config"), "config"); CertificateProviderInfoImpl certificateProviderInfo = - new CertificateProviderInfoImpl(pluginName, config); + new CertificateProviderInfoImpl(pluginName, config); certProviders.put(name, certificateProviderInfo); } builder.certProviders(certProviders); @@ -111,8 +112,7 @@ public class BootstrapperImpl extends Bootstrapper { return builder.build(); } - private static List parseServerInfos(List rawServerConfigs) - throws XdsInitializationException { + private static List parseServerInfos(List rawServerConfigs) throws XdsInitializationException { List servers = new LinkedList<>(); List> serverConfigList = JsonUtil.checkObjectList(rawServerConfigs); for (Map serverConfig : serverConfigList) { @@ -123,14 +123,14 @@ public class BootstrapperImpl extends Bootstrapper { List rawChannelCredsList = JsonUtil.getList(serverConfig, "channel_creds"); if (rawChannelCredsList == null || rawChannelCredsList.isEmpty()) { throw new XdsInitializationException( - "Invalid bootstrap: server " + serverUri + " 'channel_creds' required"); + "Invalid bootstrap: server " + serverUri + " 'channel_creds' required"); } ChannelCredentials channelCredentials = - parseChannelCredentials(JsonUtil.checkObjectList(rawChannelCredsList), serverUri); -// if (channelCredentials == null) { -// throw new XdsInitializationException( -// "Server " + serverUri + ": no supported channel credentials found"); -// } + parseChannelCredentials(JsonUtil.checkObjectList(rawChannelCredsList), serverUri); + // if (channelCredentials == null) { + // throw new XdsInitializationException( + // "Server " + serverUri + ": no supported channel credentials found"); + // } boolean useProtocolV3 = false; boolean ignoreResourceDeletion = false; @@ -139,8 +139,7 @@ public class BootstrapperImpl extends Bootstrapper { useProtocolV3 = serverFeatures.contains(SERVER_FEATURE_XDS_V3); ignoreResourceDeletion = serverFeatures.contains(SERVER_FEATURE_IGNORE_RESOURCE_DELETION); } - servers.add( - new ServerInfoImpl(serverUri, channelCredentials, useProtocolV3, ignoreResourceDeletion)); + servers.add(new ServerInfoImpl(serverUri, channelCredentials, useProtocolV3, ignoreResourceDeletion)); } return servers; } @@ -167,14 +166,14 @@ public class BootstrapperImpl extends Bootstrapper { private static T checkForNull(T value, String fieldName) throws XdsInitializationException { if (value == null) { - throw new XdsInitializationException( - "Invalid bootstrap: '" + fieldName + "' does not exist."); + throw new XdsInitializationException("Invalid bootstrap: '" + fieldName + "' does not exist."); } return value; } @Nullable - private static ChannelCredentials parseChannelCredentials(List> jsonList, String serverUri) throws XdsInitializationException { + private static ChannelCredentials parseChannelCredentials(List> jsonList, String serverUri) + throws XdsInitializationException { return null; } } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/CertificateProviderInfoImpl.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/CertificateProviderInfoImpl.java index 2c3da740a2..980b6e1fd3 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/CertificateProviderInfoImpl.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/CertificateProviderInfoImpl.java @@ -40,10 +40,6 @@ final class CertificateProviderInfoImpl extends Bootstrapper.CertificateProvider @Override public String toString() { - return "CertificateProviderInfo{" - + "pluginName=" + pluginName + ", " - + "config=" + config - + "}"; + return "CertificateProviderInfo{" + "pluginName=" + pluginName + ", " + "config=" + config + "}"; } - } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/ServerInfoImpl.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/ServerInfoImpl.java index 001008a455..c15f4f28b7 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/ServerInfoImpl.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/bootstrap/ServerInfoImpl.java @@ -28,7 +28,11 @@ final class ServerInfoImpl extends Bootstrapper.ServerInfo { private final boolean ignoreResourceDeletion; - ServerInfoImpl(String target, ChannelCredentials channelCredentials, boolean useProtocolV3, boolean ignoreResourceDeletion) { + ServerInfoImpl( + String target, + ChannelCredentials channelCredentials, + boolean useProtocolV3, + boolean ignoreResourceDeletion) { this.target = target; this.channelCredentials = channelCredentials; this.useProtocolV3 = useProtocolV3; @@ -58,11 +62,10 @@ final class ServerInfoImpl extends Bootstrapper.ServerInfo { @Override public String toString() { return "ServerInfo{" - + "target=" + target + ", " - + "channelCredentials=" + channelCredentials + ", " - + "useProtocolV3=" + useProtocolV3 + ", " - + "ignoreResourceDeletion=" + ignoreResourceDeletion - + "}"; + + "target=" + target + ", " + + "channelCredentials=" + channelCredentials + ", " + + "useProtocolV3=" + useProtocolV3 + ", " + + "ignoreResourceDeletion=" + ignoreResourceDeletion + + "}"; } - } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/AbstractProtocol.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/AbstractProtocol.java index 1054526594..a2e135f00d 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/AbstractProtocol.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/AbstractProtocol.java @@ -16,6 +16,12 @@ */ package org.apache.dubbo.registry.xds.util.protocol; +import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; +import org.apache.dubbo.common.utils.StringUtils; +import org.apache.dubbo.registry.xds.util.AdsObserver; +import org.apache.dubbo.registry.xds.util.XdsListener; import java.util.ArrayList; import java.util.Collections; @@ -31,19 +37,12 @@ import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Consumer; import java.util.stream.Collectors; -import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.registry.xds.util.AdsObserver; -import org.apache.dubbo.registry.xds.util.XdsListener; - import io.envoyproxy.envoy.config.core.v3.Node; import io.envoyproxy.envoy.service.discovery.v3.DiscoveryRequest; import io.envoyproxy.envoy.service.discovery.v3.DiscoveryResponse; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_INTERRUPTED; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REQUEST; -import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; public abstract class AbstractProtocol> implements XdsProtocol, XdsListener { @@ -107,7 +106,6 @@ public abstract class AbstractProtocol> implements return resourcesMap.get(resourceName); } - @Override public Map getResource(Set resourceNames) { resourceNames = resourceNames == null ? Collections.emptySet() : resourceNames; @@ -120,8 +118,9 @@ public abstract class AbstractProtocol> implements } private Map getResourceFromCache(Set resourceNames) { - return resourceNames.stream().filter(o -> !StringUtils.isEmpty(o)) - .collect(Collectors.toMap(k -> k, this::getCacheResource)); + return resourceNames.stream() + .filter(o -> !StringUtils.isEmpty(o)) + .collect(Collectors.toMap(k -> k, this::getCacheResource)); } public Map getResourceFromRemote(Set resourceNames) { @@ -139,8 +138,11 @@ public abstract class AbstractProtocol> implements Consumer> futureConsumer = future::complete; try { writeLock.lock(); - ConcurrentHashMapUtils.computeIfAbsent((ConcurrentHashMap, List>>>)consumerObserveMap,consumerObserveResourceNames, key -> new ArrayList<>()) - .add(futureConsumer); + ConcurrentHashMapUtils.computeIfAbsent( + (ConcurrentHashMap, List>>>) consumerObserveMap, + consumerObserveResourceNames, + key -> new ArrayList<>()) + .add(futureConsumer); } finally { writeLock.unlock(); } @@ -148,7 +150,8 @@ public abstract class AbstractProtocol> implements Set resourceNamesToObserve = new HashSet<>(resourceNames); resourceNamesToObserve.addAll(resourcesMap.keySet()); adsObserver.request(buildDiscoveryRequest(resourceNamesToObserve)); - logger.info("Send xDS Observe request to remote. Resource count: " + resourceNamesToObserve.size() + ". Resource Type: " + getTypeUrl()); + logger.info("Send xDS Observe request to remote. Resource count: " + resourceNamesToObserve.size() + + ". Resource Type: " + getTypeUrl()); try { Map result = future.get(); @@ -162,7 +165,12 @@ public abstract class AbstractProtocol> implements return result; } catch (InterruptedException e) { - logger.error(INTERNAL_INTERRUPTED, "", "", "InterruptedException occur when request control panel. error=", e); + logger.error( + INTERNAL_INTERRUPTED, + "", + "", + "InterruptedException occur when request control panel. error=", + e); Thread.currentThread().interrupt(); } catch (Exception e) { logger.error(PROTOCOL_FAILED_REQUEST, "", "", "Error occur when request control panel. error=", e); @@ -193,8 +201,8 @@ public abstract class AbstractProtocol> implements } try { writeLock.lock(); - this.observeResourcesName = consumerObserveMap.keySet() - .stream().flatMap(Set::stream).collect(Collectors.toSet()); + this.observeResourcesName = + consumerObserveMap.keySet().stream().flatMap(Set::stream).collect(Collectors.toSet()); } finally { writeLock.unlock(); } @@ -206,10 +214,10 @@ public abstract class AbstractProtocol> implements protected DiscoveryRequest buildDiscoveryRequest(Set resourceNames) { return DiscoveryRequest.newBuilder() - .setNode(node) - .setTypeUrl(getTypeUrl()) - .addAllResourceNames(resourceNames) - .build(); + .setNode(node) + .setTypeUrl(getTypeUrl()) + .addAllResourceNames(resourceNames) + .build(); } protected abstract Map decodeDiscoveryResponse(DiscoveryResponse response); @@ -238,7 +246,8 @@ public abstract class AbstractProtocol> implements return; } - logger.info("Receive resource update notification from xds server. Change resource count: " + changedResourceNames.stream() + ". Type: " + getTypeUrl()); + logger.info("Receive resource update notification from xds server. Change resource count: " + + changedResourceNames.stream() + ". Type: " + getTypeUrl()); // call once for full data try { @@ -249,9 +258,8 @@ public abstract class AbstractProtocol> implements continue; } - Map dsResultMap = entry.getKey() - .stream() - .collect(Collectors.toMap(k -> k, v -> newResult.get(v))); + Map dsResultMap = + entry.getKey().stream().collect(Collectors.toMap(k -> k, v -> newResult.get(v))); entry.getValue().forEach(o -> o.accept(dsResultMap)); } } finally { diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/delta/DeltaEndpoint.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/delta/DeltaEndpoint.java index 9e192cf1c9..46988f38e5 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/delta/DeltaEndpoint.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/delta/DeltaEndpoint.java @@ -42,10 +42,7 @@ public class DeltaEndpoint implements DeltaResource { @Override public EndpointResult getResource() { - Set set = data.values().stream() - .flatMap(Set::stream) - .collect(Collectors.toSet()); + Set set = data.values().stream().flatMap(Set::stream).collect(Collectors.toSet()); return new EndpointResult(set); } - } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/delta/DeltaListener.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/delta/DeltaListener.java index 73b2c9a005..bca3024ed9 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/delta/DeltaListener.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/delta/DeltaListener.java @@ -41,9 +41,7 @@ public class DeltaListener implements DeltaResource { @Override public ListenerResult getResource() { - Set set = data.values().stream() - .flatMap(Set::stream) - .collect(Collectors.toSet()); + Set set = data.values().stream().flatMap(Set::stream).collect(Collectors.toSet()); return new ListenerResult(set); } } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/EdsProtocol.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/EdsProtocol.java index 820860435b..91759cab9b 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/EdsProtocol.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/EdsProtocol.java @@ -16,12 +16,6 @@ */ package org.apache.dubbo.registry.xds.util.protocol.impl; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.registry.xds.util.AdsObserver; @@ -30,9 +24,14 @@ import org.apache.dubbo.registry.xds.util.protocol.delta.DeltaEndpoint; import org.apache.dubbo.registry.xds.util.protocol.message.Endpoint; import org.apache.dubbo.registry.xds.util.protocol.message.EndpointResult; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + import com.google.protobuf.Any; import com.google.protobuf.InvalidProtocolBufferException; - import io.envoyproxy.envoy.config.core.v3.HealthStatus; import io.envoyproxy.envoy.config.core.v3.Node; import io.envoyproxy.envoy.config.core.v3.SocketAddress; @@ -55,23 +54,23 @@ public class EdsProtocol extends AbstractProtocol return "type.googleapis.com/envoy.config.endpoint.v3.ClusterLoadAssignment"; } - @Override protected Map decodeDiscoveryResponse(DiscoveryResponse response) { if (getTypeUrl().equals(response.getTypeUrl())) { return response.getResourcesList().stream() - .map(EdsProtocol::unpackClusterLoadAssignment) - .filter(Objects::nonNull) - .collect(Collectors.toConcurrentMap(ClusterLoadAssignment::getClusterName, this::decodeResourceToEndpoint)); + .map(EdsProtocol::unpackClusterLoadAssignment) + .filter(Objects::nonNull) + .collect(Collectors.toConcurrentMap( + ClusterLoadAssignment::getClusterName, this::decodeResourceToEndpoint)); } return new HashMap<>(); } private EndpointResult decodeResourceToEndpoint(ClusterLoadAssignment resource) { Set endpoints = resource.getEndpointsList().stream() - .flatMap(e -> e.getLbEndpointsList().stream()) - .map(e -> decodeLbEndpointToEndpoint(resource.getClusterName(), e)) - .collect(Collectors.toSet()); + .flatMap(e -> e.getLbEndpointsList().stream()) + .map(e -> decodeLbEndpointToEndpoint(resource.getClusterName(), e)) + .collect(Collectors.toSet()); return new EndpointResult(endpoints); } @@ -80,8 +79,8 @@ public class EdsProtocol extends AbstractProtocol SocketAddress address = lbEndpoint.getEndpoint().getAddress().getSocketAddress(); endpoint.setAddress(address.getAddress()); endpoint.setPortValue(address.getPortValue()); - boolean healthy = HealthStatus.HEALTHY.equals(lbEndpoint.getHealthStatus()) || - HealthStatus.UNKNOWN.equals(lbEndpoint.getHealthStatus()); + boolean healthy = HealthStatus.HEALTHY.equals(lbEndpoint.getHealthStatus()) + || HealthStatus.UNKNOWN.equals(lbEndpoint.getHealthStatus()); endpoint.setHealthy(healthy); endpoint.setWeight(lbEndpoint.getLoadBalancingWeight().getValue()); return endpoint; diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/LdsProtocol.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/LdsProtocol.java index 0de9a485e3..00abe22f37 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/LdsProtocol.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/LdsProtocol.java @@ -16,13 +16,6 @@ */ package org.apache.dubbo.registry.xds.util.protocol.impl; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.Collectors; - import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.registry.xds.util.AdsObserver; @@ -30,9 +23,15 @@ import org.apache.dubbo.registry.xds.util.protocol.AbstractProtocol; import org.apache.dubbo.registry.xds.util.protocol.delta.DeltaListener; import org.apache.dubbo.registry.xds.util.protocol.message.ListenerResult; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; + import com.google.protobuf.Any; import com.google.protobuf.InvalidProtocolBufferException; - import io.envoyproxy.envoy.config.core.v3.Node; import io.envoyproxy.envoy.config.listener.v3.Filter; import io.envoyproxy.envoy.config.listener.v3.Listener; @@ -62,10 +61,10 @@ public class LdsProtocol extends AbstractProtocol protected Map decodeDiscoveryResponse(DiscoveryResponse response) { if (getTypeUrl().equals(response.getTypeUrl())) { Set set = response.getResourcesList().stream() - .map(LdsProtocol::unpackListener) - .filter(Objects::nonNull) - .flatMap(e -> decodeResourceToListener(e).stream()) - .collect(Collectors.toSet()); + .map(LdsProtocol::unpackListener) + .filter(Objects::nonNull) + .flatMap(e -> decodeResourceToListener(e).stream()) + .collect(Collectors.toSet()); Map listenerDecodeResult = new ConcurrentHashMap<>(); listenerDecodeResult.put(emptyResourceName, new ListenerResult(set)); return listenerDecodeResult; @@ -75,13 +74,13 @@ public class LdsProtocol extends AbstractProtocol private Set decodeResourceToListener(Listener resource) { return resource.getFilterChainsList().stream() - .flatMap(e -> e.getFiltersList().stream()) - .map(Filter::getTypedConfig) - .map(LdsProtocol::unpackHttpConnectionManager) - .filter(Objects::nonNull) - .map(HttpConnectionManager::getRds) - .map(Rds::getRouteConfigName) - .collect(Collectors.toSet()); + .flatMap(e -> e.getFiltersList().stream()) + .map(Filter::getTypedConfig) + .map(LdsProtocol::unpackHttpConnectionManager) + .filter(Objects::nonNull) + .map(HttpConnectionManager::getRds) + .map(Rds::getRouteConfigName) + .collect(Collectors.toSet()); } private static Listener unpackListener(Any any) { diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/RdsProtocol.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/RdsProtocol.java index 68970f6f1f..44bee78c1e 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/RdsProtocol.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/impl/RdsProtocol.java @@ -16,13 +16,6 @@ */ package org.apache.dubbo.registry.xds.util.protocol.impl; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.Collectors; - import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.registry.xds.util.AdsObserver; @@ -30,9 +23,15 @@ import org.apache.dubbo.registry.xds.util.protocol.AbstractProtocol; import org.apache.dubbo.registry.xds.util.protocol.delta.DeltaRoute; import org.apache.dubbo.registry.xds.util.protocol.message.RouteResult; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; + import com.google.protobuf.Any; import com.google.protobuf.InvalidProtocolBufferException; - import io.envoyproxy.envoy.config.core.v3.Node; import io.envoyproxy.envoy.config.route.v3.Route; import io.envoyproxy.envoy.config.route.v3.RouteAction; @@ -59,9 +58,9 @@ public class RdsProtocol extends AbstractProtocol { protected Map decodeDiscoveryResponse(DiscoveryResponse response) { if (getTypeUrl().equals(response.getTypeUrl())) { return response.getResourcesList().stream() - .map(RdsProtocol::unpackRouteConfiguration) - .filter(Objects::nonNull) - .collect(Collectors.toConcurrentMap(RouteConfiguration::getName, this::decodeResourceToListener)); + .map(RdsProtocol::unpackRouteConfiguration) + .filter(Objects::nonNull) + .collect(Collectors.toConcurrentMap(RouteConfiguration::getName, this::decodeResourceToListener)); } return new HashMap<>(); } @@ -69,18 +68,17 @@ public class RdsProtocol extends AbstractProtocol { private RouteResult decodeResourceToListener(RouteConfiguration resource) { Map> map = new HashMap<>(); Map rdsVirtualhostMap = new ConcurrentHashMap<>(); - resource.getVirtualHostsList() - .forEach(virtualHost -> { - Set cluster = virtualHost.getRoutesList().stream() + resource.getVirtualHostsList().forEach(virtualHost -> { + Set cluster = virtualHost.getRoutesList().stream() .map(Route::getRoute) .map(RouteAction::getCluster) .collect(Collectors.toSet()); - for (String domain : virtualHost.getDomainsList()) { - map.put(domain, cluster); - rdsVirtualhostMap.put(domain,virtualHost); - } - }); - return new RouteResult(map,rdsVirtualhostMap); + for (String domain : virtualHost.getDomainsList()) { + map.put(domain, cluster); + rdsVirtualhostMap.put(domain, virtualHost); + } + }); + return new RouteResult(map, rdsVirtualhostMap); } private static RouteConfiguration unpackRouteConfiguration(Any any) { @@ -91,6 +89,4 @@ public class RdsProtocol extends AbstractProtocol { return null; } } - - } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/message/Endpoint.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/message/Endpoint.java index 58f13bdee8..ceed163278 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/message/Endpoint.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/message/Endpoint.java @@ -67,12 +67,11 @@ public class Endpoint { @Override public String toString() { - return "Endpoint{" + - "address='" + address + '\'' + - ", portValue='" + portValue + '\'' + - ", healthy=" + healthy + - ", weight=" + weight + - '}'; + return "Endpoint{" + "address='" + + address + '\'' + ", portValue='" + + portValue + '\'' + ", healthy=" + + healthy + ", weight=" + + weight + '}'; } @Override @@ -84,10 +83,10 @@ public class Endpoint { return false; } Endpoint endpoint = (Endpoint) o; - return healthy == endpoint.healthy && - weight == endpoint.weight && - Objects.equals(address, endpoint.address) && - Objects.equals(portValue, endpoint.portValue); + return healthy == endpoint.healthy + && weight == endpoint.weight + && Objects.equals(address, endpoint.address) + && Objects.equals(portValue, endpoint.portValue); } @Override diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/message/EndpointResult.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/message/EndpointResult.java index 4f890786b1..ead2c4de27 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/message/EndpointResult.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/message/EndpointResult.java @@ -55,8 +55,6 @@ public class EndpointResult { @Override public String toString() { - return "EndpointResult{" + - "endpoints=" + endpoints + - '}'; + return "EndpointResult{" + "endpoints=" + endpoints + '}'; } } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/message/ListenerResult.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/message/ListenerResult.java index 61d717e87d..7c16703166 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/message/ListenerResult.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/message/ListenerResult.java @@ -63,8 +63,6 @@ public class ListenerResult { @Override public String toString() { - return "ListenerResult{" + - "routeConfigNames=" + routeConfigNames + - '}'; + return "ListenerResult{" + "routeConfigNames=" + routeConfigNames + '}'; } } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/message/RouteResult.java b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/message/RouteResult.java index a71e43cb6d..cf0ed1d846 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/message/RouteResult.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/registry/xds/util/protocol/message/RouteResult.java @@ -16,22 +16,20 @@ */ package org.apache.dubbo.registry.xds.util.protocol.message; +import org.apache.dubbo.common.utils.ConcurrentHashSet; + import java.util.Collections; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; -import org.apache.dubbo.common.utils.ConcurrentHashSet; - import io.envoyproxy.envoy.config.route.v3.VirtualHost; - public class RouteResult { private final Map> domainMap; private Map virtualHostMap; - public RouteResult() { this.domainMap = new ConcurrentHashMap<>(); this.virtualHostMap = new ConcurrentHashMap<>(); @@ -85,16 +83,12 @@ public class RouteResult { return virtualHostMap.get(domain); } - public void removeVirtualHost(String domain) { virtualHostMap.remove(domain); } @Override public String toString() { - return "RouteResult{" + - "domainMap=" + domainMap + - ", virtualHostMap=" + virtualHostMap + - '}'; + return "RouteResult{" + "domainMap=" + domainMap + ", virtualHostMap=" + virtualHostMap + '}'; } } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/EdsEndpointListener.java b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/EdsEndpointListener.java index 0416236166..58aaa86234 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/EdsEndpointListener.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/EdsEndpointListener.java @@ -20,9 +20,7 @@ import org.apache.dubbo.registry.xds.util.protocol.message.Endpoint; import java.util.Set; - public interface EdsEndpointListener { void onEndPointChange(String cluster, Set endpoints); - } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/EdsEndpointManager.java b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/EdsEndpointManager.java index 6291551889..a54d74c7bf 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/EdsEndpointManager.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/EdsEndpointManager.java @@ -16,13 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.router.xds; -import java.util.Collections; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Consumer; -import java.util.stream.Collectors; - import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; @@ -32,23 +25,29 @@ import org.apache.dubbo.registry.xds.util.protocol.message.Endpoint; import org.apache.dubbo.registry.xds.util.protocol.message.EndpointResult; import org.apache.dubbo.rpc.model.FrameworkModel; +import java.util.Collections; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Consumer; +import java.util.stream.Collectors; + public class EdsEndpointManager { - private static final ConcurrentHashMap> ENDPOINT_LISTENERS = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap> ENDPOINT_LISTENERS = + new ConcurrentHashMap<>(); private static final ConcurrentHashMap> ENDPOINT_DATA_CACHE = new ConcurrentHashMap<>(); - private static final ConcurrentHashMap>> EDS_LISTENERS = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap>> EDS_LISTENERS = + new ConcurrentHashMap<>(); - - public EdsEndpointManager() { - } + public EdsEndpointManager() {} public synchronized void subscribeEds(String cluster, EdsEndpointListener listener) { - Set listeners = ConcurrentHashMapUtils.computeIfAbsent(ENDPOINT_LISTENERS, cluster, key -> - new ConcurrentHashSet<>() - ); + Set listeners = + ConcurrentHashMapUtils.computeIfAbsent(ENDPOINT_LISTENERS, cluster, key -> new ConcurrentHashSet<>()); if (CollectionUtils.isEmpty(listeners)) { doSubscribeEds(cluster); } @@ -61,17 +60,19 @@ public class EdsEndpointManager { private void doSubscribeEds(String cluster) { ConcurrentHashMapUtils.computeIfAbsent(EDS_LISTENERS, cluster, key -> endpoints -> { - Set result = endpoints.values() - .stream() - .map(EndpointResult::getEndpoints) - .flatMap(Set::stream) - .collect(Collectors.toSet()); + Set result = endpoints.values().stream() + .map(EndpointResult::getEndpoints) + .flatMap(Set::stream) + .collect(Collectors.toSet()); notifyEndpointChange(cluster, result); }); Consumer> consumer = EDS_LISTENERS.get(cluster); if (PilotExchanger.isEnabled()) { - FrameworkModel.defaultModel().getBeanFactory().getBean(FrameworkExecutorRepository.class) - .getSharedExecutor().submit(() -> PilotExchanger.getInstance().observeEds(Collections.singleton(cluster), consumer)); + FrameworkModel.defaultModel() + .getBeanFactory() + .getBean(FrameworkExecutorRepository.class) + .getSharedExecutor() + .submit(() -> PilotExchanger.getInstance().observeEds(Collections.singleton(cluster), consumer)); } } @@ -96,7 +97,6 @@ public class EdsEndpointManager { ENDPOINT_DATA_CACHE.remove(cluster); } - public void notifyEndpointChange(String cluster, Set endpoints) { ENDPOINT_DATA_CACHE.put(cluster, endpoints); @@ -124,5 +124,4 @@ public class EdsEndpointManager { static ConcurrentHashMap>> getEdsListeners() { return EDS_LISTENERS; } - } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/RdsRouteRuleManager.java b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/RdsRouteRuleManager.java index a76508a138..b0371729eb 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/RdsRouteRuleManager.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/RdsRouteRuleManager.java @@ -16,13 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.router.xds; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.function.Consumer; - import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.ConcurrentHashSet; @@ -31,12 +24,19 @@ import org.apache.dubbo.registry.xds.util.protocol.message.ListenerResult; import org.apache.dubbo.registry.xds.util.protocol.message.RouteResult; import org.apache.dubbo.rpc.cluster.router.xds.rule.XdsRouteRule; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.function.Consumer; + import io.envoyproxy.envoy.config.route.v3.VirtualHost; public class RdsRouteRuleManager { - - private static final ConcurrentHashMap> RULE_LISTENERS = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap> RULE_LISTENERS = + new ConcurrentHashMap<>(); private static final ConcurrentHashMap> ROUTE_DATA_CACHE = new ConcurrentHashMap<>(); @@ -48,14 +48,12 @@ public class RdsRouteRuleManager { private static Map RDS_RESULT; - public RdsRouteRuleManager() { - } + public RdsRouteRuleManager() {} public synchronized void subscribeRds(String domain, XdsRouteRuleListener listener) { - Set listeners = ConcurrentHashMapUtils.computeIfAbsent(RULE_LISTENERS, domain, key -> - new ConcurrentHashSet<>() - ); + Set listeners = + ConcurrentHashMapUtils.computeIfAbsent(RULE_LISTENERS, domain, key -> new ConcurrentHashSet<>()); if (CollectionUtils.isEmpty(listeners)) { doSubscribeRds(domain); } @@ -129,7 +127,6 @@ public class RdsRouteRuleManager { RDS_LISTENERS.remove(domain); } - public void notifyRuleChange(String domain, List xdsRouteRules) { ROUTE_DATA_CACHE.put(domain, xdsRouteRules); @@ -162,5 +159,4 @@ public class RdsRouteRuleManager { static Map getRdsListeners() { return RDS_LISTENERS; } - } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/RdsVirtualHostListener.java b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/RdsVirtualHostListener.java index 85443cca86..58771788ee 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/RdsVirtualHostListener.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/RdsVirtualHostListener.java @@ -28,26 +28,26 @@ import org.apache.dubbo.rpc.cluster.router.xds.rule.LongRangeMatch; import org.apache.dubbo.rpc.cluster.router.xds.rule.PathMatcher; import org.apache.dubbo.rpc.cluster.router.xds.rule.XdsRouteRule; -import io.envoyproxy.envoy.config.route.v3.Route; -import io.envoyproxy.envoy.config.route.v3.RouteAction; -import io.envoyproxy.envoy.config.route.v3.RouteMatch; -import io.envoyproxy.envoy.config.route.v3.VirtualHost; - import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; +import io.envoyproxy.envoy.config.route.v3.Route; +import io.envoyproxy.envoy.config.route.v3.RouteAction; +import io.envoyproxy.envoy.config.route.v3.RouteMatch; +import io.envoyproxy.envoy.config.route.v3.VirtualHost; + public class RdsVirtualHostListener { - private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(RdsVirtualHostListener.class); + private static final ErrorTypeAwareLogger LOGGER = + LoggerFactory.getErrorTypeAwareLogger(RdsVirtualHostListener.class); private final String domain; private final RdsRouteRuleManager routeRuleManager; - public RdsVirtualHostListener(String domain, RdsRouteRuleManager routeRuleManager) { this.domain = domain; this.routeRuleManager = routeRuleManager; @@ -60,20 +60,27 @@ public class RdsVirtualHostListener { return; } try { - List xdsRouteRules = virtualHost.getRoutesList().stream().map(route -> { - if (route.getMatch().getQueryParametersCount() != 0) { - return null; - } - HttpRequestMatch match = parseMatch(route.getMatch()); - HTTPRouteDestination action = parseAction(route); - return new XdsRouteRule(match, action); - }).filter(Objects::nonNull).collect(Collectors.toList()); + List xdsRouteRules = virtualHost.getRoutesList().stream() + .map(route -> { + if (route.getMatch().getQueryParametersCount() != 0) { + return null; + } + HttpRequestMatch match = parseMatch(route.getMatch()); + HTTPRouteDestination action = parseAction(route); + return new XdsRouteRule(match, action); + }) + .filter(Objects::nonNull) + .collect(Collectors.toList()); // post rules routeRuleManager.notifyRuleChange(domain, xdsRouteRules); } catch (Exception e) { - LOGGER.error(LoggerCodeConstants.INTERNAL_ERROR, "", "", "parse domain: " + domain + " xds VirtualHost error", e); + LOGGER.error( + LoggerCodeConstants.INTERNAL_ERROR, + "", + "", + "parse domain: " + domain + " xds VirtualHost error", + e); } - } private HttpRequestMatch parseMatch(RouteMatch match) { @@ -158,11 +165,11 @@ public class RdsVirtualHostListener { httpRouteDestination.setCluster(routeAction.getCluster()); return httpRouteDestination; } else if (clusterSpecifierCase == RouteAction.ClusterSpecifierCase.WEIGHTED_CLUSTERS) { - List clusterWeights = routeAction.getWeightedClusters(). - getClustersList().stream() - .map(c -> new ClusterWeight(c.getName(), c.getWeight().getValue())) - .sorted(Comparator.comparing(ClusterWeight::getWeight)) - .collect(Collectors.toList()); + List clusterWeights = routeAction.getWeightedClusters().getClustersList().stream() + .map(c -> + new ClusterWeight(c.getName(), c.getWeight().getValue())) + .sorted(Comparator.comparing(ClusterWeight::getWeight)) + .collect(Collectors.toList()); httpRouteDestination.setWeightedClusters(clusterWeights); return httpRouteDestination; } @@ -174,5 +181,4 @@ public class RdsVirtualHostListener { throw new IllegalArgumentException("Cluster specifier is not expect"); } } - } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/XdsRouteRuleListener.java b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/XdsRouteRuleListener.java index bc2c5262ca..4e90fe2d41 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/XdsRouteRuleListener.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/XdsRouteRuleListener.java @@ -22,9 +22,7 @@ import java.util.List; public interface XdsRouteRuleListener { - void onRuleChange(String appName, List xdsRouteRules); void clearRule(String appName); - } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/XdsRouter.java b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/XdsRouter.java index c994a219ad..e043e2d3d7 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/XdsRouter.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/XdsRouter.java @@ -68,7 +68,8 @@ public class XdsRouter extends AbstractStateRouter implements XdsRouteRule public XdsRouter(URL url) { super(url); isEnable = PilotExchanger.isEnabled(); - rdsRouteRuleManager = url.getOrDefaultApplicationModel().getBeanFactory().getBean(RdsRouteRuleManager.class); + rdsRouteRuleManager = + url.getOrDefaultApplicationModel().getBeanFactory().getBean(RdsRouteRuleManager.class); edsEndpointManager = url.getOrDefaultApplicationModel().getBeanFactory().getBean(EdsEndpointManager.class); subscribeApplications = new ConcurrentHashSet<>(); destinationSubsetMap = new ConcurrentHashMap<>(); @@ -79,7 +80,8 @@ public class XdsRouter extends AbstractStateRouter implements XdsRouteRule /** * @deprecated only for uts */ - protected XdsRouter(URL url, RdsRouteRuleManager rdsRouteRuleManager, EdsEndpointManager edsEndpointManager, boolean isEnable) { + protected XdsRouter( + URL url, RdsRouteRuleManager rdsRouteRuleManager, EdsEndpointManager edsEndpointManager, boolean isEnable) { super(url); this.isEnable = isEnable; this.rdsRouteRuleManager = rdsRouteRuleManager; @@ -91,12 +93,18 @@ public class XdsRouter extends AbstractStateRouter implements XdsRouteRule } @Override - protected BitList> doRoute(BitList> invokers, URL url, Invocation invocation, - boolean needToPrintMessage, Holder> nodeHolder, - Holder messageHolder) throws RpcException { + protected BitList> doRoute( + BitList> invokers, + URL url, + Invocation invocation, + boolean needToPrintMessage, + Holder> nodeHolder, + Holder messageHolder) + throws RpcException { if (!isEnable) { if (needToPrintMessage) { - messageHolder.set("Directly Return. Reason: Pilot exchanger has not been initialized, may not in mesh mode."); + messageHolder.set( + "Directly Return. Reason: Pilot exchanger has not been initialized, may not in mesh mode."); } return invokers; } @@ -134,7 +142,12 @@ public class XdsRouter extends AbstractStateRouter implements XdsRouteRule } if (matchCluster != null) { if (stringBuilder != null) { - stringBuilder.append("Match App: ").append(subscribeApplication).append(" Cluster: ").append(matchCluster).append(' '); + stringBuilder + .append("Match App: ") + .append(subscribeApplication) + .append(" Cluster: ") + .append(matchCluster) + .append(' '); } break; } @@ -197,7 +210,8 @@ public class XdsRouter extends AbstractStateRouter implements XdsRouteRule } private String computeWeightCluster(List weightedClusters) { - int totalWeight = Math.max(weightedClusters.stream().mapToInt(ClusterWeight::getWeight).sum(), 1); + int totalWeight = Math.max( + weightedClusters.stream().mapToInt(ClusterWeight::getWeight).sum(), 1); // target must greater than 0 // if weight is 0, the destination will not receive any traffic. int target = ThreadLocalRandom.current().nextInt(1, totalWeight + 1); @@ -247,19 +261,20 @@ public class XdsRouter extends AbstractStateRouter implements XdsRouteRule computeSubset(subset, allInvokers); } } - } private void computeSubset(DestinationSubset subset, BitList> invokers) { Set endpoints = subset.getEndpoints(); - List> filterInvokers = invokers.stream().filter(inv -> { - String host = inv.getUrl().getHost(); - int port = inv.getUrl().getPort(); - Optional any = endpoints.stream() - .filter(end -> host.equals(end.getAddress()) && port == end.getPortValue()) - .findAny(); - return any.isPresent(); - }).collect(Collectors.toList()); + List> filterInvokers = invokers.stream() + .filter(inv -> { + String host = inv.getUrl().getHost(); + int port = inv.getUrl().getPort(); + Optional any = endpoints.stream() + .filter(end -> host.equals(end.getAddress()) && port == end.getPortValue()) + .findAny(); + return any.isPresent(); + }) + .collect(Collectors.toList()); subset.setInvokers(new BitList<>(filterInvokers)); } @@ -345,7 +360,6 @@ public class XdsRouter extends AbstractStateRouter implements XdsRouteRule } } - @Deprecated Set getSubscribeApplications() { return subscribeApplications; @@ -367,7 +381,6 @@ public class XdsRouter extends AbstractStateRouter implements XdsRouteRule return xdsRouteRuleMap; } - /** * for ut only */ @@ -375,5 +388,4 @@ public class XdsRouter extends AbstractStateRouter implements XdsRouteRule ConcurrentHashMap> getDestinationSubsetMap() { return destinationSubsetMap; } - } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/XdsScopeModelInitializer.java b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/XdsScopeModelInitializer.java index e94d4be4a9..b34b86ffce 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/XdsScopeModelInitializer.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/XdsScopeModelInitializer.java @@ -25,9 +25,7 @@ import org.apache.dubbo.rpc.model.ScopeModelInitializer; public class XdsScopeModelInitializer implements ScopeModelInitializer { @Override - public void initializeFrameworkModel(FrameworkModel frameworkModel) { - - } + public void initializeFrameworkModel(FrameworkModel frameworkModel) {} @Override public void initializeApplicationModel(ApplicationModel applicationModel) { @@ -37,6 +35,5 @@ public class XdsScopeModelInitializer implements ScopeModelInitializer { } @Override - public void initializeModuleModel(ModuleModel moduleModel) { - } + public void initializeModuleModel(ModuleModel moduleModel) {} } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/ClusterWeight.java b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/ClusterWeight.java index a48857cea4..fe1307c8f6 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/ClusterWeight.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/ClusterWeight.java @@ -34,5 +34,4 @@ public class ClusterWeight { public int getWeight() { return weight; } - } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/DestinationSubset.java b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/DestinationSubset.java index 9644a687b0..79fa2156f6 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/DestinationSubset.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/DestinationSubset.java @@ -45,7 +45,6 @@ public class DestinationSubset { public void setEndpoints(Set endpoints) { this.endpoints = endpoints; - } public BitList> getInvokers() { diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/HTTPRouteDestination.java b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/HTTPRouteDestination.java index 471e2a215a..91d55d337f 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/HTTPRouteDestination.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/HTTPRouteDestination.java @@ -39,5 +39,4 @@ public class HTTPRouteDestination { public void setWeightedClusters(List weightedClusters) { this.weightedClusters = weightedClusters; } - } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/HeaderMatcher.java b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/HeaderMatcher.java index 68bc38a9d5..04b0c45a04 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/HeaderMatcher.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/HeaderMatcher.java @@ -18,7 +18,6 @@ package org.apache.dubbo.rpc.cluster.router.xds.rule; public class HeaderMatcher { - public String name; public String exactValue; @@ -119,5 +118,4 @@ public class HeaderMatcher { } return false; } - } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/HttpRequestMatch.java b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/HttpRequestMatch.java index aff10ba890..fef5aa18e4 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/HttpRequestMatch.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/HttpRequestMatch.java @@ -36,6 +36,4 @@ public class HttpRequestMatch { public List getHeaderMatcherList() { return headerMatcherList; } - - } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/LongRangeMatch.java b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/LongRangeMatch.java index d52123f03b..df482575bd 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/LongRangeMatch.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/LongRangeMatch.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.rpc.cluster.router.xds.rule; public class LongRangeMatch { @@ -37,7 +36,6 @@ public class LongRangeMatch { this.end = end; } - public boolean isMatch(String input) { try { long num = Long.parseLong(input); diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/PathMatcher.java b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/PathMatcher.java index 00931fb0a5..cbf77e8711 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/PathMatcher.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/PathMatcher.java @@ -16,7 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.router.xds.rule; - public class PathMatcher { private String path; @@ -61,13 +60,11 @@ public class PathMatcher { public boolean isMatch(String input) { if (getPath() != null) { - return isCaseSensitive() - ? getPath().equals(input) - : getPath().equalsIgnoreCase(input); + return isCaseSensitive() ? getPath().equals(input) : getPath().equalsIgnoreCase(input); } else if (getPrefix() != null) { return isCaseSensitive() - ? input.startsWith(getPrefix()) - : input.toLowerCase().startsWith(getPrefix()); + ? input.startsWith(getPrefix()) + : input.toLowerCase().startsWith(getPrefix()); } return input.matches(getRegex()); } diff --git a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/XdsRouteRule.java b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/XdsRouteRule.java index 2ca613bdd1..5d2994d2d6 100644 --- a/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/XdsRouteRule.java +++ b/dubbo-xds/src/main/java/org/apache/dubbo/rpc/cluster/router/xds/rule/XdsRouteRule.java @@ -16,8 +16,6 @@ */ package org.apache.dubbo.rpc.cluster.router.xds.rule; - - public class XdsRouteRule { private final HttpRequestMatch match; @@ -29,7 +27,6 @@ public class XdsRouteRule { this.route = route; } - public HttpRequestMatch getMatch() { return match; } @@ -37,5 +34,4 @@ public class XdsRouteRule { public HTTPRouteDestination getRoute() { return route; } - } diff --git a/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/bootstrap/BootstrapperTest.java b/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/bootstrap/BootstrapperTest.java index 71875022a6..8efcdb02f0 100644 --- a/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/bootstrap/BootstrapperTest.java +++ b/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/bootstrap/BootstrapperTest.java @@ -20,116 +20,114 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.common.url.component.URLAddress; import org.apache.dubbo.registry.xds.XdsInitializationException; +import java.util.List; + import io.grpc.netty.shaded.io.netty.channel.unix.DomainSocketAddress; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.io.IOException; -import java.util.List; - class BootstrapperTest { @Test void testParse() throws XdsInitializationException { - String rawData = "{\n" + - " \"xds_servers\": [\n" + - " {\n" + - " \"server_uri\": \"unix:///etc/istio/proxy/XDS\",\n" + - " \"channel_creds\": [\n" + - " {\n" + - " \"type\": \"insecure\"\n" + - " }\n" + - " ],\n" + - " \"server_features\": [\n" + - " \"xds_v3\"\n" + - " ]\n" + - " }\n" + - " ],\n" + - " \"node\": {\n" + - " \"id\": \"sidecar~172.17.0.4~dubbo-demo-consumer-deployment-grpc-agent-58585cb9cd-gp79p.dubbo-demo~dubbo-demo.svc.cluster.local\",\n" + - " \"metadata\": {\n" + - " \"ANNOTATIONS\": {\n" + - " \"inject.istio.io/templates\": \"grpc-agent\",\n" + - " \"kubernetes.io/config.seen\": \"2022-07-19T12:53:29.742565722Z\",\n" + - " \"kubernetes.io/config.source\": \"api\",\n" + - " \"prometheus.io/path\": \"/stats/prometheus\",\n" + - " \"prometheus.io/port\": \"15020\",\n" + - " \"prometheus.io/scrape\": \"true\",\n" + - " \"proxy.istio.io/config\": \"{\\\"holdApplicationUntilProxyStarts\\\": true}\",\n" + - " \"proxy.istio.io/overrides\": \"{\\\"containers\\\":[{\\\"name\\\":\\\"app\\\",\\\"image\\\":\\\"gcr.io/istio-testing/app:latest\\\",\\\"args\\\":[\\\"--metrics=15014\\\",\\\"--port\\\",\\\"18080\\\",\\\"--tcp\\\",\\\"19090\\\",\\\"--xds-grpc-server=17070\\\",\\\"--grpc\\\",\\\"17070\\\",\\\"--grpc\\\",\\\"17171\\\",\\\"--port\\\",\\\"3333\\\",\\\"--port\\\",\\\"8080\\\",\\\"--version\\\",\\\"v1\\\",\\\"--crt=/cert.crt\\\",\\\"--key=/cert.key\\\"],\\\"ports\\\":[{\\\"containerPort\\\":17070,\\\"protocol\\\":\\\"TCP\\\"},{\\\"containerPort\\\":17171,\\\"protocol\\\":\\\"TCP\\\"},{\\\"containerPort\\\":8080,\\\"protocol\\\":\\\"TCP\\\"},{\\\"name\\\":\\\"tcp-health-port\\\",\\\"containerPort\\\":3333,\\\"protocol\\\":\\\"TCP\\\"}],\\\"env\\\":[{\\\"name\\\":\\\"INSTANCE_IP\\\",\\\"valueFrom\\\":{\\\"fieldRef\\\":{\\\"apiVersion\\\":\\\"v1\\\",\\\"fieldPath\\\":\\\"status.podIP\\\"}}}],\\\"resources\\\":{},\\\"volumeMounts\\\":[{\\\"name\\\":\\\"kube-api-access-2tknx\\\",\\\"readOnly\\\":true,\\\"mountPath\\\":\\\"/var/run/secrets/kubernetes.io/serviceaccount\\\"}],\\\"livenessProbe\\\":{\\\"tcpSocket\\\":{\\\"port\\\":\\\"tcp-health-port\\\"},\\\"initialDelaySeconds\\\":10,\\\"timeoutSeconds\\\":1,\\\"periodSeconds\\\":10,\\\"successThreshold\\\":1,\\\"failureThreshold\\\":10},\\\"readinessProbe\\\":{\\\"httpGet\\\":{\\\"path\\\":\\\"/\\\",\\\"port\\\":8080,\\\"scheme\\\":\\\"HTTP\\\"},\\\"initialDelaySeconds\\\":1,\\\"timeoutSeconds\\\":1,\\\"periodSeconds\\\":2,\\\"successThreshold\\\":1,\\\"failureThreshold\\\":10},\\\"startupProbe\\\":{\\\"tcpSocket\\\":{\\\"port\\\":\\\"tcp-health-port\\\"},\\\"timeoutSeconds\\\":1,\\\"periodSeconds\\\":10,\\\"successThreshold\\\":1,\\\"failureThreshold\\\":10},\\\"terminationMessagePath\\\":\\\"/dev/termination-log\\\",\\\"terminationMessagePolicy\\\":\\\"File\\\",\\\"imagePullPolicy\\\":\\\"Always\\\",\\\"securityContext\\\":{\\\"runAsUser\\\":1338,\\\"runAsGroup\\\":1338}},{\\\"name\\\":\\\"dubbo-demo-consumer\\\",\\\"image\\\":\\\"dockeddocking/dubbo:consumer.v1.0\\\",\\\"command\\\":[\\\"sh\\\",\\\"-c\\\",\\\"java $JAVA_OPTS -jar dubbo-demo-consumer.jar \\\"],\\\"resources\\\":{},\\\"volumeMounts\\\":[{\\\"name\\\":\\\"kube-api-access-2tknx\\\",\\\"readOnly\\\":true,\\\"mountPath\\\":\\\"/var/run/secrets/kubernetes.io/serviceaccount\\\"}],\\\"terminationMessagePath\\\":\\\"/dev/termination-log\\\",\\\"terminationMessagePolicy\\\":\\\"File\\\",\\\"imagePullPolicy\\\":\\\"Always\\\"}]}\",\n" + - " \"sidecar.istio.io/rewriteAppHTTPProbers\": \"false\",\n" + - " \"sidecar.istio.io/status\": \"{\\\"initContainers\\\":null,\\\"containers\\\":[\\\"app\\\",\\\"dubbo-demo-consumer\\\",\\\"istio-proxy\\\"],\\\"volumes\\\":[\\\"workload-socket\\\",\\\"workload-certs\\\",\\\"istio-xds\\\",\\\"istio-data\\\",\\\"istio-podinfo\\\",\\\"istio-token\\\",\\\"istiod-ca-cert\\\"],\\\"imagePullSecrets\\\":null,\\\"revision\\\":\\\"default\\\"}\"\n" + - " },\n" + - " \"APP_CONTAINERS\": \"app,dubbo-demo-consumer\",\n" + - " \"CLUSTER_ID\": \"Kubernetes\",\n" + - " \"ENVOY_PROMETHEUS_PORT\": 15090,\n" + - " \"ENVOY_STATUS_PORT\": 15021,\n" + - " \"GENERATOR\": \"grpc\",\n" + - " \"INSTANCE_IPS\": \"172.17.0.4\",\n" + - " \"INTERCEPTION_MODE\": \"REDIRECT\",\n" + - " \"ISTIO_PROXY_SHA\": \"2b6009118109b480e1d5abf3188fd7d9c0c0acf0\",\n" + - " \"ISTIO_VERSION\": \"1.14.1\",\n" + - " \"LABELS\": {\n" + - " \"app\": \"dubbo-demo-consumer-dev\",\n" + - " \"pod-template-hash\": \"58585cb9cd\",\n" + - " \"service.istio.io/canonical-name\": \"dubbo-demo-consumer-dev\",\n" + - " \"service.istio.io/canonical-revision\": \"v1\",\n" + - " \"version\": \"v1\"\n" + - " },\n" + - " \"MESH_ID\": \"cluster.local\",\n" + - " \"NAME\": \"dubbo-demo-consumer-deployment-grpc-agent-58585cb9cd-gp79p\",\n" + - " \"NAMESPACE\": \"dubbo-demo\",\n" + - " \"OWNER\": \"kubernetes://apis/apps/v1/namespaces/dubbo-demo/deployments/dubbo-demo-consumer-deployment-grpc-agent\",\n" + - " \"PILOT_SAN\": [\n" + - " \"istiod.istio-system.svc\"\n" + - " ],\n" + - " \"POD_PORTS\": \"[{\\\"containerPort\\\":17070,\\\"protocol\\\":\\\"TCP\\\"},{\\\"containerPort\\\":17171,\\\"protocol\\\":\\\"TCP\\\"},{\\\"containerPort\\\":8080,\\\"protocol\\\":\\\"TCP\\\"},{\\\"name\\\":\\\"tcp-health-port\\\",\\\"containerPort\\\":3333,\\\"protocol\\\":\\\"TCP\\\"}]\",\n" + - " \"PROV_CERT\": \"var/run/secrets/istio/root-cert.pem\",\n" + - " \"PROXY_CONFIG\": {\n" + - " \"binaryPath\": \"/usr/local/bin/envoy\",\n" + - " \"concurrency\": 2,\n" + - " \"configPath\": \"./etc/istio/proxy\",\n" + - " \"controlPlaneAuthPolicy\": \"MUTUAL_TLS\",\n" + - " \"discoveryAddress\": \"istiod.istio-system.svc:15012\",\n" + - " \"drainDuration\": \"45s\",\n" + - " \"holdApplicationUntilProxyStarts\": true,\n" + - " \"parentShutdownDuration\": \"60s\",\n" + - " \"proxyAdminPort\": 15000,\n" + - " \"serviceCluster\": \"istio-proxy\",\n" + - " \"statNameLength\": 189,\n" + - " \"statusPort\": 15020,\n" + - " \"terminationDrainDuration\": \"5s\",\n" + - " \"tracing\": {\n" + - " \"zipkin\": {\n" + - " \"address\": \"zipkin.istio-system:9411\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"SERVICE_ACCOUNT\": \"default\",\n" + - " \"WORKLOAD_NAME\": \"dubbo-demo-consumer-deployment-grpc-agent\"\n" + - " },\n" + - " \"locality\": {},\n" + - " \"UserAgentVersionType\": null\n" + - " },\n" + - " \"certificate_providers\": {\n" + - " \"default\": {\n" + - " \"plugin_name\": \"file_watcher\",\n" + - " \"config\": {\n" + - " \"certificate_file\": \"/var/lib/istio/data/cert-chain.pem\",\n" + - " \"private_key_file\": \"/var/lib/istio/data/key.pem\",\n" + - " \"ca_certificate_file\": \"/var/lib/istio/data/root-cert.pem\",\n" + - " \"refresh_interval\": \"900s\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"server_listener_resource_name_template\": \"xds.istio.io/grpc/lds/inbound/%s\"\n" + - "}"; + String rawData = "{\n" + " \"xds_servers\": [\n" + + " {\n" + + " \"server_uri\": \"unix:///etc/istio/proxy/XDS\",\n" + + " \"channel_creds\": [\n" + + " {\n" + + " \"type\": \"insecure\"\n" + + " }\n" + + " ],\n" + + " \"server_features\": [\n" + + " \"xds_v3\"\n" + + " ]\n" + + " }\n" + + " ],\n" + + " \"node\": {\n" + + " \"id\": \"sidecar~172.17.0.4~dubbo-demo-consumer-deployment-grpc-agent-58585cb9cd-gp79p.dubbo-demo~dubbo-demo.svc.cluster.local\",\n" + + " \"metadata\": {\n" + + " \"ANNOTATIONS\": {\n" + + " \"inject.istio.io/templates\": \"grpc-agent\",\n" + + " \"kubernetes.io/config.seen\": \"2022-07-19T12:53:29.742565722Z\",\n" + + " \"kubernetes.io/config.source\": \"api\",\n" + + " \"prometheus.io/path\": \"/stats/prometheus\",\n" + + " \"prometheus.io/port\": \"15020\",\n" + + " \"prometheus.io/scrape\": \"true\",\n" + + " \"proxy.istio.io/config\": \"{\\\"holdApplicationUntilProxyStarts\\\": true}\",\n" + + " \"proxy.istio.io/overrides\": \"{\\\"containers\\\":[{\\\"name\\\":\\\"app\\\",\\\"image\\\":\\\"gcr.io/istio-testing/app:latest\\\",\\\"args\\\":[\\\"--metrics=15014\\\",\\\"--port\\\",\\\"18080\\\",\\\"--tcp\\\",\\\"19090\\\",\\\"--xds-grpc-server=17070\\\",\\\"--grpc\\\",\\\"17070\\\",\\\"--grpc\\\",\\\"17171\\\",\\\"--port\\\",\\\"3333\\\",\\\"--port\\\",\\\"8080\\\",\\\"--version\\\",\\\"v1\\\",\\\"--crt=/cert.crt\\\",\\\"--key=/cert.key\\\"],\\\"ports\\\":[{\\\"containerPort\\\":17070,\\\"protocol\\\":\\\"TCP\\\"},{\\\"containerPort\\\":17171,\\\"protocol\\\":\\\"TCP\\\"},{\\\"containerPort\\\":8080,\\\"protocol\\\":\\\"TCP\\\"},{\\\"name\\\":\\\"tcp-health-port\\\",\\\"containerPort\\\":3333,\\\"protocol\\\":\\\"TCP\\\"}],\\\"env\\\":[{\\\"name\\\":\\\"INSTANCE_IP\\\",\\\"valueFrom\\\":{\\\"fieldRef\\\":{\\\"apiVersion\\\":\\\"v1\\\",\\\"fieldPath\\\":\\\"status.podIP\\\"}}}],\\\"resources\\\":{},\\\"volumeMounts\\\":[{\\\"name\\\":\\\"kube-api-access-2tknx\\\",\\\"readOnly\\\":true,\\\"mountPath\\\":\\\"/var/run/secrets/kubernetes.io/serviceaccount\\\"}],\\\"livenessProbe\\\":{\\\"tcpSocket\\\":{\\\"port\\\":\\\"tcp-health-port\\\"},\\\"initialDelaySeconds\\\":10,\\\"timeoutSeconds\\\":1,\\\"periodSeconds\\\":10,\\\"successThreshold\\\":1,\\\"failureThreshold\\\":10},\\\"readinessProbe\\\":{\\\"httpGet\\\":{\\\"path\\\":\\\"/\\\",\\\"port\\\":8080,\\\"scheme\\\":\\\"HTTP\\\"},\\\"initialDelaySeconds\\\":1,\\\"timeoutSeconds\\\":1,\\\"periodSeconds\\\":2,\\\"successThreshold\\\":1,\\\"failureThreshold\\\":10},\\\"startupProbe\\\":{\\\"tcpSocket\\\":{\\\"port\\\":\\\"tcp-health-port\\\"},\\\"timeoutSeconds\\\":1,\\\"periodSeconds\\\":10,\\\"successThreshold\\\":1,\\\"failureThreshold\\\":10},\\\"terminationMessagePath\\\":\\\"/dev/termination-log\\\",\\\"terminationMessagePolicy\\\":\\\"File\\\",\\\"imagePullPolicy\\\":\\\"Always\\\",\\\"securityContext\\\":{\\\"runAsUser\\\":1338,\\\"runAsGroup\\\":1338}},{\\\"name\\\":\\\"dubbo-demo-consumer\\\",\\\"image\\\":\\\"dockeddocking/dubbo:consumer.v1.0\\\",\\\"command\\\":[\\\"sh\\\",\\\"-c\\\",\\\"java $JAVA_OPTS -jar dubbo-demo-consumer.jar \\\"],\\\"resources\\\":{},\\\"volumeMounts\\\":[{\\\"name\\\":\\\"kube-api-access-2tknx\\\",\\\"readOnly\\\":true,\\\"mountPath\\\":\\\"/var/run/secrets/kubernetes.io/serviceaccount\\\"}],\\\"terminationMessagePath\\\":\\\"/dev/termination-log\\\",\\\"terminationMessagePolicy\\\":\\\"File\\\",\\\"imagePullPolicy\\\":\\\"Always\\\"}]}\",\n" + + " \"sidecar.istio.io/rewriteAppHTTPProbers\": \"false\",\n" + + " \"sidecar.istio.io/status\": \"{\\\"initContainers\\\":null,\\\"containers\\\":[\\\"app\\\",\\\"dubbo-demo-consumer\\\",\\\"istio-proxy\\\"],\\\"volumes\\\":[\\\"workload-socket\\\",\\\"workload-certs\\\",\\\"istio-xds\\\",\\\"istio-data\\\",\\\"istio-podinfo\\\",\\\"istio-token\\\",\\\"istiod-ca-cert\\\"],\\\"imagePullSecrets\\\":null,\\\"revision\\\":\\\"default\\\"}\"\n" + + " },\n" + + " \"APP_CONTAINERS\": \"app,dubbo-demo-consumer\",\n" + + " \"CLUSTER_ID\": \"Kubernetes\",\n" + + " \"ENVOY_PROMETHEUS_PORT\": 15090,\n" + + " \"ENVOY_STATUS_PORT\": 15021,\n" + + " \"GENERATOR\": \"grpc\",\n" + + " \"INSTANCE_IPS\": \"172.17.0.4\",\n" + + " \"INTERCEPTION_MODE\": \"REDIRECT\",\n" + + " \"ISTIO_PROXY_SHA\": \"2b6009118109b480e1d5abf3188fd7d9c0c0acf0\",\n" + + " \"ISTIO_VERSION\": \"1.14.1\",\n" + + " \"LABELS\": {\n" + + " \"app\": \"dubbo-demo-consumer-dev\",\n" + + " \"pod-template-hash\": \"58585cb9cd\",\n" + + " \"service.istio.io/canonical-name\": \"dubbo-demo-consumer-dev\",\n" + + " \"service.istio.io/canonical-revision\": \"v1\",\n" + + " \"version\": \"v1\"\n" + + " },\n" + + " \"MESH_ID\": \"cluster.local\",\n" + + " \"NAME\": \"dubbo-demo-consumer-deployment-grpc-agent-58585cb9cd-gp79p\",\n" + + " \"NAMESPACE\": \"dubbo-demo\",\n" + + " \"OWNER\": \"kubernetes://apis/apps/v1/namespaces/dubbo-demo/deployments/dubbo-demo-consumer-deployment-grpc-agent\",\n" + + " \"PILOT_SAN\": [\n" + + " \"istiod.istio-system.svc\"\n" + + " ],\n" + + " \"POD_PORTS\": \"[{\\\"containerPort\\\":17070,\\\"protocol\\\":\\\"TCP\\\"},{\\\"containerPort\\\":17171,\\\"protocol\\\":\\\"TCP\\\"},{\\\"containerPort\\\":8080,\\\"protocol\\\":\\\"TCP\\\"},{\\\"name\\\":\\\"tcp-health-port\\\",\\\"containerPort\\\":3333,\\\"protocol\\\":\\\"TCP\\\"}]\",\n" + + " \"PROV_CERT\": \"var/run/secrets/istio/root-cert.pem\",\n" + + " \"PROXY_CONFIG\": {\n" + + " \"binaryPath\": \"/usr/local/bin/envoy\",\n" + + " \"concurrency\": 2,\n" + + " \"configPath\": \"./etc/istio/proxy\",\n" + + " \"controlPlaneAuthPolicy\": \"MUTUAL_TLS\",\n" + + " \"discoveryAddress\": \"istiod.istio-system.svc:15012\",\n" + + " \"drainDuration\": \"45s\",\n" + + " \"holdApplicationUntilProxyStarts\": true,\n" + + " \"parentShutdownDuration\": \"60s\",\n" + + " \"proxyAdminPort\": 15000,\n" + + " \"serviceCluster\": \"istio-proxy\",\n" + + " \"statNameLength\": 189,\n" + + " \"statusPort\": 15020,\n" + + " \"terminationDrainDuration\": \"5s\",\n" + + " \"tracing\": {\n" + + " \"zipkin\": {\n" + + " \"address\": \"zipkin.istio-system:9411\"\n" + + " }\n" + + " }\n" + + " },\n" + + " \"SERVICE_ACCOUNT\": \"default\",\n" + + " \"WORKLOAD_NAME\": \"dubbo-demo-consumer-deployment-grpc-agent\"\n" + + " },\n" + + " \"locality\": {},\n" + + " \"UserAgentVersionType\": null\n" + + " },\n" + + " \"certificate_providers\": {\n" + + " \"default\": {\n" + + " \"plugin_name\": \"file_watcher\",\n" + + " \"config\": {\n" + + " \"certificate_file\": \"/var/lib/istio/data/cert-chain.pem\",\n" + + " \"private_key_file\": \"/var/lib/istio/data/key.pem\",\n" + + " \"ca_certificate_file\": \"/var/lib/istio/data/root-cert.pem\",\n" + + " \"refresh_interval\": \"900s\"\n" + + " }\n" + + " }\n" + + " },\n" + + " \"server_listener_resource_name_template\": \"xds.istio.io/grpc/lds/inbound/%s\"\n" + + "}"; BootstrapperImpl.bootstrapPathFromEnvVar = ""; BootstrapperImpl bootstrapper = new BootstrapperImpl(); bootstrapper.setFileReader(createFileReader(rawData)); Bootstrapper.BootstrapInfo info = bootstrapper.bootstrap(); List serverInfoList = info.servers(); Assertions.assertEquals(serverInfoList.get(0).target(), "unix:///etc/istio/proxy/XDS"); - URLAddress address =URLAddress.parse(serverInfoList.get(0).target(),null, false); + URLAddress address = URLAddress.parse(serverInfoList.get(0).target(), null, false); Assertions.assertEquals(new DomainSocketAddress(address.getPath()).path(), "etc/istio/proxy/XDS"); } @@ -147,5 +145,4 @@ class BootstrapperTest { } }; } - } diff --git a/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/protocol/impl/DsProtocolTest.java b/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/protocol/impl/DsProtocolTest.java deleted file mode 100644 index 354784d7de..0000000000 --- a/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/protocol/impl/DsProtocolTest.java +++ /dev/null @@ -1,542 +0,0 @@ -///* -// * Licensed to the Apache Software Foundation (ASF) under one or more -// * contributor license agreements. See the NOTICE file distributed with -// * this work for additional information regarding copyright ownership. -// * The ASF licenses this file to You 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 org.apache.dubbo.registry.xds.util.protocol.impl; -// -//import io.envoyproxy.envoy.config.core.v3.Node; -//import io.envoyproxy.envoy.service.discovery.v3.DiscoveryRequest; -//import io.grpc.stub.StreamObserver; -//import org.apache.dubbo.common.URL; -//import org.apache.dubbo.registry.xds.util.XdsChannel; -//import org.apache.dubbo.registry.xds.util.protocol.AbstractProtocol; -//import org.apache.dubbo.registry.xds.util.protocol.message.Endpoint; -//import org.apache.dubbo.registry.xds.util.protocol.message.EndpointResult; -//import org.apache.dubbo.registry.xds.util.protocol.message.ListenerResult; -//import org.apache.dubbo.registry.xds.util.protocol.message.RouteResult; -//import org.apache.dubbo.rpc.model.ApplicationModel; -//import org.junit.jupiter.api.Assertions; -//import org.junit.jupiter.api.BeforeEach; -//import org.junit.jupiter.api.Test; -//import org.mockito.MockedConstruction; -//import org.mockito.MockedStatic; -// -//import java.util.ArrayList; -//import java.util.HashMap; -//import java.util.HashSet; -//import java.util.List; -//import java.util.Map; -//import java.util.Set; -//import java.util.concurrent.CompletableFuture; -//import java.util.concurrent.CountDownLatch; -//import java.util.concurrent.atomic.AtomicBoolean; -//import java.util.function.Consumer; -//import java.util.stream.Collectors; -// -//import static org.mockito.Mockito.spy; -//import static org.mockito.Mockito.mock; -//import static org.mockito.Mockito.when; -//import static org.mockito.Mockito.doNothing; -//import static org.mockito.Mockito.verify; -//import static org.mockito.Mockito.any; -//import static org.mockito.Mockito.mockConstruction; -//import static org.mockito.Mockito.times; -// -//public class DsProtocolTest { -// private XdsChannel xdsChannel; -// -// private LdsProtocolMock ldsProtocolMock; -// private RdsProtocolMock rdsProtocolMock; -// -// private EdsProtocolMock edsProtocolMock; -// -// private Map listenerResult; -// -// private Set routeConfigNames; -// -// private Set cluster; -// private Map routeResult; -// -// private Set endpoints; -// private Map endpointResult; -// -// private Map> domainMap; -// -// private ApplicationModel applicationModel; -// private URL url; -// -// private Node node; -// -// public DsProtocolTest() { -// } -// -// @BeforeEach -// public void setUp() { -// this.url = spy(URL.valueOf("xds://istiod.istio-system.svc:15012?secure=plaintext")); -// this.node = mock(Node.class); -// -// this.applicationModel = ApplicationModel.defaultModel(); -// xdsChannel = mock(XdsChannel.class); -// when(xdsChannel.getUrl()).thenReturn(url); -// -// this.ldsProtocolMock = spy(new LdsProtocolMock(xdsChannel, node, 1, applicationModel)); -// this.rdsProtocolMock = spy(new RdsProtocolMock(xdsChannel, node, 1, applicationModel)); -// this.edsProtocolMock = spy(new EdsProtocolMock(xdsChannel, node, 1, applicationModel)); -// -// // mock lister result -// this.routeConfigNames = new HashSet<>(); -// routeConfigNames.add("15014"); -// Map listenerResults = new HashMap(); -// listenerResults.put(ldsProtocolMock.emptyResourceName,new ListenerResult(routeConfigNames)); -// this.listenerResult = spy(listenerResults); -// -// // mock route result -// this.domainMap = new HashMap<>(); -// Set domainValue = new HashSet<>(); -// domainValue.add("outbound|15014||istiod.istio-system.svc.cluster.local"); -// domainMap.put("istiod.istio-system.svc", domainValue); -// Map routeResults = new HashMap(); -// routeResults.put("15014", new RouteResult(domainMap)); -// this.routeResult = routeResults; -// -// // mock eds result -// Set cluster = new HashSet<>(); -// cluster.add("dubbo-samples-provider"); -// this.cluster = cluster; -// Endpoint endpoint = new Endpoint(); -// endpoint.setWeight(1); -// endpoint.setHealthy(true); -// endpoint.setPortValue(50051); -// endpoint.setAddress("10.1.1.67"); -// this.endpoints = new HashSet<>(); -// endpoints.add(endpoint); -// Map endpointResults = new HashMap(); -// endpointResults.put("dubbo-samples-provider" ,new EndpointResult(endpoints)); -// this.endpointResult = endpointResults; -//// mockedStatic.close(); -// } -// -// -// @Test -// void testGetResource() { -// StreamObserver requestStreamObserver = mock(StreamObserver.class); -// -// // mock lds getResource -// when(xdsChannel.createDeltaDiscoveryRequest(any(StreamObserver.class))).thenReturn(requestStreamObserver); -// MockedConstruction ldsMocked = mockConstruction(CompletableFuture.class, (mock, context) -> { -// when(mock.get()).thenReturn(listenerResult); -// }); -// Map ldsResult = ldsProtocolMock.getResource(null); -// -// Assertions.assertNotNull(ldsResult); -// verify(ldsProtocolMock, times(0)).isCacheExistResource(null); -// ldsMocked.close(); -// -// // mock rds getResource -// MockedConstruction rdsMocked = mockConstruction(CompletableFuture.class, (mock, context) -> { -// when(mock.get()).thenReturn(null); -// }); -// -// Map rdsResult = rdsProtocolMock.getResource(routeConfigNames); -// -// Assertions.assertNull(rdsResult); -// Assertions.assertFalse(rdsProtocolMock.isCacheExistResource(routeConfigNames)); -// -// rdsProtocolMock.getResourcesMap().putAll(routeResult); -// rdsResult = rdsProtocolMock.getResource(routeConfigNames); -// Assertions.assertNotNull(rdsResult); -// Assertions.assertTrue(rdsProtocolMock.isCacheExistResource(routeConfigNames)); -// Map newRdsResult = routeConfigNames.stream().collect(Collectors.toMap(k -> k, v -> rdsProtocolMock.getCacheResource(v))); -// Assertions.assertEquals(newRdsResult, rdsResult); -// rdsMocked.close(); -// -// //mock eds getResource -// MockedConstruction edsMocked = mockConstruction(CompletableFuture.class, (mock, context) -> { -// when(mock.get()).thenReturn(null); -// }); -// -// Map edsResult = edsProtocolMock.getResource(cluster); -// verify(edsProtocolMock, times(1)).isCacheExistResource(cluster); -// Assertions.assertNull(edsResult); -// Assertions.assertFalse(edsProtocolMock.isCacheExistResource(cluster)); -// edsProtocolMock.getResourcesMap().put("dubbo-samples-provider", new EndpointResult(endpoints)); -// edsResult = edsProtocolMock.getResource(cluster); -// Assertions.assertNotNull(edsResult); -// Assertions.assertTrue(edsProtocolMock.isCacheExistResource(cluster)); -// -// Map newEdsResult = cluster.stream().collect(Collectors.toMap(k -> k, v -> edsProtocolMock.getCacheResource(v))); -// Assertions.assertEquals(newEdsResult, endpointResult); -// edsMocked.close(); -// } -// -// @Test -// void observeDsReConnect() { -// StreamObserver requestStreamObserver = mock(StreamObserver.class); -// -// // mock lds reconnect -// when(xdsChannel.createDeltaDiscoveryRequest(any(StreamObserver.class))).thenReturn(requestStreamObserver); -// doNothing().when(requestStreamObserver).onNext(any()); -// -// Map, List>>> ldsMap = new HashMap<>(); -// AtomicBoolean isLdsReConnect = new AtomicBoolean(false); -// CountDownLatch ldsCountDownLatch = new CountDownLatch(1); -//// // support multi-consumer -// Consumer> consumer = (listenerResult) -> { -// isLdsReConnect.set(true); -// ldsCountDownLatch.countDown(); -// }; -// ldsMap.compute(new HashSet<>(), (k, v) -> { -// if (v == null) { -// v = new ArrayList<>(); -// } -// v.add(consumer); -// // support multi-consumer -// return v; -// }); -// Assertions.assertFalse(isLdsReConnect.get()); -// ldsProtocolMock.setConsumerObserveMap(ldsMap); -// try { -// triggerConsumerObserveMapListener(listenerResult, ldsProtocolMock); -// ldsProtocolMock.getResponseObserve().onError(new RuntimeException()); -// ldsCountDownLatch.await(); -// Assertions.assertTrue(isLdsReConnect.get()); -// } catch (Exception e) { -// Assertions.assertTrue(isLdsReConnect.get()); -// } -// -// //mock rds reconnnect -// Map, List>>> rdsMap = new HashMap<>(); -// AtomicBoolean isRdsReConnect = new AtomicBoolean(false); -// CountDownLatch rdsCountDownLatch = new CountDownLatch(1); -// // support multi-consumer -// Consumer> rdsConsumer = (routeResult) -> { -// isRdsReConnect.set(true); -// rdsCountDownLatch.countDown(); -// }; -// rdsMap.compute(new HashSet<>(), (k, v) -> { -// if (v == null) { -// v = new ArrayList<>(); -// } -// v.add(rdsConsumer); -// // support multi-consumer -// return v; -// }); -// Assertions.assertFalse(isRdsReConnect.get()); -// rdsProtocolMock.setConsumerObserveMap(rdsMap); -// try { -// triggerConsumerObserveMapListener(routeResult, rdsProtocolMock); -// rdsProtocolMock.getResponseObserve().onError(new RuntimeException()); -// rdsCountDownLatch.await(); -// Assertions.assertTrue(isRdsReConnect.get()); -// } catch (Exception e) { -// Assertions.assertTrue(isRdsReConnect.get()); -// } -// -// // mock eds -// Map, List>>> edsMap = new HashMap<>(); -// AtomicBoolean isEdsReConnect = new AtomicBoolean(false); -// CountDownLatch edsCountDownLatch = new CountDownLatch(1); -// // support multi-consumer -// Consumer> edsConsumer = (routeResult) -> { -// isEdsReConnect.set(true); -// edsCountDownLatch.countDown(); -// }; -// edsMap.compute(new HashSet<>(), (k, v) -> { -// if (v == null) { -// v = new ArrayList<>(); -// } -// v.add(edsConsumer); -// // support multi-consumer -// return v; -// }); -// Assertions.assertFalse(isEdsReConnect.get()); -// edsProtocolMock.setConsumerObserveMap(edsMap); -// try { -// triggerConsumerObserveMapListener(endpointResult, edsProtocolMock); -// edsProtocolMock.getResponseObserve().onError(new RuntimeException()); -// edsCountDownLatch.await(); -// Assertions.assertTrue(isEdsReConnect.get()); -// } catch (Exception e) { -// Assertions.assertTrue(isEdsReConnect.get()); -// } -// } -// -// -// @Test -// public void testMultiConsumer() { -// StreamObserver requestStreamObserver = mock(StreamObserver.class); -// when(xdsChannel.createDeltaDiscoveryRequest(any(StreamObserver.class))).thenReturn(requestStreamObserver); -// doNothing().when(requestStreamObserver).onNext(any()); -// MockedConstruction ldsMocked = mockConstruction(CompletableFuture.class, (mock, context) -> { -// when(mock.get()).thenReturn(listenerResult); -// }); -// -// Map, List>>> ldsMap = new HashMap<>(); -// AtomicBoolean ldsIsFirstConsumerInvoke = new AtomicBoolean(false); -// AtomicBoolean ldsIsSecondConsumerInvoke = new AtomicBoolean(false); -// CountDownLatch ldsCountDownLatch = new CountDownLatch(2); -// -// // support repeat consumer -// Consumer> ldsFirstConsumer = (listenerResult) -> { -// ldsIsFirstConsumerInvoke.set(true); -// ldsCountDownLatch.countDown(); -// }; -// Consumer> ldsSecondConsumer = (listenerResult) -> { -// ldsIsSecondConsumerInvoke.set(true); -// ldsCountDownLatch.countDown(); -// }; -// Set ldsResourceNames = new HashSet<>(); -// ldsResourceNames.add(ldsProtocolMock.emptyResourceName); -// -// ldsMap.computeIfAbsent(ldsResourceNames, (key) -> { -// List>> consumers = new ArrayList<>(); -// consumers.add(ldsFirstConsumer); -// consumers.add(ldsSecondConsumer); -// return consumers; -// }); -// Assertions.assertFalse(ldsIsFirstConsumerInvoke.get() || ldsIsSecondConsumerInvoke.get()); -// ldsProtocolMock.setConsumerObserveMap(ldsMap); -// -// Map oldLdsResult = new HashMap<>(); -// Map newLdsResult = new HashMap<>(); -// -// oldLdsResult.put("emptyResourcesName1", new ListenerResult(routeConfigNames)); -// newLdsResult.put("emptyResourcesName", new ListenerResult(routeConfigNames)); -// newLdsResult.put("emptyResourcesName", new ListenerResult(routeConfigNames)); -// try { -// ldsProtocolMock.getResponseObserve().discoveryResponseListener(oldLdsResult, newLdsResult); -// ldsCountDownLatch.await(); -// Assertions.assertTrue(ldsIsFirstConsumerInvoke.get() && ldsIsSecondConsumerInvoke.get()); -// } catch (Exception e) { -// Assertions.assertTrue(ldsIsFirstConsumerInvoke.get() && ldsIsSecondConsumerInvoke.get()); -// } finally { -// ldsMocked.close(); -// } -// -// // mock rds -// MockedConstruction rdsMocked = mockConstruction(CompletableFuture.class, (mock, context) -> { -// when(mock.get()).thenReturn(routeResult); -// }); -// -// Map, List>>> rdsMap = new HashMap<>(); -// AtomicBoolean rdsIsFirstConsumerInvoke = new AtomicBoolean(false); -// AtomicBoolean rdsIsSecondConsumerInvoke = new AtomicBoolean(false); -// CountDownLatch rdsCountDownLatch = new CountDownLatch(2); -// -// // support repeat consumer -// Consumer> rdsFirstConsumer = (routeResult) -> { -// rdsIsFirstConsumerInvoke.set(true); -// rdsCountDownLatch.countDown(); -// }; -// Consumer> rdsSecondConsumer = (routeResult) -> { -// rdsIsSecondConsumerInvoke.set(true); -// rdsCountDownLatch.countDown(); -// }; -// rdsMap.computeIfAbsent(routeConfigNames, (key) -> { -// List>> consumers = new ArrayList<>(); -// consumers.add(rdsFirstConsumer); -// consumers.add(rdsSecondConsumer); -// return consumers; -// }); -// Assertions.assertFalse(rdsIsFirstConsumerInvoke.get() || rdsIsSecondConsumerInvoke.get()); -// rdsProtocolMock.setConsumerObserveMap(rdsMap); -// -// Map oldRdsResult = new HashMap<>(); -// Map newRdsResult = new HashMap<>(); -// -// oldRdsResult.put("15013", new RouteResult(domainMap)); -// newRdsResult.put("15014", new RouteResult(domainMap)); -// newRdsResult.put("15014", new RouteResult(domainMap)); -// -// try { -// rdsProtocolMock.getResponseObserve().discoveryResponseListener(oldRdsResult, newRdsResult); -// rdsCountDownLatch.await(); -// Assertions.assertTrue(rdsIsFirstConsumerInvoke.get() && rdsIsSecondConsumerInvoke.get()); -// } catch (Exception e) { -// Assertions.assertTrue(rdsIsSecondConsumerInvoke.get() && rdsIsSecondConsumerInvoke.get()); -// } finally { -// rdsMocked.close(); -// } -// -// // mock eds -// MockedConstruction edsMocked = mockConstruction(CompletableFuture.class, (mock, context) -> { -// when(mock.get()).thenReturn(endpointResult); -// }); -// -// Map, List>>> edsMap = new HashMap<>(); -// AtomicBoolean edsIsFirstConsumerInvoke = new AtomicBoolean(false); -// AtomicBoolean edsIsSecondConsumerInvoke = new AtomicBoolean(false); -// CountDownLatch edsCountDownLatch = new CountDownLatch(2); -// -// // support repeat consumer -// Consumer> edsFirstConsumer = (routeResult) -> { -// edsIsFirstConsumerInvoke.set(true); -// edsCountDownLatch.countDown(); -// }; -// Consumer> edsSecondConsumer = (routeResult) -> { -// edsIsSecondConsumerInvoke.set(true); -// edsCountDownLatch.countDown(); -// }; -// edsMap.computeIfAbsent(cluster, (key) -> { -// List>> consumers = new ArrayList<>(); -// consumers.add(edsFirstConsumer); -// consumers.add(edsSecondConsumer); -// return consumers; -// }); -// Assertions.assertFalse(edsIsFirstConsumerInvoke.get() || edsIsSecondConsumerInvoke.get()); -// edsProtocolMock.setConsumerObserveMap(edsMap); -// -// Map oldEdsResult = new HashMap<>(); -// Map newEdsResult = new HashMap<>(); -// -// oldEdsResult.put("dubbo-samples-provider2", new EndpointResult(endpoints)); -// newEdsResult.put("dubbo-samples-provider", new EndpointResult(endpoints)); -// newEdsResult.put("dubbo-samples-provider", new EndpointResult(endpoints)); -// -// try { -// edsProtocolMock.getResponseObserve().discoveryResponseListener(oldEdsResult, newEdsResult); -// edsCountDownLatch.await(); -// Assertions.assertTrue(edsIsFirstConsumerInvoke.get() && edsIsSecondConsumerInvoke.get()); -// } catch (Exception e) { -// Assertions.assertTrue(edsIsFirstConsumerInvoke.get() && edsIsSecondConsumerInvoke.get()); -// } finally { -// edsMocked.close(); -//// mockedStatic.close(); -// } -// } -// -// @Test -// void testResponseObserver() { -// //mock lds -// Map, List>>> ldsMap = new HashMap<>(); -// AtomicBoolean ldsIsFirstConsumerInvoke = new AtomicBoolean(false); -// -// // support repeat consumer -// Consumer> ldsFirstConsumer = (listenerResult) -> { -// ldsIsFirstConsumerInvoke.set(true); -// }; -// Set ldsResourceNames = new HashSet<>(); -// ldsResourceNames.add(ldsProtocolMock.emptyResourceName); -// -// ldsMap.computeIfAbsent(ldsResourceNames, (key) -> { -// List>> consumers = new ArrayList<>(); -// consumers.add(ldsFirstConsumer); -// return consumers; -// }); -// Assertions.assertFalse(ldsIsFirstConsumerInvoke.get()); -// ldsProtocolMock.setConsumerObserveMap(ldsMap); -// -// Map oldLdsResult = new HashMap<>(); -// Map newLdsResult = new HashMap<>(); -// -// oldLdsResult.put("emptyResourcesName1", new ListenerResult(routeConfigNames)); -// newLdsResult.put("emptyResourcesName1", new ListenerResult(routeConfigNames)); -// try { -// ldsProtocolMock.getResponseObserve().discoveryResponseListener(oldLdsResult, newLdsResult); -// Assertions.assertFalse(ldsIsFirstConsumerInvoke.get()); -// -// newLdsResult.put("emptyResourcesName", new ListenerResult(routeConfigNames)); -// ldsProtocolMock.getResponseObserve().discoveryResponseListener(oldLdsResult, newLdsResult); -// Assertions.assertTrue(ldsIsFirstConsumerInvoke.get()); -// -// } catch (Exception e) { -// Assertions.assertTrue(ldsIsFirstConsumerInvoke.get()); -// } -// -// -// // mock rds -// Map, List>>> rdsMap = new HashMap<>(); -// AtomicBoolean rdsIsFirstConsumerInvoke = new AtomicBoolean(false); -// -// // support repeat consumer -// Consumer> rdsFirstConsumer = (routeResult) -> { -// rdsIsFirstConsumerInvoke.set(true); -// }; -// rdsMap.computeIfAbsent(routeConfigNames, (key) -> { -// List>> consumers = new ArrayList<>(); -// consumers.add(rdsFirstConsumer); -// return consumers; -// }); -// rdsProtocolMock.setConsumerObserveMap(rdsMap); -// -// Map oldRdsResult = new HashMap<>(); -// Map newRdsResult = new HashMap<>(); -// -// oldRdsResult.put("15013", new RouteResult(domainMap)); -// newRdsResult.put("15013", new RouteResult(domainMap)); -// -// try { -// Assertions.assertFalse(rdsIsFirstConsumerInvoke.get()); -// rdsProtocolMock.getResponseObserve().discoveryResponseListener(oldRdsResult, newRdsResult); -// newRdsResult.put("15014", new RouteResult(domainMap)); -// rdsProtocolMock.getResponseObserve().discoveryResponseListener(oldRdsResult, newRdsResult); -// Assertions.assertTrue(rdsIsFirstConsumerInvoke.get()); -// -// Assertions.assertTrue(rdsIsFirstConsumerInvoke.get()); -// } catch (Exception e) { -// Assertions.assertTrue(rdsIsFirstConsumerInvoke.get()); -// } -// -// // mock eds -// Map, List>>> edsMap = new HashMap<>(); -// AtomicBoolean edsIsFirstConsumerInvoke = new AtomicBoolean(false); -// -// // support repeat consumer -// Consumer> edsFirstConsumer = (routeResult) -> { -// edsIsFirstConsumerInvoke.set(true); -// }; -// edsMap.computeIfAbsent(cluster, (key) -> { -// List>> consumers = new ArrayList<>(); -// consumers.add(edsFirstConsumer); -// return consumers; -// }); -// Assertions.assertFalse(edsIsFirstConsumerInvoke.get()); -// edsProtocolMock.setConsumerObserveMap(edsMap); -// -// Map oldEdsResult = new HashMap<>(); -// Map newEdsResult = new HashMap<>(); -// -// oldEdsResult.put("dubbo-samples-provider2", new EndpointResult(endpoints)); -// newEdsResult.put("dubbo-samples-provider2", new EndpointResult(endpoints)); -// -// try { -// edsProtocolMock.getResponseObserve().discoveryResponseListener(oldEdsResult, newEdsResult); -// Assertions.assertFalse(edsIsFirstConsumerInvoke.get()); -// newEdsResult.put("dubbo-samples-provider", new EndpointResult(endpoints)); -// edsProtocolMock.getResponseObserve().discoveryResponseListener(oldEdsResult, newEdsResult); -// Assertions.assertTrue(edsIsFirstConsumerInvoke.get()); -// } catch (Exception e) { -// Assertions.assertTrue(edsIsFirstConsumerInvoke.get()); -// } -// } -// -// private void triggerConsumerObserveMapListener(Map resultMap, AbstractProtocol protocol) { -// CompletableFuture.runAsync(() -> { -// while (true) { -// Map, List>>> map = protocol.getConsumerObserveMap(); -// if (map != null && map.size() > 1) { -// map.forEach((k, v) -> v.forEach(o -> o.accept(resultMap))); -// break; -// } -// try { -// Thread.sleep(2000); -// } catch (InterruptedException e) { -// break; -// } -// } -// }); -// }; -//} diff --git a/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/protocol/impl/EdsProtocolMock.java b/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/protocol/impl/EdsProtocolMock.java index ed080fe768..6a9d3e4619 100644 --- a/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/protocol/impl/EdsProtocolMock.java +++ b/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/protocol/impl/EdsProtocolMock.java @@ -14,20 +14,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.registry.xds.util.protocol.impl; +import org.apache.dubbo.registry.xds.util.AdsObserver; +import org.apache.dubbo.registry.xds.util.protocol.message.EndpointResult; + import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Consumer; -import org.apache.dubbo.registry.xds.util.AdsObserver; -import org.apache.dubbo.registry.xds.util.protocol.message.EndpointResult; - import io.envoyproxy.envoy.config.core.v3.Node; -public class EdsProtocolMock extends EdsProtocol{ +public class EdsProtocolMock extends EdsProtocol { public EdsProtocolMock(AdsObserver adsObserver, Node node, int checkInterval) { super(adsObserver, node, checkInterval); @@ -41,12 +40,12 @@ public class EdsProtocolMock extends EdsProtocol{ this.resourcesMap = resourcesMap; } - public void setConsumerObserveMap(Map, List>>> consumerObserveMap) { + public void setConsumerObserveMap( + Map, List>>> consumerObserveMap) { this.consumerObserveMap = consumerObserveMap; } public void setObserveResourcesName(Set observeResourcesName) { this.observeResourcesName = observeResourcesName; } - } diff --git a/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/protocol/impl/LdsProtocolMock.java b/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/protocol/impl/LdsProtocolMock.java index 3c37ec8d25..bdeb636698 100644 --- a/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/protocol/impl/LdsProtocolMock.java +++ b/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/protocol/impl/LdsProtocolMock.java @@ -14,21 +14,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.registry.xds.util.protocol.impl; +import org.apache.dubbo.registry.xds.util.AdsObserver; +import org.apache.dubbo.registry.xds.util.protocol.message.ListenerResult; + import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Consumer; -import org.apache.dubbo.registry.xds.util.AdsObserver; -import org.apache.dubbo.registry.xds.util.protocol.message.ListenerResult; - import io.envoyproxy.envoy.config.core.v3.Node; import io.envoyproxy.envoy.service.discovery.v3.DiscoveryRequest; -public class LdsProtocolMock extends LdsProtocol{ +public class LdsProtocolMock extends LdsProtocol { public LdsProtocolMock(AdsObserver adsObserver, Node node, int checkInterval) { super(adsObserver, node, checkInterval); @@ -44,10 +43,10 @@ public class LdsProtocolMock extends LdsProtocol{ protected DiscoveryRequest buildDiscoveryRequest(Set resourceNames) { return DiscoveryRequest.newBuilder() - .setNode(node) - .setTypeUrl(getTypeUrl()) - .addAllResourceNames(resourceNames) - .build(); + .setNode(node) + .setTypeUrl(getTypeUrl()) + .addAllResourceNames(resourceNames) + .build(); } public Set getObserveResourcesName() { @@ -62,7 +61,8 @@ public class LdsProtocolMock extends LdsProtocol{ return consumerObserveMap; } - public void setConsumerObserveMap(Map, List>>> consumerObserveMap) { + public void setConsumerObserveMap( + Map, List>>> consumerObserveMap) { this.consumerObserveMap = consumerObserveMap; } } diff --git a/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/protocol/impl/RdsProtocolMock.java b/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/protocol/impl/RdsProtocolMock.java index 01581950d0..7d9aa78d3a 100644 --- a/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/protocol/impl/RdsProtocolMock.java +++ b/dubbo-xds/src/test/java/org/apache/dubbo/registry/xds/util/protocol/impl/RdsProtocolMock.java @@ -14,20 +14,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.dubbo.registry.xds.util.protocol.impl; +import org.apache.dubbo.registry.xds.util.AdsObserver; +import org.apache.dubbo.registry.xds.util.protocol.message.RouteResult; + import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Consumer; -import org.apache.dubbo.registry.xds.util.AdsObserver; -import org.apache.dubbo.registry.xds.util.protocol.message.RouteResult; - import io.envoyproxy.envoy.config.core.v3.Node; -public class RdsProtocolMock extends RdsProtocol{ +public class RdsProtocolMock extends RdsProtocol { public RdsProtocolMock(AdsObserver adsObserver, Node node, int checkInterval) { super(adsObserver, node, checkInterval); @@ -44,12 +43,12 @@ public class RdsProtocolMock extends RdsProtocol{ public Set getObserveResourcesName() { return observeResourcesName; } - + public void setConsumerObserveMap(Map, List>>> consumerObserveMap) { this.consumerObserveMap = consumerObserveMap; } + public void setObserveResourcesName(Set observeResourcesName) { this.observeResourcesName = observeResourcesName; } - } diff --git a/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/EdsEndpointManagerTest.java b/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/EdsEndpointManagerTest.java index 7da4950c55..1a1f2f8ceb 100644 --- a/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/EdsEndpointManagerTest.java +++ b/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/EdsEndpointManagerTest.java @@ -18,21 +18,20 @@ package org.apache.dubbo.rpc.cluster.router.xds; import org.apache.dubbo.registry.xds.util.protocol.message.Endpoint; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; public class EdsEndpointManagerTest { - @BeforeEach public void before() { EdsEndpointManager.getEdsListeners().clear(); @@ -48,25 +47,20 @@ public class EdsEndpointManagerTest { for (int i = 0; i < subscribeNum; i++) { manager.subscribeEds(cluster, new EdsEndpointListener() { @Override - public void onEndPointChange(String cluster, Set endpoints) { - - } + public void onEndPointChange(String cluster, Set endpoints) {} }); } assertNotNull(EdsEndpointManager.getEdsListeners().get(cluster)); assertEquals(EdsEndpointManager.getEndpointListeners().get(cluster).size(), subscribeNum); } - @Test public void unsubscribeRdsTest() { EdsEndpointManager manager = new EdsEndpointManager(); String domain = "testApp"; EdsEndpointListener listener = new EdsEndpointListener() { @Override - public void onEndPointChange(String cluster, Set endpoints) { - - } + public void onEndPointChange(String cluster, Set endpoints) {} }; manager.subscribeEds(domain, listener); assertNotNull(EdsEndpointManager.getEdsListeners().get(domain)); @@ -77,7 +71,6 @@ public class EdsEndpointManagerTest { assertNull(EdsEndpointManager.getEndpointListeners().get(domain)); } - @Test public void notifyRuleChangeTest() { @@ -112,5 +105,4 @@ public class EdsEndpointManagerTest { manager.notifyEndpointChange(domain, new HashSet<>()); assertEquals(cacheData.get(domain).size(), 0); } - } diff --git a/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/RdsRouteRuleManagerTest.java b/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/RdsRouteRuleManagerTest.java index 44e2ad16e5..eaef9cb320 100644 --- a/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/RdsRouteRuleManagerTest.java +++ b/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/RdsRouteRuleManagerTest.java @@ -20,14 +20,14 @@ import org.apache.dubbo.rpc.cluster.router.xds.rule.HTTPRouteDestination; import org.apache.dubbo.rpc.cluster.router.xds.rule.HttpRequestMatch; import org.apache.dubbo.rpc.cluster.router.xds.rule.XdsRouteRule; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; @@ -41,7 +41,6 @@ public class RdsRouteRuleManagerTest { RdsRouteRuleManager.getRdsListeners().clear(); } - @Test public void subscribeRdsTest() { RdsRouteRuleManager manager = new RdsRouteRuleManager(); @@ -50,35 +49,26 @@ public class RdsRouteRuleManagerTest { for (int i = 0; i < subscribeNum; i++) { manager.subscribeRds(domain, new XdsRouteRuleListener() { @Override - public void onRuleChange(String appName, List xdsRouteRules) { - - } + public void onRuleChange(String appName, List xdsRouteRules) {} @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} }); } assertNotNull(RdsRouteRuleManager.getRdsListeners().get(domain)); assertEquals(RdsRouteRuleManager.getRuleListeners().get(domain).size(), subscribeNum); } - @Test public void unsubscribeRdsTest() { RdsRouteRuleManager manager = new RdsRouteRuleManager(); String domain = "testApp"; XdsRouteRuleListener listener = new XdsRouteRuleListener() { @Override - public void onRuleChange(String appName, List xdsRouteRules) { - - } + public void onRuleChange(String appName, List xdsRouteRules) {} @Override - public void clearRule(String appName) { - - } + public void clearRule(String appName) {} }; manager.subscribeRds(domain, listener); assertNotNull(RdsRouteRuleManager.getRdsListeners().get(domain)); @@ -89,15 +79,13 @@ public class RdsRouteRuleManagerTest { assertNull(RdsRouteRuleManager.getRuleListeners().get(domain)); } - @Test public void notifyRuleChangeTest() { Map> cacheData = new HashMap<>(); String domain = "testApp"; List xdsRouteRules = new ArrayList<>(); - XdsRouteRule rule = new XdsRouteRule(new HttpRequestMatch(null, null), - new HTTPRouteDestination()); + XdsRouteRule rule = new XdsRouteRule(new HttpRequestMatch(null, null), new HTTPRouteDestination()); xdsRouteRules.add(rule); XdsRouteRuleListener listener = new XdsRouteRuleListener() { @@ -135,5 +123,4 @@ public class RdsRouteRuleManagerTest { manager.notifyRuleChange(domain, new ArrayList<>()); assertNull(cacheData.get(domain)); } - } diff --git a/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/RdsVirtualHostListenerTest.java b/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/RdsVirtualHostListenerTest.java index 2899e6f3b8..d7985366a6 100644 --- a/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/RdsVirtualHostListenerTest.java +++ b/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/RdsVirtualHostListenerTest.java @@ -19,6 +19,10 @@ package org.apache.dubbo.rpc.cluster.router.xds; import org.apache.dubbo.rpc.cluster.router.xds.rule.ClusterWeight; import org.apache.dubbo.rpc.cluster.router.xds.rule.XdsRouteRule; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import com.google.protobuf.BoolValue; import com.google.protobuf.UInt32Value; import io.envoyproxy.envoy.config.route.v3.HeaderMatcher; @@ -32,10 +36,6 @@ import io.envoyproxy.envoy.type.v3.Int64Range; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -68,17 +68,23 @@ public class RdsVirtualHostListenerTest { manager.subscribeRds(domain, listener); } - @Test public void parsePathPathMatcherTest() { String path = "/test/name"; VirtualHost virtualHost = VirtualHost.newBuilder() - .addDomains(domain) - .addRoutes(Route.newBuilder().setName("route-test") - .setMatch(RouteMatch.newBuilder().setPath(path).setCaseSensitive(BoolValue.newBuilder().setValue(true).build()).build()) - .setRoute(RouteAction.newBuilder().setCluster("cluster-test").build()) - .build() - ).build(); + .addDomains(domain) + .addRoutes(Route.newBuilder() + .setName("route-test") + .setMatch(RouteMatch.newBuilder() + .setPath(path) + .setCaseSensitive( + BoolValue.newBuilder().setValue(true).build()) + .build()) + .setRoute(RouteAction.newBuilder() + .setCluster("cluster-test") + .build()) + .build()) + .build(); rdsVirtualHostListener.parseVirtualHost(virtualHost); List rules = dataCache.get(domain); assertNotNull(rules); @@ -90,13 +96,15 @@ public class RdsVirtualHostListenerTest { public void parsePrefixPathMatcherTest() { String prefix = "/test"; VirtualHost virtualHost = VirtualHost.newBuilder() - .addDomains(domain) - .addRoutes(Route.newBuilder().setName("route-test") - .setMatch(RouteMatch.newBuilder().setPrefix(prefix).build()) - .setRoute(RouteAction.newBuilder().setCluster("cluster-test").build()) - .build() - ) - .build(); + .addDomains(domain) + .addRoutes(Route.newBuilder() + .setName("route-test") + .setMatch(RouteMatch.newBuilder().setPrefix(prefix).build()) + .setRoute(RouteAction.newBuilder() + .setCluster("cluster-test") + .build()) + .build()) + .build(); rdsVirtualHostListener.parseVirtualHost(virtualHost); List rules = dataCache.get(domain); assertNotNull(rules); @@ -107,15 +115,19 @@ public class RdsVirtualHostListenerTest { public void parseRegexPathMatcherTest() { String regex = "/test/.*"; VirtualHost virtualHost = VirtualHost.newBuilder() - .addDomains(domain) - .addRoutes(Route.newBuilder().setName("route-test") - .setMatch(RouteMatch.newBuilder().setSafeRegex( - RegexMatcher.newBuilder().setRegex(regex).build() - ).build()) - .setRoute(RouteAction.newBuilder().setCluster("cluster-test").build()) - .build() - ) - .build(); + .addDomains(domain) + .addRoutes(Route.newBuilder() + .setName("route-test") + .setMatch(RouteMatch.newBuilder() + .setSafeRegex(RegexMatcher.newBuilder() + .setRegex(regex) + .build()) + .build()) + .setRoute(RouteAction.newBuilder() + .setCluster("cluster-test") + .build()) + .build()) + .build(); rdsVirtualHostListener.parseVirtualHost(virtualHost); List rules = dataCache.get(domain); assertNotNull(rules); @@ -125,44 +137,51 @@ public class RdsVirtualHostListenerTest { @Test public void parseHeadMatcherTest() { VirtualHost virtualHost = VirtualHost.newBuilder() - .addDomains(domain) - .addRoutes(Route.newBuilder().setName("route-test") - .setMatch(RouteMatch.newBuilder() - .addHeaders(HeaderMatcher.newBuilder() - .setName("head-exactValue") - .setExactMatch("exactValue") - .setInvertMatch(true) + .addDomains(domain) + .addRoutes(Route.newBuilder() + .setName("route-test") + .setMatch(RouteMatch.newBuilder() + .addHeaders(HeaderMatcher.newBuilder() + .setName("head-exactValue") + .setExactMatch("exactValue") + .setInvertMatch(true) + .build()) + .addHeaders(HeaderMatcher.newBuilder() + .setName("head-regex") + .setSafeRegexMatch(RegexMatcher.newBuilder() + .setRegex("regex") + .build()) + .build()) + .addHeaders(HeaderMatcher.newBuilder() + .setName("head-range") + .setRangeMatch(Int64Range.newBuilder() + .setStart(1) + .setEnd(100) + .build()) + .build()) + .addHeaders(HeaderMatcher.newBuilder() + .setName("head-present") + .setPresentMatch(true) + .build()) + .addHeaders(HeaderMatcher.newBuilder() + .setName("head-prefix") + .setPrefixMatch("prefix") + .build()) + .addHeaders(HeaderMatcher.newBuilder() + .setName("head-suffix") + .setSuffixMatch("suffix") + .build()) + .build()) + .setRoute(RouteAction.newBuilder() + .setCluster("cluster-test") + .build()) .build()) - .addHeaders(HeaderMatcher.newBuilder() - .setName("head-regex") - .setSafeRegexMatch(RegexMatcher.newBuilder().setRegex("regex").build()) - .build()) - .addHeaders(HeaderMatcher.newBuilder() - .setName("head-range") - .setRangeMatch(Int64Range.newBuilder().setStart(1).setEnd(100).build()) - .build()) - .addHeaders(HeaderMatcher.newBuilder() - .setName("head-present") - .setPresentMatch(true) - .build()) - .addHeaders(HeaderMatcher.newBuilder() - .setName("head-prefix") - .setPrefixMatch("prefix") - .build()) - .addHeaders(HeaderMatcher.newBuilder() - .setName("head-suffix") - .setSuffixMatch("suffix") - .build()) - .build() - ) - .setRoute(RouteAction.newBuilder().setCluster("cluster-test").build()) - .build() - ) - .build(); + .build(); rdsVirtualHostListener.parseVirtualHost(virtualHost); List rules = dataCache.get(domain); assertNotNull(rules); - List headerMatcherList = rules.get(0).getMatch().getHeaderMatcherList(); + List headerMatcherList = + rules.get(0).getMatch().getHeaderMatcherList(); for (org.apache.dubbo.rpc.cluster.router.xds.rule.HeaderMatcher matcher : headerMatcherList) { if (matcher.getName().equals("head-exactValue")) { assertEquals(matcher.getExactValue(), "exactValue"); @@ -185,13 +204,13 @@ public class RdsVirtualHostListenerTest { public void parseRouteClusterTest() { String cluster = "cluster-test"; VirtualHost virtualHost = VirtualHost.newBuilder() - .addDomains(domain) - .addRoutes(Route.newBuilder().setName("route-test") - .setMatch(RouteMatch.newBuilder().setPrefix("/test").build()) - .setRoute(RouteAction.newBuilder().setCluster(cluster).build()) - .build() - ) - .build(); + .addDomains(domain) + .addRoutes(Route.newBuilder() + .setName("route-test") + .setMatch(RouteMatch.newBuilder().setPrefix("/test").build()) + .setRoute(RouteAction.newBuilder().setCluster(cluster).build()) + .build()) + .build(); rdsVirtualHostListener.parseVirtualHost(virtualHost); List rules = dataCache.get(domain); assertNotNull(rules); @@ -201,19 +220,28 @@ public class RdsVirtualHostListenerTest { @Test public void parseRouteWeightClusterTest() { VirtualHost virtualHost = VirtualHost.newBuilder() - .addDomains(domain) - .addRoutes(Route.newBuilder().setName("route-test") - .setMatch(RouteMatch.newBuilder().setPrefix("/test").build()) - .setRoute(RouteAction.newBuilder().setWeightedClusters( - WeightedCluster.newBuilder() - .addClusters(WeightedCluster.ClusterWeight.newBuilder().setName("cluster-test1") - .setWeight(UInt32Value.newBuilder().setValue(40).build()).build()) - .addClusters(WeightedCluster.ClusterWeight.newBuilder().setName("cluster-test2") - .setWeight(UInt32Value.newBuilder().setValue(60).build()).build()) - .build() - ).build()) - .build()) - .build(); + .addDomains(domain) + .addRoutes(Route.newBuilder() + .setName("route-test") + .setMatch(RouteMatch.newBuilder().setPrefix("/test").build()) + .setRoute(RouteAction.newBuilder() + .setWeightedClusters(WeightedCluster.newBuilder() + .addClusters(WeightedCluster.ClusterWeight.newBuilder() + .setName("cluster-test1") + .setWeight(UInt32Value.newBuilder() + .setValue(40) + .build()) + .build()) + .addClusters(WeightedCluster.ClusterWeight.newBuilder() + .setName("cluster-test2") + .setWeight(UInt32Value.newBuilder() + .setValue(60) + .build()) + .build()) + .build()) + .build()) + .build()) + .build(); rdsVirtualHostListener.parseVirtualHost(virtualHost); List rules = dataCache.get(domain); assertNotNull(rules); @@ -227,5 +255,4 @@ public class RdsVirtualHostListenerTest { } } } - } diff --git a/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/XdsRouteTest.java b/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/XdsRouteTest.java index 6d011bcf3a..7630939391 100644 --- a/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/XdsRouteTest.java +++ b/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/XdsRouteTest.java @@ -16,31 +16,29 @@ */ package org.apache.dubbo.rpc.cluster.router.xds; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.Holder; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.registry.xds.util.protocol.message.Endpoint; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; -//import org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider; import org.apache.dubbo.rpc.cluster.router.state.BitList; import org.apache.dubbo.rpc.cluster.router.xds.rule.DestinationSubset; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; import com.google.protobuf.UInt32Value; - import io.envoyproxy.envoy.config.route.v3.HeaderMatcher; import io.envoyproxy.envoy.config.route.v3.Route; import io.envoyproxy.envoy.config.route.v3.RouteAction; import io.envoyproxy.envoy.config.route.v3.RouteMatch; import io.envoyproxy.envoy.config.route.v3.VirtualHost; import io.envoyproxy.envoy.config.route.v3.WeightedCluster; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -53,27 +51,29 @@ public class XdsRouteTest { private EdsEndpointManager edsEndpointManager; private RdsRouteRuleManager rdsRouteRuleManager; -// private Set tracingContextProviders; + // private Set tracingContextProviders; private URL url; @BeforeEach public void setup() { edsEndpointManager = Mockito.spy(EdsEndpointManager.class); rdsRouteRuleManager = Mockito.spy(RdsRouteRuleManager.class); -// tracingContextProviders = new HashSet<>(); + // tracingContextProviders = new HashSet<>(); url = URL.valueOf("test://localhost/DemoInterface"); } private Invoker createInvoker(String app) { - URL url = URL.valueOf("dubbo://localhost/DemoInterface?" + (StringUtils.isEmpty(app) ? "" : "remote.application=" + app)); + URL url = URL.valueOf( + "dubbo://localhost/DemoInterface?" + (StringUtils.isEmpty(app) ? "" : "remote.application=" + app)); Invoker invoker = Mockito.mock(Invoker.class); when(invoker.getUrl()).thenReturn(url); return invoker; } private Invoker createInvoker(String app, String address) { - URL url = URL.valueOf("dubbo://" + address + "/DemoInterface?" + (StringUtils.isEmpty(app) ? "" : "remote.application=" + app)); + URL url = URL.valueOf("dubbo://" + address + "/DemoInterface?" + + (StringUtils.isEmpty(app) ? "" : "remote.application=" + app)); Invoker invoker = Mockito.mock(Invoker.class); when(invoker.getUrl()).thenReturn(url); return invoker; @@ -115,47 +115,51 @@ public class XdsRouteTest { xdsRouter.notify(invokers); String path = "/DemoInterface/call"; VirtualHost virtualHost = VirtualHost.newBuilder() - .addDomains(appName) - .addRoutes(Route.newBuilder().setName("route-test") - .setMatch(RouteMatch.newBuilder().setPath(path).build()) - .setRoute(RouteAction.newBuilder().setCluster(cluster1).build()) - .build() - ).build(); + .addDomains(appName) + .addRoutes(Route.newBuilder() + .setName("route-test") + .setMatch(RouteMatch.newBuilder().setPath(path).build()) + .setRoute(RouteAction.newBuilder().setCluster(cluster1).build()) + .build()) + .build(); RdsVirtualHostListener hostListener = new RdsVirtualHostListener(appName, rdsRouteRuleManager); hostListener.parseVirtualHost(virtualHost); assertEquals(xdsRouter.getXdsRouteRuleMap().get(appName).size(), 1); verify(edsEndpointManager, times(1)).subscribeEds(cluster1, xdsRouter); VirtualHost virtualHost2 = VirtualHost.newBuilder() - .addDomains(appName) - .addRoutes(Route.newBuilder().setName("route-test") - .setMatch(RouteMatch.newBuilder().setPath(path).build()) - .setRoute(RouteAction.newBuilder().setCluster("cluster-test2").build()) - .build() - ).build(); + .addDomains(appName) + .addRoutes(Route.newBuilder() + .setName("route-test") + .setMatch(RouteMatch.newBuilder().setPath(path).build()) + .setRoute(RouteAction.newBuilder() + .setCluster("cluster-test2") + .build()) + .build()) + .build(); hostListener.parseVirtualHost(virtualHost2); assertEquals(xdsRouter.getXdsRouteRuleMap().get(appName).size(), 1); verify(edsEndpointManager, times(1)).subscribeEds(cluster2, xdsRouter); verify(edsEndpointManager, times(1)).unSubscribeEds(cluster1, xdsRouter); } - @Test public void testEndpointChange() { XdsRouter xdsRouter = new XdsRouter<>(url, rdsRouteRuleManager, edsEndpointManager, true); String appName = "app1"; String cluster1 = "cluster-test1"; - BitList> invokers = new BitList<>(Arrays.asList(createInvoker(appName, "1.1.1.1:20880") - , createInvoker(appName, "2.2.2.2:20880"))); + BitList> invokers = new BitList<>( + Arrays.asList(createInvoker(appName, "1.1.1.1:20880"), createInvoker(appName, "2.2.2.2:20880"))); xdsRouter.notify(invokers); String path = "/DemoInterface/call"; VirtualHost virtualHost = VirtualHost.newBuilder() - .addDomains(appName) - .addRoutes(Route.newBuilder().setName("route-test") - .setMatch(RouteMatch.newBuilder().setPath(path).build()) - .setRoute(RouteAction.newBuilder().setCluster(cluster1).build()) - .build() - ).build(); + .addDomains(appName) + .addRoutes(Route.newBuilder() + .setName("route-test") + .setMatch(RouteMatch.newBuilder().setPath(path).build()) + .setRoute(RouteAction.newBuilder().setCluster(cluster1).build()) + .build()) + .build(); RdsVirtualHostListener hostListener = new RdsVirtualHostListener(appName, rdsRouteRuleManager); hostListener.parseVirtualHost(virtualHost); assertEquals(xdsRouter.getXdsRouteRuleMap().get(appName).size(), 1); @@ -172,7 +176,8 @@ public class XdsRouteTest { endpoints.add(endpoint2); edsEndpointManager.notifyEndpointChange(cluster1, endpoints); - DestinationSubset objectDestinationSubset = xdsRouter.getDestinationSubsetMap().get(cluster1); + DestinationSubset objectDestinationSubset = + xdsRouter.getDestinationSubsetMap().get(cluster1); assertEquals(invokers, objectDestinationSubset.getInvokers()); } @@ -180,8 +185,8 @@ public class XdsRouteTest { public void testRouteNotMatch() { XdsRouter xdsRouter = new XdsRouter<>(url, rdsRouteRuleManager, edsEndpointManager, true); String appName = "app1"; - BitList> invokers = new BitList<>(Arrays.asList(createInvoker(appName, "1.1.1.1:20880") - , createInvoker(appName, "2.2.2.2:20880"))); + BitList> invokers = new BitList<>( + Arrays.asList(createInvoker(appName, "1.1.1.1:20880"), createInvoker(appName, "2.2.2.2:20880"))); assertEquals(invokers, xdsRouter.route(invokers.clone(), null, null, false, null)); Holder message = new Holder<>(); xdsRouter.doRoute(invokers.clone(), null, null, true, null, message); @@ -194,17 +199,18 @@ public class XdsRouteTest { String appName = "app1"; String cluster1 = "cluster-test1"; Invoker invoker1 = createInvoker(appName, "1.1.1.1:20880"); - BitList> invokers = new BitList<>(Arrays.asList(invoker1 - , createInvoker(appName, "2.2.2.2:20880"))); + BitList> invokers = + new BitList<>(Arrays.asList(invoker1, createInvoker(appName, "2.2.2.2:20880"))); xdsRouter.notify(invokers); String path = "/DemoInterface/call"; VirtualHost virtualHost = VirtualHost.newBuilder() - .addDomains(appName) - .addRoutes(Route.newBuilder().setName("route-test") - .setMatch(RouteMatch.newBuilder().setPath(path).build()) - .setRoute(RouteAction.newBuilder().setCluster(cluster1).build()) - .build() - ).build(); + .addDomains(appName) + .addRoutes(Route.newBuilder() + .setName("route-test") + .setMatch(RouteMatch.newBuilder().setPath(path).build()) + .setRoute(RouteAction.newBuilder().setCluster(cluster1).build()) + .build()) + .build(); RdsVirtualHostListener hostListener = new RdsVirtualHostListener(appName, rdsRouteRuleManager); hostListener.parseVirtualHost(virtualHost); Invocation invocation = Mockito.mock(Invocation.class); @@ -224,32 +230,30 @@ public class XdsRouteTest { BitList> routes = xdsRouter.route(invokers.clone(), null, invocation, false, null); assertEquals(1, routes.size()); assertEquals(invoker1, routes.get(0)); - } - @Test public void testRouteHeadMatch() { XdsRouter xdsRouter = new XdsRouter<>(url, rdsRouteRuleManager, edsEndpointManager, true); String appName = "app1"; String cluster1 = "cluster-test1"; Invoker invoker1 = createInvoker(appName, "1.1.1.1:20880"); - BitList> invokers = new BitList<>(Arrays.asList(invoker1 - , createInvoker(appName, "2.2.2.2:20880"))); + BitList> invokers = + new BitList<>(Arrays.asList(invoker1, createInvoker(appName, "2.2.2.2:20880"))); xdsRouter.notify(invokers); VirtualHost virtualHost = VirtualHost.newBuilder() - .addDomains(appName) - .addRoutes(Route.newBuilder().setName("route-test") - .setMatch(RouteMatch.newBuilder().addHeaders( - HeaderMatcher.newBuilder() - .setName("userId") - .setExactMatch("123") - .build() - ).build() - ) - .setRoute(RouteAction.newBuilder().setCluster(cluster1).build()) - .build() - ).build(); + .addDomains(appName) + .addRoutes(Route.newBuilder() + .setName("route-test") + .setMatch(RouteMatch.newBuilder() + .addHeaders(HeaderMatcher.newBuilder() + .setName("userId") + .setExactMatch("123") + .build()) + .build()) + .setRoute(RouteAction.newBuilder().setCluster(cluster1).build()) + .build()) + .build(); RdsVirtualHostListener hostListener = new RdsVirtualHostListener(appName, rdsRouteRuleManager); hostListener.parseVirtualHost(virtualHost); Invocation invocation = Mockito.mock(Invocation.class); @@ -265,7 +269,6 @@ public class XdsRouteTest { assertEquals(invoker1, routes.get(0)); } - @Test public void testRouteWeightCluster() { XdsRouter xdsRouter = new XdsRouter<>(url, rdsRouteRuleManager, edsEndpointManager, true); @@ -273,28 +276,37 @@ public class XdsRouteTest { String cluster1 = "cluster-test1"; String cluster2 = "cluster-test2"; Invoker invoker1 = createInvoker(appName, "1.1.1.1:20880"); - BitList> invokers = new BitList<>(Arrays.asList(invoker1 - , createInvoker(appName, "2.2.2.2:20880"))); + BitList> invokers = + new BitList<>(Arrays.asList(invoker1, createInvoker(appName, "2.2.2.2:20880"))); xdsRouter.notify(invokers); VirtualHost virtualHost = VirtualHost.newBuilder() - .addDomains(appName) - .addRoutes(Route.newBuilder().setName("route-test") - .setMatch(RouteMatch.newBuilder().addHeaders( - HeaderMatcher.newBuilder() - .setName("userId") - .setExactMatch("123") - .build() - ).build() - ) - .setRoute(RouteAction.newBuilder().setWeightedClusters( - WeightedCluster.newBuilder() - .addClusters(WeightedCluster.ClusterWeight.newBuilder().setName(cluster1) - .setWeight(UInt32Value.newBuilder().setValue(100).build()).build()) - .addClusters(WeightedCluster.ClusterWeight.newBuilder().setName(cluster2) - .setWeight(UInt32Value.newBuilder().setValue(0).build()).build()) - .build()) - .build() - ).build()).build(); + .addDomains(appName) + .addRoutes(Route.newBuilder() + .setName("route-test") + .setMatch(RouteMatch.newBuilder() + .addHeaders(HeaderMatcher.newBuilder() + .setName("userId") + .setExactMatch("123") + .build()) + .build()) + .setRoute(RouteAction.newBuilder() + .setWeightedClusters(WeightedCluster.newBuilder() + .addClusters(WeightedCluster.ClusterWeight.newBuilder() + .setName(cluster1) + .setWeight(UInt32Value.newBuilder() + .setValue(100) + .build()) + .build()) + .addClusters(WeightedCluster.ClusterWeight.newBuilder() + .setName(cluster2) + .setWeight(UInt32Value.newBuilder() + .setValue(0) + .build()) + .build()) + .build()) + .build()) + .build()) + .build(); RdsVirtualHostListener hostListener = new RdsVirtualHostListener(appName, rdsRouteRuleManager); hostListener.parseVirtualHost(virtualHost); Invocation invocation = Mockito.mock(Invocation.class); @@ -328,18 +340,18 @@ public class XdsRouteTest { String cluster1 = "cluster-test1"; Invoker invoker1 = createInvoker(appName2, "1.1.1.1:20880"); Invoker invoker2 = createInvoker(appName1, "2.2.2.2:20880"); - BitList> invokers = new BitList<>(Arrays.asList(invoker1 - , invoker2)); + BitList> invokers = new BitList<>(Arrays.asList(invoker1, invoker2)); xdsRouter.notify(invokers); assertEquals(xdsRouter.getSubscribeApplications().size(), 2); String path = "/DemoInterface/call"; VirtualHost virtualHost = VirtualHost.newBuilder() - .addDomains(appName2) - .addRoutes(Route.newBuilder().setName("route-test") - .setMatch(RouteMatch.newBuilder().setPath(path).build()) - .setRoute(RouteAction.newBuilder().setCluster(cluster1).build()) - .build() - ).build(); + .addDomains(appName2) + .addRoutes(Route.newBuilder() + .setName("route-test") + .setMatch(RouteMatch.newBuilder().setPath(path).build()) + .setRoute(RouteAction.newBuilder().setCluster(cluster1).build()) + .build()) + .build(); RdsVirtualHostListener hostListener = new RdsVirtualHostListener(appName2, rdsRouteRuleManager); hostListener.parseVirtualHost(virtualHost); Invocation invocation = Mockito.mock(Invocation.class); @@ -360,5 +372,4 @@ public class XdsRouteTest { assertEquals(1, routes.size()); assertEquals(invoker1, routes.get(0)); } - } diff --git a/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/rule/HeaderMatcherTest.java b/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/rule/HeaderMatcherTest.java index dc8e240482..597c06e0de 100644 --- a/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/rule/HeaderMatcherTest.java +++ b/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/rule/HeaderMatcherTest.java @@ -32,7 +32,6 @@ public class HeaderMatcherTest { assertTrue(headMatcher.match(value)); } - @Test public void regexMatcherTest() { HeaderMatcher headMatcher = new HeaderMatcher(); @@ -52,7 +51,6 @@ public class HeaderMatcherTest { assertTrue(headMatcher.match("300")); } - @Test public void presentMatcherTest() { HeaderMatcher headMatcher = new HeaderMatcher(); @@ -71,7 +69,6 @@ public class HeaderMatcherTest { assertTrue(headMatcher.match("testValue")); } - @Test public void suffixMatcherTest() { HeaderMatcher headMatcher = new HeaderMatcher(); diff --git a/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/rule/PathMatcherTest.java b/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/rule/PathMatcherTest.java index 51bb920a6c..ce8e82b50b 100644 --- a/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/rule/PathMatcherTest.java +++ b/dubbo-xds/src/test/java/org/apache/dubbo/rpc/cluster/router/xds/rule/PathMatcherTest.java @@ -23,7 +23,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; public class PathMatcherTest { - @Test public void pathMatcherTest() { PathMatcher pathMatcher = new PathMatcher(); @@ -33,7 +32,6 @@ public class PathMatcherTest { assertTrue(pathMatcher.isMatch(path.toUpperCase())); pathMatcher.setCaseSensitive(true); assertFalse(pathMatcher.isMatch(path.toUpperCase())); - } @Test @@ -56,5 +54,4 @@ public class PathMatcherTest { pathMatcher.setRegex(regex); assertTrue(pathMatcher.isMatch(path)); } - } diff --git a/pom.xml b/pom.xml index 1ef9a2a6c4..e8731bb9e2 100644 --- a/pom.xml +++ b/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 + 4.0.0 - - org.apache - apache - 23 - + + org.apache + apache + 23 + - org.apache.dubbo - dubbo-parent - ${revision} - pom + org.apache.dubbo + dubbo-parent + ${revision} + pom - ${project.artifactId} - The parent project of dubbo + ${project.artifactId} + The parent project of dubbo + https://github.com/apache/dubbo + 2011 + + + The Apache Software Foundation + http://www.apache.org/ + + + + Apache License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0 + repo + + + + + dubbo.io + The Dubbo Project Contributors + dev-subscribe@dubbo.apache.org + http://dubbo.apache.org/ + + + + + Development List + dev-subscribe@dubbo.apache.org + dev-unsubscribe@dubbo.apache.org + dev@dubbo.apache.org + + + Commits List + commits-subscribe@dubbo.apache.org + commits-unsubscribe@dubbo.apache.org + commits@dubbo.apache.org + + + Issues List + issues-subscribe@dubbo.apache.org + issues-unsubscribe@dubbo.apache.org + issues@dubbo.apache.org + + + + + dubbo-common + dubbo-container + dubbo-remoting + dubbo-rpc + dubbo-cluster + dubbo-registry + dubbo-monitor + dubbo-config + dubbo-demo + dubbo-plugin + dubbo-serialization + dubbo-compatible + dubbo-dependencies-bom + dubbo-distribution + dubbo-configcenter + dubbo-dependencies + dubbo-metadata + dubbo-metrics + dubbo-spring-boot + dubbo-test + dubbo-kubernetes + dubbo-xds + dubbo-maven-plugin + + + + scm:git:https://github.com/apache/dubbo.git + scm:git:https://github.com/apache/dubbo.git + HEAD https://github.com/apache/dubbo - 2011 - - - Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0 - repo - - + - - https://github.com/apache/dubbo - scm:git:https://github.com/apache/dubbo.git - scm:git:https://github.com/apache/dubbo.git - HEAD - - - - Development List - dev-subscribe@dubbo.apache.org - dev-unsubscribe@dubbo.apache.org - dev@dubbo.apache.org - - - Commits List - commits-subscribe@dubbo.apache.org - commits-unsubscribe@dubbo.apache.org - commits@dubbo.apache.org - - - Issues List - issues-subscribe@dubbo.apache.org - issues-unsubscribe@dubbo.apache.org - issues@dubbo.apache.org - - - - - dubbo.io - The Dubbo Project Contributors - dev-subscribe@dubbo.apache.org - http://dubbo.apache.org/ - - + + Github Issues + https://github.com/apache/dubbo/issues + - - The Apache Software Foundation - http://www.apache.org/ - + + + 1.8 + 1.8 + UTF-8 + UTF-8 + 2020-04-01T08:04:00Z + -server -Xms256m -Xmx512m -XX:MetaspaceSize=64m -XX:MaxMetaspaceSize=128m -Dfile.encoding=UTF-8 + -Djava.net.preferIPv4Stack=true + + + oss + true + false + true + true + true + true - - Github Issues - https://github.com/apache/dubbo/issues - + + 3.3.0 + 3.0.0 + 3.0.0 + 2.8.2 + 3.11.0 + 3.2.1 + 3.5.0 + 9.4.53.v20231009 + 3.2.1 + 0.8.11 + 1.5.0 + 3.3.0 + 3.1.0 + 1.7.1 + 0.6.1 - - - 1.8 - 1.8 - UTF-8 - UTF-8 - 2020-04-01T08:04:00Z - -server -Xms256m -Xmx512m -XX:MetaspaceSize=64m -XX:MaxMetaspaceSize=128m -Dfile.encoding=UTF-8 - -Djava.net.preferIPv4Stack=true - - - - oss - true - false - true - true - true - true + 3.22.3 + 1.54.0 + 2.40.0 + check + 1.0.0 + 2.38.0 - - 3.3.0 - 3.0.0 - 3.0.0 - 2.8.2 - 3.11.0 - 3.2.1 - 3.5.0 - 9.4.53.v20231009 - 3.2.1 - 0.8.11 - 1.5.0 - 3.3.0 - 3.1.0 - 1.7.1 - 0.6.1 - - 3.22.3 - 1.54.0 - 2.40.0 - check - 1.0.0 - - 3.3.0-beta.2-SNAPSHOT - - - - dubbo-common - dubbo-container - dubbo-remoting - dubbo-rpc - dubbo-cluster - dubbo-registry - dubbo-monitor - dubbo-config - dubbo-demo - dubbo-plugin - dubbo-serialization - dubbo-compatible - dubbo-dependencies-bom - dubbo-distribution - dubbo-configcenter - dubbo-dependencies - dubbo-metadata - dubbo-metrics - dubbo-spring-boot - dubbo-test - dubbo-kubernetes - dubbo-xds - dubbo-maven-plugin - - - - - - org.apache.dubbo - dubbo-dependencies-bom - ${project.version} - pom - import - - - + 3.3.0-beta.2-SNAPSHOT + + - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.junit.jupiter - junit-jupiter-params - test - - - org.awaitility - awaitility - test - - - org.hamcrest - hamcrest - test - - - org.mockito - mockito-core - test - - - org.mockito - mockito-inline - test - + + org.apache.dubbo + dubbo-dependencies-bom + ${project.version} + pom + import + + - - - snapshot-ci-deploy - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${maven_enforce_version} - - - enforce-no-releases - - enforce - - - - - No Releases Allowed! - false - - - true - - - - - - - - - javadoc-lint - - [1.8,) - - - none - - - - - jacoco - - false - - + + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-params + test + + + org.awaitility + awaitility + test + + + org.hamcrest + hamcrest + test + + + org.mockito + mockito-core + test + + + org.mockito + mockito-inline + test + + - - - checkstyle - - false - false - - - - checkstyle_def - - [1.8,) - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - ${maven_checkstyle_version} - - - com.puppycrawl.tools - checkstyle - 8.45.1 - - - com.alibaba - dubbo-shared-resources - 1.0.0 - - - - - checkstyle-validation - validate - - codestyle/checkstyle.xml - codestyle/checkstyle-suppressions.xml - true - true - ${checkstyle.skip} - - **/JSONWriter.java, + + + + + false + src/main/resources + + + META-INF/ + false + ${maven.multiModuleProjectDirectory} + + NOTICE + LICENSE + + + + META-INF/versions + false + ${maven.multiModuleProjectDirectory} + + .artifacts + + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven_surefire_version} + + + + + + + + maven-failsafe-plugin + ${maven_failsafe_version} + + + maven-clean-plugin + 3.2.0 + + + org.ops4j.pax.exam + maven-paxexam-plugin + 1.2.4 + + + maven-dependency-plugin + 3.5.0 + + + + maven-jxr-plugin + 2.5 + + + org.codehaus.mojo + build-helper-maven-plugin + 3.4.0 + + + org.fusesource.hawtjni + maven-hawtjni-plugin + 1.15 + + + kr.motd.maven + exec-maven-plugin + 1.0.0.Final + + + org.apache.maven.plugins + maven-shade-plugin + 3.4.1 + + false + + + + org.eclipse.jetty + jetty-maven-plugin + ${maven_jetty_version} + + + org.apache.maven.plugins + maven-antrun-plugin + ${maven_antrun_version} + + + + + + maven-jar-plugin + ${maven_jar_version} + + + true + true + + true + true + + + ${project.version} + ${project.version} + + + + + + org.jacoco + jacoco-maven-plugin + ${maven_jacoco_version} + + + jacoco-initialize + + prepare-agent + + + jacocoArgLine + + + + report-aggregate + + report + report-aggregate + + verify + + + target/classes/**/* + target/classes/** + **/* + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + 1 + false + ${argline} ${jacocoArgLine} + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + ${maven_deploy_version} + + ${skip_maven_deploy} + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven_compiler_version} + + + -proc:none + -parameters + + true + + + + org.apache.maven.plugins + maven-antrun-plugin + + + get-version-infos + + run + + compile + + true + + + + + + + + + + + + + + + + + + org.apache.maven.plugins + maven-release-plugin + 3.0.0 + + true + false + release + deploy + ${arguments} + + + + org.codehaus.mojo + flatten-maven-plugin + ${maven_flatten_version} + + true + oss + + + + flatten + + flatten + + process-resources + + + flatten.clean + + clean + + clean + + + + + + + + + snapshot-ci-deploy + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${maven_enforce_version} + + + enforce-no-releases + + enforce + + + + + No Releases Allowed! + false + + + true + + + + + + + + + javadoc-lint + + [1.8,) + + + none + + + + + jacoco + + false + + + + + + checkstyle + + false + false + + + + checkstyle_def + + [1.8,) + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + ${maven_checkstyle_version} + + + com.puppycrawl.tools + checkstyle + 8.45.1 + + + com.alibaba + dubbo-shared-resources + 1.0.0 + + + + + checkstyle-validation + + check + + validate + + codestyle/checkstyle.xml + codestyle/checkstyle-suppressions.xml + true + true + ${checkstyle.skip} + **/JSONWriter.java, **/org/apache/dubbo/maven/plugin/aot/AbstractAotMojo.java, **/org/apache/dubbo/maven/plugin/aot/AbstractDependencyFilterMojo.java, **/org/apache/dubbo/maven/plugin/aot/CommandLineBuilder.java, @@ -339,591 +589,332 @@ **/grpc/health/**/*, **/grpc/reflection/**/*, **/target/**/*, - **/*.json - - - - check - - - - checkstyle-unix-validation - validate - - codestyle/checkstyle_unix.xml - true - true - ${checkstyle_unix.skip} - - **/target/**/* - - - **/generated/**/* - **/generated-sources/**/* - - - - check - - - - - - - - - sources - - - - maven-source-plugin - ${maven_source_version} - - - attach-sources - - jar - - - - - - - - - release - - 2.17.2 - false - - - - - org.apache.maven.plugins - maven-source-plugin - ${maven_source_version} - - - attach-sources - - jar - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - ${maven_javadoc_version} - - - attach-javadoc - - jar - aggregate - - - - - org.apache.logging.log4j - log4j-api - ${log4j2_version} - - - org.apache.logging.log4j - log4j-core - ${log4j2_version} - - - - - none - - - - - public - UTF-8 - UTF-8 - UTF-8 - ${java_source_version} - - https://docs.oracle.com/javase/8/docs/api - - none - - org.apache.dubbo.demo,org.apache.dubbo.demo.* - - Apache Dubbo ${project.version} API - Apache Dubbo ${project.version} API - - - - org.apache.maven.plugins - maven-gpg-plugin - - - verify - - sign - - - - - - - - - licenseCheck - - - - org.codehaus.mojo - license-maven-plugin - 2.3.0 - - - license-check - generate-sources - - add-third-party - - - false - false - false - - Apache License, Version 2.0|The Apache Software License, Version - 2.0|ASF 2.0|Apache 2|Apache-2.0|Apache 2.0 License|Apache 2.0|Apache License v2.0|Apache License 2.0|The Apache License, Version 2.0|The Apache Software License, Version 2.0 - - The MIT License|MIT License - The 3-Clause BSD License|New BSD License|3-Clause BSD - License|BSD|3-Clause BSD License|The New BSD License - - - - **/org/apache/dubbo/common/logger/helpers/FormattingTuple.java, - **/org/apache/dubbo/common/logger/helpers/MessageFormatter.java - - - - - - - - - - jdk15ge-add-open - - [15, - - - - - org.apache.maven.plugins - maven-surefire-plugin - - true - 1 - false - ${argline} ${jacocoArgLine} + **/*.json + + + + checkstyle-unix-validation + + check + + validate + + codestyle/checkstyle_unix.xml + true + true + ${checkstyle_unix.skip} + **/target/**/* + **/generated/**/* + **/generated-sources/**/* + + + + + + + + + sources + + + + maven-source-plugin + ${maven_source_version} + + + attach-sources + + jar + + + + + + + + + release + + 2.17.2 + false + + + + + org.apache.maven.plugins + maven-source-plugin + ${maven_source_version} + + + attach-sources + + jar + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven_javadoc_version} + + public + UTF-8 + UTF-8 + UTF-8 + ${java_source_version} + + https://docs.oracle.com/javase/8/docs/api + + none + org.apache.dubbo.demo,org.apache.dubbo.demo.* + Apache Dubbo ${project.version} API + Apache Dubbo ${project.version} API + + + + attach-javadoc + + jar + aggregate + + + + + org.apache.logging.log4j + log4j-api + ${log4j2_version} + + + org.apache.logging.log4j + log4j-core + ${log4j2_version} + + + + + none + + + + + + org.apache.maven.plugins + maven-gpg-plugin + + + + sign + + verify + + + + + + + + licenseCheck + + + + org.codehaus.mojo + license-maven-plugin + 2.3.0 + + + license-check + + add-third-party + + generate-sources + + false + false + false + + Apache License, Version 2.0|The Apache Software License, Version + 2.0|ASF 2.0|Apache 2|Apache-2.0|Apache 2.0 License|Apache 2.0|Apache License v2.0|Apache License 2.0|The Apache License, Version 2.0|The Apache Software License, Version 2.0 + The MIT License|MIT License + The 3-Clause BSD License|New BSD License|3-Clause BSD + License|BSD|3-Clause BSD License|The New BSD License + + **/org/apache/dubbo/common/logger/helpers/FormattingTuple.java, + **/org/apache/dubbo/common/logger/helpers/MessageFormatter.java + + + + + + + + + jdk15ge-add-open + + [15, + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + 1 + false + ${argline} ${jacocoArgLine} --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.math=ALL-UNNAMED - --add-opens java.base/java.util=ALL-UNNAMED - - - - - - - - - - - - - jdk15ge-simple - - - - org.apache.maven.plugins - maven-surefire-plugin - - true - 1 - false - ${argline} ${jacocoArgLine} - - - - - - - - - - - - - - jdk9-compile - - [1.9,) - - - - - maven-compiler-plugin - - 8 - - - - - - - - jacoco089 - - 0.8.9 - - - - - java11+ - - [11,) - - - - - - com.diffplug.spotless - spotless-maven-plugin - ${spotless-maven-plugin.version} - - - - src/main/java/org/apache/dubbo/common/threadlocal/InternalThreadLocal.java - src/main/java/org/apache/dubbo/common/threadlocal/InternalThreadLocalMap.java - src/main/java/org/apache/dubbo/common/timer/HashedWheelTimer.java - src/main/java/org/apache/dubbo/common/timer/Timeout.java - src/main/java/org/apache/dubbo/common/timer/Timer.java - src/main/java/org/apache/dubbo/common/timer/TimerTask.java - src/main/java/org/apache/dubbo/common/utils/CIDRUtils.java - src/main/java/org/apache/dubbo/common/utils/Utf8Utils.java - src/test/java/org/apache/dubbo/config/spring/EmbeddedZooKeeper.java - src/main/java/org/apache/dubbo/test/common/utils/TestSocketUtils.java - src/main/java/org/apache/dubbo/rpc/protocol/tri/TriHttp2RemoteFlowController.java - src/main/java/org/apache/dubbo/common/threadpool/serial/SerializingExecutor.java - src/main/java/org/apache/dubbo/maven/plugin/aot/AbstractAotMojo.java - src/main/java/org/apache/dubbo/maven/plugin/aot/AbstractDependencyFilterMojo.java - src/main/java/org/apache/dubbo/maven/plugin/aot/CommandLineBuilder.java - src/main/java/org/apache/dubbo/maven/plugin/aot/DependencyFilter.java - src/main/java/org/apache/dubbo/maven/plugin/aot/Exclude.java - src/main/java/org/apache/dubbo/maven/plugin/aot/ExcludeFilter.java - src/main/java/org/apache/dubbo/maven/plugin/aot/FilterableDependency.java - src/main/java/org/apache/dubbo/maven/plugin/aot/Include.java - src/main/java/org/apache/dubbo/maven/plugin/aot/IncludeFilter.java - src/main/java/org/apache/dubbo/maven/plugin/aot/JavaCompilerPluginConfiguration.java - src/main/java/org/apache/dubbo/maven/plugin/aot/JavaExecutable.java - src/main/java/org/apache/dubbo/maven/plugin/aot/JavaProcessExecutor.java - src/main/java/org/apache/dubbo/maven/plugin/aot/MatchingGroupIdFilter.java - src/main/java/org/apache/dubbo/maven/plugin/aot/RunArguments.java - src/main/java/org/apache/dubbo/maven/plugin/aot/RunProcess.java - src/main/java/org/apache/dubbo/aot/generate/BasicJsonWriter.java - src/main/java/org/apache/dubbo/aot/generate/ExecutableMode.java - src/main/java/org/apache/dubbo/aot/generate/MemberCategory.java - src/main/java/org/apache/dubbo/metrics/aggregate/DubboMergingDigest.java - src/main/java/org/apache/dubbo/metrics/aggregate/DubboAbstractTDigest.java - - - - - dubbo-importorder.txt - - - checkstyle-header.txt - - - - - false - true - - - - true - - - - - com.alibaba - dubbo-shared-resources - ${dubbo-shared-resources.version} - - - - - - ${spotless.action} - - process-sources - - - - - - - - - - - - - src/main/resources - false - - - ${maven.multiModuleProjectDirectory} - META-INF/ - false - - NOTICE - LICENSE - - - - ${maven.multiModuleProjectDirectory} - META-INF/versions - false - - .artifacts - - - - - - maven-jar-plugin - ${maven_jar_version} - - - true - true - - true - true - - - ${project.version} - ${project.version} - - - - - - org.jacoco - jacoco-maven-plugin - ${maven_jacoco_version} - - - jacoco-initialize - - prepare-agent - - - jacocoArgLine - - - - report-aggregate - verify - - report - report-aggregate - - - - target/classes/**/* - target/classes/** - **/* - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - true - 1 - false - ${argline} ${jacocoArgLine} - - - - - - - org.apache.maven.plugins - maven-deploy-plugin - ${maven_deploy_version} - - ${skip_maven_deploy} - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven_compiler_version} - - - -proc:none - -parameters - - true - - - - org.apache.maven.plugins - maven-antrun-plugin - - - get-version-infos - compile - - true - - - - - - - - - - - - - - - run - - - - - - org.apache.maven.plugins - maven-release-plugin - 3.0.0 - - true - false - release - deploy - ${arguments} - - - - org.codehaus.mojo - flatten-maven-plugin - ${maven_flatten_version} - - true - oss - - - - flatten - process-resources - - flatten - - - - flatten.clean - clean - - clean - - - - + --add-opens java.base/java.util=ALL-UNNAMED + + + + + + + + + + + jdk15ge-simple + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + 1 + false + ${argline} ${jacocoArgLine} + + + + + + + + + + - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven_surefire_version} - - - - - - - - maven-failsafe-plugin - ${maven_failsafe_version} - - - maven-clean-plugin - 3.2.0 - - - org.ops4j.pax.exam - maven-paxexam-plugin - 1.2.4 - - - maven-dependency-plugin - 3.5.0 - - - - maven-jxr-plugin - 2.5 - - - org.codehaus.mojo - build-helper-maven-plugin - 3.4.0 - - - org.fusesource.hawtjni - maven-hawtjni-plugin - 1.15 - - - kr.motd.maven - exec-maven-plugin - 1.0.0.Final - - - org.apache.maven.plugins - maven-shade-plugin - 3.4.1 - - false - - - - org.eclipse.jetty - jetty-maven-plugin - ${maven_jetty_version} - - - org.apache.maven.plugins - maven-antrun-plugin - ${maven_antrun_version} - - - - + + jdk9-compile + + [1.9,) + + + + + maven-compiler-plugin + + 8 + + + + + + + + jacoco089 + + 0.8.9 + + + + + java11+ + + [11,) + + + + + + com.diffplug.spotless + spotless-maven-plugin + ${spotless-maven-plugin.version} + + + + src/main/java/org/apache/dubbo/common/threadlocal/InternalThreadLocal.java + src/main/java/org/apache/dubbo/common/threadlocal/InternalThreadLocalMap.java + src/main/java/org/apache/dubbo/common/timer/HashedWheelTimer.java + src/main/java/org/apache/dubbo/common/timer/Timeout.java + src/main/java/org/apache/dubbo/common/timer/Timer.java + src/main/java/org/apache/dubbo/common/timer/TimerTask.java + src/main/java/org/apache/dubbo/common/utils/CIDRUtils.java + src/main/java/org/apache/dubbo/common/utils/Utf8Utils.java + src/test/java/org/apache/dubbo/config/spring/EmbeddedZooKeeper.java + src/main/java/org/apache/dubbo/test/common/utils/TestSocketUtils.java + src/main/java/org/apache/dubbo/rpc/protocol/tri/TriHttp2RemoteFlowController.java + src/main/java/org/apache/dubbo/common/threadpool/serial/SerializingExecutor.java + src/main/java/org/apache/dubbo/maven/plugin/aot/AbstractAotMojo.java + src/main/java/org/apache/dubbo/maven/plugin/aot/AbstractDependencyFilterMojo.java + src/main/java/org/apache/dubbo/maven/plugin/aot/CommandLineBuilder.java + src/main/java/org/apache/dubbo/maven/plugin/aot/DependencyFilter.java + src/main/java/org/apache/dubbo/maven/plugin/aot/Exclude.java + src/main/java/org/apache/dubbo/maven/plugin/aot/ExcludeFilter.java + src/main/java/org/apache/dubbo/maven/plugin/aot/FilterableDependency.java + src/main/java/org/apache/dubbo/maven/plugin/aot/Include.java + src/main/java/org/apache/dubbo/maven/plugin/aot/IncludeFilter.java + src/main/java/org/apache/dubbo/maven/plugin/aot/JavaCompilerPluginConfiguration.java + src/main/java/org/apache/dubbo/maven/plugin/aot/JavaExecutable.java + src/main/java/org/apache/dubbo/maven/plugin/aot/JavaProcessExecutor.java + src/main/java/org/apache/dubbo/maven/plugin/aot/MatchingGroupIdFilter.java + src/main/java/org/apache/dubbo/maven/plugin/aot/RunArguments.java + src/main/java/org/apache/dubbo/maven/plugin/aot/RunProcess.java + src/main/java/org/apache/dubbo/aot/generate/BasicJsonWriter.java + src/main/java/org/apache/dubbo/aot/generate/ExecutableMode.java + src/main/java/org/apache/dubbo/aot/generate/MemberCategory.java + src/main/java/org/apache/dubbo/metrics/aggregate/DubboMergingDigest.java + src/main/java/org/apache/dubbo/metrics/aggregate/DubboAbstractTDigest.java + src/main/java/org/apache/dubbo/common/logger/helpers/FormattingTuple.java + src/main/java/org/apache/dubbo/common/logger/helpers/MessageFormatter.java + src/main/java/org/apache/dubbo/maven/plugin/protoc/DubboProtocCompilerMojo.java + src/main/java/org/apache/dubbo/gen/utils/ProtoTypeMap.java + + + ${palantirJavaFormat.version} + + + + dubbo-importorder.txt + + + checkstyle-header.txt + + + + + false + true + + + + true + + + + + com.alibaba + dubbo-shared-resources + ${dubbo-shared-resources.version} + + + + + + ${spotless.action} + + process-sources + + + + + + +